LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 17080b14f46954d6812ea0a7dad4b2247e0840a8.info Lines: 77.7 % 8402 6527
Test Date: 2025-07-08 18:30:10 Functions: 63.1 % 480 303

            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, TimelineArchivalState, TimelineState, TopTenantShardItem,
      38              :     WalRedoManagerStatus,
      39              : };
      40              : use pageserver_api::shard::{ShardIdentity, ShardStripeSize, TenantShardId};
      41              : use postgres_ffi::PgMajorVersion;
      42              : use remote_storage::{DownloadError, GenericRemoteStorage, TimeoutOrCancel};
      43              : use remote_timeline_client::index::GcCompactionState;
      44              : use remote_timeline_client::manifest::{
      45              :     LATEST_TENANT_MANIFEST_VERSION, OffloadedTimelineManifest, TenantManifest,
      46              : };
      47              : use remote_timeline_client::{
      48              :     FAILED_REMOTE_OP_RETRIES, FAILED_UPLOAD_WARN_THRESHOLD, UploadQueueNotReadyError,
      49              :     download_tenant_manifest,
      50              : };
      51              : use secondary::heatmap::{HeatMapTenant, HeatMapTimeline};
      52              : use storage_broker::BrokerClientChannel;
      53              : use timeline::compaction::{CompactionOutcome, GcCompactionQueue};
      54              : use timeline::import_pgdata::ImportingTimeline;
      55              : use timeline::layer_manager::LayerManagerLockHolder;
      56              : use timeline::offload::{OffloadError, offload_timeline};
      57              : use timeline::{
      58              :     CompactFlags, CompactOptions, CompactionError, PreviousHeatmap, ShutdownMode, import_pgdata,
      59              : };
      60              : use tokio::io::BufReader;
      61              : use tokio::sync::{Notify, Semaphore, watch};
      62              : use tokio::task::JoinSet;
      63              : use tokio_util::sync::CancellationToken;
      64              : use tracing::*;
      65              : use upload_queue::NotInitialized;
      66              : use utils::circuit_breaker::CircuitBreaker;
      67              : use utils::crashsafe::path_with_suffix_extension;
      68              : use utils::sync::gate::{Gate, GateGuard};
      69              : use utils::timeout::{TimeoutCancellableError, timeout_cancellable};
      70              : use utils::try_rcu::ArcSwapExt;
      71              : use utils::zstd::{create_zst_tarball, extract_zst_tarball};
      72              : use utils::{backoff, completion, failpoint_support, fs_ext, pausable_failpoint};
      73              : 
      74              : use self::config::{AttachedLocationConfig, AttachmentMode, LocationConf};
      75              : use self::metadata::TimelineMetadata;
      76              : use self::mgr::{GetActiveTenantError, GetTenantError};
      77              : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
      78              : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
      79              : use self::timeline::uninit::{TimelineCreateGuard, TimelineExclusionError, UninitializedTimeline};
      80              : use self::timeline::{
      81              :     EvictionTaskTenantState, GcCutoffs, TimelineDeleteProgress, TimelineResources, WaitLsnError,
      82              : };
      83              : use crate::basebackup_cache::BasebackupCache;
      84              : use crate::config::PageServerConf;
      85              : use crate::context;
      86              : use crate::context::RequestContextBuilder;
      87              : use crate::context::{DownloadBehavior, RequestContext};
      88              : use crate::deletion_queue::{DeletionQueueClient, DeletionQueueError};
      89              : use crate::feature_resolver::{FeatureResolver, TenantFeatureResolver};
      90              : use crate::l0_flush::L0FlushGlobalState;
      91              : use crate::metrics::{
      92              :     BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN, CONCURRENT_INITDBS,
      93              :     INITDB_RUN_TIME, INITDB_SEMAPHORE_ACQUISITION_TIME, TENANT, TENANT_OFFLOADED_TIMELINES,
      94              :     TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC, TIMELINE_STATE_METRIC,
      95              :     remove_tenant_metrics,
      96              : };
      97              : use crate::task_mgr::TaskKind;
      98              : use crate::tenant::config::LocationMode;
      99              : use crate::tenant::gc_result::GcResult;
     100              : pub use crate::tenant::remote_timeline_client::index::IndexPart;
     101              : use crate::tenant::remote_timeline_client::{
     102              :     INITDB_PATH, MaybeDeletedIndexPart, remote_initdb_archive_path,
     103              : };
     104              : use crate::tenant::storage_layer::{DeltaLayer, ImageLayer};
     105              : use crate::tenant::timeline::delete::DeleteTimelineFlow;
     106              : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
     107              : use crate::virtual_file::VirtualFile;
     108              : use crate::walingest::WalLagCooldown;
     109              : use crate::walredo::{PostgresRedoManager, RedoAttemptType};
     110              : use crate::{InitializationOrder, TEMP_FILE_SUFFIX, import_datadir, span, task_mgr, walredo};
     111              : 
     112            0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
     113              : use utils::crashsafe;
     114              : use utils::generation::Generation;
     115              : use utils::id::TimelineId;
     116              : use utils::lsn::{Lsn, RecordLsn};
     117              : 
     118              : pub mod blob_io;
     119              : pub mod block_io;
     120              : pub mod vectored_blob_io;
     121              : 
     122              : pub mod disk_btree;
     123              : pub(crate) mod ephemeral_file;
     124              : pub mod layer_map;
     125              : 
     126              : pub mod metadata;
     127              : pub mod remote_timeline_client;
     128              : pub mod storage_layer;
     129              : 
     130              : pub mod checks;
     131              : pub mod config;
     132              : pub mod mgr;
     133              : pub mod secondary;
     134              : pub mod tasks;
     135              : pub mod upload_queue;
     136              : 
     137              : pub(crate) mod timeline;
     138              : 
     139              : pub mod size;
     140              : 
     141              : mod gc_block;
     142              : mod gc_result;
     143              : pub(crate) mod throttle;
     144              : 
     145              : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
     146              : 
     147              : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
     148              : // re-export for use in walreceiver
     149              : pub use crate::tenant::timeline::WalReceiverInfo;
     150              : 
     151              : /// The "tenants" part of `tenants/<tenant>/timelines...`
     152              : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
     153              : 
     154              : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
     155              : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
     156              : 
     157              : /// References to shared objects that are passed into each tenant, such
     158              : /// as the shared remote storage client and process initialization state.
     159              : #[derive(Clone)]
     160              : pub struct TenantSharedResources {
     161              :     pub broker_client: storage_broker::BrokerClientChannel,
     162              :     pub remote_storage: GenericRemoteStorage,
     163              :     pub deletion_queue_client: DeletionQueueClient,
     164              :     pub l0_flush_global_state: L0FlushGlobalState,
     165              :     pub basebackup_cache: Arc<BasebackupCache>,
     166              :     pub feature_resolver: FeatureResolver,
     167              : }
     168              : 
     169              : /// A [`TenantShard`] is really an _attached_ tenant.  The configuration
     170              : /// for an attached tenant is a subset of the [`LocationConf`], represented
     171              : /// in this struct.
     172              : #[derive(Clone)]
     173              : pub(super) struct AttachedTenantConf {
     174              :     tenant_conf: pageserver_api::models::TenantConfig,
     175              :     location: AttachedLocationConfig,
     176              :     /// The deadline before which we are blocked from GC so that
     177              :     /// leases have a chance to be renewed.
     178              :     lsn_lease_deadline: Option<tokio::time::Instant>,
     179              : }
     180              : 
     181              : impl AttachedTenantConf {
     182          118 :     fn new(
     183          118 :         conf: &'static PageServerConf,
     184          118 :         tenant_conf: pageserver_api::models::TenantConfig,
     185          118 :         location: AttachedLocationConfig,
     186          118 :     ) -> Self {
     187              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     188              :         //
     189              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     190              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     191              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     192          118 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     193          118 :             Some(
     194          118 :                 tokio::time::Instant::now()
     195          118 :                     + TenantShard::get_lsn_lease_length_impl(conf, &tenant_conf),
     196          118 :             )
     197              :         } else {
     198              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     199              :             // because we don't do GC in these modes.
     200            0 :             None
     201              :         };
     202              : 
     203          118 :         Self {
     204          118 :             tenant_conf,
     205          118 :             location,
     206          118 :             lsn_lease_deadline,
     207          118 :         }
     208          118 :     }
     209              : 
     210          118 :     fn try_from(
     211          118 :         conf: &'static PageServerConf,
     212          118 :         location_conf: LocationConf,
     213          118 :     ) -> anyhow::Result<Self> {
     214          118 :         match &location_conf.mode {
     215          118 :             LocationMode::Attached(attach_conf) => {
     216          118 :                 Ok(Self::new(conf, location_conf.tenant_conf, *attach_conf))
     217              :             }
     218              :             LocationMode::Secondary(_) => {
     219            0 :                 anyhow::bail!(
     220            0 :                     "Attempted to construct AttachedTenantConf from a LocationConf in secondary mode"
     221              :                 )
     222              :             }
     223              :         }
     224          118 :     }
     225              : 
     226          381 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     227          381 :         self.lsn_lease_deadline
     228          381 :             .map(|d| tokio::time::Instant::now() < d)
     229          381 :             .unwrap_or(false)
     230          381 :     }
     231              : }
     232              : struct TimelinePreload {
     233              :     timeline_id: TimelineId,
     234              :     client: RemoteTimelineClient,
     235              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     236              :     previous_heatmap: Option<PreviousHeatmap>,
     237              : }
     238              : 
     239              : pub(crate) struct TenantPreload {
     240              :     /// The tenant manifest from remote storage, or None if no manifest was found.
     241              :     tenant_manifest: Option<TenantManifest>,
     242              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     243              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     244              : }
     245              : 
     246              : /// When we spawn a tenant, there is a special mode for tenant creation that
     247              : /// avoids trying to read anything from remote storage.
     248              : pub(crate) enum SpawnMode {
     249              :     /// Activate as soon as possible
     250              :     Eager,
     251              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     252              :     Lazy,
     253              : }
     254              : 
     255              : ///
     256              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     257              : ///
     258              : pub struct TenantShard {
     259              :     // Global pageserver config parameters
     260              :     pub conf: &'static PageServerConf,
     261              : 
     262              :     /// The value creation timestamp, used to measure activation delay, see:
     263              :     /// <https://github.com/neondatabase/neon/issues/4025>
     264              :     constructed_at: Instant,
     265              : 
     266              :     state: watch::Sender<TenantState>,
     267              : 
     268              :     // Overridden tenant-specific config parameters.
     269              :     // We keep pageserver_api::models::TenantConfig sturct here to preserve the information
     270              :     // about parameters that are not set.
     271              :     // This is necessary to allow global config updates.
     272              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     273              : 
     274              :     tenant_shard_id: TenantShardId,
     275              : 
     276              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     277              :     shard_identity: ShardIdentity,
     278              : 
     279              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     280              :     /// Does not change over the lifetime of the [`TenantShard`] object.
     281              :     ///
     282              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     283              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     284              :     generation: Generation,
     285              : 
     286              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     287              : 
     288              :     /// During timeline creation, we first insert the TimelineId to the
     289              :     /// creating map, then `timelines`, then remove it from the creating map.
     290              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     291              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     292              : 
     293              :     /// Possibly offloaded and archived timelines
     294              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     295              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     296              : 
     297              :     /// Tracks the timelines that are currently importing into this tenant shard.
     298              :     ///
     299              :     /// Note that importing timelines are also present in [`Self::timelines_creating`].
     300              :     /// Keep this in mind when ordering lock acquisition.
     301              :     ///
     302              :     /// Lifetime:
     303              :     /// * An imported timeline is created while scanning the bucket on tenant attach
     304              :     ///   if the index part contains an `import_pgdata` entry and said field marks the import
     305              :     ///   as in progress.
     306              :     /// * Imported timelines are removed when the storage controller calls the post timeline
     307              :     ///   import activation endpoint.
     308              :     timelines_importing: std::sync::Mutex<HashMap<TimelineId, Arc<ImportingTimeline>>>,
     309              : 
     310              :     /// The last tenant manifest known to be in remote storage. None if the manifest has not yet
     311              :     /// been either downloaded or uploaded. Always Some after tenant attach.
     312              :     ///
     313              :     /// Initially populated during tenant attach, updated via `maybe_upload_tenant_manifest`.
     314              :     ///
     315              :     /// Do not modify this directly. It is used to check whether a new manifest needs to be
     316              :     /// uploaded. The manifest is constructed in `build_tenant_manifest`, and uploaded via
     317              :     /// `maybe_upload_tenant_manifest`.
     318              :     remote_tenant_manifest: tokio::sync::Mutex<Option<TenantManifest>>,
     319              : 
     320              :     // This mutex prevents creation of new timelines during GC.
     321              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     322              :     // `timelines` mutex during all GC iteration
     323              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     324              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     325              :     // timeout...
     326              :     gc_cs: tokio::sync::Mutex<()>,
     327              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     328              : 
     329              :     /// Provides access to timeline data sitting in the remote storage.
     330              :     pub(crate) remote_storage: GenericRemoteStorage,
     331              : 
     332              :     /// Access to global deletion queue for when this tenant wants to schedule a deletion.
     333              :     deletion_queue_client: DeletionQueueClient,
     334              : 
     335              :     /// A channel to send async requests to prepare a basebackup for the basebackup cache.
     336              :     basebackup_cache: Arc<BasebackupCache>,
     337              : 
     338              :     /// Cached logical sizes updated updated on each [`TenantShard::gather_size_inputs`].
     339              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     340              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     341              : 
     342              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     343              : 
     344              :     /// Track repeated failures to compact, so that we can back off.
     345              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     346              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     347              : 
     348              :     /// Signals the tenant compaction loop that there is L0 compaction work to be done.
     349              :     pub(crate) l0_compaction_trigger: Arc<Notify>,
     350              : 
     351              :     /// Scheduled gc-compaction tasks.
     352              :     scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
     353              : 
     354              :     /// If the tenant is in Activating state, notify this to encourage it
     355              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     356              :     /// background warmup.
     357              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     358              : 
     359              :     /// Time it took for the tenant to activate. Zero if not active yet.
     360              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     361              : 
     362              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     363              :     // Timelines' cancellation token.
     364              :     pub(crate) cancel: CancellationToken,
     365              : 
     366              :     // Users of the TenantShard such as the page service must take this Gate to avoid
     367              :     // trying to use a TenantShard which is shutting down.
     368              :     pub(crate) gate: Gate,
     369              : 
     370              :     /// Throttle applied at the top of [`Timeline::get`].
     371              :     /// All [`TenantShard::timelines`] of a given [`TenantShard`] instance share the same [`throttle::Throttle`] instance.
     372              :     pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
     373              : 
     374              :     pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
     375              : 
     376              :     /// An ongoing timeline detach concurrency limiter.
     377              :     ///
     378              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     379              :     /// to have two running at the same time. A different one can be started if an earlier one
     380              :     /// has failed for whatever reason.
     381              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     382              : 
     383              :     /// `index_part.json` based gc blocking reason tracking.
     384              :     ///
     385              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     386              :     /// proceeding.
     387              :     pub(crate) gc_block: gc_block::GcBlock,
     388              : 
     389              :     l0_flush_global_state: L0FlushGlobalState,
     390              : 
     391              :     pub(crate) feature_resolver: Arc<TenantFeatureResolver>,
     392              : }
     393              : impl std::fmt::Debug for TenantShard {
     394            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     395            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     396            0 :     }
     397              : }
     398              : 
     399              : pub(crate) enum WalRedoManager {
     400              :     Prod(WalredoManagerId, PostgresRedoManager),
     401              :     #[cfg(test)]
     402              :     Test(harness::TestRedoManager),
     403              : }
     404              : 
     405              : #[derive(thiserror::Error, Debug)]
     406              : #[error("pageserver is shutting down")]
     407              : pub(crate) struct GlobalShutDown;
     408              : 
     409              : impl WalRedoManager {
     410            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     411            0 :         let id = WalredoManagerId::next();
     412            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     413            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     414            0 :         match &mut *guard {
     415            0 :             Some(map) => {
     416            0 :                 map.insert(id, Arc::downgrade(&arc));
     417            0 :                 Ok(arc)
     418              :             }
     419            0 :             None => Err(GlobalShutDown),
     420              :         }
     421            0 :     }
     422              : }
     423              : 
     424              : impl Drop for WalRedoManager {
     425            5 :     fn drop(&mut self) {
     426            5 :         match self {
     427            0 :             Self::Prod(id, _) => {
     428            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     429            0 :                 if let Some(map) = &mut *guard {
     430            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     431            0 :                 }
     432              :             }
     433              :             #[cfg(test)]
     434            5 :             Self::Test(_) => {
     435            5 :                 // Not applicable to test redo manager
     436            5 :             }
     437              :         }
     438            5 :     }
     439              : }
     440              : 
     441              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     442              : /// the walredo processes outside of the regular order.
     443              : ///
     444              : /// This is necessary to work around a systemd bug where it freezes if there are
     445              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     446              : #[allow(clippy::type_complexity)]
     447              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     448              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     449            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     450              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     451              : pub(crate) struct WalredoManagerId(u64);
     452              : impl WalredoManagerId {
     453            0 :     pub fn next() -> Self {
     454              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     455            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     456            0 :         if id == 0 {
     457            0 :             panic!(
     458            0 :                 "WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique"
     459              :             );
     460            0 :         }
     461            0 :         Self(id)
     462            0 :     }
     463              : }
     464              : 
     465              : #[cfg(test)]
     466              : impl From<harness::TestRedoManager> for WalRedoManager {
     467          118 :     fn from(mgr: harness::TestRedoManager) -> Self {
     468          118 :         Self::Test(mgr)
     469          118 :     }
     470              : }
     471              : 
     472              : impl WalRedoManager {
     473            3 :     pub(crate) async fn shutdown(&self) -> bool {
     474            3 :         match self {
     475            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     476              :             #[cfg(test)]
     477              :             Self::Test(_) => {
     478              :                 // Not applicable to test redo manager
     479            3 :                 true
     480              :             }
     481              :         }
     482            3 :     }
     483              : 
     484            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     485            0 :         match self {
     486            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     487              :             #[cfg(test)]
     488            0 :             Self::Test(_) => {
     489            0 :                 // Not applicable to test redo manager
     490            0 :             }
     491              :         }
     492            0 :     }
     493              : 
     494              :     /// # Cancel-Safety
     495              :     ///
     496              :     /// This method is cancellation-safe.
     497        26774 :     pub async fn request_redo(
     498        26774 :         &self,
     499        26774 :         key: pageserver_api::key::Key,
     500        26774 :         lsn: Lsn,
     501        26774 :         base_img: Option<(Lsn, bytes::Bytes)>,
     502        26774 :         records: Vec<(Lsn, wal_decoder::models::record::NeonWalRecord)>,
     503        26774 :         pg_version: PgMajorVersion,
     504        26774 :         redo_attempt_type: RedoAttemptType,
     505        26774 :     ) -> Result<bytes::Bytes, walredo::Error> {
     506        26774 :         match self {
     507            0 :             Self::Prod(_, mgr) => {
     508            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     509            0 :                     .await
     510              :             }
     511              :             #[cfg(test)]
     512        26774 :             Self::Test(mgr) => {
     513        26774 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     514        26774 :                     .await
     515              :             }
     516              :         }
     517        26774 :     }
     518              : 
     519            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     520            0 :         match self {
     521            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     522              :             #[cfg(test)]
     523            0 :             WalRedoManager::Test(_) => None,
     524              :         }
     525            0 :     }
     526              : }
     527              : 
     528              : /// A very lightweight memory representation of an offloaded timeline.
     529              : ///
     530              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     531              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     532              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     533              : /// more offloaded timelines than we can manage ones that aren't.
     534              : pub struct OffloadedTimeline {
     535              :     pub tenant_shard_id: TenantShardId,
     536              :     pub timeline_id: TimelineId,
     537              :     pub ancestor_timeline_id: Option<TimelineId>,
     538              :     /// Whether to retain the branch lsn at the ancestor or not
     539              :     pub ancestor_retain_lsn: Option<Lsn>,
     540              : 
     541              :     /// When the timeline was archived.
     542              :     ///
     543              :     /// Present for future flattening deliberations.
     544              :     pub archived_at: NaiveDateTime,
     545              : 
     546              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     547              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     548              :     pub delete_progress: TimelineDeleteProgress,
     549              : 
     550              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     551              :     pub deleted_from_ancestor: AtomicBool,
     552              : 
     553              :     _metrics_guard: OffloadedTimelineMetricsGuard,
     554              : }
     555              : 
     556              : /// Increases the offloaded timeline count metric when created, and decreases when dropped.
     557              : struct OffloadedTimelineMetricsGuard;
     558              : 
     559              : impl OffloadedTimelineMetricsGuard {
     560            1 :     fn new() -> Self {
     561            1 :         TIMELINE_STATE_METRIC
     562            1 :             .with_label_values(&["offloaded"])
     563            1 :             .inc();
     564            1 :         Self
     565            1 :     }
     566              : }
     567              : 
     568              : impl Drop for OffloadedTimelineMetricsGuard {
     569            1 :     fn drop(&mut self) {
     570            1 :         TIMELINE_STATE_METRIC
     571            1 :             .with_label_values(&["offloaded"])
     572            1 :             .dec();
     573            1 :     }
     574              : }
     575              : 
     576              : impl OffloadedTimeline {
     577              :     /// Obtains an offloaded timeline from a given timeline object.
     578              :     ///
     579              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     580              :     /// the timeline is not in a stopped state.
     581              :     /// Panics if the timeline is not archived.
     582            1 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     583            1 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     584            1 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     585            1 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     586            1 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     587            1 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     588            1 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     589            1 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     590              :             } else {
     591            0 :                 (None, None)
     592              :             };
     593            1 :         let archived_at = timeline
     594            1 :             .remote_client
     595            1 :             .archived_at_stopped_queue()?
     596            1 :             .expect("must be called on an archived timeline");
     597            1 :         Ok(Self {
     598            1 :             tenant_shard_id: timeline.tenant_shard_id,
     599            1 :             timeline_id: timeline.timeline_id,
     600            1 :             ancestor_timeline_id,
     601            1 :             ancestor_retain_lsn,
     602            1 :             archived_at,
     603            1 : 
     604            1 :             delete_progress: timeline.delete_progress.clone(),
     605            1 :             deleted_from_ancestor: AtomicBool::new(false),
     606            1 : 
     607            1 :             _metrics_guard: OffloadedTimelineMetricsGuard::new(),
     608            1 :         })
     609            1 :     }
     610            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     611              :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     612              :         // by the `initialize_gc_info` function.
     613              :         let OffloadedTimelineManifest {
     614            0 :             timeline_id,
     615            0 :             ancestor_timeline_id,
     616            0 :             ancestor_retain_lsn,
     617            0 :             archived_at,
     618            0 :         } = *manifest;
     619            0 :         Self {
     620            0 :             tenant_shard_id,
     621            0 :             timeline_id,
     622            0 :             ancestor_timeline_id,
     623            0 :             ancestor_retain_lsn,
     624            0 :             archived_at,
     625            0 :             delete_progress: TimelineDeleteProgress::default(),
     626            0 :             deleted_from_ancestor: AtomicBool::new(false),
     627            0 :             _metrics_guard: OffloadedTimelineMetricsGuard::new(),
     628            0 :         }
     629            0 :     }
     630            1 :     fn manifest(&self) -> OffloadedTimelineManifest {
     631              :         let Self {
     632            1 :             timeline_id,
     633            1 :             ancestor_timeline_id,
     634            1 :             ancestor_retain_lsn,
     635            1 :             archived_at,
     636              :             ..
     637            1 :         } = self;
     638            1 :         OffloadedTimelineManifest {
     639            1 :             timeline_id: *timeline_id,
     640            1 :             ancestor_timeline_id: *ancestor_timeline_id,
     641            1 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     642            1 :             archived_at: *archived_at,
     643            1 :         }
     644            1 :     }
     645              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     646            0 :     fn delete_from_ancestor_with_timelines(
     647            0 :         &self,
     648            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     649            0 :     ) {
     650            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     651            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     652              :         {
     653            0 :             if let Some((_, ancestor_timeline)) = timelines
     654            0 :                 .iter()
     655            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     656              :             {
     657            0 :                 let removal_happened = ancestor_timeline
     658            0 :                     .gc_info
     659            0 :                     .write()
     660            0 :                     .unwrap()
     661            0 :                     .remove_child_offloaded(self.timeline_id);
     662            0 :                 if !removal_happened {
     663            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     664            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     665            0 :                 }
     666            0 :             }
     667            0 :         }
     668            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     669            0 :     }
     670              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     671              :     ///
     672              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     673            1 :     fn defuse_for_tenant_drop(&self) {
     674            1 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     675            1 :     }
     676              : }
     677              : 
     678              : impl fmt::Debug for OffloadedTimeline {
     679            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     680            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     681            0 :     }
     682              : }
     683              : 
     684              : impl Drop for OffloadedTimeline {
     685            1 :     fn drop(&mut self) {
     686            1 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     687            0 :             tracing::warn!(
     688            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     689              :                 self.timeline_id
     690              :             );
     691            1 :         }
     692            1 :     }
     693              : }
     694              : 
     695              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     696              : pub enum MaybeOffloaded {
     697              :     Yes,
     698              :     No,
     699              : }
     700              : 
     701              : #[derive(Clone, Debug)]
     702              : pub enum TimelineOrOffloaded {
     703              :     Timeline(Arc<Timeline>),
     704              :     Offloaded(Arc<OffloadedTimeline>),
     705              :     Importing(Arc<ImportingTimeline>),
     706              : }
     707              : 
     708              : impl TimelineOrOffloaded {
     709            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     710            0 :         match self {
     711            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     712            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     713              :             }
     714            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     715            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     716              :             }
     717            0 :             TimelineOrOffloaded::Importing(importing) => {
     718            0 :                 TimelineOrOffloadedArcRef::Importing(importing)
     719              :             }
     720              :         }
     721            0 :     }
     722            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     723            0 :         self.arc_ref().tenant_shard_id()
     724            0 :     }
     725            0 :     pub fn timeline_id(&self) -> TimelineId {
     726            0 :         self.arc_ref().timeline_id()
     727            0 :     }
     728            1 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     729            1 :         match self {
     730            1 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     731            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     732            0 :             TimelineOrOffloaded::Importing(importing) => &importing.delete_progress,
     733              :         }
     734            1 :     }
     735            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     736            0 :         match self {
     737            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     738            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     739            0 :             TimelineOrOffloaded::Importing(importing) => {
     740            0 :                 Some(importing.timeline.remote_client.clone())
     741              :             }
     742              :         }
     743            0 :     }
     744              : }
     745              : 
     746              : pub enum TimelineOrOffloadedArcRef<'a> {
     747              :     Timeline(&'a Arc<Timeline>),
     748              :     Offloaded(&'a Arc<OffloadedTimeline>),
     749              :     Importing(&'a Arc<ImportingTimeline>),
     750              : }
     751              : 
     752              : impl TimelineOrOffloadedArcRef<'_> {
     753            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     754            0 :         match self {
     755            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     756            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     757            0 :             TimelineOrOffloadedArcRef::Importing(importing) => importing.timeline.tenant_shard_id,
     758              :         }
     759            0 :     }
     760            0 :     pub fn timeline_id(&self) -> TimelineId {
     761            0 :         match self {
     762            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     763            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     764            0 :             TimelineOrOffloadedArcRef::Importing(importing) => importing.timeline.timeline_id,
     765              :         }
     766            0 :     }
     767              : }
     768              : 
     769              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     770            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     771            0 :         Self::Timeline(timeline)
     772            0 :     }
     773              : }
     774              : 
     775              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     776            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     777            0 :         Self::Offloaded(timeline)
     778            0 :     }
     779              : }
     780              : 
     781              : impl<'a> From<&'a Arc<ImportingTimeline>> for TimelineOrOffloadedArcRef<'a> {
     782            0 :     fn from(timeline: &'a Arc<ImportingTimeline>) -> Self {
     783            0 :         Self::Importing(timeline)
     784            0 :     }
     785              : }
     786              : 
     787              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     788              : pub enum GetTimelineError {
     789              :     #[error("Timeline is shutting down")]
     790              :     ShuttingDown,
     791              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     792              :     NotActive {
     793              :         tenant_id: TenantShardId,
     794              :         timeline_id: TimelineId,
     795              :         state: TimelineState,
     796              :     },
     797              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     798              :     NotFound {
     799              :         tenant_id: TenantShardId,
     800              :         timeline_id: TimelineId,
     801              :     },
     802              : }
     803              : 
     804              : #[derive(Debug, thiserror::Error)]
     805              : pub enum LoadLocalTimelineError {
     806              :     #[error("FailedToLoad")]
     807              :     Load(#[source] anyhow::Error),
     808              :     #[error("FailedToResumeDeletion")]
     809              :     ResumeDeletion(#[source] anyhow::Error),
     810              : }
     811              : 
     812              : #[derive(thiserror::Error)]
     813              : pub enum DeleteTimelineError {
     814              :     #[error("NotFound")]
     815              :     NotFound,
     816              : 
     817              :     #[error("HasChildren")]
     818              :     HasChildren(Vec<TimelineId>),
     819              : 
     820              :     #[error("Timeline deletion is already in progress")]
     821              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     822              : 
     823              :     #[error("Cancelled")]
     824              :     Cancelled,
     825              : 
     826              :     #[error(transparent)]
     827              :     Other(#[from] anyhow::Error),
     828              : }
     829              : 
     830              : impl Debug for DeleteTimelineError {
     831            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     832            0 :         match self {
     833            0 :             Self::NotFound => write!(f, "NotFound"),
     834            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     835            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     836            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     837            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     838              :         }
     839            0 :     }
     840              : }
     841              : 
     842              : #[derive(thiserror::Error)]
     843              : pub enum TimelineArchivalError {
     844              :     #[error("NotFound")]
     845              :     NotFound,
     846              : 
     847              :     #[error("Timeout")]
     848              :     Timeout,
     849              : 
     850              :     #[error("Cancelled")]
     851              :     Cancelled,
     852              : 
     853              :     #[error("ancestor is archived: {}", .0)]
     854              :     HasArchivedParent(TimelineId),
     855              : 
     856              :     #[error("HasUnarchivedChildren")]
     857              :     HasUnarchivedChildren(Vec<TimelineId>),
     858              : 
     859              :     #[error("Timeline archival is already in progress")]
     860              :     AlreadyInProgress,
     861              : 
     862              :     #[error(transparent)]
     863              :     Other(anyhow::Error),
     864              : }
     865              : 
     866              : #[derive(thiserror::Error, Debug)]
     867              : pub(crate) enum TenantManifestError {
     868              :     #[error("Remote storage error: {0}")]
     869              :     RemoteStorage(anyhow::Error),
     870              : 
     871              :     #[error("Cancelled")]
     872              :     Cancelled,
     873              : }
     874              : 
     875              : impl From<TenantManifestError> for TimelineArchivalError {
     876            0 :     fn from(e: TenantManifestError) -> Self {
     877            0 :         match e {
     878            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     879            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     880              :         }
     881            0 :     }
     882              : }
     883              : 
     884              : impl Debug for TimelineArchivalError {
     885            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     886            0 :         match self {
     887            0 :             Self::NotFound => write!(f, "NotFound"),
     888            0 :             Self::Timeout => write!(f, "Timeout"),
     889            0 :             Self::Cancelled => write!(f, "Cancelled"),
     890            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     891            0 :             Self::HasUnarchivedChildren(c) => {
     892            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     893              :             }
     894            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     895            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     896              :         }
     897            0 :     }
     898              : }
     899              : 
     900              : pub enum SetStoppingError {
     901              :     AlreadyStopping(completion::Barrier),
     902              :     Broken,
     903              : }
     904              : 
     905              : impl Debug for SetStoppingError {
     906            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     907            0 :         match self {
     908            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     909            0 :             Self::Broken => write!(f, "Broken"),
     910              :         }
     911            0 :     }
     912              : }
     913              : 
     914              : #[derive(thiserror::Error, Debug)]
     915              : pub(crate) enum FinalizeTimelineImportError {
     916              :     #[error("Import task not done yet")]
     917              :     ImportTaskStillRunning,
     918              :     #[error("Shutting down")]
     919              :     ShuttingDown,
     920              : }
     921              : 
     922              : /// Arguments to [`TenantShard::create_timeline`].
     923              : ///
     924              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     925              : /// is `None`, the result of the timeline create call is not deterministic.
     926              : ///
     927              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     928              : #[derive(Debug)]
     929              : pub(crate) enum CreateTimelineParams {
     930              :     Bootstrap(CreateTimelineParamsBootstrap),
     931              :     Branch(CreateTimelineParamsBranch),
     932              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     933              : }
     934              : 
     935              : #[derive(Debug)]
     936              : pub(crate) struct CreateTimelineParamsBootstrap {
     937              :     pub(crate) new_timeline_id: TimelineId,
     938              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     939              :     pub(crate) pg_version: PgMajorVersion,
     940              : }
     941              : 
     942              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     943              : #[derive(Debug)]
     944              : pub(crate) struct CreateTimelineParamsBranch {
     945              :     pub(crate) new_timeline_id: TimelineId,
     946              :     pub(crate) ancestor_timeline_id: TimelineId,
     947              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     948              : }
     949              : 
     950              : #[derive(Debug)]
     951              : pub(crate) struct CreateTimelineParamsImportPgdata {
     952              :     pub(crate) new_timeline_id: TimelineId,
     953              :     pub(crate) location: import_pgdata::index_part_format::Location,
     954              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     955              : }
     956              : 
     957              : /// What is used to determine idempotency of a [`TenantShard::create_timeline`] call in  [`TenantShard::start_creating_timeline`] in  [`TenantShard::start_creating_timeline`].
     958              : ///
     959              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     960              : ///
     961              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     962              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     963              : ///
     964              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     965              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     966              : ///
     967              : /// Notes:
     968              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     969              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     970              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     971              : ///
     972              : #[derive(Debug, Clone, PartialEq, Eq)]
     973              : pub(crate) enum CreateTimelineIdempotency {
     974              :     /// NB: special treatment, see comment in [`Self`].
     975              :     FailWithConflict,
     976              :     Bootstrap {
     977              :         pg_version: PgMajorVersion,
     978              :     },
     979              :     /// NB: branches always have the same `pg_version` as their ancestor.
     980              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     981              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     982              :     /// determining the child branch pg_version.
     983              :     Branch {
     984              :         ancestor_timeline_id: TimelineId,
     985              :         ancestor_start_lsn: Lsn,
     986              :     },
     987              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     988              : }
     989              : 
     990              : #[derive(Debug, Clone, PartialEq, Eq)]
     991              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     992              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     993              : }
     994              : 
     995              : /// What is returned by [`TenantShard::start_creating_timeline`].
     996              : #[must_use]
     997              : enum StartCreatingTimelineResult {
     998              :     CreateGuard(TimelineCreateGuard),
     999              :     Idempotent(Arc<Timeline>),
    1000              : }
    1001              : 
    1002              : #[allow(clippy::large_enum_variant, reason = "TODO")]
    1003              : enum TimelineInitAndSyncResult {
    1004              :     ReadyToActivate,
    1005              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
    1006              : }
    1007              : 
    1008              : #[must_use]
    1009              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
    1010              :     timeline: Arc<Timeline>,
    1011              :     import_pgdata: import_pgdata::index_part_format::Root,
    1012              :     guard: TimelineCreateGuard,
    1013              : }
    1014              : 
    1015              : /// What is returned by [`TenantShard::create_timeline`].
    1016              : enum CreateTimelineResult {
    1017              :     Created(Arc<Timeline>),
    1018              :     Idempotent(Arc<Timeline>),
    1019              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`TenantShard::timelines`] when
    1020              :     /// we return this result, nor will this concrete object ever be added there.
    1021              :     /// Cf method comment on [`TenantShard::create_timeline_import_pgdata`].
    1022              :     ImportSpawned(Arc<Timeline>),
    1023              : }
    1024              : 
    1025              : impl CreateTimelineResult {
    1026            0 :     fn discriminant(&self) -> &'static str {
    1027            0 :         match self {
    1028            0 :             Self::Created(_) => "Created",
    1029            0 :             Self::Idempotent(_) => "Idempotent",
    1030            0 :             Self::ImportSpawned(_) => "ImportSpawned",
    1031              :         }
    1032            0 :     }
    1033            0 :     fn timeline(&self) -> &Arc<Timeline> {
    1034            0 :         match self {
    1035            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
    1036              :         }
    1037            0 :     }
    1038              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
    1039              :     #[cfg(test)]
    1040          118 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
    1041          118 :         match self {
    1042          118 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
    1043              :         }
    1044          118 :     }
    1045              : }
    1046              : 
    1047              : #[derive(thiserror::Error, Debug)]
    1048              : pub enum CreateTimelineError {
    1049              :     #[error("creation of timeline with the given ID is in progress")]
    1050              :     AlreadyCreating,
    1051              :     #[error("timeline already exists with different parameters")]
    1052              :     Conflict,
    1053              :     #[error(transparent)]
    1054              :     AncestorLsn(anyhow::Error),
    1055              :     #[error("ancestor timeline is not active")]
    1056              :     AncestorNotActive,
    1057              :     #[error("ancestor timeline is archived")]
    1058              :     AncestorArchived,
    1059              :     #[error("tenant shutting down")]
    1060              :     ShuttingDown,
    1061              :     #[error(transparent)]
    1062              :     Other(#[from] anyhow::Error),
    1063              : }
    1064              : 
    1065              : #[derive(thiserror::Error, Debug)]
    1066              : pub enum InitdbError {
    1067              :     #[error("Operation was cancelled")]
    1068              :     Cancelled,
    1069              :     #[error(transparent)]
    1070              :     Other(anyhow::Error),
    1071              :     #[error(transparent)]
    1072              :     Inner(postgres_initdb::Error),
    1073              : }
    1074              : 
    1075              : enum CreateTimelineCause {
    1076              :     Load,
    1077              :     Delete,
    1078              : }
    1079              : 
    1080              : #[allow(clippy::large_enum_variant, reason = "TODO")]
    1081              : enum LoadTimelineCause {
    1082              :     Attach,
    1083              :     Unoffload,
    1084              : }
    1085              : 
    1086              : #[derive(thiserror::Error, Debug)]
    1087              : pub(crate) enum GcError {
    1088              :     // The tenant is shutting down
    1089              :     #[error("tenant shutting down")]
    1090              :     TenantCancelled,
    1091              : 
    1092              :     // The tenant is shutting down
    1093              :     #[error("timeline shutting down")]
    1094              :     TimelineCancelled,
    1095              : 
    1096              :     // The tenant is in a state inelegible to run GC
    1097              :     #[error("not active")]
    1098              :     NotActive,
    1099              : 
    1100              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1101              :     #[error("not active")]
    1102              :     BadLsn { why: String },
    1103              : 
    1104              :     // A remote storage error while scheduling updates after compaction
    1105              :     #[error(transparent)]
    1106              :     Remote(anyhow::Error),
    1107              : 
    1108              :     // An error reading while calculating GC cutoffs
    1109              :     #[error(transparent)]
    1110              :     GcCutoffs(PageReconstructError),
    1111              : 
    1112              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1113              :     #[error("timeline not found")]
    1114              :     TimelineNotFound,
    1115              : }
    1116              : 
    1117              : impl From<PageReconstructError> for GcError {
    1118            0 :     fn from(value: PageReconstructError) -> Self {
    1119            0 :         match value {
    1120            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1121            0 :             other => Self::GcCutoffs(other),
    1122              :         }
    1123            0 :     }
    1124              : }
    1125              : 
    1126              : impl From<NotInitialized> for GcError {
    1127            0 :     fn from(value: NotInitialized) -> Self {
    1128            0 :         match value {
    1129            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1130            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1131              :         }
    1132            0 :     }
    1133              : }
    1134              : 
    1135              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1136            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1137            0 :         GcError::TimelineCancelled
    1138            0 :     }
    1139              : }
    1140              : 
    1141              : #[derive(thiserror::Error, Debug)]
    1142              : pub(crate) enum LoadConfigError {
    1143              :     #[error("TOML deserialization error: '{0}'")]
    1144              :     DeserializeToml(#[from] toml_edit::de::Error),
    1145              : 
    1146              :     #[error("Config not found at {0}")]
    1147              :     NotFound(Utf8PathBuf),
    1148              : }
    1149              : 
    1150              : impl TenantShard {
    1151              :     /// Yet another helper for timeline initialization.
    1152              :     ///
    1153              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1154              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1155              :     /// - Downloads remote index file and adds remote files to the layer map
    1156              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1157              :     ///
    1158              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1159              :     /// it is marked as Active.
    1160              :     #[allow(clippy::too_many_arguments)]
    1161            3 :     async fn timeline_init_and_sync(
    1162            3 :         self: &Arc<Self>,
    1163            3 :         timeline_id: TimelineId,
    1164            3 :         resources: TimelineResources,
    1165            3 :         index_part: IndexPart,
    1166            3 :         metadata: TimelineMetadata,
    1167            3 :         previous_heatmap: Option<PreviousHeatmap>,
    1168            3 :         ancestor: Option<Arc<Timeline>>,
    1169            3 :         cause: LoadTimelineCause,
    1170            3 :         ctx: &RequestContext,
    1171            3 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1172            3 :         let tenant_id = self.tenant_shard_id;
    1173              : 
    1174            3 :         let import_pgdata = index_part.import_pgdata.clone();
    1175            3 :         let idempotency = match &import_pgdata {
    1176            0 :             Some(import_pgdata) => {
    1177            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1178            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1179            0 :                 })
    1180              :             }
    1181              :             None => {
    1182            3 :                 if metadata.ancestor_timeline().is_none() {
    1183            2 :                     CreateTimelineIdempotency::Bootstrap {
    1184            2 :                         pg_version: metadata.pg_version(),
    1185            2 :                     }
    1186              :                 } else {
    1187            1 :                     CreateTimelineIdempotency::Branch {
    1188            1 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1189            1 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1190            1 :                     }
    1191              :                 }
    1192              :             }
    1193              :         };
    1194              : 
    1195            3 :         let (timeline, _timeline_ctx) = self.create_timeline_struct(
    1196            3 :             timeline_id,
    1197            3 :             &metadata,
    1198            3 :             previous_heatmap,
    1199            3 :             ancestor.clone(),
    1200            3 :             resources,
    1201            3 :             CreateTimelineCause::Load,
    1202            3 :             idempotency.clone(),
    1203            3 :             index_part.gc_compaction.clone(),
    1204            3 :             index_part.rel_size_migration.clone(),
    1205            3 :             ctx,
    1206            3 :         )?;
    1207            3 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1208              : 
    1209            3 :         if !disk_consistent_lsn.is_valid() {
    1210              :             // As opposed to normal timelines which get initialised with a disk consitent LSN
    1211              :             // via initdb, imported timelines start from 0. If the import task stops before
    1212              :             // it advances disk consitent LSN, allow it to resume.
    1213            0 :             let in_progress_import = import_pgdata
    1214            0 :                 .as_ref()
    1215            0 :                 .map(|import| !import.is_done())
    1216            0 :                 .unwrap_or(false);
    1217            0 :             if !in_progress_import {
    1218            0 :                 anyhow::bail!("Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn");
    1219            0 :             }
    1220            3 :         }
    1221              : 
    1222            3 :         assert_eq!(
    1223              :             disk_consistent_lsn,
    1224            3 :             metadata.disk_consistent_lsn(),
    1225            0 :             "these are used interchangeably"
    1226              :         );
    1227              : 
    1228            3 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1229              : 
    1230            3 :         timeline
    1231            3 :             .load_layer_map(disk_consistent_lsn, index_part)
    1232            3 :             .await
    1233            3 :             .with_context(|| {
    1234            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1235            0 :             })?;
    1236              : 
    1237              :         // When unarchiving, we've mostly likely lost the heatmap generated prior
    1238              :         // to the archival operation. To allow warming this timeline up, generate
    1239              :         // a previous heatmap which contains all visible layers in the layer map.
    1240              :         // This previous heatmap will be used whenever a fresh heatmap is generated
    1241              :         // for the timeline.
    1242            3 :         if self.conf.generate_unarchival_heatmap && matches!(cause, LoadTimelineCause::Unoffload) {
    1243            0 :             let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
    1244            0 :             while let Some((tline, end_lsn)) = tline_ending_at {
    1245            0 :                 let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
    1246              :                 // Another unearchived timeline might have generated a heatmap for this ancestor.
    1247              :                 // If the current branch point greater than the previous one use the the heatmap
    1248              :                 // we just generated - it should include more layers.
    1249            0 :                 if !tline.should_keep_previous_heatmap(end_lsn) {
    1250            0 :                     tline
    1251            0 :                         .previous_heatmap
    1252            0 :                         .store(Some(Arc::new(unarchival_heatmap)));
    1253            0 :                 } else {
    1254            0 :                     tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
    1255              :                 }
    1256              : 
    1257            0 :                 match tline.ancestor_timeline() {
    1258            0 :                     Some(ancestor) => {
    1259            0 :                         if ancestor.update_layer_visibility().await.is_err() {
    1260              :                             // Ancestor timeline is shutting down.
    1261            0 :                             break;
    1262            0 :                         }
    1263              : 
    1264            0 :                         tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
    1265              :                     }
    1266            0 :                     None => {
    1267            0 :                         tline_ending_at = None;
    1268            0 :                     }
    1269              :                 }
    1270              :             }
    1271            3 :         }
    1272              : 
    1273            0 :         match import_pgdata {
    1274            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1275            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1276            0 :                 if !guard.insert(timeline_id) {
    1277              :                     // We should never try and load the same timeline twice during startup
    1278            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1279            0 :                 }
    1280            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1281            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1282            0 :                     owning_tenant: self.clone(),
    1283            0 :                     timeline_id,
    1284            0 :                     idempotency,
    1285              :                     // The users of this specific return value don't need the timline_path in there.
    1286            0 :                     timeline_path: timeline
    1287            0 :                         .conf
    1288            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1289              :                 };
    1290            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1291            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1292            0 :                         timeline,
    1293            0 :                         import_pgdata,
    1294            0 :                         guard: timeline_create_guard,
    1295            0 :                     },
    1296            0 :                 ))
    1297              :             }
    1298              :             Some(_) | None => {
    1299              :                 {
    1300            3 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1301            3 :                     match timelines_accessor.entry(timeline_id) {
    1302              :                         // We should never try and load the same timeline twice during startup
    1303              :                         Entry::Occupied(_) => {
    1304            0 :                             unreachable!(
    1305              :                                 "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1306              :                             );
    1307              :                         }
    1308            3 :                         Entry::Vacant(v) => {
    1309            3 :                             v.insert(Arc::clone(&timeline));
    1310            3 :                             timeline.maybe_spawn_flush_loop();
    1311            3 :                         }
    1312              :                     }
    1313              :                 }
    1314              : 
    1315            3 :                 if disk_consistent_lsn.is_valid() {
    1316              :                     // Sanity check: a timeline should have some content.
    1317              :                     // Exception: importing timelines might not yet have any
    1318            3 :                     anyhow::ensure!(
    1319            3 :                         ancestor.is_some()
    1320            2 :                             || timeline
    1321            2 :                                 .layers
    1322            2 :                                 .read(LayerManagerLockHolder::LoadLayerMap)
    1323            2 :                                 .await
    1324            2 :                                 .layer_map()
    1325            2 :                                 .expect(
    1326            2 :                                     "currently loading, layer manager cannot be shutdown already"
    1327              :                                 )
    1328            2 :                                 .iter_historic_layers()
    1329            2 :                                 .next()
    1330            2 :                                 .is_some(),
    1331            0 :                         "Timeline has no ancestor and no layer files"
    1332              :                     );
    1333            0 :                 }
    1334              : 
    1335            3 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate)
    1336              :             }
    1337              :         }
    1338            3 :     }
    1339              : 
    1340              :     /// Attach a tenant that's available in cloud storage.
    1341              :     ///
    1342              :     /// This returns quickly, after just creating the in-memory object
    1343              :     /// Tenant struct and launching a background task to download
    1344              :     /// the remote index files.  On return, the tenant is most likely still in
    1345              :     /// Attaching state, and it will become Active once the background task
    1346              :     /// finishes. You can use wait_until_active() to wait for the task to
    1347              :     /// complete.
    1348              :     ///
    1349              :     #[allow(clippy::too_many_arguments)]
    1350            0 :     pub(crate) fn spawn(
    1351            0 :         conf: &'static PageServerConf,
    1352            0 :         tenant_shard_id: TenantShardId,
    1353            0 :         resources: TenantSharedResources,
    1354            0 :         attached_conf: AttachedTenantConf,
    1355            0 :         shard_identity: ShardIdentity,
    1356            0 :         init_order: Option<InitializationOrder>,
    1357            0 :         mode: SpawnMode,
    1358            0 :         ctx: &RequestContext,
    1359            0 :     ) -> Result<Arc<TenantShard>, GlobalShutDown> {
    1360            0 :         let wal_redo_manager =
    1361            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1362              : 
    1363              :         let TenantSharedResources {
    1364            0 :             broker_client,
    1365            0 :             remote_storage,
    1366            0 :             deletion_queue_client,
    1367            0 :             l0_flush_global_state,
    1368            0 :             basebackup_cache,
    1369            0 :             feature_resolver,
    1370            0 :         } = resources;
    1371              : 
    1372            0 :         let attach_mode = attached_conf.location.attach_mode;
    1373            0 :         let generation = attached_conf.location.generation;
    1374              : 
    1375            0 :         let tenant = Arc::new(TenantShard::new(
    1376            0 :             TenantState::Attaching,
    1377            0 :             conf,
    1378            0 :             attached_conf,
    1379            0 :             shard_identity,
    1380            0 :             Some(wal_redo_manager),
    1381            0 :             tenant_shard_id,
    1382            0 :             remote_storage.clone(),
    1383            0 :             deletion_queue_client,
    1384            0 :             l0_flush_global_state,
    1385            0 :             basebackup_cache,
    1386            0 :             feature_resolver,
    1387              :         ));
    1388              : 
    1389              :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1390              :         // we shut down while attaching.
    1391            0 :         let attach_gate_guard = tenant
    1392            0 :             .gate
    1393            0 :             .enter()
    1394            0 :             .expect("We just created the TenantShard: nothing else can have shut it down yet");
    1395              : 
    1396              :         // Do all the hard work in the background
    1397            0 :         let tenant_clone = Arc::clone(&tenant);
    1398            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1399            0 :         task_mgr::spawn(
    1400            0 :             &tokio::runtime::Handle::current(),
    1401            0 :             TaskKind::Attach,
    1402            0 :             tenant_shard_id,
    1403            0 :             None,
    1404            0 :             "attach tenant",
    1405            0 :             async move {
    1406              : 
    1407            0 :                 info!(
    1408              :                     ?attach_mode,
    1409            0 :                     "Attaching tenant"
    1410              :                 );
    1411              : 
    1412            0 :                 let _gate_guard = attach_gate_guard;
    1413              : 
    1414              :                 // Is this tenant being spawned as part of process startup?
    1415            0 :                 let starting_up = init_order.is_some();
    1416            0 :                 scopeguard::defer! {
    1417              :                     if starting_up {
    1418              :                         TENANT.startup_complete.inc();
    1419              :                     }
    1420              :                 }
    1421              : 
    1422            0 :                 fn make_broken_or_stopping(t: &TenantShard, err: anyhow::Error) {
    1423            0 :                     t.state.send_modify(|state| match state {
    1424              :                         // TODO: the old code alluded to DeleteTenantFlow sometimes setting
    1425              :                         // TenantState::Stopping before we get here, but this may be outdated.
    1426              :                         // Let's find out with a testing assertion. If this doesn't fire, and the
    1427              :                         // logs don't show this happening in production, remove the Stopping cases.
    1428            0 :                         TenantState::Stopping{..} if cfg!(any(test, feature = "testing")) => {
    1429            0 :                             panic!("unexpected TenantState::Stopping during attach")
    1430              :                         }
    1431              :                         // If the tenant is cancelled, assume the error was caused by cancellation.
    1432            0 :                         TenantState::Attaching if t.cancel.is_cancelled() => {
    1433            0 :                             info!("attach cancelled, setting tenant state to Stopping: {err}");
    1434              :                             // NB: progress None tells `set_stopping` that attach has cancelled.
    1435            0 :                             *state = TenantState::Stopping { progress: None };
    1436              :                         }
    1437              :                         // According to the old code, DeleteTenantFlow may already have set this to
    1438              :                         // Stopping. Retain its progress.
    1439              :                         // TODO: there is no DeleteTenantFlow. Is this still needed? See above.
    1440            0 :                         TenantState::Stopping { progress } if t.cancel.is_cancelled() => {
    1441            0 :                             assert!(progress.is_some(), "concurrent attach cancellation");
    1442            0 :                             info!("attach cancelled, already Stopping: {err}");
    1443              :                         }
    1444              :                         // Mark the tenant as broken.
    1445              :                         TenantState::Attaching | TenantState::Stopping { .. } => {
    1446            0 :                             error!("attach failed, setting tenant state to Broken (was {state}): {err:?}");
    1447            0 :                             *state = TenantState::broken_from_reason(err.to_string())
    1448              :                         }
    1449              :                         // The attach task owns the tenant state until activated.
    1450            0 :                         state => panic!("invalid tenant state {state} during attach: {err:?}"),
    1451            0 :                     });
    1452            0 :                 }
    1453              : 
    1454              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1455            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1456            0 :                     make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1457            0 :                     return Ok(());
    1458            0 :                 }
    1459              : 
    1460            0 :                 let mut init_order = init_order;
    1461              :                 // take the completion because initial tenant loading will complete when all of
    1462              :                 // these tasks complete.
    1463            0 :                 let _completion = init_order
    1464            0 :                     .as_mut()
    1465            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1466            0 :                 let remote_load_completion = init_order
    1467            0 :                     .as_mut()
    1468            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1469              : 
    1470              :                 enum AttachType<'a> {
    1471              :                     /// We are attaching this tenant lazily in the background.
    1472              :                     Warmup {
    1473              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1474              :                         during_startup: bool
    1475              :                     },
    1476              :                     /// We are attaching this tenant as soon as we can, because for example an
    1477              :                     /// endpoint tried to access it.
    1478              :                     OnDemand,
    1479              :                     /// During normal operations after startup, we are attaching a tenant, and
    1480              :                     /// eager attach was requested.
    1481              :                     Normal,
    1482              :                 }
    1483              : 
    1484            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1485              :                     // Before doing any I/O, wait for at least one of:
    1486              :                     // - A client attempting to access to this tenant (on-demand loading)
    1487              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1488              : 
    1489            0 :                     tokio::select!(
    1490            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1491            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1492            0 :                             tracing::info!("Activating tenant (on-demand)");
    1493            0 :                             AttachType::OnDemand
    1494              :                         },
    1495            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1496            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1497            0 :                             tracing::info!("Activating tenant (warmup)");
    1498            0 :                             AttachType::Warmup {
    1499            0 :                                 _permit,
    1500            0 :                                 during_startup: init_order.is_some()
    1501            0 :                             }
    1502              :                         }
    1503            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1504              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1505              :                             // stayed in Activating for such a long time that shutdown found it in
    1506              :                             // that state.
    1507            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1508              :                             // Set the tenant to Stopping to signal `set_stopping` that we're done.
    1509            0 :                             make_broken_or_stopping(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"));
    1510            0 :                             return Ok(());
    1511              :                         },
    1512              :                     )
    1513              :                 } else {
    1514              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1515              :                     // concurrent_tenant_warmup queue
    1516            0 :                     AttachType::Normal
    1517              :                 };
    1518              : 
    1519            0 :                 let preload = match &mode {
    1520              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1521            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1522            0 :                         let res = tenant_clone
    1523            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1524            0 :                             .await;
    1525            0 :                         match res {
    1526            0 :                             Ok(p) => Some(p),
    1527            0 :                             Err(e) => {
    1528            0 :                                 make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1529            0 :                                 return Ok(());
    1530              :                             }
    1531              :                         }
    1532              :                     }
    1533              : 
    1534              :                 };
    1535              : 
    1536              :                 // Remote preload is complete.
    1537            0 :                 drop(remote_load_completion);
    1538              : 
    1539              : 
    1540              :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1541            0 :                 let attach_start = std::time::Instant::now();
    1542            0 :                 let attached = {
    1543            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1544            0 :                     tenant_clone.attach(preload, &ctx).await
    1545              :                 };
    1546            0 :                 let attach_duration = attach_start.elapsed();
    1547            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1548              : 
    1549            0 :                 match attached {
    1550              :                     Ok(()) => {
    1551            0 :                         info!("attach finished, activating");
    1552            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1553              :                     }
    1554            0 :                     Err(e) => make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e)),
    1555              :                 }
    1556              : 
    1557              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1558              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1559              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1560              :                 //
    1561              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1562              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1563              :                 // then warmup will wait for that before proceeding to the next tenant.
    1564            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1565            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1566            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1567            0 :                     while futs.next().await.is_some() {}
    1568            0 :                     tracing::info!("Warm-up complete");
    1569            0 :                 }
    1570              : 
    1571            0 :                 Ok(())
    1572            0 :             }
    1573            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1574              :         );
    1575            0 :         Ok(tenant)
    1576            0 :     }
    1577              : 
    1578              :     #[instrument(skip_all)]
    1579              :     pub(crate) async fn preload(
    1580              :         self: &Arc<Self>,
    1581              :         remote_storage: &GenericRemoteStorage,
    1582              :         cancel: CancellationToken,
    1583              :     ) -> anyhow::Result<TenantPreload> {
    1584              :         span::debug_assert_current_span_has_tenant_id();
    1585              :         // Get list of remote timelines
    1586              :         // download index files for every tenant timeline
    1587              :         info!("listing remote timelines");
    1588              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1589              :             remote_storage,
    1590              :             self.tenant_shard_id,
    1591              :             cancel.clone(),
    1592              :         )
    1593              :         .await?;
    1594              : 
    1595              :         let tenant_manifest = match download_tenant_manifest(
    1596              :             remote_storage,
    1597              :             &self.tenant_shard_id,
    1598              :             self.generation,
    1599              :             &cancel,
    1600              :         )
    1601              :         .await
    1602              :         {
    1603              :             Ok((tenant_manifest, _, _)) => Some(tenant_manifest),
    1604              :             Err(DownloadError::NotFound) => None,
    1605              :             Err(err) => return Err(err.into()),
    1606              :         };
    1607              : 
    1608              :         info!(
    1609              :             "found {} timelines ({} offloaded timelines)",
    1610              :             remote_timeline_ids.len(),
    1611              :             tenant_manifest
    1612              :                 .as_ref()
    1613            3 :                 .map(|m| m.offloaded_timelines.len())
    1614              :                 .unwrap_or(0)
    1615              :         );
    1616              : 
    1617              :         for k in other_keys {
    1618              :             warn!("Unexpected non timeline key {k}");
    1619              :         }
    1620              : 
    1621              :         // Avoid downloading IndexPart of offloaded timelines.
    1622              :         let mut offloaded_with_prefix = HashSet::new();
    1623              :         if let Some(tenant_manifest) = &tenant_manifest {
    1624              :             for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1625              :                 if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1626              :                     offloaded_with_prefix.insert(offloaded.timeline_id);
    1627              :                 } else {
    1628              :                     // We'll take care later of timelines in the manifest without a prefix
    1629              :                 }
    1630              :             }
    1631              :         }
    1632              : 
    1633              :         // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
    1634              :         // pulled the first heatmap. Not entirely necessary since the storage controller
    1635              :         // will kick the secondary in any case and cause a download.
    1636              :         let maybe_heatmap_at = self.read_on_disk_heatmap().await;
    1637              : 
    1638              :         let timelines = self
    1639              :             .load_timelines_metadata(
    1640              :                 remote_timeline_ids,
    1641              :                 remote_storage,
    1642              :                 maybe_heatmap_at,
    1643              :                 cancel,
    1644              :             )
    1645              :             .await?;
    1646              : 
    1647              :         Ok(TenantPreload {
    1648              :             tenant_manifest,
    1649              :             timelines: timelines
    1650              :                 .into_iter()
    1651            3 :                 .map(|(id, tl)| (id, Some(tl)))
    1652            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1653              :                 .collect(),
    1654              :         })
    1655              :     }
    1656              : 
    1657          118 :     async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
    1658          118 :         if !self.conf.load_previous_heatmap {
    1659            0 :             return None;
    1660          118 :         }
    1661              : 
    1662          118 :         let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
    1663          118 :         match tokio::fs::read_to_string(on_disk_heatmap_path).await {
    1664            0 :             Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
    1665            0 :                 Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
    1666            0 :                 Err(err) => {
    1667            0 :                     error!("Failed to deserialize old heatmap: {err}");
    1668            0 :                     None
    1669              :                 }
    1670              :             },
    1671          118 :             Err(err) => match err.kind() {
    1672          118 :                 std::io::ErrorKind::NotFound => None,
    1673              :                 _ => {
    1674            0 :                     error!("Unexpected IO error reading old heatmap: {err}");
    1675            0 :                     None
    1676              :                 }
    1677              :             },
    1678              :         }
    1679          118 :     }
    1680              : 
    1681              :     ///
    1682              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1683              :     ///
    1684              :     /// No background tasks are started as part of this routine.
    1685              :     ///
    1686          118 :     async fn attach(
    1687          118 :         self: &Arc<TenantShard>,
    1688          118 :         preload: Option<TenantPreload>,
    1689          118 :         ctx: &RequestContext,
    1690          118 :     ) -> anyhow::Result<()> {
    1691          118 :         span::debug_assert_current_span_has_tenant_id();
    1692              : 
    1693          118 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1694              : 
    1695          118 :         let Some(preload) = preload else {
    1696            0 :             anyhow::bail!(
    1697            0 :                 "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
    1698              :             );
    1699              :         };
    1700              : 
    1701          118 :         let mut offloaded_timeline_ids = HashSet::new();
    1702          118 :         let mut offloaded_timelines_list = Vec::new();
    1703          118 :         if let Some(tenant_manifest) = &preload.tenant_manifest {
    1704            3 :             for timeline_manifest in tenant_manifest.offloaded_timelines.iter() {
    1705            0 :                 let timeline_id = timeline_manifest.timeline_id;
    1706            0 :                 let offloaded_timeline =
    1707            0 :                     OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1708            0 :                 offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1709            0 :                 offloaded_timeline_ids.insert(timeline_id);
    1710            0 :             }
    1711          115 :         }
    1712              :         // Complete deletions for offloaded timeline id's from manifest.
    1713              :         // The manifest will be uploaded later in this function.
    1714          118 :         offloaded_timelines_list
    1715          118 :             .retain(|(offloaded_id, offloaded)| {
    1716              :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1717              :                 // If there is dangling references in another location, they need to be cleaned up.
    1718            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1719            0 :                 if delete {
    1720            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1721            0 :                     offloaded.defuse_for_tenant_drop();
    1722            0 :                 }
    1723            0 :                 !delete
    1724            0 :         });
    1725              : 
    1726          118 :         let mut timelines_to_resume_deletions = vec![];
    1727              : 
    1728          118 :         let mut remote_index_and_client = HashMap::new();
    1729          118 :         let mut timeline_ancestors = HashMap::new();
    1730          118 :         let mut existent_timelines = HashSet::new();
    1731          121 :         for (timeline_id, preload) in preload.timelines {
    1732            3 :             let Some(preload) = preload else { continue };
    1733              :             // This is an invariant of the `preload` function's API
    1734            3 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1735            3 :             let index_part = match preload.index_part {
    1736            3 :                 Ok(i) => {
    1737            3 :                     debug!("remote index part exists for timeline {timeline_id}");
    1738              :                     // We found index_part on the remote, this is the standard case.
    1739            3 :                     existent_timelines.insert(timeline_id);
    1740            3 :                     i
    1741              :                 }
    1742              :                 Err(DownloadError::NotFound) => {
    1743              :                     // There is no index_part on the remote. We only get here
    1744              :                     // if there is some prefix for the timeline in the remote storage.
    1745              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1746              :                     // remnant from a prior incomplete creation or deletion attempt.
    1747              :                     // Delete the local directory as the deciding criterion for a
    1748              :                     // timeline's existence is presence of index_part.
    1749            0 :                     info!(%timeline_id, "index_part not found on remote");
    1750            0 :                     continue;
    1751              :                 }
    1752            0 :                 Err(DownloadError::Fatal(why)) => {
    1753              :                     // If, while loading one remote timeline, we saw an indication that our generation
    1754              :                     // number is likely invalid, then we should not load the whole tenant.
    1755            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1756            0 :                     anyhow::bail!(why.to_string());
    1757              :                 }
    1758            0 :                 Err(e) => {
    1759              :                     // Some (possibly ephemeral) error happened during index_part download.
    1760              :                     // Pretend the timeline exists to not delete the timeline directory,
    1761              :                     // as it might be a temporary issue and we don't want to re-download
    1762              :                     // everything after it resolves.
    1763            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1764              : 
    1765            0 :                     existent_timelines.insert(timeline_id);
    1766            0 :                     continue;
    1767              :                 }
    1768              :             };
    1769            3 :             match index_part {
    1770            3 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1771            3 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1772            3 :                     remote_index_and_client.insert(
    1773            3 :                         timeline_id,
    1774            3 :                         (index_part, preload.client, preload.previous_heatmap),
    1775            3 :                     );
    1776            3 :                 }
    1777            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1778            0 :                     info!(
    1779            0 :                         "timeline {} is deleted, picking to resume deletion",
    1780              :                         timeline_id
    1781              :                     );
    1782            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1783              :                 }
    1784              :             }
    1785              :         }
    1786              : 
    1787          118 :         let mut gc_blocks = HashMap::new();
    1788              : 
    1789              :         // For every timeline, download the metadata file, scan the local directory,
    1790              :         // and build a layer map that contains an entry for each remote and local
    1791              :         // layer file.
    1792          118 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1793          121 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1794            3 :             let (index_part, remote_client, previous_heatmap) = remote_index_and_client
    1795            3 :                 .remove(&timeline_id)
    1796            3 :                 .expect("just put it in above");
    1797              : 
    1798            3 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1799              :                 // could just filter these away, but it helps while testing
    1800            0 :                 anyhow::ensure!(
    1801            0 :                     !blocking.reasons.is_empty(),
    1802            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1803              :                 );
    1804            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1805            0 :                 assert!(prev.is_none());
    1806            3 :             }
    1807              : 
    1808              :             // TODO again handle early failure
    1809            3 :             let effect = self
    1810            3 :                 .load_remote_timeline(
    1811            3 :                     timeline_id,
    1812            3 :                     index_part,
    1813            3 :                     remote_metadata,
    1814            3 :                     previous_heatmap,
    1815            3 :                     self.get_timeline_resources_for(remote_client),
    1816            3 :                     LoadTimelineCause::Attach,
    1817            3 :                     ctx,
    1818            3 :                 )
    1819            3 :                 .await
    1820            3 :                 .with_context(|| {
    1821            0 :                     format!(
    1822            0 :                         "failed to load remote timeline {} for tenant {}",
    1823            0 :                         timeline_id, self.tenant_shard_id
    1824              :                     )
    1825            0 :                 })?;
    1826              : 
    1827            3 :             match effect {
    1828            3 :                 TimelineInitAndSyncResult::ReadyToActivate => {
    1829            3 :                     // activation happens later, on Tenant::activate
    1830            3 :                 }
    1831              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1832              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1833            0 :                         timeline,
    1834            0 :                         import_pgdata,
    1835            0 :                         guard,
    1836              :                     },
    1837              :                 ) => {
    1838            0 :                     let timeline_id = timeline.timeline_id;
    1839            0 :                     let import_task_gate = Gate::default();
    1840            0 :                     let import_task_guard = import_task_gate.enter().unwrap();
    1841            0 :                     let import_task_handle =
    1842            0 :                         tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1843            0 :                             timeline.clone(),
    1844            0 :                             import_pgdata,
    1845            0 :                             guard,
    1846            0 :                             import_task_guard,
    1847            0 :                             ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    1848              :                         ));
    1849              : 
    1850            0 :                     let prev = self.timelines_importing.lock().unwrap().insert(
    1851            0 :                         timeline_id,
    1852            0 :                         Arc::new(ImportingTimeline {
    1853            0 :                             timeline: timeline.clone(),
    1854            0 :                             import_task_handle,
    1855            0 :                             import_task_gate,
    1856            0 :                             delete_progress: TimelineDeleteProgress::default(),
    1857            0 :                         }),
    1858            0 :                     );
    1859              : 
    1860            0 :                     assert!(prev.is_none());
    1861              :                 }
    1862              :             }
    1863              :         }
    1864              : 
    1865              :         // At this point we've initialized all timelines and are tracking them.
    1866              :         // Now compute the layer visibility for all (not offloaded) timelines.
    1867          118 :         let compute_visiblity_for = {
    1868          118 :             let timelines_accessor = self.timelines.lock().unwrap();
    1869          118 :             let mut timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    1870              : 
    1871          118 :             timelines_offloaded_accessor.extend(offloaded_timelines_list.into_iter());
    1872              : 
    1873              :             // Before activation, populate each Timeline's GcInfo with information about its children
    1874          118 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    1875              : 
    1876          118 :             timelines_accessor.values().cloned().collect::<Vec<_>>()
    1877              :         };
    1878              : 
    1879          121 :         for tl in compute_visiblity_for {
    1880            3 :             tl.update_layer_visibility().await.with_context(|| {
    1881            0 :                 format!(
    1882            0 :                     "failed initial timeline visibility computation {} for tenant {}",
    1883            0 :                     tl.timeline_id, self.tenant_shard_id
    1884              :                 )
    1885            0 :             })?;
    1886              :         }
    1887              : 
    1888              :         // Walk through deleted timelines, resume deletion
    1889          118 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1890            0 :             remote_timeline_client
    1891            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1892            0 :                 .context("init queue stopped")
    1893            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1894              : 
    1895            0 :             DeleteTimelineFlow::resume_deletion(
    1896            0 :                 Arc::clone(self),
    1897            0 :                 timeline_id,
    1898            0 :                 &index_part.metadata,
    1899            0 :                 remote_timeline_client,
    1900            0 :                 ctx,
    1901              :             )
    1902            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1903            0 :             .await
    1904            0 :             .context("resume_deletion")
    1905            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1906              :         }
    1907              : 
    1908              :         // Stash the preloaded tenant manifest, and upload a new manifest if changed.
    1909              :         //
    1910              :         // NB: this must happen after the tenant is fully populated above. In particular the
    1911              :         // offloaded timelines, which are included in the manifest.
    1912              :         {
    1913          118 :             let mut guard = self.remote_tenant_manifest.lock().await;
    1914          118 :             assert!(guard.is_none(), "tenant manifest set before preload"); // first populated here
    1915          118 :             *guard = preload.tenant_manifest;
    1916              :         }
    1917          118 :         self.maybe_upload_tenant_manifest().await?;
    1918              : 
    1919              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1920              :         // IndexPart is the source of truth.
    1921          118 :         self.clean_up_timelines(&existent_timelines)?;
    1922              : 
    1923          118 :         self.gc_block.set_scanned(gc_blocks);
    1924              : 
    1925          118 :         fail::fail_point!("attach-before-activate", |_| {
    1926            0 :             anyhow::bail!("attach-before-activate");
    1927            0 :         });
    1928          118 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1929              : 
    1930          118 :         info!("Done");
    1931              : 
    1932          118 :         Ok(())
    1933          118 :     }
    1934              : 
    1935              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1936              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1937              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1938          118 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1939          118 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1940              : 
    1941          118 :         let entries = match timelines_dir.read_dir_utf8() {
    1942          118 :             Ok(d) => d,
    1943            0 :             Err(e) => {
    1944            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1945            0 :                     return Ok(());
    1946              :                 } else {
    1947            0 :                     return Err(e).context("list timelines directory for tenant");
    1948              :                 }
    1949              :             }
    1950              :         };
    1951              : 
    1952          122 :         for entry in entries {
    1953            4 :             let entry = entry.context("read timeline dir entry")?;
    1954            4 :             let entry_path = entry.path();
    1955              : 
    1956            4 :             let purge = if crate::is_temporary(entry_path) {
    1957            0 :                 true
    1958              :             } else {
    1959            4 :                 match TimelineId::try_from(entry_path.file_name()) {
    1960            4 :                     Ok(i) => {
    1961              :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1962            4 :                         !existent_timelines.contains(&i)
    1963              :                     }
    1964            0 :                     Err(e) => {
    1965            0 :                         tracing::warn!(
    1966            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1967              :                         );
    1968              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1969            0 :                         false
    1970              :                     }
    1971              :                 }
    1972              :             };
    1973              : 
    1974            4 :             if purge {
    1975            1 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1976            1 :                 if let Err(e) = match entry.file_type() {
    1977            1 :                     Ok(t) => if t.is_dir() {
    1978            1 :                         std::fs::remove_dir_all(entry_path)
    1979              :                     } else {
    1980            0 :                         std::fs::remove_file(entry_path)
    1981              :                     }
    1982            1 :                     .or_else(fs_ext::ignore_not_found),
    1983            0 :                     Err(e) => Err(e),
    1984              :                 } {
    1985            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1986            1 :                 }
    1987            3 :             }
    1988              :         }
    1989              : 
    1990          118 :         Ok(())
    1991          118 :     }
    1992              : 
    1993              :     /// Get sum of all remote timelines sizes
    1994              :     ///
    1995              :     /// This function relies on the index_part instead of listing the remote storage
    1996            0 :     pub fn remote_size(&self) -> u64 {
    1997            0 :         let mut size = 0;
    1998              : 
    1999            0 :         for timeline in self.list_timelines() {
    2000            0 :             size += timeline.remote_client.get_remote_physical_size();
    2001            0 :         }
    2002              : 
    2003            0 :         size
    2004            0 :     }
    2005              : 
    2006              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    2007              :     #[allow(clippy::too_many_arguments)]
    2008              :     async fn load_remote_timeline(
    2009              :         self: &Arc<Self>,
    2010              :         timeline_id: TimelineId,
    2011              :         index_part: IndexPart,
    2012              :         remote_metadata: TimelineMetadata,
    2013              :         previous_heatmap: Option<PreviousHeatmap>,
    2014              :         resources: TimelineResources,
    2015              :         cause: LoadTimelineCause,
    2016              :         ctx: &RequestContext,
    2017              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    2018              :         span::debug_assert_current_span_has_tenant_id();
    2019              : 
    2020              :         info!("downloading index file for timeline {}", timeline_id);
    2021              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    2022              :             .await
    2023              :             .context("Failed to create new timeline directory")?;
    2024              : 
    2025              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    2026              :             let timelines = self.timelines.lock().unwrap();
    2027              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    2028            0 :                 || {
    2029            0 :                     anyhow::anyhow!(
    2030            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    2031              :                     )
    2032            0 :                 },
    2033              :             )?))
    2034              :         } else {
    2035              :             None
    2036              :         };
    2037              : 
    2038              :         self.timeline_init_and_sync(
    2039              :             timeline_id,
    2040              :             resources,
    2041              :             index_part,
    2042              :             remote_metadata,
    2043              :             previous_heatmap,
    2044              :             ancestor,
    2045              :             cause,
    2046              :             ctx,
    2047              :         )
    2048              :         .await
    2049              :     }
    2050              : 
    2051          118 :     async fn load_timelines_metadata(
    2052          118 :         self: &Arc<TenantShard>,
    2053          118 :         timeline_ids: HashSet<TimelineId>,
    2054          118 :         remote_storage: &GenericRemoteStorage,
    2055          118 :         heatmap: Option<(HeatMapTenant, std::time::Instant)>,
    2056          118 :         cancel: CancellationToken,
    2057          118 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    2058          118 :         let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
    2059              : 
    2060          118 :         let mut part_downloads = JoinSet::new();
    2061          121 :         for timeline_id in timeline_ids {
    2062            3 :             let cancel_clone = cancel.clone();
    2063              : 
    2064            3 :             let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
    2065            0 :                 hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
    2066            0 :                     heatmap: h,
    2067            0 :                     read_at: hs.1,
    2068            0 :                     end_lsn: None,
    2069            0 :                 })
    2070            0 :             });
    2071            3 :             part_downloads.spawn(
    2072            3 :                 self.load_timeline_metadata(
    2073            3 :                     timeline_id,
    2074            3 :                     remote_storage.clone(),
    2075            3 :                     previous_timeline_heatmap,
    2076            3 :                     cancel_clone,
    2077              :                 )
    2078            3 :                 .instrument(info_span!("download_index_part", %timeline_id)),
    2079              :             );
    2080              :         }
    2081              : 
    2082          118 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    2083              : 
    2084              :         loop {
    2085          121 :             tokio::select!(
    2086          121 :                 next = part_downloads.join_next() => {
    2087          121 :                     match next {
    2088            3 :                         Some(result) => {
    2089            3 :                             let preload = result.context("join preload task")?;
    2090            3 :                             timeline_preloads.insert(preload.timeline_id, preload);
    2091              :                         },
    2092              :                         None => {
    2093          118 :                             break;
    2094              :                         }
    2095              :                     }
    2096              :                 },
    2097          121 :                 _ = cancel.cancelled() => {
    2098            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    2099              :                 }
    2100              :             )
    2101              :         }
    2102              : 
    2103          118 :         Ok(timeline_preloads)
    2104          118 :     }
    2105              : 
    2106            3 :     fn build_timeline_client(
    2107            3 :         &self,
    2108            3 :         timeline_id: TimelineId,
    2109            3 :         remote_storage: GenericRemoteStorage,
    2110            3 :     ) -> RemoteTimelineClient {
    2111            3 :         RemoteTimelineClient::new(
    2112            3 :             remote_storage.clone(),
    2113            3 :             self.deletion_queue_client.clone(),
    2114            3 :             self.conf,
    2115            3 :             self.tenant_shard_id,
    2116            3 :             timeline_id,
    2117            3 :             self.generation,
    2118            3 :             &self.tenant_conf.load().location,
    2119              :         )
    2120            3 :     }
    2121              : 
    2122            3 :     fn load_timeline_metadata(
    2123            3 :         self: &Arc<TenantShard>,
    2124            3 :         timeline_id: TimelineId,
    2125            3 :         remote_storage: GenericRemoteStorage,
    2126            3 :         previous_heatmap: Option<PreviousHeatmap>,
    2127            3 :         cancel: CancellationToken,
    2128            3 :     ) -> impl Future<Output = TimelinePreload> + use<> {
    2129            3 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    2130            3 :         async move {
    2131            3 :             debug_assert_current_span_has_tenant_and_timeline_id();
    2132            3 :             debug!("starting index part download");
    2133              : 
    2134            3 :             let index_part = client.download_index_file(&cancel).await;
    2135              : 
    2136            3 :             debug!("finished index part download");
    2137              : 
    2138            3 :             TimelinePreload {
    2139            3 :                 client,
    2140            3 :                 timeline_id,
    2141            3 :                 index_part,
    2142            3 :                 previous_heatmap,
    2143            3 :             }
    2144            3 :         }
    2145            3 :     }
    2146              : 
    2147            0 :     fn check_to_be_archived_has_no_unarchived_children(
    2148            0 :         timeline_id: TimelineId,
    2149            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2150            0 :     ) -> Result<(), TimelineArchivalError> {
    2151            0 :         let children: Vec<TimelineId> = timelines
    2152            0 :             .iter()
    2153            0 :             .filter_map(|(id, entry)| {
    2154            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    2155            0 :                     return None;
    2156            0 :                 }
    2157            0 :                 if entry.is_archived() == Some(true) {
    2158            0 :                     return None;
    2159            0 :                 }
    2160            0 :                 Some(*id)
    2161            0 :             })
    2162            0 :             .collect();
    2163              : 
    2164            0 :         if !children.is_empty() {
    2165            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    2166            0 :         }
    2167            0 :         Ok(())
    2168            0 :     }
    2169              : 
    2170            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    2171            0 :         ancestor_timeline_id: TimelineId,
    2172            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2173            0 :         offloaded_timelines: &std::sync::MutexGuard<
    2174            0 :             '_,
    2175            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    2176            0 :         >,
    2177            0 :     ) -> Result<(), TimelineArchivalError> {
    2178            0 :         let has_archived_parent =
    2179            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2180            0 :                 ancestor_timeline.is_archived() == Some(true)
    2181            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2182            0 :                 true
    2183              :             } else {
    2184            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2185            0 :                 if cfg!(debug_assertions) {
    2186            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2187            0 :                 }
    2188            0 :                 return Err(TimelineArchivalError::NotFound);
    2189              :             };
    2190            0 :         if has_archived_parent {
    2191            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2192            0 :                 ancestor_timeline_id,
    2193            0 :             ));
    2194            0 :         }
    2195            0 :         Ok(())
    2196            0 :     }
    2197              : 
    2198            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2199            0 :         timeline: &Arc<Timeline>,
    2200            0 :     ) -> Result<(), TimelineArchivalError> {
    2201            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2202            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2203            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2204            0 :                     ancestor_timeline.timeline_id,
    2205            0 :                 ));
    2206            0 :             }
    2207            0 :         }
    2208            0 :         Ok(())
    2209            0 :     }
    2210              : 
    2211              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2212              :     ///
    2213              :     /// Counterpart to [`offload_timeline`].
    2214            0 :     async fn unoffload_timeline(
    2215            0 :         self: &Arc<Self>,
    2216            0 :         timeline_id: TimelineId,
    2217            0 :         broker_client: storage_broker::BrokerClientChannel,
    2218            0 :         ctx: RequestContext,
    2219            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2220            0 :         info!("unoffloading timeline");
    2221              : 
    2222              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2223              :         // We expect callers of this function to ensure this.
    2224            0 :         match self.current_state() {
    2225              :             TenantState::Activating { .. }
    2226              :             | TenantState::Attaching
    2227              :             | TenantState::Broken { .. } => {
    2228            0 :                 panic!("Timeline expected to be active")
    2229              :             }
    2230            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2231            0 :             TenantState::Active => {}
    2232              :         }
    2233            0 :         let cancel = self.cancel.clone();
    2234              : 
    2235              :         // Protect against concurrent attempts to use this TimelineId
    2236              :         // We don't care much about idempotency, as it's ensured a layer above.
    2237            0 :         let allow_offloaded = true;
    2238            0 :         let _create_guard = self
    2239            0 :             .create_timeline_create_guard(
    2240            0 :                 timeline_id,
    2241            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2242            0 :                 allow_offloaded,
    2243              :             )
    2244            0 :             .map_err(|err| match err {
    2245            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2246              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2247            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2248              :                 }
    2249            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2250            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2251            0 :             })?;
    2252              : 
    2253            0 :         let timeline_preload = self
    2254            0 :             .load_timeline_metadata(
    2255            0 :                 timeline_id,
    2256            0 :                 self.remote_storage.clone(),
    2257            0 :                 None,
    2258            0 :                 cancel.clone(),
    2259            0 :             )
    2260            0 :             .await;
    2261              : 
    2262            0 :         let index_part = match timeline_preload.index_part {
    2263            0 :             Ok(index_part) => {
    2264            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2265            0 :                 index_part
    2266              :             }
    2267              :             Err(DownloadError::NotFound) => {
    2268            0 :                 error!(%timeline_id, "index_part not found on remote");
    2269            0 :                 return Err(TimelineArchivalError::NotFound);
    2270              :             }
    2271            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2272            0 :             Err(e) => {
    2273              :                 // Some (possibly ephemeral) error happened during index_part download.
    2274            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2275            0 :                 return Err(TimelineArchivalError::Other(
    2276            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2277            0 :                 ));
    2278              :             }
    2279              :         };
    2280            0 :         let index_part = match index_part {
    2281            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2282            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2283            0 :                 info!("timeline is deleted according to index_part.json");
    2284            0 :                 return Err(TimelineArchivalError::NotFound);
    2285              :             }
    2286              :         };
    2287            0 :         let remote_metadata = index_part.metadata.clone();
    2288            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2289            0 :         self.load_remote_timeline(
    2290            0 :             timeline_id,
    2291            0 :             index_part,
    2292            0 :             remote_metadata,
    2293            0 :             None,
    2294            0 :             timeline_resources,
    2295            0 :             LoadTimelineCause::Unoffload,
    2296            0 :             &ctx,
    2297            0 :         )
    2298            0 :         .await
    2299            0 :         .with_context(|| {
    2300            0 :             format!(
    2301            0 :                 "failed to load remote timeline {} for tenant {}",
    2302            0 :                 timeline_id, self.tenant_shard_id
    2303              :             )
    2304            0 :         })
    2305            0 :         .map_err(TimelineArchivalError::Other)?;
    2306              : 
    2307            0 :         let timeline = {
    2308            0 :             let timelines = self.timelines.lock().unwrap();
    2309            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2310            0 :                 warn!("timeline not available directly after attach");
    2311              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2312              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2313            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2314            0 :                     "timeline not available directly after attach"
    2315            0 :                 )));
    2316              :             };
    2317            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2318            0 :             match offloaded_timelines.remove(&timeline_id) {
    2319            0 :                 Some(offloaded) => {
    2320            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2321            0 :                 }
    2322            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2323              :             }
    2324              : 
    2325            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2326              : 
    2327            0 :             Arc::clone(timeline)
    2328              :         };
    2329              : 
    2330              :         // Upload new list of offloaded timelines to S3
    2331            0 :         self.maybe_upload_tenant_manifest().await?;
    2332              : 
    2333              :         // Activate the timeline (if it makes sense)
    2334            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2335            0 :             let background_jobs_can_start = None;
    2336            0 :             timeline.activate(
    2337            0 :                 self.clone(),
    2338            0 :                 broker_client.clone(),
    2339            0 :                 background_jobs_can_start,
    2340            0 :                 &ctx.with_scope_timeline(&timeline),
    2341            0 :             );
    2342            0 :         }
    2343              : 
    2344            0 :         info!("timeline unoffloading complete");
    2345            0 :         Ok(timeline)
    2346            0 :     }
    2347              : 
    2348            0 :     pub(crate) async fn apply_timeline_archival_config(
    2349            0 :         self: &Arc<Self>,
    2350            0 :         timeline_id: TimelineId,
    2351            0 :         new_state: TimelineArchivalState,
    2352            0 :         broker_client: storage_broker::BrokerClientChannel,
    2353            0 :         ctx: RequestContext,
    2354            0 :     ) -> Result<(), TimelineArchivalError> {
    2355            0 :         info!("setting timeline archival config");
    2356              :         // First part: figure out what is needed to do, and do validation
    2357            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2358            0 :             let timelines = self.timelines.lock().unwrap();
    2359              : 
    2360            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2361            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2362            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2363            0 :                     return Err(TimelineArchivalError::NotFound);
    2364              :                 };
    2365            0 :                 if new_state == TimelineArchivalState::Archived {
    2366              :                     // It's offloaded already, so nothing to do
    2367            0 :                     return Ok(());
    2368            0 :                 }
    2369            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2370            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2371            0 :                         ancestor_timeline_id,
    2372            0 :                         &timelines,
    2373            0 :                         &offloaded_timelines,
    2374            0 :                     )?;
    2375            0 :                 }
    2376            0 :                 break 'outer None;
    2377              :             };
    2378              : 
    2379              :             // Do some validation. We release the timelines lock below, so there is potential
    2380              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2381              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2382            0 :             match new_state {
    2383              :                 TimelineArchivalState::Unarchived => {
    2384            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2385              :                 }
    2386              :                 TimelineArchivalState::Archived => {
    2387            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2388              :                 }
    2389              :             }
    2390            0 :             Some(Arc::clone(timeline))
    2391              :         };
    2392              : 
    2393              :         // Second part: unoffload timeline (if needed)
    2394            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2395            0 :             timeline
    2396              :         } else {
    2397              :             // Turn offloaded timeline into a non-offloaded one
    2398            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2399            0 :                 .await?
    2400              :         };
    2401              : 
    2402              :         // Third part: upload new timeline archival state and block until it is present in S3
    2403            0 :         let upload_needed = match timeline
    2404            0 :             .remote_client
    2405            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2406              :         {
    2407            0 :             Ok(upload_needed) => upload_needed,
    2408            0 :             Err(e) => {
    2409            0 :                 if timeline.cancel.is_cancelled() {
    2410            0 :                     return Err(TimelineArchivalError::Cancelled);
    2411              :                 } else {
    2412            0 :                     return Err(TimelineArchivalError::Other(e));
    2413              :                 }
    2414              :             }
    2415              :         };
    2416              : 
    2417            0 :         if upload_needed {
    2418            0 :             info!("Uploading new state");
    2419              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2420            0 :             let Ok(v) =
    2421            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2422              :             else {
    2423            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2424            0 :                 return Err(TimelineArchivalError::Timeout);
    2425              :             };
    2426            0 :             v.map_err(|e| match e {
    2427            0 :                 WaitCompletionError::NotInitialized(e) => {
    2428            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2429              :                 }
    2430              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2431            0 :                     TimelineArchivalError::Cancelled
    2432              :                 }
    2433            0 :             })?;
    2434            0 :         }
    2435            0 :         Ok(())
    2436            0 :     }
    2437              : 
    2438            1 :     pub fn get_offloaded_timeline(
    2439            1 :         &self,
    2440            1 :         timeline_id: TimelineId,
    2441            1 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2442            1 :         self.timelines_offloaded
    2443            1 :             .lock()
    2444            1 :             .unwrap()
    2445            1 :             .get(&timeline_id)
    2446            1 :             .map(Arc::clone)
    2447            1 :             .ok_or(GetTimelineError::NotFound {
    2448            1 :                 tenant_id: self.tenant_shard_id,
    2449            1 :                 timeline_id,
    2450            1 :             })
    2451            1 :     }
    2452              : 
    2453            2 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2454            2 :         self.tenant_shard_id
    2455            2 :     }
    2456              : 
    2457              :     /// Get Timeline handle for given Neon timeline ID.
    2458              :     /// This function is idempotent. It doesn't change internal state in any way.
    2459          111 :     pub fn get_timeline(
    2460          111 :         &self,
    2461          111 :         timeline_id: TimelineId,
    2462          111 :         active_only: bool,
    2463          111 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2464          111 :         let timelines_accessor = self.timelines.lock().unwrap();
    2465          111 :         let timeline = timelines_accessor
    2466          111 :             .get(&timeline_id)
    2467          111 :             .ok_or(GetTimelineError::NotFound {
    2468          111 :                 tenant_id: self.tenant_shard_id,
    2469          111 :                 timeline_id,
    2470          111 :             })?;
    2471              : 
    2472          110 :         if active_only && !timeline.is_active() {
    2473            0 :             Err(GetTimelineError::NotActive {
    2474            0 :                 tenant_id: self.tenant_shard_id,
    2475            0 :                 timeline_id,
    2476            0 :                 state: timeline.current_state(),
    2477            0 :             })
    2478              :         } else {
    2479          110 :             Ok(Arc::clone(timeline))
    2480              :         }
    2481          111 :     }
    2482              : 
    2483              :     /// Lists timelines the tenant contains.
    2484              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2485            3 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2486            3 :         self.timelines
    2487            3 :             .lock()
    2488            3 :             .unwrap()
    2489            3 :             .values()
    2490            3 :             .map(Arc::clone)
    2491            3 :             .collect()
    2492            3 :     }
    2493              : 
    2494              :     /// Lists timelines the tenant contains.
    2495              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2496            0 :     pub fn list_importing_timelines(&self) -> Vec<Arc<ImportingTimeline>> {
    2497            0 :         self.timelines_importing
    2498            0 :             .lock()
    2499            0 :             .unwrap()
    2500            0 :             .values()
    2501            0 :             .map(Arc::clone)
    2502            0 :             .collect()
    2503            0 :     }
    2504              : 
    2505              :     /// Lists timelines the tenant manages, including offloaded ones.
    2506              :     ///
    2507              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2508            0 :     pub fn list_timelines_and_offloaded(
    2509            0 :         &self,
    2510            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2511            0 :         let timelines = self
    2512            0 :             .timelines
    2513            0 :             .lock()
    2514            0 :             .unwrap()
    2515            0 :             .values()
    2516            0 :             .map(Arc::clone)
    2517            0 :             .collect();
    2518            0 :         let offloaded = self
    2519            0 :             .timelines_offloaded
    2520            0 :             .lock()
    2521            0 :             .unwrap()
    2522            0 :             .values()
    2523            0 :             .map(Arc::clone)
    2524            0 :             .collect();
    2525            0 :         (timelines, offloaded)
    2526            0 :     }
    2527              : 
    2528            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2529            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2530            0 :     }
    2531              : 
    2532              :     /// This is used by tests & import-from-basebackup.
    2533              :     ///
    2534              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2535              :     /// a state that will fail [`TenantShard::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2536              :     ///
    2537              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2538              :     /// by [`TenantShard::load_remote_timeline`] / [`TenantShard::attach`].
    2539              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2540              :     /// to the [`TenantShard::timelines`].
    2541              :     ///
    2542              :     /// Tests should use `TenantShard::create_test_timeline` to set up the minimum required metadata keys.
    2543          114 :     pub(crate) async fn create_empty_timeline(
    2544          114 :         self: &Arc<Self>,
    2545          114 :         new_timeline_id: TimelineId,
    2546          114 :         initdb_lsn: Lsn,
    2547          114 :         pg_version: PgMajorVersion,
    2548          114 :         ctx: &RequestContext,
    2549          114 :     ) -> anyhow::Result<(UninitializedTimeline, RequestContext)> {
    2550          114 :         anyhow::ensure!(
    2551          114 :             self.is_active(),
    2552            0 :             "Cannot create empty timelines on inactive tenant"
    2553              :         );
    2554              : 
    2555              :         // Protect against concurrent attempts to use this TimelineId
    2556          114 :         let create_guard = match self
    2557          114 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2558          114 :             .await?
    2559              :         {
    2560          113 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2561              :             StartCreatingTimelineResult::Idempotent(_) => {
    2562            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2563              :             }
    2564              :         };
    2565              : 
    2566          113 :         let new_metadata = TimelineMetadata::new(
    2567              :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2568              :             // make it valid, before calling finish_creation()
    2569          113 :             Lsn(0),
    2570          113 :             None,
    2571          113 :             None,
    2572          113 :             Lsn(0),
    2573          113 :             initdb_lsn,
    2574          113 :             initdb_lsn,
    2575          113 :             pg_version,
    2576              :         );
    2577          113 :         self.prepare_new_timeline(
    2578          113 :             new_timeline_id,
    2579          113 :             &new_metadata,
    2580          113 :             create_guard,
    2581          113 :             initdb_lsn,
    2582          113 :             None,
    2583          113 :             None,
    2584          113 :             ctx,
    2585          113 :         )
    2586          113 :         .await
    2587          114 :     }
    2588              : 
    2589              :     /// Helper for unit tests to create an empty timeline.
    2590              :     ///
    2591              :     /// The timeline is has state value `Active` but its background loops are not running.
    2592              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2593              :     // Our current tests don't need the background loops.
    2594              :     #[cfg(test)]
    2595          109 :     pub async fn create_test_timeline(
    2596          109 :         self: &Arc<Self>,
    2597          109 :         new_timeline_id: TimelineId,
    2598          109 :         initdb_lsn: Lsn,
    2599          109 :         pg_version: PgMajorVersion,
    2600          109 :         ctx: &RequestContext,
    2601          109 :     ) -> anyhow::Result<Arc<Timeline>> {
    2602          109 :         let (uninit_tl, ctx) = self
    2603          109 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2604          109 :             .await?;
    2605          109 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2606          109 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2607              : 
    2608              :         // Setup minimum keys required for the timeline to be usable.
    2609          109 :         let mut modification = tline.begin_modification(initdb_lsn);
    2610          109 :         modification
    2611          109 :             .init_empty_test_timeline()
    2612          109 :             .context("init_empty_test_timeline")?;
    2613          109 :         modification
    2614          109 :             .commit(&ctx)
    2615          109 :             .await
    2616          109 :             .context("commit init_empty_test_timeline modification")?;
    2617              : 
    2618              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2619          109 :         tline.maybe_spawn_flush_loop();
    2620          109 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2621              : 
    2622              :         // Make sure the freeze_and_flush reaches remote storage.
    2623          109 :         tline.remote_client.wait_completion().await.unwrap();
    2624              : 
    2625          109 :         let tl = uninit_tl.finish_creation().await?;
    2626              :         // The non-test code would call tl.activate() here.
    2627          109 :         tl.set_state(TimelineState::Active);
    2628          109 :         Ok(tl)
    2629          109 :     }
    2630              : 
    2631              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2632              :     #[cfg(test)]
    2633              :     #[allow(clippy::too_many_arguments)]
    2634           24 :     pub async fn create_test_timeline_with_layers(
    2635           24 :         self: &Arc<Self>,
    2636           24 :         new_timeline_id: TimelineId,
    2637           24 :         initdb_lsn: Lsn,
    2638           24 :         pg_version: PgMajorVersion,
    2639           24 :         ctx: &RequestContext,
    2640           24 :         in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
    2641           24 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2642           24 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2643           24 :         end_lsn: Lsn,
    2644           24 :     ) -> anyhow::Result<Arc<Timeline>> {
    2645              :         use checks::check_valid_layermap;
    2646              :         use itertools::Itertools;
    2647              : 
    2648           24 :         let tline = self
    2649           24 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2650           24 :             .await?;
    2651           24 :         tline.force_advance_lsn(end_lsn);
    2652           71 :         for deltas in delta_layer_desc {
    2653           47 :             tline
    2654           47 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2655           47 :                 .await?;
    2656              :         }
    2657           58 :         for (lsn, images) in image_layer_desc {
    2658           34 :             tline
    2659           34 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2660           34 :                 .await?;
    2661              :         }
    2662           28 :         for in_memory in in_memory_layer_desc {
    2663            4 :             tline
    2664            4 :                 .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
    2665            4 :                 .await?;
    2666              :         }
    2667           24 :         let layer_names = tline
    2668           24 :             .layers
    2669           24 :             .read(LayerManagerLockHolder::Testing)
    2670           24 :             .await
    2671           24 :             .layer_map()
    2672           24 :             .unwrap()
    2673           24 :             .iter_historic_layers()
    2674          105 :             .map(|layer| layer.layer_name())
    2675           24 :             .collect_vec();
    2676           24 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2677            0 :             bail!("invalid layermap: {err}");
    2678           24 :         }
    2679           24 :         Ok(tline)
    2680           24 :     }
    2681              : 
    2682              :     /// Create a new timeline.
    2683              :     ///
    2684              :     /// Returns the new timeline ID and reference to its Timeline object.
    2685              :     ///
    2686              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2687              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2688              :     #[allow(clippy::too_many_arguments)]
    2689            0 :     pub(crate) async fn create_timeline(
    2690            0 :         self: &Arc<TenantShard>,
    2691            0 :         params: CreateTimelineParams,
    2692            0 :         broker_client: storage_broker::BrokerClientChannel,
    2693            0 :         ctx: &RequestContext,
    2694            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2695            0 :         if !self.is_active() {
    2696            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2697            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2698              :             } else {
    2699            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2700            0 :                     "Cannot create timelines on inactive tenant"
    2701            0 :                 )));
    2702              :             }
    2703            0 :         }
    2704              : 
    2705            0 :         let _gate = self
    2706            0 :             .gate
    2707            0 :             .enter()
    2708            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2709              : 
    2710            0 :         let result: CreateTimelineResult = match params {
    2711              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2712            0 :                 new_timeline_id,
    2713            0 :                 existing_initdb_timeline_id,
    2714            0 :                 pg_version,
    2715              :             }) => {
    2716            0 :                 self.bootstrap_timeline(
    2717            0 :                     new_timeline_id,
    2718            0 :                     pg_version,
    2719            0 :                     existing_initdb_timeline_id,
    2720            0 :                     ctx,
    2721            0 :                 )
    2722            0 :                 .await?
    2723              :             }
    2724              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2725            0 :                 new_timeline_id,
    2726            0 :                 ancestor_timeline_id,
    2727            0 :                 mut ancestor_start_lsn,
    2728              :             }) => {
    2729            0 :                 let ancestor_timeline = self
    2730            0 :                     .get_timeline(ancestor_timeline_id, false)
    2731            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2732              : 
    2733              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2734              :                 // ready for other purposes either.
    2735            0 :                 if !ancestor_timeline.is_active() {
    2736            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2737            0 :                 }
    2738              : 
    2739            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2740            0 :                     info!("tried to branch archived timeline");
    2741            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2742            0 :                 }
    2743              : 
    2744            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2745            0 :                     *lsn = lsn.align();
    2746              : 
    2747            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2748            0 :                     if ancestor_ancestor_lsn > *lsn {
    2749              :                         // can we safely just branch from the ancestor instead?
    2750            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2751            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2752            0 :                             lsn,
    2753            0 :                             ancestor_timeline_id,
    2754            0 :                             ancestor_ancestor_lsn,
    2755            0 :                         )));
    2756            0 :                     }
    2757              : 
    2758              :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2759              :                     // to the requested branch point. The repository code itself doesn't
    2760              :                     // require it, but if we start to receive WAL on the new timeline,
    2761              :                     // decoding the new WAL might need to look up previous pages, relation
    2762              :                     // sizes etc. and that would get confused if the previous page versions
    2763              :                     // are not in the repository yet.
    2764            0 :                     ancestor_timeline
    2765            0 :                         .wait_lsn(
    2766            0 :                             *lsn,
    2767            0 :                             timeline::WaitLsnWaiter::Tenant,
    2768            0 :                             timeline::WaitLsnTimeout::Default,
    2769            0 :                             ctx,
    2770            0 :                         )
    2771            0 :                         .await
    2772            0 :                         .map_err(|e| match e {
    2773            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2774            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2775              :                             }
    2776            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2777            0 :                         })?;
    2778            0 :                 }
    2779              : 
    2780            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2781            0 :                     .await?
    2782              :             }
    2783            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2784            0 :                 self.create_timeline_import_pgdata(params, ctx).await?
    2785              :             }
    2786              :         };
    2787              : 
    2788              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2789              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2790              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2791              :         //
    2792              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2793              :         // assume that, because they can see the timeline via API, that the creation is done and
    2794              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2795              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2796              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2797              :         //
    2798              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2799              :         // creation API until it returns success. Only then is durability guaranteed.
    2800            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2801            0 :         result
    2802            0 :             .timeline()
    2803            0 :             .remote_client
    2804            0 :             .wait_completion()
    2805            0 :             .await
    2806            0 :             .map_err(|e| match e {
    2807              :                 WaitCompletionError::NotInitialized(
    2808            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2809            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2810              :                 WaitCompletionError::NotInitialized(_) => {
    2811              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2812            0 :                     debug_assert!(false);
    2813            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2814              :                 }
    2815              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2816            0 :                     CreateTimelineError::ShuttingDown
    2817              :                 }
    2818            0 :             })?;
    2819              : 
    2820              :         // The creating task is responsible for activating the timeline.
    2821              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2822              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2823            0 :         let activated_timeline = match result {
    2824            0 :             CreateTimelineResult::Created(timeline) => {
    2825            0 :                 timeline.activate(
    2826            0 :                     self.clone(),
    2827            0 :                     broker_client,
    2828            0 :                     None,
    2829            0 :                     &ctx.with_scope_timeline(&timeline),
    2830              :                 );
    2831            0 :                 timeline
    2832              :             }
    2833            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2834            0 :                 info!(
    2835            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2836              :                 );
    2837            0 :                 timeline
    2838              :             }
    2839            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2840            0 :                 info!(
    2841            0 :                     "import task spawned, timeline will become visible and activated once the import is done"
    2842              :                 );
    2843            0 :                 timeline
    2844              :             }
    2845              :         };
    2846              : 
    2847            0 :         Ok(activated_timeline)
    2848            0 :     }
    2849              : 
    2850              :     /// The returned [`Arc<Timeline>`] is NOT in the [`TenantShard::timelines`] map until the import
    2851              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2852              :     /// [`TenantShard::timelines`] map when the import completes.
    2853              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2854              :     /// for the response.
    2855            0 :     async fn create_timeline_import_pgdata(
    2856            0 :         self: &Arc<Self>,
    2857            0 :         params: CreateTimelineParamsImportPgdata,
    2858            0 :         ctx: &RequestContext,
    2859            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2860              :         let CreateTimelineParamsImportPgdata {
    2861            0 :             new_timeline_id,
    2862            0 :             location,
    2863            0 :             idempotency_key,
    2864            0 :         } = params;
    2865              : 
    2866            0 :         let started_at = chrono::Utc::now().naive_utc();
    2867              : 
    2868              :         //
    2869              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2870              :         // is the canonical way we do it.
    2871              :         // - create an empty timeline in-memory
    2872              :         // - use its remote_timeline_client to do the upload
    2873              :         // - dispose of the uninit timeline
    2874              :         // - keep the creation guard alive
    2875              : 
    2876            0 :         let timeline_create_guard = match self
    2877            0 :             .start_creating_timeline(
    2878            0 :                 new_timeline_id,
    2879            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2880            0 :                     idempotency_key: idempotency_key.clone(),
    2881            0 :                 }),
    2882            0 :             )
    2883            0 :             .await?
    2884              :         {
    2885            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2886            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2887            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    2888              :             }
    2889              :         };
    2890              : 
    2891            0 :         let (mut uninit_timeline, timeline_ctx) = {
    2892            0 :             let this = &self;
    2893            0 :             let initdb_lsn = Lsn(0);
    2894            0 :             async move {
    2895            0 :                 let new_metadata = TimelineMetadata::new(
    2896              :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2897              :                     // make it valid, before calling finish_creation()
    2898            0 :                     Lsn(0),
    2899            0 :                     None,
    2900            0 :                     None,
    2901            0 :                     Lsn(0),
    2902            0 :                     initdb_lsn,
    2903            0 :                     initdb_lsn,
    2904            0 :                     PgMajorVersion::PG15,
    2905              :                 );
    2906            0 :                 this.prepare_new_timeline(
    2907            0 :                     new_timeline_id,
    2908            0 :                     &new_metadata,
    2909            0 :                     timeline_create_guard,
    2910            0 :                     initdb_lsn,
    2911            0 :                     None,
    2912            0 :                     None,
    2913            0 :                     ctx,
    2914            0 :                 )
    2915            0 :                 .await
    2916            0 :             }
    2917              :         }
    2918            0 :         .await?;
    2919              : 
    2920            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2921            0 :             idempotency_key,
    2922            0 :             location,
    2923            0 :             started_at,
    2924            0 :         };
    2925            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2926            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2927            0 :         );
    2928            0 :         uninit_timeline
    2929            0 :             .raw_timeline()
    2930            0 :             .unwrap()
    2931            0 :             .remote_client
    2932            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2933              : 
    2934              :         // wait_completion happens in caller
    2935              : 
    2936            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2937              : 
    2938            0 :         let import_task_gate = Gate::default();
    2939            0 :         let import_task_guard = import_task_gate.enter().unwrap();
    2940              : 
    2941            0 :         let import_task_handle = tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2942            0 :             timeline.clone(),
    2943            0 :             index_part,
    2944            0 :             timeline_create_guard,
    2945            0 :             import_task_guard,
    2946            0 :             timeline_ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    2947              :         ));
    2948              : 
    2949            0 :         let prev = self.timelines_importing.lock().unwrap().insert(
    2950            0 :             timeline.timeline_id,
    2951            0 :             Arc::new(ImportingTimeline {
    2952            0 :                 timeline: timeline.clone(),
    2953            0 :                 import_task_handle,
    2954            0 :                 import_task_gate,
    2955            0 :                 delete_progress: TimelineDeleteProgress::default(),
    2956            0 :             }),
    2957            0 :         );
    2958              : 
    2959              :         // Idempotency is enforced higher up the stack
    2960            0 :         assert!(prev.is_none());
    2961              : 
    2962              :         // NB: the timeline doesn't exist in self.timelines at this point
    2963            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2964            0 :     }
    2965              : 
    2966              :     /// Finalize the import of a timeline on this shard by marking it complete in
    2967              :     /// the index part. If the import task hasn't finished yet, returns an error.
    2968              :     ///
    2969              :     /// This method is idempotent. If the import was finalized once, the next call
    2970              :     /// will be a no-op.
    2971            0 :     pub(crate) async fn finalize_importing_timeline(
    2972            0 :         &self,
    2973            0 :         timeline_id: TimelineId,
    2974            0 :     ) -> Result<(), FinalizeTimelineImportError> {
    2975            0 :         let timeline = {
    2976            0 :             let locked = self.timelines_importing.lock().unwrap();
    2977            0 :             match locked.get(&timeline_id) {
    2978            0 :                 Some(importing_timeline) => {
    2979            0 :                     if !importing_timeline.import_task_handle.is_finished() {
    2980            0 :                         return Err(FinalizeTimelineImportError::ImportTaskStillRunning);
    2981            0 :                     }
    2982              : 
    2983            0 :                     importing_timeline.timeline.clone()
    2984              :                 }
    2985              :                 None => {
    2986            0 :                     return Ok(());
    2987              :                 }
    2988              :             }
    2989              :         };
    2990              : 
    2991            0 :         timeline
    2992            0 :             .remote_client
    2993            0 :             .schedule_index_upload_for_import_pgdata_finalize()
    2994            0 :             .map_err(|_err| FinalizeTimelineImportError::ShuttingDown)?;
    2995            0 :         timeline
    2996            0 :             .remote_client
    2997            0 :             .wait_completion()
    2998            0 :             .await
    2999            0 :             .map_err(|_err| FinalizeTimelineImportError::ShuttingDown)?;
    3000              : 
    3001            0 :         self.timelines_importing
    3002            0 :             .lock()
    3003            0 :             .unwrap()
    3004            0 :             .remove(&timeline_id);
    3005              : 
    3006            0 :         Ok(())
    3007            0 :     }
    3008              : 
    3009              :     #[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))]
    3010              :     async fn create_timeline_import_pgdata_task(
    3011              :         self: Arc<TenantShard>,
    3012              :         timeline: Arc<Timeline>,
    3013              :         index_part: import_pgdata::index_part_format::Root,
    3014              :         timeline_create_guard: TimelineCreateGuard,
    3015              :         _import_task_guard: GateGuard,
    3016              :         ctx: RequestContext,
    3017              :     ) {
    3018              :         debug_assert_current_span_has_tenant_and_timeline_id();
    3019              :         info!("starting");
    3020              :         scopeguard::defer! {info!("exiting")};
    3021              : 
    3022              :         let res = self
    3023              :             .create_timeline_import_pgdata_task_impl(
    3024              :                 timeline,
    3025              :                 index_part,
    3026              :                 timeline_create_guard,
    3027              :                 ctx,
    3028              :             )
    3029              :             .await;
    3030              :         if let Err(err) = &res {
    3031              :             error!(?err, "task failed");
    3032              :             // TODO sleep & retry, sensitive to tenant shutdown
    3033              :             // TODO: allow timeline deletion requests => should cancel the task
    3034              :         }
    3035              :     }
    3036              : 
    3037            0 :     async fn create_timeline_import_pgdata_task_impl(
    3038            0 :         self: Arc<TenantShard>,
    3039            0 :         timeline: Arc<Timeline>,
    3040            0 :         index_part: import_pgdata::index_part_format::Root,
    3041            0 :         _timeline_create_guard: TimelineCreateGuard,
    3042            0 :         ctx: RequestContext,
    3043            0 :     ) -> Result<(), anyhow::Error> {
    3044            0 :         info!("importing pgdata");
    3045            0 :         let ctx = ctx.with_scope_timeline(&timeline);
    3046            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    3047            0 :             .await
    3048            0 :             .context("import")?;
    3049            0 :         info!("import done - waiting for activation");
    3050              : 
    3051            0 :         anyhow::Ok(())
    3052            0 :     }
    3053              : 
    3054            0 :     pub(crate) async fn delete_timeline(
    3055            0 :         self: Arc<Self>,
    3056            0 :         timeline_id: TimelineId,
    3057            0 :     ) -> Result<(), DeleteTimelineError> {
    3058            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    3059              : 
    3060            0 :         Ok(())
    3061            0 :     }
    3062              : 
    3063              :     /// perform one garbage collection iteration, removing old data files from disk.
    3064              :     /// this function is periodically called by gc task.
    3065              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    3066              :     ///
    3067              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    3068              :     ///
    3069              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    3070              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    3071              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    3072              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    3073              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    3074              :     /// requires more history to be retained.
    3075              :     //
    3076          377 :     pub(crate) async fn gc_iteration(
    3077          377 :         &self,
    3078          377 :         target_timeline_id: Option<TimelineId>,
    3079          377 :         horizon: u64,
    3080          377 :         pitr: Duration,
    3081          377 :         cancel: &CancellationToken,
    3082          377 :         ctx: &RequestContext,
    3083          377 :     ) -> Result<GcResult, GcError> {
    3084              :         // Don't start doing work during shutdown
    3085          377 :         if let TenantState::Stopping { .. } = self.current_state() {
    3086            0 :             return Ok(GcResult::default());
    3087          377 :         }
    3088              : 
    3089              :         // there is a global allowed_error for this
    3090          377 :         if !self.is_active() {
    3091            0 :             return Err(GcError::NotActive);
    3092          377 :         }
    3093              : 
    3094              :         {
    3095          377 :             let conf = self.tenant_conf.load();
    3096              : 
    3097              :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    3098              :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    3099              :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    3100              :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    3101          377 :             if !conf.location.may_delete_layers_hint() {
    3102            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    3103            0 :                 return Ok(GcResult::default());
    3104          377 :             }
    3105              : 
    3106          377 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    3107            0 :                 info!("Skipping GC because lsn lease deadline is not reached");
    3108            0 :                 return Ok(GcResult::default());
    3109          377 :             }
    3110              :         }
    3111              : 
    3112          377 :         let _guard = match self.gc_block.start().await {
    3113          377 :             Ok(guard) => guard,
    3114            0 :             Err(reasons) => {
    3115            0 :                 info!("Skipping GC: {reasons}");
    3116            0 :                 return Ok(GcResult::default());
    3117              :             }
    3118              :         };
    3119              : 
    3120          377 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    3121          377 :             .await
    3122          377 :     }
    3123              : 
    3124              :     /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
    3125              :     /// whether another compaction is needed, if we still have pending work or if we yield for
    3126              :     /// immediate L0 compaction.
    3127              :     ///
    3128              :     /// Compaction can also be explicitly requested for a timeline via the HTTP API.
    3129            0 :     async fn compaction_iteration(
    3130            0 :         self: &Arc<Self>,
    3131            0 :         cancel: &CancellationToken,
    3132            0 :         ctx: &RequestContext,
    3133            0 :     ) -> Result<CompactionOutcome, CompactionError> {
    3134              :         // Don't compact inactive tenants.
    3135            0 :         if !self.is_active() {
    3136            0 :             return Ok(CompactionOutcome::Skipped);
    3137            0 :         }
    3138              : 
    3139              :         // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
    3140              :         // since we need to compact L0 even in AttachedMulti to bound read amplification.
    3141            0 :         let location = self.tenant_conf.load().location;
    3142            0 :         if !location.may_upload_layers_hint() {
    3143            0 :             info!("skipping compaction in location state {location:?}");
    3144            0 :             return Ok(CompactionOutcome::Skipped);
    3145            0 :         }
    3146              : 
    3147              :         // Don't compact if the circuit breaker is tripped.
    3148            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    3149            0 :             info!("skipping compaction due to previous failures");
    3150            0 :             return Ok(CompactionOutcome::Skipped);
    3151            0 :         }
    3152              : 
    3153              :         // Collect all timelines to compact, along with offload instructions and L0 counts.
    3154            0 :         let mut compact: Vec<Arc<Timeline>> = Vec::new();
    3155            0 :         let mut offload: HashSet<TimelineId> = HashSet::new();
    3156            0 :         let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
    3157              : 
    3158              :         {
    3159            0 :             let offload_enabled = self.get_timeline_offloading_enabled();
    3160            0 :             let timelines = self.timelines.lock().unwrap();
    3161            0 :             for (&timeline_id, timeline) in timelines.iter() {
    3162              :                 // Skip inactive timelines.
    3163            0 :                 if !timeline.is_active() {
    3164            0 :                     continue;
    3165            0 :                 }
    3166              : 
    3167              :                 // Schedule the timeline for compaction.
    3168            0 :                 compact.push(timeline.clone());
    3169              : 
    3170              :                 // Schedule the timeline for offloading if eligible.
    3171            0 :                 let can_offload = offload_enabled
    3172            0 :                     && timeline.can_offload().0
    3173            0 :                     && !timelines
    3174            0 :                         .iter()
    3175            0 :                         .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
    3176            0 :                 if can_offload {
    3177            0 :                     offload.insert(timeline_id);
    3178            0 :                 }
    3179              :             }
    3180              :         } // release timelines lock
    3181              : 
    3182            0 :         for timeline in &compact {
    3183              :             // Collect L0 counts. Can't await while holding lock above.
    3184            0 :             if let Ok(lm) = timeline
    3185            0 :                 .layers
    3186            0 :                 .read(LayerManagerLockHolder::Compaction)
    3187            0 :                 .await
    3188            0 :                 .layer_map()
    3189            0 :             {
    3190            0 :                 l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
    3191            0 :             }
    3192              :         }
    3193              : 
    3194              :         // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
    3195              :         // bound read amplification.
    3196              :         //
    3197              :         // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
    3198              :         // compaction and offloading. We leave that as a potential problem to solve later. Consider
    3199              :         // splitting L0 and image/GC compaction to separate background jobs.
    3200            0 :         if self.get_compaction_l0_first() {
    3201            0 :             let compaction_threshold = self.get_compaction_threshold();
    3202            0 :             let compact_l0 = compact
    3203            0 :                 .iter()
    3204            0 :                 .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
    3205            0 :                 .filter(|&(_, l0)| l0 >= compaction_threshold)
    3206            0 :                 .sorted_by_key(|&(_, l0)| l0)
    3207            0 :                 .rev()
    3208            0 :                 .map(|(tli, _)| tli.clone())
    3209            0 :                 .collect_vec();
    3210              : 
    3211            0 :             let mut has_pending_l0 = false;
    3212            0 :             for timeline in compact_l0 {
    3213            0 :                 let ctx = &ctx.with_scope_timeline(&timeline);
    3214              :                 // NB: don't set CompactFlags::YieldForL0, since this is an L0-only compaction pass.
    3215            0 :                 let outcome = timeline
    3216            0 :                     .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
    3217            0 :                     .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3218            0 :                     .await
    3219            0 :                     .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3220            0 :                 match outcome {
    3221            0 :                     CompactionOutcome::Done => {}
    3222            0 :                     CompactionOutcome::Skipped => {}
    3223            0 :                     CompactionOutcome::Pending => has_pending_l0 = true,
    3224            0 :                     CompactionOutcome::YieldForL0 => has_pending_l0 = true,
    3225              :                 }
    3226              :             }
    3227            0 :             if has_pending_l0 {
    3228            0 :                 return Ok(CompactionOutcome::YieldForL0); // do another pass
    3229            0 :             }
    3230            0 :         }
    3231              : 
    3232              :         // Pass 2: image compaction and timeline offloading. If any timelines have accumulated more
    3233              :         // L0 layers, they may also be compacted here. Image compaction will yield if there is
    3234              :         // pending L0 compaction on any tenant timeline.
    3235              :         //
    3236              :         // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
    3237              :         // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
    3238            0 :         let mut has_pending = false;
    3239            0 :         for timeline in compact {
    3240            0 :             if !timeline.is_active() {
    3241            0 :                 continue;
    3242            0 :             }
    3243            0 :             let ctx = &ctx.with_scope_timeline(&timeline);
    3244              : 
    3245              :             // Yield for L0 if the separate L0 pass is enabled (otherwise there's no point).
    3246            0 :             let mut flags = EnumSet::default();
    3247            0 :             if self.get_compaction_l0_first() {
    3248            0 :                 flags |= CompactFlags::YieldForL0;
    3249            0 :             }
    3250              : 
    3251            0 :             let mut outcome = timeline
    3252            0 :                 .compact(cancel, flags, ctx)
    3253            0 :                 .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3254            0 :                 .await
    3255            0 :                 .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3256              : 
    3257              :             // If we're done compacting, check the scheduled GC compaction queue for more work.
    3258            0 :             if outcome == CompactionOutcome::Done {
    3259            0 :                 let queue = {
    3260            0 :                     let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3261            0 :                     guard
    3262            0 :                         .entry(timeline.timeline_id)
    3263            0 :                         .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
    3264            0 :                         .clone()
    3265              :                 };
    3266            0 :                 let gc_compaction_strategy = self
    3267            0 :                     .feature_resolver
    3268            0 :                     .evaluate_multivariate("gc-comapction-strategy")
    3269            0 :                     .ok();
    3270            0 :                 let span = if let Some(gc_compaction_strategy) = gc_compaction_strategy {
    3271            0 :                     info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id, strategy = %gc_compaction_strategy)
    3272              :                 } else {
    3273            0 :                     info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id)
    3274              :                 };
    3275            0 :                 outcome = queue
    3276            0 :                     .iteration(cancel, ctx, &self.gc_block, &timeline)
    3277            0 :                     .instrument(span)
    3278            0 :                     .await?;
    3279            0 :             }
    3280              : 
    3281              :             // If we're done compacting, offload the timeline if requested.
    3282            0 :             if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
    3283            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3284            0 :                 offload_timeline(self, &timeline)
    3285            0 :                     .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
    3286            0 :                     .await
    3287            0 :                     .or_else(|err| match err {
    3288              :                         // Ignore this, we likely raced with unarchival.
    3289            0 :                         OffloadError::NotArchived => Ok(()),
    3290            0 :                         OffloadError::AlreadyInProgress => Ok(()),
    3291            0 :                         OffloadError::Cancelled => Err(CompactionError::ShuttingDown),
    3292              :                         // don't break the anyhow chain
    3293            0 :                         OffloadError::Other(err) => Err(CompactionError::Other(err)),
    3294            0 :                     })?;
    3295            0 :             }
    3296              : 
    3297            0 :             match outcome {
    3298            0 :                 CompactionOutcome::Done => {}
    3299            0 :                 CompactionOutcome::Skipped => {}
    3300            0 :                 CompactionOutcome::Pending => has_pending = true,
    3301              :                 // This mostly makes sense when the L0-only pass above is enabled, since there's
    3302              :                 // otherwise no guarantee that we'll start with the timeline that has high L0.
    3303            0 :                 CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
    3304              :             }
    3305              :         }
    3306              : 
    3307              :         // Success! Untrip the breaker if necessary.
    3308            0 :         self.compaction_circuit_breaker
    3309            0 :             .lock()
    3310            0 :             .unwrap()
    3311            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3312              : 
    3313            0 :         match has_pending {
    3314            0 :             true => Ok(CompactionOutcome::Pending),
    3315            0 :             false => Ok(CompactionOutcome::Done),
    3316              :         }
    3317            0 :     }
    3318              : 
    3319              :     /// Trips the compaction circuit breaker if appropriate.
    3320            0 :     pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
    3321            0 :         match err {
    3322            0 :             err if err.is_cancel() => {}
    3323            0 :             CompactionError::ShuttingDown => (),
    3324            0 :             CompactionError::CollectKeySpaceError(err) => {
    3325            0 :                 // CollectKeySpaceError::Cancelled and PageRead::Cancelled are handled in `err.is_cancel` branch.
    3326            0 :                 self.compaction_circuit_breaker
    3327            0 :                     .lock()
    3328            0 :                     .unwrap()
    3329            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3330            0 :             }
    3331            0 :             CompactionError::Other(err) => {
    3332            0 :                 self.compaction_circuit_breaker
    3333            0 :                     .lock()
    3334            0 :                     .unwrap()
    3335            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3336            0 :             }
    3337              :         }
    3338            0 :     }
    3339              : 
    3340              :     /// Cancel scheduled compaction tasks
    3341            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3342            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3343            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3344            0 :             q.cancel_scheduled();
    3345            0 :         }
    3346            0 :     }
    3347              : 
    3348            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3349            0 :         &self,
    3350            0 :         timeline_id: TimelineId,
    3351            0 :     ) -> Vec<CompactInfoResponse> {
    3352            0 :         let res = {
    3353            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3354            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3355              :         };
    3356            0 :         let Some((running, remaining)) = res else {
    3357            0 :             return Vec::new();
    3358              :         };
    3359            0 :         let mut result = Vec::new();
    3360            0 :         if let Some((id, running)) = running {
    3361            0 :             result.extend(running.into_compact_info_resp(id, true));
    3362            0 :         }
    3363            0 :         for (id, job) in remaining {
    3364            0 :             result.extend(job.into_compact_info_resp(id, false));
    3365            0 :         }
    3366            0 :         result
    3367            0 :     }
    3368              : 
    3369              :     /// Schedule a compaction task for a timeline.
    3370            0 :     pub(crate) async fn schedule_compaction(
    3371            0 :         &self,
    3372            0 :         timeline_id: TimelineId,
    3373            0 :         options: CompactOptions,
    3374            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3375            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3376            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3377            0 :         let q = guard
    3378            0 :             .entry(timeline_id)
    3379            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3380            0 :         q.schedule_manual_compaction(options, Some(tx));
    3381            0 :         Ok(rx)
    3382            0 :     }
    3383              : 
    3384              :     /// Performs periodic housekeeping, via the tenant housekeeping background task.
    3385            0 :     async fn housekeeping(&self) {
    3386              :         // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
    3387              :         // during ingest, but we don't want idle timelines to hold open layers for too long.
    3388              :         //
    3389              :         // We don't do this if the tenant can't upload layers (i.e. it's in stale attachment mode).
    3390              :         // We don't run compaction in this case either, and don't want to keep flushing tiny L0
    3391              :         // layers that won't be compacted down.
    3392            0 :         if self.tenant_conf.load().location.may_upload_layers_hint() {
    3393            0 :             let timelines = self
    3394            0 :                 .timelines
    3395            0 :                 .lock()
    3396            0 :                 .unwrap()
    3397            0 :                 .values()
    3398            0 :                 .filter(|tli| tli.is_active())
    3399            0 :                 .cloned()
    3400            0 :                 .collect_vec();
    3401              : 
    3402            0 :             for timeline in timelines {
    3403            0 :                 timeline.maybe_freeze_ephemeral_layer().await;
    3404              :             }
    3405            0 :         }
    3406              : 
    3407              :         // Shut down walredo if idle.
    3408              :         const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
    3409            0 :         if let Some(ref walredo_mgr) = self.walredo_mgr {
    3410            0 :             walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
    3411            0 :         }
    3412              : 
    3413              :         // Update the feature resolver with the latest tenant-spcific data.
    3414            0 :         self.feature_resolver.refresh_properties_and_flags(self);
    3415            0 :     }
    3416              : 
    3417            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3418            0 :         let timelines = self.timelines.lock().unwrap();
    3419            0 :         !timelines
    3420            0 :             .iter()
    3421            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3422            0 :     }
    3423              : 
    3424         1369 :     pub fn current_state(&self) -> TenantState {
    3425         1369 :         self.state.borrow().clone()
    3426         1369 :     }
    3427              : 
    3428          988 :     pub fn is_active(&self) -> bool {
    3429          988 :         self.current_state() == TenantState::Active
    3430          988 :     }
    3431              : 
    3432            0 :     pub fn generation(&self) -> Generation {
    3433            0 :         self.generation
    3434            0 :     }
    3435              : 
    3436            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3437            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3438            0 :     }
    3439              : 
    3440              :     /// Changes tenant status to active, unless shutdown was already requested.
    3441              :     ///
    3442              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3443              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3444            0 :     fn activate(
    3445            0 :         self: &Arc<Self>,
    3446            0 :         broker_client: BrokerClientChannel,
    3447            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3448            0 :         ctx: &RequestContext,
    3449            0 :     ) {
    3450            0 :         span::debug_assert_current_span_has_tenant_id();
    3451              : 
    3452            0 :         let mut activating = false;
    3453            0 :         self.state.send_modify(|current_state| {
    3454              :             use pageserver_api::models::ActivatingFrom;
    3455            0 :             match &*current_state {
    3456              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3457            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {current_state:?}");
    3458              :                 }
    3459            0 :                 TenantState::Attaching => {
    3460            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3461            0 :                 }
    3462              :             }
    3463            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3464            0 :             activating = true;
    3465              :             // Continue outside the closure. We need to grab timelines.lock()
    3466              :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3467            0 :         });
    3468              : 
    3469            0 :         if activating {
    3470            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3471            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3472            0 :             let timelines_to_activate = timelines_accessor
    3473            0 :                 .values()
    3474            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3475              : 
    3476              :             // Spawn gc and compaction loops. The loops will shut themselves
    3477              :             // down when they notice that the tenant is inactive.
    3478            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3479              : 
    3480            0 :             let mut activated_timelines = 0;
    3481              : 
    3482            0 :             for timeline in timelines_to_activate {
    3483            0 :                 timeline.activate(
    3484            0 :                     self.clone(),
    3485            0 :                     broker_client.clone(),
    3486            0 :                     background_jobs_can_start,
    3487            0 :                     &ctx.with_scope_timeline(timeline),
    3488            0 :                 );
    3489            0 :                 activated_timelines += 1;
    3490            0 :             }
    3491              : 
    3492            0 :             let tid = self.tenant_shard_id.tenant_id.to_string();
    3493            0 :             let shard_id = self.tenant_shard_id.shard_slug().to_string();
    3494            0 :             let offloaded_timeline_count = timelines_offloaded_accessor.len();
    3495            0 :             TENANT_OFFLOADED_TIMELINES
    3496            0 :                 .with_label_values(&[&tid, &shard_id])
    3497            0 :                 .set(offloaded_timeline_count as u64);
    3498              : 
    3499            0 :             self.state.send_modify(move |current_state| {
    3500            0 :                 assert!(
    3501            0 :                     matches!(current_state, TenantState::Activating(_)),
    3502            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3503              :                 );
    3504            0 :                 *current_state = TenantState::Active;
    3505              : 
    3506            0 :                 let elapsed = self.constructed_at.elapsed();
    3507            0 :                 let total_timelines = timelines_accessor.len();
    3508              : 
    3509              :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3510              :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3511            0 :                 info!(
    3512            0 :                     since_creation_millis = elapsed.as_millis(),
    3513            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3514            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3515              :                     activated_timelines,
    3516              :                     total_timelines,
    3517            0 :                     post_state = <&'static str>::from(&*current_state),
    3518            0 :                     "activation attempt finished"
    3519              :                 );
    3520              : 
    3521            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3522            0 :             });
    3523            0 :         }
    3524            0 :     }
    3525              : 
    3526              :     /// Shutdown the tenant and join all of the spawned tasks.
    3527              :     ///
    3528              :     /// The method caters for all use-cases:
    3529              :     /// - pageserver shutdown (freeze_and_flush == true)
    3530              :     /// - detach + ignore (freeze_and_flush == false)
    3531              :     ///
    3532              :     /// This will attempt to shutdown even if tenant is broken.
    3533              :     ///
    3534              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3535              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3536              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3537              :     /// the ongoing shutdown.
    3538            3 :     async fn shutdown(
    3539            3 :         &self,
    3540            3 :         shutdown_progress: completion::Barrier,
    3541            3 :         shutdown_mode: timeline::ShutdownMode,
    3542            3 :     ) -> Result<(), completion::Barrier> {
    3543            3 :         span::debug_assert_current_span_has_tenant_id();
    3544              : 
    3545              :         // Set tenant (and its timlines) to Stoppping state.
    3546              :         //
    3547              :         // Since we can only transition into Stopping state after activation is complete,
    3548              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3549              :         //
    3550              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3551              :         // 1. Lock out any new requests to the tenants.
    3552              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3553              :         // 3. Signal cancellation for other tenant background loops.
    3554              :         // 4. ???
    3555              :         //
    3556              :         // The waiting for the cancellation is not done uniformly.
    3557              :         // We certainly wait for WAL receivers to shut down.
    3558              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3559              :         // But the tenant background loops are joined-on in our caller.
    3560              :         // It's mesed up.
    3561              :         // we just ignore the failure to stop
    3562              : 
    3563              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3564              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3565              :         // is very slow.
    3566            3 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3567            0 :             self.cancel.cancel();
    3568              : 
    3569              :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3570              :             // are children of ours, so their flush loops will have shut down already
    3571            0 :             timeline::ShutdownMode::Hard
    3572              :         } else {
    3573            3 :             shutdown_mode
    3574              :         };
    3575              : 
    3576            3 :         match self.set_stopping(shutdown_progress).await {
    3577            3 :             Ok(()) => {}
    3578            0 :             Err(SetStoppingError::Broken) => {
    3579            0 :                 // assume that this is acceptable
    3580            0 :             }
    3581            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3582              :                 // give caller the option to wait for this this shutdown
    3583            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3584            0 :                 return Err(other);
    3585              :             }
    3586              :         };
    3587              : 
    3588            3 :         let mut js = tokio::task::JoinSet::new();
    3589              :         {
    3590            3 :             let timelines = self.timelines.lock().unwrap();
    3591            3 :             timelines.values().for_each(|timeline| {
    3592            3 :                 let timeline = Arc::clone(timeline);
    3593            3 :                 let timeline_id = timeline.timeline_id;
    3594            3 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3595            3 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3596            3 :             });
    3597              :         }
    3598              :         {
    3599            3 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3600            3 :             timelines_offloaded.values().for_each(|timeline| {
    3601            0 :                 timeline.defuse_for_tenant_drop();
    3602            0 :             });
    3603              :         }
    3604              :         {
    3605            3 :             let mut timelines_importing = self.timelines_importing.lock().unwrap();
    3606            3 :             timelines_importing
    3607            3 :                 .drain()
    3608            3 :                 .for_each(|(timeline_id, importing_timeline)| {
    3609            0 :                     let span = tracing::info_span!("importing_timeline_shutdown", %timeline_id);
    3610            0 :                     js.spawn(async move { importing_timeline.shutdown().instrument(span).await });
    3611            0 :                 });
    3612              :         }
    3613              :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3614            3 :         tracing::info!("Waiting for timelines...");
    3615            6 :         while let Some(res) = js.join_next().await {
    3616            0 :             match res {
    3617            3 :                 Ok(()) => {}
    3618            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3619            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3620            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3621              :             }
    3622              :         }
    3623              : 
    3624            3 :         if let ShutdownMode::Reload = shutdown_mode {
    3625            0 :             tracing::info!("Flushing deletion queue");
    3626            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3627            0 :                 match e {
    3628            0 :                     DeletionQueueError::ShuttingDown => {
    3629            0 :                         // This is the only error we expect for now. In the future, if more error
    3630            0 :                         // variants are added, we should handle them here.
    3631            0 :                     }
    3632              :                 }
    3633            0 :             }
    3634            3 :         }
    3635              : 
    3636              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3637              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3638            3 :         tracing::debug!("Cancelling CancellationToken");
    3639            3 :         self.cancel.cancel();
    3640              : 
    3641              :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3642              :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3643              :         //
    3644              :         // this will additionally shutdown and await all timeline tasks.
    3645            3 :         tracing::debug!("Waiting for tasks...");
    3646            3 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3647              : 
    3648            3 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3649            3 :             walredo_mgr.shutdown().await;
    3650            0 :         }
    3651              : 
    3652              :         // Wait for any in-flight operations to complete
    3653            3 :         self.gate.close().await;
    3654              : 
    3655            3 :         remove_tenant_metrics(&self.tenant_shard_id);
    3656              : 
    3657            3 :         Ok(())
    3658            3 :     }
    3659              : 
    3660              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3661              :     ///
    3662              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3663              :     ///
    3664              :     /// This function is not cancel-safe!
    3665            3 :     async fn set_stopping(&self, progress: completion::Barrier) -> Result<(), SetStoppingError> {
    3666            3 :         let mut rx = self.state.subscribe();
    3667              : 
    3668              :         // cannot stop before we're done activating, so wait out until we're done activating
    3669            3 :         rx.wait_for(|state| match state {
    3670              :             TenantState::Activating(_) | TenantState::Attaching => {
    3671            0 :                 info!("waiting for {state} to turn Active|Broken|Stopping");
    3672            0 :                 false
    3673              :             }
    3674            3 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3675            3 :         })
    3676            3 :         .await
    3677            3 :         .expect("cannot drop self.state while on a &self method");
    3678              : 
    3679              :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3680            3 :         let mut err = None;
    3681            3 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3682              :             TenantState::Activating(_) | TenantState::Attaching => {
    3683            0 :                 unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3684              :             }
    3685              :             TenantState::Active => {
    3686              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3687              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3688              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3689            3 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3690              :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3691              :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3692            3 :                 true
    3693              :             }
    3694              :             TenantState::Stopping { progress: None } => {
    3695              :                 // An attach was cancelled, and the attach transitioned the tenant from Attaching to
    3696              :                 // Stopping(None) to let us know it exited. Register our progress and continue.
    3697            0 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3698            0 :                 true
    3699              :             }
    3700            0 :             TenantState::Broken { reason, .. } => {
    3701            0 :                 info!(
    3702            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3703              :                 );
    3704            0 :                 err = Some(SetStoppingError::Broken);
    3705            0 :                 false
    3706              :             }
    3707            0 :             TenantState::Stopping { progress: Some(progress) } => {
    3708            0 :                 info!("Tenant is already in Stopping state");
    3709            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3710            0 :                 false
    3711              :             }
    3712            3 :         });
    3713            3 :         match (stopping, err) {
    3714            3 :             (true, None) => {} // continue
    3715            0 :             (false, Some(err)) => return Err(err),
    3716            0 :             (true, Some(_)) => unreachable!(
    3717              :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3718              :             ),
    3719            0 :             (false, None) => unreachable!(
    3720              :                 "send_if_modified closure must return true if transitioning to Stopping"
    3721              :             ),
    3722              :         }
    3723              : 
    3724            3 :         let timelines_accessor = self.timelines.lock().unwrap();
    3725            3 :         let not_broken_timelines = timelines_accessor
    3726            3 :             .values()
    3727            3 :             .filter(|timeline| !timeline.is_broken());
    3728            6 :         for timeline in not_broken_timelines {
    3729            3 :             timeline.set_state(TimelineState::Stopping);
    3730            3 :         }
    3731            3 :         Ok(())
    3732            3 :     }
    3733              : 
    3734              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3735              :     /// `remove_tenant_from_memory`
    3736              :     ///
    3737              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3738              :     ///
    3739              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3740            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3741            0 :         let mut rx = self.state.subscribe();
    3742              : 
    3743              :         // The load & attach routines own the tenant state until it has reached `Active`.
    3744              :         // So, wait until it's done.
    3745            0 :         rx.wait_for(|state| match state {
    3746              :             TenantState::Activating(_) | TenantState::Attaching => {
    3747            0 :                 info!(
    3748            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3749            0 :                     <&'static str>::from(state)
    3750              :                 );
    3751            0 :                 false
    3752              :             }
    3753            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3754            0 :         })
    3755            0 :         .await
    3756            0 :         .expect("cannot drop self.state while on a &self method");
    3757              : 
    3758              :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3759            0 :         self.set_broken_no_wait(reason)
    3760            0 :     }
    3761              : 
    3762            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3763            0 :         let reason = reason.to_string();
    3764            0 :         self.state.send_modify(|current_state| {
    3765            0 :             match *current_state {
    3766              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3767            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3768              :                 }
    3769              :                 TenantState::Active => {
    3770            0 :                     if cfg!(feature = "testing") {
    3771            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3772            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3773              :                     } else {
    3774            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3775              :                     }
    3776              :                 }
    3777              :                 TenantState::Broken { .. } => {
    3778            0 :                     warn!("Tenant is already in Broken state");
    3779              :                 }
    3780              :                 // This is the only "expected" path, any other path is a bug.
    3781              :                 TenantState::Stopping { .. } => {
    3782            0 :                     warn!(
    3783            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3784              :                         reason
    3785              :                     );
    3786            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3787              :                 }
    3788              :            }
    3789            0 :         });
    3790            0 :     }
    3791              : 
    3792            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3793            0 :         self.state.subscribe()
    3794            0 :     }
    3795              : 
    3796              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3797              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3798            0 :     pub(crate) fn activate_now(&self) {
    3799            0 :         self.activate_now_sem.add_permits(1);
    3800            0 :     }
    3801              : 
    3802            0 :     pub(crate) async fn wait_to_become_active(
    3803            0 :         &self,
    3804            0 :         timeout: Duration,
    3805            0 :     ) -> Result<(), GetActiveTenantError> {
    3806            0 :         let mut receiver = self.state.subscribe();
    3807              :         loop {
    3808            0 :             let current_state = receiver.borrow_and_update().clone();
    3809            0 :             match current_state {
    3810              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3811              :                     // in these states, there's a chance that we can reach ::Active
    3812            0 :                     self.activate_now();
    3813            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3814            0 :                         Ok(r) => {
    3815            0 :                             r.map_err(
    3816              :                             |_e: tokio::sync::watch::error::RecvError|
    3817              :                                 // Tenant existed but was dropped: report it as non-existent
    3818            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3819            0 :                         )?
    3820              :                         }
    3821              :                         Err(TimeoutCancellableError::Cancelled) => {
    3822            0 :                             return Err(GetActiveTenantError::Cancelled);
    3823              :                         }
    3824              :                         Err(TimeoutCancellableError::Timeout) => {
    3825            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3826            0 :                                 latest_state: Some(self.current_state()),
    3827            0 :                                 wait_time: timeout,
    3828            0 :                             });
    3829              :                         }
    3830              :                     }
    3831              :                 }
    3832              :                 TenantState::Active => {
    3833            0 :                     return Ok(());
    3834              :                 }
    3835            0 :                 TenantState::Broken { reason, .. } => {
    3836              :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3837              :                     // it's logically a 500 to external API users (broken is always a bug).
    3838            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3839              :                 }
    3840              :                 TenantState::Stopping { .. } => {
    3841              :                     // There's no chance the tenant can transition back into ::Active
    3842            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3843              :                 }
    3844              :             }
    3845              :         }
    3846            0 :     }
    3847              : 
    3848            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3849            0 :         self.tenant_conf.load().location.attach_mode
    3850            0 :     }
    3851              : 
    3852              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3853              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3854              :     /// rare external API calls, like a reconciliation at startup.
    3855            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3856            0 :         let attached_tenant_conf = self.tenant_conf.load();
    3857              : 
    3858            0 :         let location_config_mode = match attached_tenant_conf.location.attach_mode {
    3859            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3860            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3861            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3862              :         };
    3863              : 
    3864            0 :         models::LocationConfig {
    3865            0 :             mode: location_config_mode,
    3866            0 :             generation: self.generation.into(),
    3867            0 :             secondary_conf: None,
    3868            0 :             shard_number: self.shard_identity.number.0,
    3869            0 :             shard_count: self.shard_identity.count.literal(),
    3870            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3871            0 :             tenant_conf: attached_tenant_conf.tenant_conf.clone(),
    3872            0 :         }
    3873            0 :     }
    3874              : 
    3875            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3876            0 :         &self.tenant_shard_id
    3877            0 :     }
    3878              : 
    3879            0 :     pub(crate) fn get_shard_identity(&self) -> ShardIdentity {
    3880            0 :         self.shard_identity
    3881            0 :     }
    3882              : 
    3883          119 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3884          119 :         self.shard_identity.stripe_size
    3885          119 :     }
    3886              : 
    3887            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3888            0 :         self.generation
    3889            0 :     }
    3890              : 
    3891              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3892              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3893              :     /// resetting this tenant to a valid state if we fail.
    3894            0 :     pub(crate) async fn split_prepare(
    3895            0 :         &self,
    3896            0 :         child_shards: &Vec<TenantShardId>,
    3897            0 :     ) -> anyhow::Result<()> {
    3898            0 :         let (timelines, offloaded) = {
    3899            0 :             let timelines = self.timelines.lock().unwrap();
    3900            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3901            0 :             (timelines.clone(), offloaded.clone())
    3902            0 :         };
    3903            0 :         let timelines_iter = timelines
    3904            0 :             .values()
    3905            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3906            0 :             .chain(
    3907            0 :                 offloaded
    3908            0 :                     .values()
    3909            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3910              :             );
    3911            0 :         for timeline in timelines_iter {
    3912              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3913              :             // to ensure that they do not start a split if currently in the process of doing these.
    3914              : 
    3915            0 :             let timeline_id = timeline.timeline_id();
    3916              : 
    3917            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3918              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3919              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3920              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3921            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3922            0 :                 timeline
    3923            0 :                     .remote_client
    3924            0 :                     .schedule_index_upload_for_file_changes()?;
    3925            0 :                 timeline.remote_client.wait_completion().await?;
    3926            0 :             }
    3927              : 
    3928            0 :             let remote_client = match timeline {
    3929            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3930            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3931            0 :                     let remote_client = self
    3932            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3933            0 :                     Arc::new(remote_client)
    3934              :                 }
    3935              :                 TimelineOrOffloadedArcRef::Importing(_) => {
    3936            0 :                     unreachable!("Importing timelines are not included in the iterator")
    3937              :                 }
    3938              :             };
    3939              : 
    3940              :             // Shut down the timeline's remote client: this means that the indices we write
    3941              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3942            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3943            0 :             remote_client.shutdown().await;
    3944              : 
    3945              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3946              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3947              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3948              :             // we use here really is the remotely persistent one).
    3949            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3950            0 :             let result = remote_client
    3951            0 :                 .download_index_file(&self.cancel)
    3952            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))
    3953            0 :                 .await?;
    3954            0 :             let index_part = match result {
    3955              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3956            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3957              :                 }
    3958            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3959              :             };
    3960              : 
    3961              :             // A shard split may not take place while a timeline import is on-going
    3962              :             // for the tenant. Timeline imports run as part of each tenant shard
    3963              :             // and rely on the sharding scheme to split the work among pageservers.
    3964              :             // If we were to split in the middle of this process, we would have to
    3965              :             // either ensure that it's driven to completion on the old shard set
    3966              :             // or transfer it to the new shard set. It's technically possible, but complex.
    3967            0 :             match index_part.import_pgdata {
    3968            0 :                 Some(ref import) if !import.is_done() => {
    3969            0 :                     anyhow::bail!(
    3970            0 :                         "Cannot split due to import with idempotency key: {:?}",
    3971            0 :                         import.idempotency_key()
    3972              :                     );
    3973              :                 }
    3974            0 :                 Some(_) | None => {
    3975            0 :                     // fallthrough
    3976            0 :                 }
    3977              :             }
    3978              : 
    3979            0 :             for child_shard in child_shards {
    3980            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3981            0 :                 upload_index_part(
    3982            0 :                     &self.remote_storage,
    3983            0 :                     child_shard,
    3984            0 :                     &timeline_id,
    3985            0 :                     self.generation,
    3986            0 :                     &index_part,
    3987            0 :                     &self.cancel,
    3988            0 :                 )
    3989            0 :                 .await?;
    3990              :             }
    3991              :         }
    3992              : 
    3993            0 :         let tenant_manifest = self.build_tenant_manifest();
    3994            0 :         for child_shard in child_shards {
    3995            0 :             tracing::info!(
    3996            0 :                 "Uploading tenant manifest for child {}",
    3997            0 :                 child_shard.to_index()
    3998              :             );
    3999            0 :             upload_tenant_manifest(
    4000            0 :                 &self.remote_storage,
    4001            0 :                 child_shard,
    4002            0 :                 self.generation,
    4003            0 :                 &tenant_manifest,
    4004            0 :                 &self.cancel,
    4005            0 :             )
    4006            0 :             .await?;
    4007              :         }
    4008              : 
    4009            0 :         Ok(())
    4010            0 :     }
    4011              : 
    4012            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    4013            0 :         let mut result = TopTenantShardItem {
    4014            0 :             id: self.tenant_shard_id,
    4015            0 :             resident_size: 0,
    4016            0 :             physical_size: 0,
    4017            0 :             max_logical_size: 0,
    4018            0 :             max_logical_size_per_shard: 0,
    4019            0 :         };
    4020              : 
    4021            0 :         for timeline in self.timelines.lock().unwrap().values() {
    4022            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    4023            0 : 
    4024            0 :             result.physical_size += timeline
    4025            0 :                 .remote_client
    4026            0 :                 .metrics
    4027            0 :                 .remote_physical_size_gauge
    4028            0 :                 .get();
    4029            0 :             result.max_logical_size = std::cmp::max(
    4030            0 :                 result.max_logical_size,
    4031            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    4032            0 :             );
    4033            0 :         }
    4034              : 
    4035            0 :         result.max_logical_size_per_shard = result
    4036            0 :             .max_logical_size
    4037            0 :             .div_ceil(self.tenant_shard_id.shard_count.count() as u64);
    4038              : 
    4039            0 :         result
    4040            0 :     }
    4041              : }
    4042              : 
    4043              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    4044              : /// perform a topological sort, so that the parent of each timeline comes
    4045              : /// before the children.
    4046              : /// E extracts the ancestor from T
    4047              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    4048          118 : fn tree_sort_timelines<T, E>(
    4049          118 :     timelines: HashMap<TimelineId, T>,
    4050          118 :     extractor: E,
    4051          118 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    4052          118 : where
    4053          118 :     E: Fn(&T) -> Option<TimelineId>,
    4054              : {
    4055          118 :     let mut result = Vec::with_capacity(timelines.len());
    4056              : 
    4057          118 :     let mut now = Vec::with_capacity(timelines.len());
    4058              :     // (ancestor, children)
    4059          118 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    4060          118 :         HashMap::with_capacity(timelines.len());
    4061              : 
    4062          121 :     for (timeline_id, value) in timelines {
    4063            3 :         if let Some(ancestor_id) = extractor(&value) {
    4064            1 :             let children = later.entry(ancestor_id).or_default();
    4065            1 :             children.push((timeline_id, value));
    4066            2 :         } else {
    4067            2 :             now.push((timeline_id, value));
    4068            2 :         }
    4069              :     }
    4070              : 
    4071          121 :     while let Some((timeline_id, metadata)) = now.pop() {
    4072            3 :         result.push((timeline_id, metadata));
    4073              :         // All children of this can be loaded now
    4074            3 :         if let Some(mut children) = later.remove(&timeline_id) {
    4075            1 :             now.append(&mut children);
    4076            2 :         }
    4077              :     }
    4078              : 
    4079              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    4080          118 :     if !later.is_empty() {
    4081            0 :         for (missing_id, orphan_ids) in later {
    4082            0 :             for (orphan_id, _) in orphan_ids {
    4083            0 :                 error!(
    4084            0 :                     "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
    4085              :                 );
    4086              :             }
    4087              :         }
    4088            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    4089          118 :     }
    4090              : 
    4091          118 :     Ok(result)
    4092          118 : }
    4093              : 
    4094              : impl TenantShard {
    4095            0 :     pub fn tenant_specific_overrides(&self) -> pageserver_api::models::TenantConfig {
    4096            0 :         self.tenant_conf.load().tenant_conf.clone()
    4097            0 :     }
    4098              : 
    4099            0 :     pub fn effective_config(&self) -> pageserver_api::config::TenantConfigToml {
    4100            0 :         self.tenant_specific_overrides()
    4101            0 :             .merge(self.conf.default_tenant_conf.clone())
    4102            0 :     }
    4103              : 
    4104            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    4105            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4106            0 :         tenant_conf
    4107            0 :             .checkpoint_distance
    4108            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    4109            0 :     }
    4110              : 
    4111            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    4112            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4113            0 :         tenant_conf
    4114            0 :             .checkpoint_timeout
    4115            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    4116            0 :     }
    4117              : 
    4118            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    4119            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4120            0 :         tenant_conf
    4121            0 :             .compaction_target_size
    4122            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    4123            0 :     }
    4124              : 
    4125            0 :     pub fn get_compaction_period(&self) -> Duration {
    4126            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4127            0 :         tenant_conf
    4128            0 :             .compaction_period
    4129            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    4130            0 :     }
    4131              : 
    4132            0 :     pub fn get_compaction_threshold(&self) -> usize {
    4133            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4134            0 :         tenant_conf
    4135            0 :             .compaction_threshold
    4136            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    4137            0 :     }
    4138              : 
    4139            0 :     pub fn get_rel_size_v2_enabled(&self) -> bool {
    4140            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4141            0 :         tenant_conf
    4142            0 :             .rel_size_v2_enabled
    4143            0 :             .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
    4144            0 :     }
    4145              : 
    4146            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    4147            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4148            0 :         tenant_conf
    4149            0 :             .compaction_upper_limit
    4150            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    4151            0 :     }
    4152              : 
    4153            0 :     pub fn get_compaction_l0_first(&self) -> bool {
    4154            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4155            0 :         tenant_conf
    4156            0 :             .compaction_l0_first
    4157            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
    4158            0 :     }
    4159              : 
    4160          120 :     pub fn get_gc_horizon(&self) -> u64 {
    4161          120 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4162          120 :         tenant_conf
    4163          120 :             .gc_horizon
    4164          120 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    4165          120 :     }
    4166              : 
    4167            0 :     pub fn get_gc_period(&self) -> Duration {
    4168            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4169            0 :         tenant_conf
    4170            0 :             .gc_period
    4171            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    4172            0 :     }
    4173              : 
    4174            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    4175            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4176            0 :         tenant_conf
    4177            0 :             .image_creation_threshold
    4178            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    4179            0 :     }
    4180              : 
    4181            2 :     pub fn get_pitr_interval(&self) -> Duration {
    4182            2 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4183            2 :         tenant_conf
    4184            2 :             .pitr_interval
    4185            2 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    4186            2 :     }
    4187              : 
    4188            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    4189            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4190            0 :         tenant_conf
    4191            0 :             .min_resident_size_override
    4192            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    4193            0 :     }
    4194              : 
    4195            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    4196            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4197            0 :         let heatmap_period = tenant_conf
    4198            0 :             .heatmap_period
    4199            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    4200            0 :         if heatmap_period.is_zero() {
    4201            0 :             None
    4202              :         } else {
    4203            0 :             Some(heatmap_period)
    4204              :         }
    4205            0 :     }
    4206              : 
    4207            0 :     pub fn get_lsn_lease_length(&self) -> Duration {
    4208            0 :         Self::get_lsn_lease_length_impl(self.conf, &self.tenant_conf.load().tenant_conf)
    4209            0 :     }
    4210              : 
    4211          118 :     pub fn get_lsn_lease_length_impl(
    4212          118 :         conf: &'static PageServerConf,
    4213          118 :         tenant_conf: &pageserver_api::models::TenantConfig,
    4214          118 :     ) -> Duration {
    4215          118 :         tenant_conf
    4216          118 :             .lsn_lease_length
    4217          118 :             .unwrap_or(conf.default_tenant_conf.lsn_lease_length)
    4218          118 :     }
    4219              : 
    4220            0 :     pub fn get_timeline_offloading_enabled(&self) -> bool {
    4221            0 :         if self.conf.timeline_offloading {
    4222            0 :             return true;
    4223            0 :         }
    4224            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4225            0 :         tenant_conf
    4226            0 :             .timeline_offloading
    4227            0 :             .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
    4228            0 :     }
    4229              : 
    4230              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    4231          119 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4232              :         // Collect the offloaded timelines, and sort them for deterministic output.
    4233          119 :         let offloaded_timelines = self
    4234          119 :             .timelines_offloaded
    4235          119 :             .lock()
    4236          119 :             .unwrap()
    4237          119 :             .values()
    4238          119 :             .map(|tli| tli.manifest())
    4239          119 :             .sorted_by_key(|m| m.timeline_id)
    4240          119 :             .collect_vec();
    4241              : 
    4242          119 :         TenantManifest {
    4243          119 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4244          119 :             stripe_size: Some(self.get_shard_stripe_size()),
    4245          119 :             offloaded_timelines,
    4246          119 :         }
    4247          119 :     }
    4248              : 
    4249            1 :     pub fn update_tenant_config<
    4250            1 :         F: Fn(
    4251            1 :             pageserver_api::models::TenantConfig,
    4252            1 :         ) -> anyhow::Result<pageserver_api::models::TenantConfig>,
    4253            1 :     >(
    4254            1 :         &self,
    4255            1 :         update: F,
    4256            1 :     ) -> anyhow::Result<pageserver_api::models::TenantConfig> {
    4257              :         // Use read-copy-update in order to avoid overwriting the location config
    4258              :         // state if this races with [`TenantShard::set_new_location_config`]. Note that
    4259              :         // this race is not possible if both request types come from the storage
    4260              :         // controller (as they should!) because an exclusive op lock is required
    4261              :         // on the storage controller side.
    4262              : 
    4263            1 :         self.tenant_conf
    4264            1 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    4265            1 :                 Ok(Arc::new(AttachedTenantConf {
    4266            1 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    4267            1 :                     location: attached_conf.location,
    4268            1 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    4269              :                 }))
    4270            1 :             })?;
    4271              : 
    4272            1 :         let updated = self.tenant_conf.load();
    4273              : 
    4274            1 :         self.tenant_conf_updated(&updated.tenant_conf);
    4275              :         // Don't hold self.timelines.lock() during the notifies.
    4276              :         // There's no risk of deadlock right now, but there could be if we consolidate
    4277              :         // mutexes in struct Timeline in the future.
    4278            1 :         let timelines = self.list_timelines();
    4279            1 :         for timeline in timelines {
    4280            0 :             timeline.tenant_conf_updated(&updated);
    4281            0 :         }
    4282              : 
    4283            1 :         Ok(updated.tenant_conf.clone())
    4284            1 :     }
    4285              : 
    4286            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    4287            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    4288              : 
    4289            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4290              : 
    4291            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4292              :         // Don't hold self.timelines.lock() during the notifies.
    4293              :         // There's no risk of deadlock right now, but there could be if we consolidate
    4294              :         // mutexes in struct Timeline in the future.
    4295            0 :         let timelines = self.list_timelines();
    4296            0 :         for timeline in timelines {
    4297            0 :             timeline.tenant_conf_updated(&new_conf);
    4298            0 :         }
    4299            0 :     }
    4300              : 
    4301          119 :     fn get_pagestream_throttle_config(
    4302          119 :         psconf: &'static PageServerConf,
    4303          119 :         overrides: &pageserver_api::models::TenantConfig,
    4304          119 :     ) -> throttle::Config {
    4305          119 :         overrides
    4306          119 :             .timeline_get_throttle
    4307          119 :             .clone()
    4308          119 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4309          119 :     }
    4310              : 
    4311            1 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &pageserver_api::models::TenantConfig) {
    4312            1 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4313            1 :         self.pagestream_throttle.reconfigure(conf)
    4314            1 :     }
    4315              : 
    4316              :     /// Helper function to create a new Timeline struct.
    4317              :     ///
    4318              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4319              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4320              :     /// map.
    4321              :     ///
    4322              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4323              :     /// and we might not have the ancestor present anymore which is fine for to be
    4324              :     /// deleted timelines.
    4325              :     #[allow(clippy::too_many_arguments)]
    4326          234 :     fn create_timeline_struct(
    4327          234 :         &self,
    4328          234 :         new_timeline_id: TimelineId,
    4329          234 :         new_metadata: &TimelineMetadata,
    4330          234 :         previous_heatmap: Option<PreviousHeatmap>,
    4331          234 :         ancestor: Option<Arc<Timeline>>,
    4332          234 :         resources: TimelineResources,
    4333          234 :         cause: CreateTimelineCause,
    4334          234 :         create_idempotency: CreateTimelineIdempotency,
    4335          234 :         gc_compaction_state: Option<GcCompactionState>,
    4336          234 :         rel_size_v2_status: Option<RelSizeMigration>,
    4337          234 :         ctx: &RequestContext,
    4338          234 :     ) -> anyhow::Result<(Arc<Timeline>, RequestContext)> {
    4339          234 :         let state = match cause {
    4340              :             CreateTimelineCause::Load => {
    4341          234 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4342          234 :                 anyhow::ensure!(
    4343          234 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4344            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4345              :                 );
    4346          234 :                 TimelineState::Loading
    4347              :             }
    4348            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4349              :         };
    4350              : 
    4351          234 :         let pg_version = new_metadata.pg_version();
    4352              : 
    4353          234 :         let timeline = Timeline::new(
    4354          234 :             self.conf,
    4355          234 :             Arc::clone(&self.tenant_conf),
    4356          234 :             new_metadata,
    4357          234 :             previous_heatmap,
    4358          234 :             ancestor,
    4359          234 :             new_timeline_id,
    4360          234 :             self.tenant_shard_id,
    4361          234 :             self.generation,
    4362          234 :             self.shard_identity,
    4363          234 :             self.walredo_mgr.clone(),
    4364          234 :             resources,
    4365          234 :             pg_version,
    4366          234 :             state,
    4367          234 :             self.attach_wal_lag_cooldown.clone(),
    4368          234 :             create_idempotency,
    4369          234 :             gc_compaction_state,
    4370          234 :             rel_size_v2_status,
    4371          234 :             self.cancel.child_token(),
    4372              :         );
    4373              : 
    4374          234 :         let timeline_ctx = RequestContextBuilder::from(ctx)
    4375          234 :             .scope(context::Scope::new_timeline(&timeline))
    4376          234 :             .detached_child();
    4377              : 
    4378          234 :         Ok((timeline, timeline_ctx))
    4379          234 :     }
    4380              : 
    4381              :     /// [`TenantShard::shutdown`] must be called before dropping the returned [`TenantShard`] object
    4382              :     /// to ensure proper cleanup of background tasks and metrics.
    4383              :     //
    4384              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4385              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4386              :     #[allow(clippy::too_many_arguments)]
    4387          118 :     fn new(
    4388          118 :         state: TenantState,
    4389          118 :         conf: &'static PageServerConf,
    4390          118 :         attached_conf: AttachedTenantConf,
    4391          118 :         shard_identity: ShardIdentity,
    4392          118 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4393          118 :         tenant_shard_id: TenantShardId,
    4394          118 :         remote_storage: GenericRemoteStorage,
    4395          118 :         deletion_queue_client: DeletionQueueClient,
    4396          118 :         l0_flush_global_state: L0FlushGlobalState,
    4397          118 :         basebackup_cache: Arc<BasebackupCache>,
    4398          118 :         feature_resolver: FeatureResolver,
    4399          118 :     ) -> TenantShard {
    4400          118 :         assert!(!attached_conf.location.generation.is_none());
    4401              : 
    4402          118 :         let (state, mut rx) = watch::channel(state);
    4403              : 
    4404          118 :         tokio::spawn(async move {
    4405              :             // reflect tenant state in metrics:
    4406              :             // - global per tenant state: TENANT_STATE_METRIC
    4407              :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4408              :             //
    4409              :             // set of broken tenants should not have zero counts so that it remains accessible for
    4410              :             // alerting.
    4411              : 
    4412          118 :             let tid = tenant_shard_id.to_string();
    4413          118 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4414          118 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4415              : 
    4416          236 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4417          236 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4418          236 :             }
    4419              : 
    4420          118 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4421              : 
    4422          118 :             let is_broken = tuple.1;
    4423          118 :             let mut counted_broken = if is_broken {
    4424              :                 // add the id to the set right away, there should not be any updates on the channel
    4425              :                 // after before tenant is removed, if ever
    4426            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4427            0 :                 true
    4428              :             } else {
    4429          118 :                 false
    4430              :             };
    4431              : 
    4432              :             loop {
    4433          236 :                 let labels = &tuple.0;
    4434          236 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4435          236 :                 current.inc();
    4436              : 
    4437          236 :                 if rx.changed().await.is_err() {
    4438              :                     // tenant has been dropped
    4439            7 :                     current.dec();
    4440            7 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4441            7 :                     break;
    4442          118 :                 }
    4443              : 
    4444          118 :                 current.dec();
    4445          118 :                 tuple = inspect_state(&rx.borrow_and_update());
    4446              : 
    4447          118 :                 let is_broken = tuple.1;
    4448          118 :                 if is_broken && !counted_broken {
    4449            0 :                     counted_broken = true;
    4450            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4451            0 :                     // access
    4452            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4453          118 :                 }
    4454              :             }
    4455            7 :         });
    4456              : 
    4457          118 :         TenantShard {
    4458          118 :             tenant_shard_id,
    4459          118 :             shard_identity,
    4460          118 :             generation: attached_conf.location.generation,
    4461          118 :             conf,
    4462          118 :             // using now here is good enough approximation to catch tenants with really long
    4463          118 :             // activation times.
    4464          118 :             constructed_at: Instant::now(),
    4465          118 :             timelines: Mutex::new(HashMap::new()),
    4466          118 :             timelines_creating: Mutex::new(HashSet::new()),
    4467          118 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4468          118 :             timelines_importing: Mutex::new(HashMap::new()),
    4469          118 :             remote_tenant_manifest: Default::default(),
    4470          118 :             gc_cs: tokio::sync::Mutex::new(()),
    4471          118 :             walredo_mgr,
    4472          118 :             remote_storage,
    4473          118 :             deletion_queue_client,
    4474          118 :             state,
    4475          118 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4476          118 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4477          118 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4478          118 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4479          118 :                 format!("compaction-{tenant_shard_id}"),
    4480          118 :                 5,
    4481          118 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4482          118 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4483          118 :                 // use an extremely long backoff.
    4484          118 :                 Some(Duration::from_secs(3600 * 24)),
    4485          118 :             )),
    4486          118 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4487          118 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4488          118 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4489          118 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4490          118 :             cancel: CancellationToken::default(),
    4491          118 :             gate: Gate::default(),
    4492          118 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4493          118 :                 TenantShard::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4494          118 :             )),
    4495          118 :             pagestream_throttle_metrics: Arc::new(
    4496          118 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4497          118 :             ),
    4498          118 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4499          118 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4500          118 :             gc_block: Default::default(),
    4501          118 :             l0_flush_global_state,
    4502          118 :             basebackup_cache,
    4503          118 :             feature_resolver: Arc::new(TenantFeatureResolver::new(
    4504          118 :                 feature_resolver,
    4505          118 :                 tenant_shard_id.tenant_id,
    4506          118 :             )),
    4507          118 :         }
    4508          118 :     }
    4509              : 
    4510              :     /// Locate and load config
    4511            0 :     pub(super) fn load_tenant_config(
    4512            0 :         conf: &'static PageServerConf,
    4513            0 :         tenant_shard_id: &TenantShardId,
    4514            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4515            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4516              : 
    4517            0 :         info!("loading tenant configuration from {config_path}");
    4518              : 
    4519              :         // load and parse file
    4520            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4521            0 :             match e.kind() {
    4522              :                 std::io::ErrorKind::NotFound => {
    4523              :                     // The config should almost always exist for a tenant directory:
    4524              :                     //  - When attaching a tenant, the config is the first thing we write
    4525              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4526              :                     //    before deleting contents.
    4527              :                     //
    4528              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4529              :                     // between creating directory and writing config.  Callers should handle that as if the
    4530              :                     // directory didn't exist.
    4531              : 
    4532            0 :                     LoadConfigError::NotFound(config_path)
    4533              :                 }
    4534              :                 _ => {
    4535              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4536              :                     // that we cannot cleanly recover
    4537            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4538              :                 }
    4539              :             }
    4540            0 :         })?;
    4541              : 
    4542            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4543            0 :     }
    4544              : 
    4545              :     /// Stores a tenant location config to disk.
    4546              :     ///
    4547              :     /// NB: make sure to call `ShardIdentity::assert_equal` before persisting a new config, to avoid
    4548              :     /// changes to shard parameters that may result in data corruption.
    4549              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4550              :     pub(super) async fn persist_tenant_config(
    4551              :         conf: &'static PageServerConf,
    4552              :         tenant_shard_id: &TenantShardId,
    4553              :         location_conf: &LocationConf,
    4554              :     ) -> std::io::Result<()> {
    4555              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4556              : 
    4557              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4558              :     }
    4559              : 
    4560              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4561              :     pub(super) async fn persist_tenant_config_at(
    4562              :         tenant_shard_id: &TenantShardId,
    4563              :         config_path: &Utf8Path,
    4564              :         location_conf: &LocationConf,
    4565              :     ) -> std::io::Result<()> {
    4566              :         debug!("persisting tenantconf to {config_path}");
    4567              : 
    4568              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4569              : #  It is read in case of pageserver restart.
    4570              : "#
    4571              :         .to_string();
    4572              : 
    4573            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4574            0 :             Err(std::io::Error::other("tenant-config-before-write"))
    4575            0 :         });
    4576              : 
    4577              :         // Convert the config to a toml file.
    4578              :         conf_content +=
    4579              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4580              : 
    4581              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4582              : 
    4583              :         let conf_content = conf_content.into_bytes();
    4584              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4585              :     }
    4586              : 
    4587              :     //
    4588              :     // How garbage collection works:
    4589              :     //
    4590              :     //                    +--bar------------->
    4591              :     //                   /
    4592              :     //             +----+-----foo---------------->
    4593              :     //            /
    4594              :     // ----main--+-------------------------->
    4595              :     //                \
    4596              :     //                 +-----baz-------->
    4597              :     //
    4598              :     //
    4599              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4600              :     //    `gc_infos` are being refreshed
    4601              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4602              :     //    all the points where other timelines have been branched off.
    4603              :     //    We will refrain from removing page versions at those LSNs.
    4604              :     // 3. For each timeline, scan all layer files on the timeline.
    4605              :     //    Remove all files for which a newer file exists and which
    4606              :     //    don't cover any branch point LSNs.
    4607              :     //
    4608              :     // TODO:
    4609              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4610              :     //   don't need to keep that in the parent anymore. But currently
    4611              :     //   we do.
    4612          377 :     async fn gc_iteration_internal(
    4613          377 :         &self,
    4614          377 :         target_timeline_id: Option<TimelineId>,
    4615          377 :         horizon: u64,
    4616          377 :         pitr: Duration,
    4617          377 :         cancel: &CancellationToken,
    4618          377 :         ctx: &RequestContext,
    4619          377 :     ) -> Result<GcResult, GcError> {
    4620          377 :         let mut totals: GcResult = Default::default();
    4621          377 :         let now = Instant::now();
    4622              : 
    4623          377 :         let gc_timelines = self
    4624          377 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4625          377 :             .await?;
    4626              : 
    4627          377 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4628              : 
    4629              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4630          377 :         if !gc_timelines.is_empty() {
    4631          377 :             info!("{} timelines need GC", gc_timelines.len());
    4632              :         } else {
    4633            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4634              :         }
    4635              : 
    4636              :         // Perform GC for each timeline.
    4637              :         //
    4638              :         // Note that we don't hold the `TenantShard::gc_cs` lock here because we don't want to delay the
    4639              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4640              :         // with branch creation.
    4641              :         //
    4642              :         // See comments in [`TenantShard::branch_timeline`] for more information about why branch
    4643              :         // creation task can run concurrently with timeline's GC iteration.
    4644          754 :         for timeline in gc_timelines {
    4645          377 :             if cancel.is_cancelled() {
    4646              :                 // We were requested to shut down. Stop and return with the progress we
    4647              :                 // made.
    4648            0 :                 break;
    4649          377 :             }
    4650          377 :             let result = match timeline.gc().await {
    4651              :                 Err(GcError::TimelineCancelled) => {
    4652            0 :                     if target_timeline_id.is_some() {
    4653              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4654            0 :                         return Err(GcError::TimelineCancelled);
    4655              :                     } else {
    4656              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4657              :                         // skip past this and proceed to try GC on other timelines.
    4658            0 :                         continue;
    4659              :                     }
    4660              :                 }
    4661          377 :                 r => r?,
    4662              :             };
    4663          377 :             totals += result;
    4664              :         }
    4665              : 
    4666          377 :         totals.elapsed = now.elapsed();
    4667          377 :         Ok(totals)
    4668          377 :     }
    4669              : 
    4670              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4671              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4672              :     /// [`TenantShard::get_gc_horizon`].
    4673              :     ///
    4674              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4675            2 :     pub(crate) async fn refresh_gc_info(
    4676            2 :         &self,
    4677            2 :         cancel: &CancellationToken,
    4678            2 :         ctx: &RequestContext,
    4679            2 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4680              :         // since this method can now be called at different rates than the configured gc loop, it
    4681              :         // might be that these configuration values get applied faster than what it was previously,
    4682              :         // since these were only read from the gc task.
    4683            2 :         let horizon = self.get_gc_horizon();
    4684            2 :         let pitr = self.get_pitr_interval();
    4685              : 
    4686              :         // refresh all timelines
    4687            2 :         let target_timeline_id = None;
    4688              : 
    4689            2 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4690            2 :             .await
    4691            2 :     }
    4692              : 
    4693              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4694              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4695              :     ///
    4696              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4697          118 :     fn initialize_gc_info(
    4698          118 :         &self,
    4699          118 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4700          118 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4701          118 :         restrict_to_timeline: Option<TimelineId>,
    4702          118 :     ) {
    4703          118 :         if restrict_to_timeline.is_none() {
    4704              :             // This function must be called before activation: after activation timeline create/delete operations
    4705              :             // might happen, and this function is not safe to run concurrently with those.
    4706          118 :             assert!(!self.is_active());
    4707            0 :         }
    4708              : 
    4709              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4710              :         // the branch point where it was created.
    4711          118 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4712          118 :             BTreeMap::new();
    4713          118 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4714            3 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4715            1 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4716            1 :                 ancestor_children.push((
    4717            1 :                     timeline_entry.get_ancestor_lsn(),
    4718            1 :                     *timeline_id,
    4719            1 :                     MaybeOffloaded::No,
    4720            1 :                 ));
    4721            2 :             }
    4722            3 :         });
    4723          118 :         timelines_offloaded
    4724          118 :             .iter()
    4725          118 :             .for_each(|(timeline_id, timeline_entry)| {
    4726            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4727            0 :                     return;
    4728              :                 };
    4729            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4730            0 :                     return;
    4731              :                 };
    4732            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4733            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4734            0 :             });
    4735              : 
    4736              :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4737          118 :         let horizon = self.get_gc_horizon();
    4738              : 
    4739              :         // Populate each timeline's GcInfo with information about its child branches
    4740          118 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4741            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4742              :         } else {
    4743          118 :             itertools::Either::Right(timelines.values())
    4744              :         };
    4745          121 :         for timeline in timelines_to_write {
    4746            3 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4747            3 :                 .remove(&timeline.timeline_id)
    4748            3 :                 .unwrap_or_default();
    4749              : 
    4750            3 :             branchpoints.sort_by_key(|b| b.0);
    4751              : 
    4752            3 :             let mut target = timeline.gc_info.write().unwrap();
    4753              : 
    4754            3 :             target.retain_lsns = branchpoints;
    4755              : 
    4756            3 :             let space_cutoff = timeline
    4757            3 :                 .get_last_record_lsn()
    4758            3 :                 .checked_sub(horizon)
    4759            3 :                 .unwrap_or(Lsn(0));
    4760              : 
    4761            3 :             target.cutoffs = GcCutoffs {
    4762            3 :                 space: space_cutoff,
    4763            3 :                 time: None,
    4764            3 :             };
    4765              :         }
    4766          118 :     }
    4767              : 
    4768          379 :     async fn refresh_gc_info_internal(
    4769          379 :         &self,
    4770          379 :         target_timeline_id: Option<TimelineId>,
    4771          379 :         horizon: u64,
    4772          379 :         pitr: Duration,
    4773          379 :         cancel: &CancellationToken,
    4774          379 :         ctx: &RequestContext,
    4775          379 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4776              :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4777              :         // currently visible timelines.
    4778          379 :         let timelines = self
    4779          379 :             .timelines
    4780          379 :             .lock()
    4781          379 :             .unwrap()
    4782          379 :             .values()
    4783         1663 :             .filter(|tl| match target_timeline_id.as_ref() {
    4784         1655 :                 Some(target) => &tl.timeline_id == target,
    4785            8 :                 None => true,
    4786         1663 :             })
    4787          379 :             .cloned()
    4788          379 :             .collect::<Vec<_>>();
    4789              : 
    4790          379 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4791              :             // We were to act on a particular timeline and it wasn't found
    4792            0 :             return Err(GcError::TimelineNotFound);
    4793          379 :         }
    4794              : 
    4795          379 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4796          379 :             HashMap::with_capacity(timelines.len());
    4797              : 
    4798              :         // Ensures all timelines use the same start time when computing the time cutoff.
    4799          379 :         let now_ts_for_pitr_calc = SystemTime::now();
    4800          385 :         for timeline in timelines.iter() {
    4801          385 :             let ctx = &ctx.with_scope_timeline(timeline);
    4802          385 :             let cutoff = timeline
    4803          385 :                 .get_last_record_lsn()
    4804          385 :                 .checked_sub(horizon)
    4805          385 :                 .unwrap_or(Lsn(0));
    4806              : 
    4807          385 :             let cutoffs = timeline
    4808          385 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4809          385 :                 .await?;
    4810          385 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4811          385 :             assert!(old.is_none());
    4812              :         }
    4813              : 
    4814          379 :         if !self.is_active() || self.cancel.is_cancelled() {
    4815            0 :             return Err(GcError::TenantCancelled);
    4816          379 :         }
    4817              : 
    4818              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4819              :         // because that will stall branch creation.
    4820          379 :         let gc_cs = self.gc_cs.lock().await;
    4821              : 
    4822              :         // Ok, we now know all the branch points.
    4823              :         // Update the GC information for each timeline.
    4824          379 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4825          764 :         for timeline in timelines {
    4826              :             // We filtered the timeline list above
    4827          385 :             if let Some(target_timeline_id) = target_timeline_id {
    4828          377 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4829            8 :             }
    4830              : 
    4831              :             {
    4832          385 :                 let mut target = timeline.gc_info.write().unwrap();
    4833              : 
    4834              :                 // Cull any expired leases
    4835          385 :                 let now = SystemTime::now();
    4836          385 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4837              : 
    4838          385 :                 timeline
    4839          385 :                     .metrics
    4840          385 :                     .valid_lsn_lease_count_gauge
    4841          385 :                     .set(target.leases.len() as u64);
    4842              : 
    4843              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4844          385 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4845           56 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4846            6 :                         target.within_ancestor_pitr =
    4847            6 :                             Some(timeline.get_ancestor_lsn()) >= ancestor_gc_cutoffs.time;
    4848           50 :                     }
    4849          329 :                 }
    4850              : 
    4851              :                 // Update metrics that depend on GC state
    4852          385 :                 timeline
    4853          385 :                     .metrics
    4854          385 :                     .archival_size
    4855          385 :                     .set(if target.within_ancestor_pitr {
    4856            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4857              :                     } else {
    4858          385 :                         0
    4859              :                     });
    4860          385 :                 if let Some(time_cutoff) = target.cutoffs.time {
    4861          319 :                     timeline.metrics.pitr_history_size.set(
    4862          319 :                         timeline
    4863          319 :                             .get_last_record_lsn()
    4864          319 :                             .checked_sub(time_cutoff)
    4865          319 :                             .unwrap_or_default()
    4866          319 :                             .0,
    4867          319 :                     );
    4868          319 :                 }
    4869              : 
    4870              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4871              :                 // - this timeline was created while we were finding cutoffs
    4872              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4873          385 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4874          385 :                     let original_cutoffs = target.cutoffs.clone();
    4875              :                     // GC cutoffs should never go back
    4876          385 :                     target.cutoffs = GcCutoffs {
    4877          385 :                         space: cutoffs.space.max(original_cutoffs.space),
    4878          385 :                         time: cutoffs.time.max(original_cutoffs.time),
    4879          385 :                     }
    4880            0 :                 }
    4881              :             }
    4882              : 
    4883          385 :             gc_timelines.push(timeline);
    4884              :         }
    4885          379 :         drop(gc_cs);
    4886          379 :         Ok(gc_timelines)
    4887          379 :     }
    4888              : 
    4889              :     /// A substitute for `branch_timeline` for use in unit tests.
    4890              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4891              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4892              :     /// timeline background tasks are launched, except the flush loop.
    4893              :     #[cfg(test)]
    4894          119 :     async fn branch_timeline_test(
    4895          119 :         self: &Arc<Self>,
    4896          119 :         src_timeline: &Arc<Timeline>,
    4897          119 :         dst_id: TimelineId,
    4898          119 :         ancestor_lsn: Option<Lsn>,
    4899          119 :         ctx: &RequestContext,
    4900          119 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4901          119 :         let tl = self
    4902          119 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4903          119 :             .await?
    4904          117 :             .into_timeline_for_test();
    4905          117 :         tl.set_state(TimelineState::Active);
    4906          117 :         Ok(tl)
    4907          119 :     }
    4908              : 
    4909              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4910              :     #[cfg(test)]
    4911              :     #[allow(clippy::too_many_arguments)]
    4912            6 :     pub async fn branch_timeline_test_with_layers(
    4913            6 :         self: &Arc<Self>,
    4914            6 :         src_timeline: &Arc<Timeline>,
    4915            6 :         dst_id: TimelineId,
    4916            6 :         ancestor_lsn: Option<Lsn>,
    4917            6 :         ctx: &RequestContext,
    4918            6 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4919            6 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4920            6 :         end_lsn: Lsn,
    4921            6 :     ) -> anyhow::Result<Arc<Timeline>> {
    4922              :         use checks::check_valid_layermap;
    4923              :         use itertools::Itertools;
    4924              : 
    4925            6 :         let tline = self
    4926            6 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4927            6 :             .await?;
    4928            6 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4929            6 :             ancestor_lsn
    4930              :         } else {
    4931            0 :             tline.get_last_record_lsn()
    4932              :         };
    4933            6 :         assert!(end_lsn >= ancestor_lsn);
    4934            6 :         tline.force_advance_lsn(end_lsn);
    4935            9 :         for deltas in delta_layer_desc {
    4936            3 :             tline
    4937            3 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4938            3 :                 .await?;
    4939              :         }
    4940            8 :         for (lsn, images) in image_layer_desc {
    4941            2 :             tline
    4942            2 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4943            2 :                 .await?;
    4944              :         }
    4945            6 :         let layer_names = tline
    4946            6 :             .layers
    4947            6 :             .read(LayerManagerLockHolder::Testing)
    4948            6 :             .await
    4949            6 :             .layer_map()
    4950            6 :             .unwrap()
    4951            6 :             .iter_historic_layers()
    4952            6 :             .map(|layer| layer.layer_name())
    4953            6 :             .collect_vec();
    4954            6 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4955            0 :             bail!("invalid layermap: {err}");
    4956            6 :         }
    4957            6 :         Ok(tline)
    4958            6 :     }
    4959              : 
    4960              :     /// Branch an existing timeline.
    4961            0 :     async fn branch_timeline(
    4962            0 :         self: &Arc<Self>,
    4963            0 :         src_timeline: &Arc<Timeline>,
    4964            0 :         dst_id: TimelineId,
    4965            0 :         start_lsn: Option<Lsn>,
    4966            0 :         ctx: &RequestContext,
    4967            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4968            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4969            0 :             .await
    4970            0 :     }
    4971              : 
    4972          119 :     async fn branch_timeline_impl(
    4973          119 :         self: &Arc<Self>,
    4974          119 :         src_timeline: &Arc<Timeline>,
    4975          119 :         dst_id: TimelineId,
    4976          119 :         start_lsn: Option<Lsn>,
    4977          119 :         ctx: &RequestContext,
    4978          119 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4979          119 :         let src_id = src_timeline.timeline_id;
    4980              : 
    4981              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4982              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4983              :         // valid while we are creating the branch.
    4984          119 :         let _gc_cs = self.gc_cs.lock().await;
    4985              : 
    4986              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4987          119 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4988            1 :             let lsn = src_timeline.get_last_record_lsn();
    4989            1 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4990            1 :             lsn
    4991            1 :         });
    4992              : 
    4993              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4994          119 :         let timeline_create_guard = match self
    4995          119 :             .start_creating_timeline(
    4996          119 :                 dst_id,
    4997          119 :                 CreateTimelineIdempotency::Branch {
    4998          119 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4999          119 :                     ancestor_start_lsn: start_lsn,
    5000          119 :                 },
    5001          119 :             )
    5002          119 :             .await?
    5003              :         {
    5004          119 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5005            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5006            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5007              :             }
    5008              :         };
    5009              : 
    5010              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    5011              :         // horizon on the source timeline
    5012              :         //
    5013              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    5014              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    5015              :         // planned GC cutoff in 'gc_info' is normally larger than
    5016              :         // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
    5017              :         // changed the GC settings for the tenant to make the PITR window
    5018              :         // larger, but some of the data was already removed by an earlier GC
    5019              :         // iteration.
    5020              : 
    5021              :         // check against last actual 'latest_gc_cutoff' first
    5022          119 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    5023              :         {
    5024          119 :             let gc_info = src_timeline.gc_info.read().unwrap();
    5025          119 :             let planned_cutoff = gc_info.min_cutoff();
    5026          119 :             if gc_info.lsn_covered_by_lease(start_lsn) {
    5027            0 :                 tracing::info!(
    5028            0 :                     "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
    5029            0 :                     *applied_gc_cutoff_lsn
    5030              :                 );
    5031              :             } else {
    5032          119 :                 src_timeline
    5033          119 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    5034          119 :                     .context(format!(
    5035          119 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    5036          119 :                         *applied_gc_cutoff_lsn,
    5037              :                     ))
    5038          119 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    5039              : 
    5040              :                 // and then the planned GC cutoff
    5041          117 :                 if start_lsn < planned_cutoff {
    5042            0 :                     return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    5043            0 :                         "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
    5044            0 :                     )));
    5045          117 :                 }
    5046              :             }
    5047              :         }
    5048              : 
    5049              :         //
    5050              :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    5051              :         // so that GC cannot advance the GC cutoff until we are finished.
    5052              :         // Proceed with the branch creation.
    5053              :         //
    5054              : 
    5055              :         // Determine prev-LSN for the new timeline. We can only determine it if
    5056              :         // the timeline was branched at the current end of the source timeline.
    5057              :         let RecordLsn {
    5058          117 :             last: src_last,
    5059          117 :             prev: src_prev,
    5060          117 :         } = src_timeline.get_last_record_rlsn();
    5061          117 :         let dst_prev = if src_last == start_lsn {
    5062          108 :             Some(src_prev)
    5063              :         } else {
    5064            9 :             None
    5065              :         };
    5066              : 
    5067              :         // Create the metadata file, noting the ancestor of the new timeline.
    5068              :         // There is initially no data in it, but all the read-calls know to look
    5069              :         // into the ancestor.
    5070          117 :         let metadata = TimelineMetadata::new(
    5071          117 :             start_lsn,
    5072          117 :             dst_prev,
    5073          117 :             Some(src_id),
    5074          117 :             start_lsn,
    5075          117 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    5076          117 :             src_timeline.initdb_lsn,
    5077          117 :             src_timeline.pg_version,
    5078              :         );
    5079              : 
    5080          117 :         let (uninitialized_timeline, _timeline_ctx) = self
    5081          117 :             .prepare_new_timeline(
    5082          117 :                 dst_id,
    5083          117 :                 &metadata,
    5084          117 :                 timeline_create_guard,
    5085          117 :                 start_lsn + 1,
    5086          117 :                 Some(Arc::clone(src_timeline)),
    5087          117 :                 Some(src_timeline.get_rel_size_v2_status()),
    5088          117 :                 ctx,
    5089          117 :             )
    5090          117 :             .await?;
    5091              : 
    5092          117 :         let new_timeline = uninitialized_timeline.finish_creation().await?;
    5093              : 
    5094              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    5095              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    5096              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    5097              :         // could get incorrect information and remove more layers, than needed.
    5098              :         // See also https://github.com/neondatabase/neon/issues/3865
    5099          117 :         new_timeline
    5100          117 :             .remote_client
    5101          117 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    5102          117 :             .context("branch initial metadata upload")?;
    5103              : 
    5104              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5105              : 
    5106          117 :         Ok(CreateTimelineResult::Created(new_timeline))
    5107          119 :     }
    5108              : 
    5109              :     /// For unit tests, make this visible so that other modules can directly create timelines
    5110              :     #[cfg(test)]
    5111              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    5112              :     pub(crate) async fn bootstrap_timeline_test(
    5113              :         self: &Arc<Self>,
    5114              :         timeline_id: TimelineId,
    5115              :         pg_version: PgMajorVersion,
    5116              :         load_existing_initdb: Option<TimelineId>,
    5117              :         ctx: &RequestContext,
    5118              :     ) -> anyhow::Result<Arc<Timeline>> {
    5119              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    5120              :             .await
    5121              :             .map_err(anyhow::Error::new)
    5122            1 :             .map(|r| r.into_timeline_for_test())
    5123              :     }
    5124              : 
    5125              :     /// Get exclusive access to the timeline ID for creation.
    5126              :     ///
    5127              :     /// Timeline-creating code paths must use this function before making changes
    5128              :     /// to in-memory or persistent state.
    5129              :     ///
    5130              :     /// The `state` parameter is a description of the timeline creation operation
    5131              :     /// we intend to perform.
    5132              :     /// If the timeline was already created in the meantime, we check whether this
    5133              :     /// request conflicts or is idempotent , based on `state`.
    5134          234 :     async fn start_creating_timeline(
    5135          234 :         self: &Arc<Self>,
    5136          234 :         new_timeline_id: TimelineId,
    5137          234 :         idempotency: CreateTimelineIdempotency,
    5138          234 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    5139          234 :         let allow_offloaded = false;
    5140          234 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    5141          233 :             Ok(create_guard) => {
    5142          233 :                 pausable_failpoint!("timeline-creation-after-uninit");
    5143          233 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    5144              :             }
    5145            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    5146              :             Err(TimelineExclusionError::AlreadyCreating) => {
    5147              :                 // Creation is in progress, we cannot create it again, and we cannot
    5148              :                 // check if this request matches the existing one, so caller must try
    5149              :                 // again later.
    5150            0 :                 Err(CreateTimelineError::AlreadyCreating)
    5151              :             }
    5152            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    5153              :             Err(TimelineExclusionError::AlreadyExists {
    5154            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    5155              :                 ..
    5156              :             }) => {
    5157            0 :                 info!("timeline already exists but is offloaded");
    5158            0 :                 Err(CreateTimelineError::Conflict)
    5159              :             }
    5160              :             Err(TimelineExclusionError::AlreadyExists {
    5161            0 :                 existing: TimelineOrOffloaded::Importing(_existing),
    5162              :                 ..
    5163              :             }) => {
    5164              :                 // If there's a timeline already importing, then we would hit
    5165              :                 // the [`TimelineExclusionError::AlreadyCreating`] branch above.
    5166            0 :                 unreachable!("Importing timelines hold the creation guard")
    5167              :             }
    5168              :             Err(TimelineExclusionError::AlreadyExists {
    5169            1 :                 existing: TimelineOrOffloaded::Timeline(existing),
    5170            1 :                 arg,
    5171              :             }) => {
    5172              :                 {
    5173            1 :                     let existing = &existing.create_idempotency;
    5174            1 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    5175            1 :                     debug!("timeline already exists");
    5176              : 
    5177            1 :                     match (existing, &arg) {
    5178              :                         // FailWithConflict => no idempotency check
    5179              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    5180              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    5181            1 :                             warn!("timeline already exists, failing request");
    5182            1 :                             return Err(CreateTimelineError::Conflict);
    5183              :                         }
    5184              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    5185            0 :                         (x, y) if x == y => {
    5186            0 :                             info!(
    5187            0 :                                 "timeline already exists and idempotency matches, succeeding request"
    5188              :                             );
    5189              :                             // fallthrough
    5190              :                         }
    5191              :                         (_, _) => {
    5192            0 :                             warn!("idempotency conflict, failing request");
    5193            0 :                             return Err(CreateTimelineError::Conflict);
    5194              :                         }
    5195              :                     }
    5196              :                 }
    5197              : 
    5198            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    5199              :             }
    5200              :         }
    5201          234 :     }
    5202              : 
    5203            0 :     async fn upload_initdb(
    5204            0 :         &self,
    5205            0 :         timelines_path: &Utf8PathBuf,
    5206            0 :         pgdata_path: &Utf8PathBuf,
    5207            0 :         timeline_id: &TimelineId,
    5208            0 :     ) -> anyhow::Result<()> {
    5209            0 :         let temp_path = timelines_path.join(format!(
    5210            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    5211            0 :         ));
    5212              : 
    5213            0 :         scopeguard::defer! {
    5214              :             if let Err(e) = fs::remove_file(&temp_path) {
    5215              :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    5216              :             }
    5217              :         }
    5218              : 
    5219            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    5220              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    5221            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    5222            0 :             warn!(
    5223            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    5224              :             );
    5225            0 :         }
    5226              : 
    5227            0 :         pausable_failpoint!("before-initdb-upload");
    5228              : 
    5229            0 :         backoff::retry(
    5230            0 :             || async {
    5231            0 :                 self::remote_timeline_client::upload_initdb_dir(
    5232            0 :                     &self.remote_storage,
    5233            0 :                     &self.tenant_shard_id.tenant_id,
    5234            0 :                     timeline_id,
    5235            0 :                     pgdata_zstd.try_clone().await?,
    5236            0 :                     tar_zst_size,
    5237            0 :                     &self.cancel,
    5238              :                 )
    5239            0 :                 .await
    5240            0 :             },
    5241              :             |_| false,
    5242              :             3,
    5243              :             u32::MAX,
    5244            0 :             "persist_initdb_tar_zst",
    5245            0 :             &self.cancel,
    5246              :         )
    5247            0 :         .await
    5248            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    5249            0 :         .and_then(|x| x)
    5250            0 :     }
    5251              : 
    5252              :     /// - run initdb to init temporary instance and get bootstrap data
    5253              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    5254            1 :     async fn bootstrap_timeline(
    5255            1 :         self: &Arc<Self>,
    5256            1 :         timeline_id: TimelineId,
    5257            1 :         pg_version: PgMajorVersion,
    5258            1 :         load_existing_initdb: Option<TimelineId>,
    5259            1 :         ctx: &RequestContext,
    5260            1 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5261            1 :         let timeline_create_guard = match self
    5262            1 :             .start_creating_timeline(
    5263            1 :                 timeline_id,
    5264            1 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5265            1 :             )
    5266            1 :             .await?
    5267              :         {
    5268            1 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5269            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5270            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5271              :             }
    5272              :         };
    5273              : 
    5274              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    5275              :         // temporary directory for basebackup files for the given timeline.
    5276              : 
    5277            1 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5278            1 :         let pgdata_path = path_with_suffix_extension(
    5279            1 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5280            1 :             TEMP_FILE_SUFFIX,
    5281              :         );
    5282              : 
    5283              :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5284              :         // we won't race with other creations or existent timelines with the same path.
    5285            1 :         if pgdata_path.exists() {
    5286            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    5287            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    5288            0 :             })?;
    5289            0 :             tracing::info!("removed previous attempt's temporary initdb directory '{pgdata_path}'");
    5290            1 :         }
    5291              : 
    5292              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5293            1 :         let pgdata_path_deferred = pgdata_path.clone();
    5294            1 :         scopeguard::defer! {
    5295              :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred).or_else(fs_ext::ignore_not_found) {
    5296              :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5297              :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5298              :             } else {
    5299              :                 tracing::info!("removed temporary initdb directory '{pgdata_path_deferred}'");
    5300              :             }
    5301              :         }
    5302            1 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5303            1 :             if existing_initdb_timeline_id != timeline_id {
    5304            0 :                 let source_path = &remote_initdb_archive_path(
    5305            0 :                     &self.tenant_shard_id.tenant_id,
    5306            0 :                     &existing_initdb_timeline_id,
    5307            0 :                 );
    5308            0 :                 let dest_path =
    5309            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    5310              : 
    5311              :                 // if this fails, it will get retried by retried control plane requests
    5312            0 :                 self.remote_storage
    5313            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    5314            0 :                     .await
    5315            0 :                     .context("copy initdb tar")?;
    5316            1 :             }
    5317            1 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5318            1 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5319            1 :                     self.conf,
    5320            1 :                     &self.remote_storage,
    5321            1 :                     &self.tenant_shard_id,
    5322            1 :                     &existing_initdb_timeline_id,
    5323            1 :                     &self.cancel,
    5324            1 :                 )
    5325            1 :                 .await
    5326            1 :                 .context("download initdb tar")?;
    5327              : 
    5328            1 :             scopeguard::defer! {
    5329              :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5330              :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5331              :                 }
    5332              :             }
    5333              : 
    5334            1 :             let buf_read =
    5335            1 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5336            1 :             extract_zst_tarball(&pgdata_path, buf_read)
    5337            1 :                 .await
    5338            1 :                 .context("extract initdb tar")?;
    5339              :         } else {
    5340              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    5341            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    5342            0 :                 .await
    5343            0 :                 .context("run initdb")?;
    5344              : 
    5345              :             // Upload the created data dir to S3
    5346            0 :             if self.tenant_shard_id().is_shard_zero() {
    5347            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5348            0 :                     .await?;
    5349            0 :             }
    5350              :         }
    5351            1 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5352              : 
    5353              :         // Import the contents of the data directory at the initial checkpoint
    5354              :         // LSN, and any WAL after that.
    5355              :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5356              :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5357            1 :         let new_metadata = TimelineMetadata::new(
    5358            1 :             Lsn(0),
    5359            1 :             None,
    5360            1 :             None,
    5361            1 :             Lsn(0),
    5362            1 :             pgdata_lsn,
    5363            1 :             pgdata_lsn,
    5364            1 :             pg_version,
    5365              :         );
    5366            1 :         let (mut raw_timeline, timeline_ctx) = self
    5367            1 :             .prepare_new_timeline(
    5368            1 :                 timeline_id,
    5369            1 :                 &new_metadata,
    5370            1 :                 timeline_create_guard,
    5371            1 :                 pgdata_lsn,
    5372            1 :                 None,
    5373            1 :                 None,
    5374            1 :                 ctx,
    5375            1 :             )
    5376            1 :             .await?;
    5377              : 
    5378            1 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5379            1 :         raw_timeline
    5380            1 :             .write(|unfinished_timeline| async move {
    5381            1 :                 import_datadir::import_timeline_from_postgres_datadir(
    5382            1 :                     &unfinished_timeline,
    5383            1 :                     &pgdata_path,
    5384            1 :                     pgdata_lsn,
    5385            1 :                     &timeline_ctx,
    5386            1 :                 )
    5387            1 :                 .await
    5388            1 :                 .with_context(|| {
    5389            0 :                     format!(
    5390            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5391              :                     )
    5392            0 :                 })?;
    5393              : 
    5394            1 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5395            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5396            0 :                         "failpoint before-checkpoint-new-timeline"
    5397            0 :                     )))
    5398            0 :                 });
    5399              : 
    5400            1 :                 Ok(())
    5401            2 :             })
    5402            1 :             .await?;
    5403              : 
    5404              :         // All done!
    5405            1 :         let timeline = raw_timeline.finish_creation().await?;
    5406              : 
    5407              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5408              : 
    5409            1 :         Ok(CreateTimelineResult::Created(timeline))
    5410            1 :     }
    5411              : 
    5412          231 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5413          231 :         RemoteTimelineClient::new(
    5414          231 :             self.remote_storage.clone(),
    5415          231 :             self.deletion_queue_client.clone(),
    5416          231 :             self.conf,
    5417          231 :             self.tenant_shard_id,
    5418          231 :             timeline_id,
    5419          231 :             self.generation,
    5420          231 :             &self.tenant_conf.load().location,
    5421              :         )
    5422          231 :     }
    5423              : 
    5424              :     /// Builds required resources for a new timeline.
    5425          231 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5426          231 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5427          231 :         self.get_timeline_resources_for(remote_client)
    5428          231 :     }
    5429              : 
    5430              :     /// Builds timeline resources for the given remote client.
    5431          234 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5432          234 :         TimelineResources {
    5433          234 :             remote_client,
    5434          234 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5435          234 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5436          234 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5437          234 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5438          234 :             basebackup_cache: self.basebackup_cache.clone(),
    5439          234 :             feature_resolver: self.feature_resolver.clone(),
    5440          234 :         }
    5441          234 :     }
    5442              : 
    5443              :     /// Creates intermediate timeline structure and its files.
    5444              :     ///
    5445              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5446              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5447              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5448              :     #[allow(clippy::too_many_arguments)]
    5449          231 :     async fn prepare_new_timeline<'a>(
    5450          231 :         &'a self,
    5451          231 :         new_timeline_id: TimelineId,
    5452          231 :         new_metadata: &TimelineMetadata,
    5453          231 :         create_guard: TimelineCreateGuard,
    5454          231 :         start_lsn: Lsn,
    5455          231 :         ancestor: Option<Arc<Timeline>>,
    5456          231 :         rel_size_v2_status: Option<RelSizeMigration>,
    5457          231 :         ctx: &RequestContext,
    5458          231 :     ) -> anyhow::Result<(UninitializedTimeline<'a>, RequestContext)> {
    5459          231 :         let tenant_shard_id = self.tenant_shard_id;
    5460              : 
    5461          231 :         let resources = self.build_timeline_resources(new_timeline_id);
    5462          231 :         resources
    5463          231 :             .remote_client
    5464          231 :             .init_upload_queue_for_empty_remote(new_metadata, rel_size_v2_status.clone())?;
    5465              : 
    5466          231 :         let (timeline_struct, timeline_ctx) = self
    5467          231 :             .create_timeline_struct(
    5468          231 :                 new_timeline_id,
    5469          231 :                 new_metadata,
    5470          231 :                 None,
    5471          231 :                 ancestor,
    5472          231 :                 resources,
    5473          231 :                 CreateTimelineCause::Load,
    5474          231 :                 create_guard.idempotency.clone(),
    5475          231 :                 None,
    5476          231 :                 rel_size_v2_status,
    5477          231 :                 ctx,
    5478              :             )
    5479          231 :             .context("Failed to create timeline data structure")?;
    5480              : 
    5481          231 :         timeline_struct.init_empty_layer_map(start_lsn);
    5482              : 
    5483          231 :         if let Err(e) = self
    5484          231 :             .create_timeline_files(&create_guard.timeline_path)
    5485          231 :             .await
    5486              :         {
    5487            0 :             error!(
    5488            0 :                 "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
    5489              :             );
    5490            0 :             cleanup_timeline_directory(create_guard);
    5491            0 :             return Err(e);
    5492          231 :         }
    5493              : 
    5494          231 :         debug!(
    5495            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5496              :         );
    5497              : 
    5498          231 :         Ok((
    5499          231 :             UninitializedTimeline::new(
    5500          231 :                 self,
    5501          231 :                 new_timeline_id,
    5502          231 :                 Some((timeline_struct, create_guard)),
    5503          231 :             ),
    5504          231 :             timeline_ctx,
    5505          231 :         ))
    5506          231 :     }
    5507              : 
    5508          231 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5509          231 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5510              : 
    5511          231 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5512            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5513            0 :         });
    5514              : 
    5515          231 :         Ok(())
    5516          231 :     }
    5517              : 
    5518              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5519              :     /// concurrent attempts to create the same timeline.
    5520              :     ///
    5521              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5522              :     /// offloaded timelines or not.
    5523          234 :     fn create_timeline_create_guard(
    5524          234 :         self: &Arc<Self>,
    5525          234 :         timeline_id: TimelineId,
    5526          234 :         idempotency: CreateTimelineIdempotency,
    5527          234 :         allow_offloaded: bool,
    5528          234 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5529          234 :         let tenant_shard_id = self.tenant_shard_id;
    5530              : 
    5531          234 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5532              : 
    5533          234 :         let create_guard = TimelineCreateGuard::new(
    5534          234 :             self,
    5535          234 :             timeline_id,
    5536          234 :             timeline_path.clone(),
    5537          234 :             idempotency,
    5538          234 :             allow_offloaded,
    5539            1 :         )?;
    5540              : 
    5541              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5542              :         // for creation.
    5543              :         // A timeline directory should never exist on disk already:
    5544              :         // - a previous failed creation would have cleaned up after itself
    5545              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5546              :         //
    5547              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5548              :         // this error may indicate a bug in cleanup on failed creations.
    5549          233 :         if timeline_path.exists() {
    5550            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5551            0 :                 "Timeline directory already exists! This is a bug."
    5552            0 :             )));
    5553          233 :         }
    5554              : 
    5555          233 :         Ok(create_guard)
    5556          234 :     }
    5557              : 
    5558              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5559              :     ///
    5560              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5561              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5562              :     pub async fn gather_size_inputs(
    5563              :         &self,
    5564              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5565              :         // (only if it is shorter than the real cutoff).
    5566              :         max_retention_period: Option<u64>,
    5567              :         cause: LogicalSizeCalculationCause,
    5568              :         cancel: &CancellationToken,
    5569              :         ctx: &RequestContext,
    5570              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5571              :         let logical_sizes_at_once = self
    5572              :             .conf
    5573              :             .concurrent_tenant_size_logical_size_queries
    5574              :             .inner();
    5575              : 
    5576              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5577              :         //
    5578              :         // But the only case where we need to run multiple of these at once is when we
    5579              :         // request a size for a tenant manually via API, while another background calculation
    5580              :         // is in progress (which is not a common case).
    5581              :         //
    5582              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5583              :         let mut shared_cache = tokio::select! {
    5584              :             locked = self.cached_logical_sizes.lock() => locked,
    5585              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5586              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5587              :         };
    5588              : 
    5589              :         size::gather_inputs(
    5590              :             self,
    5591              :             logical_sizes_at_once,
    5592              :             max_retention_period,
    5593              :             &mut shared_cache,
    5594              :             cause,
    5595              :             cancel,
    5596              :             ctx,
    5597              :         )
    5598              :         .await
    5599              :     }
    5600              : 
    5601              :     /// Calculate synthetic tenant size and cache the result.
    5602              :     /// This is periodically called by background worker.
    5603              :     /// result is cached in tenant struct
    5604              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5605              :     pub async fn calculate_synthetic_size(
    5606              :         &self,
    5607              :         cause: LogicalSizeCalculationCause,
    5608              :         cancel: &CancellationToken,
    5609              :         ctx: &RequestContext,
    5610              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5611              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5612              : 
    5613              :         let size = inputs.calculate();
    5614              : 
    5615              :         self.set_cached_synthetic_size(size);
    5616              : 
    5617              :         Ok(size)
    5618              :     }
    5619              : 
    5620              :     /// Cache given synthetic size and update the metric value
    5621            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5622            0 :         self.cached_synthetic_tenant_size
    5623            0 :             .store(size, Ordering::Relaxed);
    5624              : 
    5625              :         // Only shard zero should be calculating synthetic sizes
    5626            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5627              : 
    5628            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5629            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5630            0 :             .unwrap()
    5631            0 :             .set(size);
    5632            0 :     }
    5633              : 
    5634            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5635            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5636            0 :     }
    5637              : 
    5638              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5639              :     ///
    5640              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5641              :     /// from an external API handler.
    5642              :     ///
    5643              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5644              :     /// still bounded by tenant/timeline shutdown.
    5645              :     #[tracing::instrument(skip_all)]
    5646              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5647              :         let timelines = self.timelines.lock().unwrap().clone();
    5648              : 
    5649            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5650            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5651            0 :             timeline.freeze_and_flush().await?;
    5652            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5653            0 :             timeline.remote_client.wait_completion().await?;
    5654              : 
    5655            0 :             Ok(())
    5656            0 :         }
    5657              : 
    5658              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5659              :         // aborted when this function's future is cancelled: they should stay alive
    5660              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5661              :         // before Timeline shutdown completes.
    5662              :         let mut results = FuturesUnordered::new();
    5663              : 
    5664              :         for (_timeline_id, timeline) in timelines {
    5665              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5666              :             // means that if this function's future is cancelled, the Timeline shutdown
    5667              :             // will still wait for any I/O in here to complete.
    5668              :             let Ok(gate) = timeline.gate.enter() else {
    5669              :                 continue;
    5670              :             };
    5671            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5672              :             results.push(jh);
    5673              :         }
    5674              : 
    5675              :         while let Some(r) = results.next().await {
    5676              :             if let Err(e) = r {
    5677              :                 if !e.is_cancelled() && !e.is_panic() {
    5678              :                     tracing::error!("unexpected join error: {e:?}");
    5679              :                 }
    5680              :             }
    5681              :         }
    5682              : 
    5683              :         // The flushes we did above were just writes, but the TenantShard might have had
    5684              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5685              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5686              :         // because it's typically a no-op.
    5687              :         match self.deletion_queue_client.flush_execute().await {
    5688              :             Ok(_) => {}
    5689              :             Err(DeletionQueueError::ShuttingDown) => {}
    5690              :         }
    5691              : 
    5692              :         Ok(())
    5693              :     }
    5694              : 
    5695            0 :     pub(crate) fn get_tenant_conf(&self) -> pageserver_api::models::TenantConfig {
    5696            0 :         self.tenant_conf.load().tenant_conf.clone()
    5697            0 :     }
    5698              : 
    5699              :     /// How much local storage would this tenant like to have?  It can cope with
    5700              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5701              :     /// the TenantShard to advertise how much storage it would prefer to have to provide fast I/O
    5702              :     /// by keeping important things on local disk.
    5703              :     ///
    5704              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5705              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5706              :     /// actually use more than they report here.
    5707            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5708            0 :         let timelines = self.timelines.lock().unwrap();
    5709              : 
    5710              :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5711              :         // reflects the observation that on tenants with multiple large branches, typically only one
    5712              :         // of them is used actively enough to occupy space on disk.
    5713            0 :         timelines
    5714            0 :             .values()
    5715            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5716            0 :             .max()
    5717            0 :             .unwrap_or(0)
    5718            0 :     }
    5719              : 
    5720              :     /// Builds a new tenant manifest, and uploads it if it differs from the last-known tenant
    5721              :     /// manifest in `Self::remote_tenant_manifest`.
    5722              :     ///
    5723              :     /// TODO: instead of requiring callers to remember to call `maybe_upload_tenant_manifest` after
    5724              :     /// changing any `TenantShard` state that's included in the manifest, consider making the manifest
    5725              :     /// the authoritative source of data with an API that automatically uploads on changes. Revisit
    5726              :     /// this when the manifest is more widely used and we have a better idea of the data model.
    5727          119 :     pub(crate) async fn maybe_upload_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5728              :         // Multiple tasks may call this function concurrently after mutating the TenantShard runtime
    5729              :         // state, affecting the manifest generated by `build_tenant_manifest`. We use an async mutex
    5730              :         // to serialize these callers. `eq_ignoring_version` acts as a slightly inefficient but
    5731              :         // simple coalescing mechanism.
    5732          119 :         let mut guard = tokio::select! {
    5733          119 :             guard = self.remote_tenant_manifest.lock() => guard,
    5734          119 :             _ = self.cancel.cancelled() => return Err(TenantManifestError::Cancelled),
    5735              :         };
    5736              : 
    5737              :         // Build a new manifest.
    5738          119 :         let manifest = self.build_tenant_manifest();
    5739              : 
    5740              :         // Check if the manifest has changed. We ignore the version number here, to avoid
    5741              :         // uploading every manifest on version number bumps.
    5742          119 :         if let Some(old) = guard.as_ref() {
    5743            4 :             if manifest.eq_ignoring_version(old) {
    5744            3 :                 return Ok(());
    5745            1 :             }
    5746          115 :         }
    5747              : 
    5748              :         // Update metrics
    5749          116 :         let tid = self.tenant_shard_id.to_string();
    5750          116 :         let shard_id = self.tenant_shard_id.shard_slug().to_string();
    5751          116 :         let set_key = &[tid.as_str(), shard_id.as_str()][..];
    5752          116 :         TENANT_OFFLOADED_TIMELINES
    5753          116 :             .with_label_values(set_key)
    5754          116 :             .set(manifest.offloaded_timelines.len() as u64);
    5755              : 
    5756              :         // Upload the manifest. Remote storage does no retries internally, so retry here.
    5757          116 :         match backoff::retry(
    5758          116 :             || async {
    5759          116 :                 upload_tenant_manifest(
    5760          116 :                     &self.remote_storage,
    5761          116 :                     &self.tenant_shard_id,
    5762          116 :                     self.generation,
    5763          116 :                     &manifest,
    5764          116 :                     &self.cancel,
    5765          116 :                 )
    5766          116 :                 .await
    5767          232 :             },
    5768            0 :             |_| self.cancel.is_cancelled(),
    5769              :             FAILED_UPLOAD_WARN_THRESHOLD,
    5770              :             FAILED_REMOTE_OP_RETRIES,
    5771          116 :             "uploading tenant manifest",
    5772          116 :             &self.cancel,
    5773              :         )
    5774          116 :         .await
    5775              :         {
    5776            0 :             None => Err(TenantManifestError::Cancelled),
    5777            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5778            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5779              :             Some(Ok(_)) => {
    5780              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5781              :                 // re-uploading the same thing.
    5782          116 :                 *guard = Some(manifest);
    5783              : 
    5784          116 :                 Ok(())
    5785              :             }
    5786              :         }
    5787          119 :     }
    5788              : }
    5789              : 
    5790              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5791              : /// to get bootstrap data for timeline initialization.
    5792            0 : async fn run_initdb(
    5793            0 :     conf: &'static PageServerConf,
    5794            0 :     initdb_target_dir: &Utf8Path,
    5795            0 :     pg_version: PgMajorVersion,
    5796            0 :     cancel: &CancellationToken,
    5797            0 : ) -> Result<(), InitdbError> {
    5798            0 :     let initdb_bin_path = conf
    5799            0 :         .pg_bin_dir(pg_version)
    5800            0 :         .map_err(InitdbError::Other)?
    5801            0 :         .join("initdb");
    5802            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5803            0 :     info!(
    5804            0 :         "running {} in {}, libdir: {}",
    5805              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5806              :     );
    5807              : 
    5808            0 :     let _permit = {
    5809            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5810            0 :         INIT_DB_SEMAPHORE.acquire().await
    5811              :     };
    5812              : 
    5813            0 :     CONCURRENT_INITDBS.inc();
    5814            0 :     scopeguard::defer! {
    5815              :         CONCURRENT_INITDBS.dec();
    5816              :     }
    5817              : 
    5818            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5819            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5820            0 :         superuser: &conf.superuser,
    5821            0 :         locale: &conf.locale,
    5822            0 :         initdb_bin: &initdb_bin_path,
    5823            0 :         pg_version,
    5824            0 :         library_search_path: &initdb_lib_dir,
    5825            0 :         pgdata: initdb_target_dir,
    5826            0 :     })
    5827            0 :     .await
    5828            0 :     .map_err(InitdbError::Inner);
    5829              : 
    5830              :     // This isn't true cancellation support, see above. Still return an error to
    5831              :     // excercise the cancellation code path.
    5832            0 :     if cancel.is_cancelled() {
    5833            0 :         return Err(InitdbError::Cancelled);
    5834            0 :     }
    5835              : 
    5836            0 :     res
    5837            0 : }
    5838              : 
    5839              : /// Dump contents of a layer file to stdout.
    5840            0 : pub async fn dump_layerfile_from_path(
    5841            0 :     path: &Utf8Path,
    5842            0 :     verbose: bool,
    5843            0 :     ctx: &RequestContext,
    5844            0 : ) -> anyhow::Result<()> {
    5845              :     use std::os::unix::fs::FileExt;
    5846              : 
    5847              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5848              :     // file.
    5849            0 :     let file = File::open(path)?;
    5850            0 :     let mut header_buf = [0u8; 2];
    5851            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5852              : 
    5853            0 :     match u16::from_be_bytes(header_buf) {
    5854              :         crate::IMAGE_FILE_MAGIC => {
    5855            0 :             ImageLayer::new_for_path(path, file)?
    5856            0 :                 .dump(verbose, ctx)
    5857            0 :                 .await?
    5858              :         }
    5859              :         crate::DELTA_FILE_MAGIC => {
    5860            0 :             DeltaLayer::new_for_path(path, file)?
    5861            0 :                 .dump(verbose, ctx)
    5862            0 :                 .await?
    5863              :         }
    5864            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5865              :     }
    5866              : 
    5867            0 :     Ok(())
    5868            0 : }
    5869              : 
    5870              : #[cfg(test)]
    5871              : pub(crate) mod harness {
    5872              :     use bytes::{Bytes, BytesMut};
    5873              :     use hex_literal::hex;
    5874              :     use once_cell::sync::OnceCell;
    5875              :     use pageserver_api::key::Key;
    5876              :     use pageserver_api::models::ShardParameters;
    5877              :     use pageserver_api::shard::ShardIndex;
    5878              :     use utils::id::TenantId;
    5879              :     use utils::logging;
    5880              :     use wal_decoder::models::record::NeonWalRecord;
    5881              : 
    5882              :     use super::*;
    5883              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5884              :     use crate::l0_flush::L0FlushConfig;
    5885              :     use crate::walredo::apply_neon;
    5886              : 
    5887              :     pub const TIMELINE_ID: TimelineId =
    5888              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5889              :     pub const NEW_TIMELINE_ID: TimelineId =
    5890              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5891              : 
    5892              :     /// Convenience function to create a page image with given string as the only content
    5893      2514377 :     pub fn test_img(s: &str) -> Bytes {
    5894      2514377 :         let mut buf = BytesMut::new();
    5895      2514377 :         buf.extend_from_slice(s.as_bytes());
    5896      2514377 :         buf.resize(64, 0);
    5897              : 
    5898      2514377 :         buf.freeze()
    5899      2514377 :     }
    5900              : 
    5901              :     pub struct TenantHarness {
    5902              :         pub conf: &'static PageServerConf,
    5903              :         pub tenant_conf: pageserver_api::models::TenantConfig,
    5904              :         pub tenant_shard_id: TenantShardId,
    5905              :         pub shard_identity: ShardIdentity,
    5906              :         pub generation: Generation,
    5907              :         pub shard: ShardIndex,
    5908              :         pub remote_storage: GenericRemoteStorage,
    5909              :         pub remote_fs_dir: Utf8PathBuf,
    5910              :         pub deletion_queue: MockDeletionQueue,
    5911              :     }
    5912              : 
    5913              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5914              : 
    5915          130 :     pub(crate) fn setup_logging() {
    5916          130 :         LOG_HANDLE.get_or_init(|| {
    5917          124 :             logging::init(
    5918          124 :                 logging::LogFormat::Test,
    5919              :                 // enable it in case the tests exercise code paths that use
    5920              :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5921          124 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5922          124 :                 logging::Output::Stdout,
    5923              :             )
    5924          124 :             .expect("Failed to init test logging");
    5925          124 :         });
    5926          130 :     }
    5927              : 
    5928              :     impl TenantHarness {
    5929          118 :         pub async fn create_custom(
    5930          118 :             test_name: &'static str,
    5931          118 :             tenant_conf: pageserver_api::models::TenantConfig,
    5932          118 :             tenant_id: TenantId,
    5933          118 :             shard_identity: ShardIdentity,
    5934          118 :             generation: Generation,
    5935          118 :         ) -> anyhow::Result<Self> {
    5936          118 :             setup_logging();
    5937              : 
    5938          118 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5939          118 :             let _ = fs::remove_dir_all(&repo_dir);
    5940          118 :             fs::create_dir_all(&repo_dir)?;
    5941              : 
    5942          118 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5943              :             // Make a static copy of the config. This can never be free'd, but that's
    5944              :             // OK in a test.
    5945          118 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5946              : 
    5947          118 :             let shard = shard_identity.shard_index();
    5948          118 :             let tenant_shard_id = TenantShardId {
    5949          118 :                 tenant_id,
    5950          118 :                 shard_number: shard.shard_number,
    5951          118 :                 shard_count: shard.shard_count,
    5952          118 :             };
    5953          118 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5954          118 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5955              : 
    5956              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5957          118 :             let remote_fs_dir = conf.workdir.join("localfs");
    5958          118 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5959          118 :             let config = RemoteStorageConfig {
    5960          118 :                 storage: RemoteStorageKind::LocalFs {
    5961          118 :                     local_path: remote_fs_dir.clone(),
    5962          118 :                 },
    5963          118 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5964          118 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5965          118 :             };
    5966          118 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5967          118 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5968              : 
    5969          118 :             Ok(Self {
    5970          118 :                 conf,
    5971          118 :                 tenant_conf,
    5972          118 :                 tenant_shard_id,
    5973          118 :                 shard_identity,
    5974          118 :                 generation,
    5975          118 :                 shard,
    5976          118 :                 remote_storage,
    5977          118 :                 remote_fs_dir,
    5978          118 :                 deletion_queue,
    5979          118 :             })
    5980          118 :         }
    5981              : 
    5982          110 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5983              :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5984              :             // The tests perform them manually if needed.
    5985          110 :             let tenant_conf = pageserver_api::models::TenantConfig {
    5986          110 :                 gc_period: Some(Duration::ZERO),
    5987          110 :                 compaction_period: Some(Duration::ZERO),
    5988          110 :                 ..Default::default()
    5989          110 :             };
    5990          110 :             let tenant_id = TenantId::generate();
    5991          110 :             let shard = ShardIdentity::unsharded();
    5992          110 :             Self::create_custom(
    5993          110 :                 test_name,
    5994          110 :                 tenant_conf,
    5995          110 :                 tenant_id,
    5996          110 :                 shard,
    5997          110 :                 Generation::new(0xdeadbeef),
    5998          110 :             )
    5999          110 :             .await
    6000          110 :         }
    6001              : 
    6002           10 :         pub fn span(&self) -> tracing::Span {
    6003           10 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    6004           10 :         }
    6005              : 
    6006          118 :         pub(crate) async fn load(&self) -> (Arc<TenantShard>, RequestContext) {
    6007          118 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error)
    6008          118 :                 .with_scope_unit_test();
    6009              :             (
    6010          118 :                 self.do_try_load(&ctx)
    6011          118 :                     .await
    6012          118 :                     .expect("failed to load test tenant"),
    6013          118 :                 ctx,
    6014              :             )
    6015          118 :         }
    6016              : 
    6017              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    6018              :         pub(crate) async fn do_try_load(
    6019              :             &self,
    6020              :             ctx: &RequestContext,
    6021              :         ) -> anyhow::Result<Arc<TenantShard>> {
    6022              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    6023              : 
    6024              :             let (basebackup_cache, _) = BasebackupCache::new(Utf8PathBuf::new(), None);
    6025              : 
    6026              :             let tenant = Arc::new(TenantShard::new(
    6027              :                 TenantState::Attaching,
    6028              :                 self.conf,
    6029              :                 AttachedTenantConf::try_from(
    6030              :                     self.conf,
    6031              :                     LocationConf::attached_single(
    6032              :                         self.tenant_conf.clone(),
    6033              :                         self.generation,
    6034              :                         ShardParameters::default(),
    6035              :                     ),
    6036              :                 )
    6037              :                 .unwrap(),
    6038              :                 self.shard_identity,
    6039              :                 Some(walredo_mgr),
    6040              :                 self.tenant_shard_id,
    6041              :                 self.remote_storage.clone(),
    6042              :                 self.deletion_queue.new_client(),
    6043              :                 // TODO: ideally we should run all unit tests with both configs
    6044              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    6045              :                 basebackup_cache,
    6046              :                 FeatureResolver::new_disabled(),
    6047              :             ));
    6048              : 
    6049              :             let preload = tenant
    6050              :                 .preload(&self.remote_storage, CancellationToken::new())
    6051              :                 .await?;
    6052              :             tenant.attach(Some(preload), ctx).await?;
    6053              : 
    6054              :             tenant.state.send_replace(TenantState::Active);
    6055              :             for timeline in tenant.timelines.lock().unwrap().values() {
    6056              :                 timeline.set_state(TimelineState::Active);
    6057              :             }
    6058              :             Ok(tenant)
    6059              :         }
    6060              : 
    6061            1 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    6062            1 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    6063            1 :         }
    6064              :     }
    6065              : 
    6066              :     // Mock WAL redo manager that doesn't do much
    6067              :     pub(crate) struct TestRedoManager;
    6068              : 
    6069              :     impl TestRedoManager {
    6070              :         /// # Cancel-Safety
    6071              :         ///
    6072              :         /// This method is cancellation-safe.
    6073        26774 :         pub async fn request_redo(
    6074        26774 :             &self,
    6075        26774 :             key: Key,
    6076        26774 :             lsn: Lsn,
    6077        26774 :             base_img: Option<(Lsn, Bytes)>,
    6078        26774 :             records: Vec<(Lsn, NeonWalRecord)>,
    6079        26774 :             _pg_version: PgMajorVersion,
    6080        26774 :             _redo_attempt_type: RedoAttemptType,
    6081        26774 :         ) -> Result<Bytes, walredo::Error> {
    6082      1403510 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    6083        26774 :             if records_neon {
    6084              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    6085        26774 :                 let mut page = match (base_img, records.first()) {
    6086        13029 :                     (Some((_lsn, img)), _) => {
    6087        13029 :                         let mut page = BytesMut::new();
    6088        13029 :                         page.extend_from_slice(&img);
    6089        13029 :                         page
    6090              :                     }
    6091        13745 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    6092              :                     _ => {
    6093            0 :                         panic!("Neon WAL redo requires base image or will init record");
    6094              :                     }
    6095              :                 };
    6096              : 
    6097      1430283 :                 for (record_lsn, record) in records {
    6098      1403510 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    6099              :                 }
    6100        26773 :                 Ok(page.freeze())
    6101              :             } else {
    6102              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    6103            0 :                 let s = format!(
    6104            0 :                     "redo for {} to get to {}, with {} and {} records",
    6105              :                     key,
    6106              :                     lsn,
    6107            0 :                     if base_img.is_some() {
    6108            0 :                         "base image"
    6109              :                     } else {
    6110            0 :                         "no base image"
    6111              :                     },
    6112            0 :                     records.len()
    6113              :                 );
    6114            0 :                 println!("{s}");
    6115              : 
    6116            0 :                 Ok(test_img(&s))
    6117              :             }
    6118        26774 :         }
    6119              :     }
    6120              : }
    6121              : 
    6122              : #[cfg(test)]
    6123              : mod tests {
    6124              :     use std::collections::{BTreeMap, BTreeSet};
    6125              : 
    6126              :     use bytes::{Bytes, BytesMut};
    6127              :     use hex_literal::hex;
    6128              :     use itertools::Itertools;
    6129              :     #[cfg(feature = "testing")]
    6130              :     use models::CompactLsnRange;
    6131              :     use pageserver_api::key::{
    6132              :         AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX, repl_origin_key,
    6133              :     };
    6134              :     use pageserver_api::keyspace::KeySpace;
    6135              :     #[cfg(feature = "testing")]
    6136              :     use pageserver_api::keyspace::KeySpaceRandomAccum;
    6137              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings, LsnLease};
    6138              :     use pageserver_compaction::helpers::overlaps_with;
    6139              :     #[cfg(feature = "testing")]
    6140              :     use rand::SeedableRng;
    6141              :     #[cfg(feature = "testing")]
    6142              :     use rand::rngs::StdRng;
    6143              :     use rand::{Rng, thread_rng};
    6144              :     #[cfg(feature = "testing")]
    6145              :     use std::ops::Range;
    6146              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    6147              :     use tests::storage_layer::ValuesReconstructState;
    6148              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    6149              :     #[cfg(feature = "testing")]
    6150              :     use timeline::GcInfo;
    6151              :     #[cfg(feature = "testing")]
    6152              :     use timeline::InMemoryLayerTestDesc;
    6153              :     #[cfg(feature = "testing")]
    6154              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    6155              :     use timeline::{CompactOptions, DeltaLayerTestDesc, VersionedKeySpaceQuery};
    6156              :     use utils::id::TenantId;
    6157              :     use utils::shard::{ShardCount, ShardNumber};
    6158              :     #[cfg(feature = "testing")]
    6159              :     use wal_decoder::models::record::NeonWalRecord;
    6160              :     use wal_decoder::models::value::Value;
    6161              : 
    6162              :     use super::*;
    6163              :     use crate::DEFAULT_PG_VERSION;
    6164              :     use crate::keyspace::KeySpaceAccum;
    6165              :     use crate::tenant::harness::*;
    6166              :     use crate::tenant::timeline::CompactFlags;
    6167              : 
    6168              :     static TEST_KEY: Lazy<Key> =
    6169           10 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    6170              : 
    6171              :     #[cfg(feature = "testing")]
    6172              :     struct TestTimelineSpecification {
    6173              :         start_lsn: Lsn,
    6174              :         last_record_lsn: Lsn,
    6175              : 
    6176              :         in_memory_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    6177              :         delta_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    6178              :         image_layers_shape: Vec<(Range<Key>, Lsn)>,
    6179              : 
    6180              :         gap_chance: u8,
    6181              :         will_init_chance: u8,
    6182              :     }
    6183              : 
    6184              :     #[cfg(feature = "testing")]
    6185              :     struct Storage {
    6186              :         storage: HashMap<(Key, Lsn), Value>,
    6187              :         start_lsn: Lsn,
    6188              :     }
    6189              : 
    6190              :     #[cfg(feature = "testing")]
    6191              :     impl Storage {
    6192        32000 :         fn get(&self, key: Key, lsn: Lsn) -> Bytes {
    6193              :             use bytes::BufMut;
    6194              : 
    6195        32000 :             let mut crnt_lsn = lsn;
    6196        32000 :             let mut got_base = false;
    6197              : 
    6198        32000 :             let mut acc = Vec::new();
    6199              : 
    6200      2831871 :             while crnt_lsn >= self.start_lsn {
    6201      2831871 :                 if let Some(value) = self.storage.get(&(key, crnt_lsn)) {
    6202      1421172 :                     acc.push(value.clone());
    6203              : 
    6204      1402881 :                     match value {
    6205      1402881 :                         Value::WalRecord(NeonWalRecord::Test { will_init, .. }) => {
    6206      1402881 :                             if *will_init {
    6207        13709 :                                 got_base = true;
    6208        13709 :                                 break;
    6209      1389172 :                             }
    6210              :                         }
    6211              :                         Value::Image(_) => {
    6212        18291 :                             got_base = true;
    6213        18291 :                             break;
    6214              :                         }
    6215            0 :                         _ => unreachable!(),
    6216              :                     }
    6217      1410699 :                 }
    6218              : 
    6219      2799871 :                 crnt_lsn = crnt_lsn.checked_sub(1u64).unwrap();
    6220              :             }
    6221              : 
    6222        32000 :             assert!(
    6223        32000 :                 got_base,
    6224            0 :                 "Input data was incorrect. No base image for {key}@{lsn}"
    6225              :             );
    6226              : 
    6227        32000 :             tracing::debug!("Wal redo depth for {key}@{lsn} is {}", acc.len());
    6228              : 
    6229        32000 :             let mut blob = BytesMut::new();
    6230      1421172 :             for value in acc.into_iter().rev() {
    6231      1402881 :                 match value {
    6232      1402881 :                     Value::WalRecord(NeonWalRecord::Test { append, .. }) => {
    6233      1402881 :                         blob.extend_from_slice(append.as_bytes());
    6234      1402881 :                     }
    6235        18291 :                     Value::Image(img) => {
    6236        18291 :                         blob.put(img);
    6237        18291 :                     }
    6238            0 :                     _ => unreachable!(),
    6239              :                 }
    6240              :             }
    6241              : 
    6242        32000 :             blob.into()
    6243        32000 :         }
    6244              :     }
    6245              : 
    6246              :     #[cfg(feature = "testing")]
    6247              :     #[allow(clippy::too_many_arguments)]
    6248            1 :     async fn randomize_timeline(
    6249            1 :         tenant: &Arc<TenantShard>,
    6250            1 :         new_timeline_id: TimelineId,
    6251            1 :         pg_version: PgMajorVersion,
    6252            1 :         spec: TestTimelineSpecification,
    6253            1 :         random: &mut rand::rngs::StdRng,
    6254            1 :         ctx: &RequestContext,
    6255            1 :     ) -> anyhow::Result<(Arc<Timeline>, Storage, Vec<Lsn>)> {
    6256            1 :         let mut storage: HashMap<(Key, Lsn), Value> = HashMap::default();
    6257            1 :         let mut interesting_lsns = vec![spec.last_record_lsn];
    6258              : 
    6259            2 :         for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6260            2 :             let mut lsn = lsn_range.start;
    6261          202 :             while lsn < lsn_range.end {
    6262          200 :                 let mut key = key_range.start;
    6263        21018 :                 while key < key_range.end {
    6264        20818 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6265        20818 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6266              : 
    6267        20818 :                     if gap {
    6268         1018 :                         continue;
    6269        19800 :                     }
    6270              : 
    6271        19800 :                     let record = if will_init {
    6272          191 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6273              :                     } else {
    6274        19609 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6275              :                     };
    6276              : 
    6277        19800 :                     storage.insert((key, lsn), record);
    6278              : 
    6279        19800 :                     key = key.next();
    6280              :                 }
    6281          200 :                 lsn = Lsn(lsn.0 + 1);
    6282              :             }
    6283              : 
    6284              :             // Stash some interesting LSN for future use
    6285            6 :             for offset in [0, 5, 100].iter() {
    6286            6 :                 if *offset == 0 {
    6287            2 :                     interesting_lsns.push(lsn_range.start);
    6288            2 :                 } else {
    6289            4 :                     let below = lsn_range.start.checked_sub(*offset);
    6290            4 :                     match below {
    6291            4 :                         Some(v) if v >= spec.start_lsn => {
    6292            4 :                             interesting_lsns.push(v);
    6293            4 :                         }
    6294            0 :                         _ => {}
    6295              :                     }
    6296              : 
    6297            4 :                     let above = Lsn(lsn_range.start.0 + offset);
    6298            4 :                     interesting_lsns.push(above);
    6299              :                 }
    6300              :             }
    6301              :         }
    6302              : 
    6303            3 :         for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6304            3 :             let mut lsn = lsn_range.start;
    6305          315 :             while lsn < lsn_range.end {
    6306          312 :                 let mut key = key_range.start;
    6307        11112 :                 while key < key_range.end {
    6308        10800 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6309        10800 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6310              : 
    6311        10800 :                     if gap {
    6312          504 :                         continue;
    6313        10296 :                     }
    6314              : 
    6315        10296 :                     let record = if will_init {
    6316          103 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6317              :                     } else {
    6318        10193 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6319              :                     };
    6320              : 
    6321        10296 :                     storage.insert((key, lsn), record);
    6322              : 
    6323        10296 :                     key = key.next();
    6324              :                 }
    6325          312 :                 lsn = Lsn(lsn.0 + 1);
    6326              :             }
    6327              : 
    6328              :             // Stash some interesting LSN for future use
    6329            9 :             for offset in [0, 5, 100].iter() {
    6330            9 :                 if *offset == 0 {
    6331            3 :                     interesting_lsns.push(lsn_range.start);
    6332            3 :                 } else {
    6333            6 :                     let below = lsn_range.start.checked_sub(*offset);
    6334            6 :                     match below {
    6335            6 :                         Some(v) if v >= spec.start_lsn => {
    6336            3 :                             interesting_lsns.push(v);
    6337            3 :                         }
    6338            3 :                         _ => {}
    6339              :                     }
    6340              : 
    6341            6 :                     let above = Lsn(lsn_range.start.0 + offset);
    6342            6 :                     interesting_lsns.push(above);
    6343              :                 }
    6344              :             }
    6345              :         }
    6346              : 
    6347            3 :         for (key_range, lsn) in spec.image_layers_shape.iter() {
    6348            3 :             let mut key = key_range.start;
    6349          142 :             while key < key_range.end {
    6350          139 :                 let blob = Bytes::from(format!("[image {key}@{lsn}]"));
    6351          139 :                 let record = Value::Image(blob.clone());
    6352          139 :                 storage.insert((key, *lsn), record);
    6353          139 : 
    6354          139 :                 key = key.next();
    6355          139 :             }
    6356              : 
    6357              :             // Stash some interesting LSN for future use
    6358            9 :             for offset in [0, 5, 100].iter() {
    6359            9 :                 if *offset == 0 {
    6360            3 :                     interesting_lsns.push(*lsn);
    6361            3 :                 } else {
    6362            6 :                     let below = lsn.checked_sub(*offset);
    6363            6 :                     match below {
    6364            6 :                         Some(v) if v >= spec.start_lsn => {
    6365            4 :                             interesting_lsns.push(v);
    6366            4 :                         }
    6367            2 :                         _ => {}
    6368              :                     }
    6369              : 
    6370            6 :                     let above = Lsn(lsn.0 + offset);
    6371            6 :                     interesting_lsns.push(above);
    6372              :                 }
    6373              :             }
    6374              :         }
    6375              : 
    6376            1 :         let in_memory_test_layers = {
    6377            1 :             let mut acc = Vec::new();
    6378              : 
    6379            2 :             for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6380            2 :                 let mut data = Vec::new();
    6381              : 
    6382            2 :                 let mut lsn = lsn_range.start;
    6383          202 :                 while lsn < lsn_range.end {
    6384          200 :                     let mut key = key_range.start;
    6385        20000 :                     while key < key_range.end {
    6386        19800 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6387        19800 :                             data.push((key, lsn, record.clone()));
    6388        19800 :                         }
    6389              : 
    6390        19800 :                         key = key.next();
    6391              :                     }
    6392          200 :                     lsn = Lsn(lsn.0 + 1);
    6393              :                 }
    6394              : 
    6395            2 :                 acc.push(InMemoryLayerTestDesc {
    6396            2 :                     data,
    6397            2 :                     lsn_range: lsn_range.clone(),
    6398            2 :                     is_open: false,
    6399            2 :                 })
    6400              :             }
    6401              : 
    6402            1 :             acc
    6403              :         };
    6404              : 
    6405            1 :         let delta_test_layers = {
    6406            1 :             let mut acc = Vec::new();
    6407              : 
    6408            3 :             for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6409            3 :                 let mut data = Vec::new();
    6410              : 
    6411            3 :                 let mut lsn = lsn_range.start;
    6412          315 :                 while lsn < lsn_range.end {
    6413          312 :                     let mut key = key_range.start;
    6414        10608 :                     while key < key_range.end {
    6415        10296 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6416        10296 :                             data.push((key, lsn, record.clone()));
    6417        10296 :                         }
    6418              : 
    6419        10296 :                         key = key.next();
    6420              :                     }
    6421          312 :                     lsn = Lsn(lsn.0 + 1);
    6422              :                 }
    6423              : 
    6424            3 :                 acc.push(DeltaLayerTestDesc {
    6425            3 :                     data,
    6426            3 :                     lsn_range: lsn_range.clone(),
    6427            3 :                     key_range: key_range.clone(),
    6428            3 :                 })
    6429              :             }
    6430              : 
    6431            1 :             acc
    6432              :         };
    6433              : 
    6434            1 :         let image_test_layers = {
    6435            1 :             let mut acc = Vec::new();
    6436              : 
    6437            3 :             for (key_range, lsn) in spec.image_layers_shape.iter() {
    6438            3 :                 let mut data = Vec::new();
    6439              : 
    6440            3 :                 let mut key = key_range.start;
    6441          142 :                 while key < key_range.end {
    6442          139 :                     if let Some(record) = storage.get(&(key, *lsn)) {
    6443          139 :                         let blob = match record {
    6444          139 :                             Value::Image(blob) => blob.clone(),
    6445            0 :                             _ => unreachable!(),
    6446              :                         };
    6447              : 
    6448          139 :                         data.push((key, blob));
    6449            0 :                     }
    6450              : 
    6451          139 :                     key = key.next();
    6452              :                 }
    6453              : 
    6454            3 :                 acc.push((*lsn, data));
    6455              :             }
    6456              : 
    6457            1 :             acc
    6458              :         };
    6459              : 
    6460            1 :         let tline = tenant
    6461            1 :             .create_test_timeline_with_layers(
    6462            1 :                 new_timeline_id,
    6463            1 :                 spec.start_lsn,
    6464            1 :                 pg_version,
    6465            1 :                 ctx,
    6466            1 :                 in_memory_test_layers,
    6467            1 :                 delta_test_layers,
    6468            1 :                 image_test_layers,
    6469            1 :                 spec.last_record_lsn,
    6470            1 :             )
    6471            1 :             .await?;
    6472              : 
    6473            1 :         Ok((
    6474            1 :             tline,
    6475            1 :             Storage {
    6476            1 :                 storage,
    6477            1 :                 start_lsn: spec.start_lsn,
    6478            1 :             },
    6479            1 :             interesting_lsns,
    6480            1 :         ))
    6481            1 :     }
    6482              : 
    6483              :     #[tokio::test]
    6484            1 :     async fn test_basic() -> anyhow::Result<()> {
    6485            1 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    6486            1 :         let tline = tenant
    6487            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6488            1 :             .await?;
    6489              : 
    6490            1 :         let mut writer = tline.writer().await;
    6491            1 :         writer
    6492            1 :             .put(
    6493            1 :                 *TEST_KEY,
    6494            1 :                 Lsn(0x10),
    6495            1 :                 &Value::Image(test_img("foo at 0x10")),
    6496            1 :                 &ctx,
    6497            1 :             )
    6498            1 :             .await?;
    6499            1 :         writer.finish_write(Lsn(0x10));
    6500            1 :         drop(writer);
    6501              : 
    6502            1 :         let mut writer = tline.writer().await;
    6503            1 :         writer
    6504            1 :             .put(
    6505            1 :                 *TEST_KEY,
    6506            1 :                 Lsn(0x20),
    6507            1 :                 &Value::Image(test_img("foo at 0x20")),
    6508            1 :                 &ctx,
    6509            1 :             )
    6510            1 :             .await?;
    6511            1 :         writer.finish_write(Lsn(0x20));
    6512            1 :         drop(writer);
    6513              : 
    6514            1 :         assert_eq!(
    6515            1 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6516            1 :             test_img("foo at 0x10")
    6517              :         );
    6518            1 :         assert_eq!(
    6519            1 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6520            1 :             test_img("foo at 0x10")
    6521              :         );
    6522            1 :         assert_eq!(
    6523            1 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6524            1 :             test_img("foo at 0x20")
    6525              :         );
    6526              : 
    6527            2 :         Ok(())
    6528            1 :     }
    6529              : 
    6530              :     #[tokio::test]
    6531            1 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    6532            1 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    6533            1 :             .await?
    6534            1 :             .load()
    6535            1 :             .await;
    6536            1 :         let _ = tenant
    6537            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6538            1 :             .await?;
    6539              : 
    6540            1 :         match tenant
    6541            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6542            1 :             .await
    6543            1 :         {
    6544            1 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    6545            1 :             Err(e) => assert_eq!(
    6546            1 :                 e.to_string(),
    6547            1 :                 "timeline already exists with different parameters".to_string()
    6548            1 :             ),
    6549            1 :         }
    6550            1 : 
    6551            1 :         Ok(())
    6552            1 :     }
    6553              : 
    6554              :     /// Convenience function to create a page image with given string as the only content
    6555            5 :     pub fn test_value(s: &str) -> Value {
    6556            5 :         let mut buf = BytesMut::new();
    6557            5 :         buf.extend_from_slice(s.as_bytes());
    6558            5 :         Value::Image(buf.freeze())
    6559            5 :     }
    6560              : 
    6561              :     ///
    6562              :     /// Test branch creation
    6563              :     ///
    6564              :     #[tokio::test]
    6565            1 :     async fn test_branch() -> anyhow::Result<()> {
    6566              :         use std::str::from_utf8;
    6567              : 
    6568            1 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    6569            1 :         let tline = tenant
    6570            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6571            1 :             .await?;
    6572            1 :         let mut writer = tline.writer().await;
    6573              : 
    6574              :         #[allow(non_snake_case)]
    6575            1 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6576              :         #[allow(non_snake_case)]
    6577            1 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6578              : 
    6579              :         // Insert a value on the timeline
    6580            1 :         writer
    6581            1 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6582            1 :             .await?;
    6583            1 :         writer
    6584            1 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6585            1 :             .await?;
    6586            1 :         writer.finish_write(Lsn(0x20));
    6587              : 
    6588            1 :         writer
    6589            1 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6590            1 :             .await?;
    6591            1 :         writer.finish_write(Lsn(0x30));
    6592            1 :         writer
    6593            1 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6594            1 :             .await?;
    6595            1 :         writer.finish_write(Lsn(0x40));
    6596              : 
    6597              :         //assert_current_logical_size(&tline, Lsn(0x40));
    6598              : 
    6599              :         // Branch the history, modify relation differently on the new timeline
    6600            1 :         tenant
    6601            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6602            1 :             .await?;
    6603            1 :         let newtline = tenant
    6604            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6605            1 :             .expect("Should have a local timeline");
    6606            1 :         let mut new_writer = newtline.writer().await;
    6607            1 :         new_writer
    6608            1 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6609            1 :             .await?;
    6610            1 :         new_writer.finish_write(Lsn(0x40));
    6611              : 
    6612              :         // Check page contents on both branches
    6613            1 :         assert_eq!(
    6614            1 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6615              :             "foo at 0x40"
    6616              :         );
    6617            1 :         assert_eq!(
    6618            1 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6619              :             "bar at 0x40"
    6620              :         );
    6621            1 :         assert_eq!(
    6622            1 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6623              :             "foobar at 0x20"
    6624              :         );
    6625              : 
    6626              :         //assert_current_logical_size(&tline, Lsn(0x40));
    6627              : 
    6628            2 :         Ok(())
    6629            1 :     }
    6630              : 
    6631           10 :     async fn make_some_layers(
    6632           10 :         tline: &Timeline,
    6633           10 :         start_lsn: Lsn,
    6634           10 :         ctx: &RequestContext,
    6635           10 :     ) -> anyhow::Result<()> {
    6636           10 :         let mut lsn = start_lsn;
    6637              :         {
    6638           10 :             let mut writer = tline.writer().await;
    6639              :             // Create a relation on the timeline
    6640           10 :             writer
    6641           10 :                 .put(
    6642           10 :                     *TEST_KEY,
    6643           10 :                     lsn,
    6644           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6645           10 :                     ctx,
    6646           10 :                 )
    6647           10 :                 .await?;
    6648           10 :             writer.finish_write(lsn);
    6649           10 :             lsn += 0x10;
    6650           10 :             writer
    6651           10 :                 .put(
    6652           10 :                     *TEST_KEY,
    6653           10 :                     lsn,
    6654           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6655           10 :                     ctx,
    6656           10 :                 )
    6657           10 :                 .await?;
    6658           10 :             writer.finish_write(lsn);
    6659           10 :             lsn += 0x10;
    6660              :         }
    6661           10 :         tline.freeze_and_flush().await?;
    6662              :         {
    6663           10 :             let mut writer = tline.writer().await;
    6664           10 :             writer
    6665           10 :                 .put(
    6666           10 :                     *TEST_KEY,
    6667           10 :                     lsn,
    6668           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6669           10 :                     ctx,
    6670           10 :                 )
    6671           10 :                 .await?;
    6672           10 :             writer.finish_write(lsn);
    6673           10 :             lsn += 0x10;
    6674           10 :             writer
    6675           10 :                 .put(
    6676           10 :                     *TEST_KEY,
    6677           10 :                     lsn,
    6678           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6679           10 :                     ctx,
    6680           10 :                 )
    6681           10 :                 .await?;
    6682           10 :             writer.finish_write(lsn);
    6683              :         }
    6684           10 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6685           10 :     }
    6686              : 
    6687              :     #[tokio::test]
    6688            1 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6689            1 :         let (tenant, ctx) =
    6690            1 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6691            1 :                 .await?
    6692            1 :                 .load()
    6693            1 :                 .await;
    6694            1 :         let tline = tenant
    6695            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6696            1 :             .await?;
    6697            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6698              : 
    6699              :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6700              :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6701              :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6702              :         // below should fail.
    6703            1 :         tenant
    6704            1 :             .gc_iteration(
    6705            1 :                 Some(TIMELINE_ID),
    6706            1 :                 0x10,
    6707            1 :                 Duration::ZERO,
    6708            1 :                 &CancellationToken::new(),
    6709            1 :                 &ctx,
    6710            1 :             )
    6711            1 :             .await?;
    6712              : 
    6713              :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6714            1 :         match tenant
    6715            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6716            1 :             .await
    6717            1 :         {
    6718            1 :             Ok(_) => panic!("branching should have failed"),
    6719            1 :             Err(err) => {
    6720            1 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6721            1 :                     panic!("wrong error type")
    6722            1 :                 };
    6723            1 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6724            1 :                 assert!(
    6725            1 :                     err.source()
    6726            1 :                         .unwrap()
    6727            1 :                         .to_string()
    6728            1 :                         .contains("we might've already garbage collected needed data")
    6729            1 :                 )
    6730            1 :             }
    6731            1 :         }
    6732            1 : 
    6733            1 :         Ok(())
    6734            1 :     }
    6735              : 
    6736              :     #[tokio::test]
    6737            1 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6738            1 :         let (tenant, ctx) =
    6739            1 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6740            1 :                 .await?
    6741            1 :                 .load()
    6742            1 :                 .await;
    6743              : 
    6744            1 :         let tline = tenant
    6745            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6746            1 :             .await?;
    6747              :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6748            1 :         match tenant
    6749            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6750            1 :             .await
    6751            1 :         {
    6752            1 :             Ok(_) => panic!("branching should have failed"),
    6753            1 :             Err(err) => {
    6754            1 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6755            1 :                     panic!("wrong error type");
    6756            1 :                 };
    6757            1 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6758            1 :                 assert!(
    6759            1 :                     &err.source()
    6760            1 :                         .unwrap()
    6761            1 :                         .to_string()
    6762            1 :                         .contains("is earlier than latest GC cutoff")
    6763            1 :                 );
    6764            1 :             }
    6765            1 :         }
    6766            1 : 
    6767            1 :         Ok(())
    6768            1 :     }
    6769              : 
    6770              :     /*
    6771              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6772              :     // remove the old value, we'd need to work a little harder
    6773              :     #[tokio::test]
    6774              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6775              :         let repo =
    6776              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6777              :             .load();
    6778              : 
    6779              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6780              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6781              : 
    6782              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6783              :         let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
    6784              :         assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
    6785              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6786              :             Ok(_) => panic!("request for page should have failed"),
    6787              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6788              :         }
    6789              :         Ok(())
    6790              :     }
    6791              :      */
    6792              : 
    6793              :     #[tokio::test]
    6794            1 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6795            1 :         let (tenant, ctx) =
    6796            1 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6797            1 :                 .await?
    6798            1 :                 .load()
    6799            1 :                 .await;
    6800            1 :         let tline = tenant
    6801            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6802            1 :             .await?;
    6803            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6804              : 
    6805            1 :         tenant
    6806            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6807            1 :             .await?;
    6808            1 :         let newtline = tenant
    6809            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6810            1 :             .expect("Should have a local timeline");
    6811              : 
    6812            1 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6813              : 
    6814            1 :         tline.set_broken("test".to_owned());
    6815              : 
    6816            1 :         tenant
    6817            1 :             .gc_iteration(
    6818            1 :                 Some(TIMELINE_ID),
    6819            1 :                 0x10,
    6820            1 :                 Duration::ZERO,
    6821            1 :                 &CancellationToken::new(),
    6822            1 :                 &ctx,
    6823            1 :             )
    6824            1 :             .await?;
    6825              : 
    6826              :         // The branchpoints should contain all timelines, even ones marked
    6827              :         // as Broken.
    6828              :         {
    6829            1 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6830            1 :             assert_eq!(branchpoints.len(), 1);
    6831            1 :             assert_eq!(
    6832            1 :                 branchpoints[0],
    6833              :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6834              :             );
    6835              :         }
    6836              : 
    6837              :         // You can read the key from the child branch even though the parent is
    6838              :         // Broken, as long as you don't need to access data from the parent.
    6839            1 :         assert_eq!(
    6840            1 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6841            1 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6842              :         );
    6843              : 
    6844              :         // This needs to traverse to the parent, and fails.
    6845            1 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6846            1 :         assert!(
    6847            1 :             err.to_string().starts_with(&format!(
    6848            1 :                 "bad state on timeline {}: Broken",
    6849            1 :                 tline.timeline_id
    6850            1 :             )),
    6851            0 :             "{err}"
    6852              :         );
    6853              : 
    6854            2 :         Ok(())
    6855            1 :     }
    6856              : 
    6857              :     #[tokio::test]
    6858            1 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6859            1 :         let (tenant, ctx) =
    6860            1 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6861            1 :                 .await?
    6862            1 :                 .load()
    6863            1 :                 .await;
    6864            1 :         let tline = tenant
    6865            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6866            1 :             .await?;
    6867            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6868              : 
    6869            1 :         tenant
    6870            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6871            1 :             .await?;
    6872            1 :         let newtline = tenant
    6873            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6874            1 :             .expect("Should have a local timeline");
    6875              :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6876            1 :         tenant
    6877            1 :             .gc_iteration(
    6878            1 :                 Some(TIMELINE_ID),
    6879            1 :                 0x10,
    6880            1 :                 Duration::ZERO,
    6881            1 :                 &CancellationToken::new(),
    6882            1 :                 &ctx,
    6883            1 :             )
    6884            1 :             .await?;
    6885            1 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6886              : 
    6887            2 :         Ok(())
    6888            1 :     }
    6889              :     #[tokio::test]
    6890            1 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6891            1 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6892            1 :             .await?
    6893            1 :             .load()
    6894            1 :             .await;
    6895            1 :         let tline = tenant
    6896            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6897            1 :             .await?;
    6898            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6899              : 
    6900            1 :         tenant
    6901            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6902            1 :             .await?;
    6903            1 :         let newtline = tenant
    6904            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6905            1 :             .expect("Should have a local timeline");
    6906              : 
    6907            1 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6908              : 
    6909              :         // run gc on parent
    6910            1 :         tenant
    6911            1 :             .gc_iteration(
    6912            1 :                 Some(TIMELINE_ID),
    6913            1 :                 0x10,
    6914            1 :                 Duration::ZERO,
    6915            1 :                 &CancellationToken::new(),
    6916            1 :                 &ctx,
    6917            1 :             )
    6918            1 :             .await?;
    6919              : 
    6920              :         // Check that the data is still accessible on the branch.
    6921            1 :         assert_eq!(
    6922            1 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6923            1 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6924              :         );
    6925              : 
    6926            2 :         Ok(())
    6927            1 :     }
    6928              : 
    6929              :     #[tokio::test]
    6930            1 :     async fn timeline_load() -> anyhow::Result<()> {
    6931              :         const TEST_NAME: &str = "timeline_load";
    6932            1 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6933              :         {
    6934            1 :             let (tenant, ctx) = harness.load().await;
    6935            1 :             let tline = tenant
    6936            1 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6937            1 :                 .await?;
    6938            1 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6939              :             // so that all uploads finish & we can call harness.load() below again
    6940            1 :             tenant
    6941            1 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6942            1 :                 .instrument(harness.span())
    6943            1 :                 .await
    6944            1 :                 .ok()
    6945            1 :                 .unwrap();
    6946              :         }
    6947              : 
    6948            1 :         let (tenant, _ctx) = harness.load().await;
    6949            1 :         tenant
    6950            1 :             .get_timeline(TIMELINE_ID, true)
    6951            1 :             .expect("cannot load timeline");
    6952              : 
    6953            2 :         Ok(())
    6954            1 :     }
    6955              : 
    6956              :     #[tokio::test]
    6957            1 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6958              :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6959            1 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6960              :         // create two timelines
    6961              :         {
    6962            1 :             let (tenant, ctx) = harness.load().await;
    6963            1 :             let tline = tenant
    6964            1 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6965            1 :                 .await?;
    6966              : 
    6967            1 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6968              : 
    6969            1 :             let child_tline = tenant
    6970            1 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6971            1 :                 .await?;
    6972            1 :             child_tline.set_state(TimelineState::Active);
    6973              : 
    6974            1 :             let newtline = tenant
    6975            1 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6976            1 :                 .expect("Should have a local timeline");
    6977              : 
    6978            1 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6979              : 
    6980              :             // so that all uploads finish & we can call harness.load() below again
    6981            1 :             tenant
    6982            1 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6983            1 :                 .instrument(harness.span())
    6984            1 :                 .await
    6985            1 :                 .ok()
    6986            1 :                 .unwrap();
    6987              :         }
    6988              : 
    6989              :         // check that both of them are initially unloaded
    6990            1 :         let (tenant, _ctx) = harness.load().await;
    6991              : 
    6992              :         // check that both, child and ancestor are loaded
    6993            1 :         let _child_tline = tenant
    6994            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6995            1 :             .expect("cannot get child timeline loaded");
    6996              : 
    6997            1 :         let _ancestor_tline = tenant
    6998            1 :             .get_timeline(TIMELINE_ID, true)
    6999            1 :             .expect("cannot get ancestor timeline loaded");
    7000              : 
    7001            2 :         Ok(())
    7002            1 :     }
    7003              : 
    7004              :     #[tokio::test]
    7005            1 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    7006              :         use storage_layer::AsLayerDesc;
    7007            1 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    7008            1 :             .await?
    7009            1 :             .load()
    7010            1 :             .await;
    7011            1 :         let tline = tenant
    7012            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7013            1 :             .await?;
    7014            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    7015              : 
    7016            1 :         let layer_map = tline.layers.read(LayerManagerLockHolder::Testing).await;
    7017            1 :         let level0_deltas = layer_map
    7018            1 :             .layer_map()?
    7019            1 :             .level0_deltas()
    7020            1 :             .iter()
    7021            2 :             .map(|desc| layer_map.get_from_desc(desc))
    7022            1 :             .collect::<Vec<_>>();
    7023              : 
    7024            1 :         assert!(!level0_deltas.is_empty());
    7025              : 
    7026            3 :         for delta in level0_deltas {
    7027            1 :             // Ensure we are dumping a delta layer here
    7028            2 :             assert!(delta.layer_desc().is_delta);
    7029            2 :             delta.dump(true, &ctx).await.unwrap();
    7030            1 :         }
    7031            1 : 
    7032            1 :         Ok(())
    7033            1 :     }
    7034              : 
    7035              :     #[tokio::test]
    7036            1 :     async fn test_images() -> anyhow::Result<()> {
    7037            1 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    7038            1 :         let tline = tenant
    7039            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7040            1 :             .await?;
    7041              : 
    7042            1 :         let mut writer = tline.writer().await;
    7043            1 :         writer
    7044            1 :             .put(
    7045            1 :                 *TEST_KEY,
    7046            1 :                 Lsn(0x10),
    7047            1 :                 &Value::Image(test_img("foo at 0x10")),
    7048            1 :                 &ctx,
    7049            1 :             )
    7050            1 :             .await?;
    7051            1 :         writer.finish_write(Lsn(0x10));
    7052            1 :         drop(writer);
    7053              : 
    7054            1 :         tline.freeze_and_flush().await?;
    7055            1 :         tline
    7056            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7057            1 :             .await?;
    7058              : 
    7059            1 :         let mut writer = tline.writer().await;
    7060            1 :         writer
    7061            1 :             .put(
    7062            1 :                 *TEST_KEY,
    7063            1 :                 Lsn(0x20),
    7064            1 :                 &Value::Image(test_img("foo at 0x20")),
    7065            1 :                 &ctx,
    7066            1 :             )
    7067            1 :             .await?;
    7068            1 :         writer.finish_write(Lsn(0x20));
    7069            1 :         drop(writer);
    7070              : 
    7071            1 :         tline.freeze_and_flush().await?;
    7072            1 :         tline
    7073            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7074            1 :             .await?;
    7075              : 
    7076            1 :         let mut writer = tline.writer().await;
    7077            1 :         writer
    7078            1 :             .put(
    7079            1 :                 *TEST_KEY,
    7080            1 :                 Lsn(0x30),
    7081            1 :                 &Value::Image(test_img("foo at 0x30")),
    7082            1 :                 &ctx,
    7083            1 :             )
    7084            1 :             .await?;
    7085            1 :         writer.finish_write(Lsn(0x30));
    7086            1 :         drop(writer);
    7087              : 
    7088            1 :         tline.freeze_and_flush().await?;
    7089            1 :         tline
    7090            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7091            1 :             .await?;
    7092              : 
    7093            1 :         let mut writer = tline.writer().await;
    7094            1 :         writer
    7095            1 :             .put(
    7096            1 :                 *TEST_KEY,
    7097            1 :                 Lsn(0x40),
    7098            1 :                 &Value::Image(test_img("foo at 0x40")),
    7099            1 :                 &ctx,
    7100            1 :             )
    7101            1 :             .await?;
    7102            1 :         writer.finish_write(Lsn(0x40));
    7103            1 :         drop(writer);
    7104              : 
    7105            1 :         tline.freeze_and_flush().await?;
    7106            1 :         tline
    7107            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7108            1 :             .await?;
    7109              : 
    7110            1 :         assert_eq!(
    7111            1 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    7112            1 :             test_img("foo at 0x10")
    7113              :         );
    7114            1 :         assert_eq!(
    7115            1 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    7116            1 :             test_img("foo at 0x10")
    7117              :         );
    7118            1 :         assert_eq!(
    7119            1 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    7120            1 :             test_img("foo at 0x20")
    7121              :         );
    7122            1 :         assert_eq!(
    7123            1 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    7124            1 :             test_img("foo at 0x30")
    7125              :         );
    7126            1 :         assert_eq!(
    7127            1 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    7128            1 :             test_img("foo at 0x40")
    7129              :         );
    7130              : 
    7131            2 :         Ok(())
    7132            1 :     }
    7133              : 
    7134            2 :     async fn bulk_insert_compact_gc(
    7135            2 :         tenant: &TenantShard,
    7136            2 :         timeline: &Arc<Timeline>,
    7137            2 :         ctx: &RequestContext,
    7138            2 :         lsn: Lsn,
    7139            2 :         repeat: usize,
    7140            2 :         key_count: usize,
    7141            2 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    7142            2 :         let compact = true;
    7143            2 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    7144            2 :     }
    7145              : 
    7146            4 :     async fn bulk_insert_maybe_compact_gc(
    7147            4 :         tenant: &TenantShard,
    7148            4 :         timeline: &Arc<Timeline>,
    7149            4 :         ctx: &RequestContext,
    7150            4 :         mut lsn: Lsn,
    7151            4 :         repeat: usize,
    7152            4 :         key_count: usize,
    7153            4 :         compact: bool,
    7154            4 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    7155            4 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    7156              : 
    7157            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7158            4 :         let mut blknum = 0;
    7159              : 
    7160              :         // Enforce that key range is monotonously increasing
    7161            4 :         let mut keyspace = KeySpaceAccum::new();
    7162              : 
    7163            4 :         let cancel = CancellationToken::new();
    7164              : 
    7165            4 :         for _ in 0..repeat {
    7166          200 :             for _ in 0..key_count {
    7167      2000000 :                 test_key.field6 = blknum;
    7168      2000000 :                 let mut writer = timeline.writer().await;
    7169      2000000 :                 writer
    7170      2000000 :                     .put(
    7171      2000000 :                         test_key,
    7172      2000000 :                         lsn,
    7173      2000000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7174      2000000 :                         ctx,
    7175      2000000 :                     )
    7176      2000000 :                     .await?;
    7177      2000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    7178      2000000 :                 writer.finish_write(lsn);
    7179      2000000 :                 drop(writer);
    7180              : 
    7181      2000000 :                 keyspace.add_key(test_key);
    7182              : 
    7183      2000000 :                 lsn = Lsn(lsn.0 + 0x10);
    7184      2000000 :                 blknum += 1;
    7185              :             }
    7186              : 
    7187          200 :             timeline.freeze_and_flush().await?;
    7188          200 :             if compact {
    7189              :                 // this requires timeline to be &Arc<Timeline>
    7190          100 :                 timeline.compact(&cancel, EnumSet::default(), ctx).await?;
    7191          100 :             }
    7192              : 
    7193              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    7194              :             // originally was.
    7195          200 :             let res = tenant
    7196          200 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    7197          200 :                 .await?;
    7198              : 
    7199          200 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    7200              :         }
    7201              : 
    7202            4 :         Ok(inserted)
    7203            4 :     }
    7204              : 
    7205              :     //
    7206              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    7207              :     // Repeat 50 times.
    7208              :     //
    7209              :     #[tokio::test]
    7210            1 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    7211            1 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    7212            1 :         let (tenant, ctx) = harness.load().await;
    7213            1 :         let tline = tenant
    7214            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7215            1 :             .await?;
    7216              : 
    7217            1 :         let lsn = Lsn(0x10);
    7218            1 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7219              : 
    7220            2 :         Ok(())
    7221            1 :     }
    7222              : 
    7223              :     // Test the vectored get real implementation against a simple sequential implementation.
    7224              :     //
    7225              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    7226              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    7227              :     // grow to the right on the X axis.
    7228              :     //                       [Delta]
    7229              :     //                 [Delta]
    7230              :     //           [Delta]
    7231              :     //    [Delta]
    7232              :     // ------------ Image ---------------
    7233              :     //
    7234              :     // After layer generation we pick the ranges to query as follows:
    7235              :     // 1. The beginning of each delta layer
    7236              :     // 2. At the seam between two adjacent delta layers
    7237              :     //
    7238              :     // There's one major downside to this test: delta layers only contains images,
    7239              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    7240              :     #[tokio::test]
    7241            1 :     async fn test_get_vectored() -> anyhow::Result<()> {
    7242            1 :         let harness = TenantHarness::create("test_get_vectored").await?;
    7243            1 :         let (tenant, ctx) = harness.load().await;
    7244            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7245            1 :         let tline = tenant
    7246            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7247            1 :             .await?;
    7248              : 
    7249            1 :         let lsn = Lsn(0x10);
    7250            1 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7251              : 
    7252            1 :         let guard = tline.layers.read(LayerManagerLockHolder::Testing).await;
    7253            1 :         let lm = guard.layer_map()?;
    7254              : 
    7255            1 :         lm.dump(true, &ctx).await?;
    7256              : 
    7257            1 :         let mut reads = Vec::new();
    7258            1 :         let mut prev = None;
    7259            6 :         lm.iter_historic_layers().for_each(|desc| {
    7260            6 :             if !desc.is_delta() {
    7261            1 :                 prev = Some(desc.clone());
    7262            1 :                 return;
    7263            5 :             }
    7264              : 
    7265            5 :             let start = desc.key_range.start;
    7266            5 :             let end = desc
    7267            5 :                 .key_range
    7268            5 :                 .start
    7269            5 :                 .add(tenant.conf.max_get_vectored_keys.get() as u32);
    7270            5 :             reads.push(KeySpace {
    7271            5 :                 ranges: vec![start..end],
    7272            5 :             });
    7273              : 
    7274            5 :             if let Some(prev) = &prev {
    7275            5 :                 if !prev.is_delta() {
    7276            5 :                     return;
    7277            0 :                 }
    7278              : 
    7279            0 :                 let first_range = Key {
    7280            0 :                     field6: prev.key_range.end.field6 - 4,
    7281            0 :                     ..prev.key_range.end
    7282            0 :                 }..prev.key_range.end;
    7283              : 
    7284            0 :                 let second_range = desc.key_range.start..Key {
    7285            0 :                     field6: desc.key_range.start.field6 + 4,
    7286            0 :                     ..desc.key_range.start
    7287            0 :                 };
    7288              : 
    7289            0 :                 reads.push(KeySpace {
    7290            0 :                     ranges: vec![first_range, second_range],
    7291            0 :                 });
    7292            0 :             };
    7293              : 
    7294            0 :             prev = Some(desc.clone());
    7295            6 :         });
    7296              : 
    7297            1 :         drop(guard);
    7298              : 
    7299              :         // Pick a big LSN such that we query over all the changes.
    7300            1 :         let reads_lsn = Lsn(u64::MAX - 1);
    7301              : 
    7302            6 :         for read in reads {
    7303            5 :             info!("Doing vectored read on {:?}", read);
    7304            1 : 
    7305            5 :             let query = VersionedKeySpaceQuery::uniform(read.clone(), reads_lsn);
    7306            1 : 
    7307            5 :             let vectored_res = tline
    7308            5 :                 .get_vectored_impl(
    7309            5 :                     query,
    7310            5 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7311            5 :                     &ctx,
    7312            5 :                 )
    7313            5 :                 .await;
    7314            1 : 
    7315            5 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    7316            5 :             let mut expect_missing = false;
    7317            5 :             let mut key = read.start().unwrap();
    7318          165 :             while key != read.end().unwrap() {
    7319          160 :                 if let Some(lsns) = inserted.get(&key) {
    7320          160 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    7321          160 :                     match expected_lsn {
    7322          160 :                         Some(lsn) => {
    7323          160 :                             expected_lsns.insert(key, *lsn);
    7324          160 :                         }
    7325            1 :                         None => {
    7326            1 :                             expect_missing = true;
    7327            1 :                             break;
    7328            1 :                         }
    7329            1 :                     }
    7330            1 :                 } else {
    7331            1 :                     expect_missing = true;
    7332            1 :                     break;
    7333            1 :                 }
    7334            1 : 
    7335          160 :                 key = key.next();
    7336            1 :             }
    7337            1 : 
    7338            5 :             if expect_missing {
    7339            1 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    7340            1 :             } else {
    7341          160 :                 for (key, image) in vectored_res? {
    7342          160 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    7343          160 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    7344          160 :                     assert_eq!(image?, expected_image);
    7345            1 :                 }
    7346            1 :             }
    7347            1 :         }
    7348            1 : 
    7349            1 :         Ok(())
    7350            1 :     }
    7351              : 
    7352              :     #[tokio::test]
    7353            1 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    7354            1 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    7355              : 
    7356            1 :         let (tenant, ctx) = harness.load().await;
    7357            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7358            1 :         let (tline, ctx) = tenant
    7359            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7360            1 :             .await?;
    7361            1 :         let tline = tline.raw_timeline().unwrap();
    7362              : 
    7363            1 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    7364            1 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    7365            1 :         modification.set_lsn(Lsn(0x1008))?;
    7366            1 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    7367            1 :         modification.commit(&ctx).await?;
    7368              : 
    7369            1 :         let child_timeline_id = TimelineId::generate();
    7370            1 :         tenant
    7371            1 :             .branch_timeline_test(
    7372            1 :                 tline,
    7373            1 :                 child_timeline_id,
    7374            1 :                 Some(tline.get_last_record_lsn()),
    7375            1 :                 &ctx,
    7376            1 :             )
    7377            1 :             .await?;
    7378              : 
    7379            1 :         let child_timeline = tenant
    7380            1 :             .get_timeline(child_timeline_id, true)
    7381            1 :             .expect("Should have the branched timeline");
    7382              : 
    7383            1 :         let aux_keyspace = KeySpace {
    7384            1 :             ranges: vec![NON_INHERITED_RANGE],
    7385            1 :         };
    7386            1 :         let read_lsn = child_timeline.get_last_record_lsn();
    7387              : 
    7388            1 :         let query = VersionedKeySpaceQuery::uniform(aux_keyspace.clone(), read_lsn);
    7389              : 
    7390            1 :         let vectored_res = child_timeline
    7391            1 :             .get_vectored_impl(
    7392            1 :                 query,
    7393            1 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7394            1 :                 &ctx,
    7395            1 :             )
    7396            1 :             .await;
    7397              : 
    7398            1 :         let images = vectored_res?;
    7399            1 :         assert!(images.is_empty());
    7400            2 :         Ok(())
    7401            1 :     }
    7402              : 
    7403              :     // Test that vectored get handles layer gaps correctly
    7404              :     // by advancing into the next ancestor timeline if required.
    7405              :     //
    7406              :     // The test generates timelines that look like the diagram below.
    7407              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    7408              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    7409              :     //
    7410              :     // ```
    7411              :     //-------------------------------+
    7412              :     //                          ...  |
    7413              :     //               [   L1   ]      |
    7414              :     //     [ / L1   ]                | Child Timeline
    7415              :     // ...                           |
    7416              :     // ------------------------------+
    7417              :     //     [ X L1   ]                | Parent Timeline
    7418              :     // ------------------------------+
    7419              :     // ```
    7420              :     #[tokio::test]
    7421            1 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    7422            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
    7423            1 :             // Make compaction deterministic
    7424            1 :             gc_period: Some(Duration::ZERO),
    7425            1 :             compaction_period: Some(Duration::ZERO),
    7426            1 :             // Encourage creation of L1 layers
    7427            1 :             checkpoint_distance: Some(16 * 1024),
    7428            1 :             compaction_target_size: Some(8 * 1024),
    7429            1 :             ..Default::default()
    7430            1 :         };
    7431              : 
    7432            1 :         let harness = TenantHarness::create_custom(
    7433            1 :             "test_get_vectored_key_gap",
    7434            1 :             tenant_conf,
    7435            1 :             TenantId::generate(),
    7436            1 :             ShardIdentity::unsharded(),
    7437            1 :             Generation::new(0xdeadbeef),
    7438            1 :         )
    7439            1 :         .await?;
    7440            1 :         let (tenant, ctx) = harness.load().await;
    7441            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7442              : 
    7443            1 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7444            1 :         let gap_at_key = current_key.add(100);
    7445            1 :         let mut current_lsn = Lsn(0x10);
    7446              : 
    7447              :         const KEY_COUNT: usize = 10_000;
    7448              : 
    7449            1 :         let timeline_id = TimelineId::generate();
    7450            1 :         let current_timeline = tenant
    7451            1 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7452            1 :             .await?;
    7453              : 
    7454            1 :         current_lsn += 0x100;
    7455              : 
    7456            1 :         let mut writer = current_timeline.writer().await;
    7457            1 :         writer
    7458            1 :             .put(
    7459            1 :                 gap_at_key,
    7460            1 :                 current_lsn,
    7461            1 :                 &Value::Image(test_img(&format!("{gap_at_key} at {current_lsn}"))),
    7462            1 :                 &ctx,
    7463            1 :             )
    7464            1 :             .await?;
    7465            1 :         writer.finish_write(current_lsn);
    7466            1 :         drop(writer);
    7467              : 
    7468            1 :         let mut latest_lsns = HashMap::new();
    7469            1 :         latest_lsns.insert(gap_at_key, current_lsn);
    7470              : 
    7471            1 :         current_timeline.freeze_and_flush().await?;
    7472              : 
    7473            1 :         let child_timeline_id = TimelineId::generate();
    7474              : 
    7475            1 :         tenant
    7476            1 :             .branch_timeline_test(
    7477            1 :                 &current_timeline,
    7478            1 :                 child_timeline_id,
    7479            1 :                 Some(current_lsn),
    7480            1 :                 &ctx,
    7481            1 :             )
    7482            1 :             .await?;
    7483            1 :         let child_timeline = tenant
    7484            1 :             .get_timeline(child_timeline_id, true)
    7485            1 :             .expect("Should have the branched timeline");
    7486              : 
    7487        10001 :         for i in 0..KEY_COUNT {
    7488        10000 :             if current_key == gap_at_key {
    7489            1 :                 current_key = current_key.next();
    7490            1 :                 continue;
    7491         9999 :             }
    7492              : 
    7493         9999 :             current_lsn += 0x10;
    7494              : 
    7495         9999 :             let mut writer = child_timeline.writer().await;
    7496         9999 :             writer
    7497         9999 :                 .put(
    7498         9999 :                     current_key,
    7499         9999 :                     current_lsn,
    7500         9999 :                     &Value::Image(test_img(&format!("{current_key} at {current_lsn}"))),
    7501         9999 :                     &ctx,
    7502         9999 :                 )
    7503         9999 :                 .await?;
    7504         9999 :             writer.finish_write(current_lsn);
    7505         9999 :             drop(writer);
    7506              : 
    7507         9999 :             latest_lsns.insert(current_key, current_lsn);
    7508         9999 :             current_key = current_key.next();
    7509              : 
    7510              :             // Flush every now and then to encourage layer file creation.
    7511         9999 :             if i % 500 == 0 {
    7512           20 :                 child_timeline.freeze_and_flush().await?;
    7513         9979 :             }
    7514              :         }
    7515              : 
    7516            1 :         child_timeline.freeze_and_flush().await?;
    7517            1 :         let mut flags = EnumSet::new();
    7518            1 :         flags.insert(CompactFlags::ForceRepartition);
    7519            1 :         child_timeline
    7520            1 :             .compact(&CancellationToken::new(), flags, &ctx)
    7521            1 :             .await?;
    7522              : 
    7523            1 :         let key_near_end = {
    7524            1 :             let mut tmp = current_key;
    7525            1 :             tmp.field6 -= 10;
    7526            1 :             tmp
    7527              :         };
    7528              : 
    7529            1 :         let key_near_gap = {
    7530            1 :             let mut tmp = gap_at_key;
    7531            1 :             tmp.field6 -= 10;
    7532            1 :             tmp
    7533              :         };
    7534              : 
    7535            1 :         let read = KeySpace {
    7536            1 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    7537            1 :         };
    7538              : 
    7539            1 :         let query = VersionedKeySpaceQuery::uniform(read.clone(), current_lsn);
    7540              : 
    7541            1 :         let results = child_timeline
    7542            1 :             .get_vectored_impl(
    7543            1 :                 query,
    7544            1 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7545            1 :                 &ctx,
    7546            1 :             )
    7547            1 :             .await?;
    7548              : 
    7549           22 :         for (key, img_res) in results {
    7550           21 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    7551           21 :             assert_eq!(img_res?, expected);
    7552            1 :         }
    7553            1 : 
    7554            1 :         Ok(())
    7555            1 :     }
    7556              : 
    7557              :     // Test that vectored get descends into ancestor timelines correctly and
    7558              :     // does not return an image that's newer than requested.
    7559              :     //
    7560              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    7561              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    7562              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    7563              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    7564              :     // order to avoid returning an image that's too new. The test below constructs such
    7565              :     // a timeline setup and does a few queries around the Lsn of each page image.
    7566              :     // ```
    7567              :     //    LSN
    7568              :     //     ^
    7569              :     //     |
    7570              :     //     |
    7571              :     // 500 | --------------------------------------> branch point
    7572              :     // 400 |        X
    7573              :     // 300 |        X
    7574              :     // 200 | --------------------------------------> requested lsn
    7575              :     // 100 |        X
    7576              :     //     |---------------------------------------> Key
    7577              :     //              |
    7578              :     //              ------> requested key
    7579              :     //
    7580              :     // Legend:
    7581              :     // * X - page images
    7582              :     // ```
    7583              :     #[tokio::test]
    7584            1 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7585            1 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7586            1 :         let (tenant, ctx) = harness.load().await;
    7587            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7588              : 
    7589            1 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7590            1 :         let end_key = start_key.add(1000);
    7591            1 :         let child_gap_at_key = start_key.add(500);
    7592            1 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7593              : 
    7594            1 :         let mut current_lsn = Lsn(0x10);
    7595              : 
    7596            1 :         let timeline_id = TimelineId::generate();
    7597            1 :         let parent_timeline = tenant
    7598            1 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7599            1 :             .await?;
    7600              : 
    7601            1 :         current_lsn += 0x100;
    7602              : 
    7603            4 :         for _ in 0..3 {
    7604            3 :             let mut key = start_key;
    7605         3003 :             while key < end_key {
    7606         3000 :                 current_lsn += 0x10;
    7607              : 
    7608         3000 :                 let image_value = format!("{child_gap_at_key} at {current_lsn}");
    7609              : 
    7610         3000 :                 let mut writer = parent_timeline.writer().await;
    7611         3000 :                 writer
    7612         3000 :                     .put(
    7613         3000 :                         key,
    7614         3000 :                         current_lsn,
    7615         3000 :                         &Value::Image(test_img(&image_value)),
    7616         3000 :                         &ctx,
    7617         3000 :                     )
    7618         3000 :                     .await?;
    7619         3000 :                 writer.finish_write(current_lsn);
    7620              : 
    7621         3000 :                 if key == child_gap_at_key {
    7622            3 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7623         2997 :                 }
    7624              : 
    7625         3000 :                 key = key.next();
    7626              :             }
    7627              : 
    7628            3 :             parent_timeline.freeze_and_flush().await?;
    7629              :         }
    7630              : 
    7631            1 :         let child_timeline_id = TimelineId::generate();
    7632              : 
    7633            1 :         let child_timeline = tenant
    7634            1 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7635            1 :             .await?;
    7636              : 
    7637            1 :         let mut key = start_key;
    7638         1001 :         while key < end_key {
    7639         1000 :             if key == child_gap_at_key {
    7640            1 :                 key = key.next();
    7641            1 :                 continue;
    7642          999 :             }
    7643              : 
    7644          999 :             current_lsn += 0x10;
    7645              : 
    7646          999 :             let mut writer = child_timeline.writer().await;
    7647          999 :             writer
    7648          999 :                 .put(
    7649          999 :                     key,
    7650          999 :                     current_lsn,
    7651          999 :                     &Value::Image(test_img(&format!("{key} at {current_lsn}"))),
    7652          999 :                     &ctx,
    7653          999 :                 )
    7654          999 :                 .await?;
    7655          999 :             writer.finish_write(current_lsn);
    7656              : 
    7657          999 :             key = key.next();
    7658              :         }
    7659              : 
    7660            1 :         child_timeline.freeze_and_flush().await?;
    7661              : 
    7662            1 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7663            1 :         let mut query_lsns = Vec::new();
    7664            3 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7665           18 :             for offset in lsn_offsets {
    7666           15 :                 query_lsns.push(Lsn(image_lsn
    7667           15 :                     .0
    7668           15 :                     .checked_add_signed(offset)
    7669           15 :                     .expect("Shouldn't overflow")));
    7670           15 :             }
    7671            1 :         }
    7672            1 : 
    7673           16 :         for query_lsn in query_lsns {
    7674           15 :             let query = VersionedKeySpaceQuery::uniform(
    7675           15 :                 KeySpace {
    7676           15 :                     ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7677           15 :                 },
    7678           15 :                 query_lsn,
    7679            1 :             );
    7680            1 : 
    7681           15 :             let results = child_timeline
    7682           15 :                 .get_vectored_impl(
    7683           15 :                     query,
    7684           15 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7685           15 :                     &ctx,
    7686           15 :                 )
    7687           15 :                 .await;
    7688            1 : 
    7689           15 :             let expected_item = parent_gap_lsns
    7690           15 :                 .iter()
    7691           15 :                 .rev()
    7692           34 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7693            1 : 
    7694           15 :             info!(
    7695            1 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7696            1 :                 query_lsn, expected_item
    7697            1 :             );
    7698            1 : 
    7699           15 :             match expected_item {
    7700           13 :                 Some((_, img_value)) => {
    7701           13 :                     let key_results = results.expect("No vectored get error expected");
    7702           13 :                     let key_result = &key_results[&child_gap_at_key];
    7703           13 :                     let returned_img = key_result
    7704           13 :                         .as_ref()
    7705           13 :                         .expect("No page reconstruct error expected");
    7706            1 : 
    7707           13 :                     info!(
    7708            1 :                         "Vectored read at LSN {} returned image {}",
    7709            1 :                         query_lsn,
    7710            1 :                         std::str::from_utf8(returned_img)?
    7711            1 :                     );
    7712           13 :                     assert_eq!(*returned_img, test_img(img_value));
    7713            1 :                 }
    7714            1 :                 None => {
    7715            2 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7716            1 :                 }
    7717            1 :             }
    7718            1 :         }
    7719            1 : 
    7720            1 :         Ok(())
    7721            1 :     }
    7722              : 
    7723              :     #[tokio::test]
    7724            1 :     async fn test_random_updates() -> anyhow::Result<()> {
    7725            1 :         let names_algorithms = [
    7726            1 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7727            1 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7728            1 :         ];
    7729            3 :         for (name, algorithm) in names_algorithms {
    7730            2 :             test_random_updates_algorithm(name, algorithm).await?;
    7731            1 :         }
    7732            1 :         Ok(())
    7733            1 :     }
    7734              : 
    7735            2 :     async fn test_random_updates_algorithm(
    7736            2 :         name: &'static str,
    7737            2 :         compaction_algorithm: CompactionAlgorithm,
    7738            2 :     ) -> anyhow::Result<()> {
    7739            2 :         let mut harness = TenantHarness::create(name).await?;
    7740            2 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    7741            2 :             kind: compaction_algorithm,
    7742            2 :         });
    7743            2 :         let (tenant, ctx) = harness.load().await;
    7744            2 :         let tline = tenant
    7745            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7746            2 :             .await?;
    7747              : 
    7748              :         const NUM_KEYS: usize = 1000;
    7749            2 :         let cancel = CancellationToken::new();
    7750              : 
    7751            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7752            2 :         let mut test_key_end = test_key;
    7753            2 :         test_key_end.field6 = NUM_KEYS as u32;
    7754            2 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7755              : 
    7756            2 :         let mut keyspace = KeySpaceAccum::new();
    7757              : 
    7758              :         // Track when each page was last modified. Used to assert that
    7759              :         // a read sees the latest page version.
    7760            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    7761              : 
    7762            2 :         let mut lsn = Lsn(0x10);
    7763              :         #[allow(clippy::needless_range_loop)]
    7764         2002 :         for blknum in 0..NUM_KEYS {
    7765         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7766         2000 :             test_key.field6 = blknum as u32;
    7767         2000 :             let mut writer = tline.writer().await;
    7768         2000 :             writer
    7769         2000 :                 .put(
    7770         2000 :                     test_key,
    7771         2000 :                     lsn,
    7772         2000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7773         2000 :                     &ctx,
    7774         2000 :                 )
    7775         2000 :                 .await?;
    7776         2000 :             writer.finish_write(lsn);
    7777         2000 :             updated[blknum] = lsn;
    7778         2000 :             drop(writer);
    7779              : 
    7780         2000 :             keyspace.add_key(test_key);
    7781              :         }
    7782              : 
    7783          102 :         for _ in 0..50 {
    7784       100100 :             for _ in 0..NUM_KEYS {
    7785       100000 :                 lsn = Lsn(lsn.0 + 0x10);
    7786       100000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7787       100000 :                 test_key.field6 = blknum as u32;
    7788       100000 :                 let mut writer = tline.writer().await;
    7789       100000 :                 writer
    7790       100000 :                     .put(
    7791       100000 :                         test_key,
    7792       100000 :                         lsn,
    7793       100000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7794       100000 :                         &ctx,
    7795       100000 :                     )
    7796       100000 :                     .await?;
    7797       100000 :                 writer.finish_write(lsn);
    7798       100000 :                 drop(writer);
    7799       100000 :                 updated[blknum] = lsn;
    7800              :             }
    7801              : 
    7802              :             // Read all the blocks
    7803       100000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7804       100000 :                 test_key.field6 = blknum as u32;
    7805       100000 :                 assert_eq!(
    7806       100000 :                     tline.get(test_key, lsn, &ctx).await?,
    7807       100000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    7808              :                 );
    7809              :             }
    7810              : 
    7811              :             // Perform a cycle of flush, and GC
    7812          100 :             tline.freeze_and_flush().await?;
    7813          100 :             tenant
    7814          100 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7815          100 :                 .await?;
    7816              :         }
    7817              : 
    7818            2 :         Ok(())
    7819            2 :     }
    7820              : 
    7821              :     #[tokio::test]
    7822            1 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7823            1 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7824            1 :             .await?
    7825            1 :             .load()
    7826            1 :             .await;
    7827            1 :         let mut tline = tenant
    7828            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7829            1 :             .await?;
    7830              : 
    7831              :         const NUM_KEYS: usize = 1000;
    7832              : 
    7833            1 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7834              : 
    7835            1 :         let mut keyspace = KeySpaceAccum::new();
    7836              : 
    7837            1 :         let cancel = CancellationToken::new();
    7838              : 
    7839              :         // Track when each page was last modified. Used to assert that
    7840              :         // a read sees the latest page version.
    7841            1 :         let mut updated = [Lsn(0); NUM_KEYS];
    7842              : 
    7843            1 :         let mut lsn = Lsn(0x10);
    7844            1 :         #[allow(clippy::needless_range_loop)]
    7845         1001 :         for blknum in 0..NUM_KEYS {
    7846         1000 :             lsn = Lsn(lsn.0 + 0x10);
    7847         1000 :             test_key.field6 = blknum as u32;
    7848         1000 :             let mut writer = tline.writer().await;
    7849         1000 :             writer
    7850         1000 :                 .put(
    7851         1000 :                     test_key,
    7852         1000 :                     lsn,
    7853         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7854         1000 :                     &ctx,
    7855         1000 :                 )
    7856         1000 :                 .await?;
    7857         1000 :             writer.finish_write(lsn);
    7858         1000 :             updated[blknum] = lsn;
    7859         1000 :             drop(writer);
    7860            1 : 
    7861         1000 :             keyspace.add_key(test_key);
    7862            1 :         }
    7863            1 : 
    7864           51 :         for _ in 0..50 {
    7865           50 :             let new_tline_id = TimelineId::generate();
    7866           50 :             tenant
    7867           50 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7868           50 :                 .await?;
    7869           50 :             tline = tenant
    7870           50 :                 .get_timeline(new_tline_id, true)
    7871           50 :                 .expect("Should have the branched timeline");
    7872            1 : 
    7873        50050 :             for _ in 0..NUM_KEYS {
    7874        50000 :                 lsn = Lsn(lsn.0 + 0x10);
    7875        50000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7876        50000 :                 test_key.field6 = blknum as u32;
    7877        50000 :                 let mut writer = tline.writer().await;
    7878        50000 :                 writer
    7879        50000 :                     .put(
    7880        50000 :                         test_key,
    7881        50000 :                         lsn,
    7882        50000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7883        50000 :                         &ctx,
    7884        50000 :                     )
    7885        50000 :                     .await?;
    7886        50000 :                 println!("updating {blknum} at {lsn}");
    7887        50000 :                 writer.finish_write(lsn);
    7888        50000 :                 drop(writer);
    7889        50000 :                 updated[blknum] = lsn;
    7890            1 :             }
    7891            1 : 
    7892            1 :             // Read all the blocks
    7893        50000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7894        50000 :                 test_key.field6 = blknum as u32;
    7895        50000 :                 assert_eq!(
    7896        50000 :                     tline.get(test_key, lsn, &ctx).await?,
    7897        50000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    7898            1 :                 );
    7899            1 :             }
    7900            1 : 
    7901            1 :             // Perform a cycle of flush, compact, and GC
    7902           50 :             tline.freeze_and_flush().await?;
    7903           50 :             tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    7904           50 :             tenant
    7905           50 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7906           50 :                 .await?;
    7907            1 :         }
    7908            1 : 
    7909            1 :         Ok(())
    7910            1 :     }
    7911              : 
    7912              :     #[tokio::test]
    7913            1 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7914            1 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7915            1 :             .await?
    7916            1 :             .load()
    7917            1 :             .await;
    7918            1 :         let mut tline = tenant
    7919            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7920            1 :             .await?;
    7921              : 
    7922              :         const NUM_KEYS: usize = 100;
    7923              :         const NUM_TLINES: usize = 50;
    7924              : 
    7925            1 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7926              :         // Track page mutation lsns across different timelines.
    7927            1 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7928              : 
    7929            1 :         let mut lsn = Lsn(0x10);
    7930              : 
    7931            1 :         #[allow(clippy::needless_range_loop)]
    7932           51 :         for idx in 0..NUM_TLINES {
    7933           50 :             let new_tline_id = TimelineId::generate();
    7934           50 :             tenant
    7935           50 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7936           50 :                 .await?;
    7937           50 :             tline = tenant
    7938           50 :                 .get_timeline(new_tline_id, true)
    7939           50 :                 .expect("Should have the branched timeline");
    7940            1 : 
    7941         5050 :             for _ in 0..NUM_KEYS {
    7942         5000 :                 lsn = Lsn(lsn.0 + 0x10);
    7943         5000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7944         5000 :                 test_key.field6 = blknum as u32;
    7945         5000 :                 let mut writer = tline.writer().await;
    7946         5000 :                 writer
    7947         5000 :                     .put(
    7948         5000 :                         test_key,
    7949         5000 :                         lsn,
    7950         5000 :                         &Value::Image(test_img(&format!("{idx} {blknum} at {lsn}"))),
    7951         5000 :                         &ctx,
    7952         5000 :                     )
    7953         5000 :                     .await?;
    7954         5000 :                 println!("updating [{idx}][{blknum}] at {lsn}");
    7955         5000 :                 writer.finish_write(lsn);
    7956         5000 :                 drop(writer);
    7957         5000 :                 updated[idx][blknum] = lsn;
    7958            1 :             }
    7959            1 :         }
    7960            1 : 
    7961            1 :         // Read pages from leaf timeline across all ancestors.
    7962           50 :         for (idx, lsns) in updated.iter().enumerate() {
    7963         5000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7964            1 :                 // Skip empty mutations.
    7965         5000 :                 if lsn.0 == 0 {
    7966         1847 :                     continue;
    7967         3153 :                 }
    7968         3153 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7969         3153 :                 test_key.field6 = blknum as u32;
    7970         3153 :                 assert_eq!(
    7971         3153 :                     tline.get(test_key, *lsn, &ctx).await?,
    7972         3153 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7973            1 :                 );
    7974            1 :             }
    7975            1 :         }
    7976            1 :         Ok(())
    7977            1 :     }
    7978              : 
    7979              :     #[tokio::test]
    7980            1 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7981            1 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7982            1 :             .await?
    7983            1 :             .load()
    7984            1 :             .await;
    7985              : 
    7986            1 :         let initdb_lsn = Lsn(0x20);
    7987            1 :         let (utline, ctx) = tenant
    7988            1 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7989            1 :             .await?;
    7990            1 :         let tline = utline.raw_timeline().unwrap();
    7991              : 
    7992              :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7993            1 :         tline.maybe_spawn_flush_loop();
    7994              : 
    7995              :         // Make sure the timeline has the minimum set of required keys for operation.
    7996              :         // The only operation you can always do on an empty timeline is to `put` new data.
    7997              :         // Except if you `put` at `initdb_lsn`.
    7998              :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7999              :         // It uses `repartition()`, which assumes some keys to be present.
    8000              :         // Let's make sure the test timeline can handle that case.
    8001              :         {
    8002            1 :             let mut state = tline.flush_loop_state.lock().unwrap();
    8003            1 :             assert_eq!(
    8004              :                 timeline::FlushLoopState::Running {
    8005              :                     expect_initdb_optimization: false,
    8006              :                     initdb_optimization_count: 0,
    8007              :                 },
    8008            1 :                 *state
    8009              :             );
    8010            1 :             *state = timeline::FlushLoopState::Running {
    8011            1 :                 expect_initdb_optimization: true,
    8012            1 :                 initdb_optimization_count: 0,
    8013            1 :             };
    8014              :         }
    8015              : 
    8016              :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    8017              :         // As explained above, the optimization requires some keys to be present.
    8018              :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    8019              :         // This is what `create_test_timeline` does, by the way.
    8020            1 :         let mut modification = tline.begin_modification(initdb_lsn);
    8021            1 :         modification
    8022            1 :             .init_empty_test_timeline()
    8023            1 :             .context("init_empty_test_timeline")?;
    8024            1 :         modification
    8025            1 :             .commit(&ctx)
    8026            1 :             .await
    8027            1 :             .context("commit init_empty_test_timeline modification")?;
    8028              : 
    8029              :         // Do the flush. The flush code will check the expectations that we set above.
    8030            1 :         tline.freeze_and_flush().await?;
    8031              : 
    8032              :         // assert freeze_and_flush exercised the initdb optimization
    8033            1 :         {
    8034            1 :             let state = tline.flush_loop_state.lock().unwrap();
    8035            1 :             let timeline::FlushLoopState::Running {
    8036            1 :                 expect_initdb_optimization,
    8037            1 :                 initdb_optimization_count,
    8038            1 :             } = *state
    8039            1 :             else {
    8040            1 :                 panic!("unexpected state: {:?}", *state);
    8041            1 :             };
    8042            1 :             assert!(expect_initdb_optimization);
    8043            1 :             assert!(initdb_optimization_count > 0);
    8044            1 :         }
    8045            1 :         Ok(())
    8046            1 :     }
    8047              : 
    8048              :     #[tokio::test]
    8049            1 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    8050            1 :         let name = "test_create_guard_crash";
    8051            1 :         let harness = TenantHarness::create(name).await?;
    8052              :         {
    8053            1 :             let (tenant, ctx) = harness.load().await;
    8054            1 :             let (tline, _ctx) = tenant
    8055            1 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    8056            1 :                 .await?;
    8057              :             // Leave the timeline ID in [`TenantShard::timelines_creating`] to exclude attempting to create it again
    8058            1 :             let raw_tline = tline.raw_timeline().unwrap();
    8059            1 :             raw_tline
    8060            1 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    8061            1 :                 .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))
    8062            1 :                 .await;
    8063            1 :             std::mem::forget(tline);
    8064              :         }
    8065              : 
    8066            1 :         let (tenant, _) = harness.load().await;
    8067            1 :         match tenant.get_timeline(TIMELINE_ID, false) {
    8068            0 :             Ok(_) => panic!("timeline should've been removed during load"),
    8069            1 :             Err(e) => {
    8070            1 :                 assert_eq!(
    8071              :                     e,
    8072            1 :                     GetTimelineError::NotFound {
    8073            1 :                         tenant_id: tenant.tenant_shard_id,
    8074            1 :                         timeline_id: TIMELINE_ID,
    8075            1 :                     }
    8076              :                 )
    8077              :             }
    8078              :         }
    8079              : 
    8080            1 :         assert!(
    8081            1 :             !harness
    8082            1 :                 .conf
    8083            1 :                 .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    8084            1 :                 .exists()
    8085              :         );
    8086              : 
    8087            2 :         Ok(())
    8088            1 :     }
    8089              : 
    8090              :     #[tokio::test]
    8091            1 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    8092            1 :         let names_algorithms = [
    8093            1 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    8094            1 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    8095            1 :         ];
    8096            3 :         for (name, algorithm) in names_algorithms {
    8097            2 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    8098            1 :         }
    8099            1 :         Ok(())
    8100            1 :     }
    8101              : 
    8102            2 :     async fn test_read_at_max_lsn_algorithm(
    8103            2 :         name: &'static str,
    8104            2 :         compaction_algorithm: CompactionAlgorithm,
    8105            2 :     ) -> anyhow::Result<()> {
    8106            2 :         let mut harness = TenantHarness::create(name).await?;
    8107            2 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    8108            2 :             kind: compaction_algorithm,
    8109            2 :         });
    8110            2 :         let (tenant, ctx) = harness.load().await;
    8111            2 :         let tline = tenant
    8112            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    8113            2 :             .await?;
    8114              : 
    8115            2 :         let lsn = Lsn(0x10);
    8116            2 :         let compact = false;
    8117            2 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    8118              : 
    8119            2 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8120            2 :         let read_lsn = Lsn(u64::MAX - 1);
    8121              : 
    8122            2 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    8123            2 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    8124              : 
    8125            2 :         Ok(())
    8126            2 :     }
    8127              : 
    8128              :     #[tokio::test]
    8129            1 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    8130            1 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    8131            1 :         let (tenant, ctx) = harness.load().await;
    8132            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8133            1 :         let tline = tenant
    8134            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8135            1 :             .await?;
    8136              : 
    8137              :         const NUM_KEYS: usize = 1000;
    8138              :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8139              : 
    8140            1 :         let cancel = CancellationToken::new();
    8141              : 
    8142            1 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8143            1 :         base_key.field1 = AUX_KEY_PREFIX;
    8144            1 :         let mut test_key = base_key;
    8145              : 
    8146              :         // Track when each page was last modified. Used to assert that
    8147              :         // a read sees the latest page version.
    8148            1 :         let mut updated = [Lsn(0); NUM_KEYS];
    8149              : 
    8150            1 :         let mut lsn = Lsn(0x10);
    8151              :         #[allow(clippy::needless_range_loop)]
    8152         1001 :         for blknum in 0..NUM_KEYS {
    8153         1000 :             lsn = Lsn(lsn.0 + 0x10);
    8154         1000 :             test_key.field6 = (blknum * STEP) as u32;
    8155         1000 :             let mut writer = tline.writer().await;
    8156         1000 :             writer
    8157         1000 :                 .put(
    8158         1000 :                     test_key,
    8159         1000 :                     lsn,
    8160         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8161         1000 :                     &ctx,
    8162         1000 :                 )
    8163         1000 :                 .await?;
    8164         1000 :             writer.finish_write(lsn);
    8165         1000 :             updated[blknum] = lsn;
    8166         1000 :             drop(writer);
    8167              :         }
    8168              : 
    8169            1 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8170              : 
    8171           12 :         for iter in 0..=10 {
    8172            1 :             // Read all the blocks
    8173        11000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    8174        11000 :                 test_key.field6 = (blknum * STEP) as u32;
    8175        11000 :                 assert_eq!(
    8176        11000 :                     tline.get(test_key, lsn, &ctx).await?,
    8177        11000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    8178            1 :                 );
    8179            1 :             }
    8180            1 : 
    8181           11 :             let mut cnt = 0;
    8182           11 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8183            1 : 
    8184        11000 :             for (key, value) in tline
    8185           11 :                 .get_vectored_impl(
    8186           11 :                     query,
    8187           11 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    8188           11 :                     &ctx,
    8189           11 :                 )
    8190           11 :                 .await?
    8191            1 :             {
    8192        11000 :                 let blknum = key.field6 as usize;
    8193        11000 :                 let value = value?;
    8194        11000 :                 assert!(blknum % STEP == 0);
    8195        11000 :                 let blknum = blknum / STEP;
    8196        11000 :                 assert_eq!(
    8197            1 :                     value,
    8198        11000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    8199            1 :                 );
    8200        11000 :                 cnt += 1;
    8201            1 :             }
    8202            1 : 
    8203           11 :             assert_eq!(cnt, NUM_KEYS);
    8204            1 : 
    8205        11011 :             for _ in 0..NUM_KEYS {
    8206        11000 :                 lsn = Lsn(lsn.0 + 0x10);
    8207        11000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8208        11000 :                 test_key.field6 = (blknum * STEP) as u32;
    8209        11000 :                 let mut writer = tline.writer().await;
    8210        11000 :                 writer
    8211        11000 :                     .put(
    8212        11000 :                         test_key,
    8213        11000 :                         lsn,
    8214        11000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8215        11000 :                         &ctx,
    8216        11000 :                     )
    8217        11000 :                     .await?;
    8218        11000 :                 writer.finish_write(lsn);
    8219        11000 :                 drop(writer);
    8220        11000 :                 updated[blknum] = lsn;
    8221            1 :             }
    8222            1 : 
    8223            1 :             // Perform two cycles of flush, compact, and GC
    8224           33 :             for round in 0..2 {
    8225           22 :                 tline.freeze_and_flush().await?;
    8226           22 :                 tline
    8227           22 :                     .compact(
    8228           22 :                         &cancel,
    8229           22 :                         if iter % 5 == 0 && round == 0 {
    8230            3 :                             let mut flags = EnumSet::new();
    8231            3 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8232            3 :                             flags.insert(CompactFlags::ForceRepartition);
    8233            3 :                             flags
    8234            1 :                         } else {
    8235           19 :                             EnumSet::empty()
    8236            1 :                         },
    8237           22 :                         &ctx,
    8238            1 :                     )
    8239           22 :                     .await?;
    8240           22 :                 tenant
    8241           22 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    8242           22 :                     .await?;
    8243            1 :             }
    8244            1 :         }
    8245            1 : 
    8246            1 :         Ok(())
    8247            1 :     }
    8248              : 
    8249              :     #[tokio::test]
    8250            1 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    8251            1 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    8252            1 :         let (tenant, ctx) = harness.load().await;
    8253            1 :         let tline = tenant
    8254            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8255            1 :             .await?;
    8256              : 
    8257            1 :         let cancel = CancellationToken::new();
    8258              : 
    8259            1 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8260            1 :         base_key.field1 = AUX_KEY_PREFIX;
    8261            1 :         let test_key = base_key;
    8262            1 :         let mut lsn = Lsn(0x10);
    8263              : 
    8264           21 :         for _ in 0..20 {
    8265           20 :             lsn = Lsn(lsn.0 + 0x10);
    8266           20 :             let mut writer = tline.writer().await;
    8267           20 :             writer
    8268           20 :                 .put(
    8269           20 :                     test_key,
    8270           20 :                     lsn,
    8271           20 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    8272           20 :                     &ctx,
    8273           20 :                 )
    8274           20 :                 .await?;
    8275           20 :             writer.finish_write(lsn);
    8276           20 :             drop(writer);
    8277           20 :             tline.freeze_and_flush().await?; // force create a delta layer
    8278              :         }
    8279              : 
    8280            1 :         let before_num_l0_delta_files = tline
    8281            1 :             .layers
    8282            1 :             .read(LayerManagerLockHolder::Testing)
    8283            1 :             .await
    8284            1 :             .layer_map()?
    8285            1 :             .level0_deltas()
    8286            1 :             .len();
    8287              : 
    8288            1 :         tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    8289              : 
    8290            1 :         let after_num_l0_delta_files = tline
    8291            1 :             .layers
    8292            1 :             .read(LayerManagerLockHolder::Testing)
    8293            1 :             .await
    8294            1 :             .layer_map()?
    8295            1 :             .level0_deltas()
    8296            1 :             .len();
    8297              : 
    8298            1 :         assert!(
    8299            1 :             after_num_l0_delta_files < before_num_l0_delta_files,
    8300            0 :             "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
    8301              :         );
    8302              : 
    8303            1 :         assert_eq!(
    8304            1 :             tline.get(test_key, lsn, &ctx).await?,
    8305            1 :             test_img(&format!("{} at {}", 0, lsn))
    8306              :         );
    8307              : 
    8308            2 :         Ok(())
    8309            1 :     }
    8310              : 
    8311              :     #[tokio::test]
    8312            1 :     async fn test_aux_file_e2e() {
    8313            1 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    8314              : 
    8315            1 :         let (tenant, ctx) = harness.load().await;
    8316            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8317              : 
    8318            1 :         let mut lsn = Lsn(0x08);
    8319              : 
    8320            1 :         let tline: Arc<Timeline> = tenant
    8321            1 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8322            1 :             .await
    8323            1 :             .unwrap();
    8324              : 
    8325              :         {
    8326            1 :             lsn += 8;
    8327            1 :             let mut modification = tline.begin_modification(lsn);
    8328            1 :             modification
    8329            1 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    8330            1 :                 .await
    8331            1 :                 .unwrap();
    8332            1 :             modification.commit(&ctx).await.unwrap();
    8333              :         }
    8334              : 
    8335              :         // we can read everything from the storage
    8336            1 :         let files = tline
    8337            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8338            1 :             .await
    8339            1 :             .unwrap();
    8340            1 :         assert_eq!(
    8341            1 :             files.get("pg_logical/mappings/test1"),
    8342            1 :             Some(&bytes::Bytes::from_static(b"first"))
    8343              :         );
    8344              : 
    8345              :         {
    8346            1 :             lsn += 8;
    8347            1 :             let mut modification = tline.begin_modification(lsn);
    8348            1 :             modification
    8349            1 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    8350            1 :                 .await
    8351            1 :                 .unwrap();
    8352            1 :             modification.commit(&ctx).await.unwrap();
    8353              :         }
    8354              : 
    8355            1 :         let files = tline
    8356            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8357            1 :             .await
    8358            1 :             .unwrap();
    8359            1 :         assert_eq!(
    8360            1 :             files.get("pg_logical/mappings/test2"),
    8361            1 :             Some(&bytes::Bytes::from_static(b"second"))
    8362              :         );
    8363              : 
    8364            1 :         let child = tenant
    8365            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    8366            1 :             .await
    8367            1 :             .unwrap();
    8368              : 
    8369            1 :         let files = child
    8370            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8371            1 :             .await
    8372            1 :             .unwrap();
    8373            1 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    8374            1 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    8375            1 :     }
    8376              : 
    8377              :     #[tokio::test]
    8378            1 :     async fn test_repl_origin_tombstones() {
    8379            1 :         let harness = TenantHarness::create("test_repl_origin_tombstones")
    8380            1 :             .await
    8381            1 :             .unwrap();
    8382              : 
    8383            1 :         let (tenant, ctx) = harness.load().await;
    8384            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8385              : 
    8386            1 :         let mut lsn = Lsn(0x08);
    8387              : 
    8388            1 :         let tline: Arc<Timeline> = tenant
    8389            1 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8390            1 :             .await
    8391            1 :             .unwrap();
    8392              : 
    8393            1 :         let repl_lsn = Lsn(0x10);
    8394              :         {
    8395            1 :             lsn += 8;
    8396            1 :             let mut modification = tline.begin_modification(lsn);
    8397            1 :             modification.put_for_unit_test(repl_origin_key(2), Value::Image(Bytes::new()));
    8398            1 :             modification.set_replorigin(1, repl_lsn).await.unwrap();
    8399            1 :             modification.commit(&ctx).await.unwrap();
    8400              :         }
    8401              : 
    8402              :         // we can read everything from the storage
    8403            1 :         let repl_origins = tline
    8404            1 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8405            1 :             .await
    8406            1 :             .unwrap();
    8407            1 :         assert_eq!(repl_origins.len(), 1);
    8408            1 :         assert_eq!(repl_origins[&1], lsn);
    8409              : 
    8410              :         {
    8411            1 :             lsn += 8;
    8412            1 :             let mut modification = tline.begin_modification(lsn);
    8413            1 :             modification.put_for_unit_test(
    8414            1 :                 repl_origin_key(3),
    8415            1 :                 Value::Image(Bytes::copy_from_slice(b"cannot_decode_this")),
    8416              :             );
    8417            1 :             modification.commit(&ctx).await.unwrap();
    8418              :         }
    8419            1 :         let result = tline
    8420            1 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8421            1 :             .await;
    8422            1 :         assert!(result.is_err());
    8423            1 :     }
    8424              : 
    8425              :     #[tokio::test]
    8426            1 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    8427            1 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    8428            1 :         let (tenant, ctx) = harness.load().await;
    8429            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8430            1 :         let tline = tenant
    8431            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8432            1 :             .await?;
    8433              : 
    8434              :         const NUM_KEYS: usize = 1000;
    8435              :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8436              : 
    8437            1 :         let cancel = CancellationToken::new();
    8438              : 
    8439            1 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8440            1 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8441            1 :         let mut test_key = base_key;
    8442            1 :         let mut lsn = Lsn(0x10);
    8443              : 
    8444            4 :         async fn scan_with_statistics(
    8445            4 :             tline: &Timeline,
    8446            4 :             keyspace: &KeySpace,
    8447            4 :             lsn: Lsn,
    8448            4 :             ctx: &RequestContext,
    8449            4 :             io_concurrency: IoConcurrency,
    8450            4 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    8451            4 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8452            4 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8453            4 :             let res = tline
    8454            4 :                 .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8455            4 :                 .await?;
    8456            4 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    8457            4 :         }
    8458              : 
    8459         1001 :         for blknum in 0..NUM_KEYS {
    8460         1000 :             lsn = Lsn(lsn.0 + 0x10);
    8461         1000 :             test_key.field6 = (blknum * STEP) as u32;
    8462         1000 :             let mut writer = tline.writer().await;
    8463         1000 :             writer
    8464         1000 :                 .put(
    8465         1000 :                     test_key,
    8466         1000 :                     lsn,
    8467         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8468         1000 :                     &ctx,
    8469         1000 :                 )
    8470         1000 :                 .await?;
    8471         1000 :             writer.finish_write(lsn);
    8472         1000 :             drop(writer);
    8473              :         }
    8474              : 
    8475            1 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8476              : 
    8477           11 :         for iter in 1..=10 {
    8478        10010 :             for _ in 0..NUM_KEYS {
    8479        10000 :                 lsn = Lsn(lsn.0 + 0x10);
    8480        10000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8481        10000 :                 test_key.field6 = (blknum * STEP) as u32;
    8482        10000 :                 let mut writer = tline.writer().await;
    8483        10000 :                 writer
    8484        10000 :                     .put(
    8485        10000 :                         test_key,
    8486        10000 :                         lsn,
    8487        10000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8488        10000 :                         &ctx,
    8489        10000 :                     )
    8490        10000 :                     .await?;
    8491        10000 :                 writer.finish_write(lsn);
    8492        10000 :                 drop(writer);
    8493            1 :             }
    8494            1 : 
    8495           10 :             tline.freeze_and_flush().await?;
    8496            1 :             // Force layers to L1
    8497           10 :             tline
    8498           10 :                 .compact(
    8499           10 :                     &cancel,
    8500           10 :                     {
    8501           10 :                         let mut flags = EnumSet::new();
    8502           10 :                         flags.insert(CompactFlags::ForceL0Compaction);
    8503           10 :                         flags
    8504           10 :                     },
    8505           10 :                     &ctx,
    8506           10 :                 )
    8507           10 :                 .await?;
    8508            1 : 
    8509           10 :             if iter % 5 == 0 {
    8510            2 :                 let scan_lsn = Lsn(lsn.0 + 1);
    8511            2 :                 info!("scanning at {}", scan_lsn);
    8512            2 :                 let (_, before_delta_file_accessed) =
    8513            2 :                     scan_with_statistics(&tline, &keyspace, scan_lsn, &ctx, io_concurrency.clone())
    8514            2 :                         .await?;
    8515            2 :                 tline
    8516            2 :                     .compact(
    8517            2 :                         &cancel,
    8518            2 :                         {
    8519            2 :                             let mut flags = EnumSet::new();
    8520            2 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8521            2 :                             flags.insert(CompactFlags::ForceRepartition);
    8522            2 :                             flags.insert(CompactFlags::ForceL0Compaction);
    8523            2 :                             flags
    8524            2 :                         },
    8525            2 :                         &ctx,
    8526            2 :                     )
    8527            2 :                     .await?;
    8528            2 :                 let (_, after_delta_file_accessed) =
    8529            2 :                     scan_with_statistics(&tline, &keyspace, scan_lsn, &ctx, io_concurrency.clone())
    8530            2 :                         .await?;
    8531            2 :                 assert!(
    8532            2 :                     after_delta_file_accessed < before_delta_file_accessed,
    8533            1 :                     "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
    8534            1 :                 );
    8535            1 :                 // 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.
    8536            2 :                 assert!(
    8537            2 :                     after_delta_file_accessed <= 2,
    8538            1 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    8539            1 :                 );
    8540            8 :             }
    8541            1 :         }
    8542            1 : 
    8543            1 :         Ok(())
    8544            1 :     }
    8545              : 
    8546              :     #[tokio::test]
    8547            1 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    8548            1 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    8549            1 :         let (tenant, ctx) = harness.load().await;
    8550              : 
    8551            1 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8552            1 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    8553            1 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    8554              : 
    8555            1 :         let tline = tenant
    8556            1 :             .create_test_timeline_with_layers(
    8557            1 :                 TIMELINE_ID,
    8558            1 :                 Lsn(0x10),
    8559            1 :                 DEFAULT_PG_VERSION,
    8560            1 :                 &ctx,
    8561            1 :                 Vec::new(), // in-memory layers
    8562            1 :                 Vec::new(), // delta layers
    8563            1 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    8564            1 :                 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
    8565            1 :             )
    8566            1 :             .await?;
    8567            1 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    8568              : 
    8569            1 :         let child = tenant
    8570            1 :             .branch_timeline_test_with_layers(
    8571            1 :                 &tline,
    8572            1 :                 NEW_TIMELINE_ID,
    8573            1 :                 Some(Lsn(0x20)),
    8574            1 :                 &ctx,
    8575            1 :                 Vec::new(), // delta layers
    8576            1 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    8577            1 :                 Lsn(0x30),
    8578            1 :             )
    8579            1 :             .await
    8580            1 :             .unwrap();
    8581              : 
    8582            1 :         let lsn = Lsn(0x30);
    8583              : 
    8584              :         // test vectored get on parent timeline
    8585            1 :         assert_eq!(
    8586            1 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8587            1 :             Some(test_img("data key 1"))
    8588              :         );
    8589            1 :         assert!(
    8590            1 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    8591            1 :                 .await
    8592            1 :                 .unwrap_err()
    8593            1 :                 .is_missing_key_error()
    8594              :         );
    8595            1 :         assert!(
    8596            1 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    8597            1 :                 .await
    8598            1 :                 .unwrap_err()
    8599            1 :                 .is_missing_key_error()
    8600              :         );
    8601              : 
    8602              :         // test vectored get on child timeline
    8603            1 :         assert_eq!(
    8604            1 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8605            1 :             Some(test_img("data key 1"))
    8606              :         );
    8607            1 :         assert_eq!(
    8608            1 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8609            1 :             Some(test_img("data key 2"))
    8610              :         );
    8611            1 :         assert!(
    8612            1 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    8613            1 :                 .await
    8614            1 :                 .unwrap_err()
    8615            1 :                 .is_missing_key_error()
    8616              :         );
    8617              : 
    8618            2 :         Ok(())
    8619            1 :     }
    8620              : 
    8621              :     #[tokio::test]
    8622            1 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    8623            1 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    8624            1 :         let (tenant, ctx) = harness.load().await;
    8625            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8626              : 
    8627            1 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8628            1 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8629            1 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8630            1 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8631              : 
    8632            1 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    8633            1 :         let base_inherited_key_child =
    8634            1 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    8635            1 :         let base_inherited_key_nonexist =
    8636            1 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    8637            1 :         let base_inherited_key_overwrite =
    8638            1 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    8639              : 
    8640            1 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8641            1 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    8642              : 
    8643            1 :         let tline = tenant
    8644            1 :             .create_test_timeline_with_layers(
    8645            1 :                 TIMELINE_ID,
    8646            1 :                 Lsn(0x10),
    8647            1 :                 DEFAULT_PG_VERSION,
    8648            1 :                 &ctx,
    8649            1 :                 Vec::new(), // in-memory layers
    8650            1 :                 Vec::new(), // delta layers
    8651            1 :                 vec![(
    8652            1 :                     Lsn(0x20),
    8653            1 :                     vec![
    8654            1 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    8655            1 :                         (
    8656            1 :                             base_inherited_key_overwrite,
    8657            1 :                             test_img("metadata key overwrite 1a"),
    8658            1 :                         ),
    8659            1 :                         (base_key, test_img("metadata key 1")),
    8660            1 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8661            1 :                     ],
    8662            1 :                 )], // image layers
    8663            1 :                 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
    8664            1 :             )
    8665            1 :             .await?;
    8666              : 
    8667            1 :         let child = tenant
    8668            1 :             .branch_timeline_test_with_layers(
    8669            1 :                 &tline,
    8670            1 :                 NEW_TIMELINE_ID,
    8671            1 :                 Some(Lsn(0x20)),
    8672            1 :                 &ctx,
    8673            1 :                 Vec::new(), // delta layers
    8674            1 :                 vec![(
    8675            1 :                     Lsn(0x30),
    8676            1 :                     vec![
    8677            1 :                         (
    8678            1 :                             base_inherited_key_child,
    8679            1 :                             test_img("metadata inherited key 2"),
    8680            1 :                         ),
    8681            1 :                         (
    8682            1 :                             base_inherited_key_overwrite,
    8683            1 :                             test_img("metadata key overwrite 2a"),
    8684            1 :                         ),
    8685            1 :                         (base_key_child, test_img("metadata key 2")),
    8686            1 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8687            1 :                     ],
    8688            1 :                 )], // image layers
    8689            1 :                 Lsn(0x30),
    8690            1 :             )
    8691            1 :             .await
    8692            1 :             .unwrap();
    8693              : 
    8694            1 :         let lsn = Lsn(0x30);
    8695              : 
    8696              :         // test vectored get on parent timeline
    8697            1 :         assert_eq!(
    8698            1 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8699            1 :             Some(test_img("metadata key 1"))
    8700              :         );
    8701            1 :         assert_eq!(
    8702            1 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8703              :             None
    8704              :         );
    8705            1 :         assert_eq!(
    8706            1 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8707              :             None
    8708              :         );
    8709            1 :         assert_eq!(
    8710            1 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8711            1 :             Some(test_img("metadata key overwrite 1b"))
    8712              :         );
    8713            1 :         assert_eq!(
    8714            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8715            1 :             Some(test_img("metadata inherited key 1"))
    8716              :         );
    8717            1 :         assert_eq!(
    8718            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8719              :             None
    8720              :         );
    8721            1 :         assert_eq!(
    8722            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8723              :             None
    8724              :         );
    8725            1 :         assert_eq!(
    8726            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8727            1 :             Some(test_img("metadata key overwrite 1a"))
    8728              :         );
    8729              : 
    8730              :         // test vectored get on child timeline
    8731            1 :         assert_eq!(
    8732            1 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8733              :             None
    8734              :         );
    8735            1 :         assert_eq!(
    8736            1 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8737            1 :             Some(test_img("metadata key 2"))
    8738              :         );
    8739            1 :         assert_eq!(
    8740            1 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8741              :             None
    8742              :         );
    8743            1 :         assert_eq!(
    8744            1 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8745            1 :             Some(test_img("metadata inherited key 1"))
    8746              :         );
    8747            1 :         assert_eq!(
    8748            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8749            1 :             Some(test_img("metadata inherited key 2"))
    8750              :         );
    8751            1 :         assert_eq!(
    8752            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8753              :             None
    8754              :         );
    8755            1 :         assert_eq!(
    8756            1 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8757            1 :             Some(test_img("metadata key overwrite 2b"))
    8758              :         );
    8759            1 :         assert_eq!(
    8760            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8761            1 :             Some(test_img("metadata key overwrite 2a"))
    8762              :         );
    8763              : 
    8764              :         // test vectored scan on parent timeline
    8765            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8766            1 :         let query =
    8767            1 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8768            1 :         let res = tline
    8769            1 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8770            1 :             .await?;
    8771              : 
    8772            1 :         assert_eq!(
    8773            1 :             res.into_iter()
    8774            4 :                 .map(|(k, v)| (k, v.unwrap()))
    8775            1 :                 .collect::<Vec<_>>(),
    8776            1 :             vec![
    8777            1 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8778            1 :                 (
    8779            1 :                     base_inherited_key_overwrite,
    8780            1 :                     test_img("metadata key overwrite 1a")
    8781            1 :                 ),
    8782            1 :                 (base_key, test_img("metadata key 1")),
    8783            1 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8784              :             ]
    8785              :         );
    8786              : 
    8787              :         // test vectored scan on child timeline
    8788            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8789            1 :         let query =
    8790            1 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8791            1 :         let res = child
    8792            1 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8793            1 :             .await?;
    8794              : 
    8795            1 :         assert_eq!(
    8796            1 :             res.into_iter()
    8797            5 :                 .map(|(k, v)| (k, v.unwrap()))
    8798            1 :                 .collect::<Vec<_>>(),
    8799            1 :             vec![
    8800            1 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8801            1 :                 (
    8802            1 :                     base_inherited_key_child,
    8803            1 :                     test_img("metadata inherited key 2")
    8804            1 :                 ),
    8805            1 :                 (
    8806            1 :                     base_inherited_key_overwrite,
    8807            1 :                     test_img("metadata key overwrite 2a")
    8808            1 :                 ),
    8809            1 :                 (base_key_child, test_img("metadata key 2")),
    8810            1 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8811              :             ]
    8812              :         );
    8813              : 
    8814            2 :         Ok(())
    8815            1 :     }
    8816              : 
    8817           28 :     async fn get_vectored_impl_wrapper(
    8818           28 :         tline: &Arc<Timeline>,
    8819           28 :         key: Key,
    8820           28 :         lsn: Lsn,
    8821           28 :         ctx: &RequestContext,
    8822           28 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8823           28 :         let io_concurrency = IoConcurrency::spawn_from_conf(
    8824           28 :             tline.conf.get_vectored_concurrent_io,
    8825           28 :             tline.gate.enter().unwrap(),
    8826              :         );
    8827           28 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8828           28 :         let query = VersionedKeySpaceQuery::uniform(KeySpace::single(key..key.next()), lsn);
    8829           28 :         let mut res = tline
    8830           28 :             .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8831           28 :             .await?;
    8832           25 :         Ok(res.pop_last().map(|(k, v)| {
    8833           16 :             assert_eq!(k, key);
    8834           16 :             v.unwrap()
    8835           16 :         }))
    8836           28 :     }
    8837              : 
    8838              :     #[tokio::test]
    8839            1 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8840            1 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8841            1 :         let (tenant, ctx) = harness.load().await;
    8842            1 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8843            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8844            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8845            1 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8846              : 
    8847              :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8848              :         // Lsn 0x30 key0, key3, no key1+key2
    8849              :         // Lsn 0x20 key1+key2 tomestones
    8850              :         // Lsn 0x10 key1 in image, key2 in delta
    8851            1 :         let tline = tenant
    8852            1 :             .create_test_timeline_with_layers(
    8853            1 :                 TIMELINE_ID,
    8854            1 :                 Lsn(0x10),
    8855            1 :                 DEFAULT_PG_VERSION,
    8856            1 :                 &ctx,
    8857            1 :                 Vec::new(), // in-memory layers
    8858            1 :                 // delta layers
    8859            1 :                 vec![
    8860            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8861            1 :                         Lsn(0x10)..Lsn(0x20),
    8862            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8863            1 :                     ),
    8864            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8865            1 :                         Lsn(0x20)..Lsn(0x30),
    8866            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8867            1 :                     ),
    8868            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8869            1 :                         Lsn(0x20)..Lsn(0x30),
    8870            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8871            1 :                     ),
    8872            1 :                 ],
    8873            1 :                 // image layers
    8874            1 :                 vec![
    8875            1 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8876            1 :                     (
    8877            1 :                         Lsn(0x30),
    8878            1 :                         vec![
    8879            1 :                             (key0, test_img("metadata key 0")),
    8880            1 :                             (key3, test_img("metadata key 3")),
    8881            1 :                         ],
    8882            1 :                     ),
    8883            1 :                 ],
    8884            1 :                 Lsn(0x30),
    8885            1 :             )
    8886            1 :             .await?;
    8887              : 
    8888            1 :         let lsn = Lsn(0x30);
    8889            1 :         let old_lsn = Lsn(0x20);
    8890              : 
    8891            1 :         assert_eq!(
    8892            1 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8893            1 :             Some(test_img("metadata key 0"))
    8894              :         );
    8895            1 :         assert_eq!(
    8896            1 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8897              :             None,
    8898              :         );
    8899            1 :         assert_eq!(
    8900            1 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8901              :             None,
    8902              :         );
    8903            1 :         assert_eq!(
    8904            1 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8905            1 :             Some(Bytes::new()),
    8906              :         );
    8907            1 :         assert_eq!(
    8908            1 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8909            1 :             Some(Bytes::new()),
    8910              :         );
    8911            1 :         assert_eq!(
    8912            1 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8913            1 :             Some(test_img("metadata key 3"))
    8914              :         );
    8915              : 
    8916            2 :         Ok(())
    8917            1 :     }
    8918              : 
    8919              :     #[tokio::test]
    8920            1 :     async fn test_metadata_tombstone_image_creation() {
    8921            1 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8922            1 :             .await
    8923            1 :             .unwrap();
    8924            1 :         let (tenant, ctx) = harness.load().await;
    8925            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8926              : 
    8927            1 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8928            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8929            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8930            1 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8931              : 
    8932            1 :         let tline = tenant
    8933            1 :             .create_test_timeline_with_layers(
    8934            1 :                 TIMELINE_ID,
    8935            1 :                 Lsn(0x10),
    8936            1 :                 DEFAULT_PG_VERSION,
    8937            1 :                 &ctx,
    8938            1 :                 Vec::new(), // in-memory layers
    8939            1 :                 // delta layers
    8940            1 :                 vec![
    8941            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8942            1 :                         Lsn(0x10)..Lsn(0x20),
    8943            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8944            1 :                     ),
    8945            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8946            1 :                         Lsn(0x20)..Lsn(0x30),
    8947            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8948            1 :                     ),
    8949            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8950            1 :                         Lsn(0x20)..Lsn(0x30),
    8951            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8952            1 :                     ),
    8953            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8954            1 :                         Lsn(0x30)..Lsn(0x40),
    8955            1 :                         vec![
    8956            1 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8957            1 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8958            1 :                         ],
    8959            1 :                     ),
    8960            1 :                 ],
    8961            1 :                 // image layers
    8962            1 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8963            1 :                 Lsn(0x40),
    8964            1 :             )
    8965            1 :             .await
    8966            1 :             .unwrap();
    8967              : 
    8968            1 :         let cancel = CancellationToken::new();
    8969              : 
    8970              :         // Image layer creation happens on the disk_consistent_lsn so we need to force set it now.
    8971            1 :         tline.force_set_disk_consistent_lsn(Lsn(0x40));
    8972            1 :         tline
    8973            1 :             .compact(
    8974            1 :                 &cancel,
    8975            1 :                 {
    8976            1 :                     let mut flags = EnumSet::new();
    8977            1 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8978            1 :                     flags.insert(CompactFlags::ForceRepartition);
    8979            1 :                     flags
    8980            1 :                 },
    8981            1 :                 &ctx,
    8982            1 :             )
    8983            1 :             .await
    8984            1 :             .unwrap();
    8985              :         // Image layers are created at repartition LSN
    8986            1 :         let images = tline
    8987            1 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    8988            1 :             .await
    8989            1 :             .unwrap()
    8990            1 :             .into_iter()
    8991            9 :             .filter(|(k, _)| k.is_metadata_key())
    8992            1 :             .collect::<Vec<_>>();
    8993            1 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8994            1 :     }
    8995              : 
    8996              :     #[tokio::test]
    8997            1 :     async fn test_metadata_tombstone_empty_image_creation() {
    8998            1 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8999            1 :             .await
    9000            1 :             .unwrap();
    9001            1 :         let (tenant, ctx) = harness.load().await;
    9002            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    9003              : 
    9004            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    9005            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    9006              : 
    9007            1 :         let tline = tenant
    9008            1 :             .create_test_timeline_with_layers(
    9009            1 :                 TIMELINE_ID,
    9010            1 :                 Lsn(0x10),
    9011            1 :                 DEFAULT_PG_VERSION,
    9012            1 :                 &ctx,
    9013            1 :                 Vec::new(), // in-memory layers
    9014            1 :                 // delta layers
    9015            1 :                 vec![
    9016            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9017            1 :                         Lsn(0x10)..Lsn(0x20),
    9018            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    9019            1 :                     ),
    9020            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9021            1 :                         Lsn(0x20)..Lsn(0x30),
    9022            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    9023            1 :                     ),
    9024            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9025            1 :                         Lsn(0x20)..Lsn(0x30),
    9026            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    9027            1 :                     ),
    9028            1 :                 ],
    9029            1 :                 // image layers
    9030            1 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    9031            1 :                 Lsn(0x30),
    9032            1 :             )
    9033            1 :             .await
    9034            1 :             .unwrap();
    9035              : 
    9036            1 :         let cancel = CancellationToken::new();
    9037              : 
    9038            1 :         tline
    9039            1 :             .compact(
    9040            1 :                 &cancel,
    9041            1 :                 {
    9042            1 :                     let mut flags = EnumSet::new();
    9043            1 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    9044            1 :                     flags.insert(CompactFlags::ForceRepartition);
    9045            1 :                     flags
    9046            1 :                 },
    9047            1 :                 &ctx,
    9048            1 :             )
    9049            1 :             .await
    9050            1 :             .unwrap();
    9051              : 
    9052              :         // Image layers are created at last_record_lsn
    9053            1 :         let images = tline
    9054            1 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    9055            1 :             .await
    9056            1 :             .unwrap()
    9057            1 :             .into_iter()
    9058            7 :             .filter(|(k, _)| k.is_metadata_key())
    9059            1 :             .collect::<Vec<_>>();
    9060            1 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    9061            1 :     }
    9062              : 
    9063              :     #[tokio::test]
    9064            1 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    9065            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    9066            1 :         let (tenant, ctx) = harness.load().await;
    9067            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    9068              : 
    9069           51 :         fn get_key(id: u32) -> Key {
    9070              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9071           51 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9072           51 :             key.field6 = id;
    9073           51 :             key
    9074           51 :         }
    9075              : 
    9076              :         // We create
    9077              :         // - one bottom-most image layer,
    9078              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9079              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9080              :         // - a delta layer D3 above the horizon.
    9081              :         //
    9082              :         //                             | D3 |
    9083              :         //  | D1 |
    9084              :         // -|    |-- gc horizon -----------------
    9085              :         //  |    |                | D2 |
    9086              :         // --------- img layer ------------------
    9087              :         //
    9088              :         // What we should expact from this compaction is:
    9089              :         //                             | D3 |
    9090              :         //  | Part of D1 |
    9091              :         // --------- img layer with D1+D2 at GC horizon------------------
    9092              : 
    9093              :         // img layer at 0x10
    9094            1 :         let img_layer = (0..10)
    9095           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9096            1 :             .collect_vec();
    9097              : 
    9098            1 :         let delta1 = vec![
    9099            1 :             (
    9100            1 :                 get_key(1),
    9101            1 :                 Lsn(0x20),
    9102            1 :                 Value::Image(Bytes::from("value 1@0x20")),
    9103            1 :             ),
    9104            1 :             (
    9105            1 :                 get_key(2),
    9106            1 :                 Lsn(0x30),
    9107            1 :                 Value::Image(Bytes::from("value 2@0x30")),
    9108            1 :             ),
    9109            1 :             (
    9110            1 :                 get_key(3),
    9111            1 :                 Lsn(0x40),
    9112            1 :                 Value::Image(Bytes::from("value 3@0x40")),
    9113            1 :             ),
    9114              :         ];
    9115            1 :         let delta2 = vec![
    9116            1 :             (
    9117            1 :                 get_key(5),
    9118            1 :                 Lsn(0x20),
    9119            1 :                 Value::Image(Bytes::from("value 5@0x20")),
    9120            1 :             ),
    9121            1 :             (
    9122            1 :                 get_key(6),
    9123            1 :                 Lsn(0x20),
    9124            1 :                 Value::Image(Bytes::from("value 6@0x20")),
    9125            1 :             ),
    9126              :         ];
    9127            1 :         let delta3 = vec![
    9128            1 :             (
    9129            1 :                 get_key(8),
    9130            1 :                 Lsn(0x48),
    9131            1 :                 Value::Image(Bytes::from("value 8@0x48")),
    9132            1 :             ),
    9133            1 :             (
    9134            1 :                 get_key(9),
    9135            1 :                 Lsn(0x48),
    9136            1 :                 Value::Image(Bytes::from("value 9@0x48")),
    9137            1 :             ),
    9138              :         ];
    9139              : 
    9140            1 :         let tline = tenant
    9141            1 :             .create_test_timeline_with_layers(
    9142            1 :                 TIMELINE_ID,
    9143            1 :                 Lsn(0x10),
    9144            1 :                 DEFAULT_PG_VERSION,
    9145            1 :                 &ctx,
    9146            1 :                 Vec::new(), // in-memory layers
    9147            1 :                 vec![
    9148            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9149            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9150            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9151            1 :                 ], // delta layers
    9152            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9153            1 :                 Lsn(0x50),
    9154            1 :             )
    9155            1 :             .await?;
    9156              :         {
    9157            1 :             tline
    9158            1 :                 .applied_gc_cutoff_lsn
    9159            1 :                 .lock_for_write()
    9160            1 :                 .store_and_unlock(Lsn(0x30))
    9161            1 :                 .wait()
    9162            1 :                 .await;
    9163              :             // Update GC info
    9164            1 :             let mut guard = tline.gc_info.write().unwrap();
    9165            1 :             guard.cutoffs.time = Some(Lsn(0x30));
    9166            1 :             guard.cutoffs.space = Lsn(0x30);
    9167              :         }
    9168              : 
    9169            1 :         let expected_result = [
    9170            1 :             Bytes::from_static(b"value 0@0x10"),
    9171            1 :             Bytes::from_static(b"value 1@0x20"),
    9172            1 :             Bytes::from_static(b"value 2@0x30"),
    9173            1 :             Bytes::from_static(b"value 3@0x40"),
    9174            1 :             Bytes::from_static(b"value 4@0x10"),
    9175            1 :             Bytes::from_static(b"value 5@0x20"),
    9176            1 :             Bytes::from_static(b"value 6@0x20"),
    9177            1 :             Bytes::from_static(b"value 7@0x10"),
    9178            1 :             Bytes::from_static(b"value 8@0x48"),
    9179            1 :             Bytes::from_static(b"value 9@0x48"),
    9180            1 :         ];
    9181              : 
    9182           10 :         for (idx, expected) in expected_result.iter().enumerate() {
    9183           10 :             assert_eq!(
    9184           10 :                 tline
    9185           10 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9186           10 :                     .await
    9187           10 :                     .unwrap(),
    9188              :                 expected
    9189              :             );
    9190              :         }
    9191              : 
    9192            1 :         let cancel = CancellationToken::new();
    9193            1 :         tline
    9194            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9195            1 :             .await
    9196            1 :             .unwrap();
    9197              : 
    9198           10 :         for (idx, expected) in expected_result.iter().enumerate() {
    9199           10 :             assert_eq!(
    9200           10 :                 tline
    9201           10 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9202           10 :                     .await
    9203           10 :                     .unwrap(),
    9204              :                 expected
    9205              :             );
    9206              :         }
    9207              : 
    9208              :         // Check if the image layer at the GC horizon contains exactly what we want
    9209            1 :         let image_at_gc_horizon = tline
    9210            1 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    9211            1 :             .await
    9212            1 :             .unwrap()
    9213            1 :             .into_iter()
    9214           17 :             .filter(|(k, _)| k.is_metadata_key())
    9215            1 :             .collect::<Vec<_>>();
    9216              : 
    9217            1 :         assert_eq!(image_at_gc_horizon.len(), 10);
    9218            1 :         let expected_result = [
    9219            1 :             Bytes::from_static(b"value 0@0x10"),
    9220            1 :             Bytes::from_static(b"value 1@0x20"),
    9221            1 :             Bytes::from_static(b"value 2@0x30"),
    9222            1 :             Bytes::from_static(b"value 3@0x10"),
    9223            1 :             Bytes::from_static(b"value 4@0x10"),
    9224            1 :             Bytes::from_static(b"value 5@0x20"),
    9225            1 :             Bytes::from_static(b"value 6@0x20"),
    9226            1 :             Bytes::from_static(b"value 7@0x10"),
    9227            1 :             Bytes::from_static(b"value 8@0x10"),
    9228            1 :             Bytes::from_static(b"value 9@0x10"),
    9229            1 :         ];
    9230           11 :         for idx in 0..10 {
    9231           10 :             assert_eq!(
    9232           10 :                 image_at_gc_horizon[idx],
    9233           10 :                 (get_key(idx as u32), expected_result[idx].clone())
    9234              :             );
    9235              :         }
    9236              : 
    9237              :         // Check if old layers are removed / new layers have the expected LSN
    9238            1 :         let all_layers = inspect_and_sort(&tline, None).await;
    9239            1 :         assert_eq!(
    9240              :             all_layers,
    9241            1 :             vec![
    9242              :                 // Image layer at GC horizon
    9243            1 :                 PersistentLayerKey {
    9244            1 :                     key_range: Key::MIN..Key::MAX,
    9245            1 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    9246            1 :                     is_delta: false
    9247            1 :                 },
    9248              :                 // The delta layer below the horizon
    9249            1 :                 PersistentLayerKey {
    9250            1 :                     key_range: get_key(3)..get_key(4),
    9251            1 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    9252            1 :                     is_delta: true
    9253            1 :                 },
    9254              :                 // The delta3 layer that should not be picked for the compaction
    9255            1 :                 PersistentLayerKey {
    9256            1 :                     key_range: get_key(8)..get_key(10),
    9257            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9258            1 :                     is_delta: true
    9259            1 :                 }
    9260              :             ]
    9261              :         );
    9262              : 
    9263              :         // increase GC horizon and compact again
    9264              :         {
    9265            1 :             tline
    9266            1 :                 .applied_gc_cutoff_lsn
    9267            1 :                 .lock_for_write()
    9268            1 :                 .store_and_unlock(Lsn(0x40))
    9269            1 :                 .wait()
    9270            1 :                 .await;
    9271              :             // Update GC info
    9272            1 :             let mut guard = tline.gc_info.write().unwrap();
    9273            1 :             guard.cutoffs.time = Some(Lsn(0x40));
    9274            1 :             guard.cutoffs.space = Lsn(0x40);
    9275              :         }
    9276            1 :         tline
    9277            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9278            1 :             .await
    9279            1 :             .unwrap();
    9280              : 
    9281            2 :         Ok(())
    9282            1 :     }
    9283              : 
    9284              :     #[cfg(feature = "testing")]
    9285              :     #[tokio::test]
    9286            1 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    9287            1 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    9288            1 :         let (tenant, ctx) = harness.load().await;
    9289              : 
    9290           17 :         fn get_key(id: u32) -> Key {
    9291              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9292           17 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9293           17 :             key.field6 = id;
    9294           17 :             key
    9295           17 :         }
    9296              : 
    9297            1 :         let delta1 = vec![
    9298            1 :             (
    9299            1 :                 get_key(1),
    9300            1 :                 Lsn(0x20),
    9301            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9302            1 :             ),
    9303            1 :             (
    9304            1 :                 get_key(1),
    9305            1 :                 Lsn(0x30),
    9306            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9307            1 :             ),
    9308            1 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    9309            1 :             (
    9310            1 :                 get_key(2),
    9311            1 :                 Lsn(0x20),
    9312            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9313            1 :             ),
    9314            1 :             (
    9315            1 :                 get_key(2),
    9316            1 :                 Lsn(0x30),
    9317            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9318            1 :             ),
    9319            1 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    9320            1 :             (
    9321            1 :                 get_key(3),
    9322            1 :                 Lsn(0x20),
    9323            1 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    9324            1 :             ),
    9325            1 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    9326            1 :             (
    9327            1 :                 get_key(4),
    9328            1 :                 Lsn(0x20),
    9329            1 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    9330            1 :             ),
    9331            1 :             (
    9332            1 :                 get_key(4),
    9333            1 :                 Lsn(0x30),
    9334            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "i")),
    9335            1 :             ),
    9336            1 :             (
    9337            1 :                 get_key(5),
    9338            1 :                 Lsn(0x20),
    9339            1 :                 Value::WalRecord(NeonWalRecord::wal_init("1")),
    9340            1 :             ),
    9341            1 :             (
    9342            1 :                 get_key(5),
    9343            1 :                 Lsn(0x30),
    9344            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "2")),
    9345            1 :             ),
    9346              :         ];
    9347            1 :         let image1 = vec![(get_key(1), "0x10".into())];
    9348              : 
    9349            1 :         let tline = tenant
    9350            1 :             .create_test_timeline_with_layers(
    9351            1 :                 TIMELINE_ID,
    9352            1 :                 Lsn(0x10),
    9353            1 :                 DEFAULT_PG_VERSION,
    9354            1 :                 &ctx,
    9355            1 :                 Vec::new(), // in-memory layers
    9356            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9357            1 :                     Lsn(0x10)..Lsn(0x40),
    9358            1 :                     delta1,
    9359            1 :                 )], // delta layers
    9360            1 :                 vec![(Lsn(0x10), image1)], // image layers
    9361            1 :                 Lsn(0x50),
    9362            1 :             )
    9363            1 :             .await?;
    9364              : 
    9365            1 :         assert_eq!(
    9366            1 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    9367            1 :             Bytes::from_static(b"0x10,0x20,0x30")
    9368              :         );
    9369            1 :         assert_eq!(
    9370            1 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    9371            1 :             Bytes::from_static(b"0x10,0x20,0x30")
    9372              :         );
    9373              : 
    9374              :         // Need to remove the limit of "Neon WAL redo requires base image".
    9375              : 
    9376            1 :         assert_eq!(
    9377            1 :             tline.get(get_key(3), Lsn(0x50), &ctx).await?,
    9378            1 :             Bytes::from_static(b"c")
    9379              :         );
    9380            1 :         assert_eq!(
    9381            1 :             tline.get(get_key(4), Lsn(0x50), &ctx).await?,
    9382            1 :             Bytes::from_static(b"ij")
    9383              :         );
    9384              : 
    9385              :         // Manual testing required: currently, read errors will panic the process in debug mode. So we
    9386              :         // cannot enable this assertion in the unit test.
    9387              :         // assert!(tline.get(get_key(5), Lsn(0x50), &ctx).await.is_err());
    9388              : 
    9389            2 :         Ok(())
    9390            1 :     }
    9391              : 
    9392              :     #[tokio::test]
    9393            1 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    9394            1 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    9395            1 :             .await
    9396            1 :             .unwrap()
    9397            1 :             .load()
    9398            1 :             .await;
    9399              :         // set a non-zero lease length to test the feature
    9400            1 :         tenant
    9401            1 :             .update_tenant_config(|mut conf| {
    9402            1 :                 conf.lsn_lease_length = Some(LsnLease::DEFAULT_LENGTH);
    9403            1 :                 Ok(conf)
    9404            1 :             })
    9405            1 :             .unwrap();
    9406              : 
    9407            1 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9408              : 
    9409            1 :         let end_lsn = Lsn(0x100);
    9410            1 :         let image_layers = (0x20..=0x90)
    9411            1 :             .step_by(0x10)
    9412            8 :             .map(|n| (Lsn(n), vec![(key, test_img(&format!("data key at {n:x}")))]))
    9413            1 :             .collect();
    9414              : 
    9415            1 :         let timeline = tenant
    9416            1 :             .create_test_timeline_with_layers(
    9417            1 :                 TIMELINE_ID,
    9418            1 :                 Lsn(0x10),
    9419            1 :                 DEFAULT_PG_VERSION,
    9420            1 :                 &ctx,
    9421            1 :                 Vec::new(), // in-memory layers
    9422            1 :                 Vec::new(),
    9423            1 :                 image_layers,
    9424            1 :                 end_lsn,
    9425            1 :             )
    9426            1 :             .await?;
    9427              : 
    9428            1 :         let leased_lsns = [0x30, 0x50, 0x70];
    9429            1 :         let mut leases = Vec::new();
    9430            3 :         leased_lsns.iter().for_each(|n| {
    9431            3 :             leases.push(
    9432            3 :                 timeline
    9433            3 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    9434            3 :                     .expect("lease request should succeed"),
    9435              :             );
    9436            3 :         });
    9437              : 
    9438            1 :         let updated_lease_0 = timeline
    9439            1 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    9440            1 :             .expect("lease renewal should succeed");
    9441            1 :         assert_eq!(
    9442            1 :             updated_lease_0.valid_until, leases[0].valid_until,
    9443            0 :             " Renewing with shorter lease should not change the lease."
    9444              :         );
    9445              : 
    9446            1 :         let updated_lease_1 = timeline
    9447            1 :             .renew_lsn_lease(
    9448            1 :                 Lsn(leased_lsns[1]),
    9449            1 :                 timeline.get_lsn_lease_length() * 2,
    9450            1 :                 &ctx,
    9451            1 :             )
    9452            1 :             .expect("lease renewal should succeed");
    9453            1 :         assert!(
    9454            1 :             updated_lease_1.valid_until > leases[1].valid_until,
    9455            0 :             "Renewing with a long lease should renew lease with later expiration time."
    9456              :         );
    9457              : 
    9458              :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    9459            1 :         info!(
    9460            0 :             "applied_gc_cutoff_lsn: {}",
    9461            0 :             *timeline.get_applied_gc_cutoff_lsn()
    9462              :         );
    9463            1 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    9464              : 
    9465            1 :         let res = tenant
    9466            1 :             .gc_iteration(
    9467            1 :                 Some(TIMELINE_ID),
    9468            1 :                 0,
    9469            1 :                 Duration::ZERO,
    9470            1 :                 &CancellationToken::new(),
    9471            1 :                 &ctx,
    9472            1 :             )
    9473            1 :             .await
    9474            1 :             .unwrap();
    9475              : 
    9476              :         // Keeping everything <= Lsn(0x80) b/c leases:
    9477              :         // 0/10: initdb layer
    9478              :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    9479            1 :         assert_eq!(res.layers_needed_by_leases, 7);
    9480              :         // Keeping 0/90 b/c it is the latest layer.
    9481            1 :         assert_eq!(res.layers_not_updated, 1);
    9482              :         // Removed 0/80.
    9483            1 :         assert_eq!(res.layers_removed, 1);
    9484              : 
    9485              :         // Make lease on a already GC-ed LSN.
    9486              :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    9487            1 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    9488            1 :         timeline
    9489            1 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    9490            1 :             .expect_err("lease request on GC-ed LSN should fail");
    9491              : 
    9492              :         // Should still be able to renew a currently valid lease
    9493              :         // Assumption: original lease to is still valid for 0/50.
    9494              :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    9495            1 :         timeline
    9496            1 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    9497            1 :             .expect("lease renewal with validation should succeed");
    9498              : 
    9499            2 :         Ok(())
    9500            1 :     }
    9501              : 
    9502              :     #[tokio::test]
    9503            1 :     async fn test_failed_flush_should_not_update_disk_consistent_lsn() -> anyhow::Result<()> {
    9504              :         //
    9505              :         // Setup
    9506              :         //
    9507            1 :         let harness = TenantHarness::create_custom(
    9508            1 :             "test_failed_flush_should_not_upload_disk_consistent_lsn",
    9509            1 :             pageserver_api::models::TenantConfig::default(),
    9510            1 :             TenantId::generate(),
    9511            1 :             ShardIdentity::new(ShardNumber(0), ShardCount(4), ShardStripeSize(128)).unwrap(),
    9512            1 :             Generation::new(1),
    9513            1 :         )
    9514            1 :         .await?;
    9515            1 :         let (tenant, ctx) = harness.load().await;
    9516              : 
    9517            1 :         let timeline = tenant
    9518            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9519            1 :             .await?;
    9520            1 :         assert_eq!(timeline.get_shard_identity().count, ShardCount(4));
    9521            1 :         let mut writer = timeline.writer().await;
    9522            1 :         writer
    9523            1 :             .put(
    9524            1 :                 *TEST_KEY,
    9525            1 :                 Lsn(0x20),
    9526            1 :                 &Value::Image(test_img("foo at 0x20")),
    9527            1 :                 &ctx,
    9528            1 :             )
    9529            1 :             .await?;
    9530            1 :         writer.finish_write(Lsn(0x20));
    9531            1 :         drop(writer);
    9532            1 :         timeline.freeze_and_flush().await.unwrap();
    9533              : 
    9534            1 :         timeline.remote_client.wait_completion().await.unwrap();
    9535            1 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    9536            1 :         let remote_consistent_lsn = timeline.get_remote_consistent_lsn_projected();
    9537            1 :         assert_eq!(Some(disk_consistent_lsn), remote_consistent_lsn);
    9538              : 
    9539              :         //
    9540              :         // Test
    9541              :         //
    9542              : 
    9543            1 :         let mut writer = timeline.writer().await;
    9544            1 :         writer
    9545            1 :             .put(
    9546            1 :                 *TEST_KEY,
    9547            1 :                 Lsn(0x30),
    9548            1 :                 &Value::Image(test_img("foo at 0x30")),
    9549            1 :                 &ctx,
    9550            1 :             )
    9551            1 :             .await?;
    9552            1 :         writer.finish_write(Lsn(0x30));
    9553            1 :         drop(writer);
    9554              : 
    9555            1 :         fail::cfg(
    9556              :             "flush-layer-before-update-remote-consistent-lsn",
    9557            1 :             "return()",
    9558              :         )
    9559            1 :         .unwrap();
    9560              : 
    9561            1 :         let flush_res = timeline.freeze_and_flush().await;
    9562              :         // if flush failed, the disk/remote consistent LSN should not be updated
    9563            1 :         assert!(flush_res.is_err());
    9564            1 :         assert_eq!(disk_consistent_lsn, timeline.get_disk_consistent_lsn());
    9565            1 :         assert_eq!(
    9566              :             remote_consistent_lsn,
    9567            1 :             timeline.get_remote_consistent_lsn_projected()
    9568              :         );
    9569              : 
    9570            2 :         Ok(())
    9571            1 :     }
    9572              : 
    9573              :     #[cfg(feature = "testing")]
    9574              :     #[tokio::test]
    9575            1 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    9576            2 :         test_simple_bottom_most_compaction_deltas_helper(
    9577            2 :             "test_simple_bottom_most_compaction_deltas_1",
    9578            2 :             false,
    9579            2 :         )
    9580            2 :         .await
    9581            1 :     }
    9582              : 
    9583              :     #[cfg(feature = "testing")]
    9584              :     #[tokio::test]
    9585            1 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    9586            2 :         test_simple_bottom_most_compaction_deltas_helper(
    9587            2 :             "test_simple_bottom_most_compaction_deltas_2",
    9588            2 :             true,
    9589            2 :         )
    9590            2 :         .await
    9591            1 :     }
    9592              : 
    9593              :     #[cfg(feature = "testing")]
    9594            2 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    9595            2 :         test_name: &'static str,
    9596            2 :         use_delta_bottom_layer: bool,
    9597            2 :     ) -> anyhow::Result<()> {
    9598            2 :         let harness = TenantHarness::create(test_name).await?;
    9599            2 :         let (tenant, ctx) = harness.load().await;
    9600              : 
    9601          138 :         fn get_key(id: u32) -> Key {
    9602              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9603          138 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9604          138 :             key.field6 = id;
    9605          138 :             key
    9606          138 :         }
    9607              : 
    9608              :         // We create
    9609              :         // - one bottom-most image layer,
    9610              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9611              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9612              :         // - a delta layer D3 above the horizon.
    9613              :         //
    9614              :         //                             | D3 |
    9615              :         //  | D1 |
    9616              :         // -|    |-- gc horizon -----------------
    9617              :         //  |    |                | D2 |
    9618              :         // --------- img layer ------------------
    9619              :         //
    9620              :         // What we should expact from this compaction is:
    9621              :         //                             | D3 |
    9622              :         //  | Part of D1 |
    9623              :         // --------- img layer with D1+D2 at GC horizon------------------
    9624              : 
    9625              :         // img layer at 0x10
    9626            2 :         let img_layer = (0..10)
    9627           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9628            2 :             .collect_vec();
    9629              :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    9630            2 :         let delta4 = (0..10)
    9631           20 :             .map(|id| {
    9632           20 :                 (
    9633           20 :                     get_key(id),
    9634           20 :                     Lsn(0x08),
    9635           20 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    9636           20 :                 )
    9637           20 :             })
    9638            2 :             .collect_vec();
    9639              : 
    9640            2 :         let delta1 = vec![
    9641            2 :             (
    9642            2 :                 get_key(1),
    9643            2 :                 Lsn(0x20),
    9644            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9645            2 :             ),
    9646            2 :             (
    9647            2 :                 get_key(2),
    9648            2 :                 Lsn(0x30),
    9649            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9650            2 :             ),
    9651            2 :             (
    9652            2 :                 get_key(3),
    9653            2 :                 Lsn(0x28),
    9654            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9655            2 :             ),
    9656            2 :             (
    9657            2 :                 get_key(3),
    9658            2 :                 Lsn(0x30),
    9659            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9660            2 :             ),
    9661            2 :             (
    9662            2 :                 get_key(3),
    9663            2 :                 Lsn(0x40),
    9664            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9665            2 :             ),
    9666              :         ];
    9667            2 :         let delta2 = vec![
    9668            2 :             (
    9669            2 :                 get_key(5),
    9670            2 :                 Lsn(0x20),
    9671            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9672            2 :             ),
    9673            2 :             (
    9674            2 :                 get_key(6),
    9675            2 :                 Lsn(0x20),
    9676            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9677            2 :             ),
    9678              :         ];
    9679            2 :         let delta3 = vec![
    9680            2 :             (
    9681            2 :                 get_key(8),
    9682            2 :                 Lsn(0x48),
    9683            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9684            2 :             ),
    9685            2 :             (
    9686            2 :                 get_key(9),
    9687            2 :                 Lsn(0x48),
    9688            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9689            2 :             ),
    9690              :         ];
    9691              : 
    9692            2 :         let tline = if use_delta_bottom_layer {
    9693            1 :             tenant
    9694            1 :                 .create_test_timeline_with_layers(
    9695            1 :                     TIMELINE_ID,
    9696            1 :                     Lsn(0x08),
    9697            1 :                     DEFAULT_PG_VERSION,
    9698            1 :                     &ctx,
    9699            1 :                     Vec::new(), // in-memory layers
    9700            1 :                     vec![
    9701            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9702            1 :                             Lsn(0x08)..Lsn(0x10),
    9703            1 :                             delta4,
    9704            1 :                         ),
    9705            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9706            1 :                             Lsn(0x20)..Lsn(0x48),
    9707            1 :                             delta1,
    9708            1 :                         ),
    9709            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9710            1 :                             Lsn(0x20)..Lsn(0x48),
    9711            1 :                             delta2,
    9712            1 :                         ),
    9713            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9714            1 :                             Lsn(0x48)..Lsn(0x50),
    9715            1 :                             delta3,
    9716            1 :                         ),
    9717            1 :                     ], // delta layers
    9718            1 :                     vec![],     // image layers
    9719            1 :                     Lsn(0x50),
    9720            1 :                 )
    9721            1 :                 .await?
    9722              :         } else {
    9723            1 :             tenant
    9724            1 :                 .create_test_timeline_with_layers(
    9725            1 :                     TIMELINE_ID,
    9726            1 :                     Lsn(0x10),
    9727            1 :                     DEFAULT_PG_VERSION,
    9728            1 :                     &ctx,
    9729            1 :                     Vec::new(), // in-memory layers
    9730            1 :                     vec![
    9731            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9732            1 :                             Lsn(0x10)..Lsn(0x48),
    9733            1 :                             delta1,
    9734            1 :                         ),
    9735            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9736            1 :                             Lsn(0x10)..Lsn(0x48),
    9737            1 :                             delta2,
    9738            1 :                         ),
    9739            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9740            1 :                             Lsn(0x48)..Lsn(0x50),
    9741            1 :                             delta3,
    9742            1 :                         ),
    9743            1 :                     ], // delta layers
    9744            1 :                     vec![(Lsn(0x10), img_layer)], // image layers
    9745            1 :                     Lsn(0x50),
    9746            1 :                 )
    9747            1 :                 .await?
    9748              :         };
    9749              :         {
    9750            2 :             tline
    9751            2 :                 .applied_gc_cutoff_lsn
    9752            2 :                 .lock_for_write()
    9753            2 :                 .store_and_unlock(Lsn(0x30))
    9754            2 :                 .wait()
    9755            2 :                 .await;
    9756              :             // Update GC info
    9757            2 :             let mut guard = tline.gc_info.write().unwrap();
    9758            2 :             *guard = GcInfo {
    9759            2 :                 retain_lsns: vec![],
    9760            2 :                 cutoffs: GcCutoffs {
    9761            2 :                     time: Some(Lsn(0x30)),
    9762            2 :                     space: Lsn(0x30),
    9763            2 :                 },
    9764            2 :                 leases: Default::default(),
    9765            2 :                 within_ancestor_pitr: false,
    9766            2 :             };
    9767              :         }
    9768              : 
    9769            2 :         let expected_result = [
    9770            2 :             Bytes::from_static(b"value 0@0x10"),
    9771            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9772            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9773            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9774            2 :             Bytes::from_static(b"value 4@0x10"),
    9775            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9776            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9777            2 :             Bytes::from_static(b"value 7@0x10"),
    9778            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9779            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9780            2 :         ];
    9781              : 
    9782            2 :         let expected_result_at_gc_horizon = [
    9783            2 :             Bytes::from_static(b"value 0@0x10"),
    9784            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9785            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9786            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9787            2 :             Bytes::from_static(b"value 4@0x10"),
    9788            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9789            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9790            2 :             Bytes::from_static(b"value 7@0x10"),
    9791            2 :             Bytes::from_static(b"value 8@0x10"),
    9792            2 :             Bytes::from_static(b"value 9@0x10"),
    9793            2 :         ];
    9794              : 
    9795           22 :         for idx in 0..10 {
    9796           20 :             assert_eq!(
    9797           20 :                 tline
    9798           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9799           20 :                     .await
    9800           20 :                     .unwrap(),
    9801           20 :                 &expected_result[idx]
    9802              :             );
    9803           20 :             assert_eq!(
    9804           20 :                 tline
    9805           20 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9806           20 :                     .await
    9807           20 :                     .unwrap(),
    9808           20 :                 &expected_result_at_gc_horizon[idx]
    9809              :             );
    9810              :         }
    9811              : 
    9812            2 :         let cancel = CancellationToken::new();
    9813            2 :         tline
    9814            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9815            2 :             .await
    9816            2 :             .unwrap();
    9817              : 
    9818           22 :         for idx in 0..10 {
    9819           20 :             assert_eq!(
    9820           20 :                 tline
    9821           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9822           20 :                     .await
    9823           20 :                     .unwrap(),
    9824           20 :                 &expected_result[idx]
    9825              :             );
    9826           20 :             assert_eq!(
    9827           20 :                 tline
    9828           20 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9829           20 :                     .await
    9830           20 :                     .unwrap(),
    9831           20 :                 &expected_result_at_gc_horizon[idx]
    9832              :             );
    9833              :         }
    9834              : 
    9835              :         // increase GC horizon and compact again
    9836              :         {
    9837            2 :             tline
    9838            2 :                 .applied_gc_cutoff_lsn
    9839            2 :                 .lock_for_write()
    9840            2 :                 .store_and_unlock(Lsn(0x40))
    9841            2 :                 .wait()
    9842            2 :                 .await;
    9843              :             // Update GC info
    9844            2 :             let mut guard = tline.gc_info.write().unwrap();
    9845            2 :             guard.cutoffs.time = Some(Lsn(0x40));
    9846            2 :             guard.cutoffs.space = Lsn(0x40);
    9847              :         }
    9848            2 :         tline
    9849            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9850            2 :             .await
    9851            2 :             .unwrap();
    9852              : 
    9853            2 :         Ok(())
    9854            2 :     }
    9855              : 
    9856              :     #[cfg(feature = "testing")]
    9857              :     #[tokio::test]
    9858            1 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9859            1 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9860            1 :         let (tenant, ctx) = harness.load().await;
    9861            1 :         let tline = tenant
    9862            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9863            1 :             .await?;
    9864            1 :         tline.force_advance_lsn(Lsn(0x70));
    9865            1 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9866            1 :         let history = vec![
    9867            1 :             (
    9868            1 :                 key,
    9869            1 :                 Lsn(0x10),
    9870            1 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9871            1 :             ),
    9872            1 :             (
    9873            1 :                 key,
    9874            1 :                 Lsn(0x20),
    9875            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9876            1 :             ),
    9877            1 :             (
    9878            1 :                 key,
    9879            1 :                 Lsn(0x30),
    9880            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9881            1 :             ),
    9882            1 :             (
    9883            1 :                 key,
    9884            1 :                 Lsn(0x40),
    9885            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9886            1 :             ),
    9887            1 :             (
    9888            1 :                 key,
    9889            1 :                 Lsn(0x50),
    9890            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9891            1 :             ),
    9892            1 :             (
    9893            1 :                 key,
    9894            1 :                 Lsn(0x60),
    9895            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9896            1 :             ),
    9897            1 :             (
    9898            1 :                 key,
    9899            1 :                 Lsn(0x70),
    9900            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9901            1 :             ),
    9902            1 :             (
    9903            1 :                 key,
    9904            1 :                 Lsn(0x80),
    9905            1 :                 Value::Image(Bytes::copy_from_slice(
    9906            1 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9907            1 :                 )),
    9908            1 :             ),
    9909            1 :             (
    9910            1 :                 key,
    9911            1 :                 Lsn(0x90),
    9912            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9913            1 :             ),
    9914              :         ];
    9915            1 :         let res = tline
    9916            1 :             .generate_key_retention(
    9917            1 :                 key,
    9918            1 :                 &history,
    9919            1 :                 Lsn(0x60),
    9920            1 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9921            1 :                 3,
    9922            1 :                 None,
    9923            1 :                 true,
    9924            1 :             )
    9925            1 :             .await
    9926            1 :             .unwrap();
    9927            1 :         let expected_res = KeyHistoryRetention {
    9928            1 :             below_horizon: vec![
    9929            1 :                 (
    9930            1 :                     Lsn(0x20),
    9931            1 :                     KeyLogAtLsn(vec![(
    9932            1 :                         Lsn(0x20),
    9933            1 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9934            1 :                     )]),
    9935            1 :                 ),
    9936            1 :                 (
    9937            1 :                     Lsn(0x40),
    9938            1 :                     KeyLogAtLsn(vec![
    9939            1 :                         (
    9940            1 :                             Lsn(0x30),
    9941            1 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9942            1 :                         ),
    9943            1 :                         (
    9944            1 :                             Lsn(0x40),
    9945            1 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9946            1 :                         ),
    9947            1 :                     ]),
    9948            1 :                 ),
    9949            1 :                 (
    9950            1 :                     Lsn(0x50),
    9951            1 :                     KeyLogAtLsn(vec![(
    9952            1 :                         Lsn(0x50),
    9953            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9954            1 :                     )]),
    9955            1 :                 ),
    9956            1 :                 (
    9957            1 :                     Lsn(0x60),
    9958            1 :                     KeyLogAtLsn(vec![(
    9959            1 :                         Lsn(0x60),
    9960            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9961            1 :                     )]),
    9962            1 :                 ),
    9963            1 :             ],
    9964            1 :             above_horizon: KeyLogAtLsn(vec![
    9965            1 :                 (
    9966            1 :                     Lsn(0x70),
    9967            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9968            1 :                 ),
    9969            1 :                 (
    9970            1 :                     Lsn(0x80),
    9971            1 :                     Value::Image(Bytes::copy_from_slice(
    9972            1 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9973            1 :                     )),
    9974            1 :                 ),
    9975            1 :                 (
    9976            1 :                     Lsn(0x90),
    9977            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9978            1 :                 ),
    9979            1 :             ]),
    9980            1 :         };
    9981            1 :         assert_eq!(res, expected_res);
    9982              : 
    9983              :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9984              :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9985              :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9986              :         // For example, we have
    9987              :         // ```plain
    9988              :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9989              :         // ```
    9990              :         // Now the GC horizon moves up, and we have
    9991              :         // ```plain
    9992              :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9993              :         // ```
    9994              :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9995              :         // We will end up with
    9996              :         // ```plain
    9997              :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9998              :         // ```
    9999              :         // Now we run the GC-compaction, and this key does not have a full history.
   10000              :         // We should be able to handle this partial history and drop everything before the
   10001              :         // gc_horizon image.
   10002              : 
   10003            1 :         let history = vec![
   10004            1 :             (
   10005            1 :                 key,
   10006            1 :                 Lsn(0x20),
   10007            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10008            1 :             ),
   10009            1 :             (
   10010            1 :                 key,
   10011            1 :                 Lsn(0x30),
   10012            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
   10013            1 :             ),
   10014            1 :             (
   10015            1 :                 key,
   10016            1 :                 Lsn(0x40),
   10017            1 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
   10018            1 :             ),
   10019            1 :             (
   10020            1 :                 key,
   10021            1 :                 Lsn(0x50),
   10022            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
   10023            1 :             ),
   10024            1 :             (
   10025            1 :                 key,
   10026            1 :                 Lsn(0x60),
   10027            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10028            1 :             ),
   10029            1 :             (
   10030            1 :                 key,
   10031            1 :                 Lsn(0x70),
   10032            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10033            1 :             ),
   10034            1 :             (
   10035            1 :                 key,
   10036            1 :                 Lsn(0x80),
   10037            1 :                 Value::Image(Bytes::copy_from_slice(
   10038            1 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
   10039            1 :                 )),
   10040            1 :             ),
   10041            1 :             (
   10042            1 :                 key,
   10043            1 :                 Lsn(0x90),
   10044            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
   10045            1 :             ),
   10046              :         ];
   10047            1 :         let res = tline
   10048            1 :             .generate_key_retention(
   10049            1 :                 key,
   10050            1 :                 &history,
   10051            1 :                 Lsn(0x60),
   10052            1 :                 &[Lsn(0x40), Lsn(0x50)],
   10053            1 :                 3,
   10054            1 :                 None,
   10055            1 :                 true,
   10056            1 :             )
   10057            1 :             .await
   10058            1 :             .unwrap();
   10059            1 :         let expected_res = KeyHistoryRetention {
   10060            1 :             below_horizon: vec![
   10061            1 :                 (
   10062            1 :                     Lsn(0x40),
   10063            1 :                     KeyLogAtLsn(vec![(
   10064            1 :                         Lsn(0x40),
   10065            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
   10066            1 :                     )]),
   10067            1 :                 ),
   10068            1 :                 (
   10069            1 :                     Lsn(0x50),
   10070            1 :                     KeyLogAtLsn(vec![(
   10071            1 :                         Lsn(0x50),
   10072            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
   10073            1 :                     )]),
   10074            1 :                 ),
   10075            1 :                 (
   10076            1 :                     Lsn(0x60),
   10077            1 :                     KeyLogAtLsn(vec![(
   10078            1 :                         Lsn(0x60),
   10079            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10080            1 :                     )]),
   10081            1 :                 ),
   10082            1 :             ],
   10083            1 :             above_horizon: KeyLogAtLsn(vec![
   10084            1 :                 (
   10085            1 :                     Lsn(0x70),
   10086            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10087            1 :                 ),
   10088            1 :                 (
   10089            1 :                     Lsn(0x80),
   10090            1 :                     Value::Image(Bytes::copy_from_slice(
   10091            1 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
   10092            1 :                     )),
   10093            1 :                 ),
   10094            1 :                 (
   10095            1 :                     Lsn(0x90),
   10096            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
   10097            1 :                 ),
   10098            1 :             ]),
   10099            1 :         };
   10100            1 :         assert_eq!(res, expected_res);
   10101              : 
   10102              :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
   10103              :         // the ancestor image in the test case.
   10104              : 
   10105            1 :         let history = vec![
   10106            1 :             (
   10107            1 :                 key,
   10108            1 :                 Lsn(0x20),
   10109            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10110            1 :             ),
   10111            1 :             (
   10112            1 :                 key,
   10113            1 :                 Lsn(0x30),
   10114            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
   10115            1 :             ),
   10116            1 :             (
   10117            1 :                 key,
   10118            1 :                 Lsn(0x40),
   10119            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
   10120            1 :             ),
   10121            1 :             (
   10122            1 :                 key,
   10123            1 :                 Lsn(0x70),
   10124            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10125            1 :             ),
   10126              :         ];
   10127            1 :         let res = tline
   10128            1 :             .generate_key_retention(
   10129            1 :                 key,
   10130            1 :                 &history,
   10131            1 :                 Lsn(0x60),
   10132            1 :                 &[],
   10133            1 :                 3,
   10134            1 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
   10135            1 :                 true,
   10136            1 :             )
   10137            1 :             .await
   10138            1 :             .unwrap();
   10139            1 :         let expected_res = KeyHistoryRetention {
   10140            1 :             below_horizon: vec![(
   10141            1 :                 Lsn(0x60),
   10142            1 :                 KeyLogAtLsn(vec![(
   10143            1 :                     Lsn(0x60),
   10144            1 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
   10145            1 :                 )]),
   10146            1 :             )],
   10147            1 :             above_horizon: KeyLogAtLsn(vec![(
   10148            1 :                 Lsn(0x70),
   10149            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10150            1 :             )]),
   10151            1 :         };
   10152            1 :         assert_eq!(res, expected_res);
   10153              : 
   10154            1 :         let history = vec![
   10155            1 :             (
   10156            1 :                 key,
   10157            1 :                 Lsn(0x20),
   10158            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10159            1 :             ),
   10160            1 :             (
   10161            1 :                 key,
   10162            1 :                 Lsn(0x40),
   10163            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
   10164            1 :             ),
   10165            1 :             (
   10166            1 :                 key,
   10167            1 :                 Lsn(0x60),
   10168            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10169            1 :             ),
   10170            1 :             (
   10171            1 :                 key,
   10172            1 :                 Lsn(0x70),
   10173            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10174            1 :             ),
   10175              :         ];
   10176            1 :         let res = tline
   10177            1 :             .generate_key_retention(
   10178            1 :                 key,
   10179            1 :                 &history,
   10180            1 :                 Lsn(0x60),
   10181            1 :                 &[Lsn(0x30)],
   10182            1 :                 3,
   10183            1 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
   10184            1 :                 true,
   10185            1 :             )
   10186            1 :             .await
   10187            1 :             .unwrap();
   10188            1 :         let expected_res = KeyHistoryRetention {
   10189            1 :             below_horizon: vec![
   10190            1 :                 (
   10191            1 :                     Lsn(0x30),
   10192            1 :                     KeyLogAtLsn(vec![(
   10193            1 :                         Lsn(0x20),
   10194            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10195            1 :                     )]),
   10196            1 :                 ),
   10197            1 :                 (
   10198            1 :                     Lsn(0x60),
   10199            1 :                     KeyLogAtLsn(vec![(
   10200            1 :                         Lsn(0x60),
   10201            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
   10202            1 :                     )]),
   10203            1 :                 ),
   10204            1 :             ],
   10205            1 :             above_horizon: KeyLogAtLsn(vec![(
   10206            1 :                 Lsn(0x70),
   10207            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10208            1 :             )]),
   10209            1 :         };
   10210            1 :         assert_eq!(res, expected_res);
   10211              : 
   10212            2 :         Ok(())
   10213            1 :     }
   10214              : 
   10215              :     #[cfg(feature = "testing")]
   10216              :     #[tokio::test]
   10217            1 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
   10218            1 :         let harness =
   10219            1 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
   10220            1 :         let (tenant, ctx) = harness.load().await;
   10221              : 
   10222          259 :         fn get_key(id: u32) -> Key {
   10223              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10224          259 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10225          259 :             key.field6 = id;
   10226          259 :             key
   10227          259 :         }
   10228              : 
   10229            1 :         let img_layer = (0..10)
   10230           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10231            1 :             .collect_vec();
   10232              : 
   10233            1 :         let delta1 = vec![
   10234            1 :             (
   10235            1 :                 get_key(1),
   10236            1 :                 Lsn(0x20),
   10237            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10238            1 :             ),
   10239            1 :             (
   10240            1 :                 get_key(2),
   10241            1 :                 Lsn(0x30),
   10242            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10243            1 :             ),
   10244            1 :             (
   10245            1 :                 get_key(3),
   10246            1 :                 Lsn(0x28),
   10247            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10248            1 :             ),
   10249            1 :             (
   10250            1 :                 get_key(3),
   10251            1 :                 Lsn(0x30),
   10252            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10253            1 :             ),
   10254            1 :             (
   10255            1 :                 get_key(3),
   10256            1 :                 Lsn(0x40),
   10257            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10258            1 :             ),
   10259              :         ];
   10260            1 :         let delta2 = vec![
   10261            1 :             (
   10262            1 :                 get_key(5),
   10263            1 :                 Lsn(0x20),
   10264            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10265            1 :             ),
   10266            1 :             (
   10267            1 :                 get_key(6),
   10268            1 :                 Lsn(0x20),
   10269            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10270            1 :             ),
   10271              :         ];
   10272            1 :         let delta3 = vec![
   10273            1 :             (
   10274            1 :                 get_key(8),
   10275            1 :                 Lsn(0x48),
   10276            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10277            1 :             ),
   10278            1 :             (
   10279            1 :                 get_key(9),
   10280            1 :                 Lsn(0x48),
   10281            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10282            1 :             ),
   10283              :         ];
   10284              : 
   10285            1 :         let tline = tenant
   10286            1 :             .create_test_timeline_with_layers(
   10287            1 :                 TIMELINE_ID,
   10288            1 :                 Lsn(0x10),
   10289            1 :                 DEFAULT_PG_VERSION,
   10290            1 :                 &ctx,
   10291            1 :                 Vec::new(), // in-memory layers
   10292            1 :                 vec![
   10293            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
   10294            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
   10295            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10296            1 :                 ], // delta layers
   10297            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10298            1 :                 Lsn(0x50),
   10299            1 :             )
   10300            1 :             .await?;
   10301              :         {
   10302            1 :             tline
   10303            1 :                 .applied_gc_cutoff_lsn
   10304            1 :                 .lock_for_write()
   10305            1 :                 .store_and_unlock(Lsn(0x30))
   10306            1 :                 .wait()
   10307            1 :                 .await;
   10308              :             // Update GC info
   10309            1 :             let mut guard = tline.gc_info.write().unwrap();
   10310            1 :             *guard = GcInfo {
   10311            1 :                 retain_lsns: vec![
   10312            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10313            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10314            1 :                 ],
   10315            1 :                 cutoffs: GcCutoffs {
   10316            1 :                     time: Some(Lsn(0x30)),
   10317            1 :                     space: Lsn(0x30),
   10318            1 :                 },
   10319            1 :                 leases: Default::default(),
   10320            1 :                 within_ancestor_pitr: false,
   10321            1 :             };
   10322              :         }
   10323              : 
   10324            1 :         let expected_result = [
   10325            1 :             Bytes::from_static(b"value 0@0x10"),
   10326            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10327            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10328            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10329            1 :             Bytes::from_static(b"value 4@0x10"),
   10330            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10331            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10332            1 :             Bytes::from_static(b"value 7@0x10"),
   10333            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10334            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10335            1 :         ];
   10336              : 
   10337            1 :         let expected_result_at_gc_horizon = [
   10338            1 :             Bytes::from_static(b"value 0@0x10"),
   10339            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10340            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10341            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
   10342            1 :             Bytes::from_static(b"value 4@0x10"),
   10343            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10344            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10345            1 :             Bytes::from_static(b"value 7@0x10"),
   10346            1 :             Bytes::from_static(b"value 8@0x10"),
   10347            1 :             Bytes::from_static(b"value 9@0x10"),
   10348            1 :         ];
   10349              : 
   10350            1 :         let expected_result_at_lsn_20 = [
   10351            1 :             Bytes::from_static(b"value 0@0x10"),
   10352            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10353            1 :             Bytes::from_static(b"value 2@0x10"),
   10354            1 :             Bytes::from_static(b"value 3@0x10"),
   10355            1 :             Bytes::from_static(b"value 4@0x10"),
   10356            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10357            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10358            1 :             Bytes::from_static(b"value 7@0x10"),
   10359            1 :             Bytes::from_static(b"value 8@0x10"),
   10360            1 :             Bytes::from_static(b"value 9@0x10"),
   10361            1 :         ];
   10362              : 
   10363            1 :         let expected_result_at_lsn_10 = [
   10364            1 :             Bytes::from_static(b"value 0@0x10"),
   10365            1 :             Bytes::from_static(b"value 1@0x10"),
   10366            1 :             Bytes::from_static(b"value 2@0x10"),
   10367            1 :             Bytes::from_static(b"value 3@0x10"),
   10368            1 :             Bytes::from_static(b"value 4@0x10"),
   10369            1 :             Bytes::from_static(b"value 5@0x10"),
   10370            1 :             Bytes::from_static(b"value 6@0x10"),
   10371            1 :             Bytes::from_static(b"value 7@0x10"),
   10372            1 :             Bytes::from_static(b"value 8@0x10"),
   10373            1 :             Bytes::from_static(b"value 9@0x10"),
   10374            1 :         ];
   10375              : 
   10376            6 :         let verify_result = || async {
   10377            6 :             let gc_horizon = {
   10378            6 :                 let gc_info = tline.gc_info.read().unwrap();
   10379            6 :                 gc_info.cutoffs.time.unwrap_or_default()
   10380              :             };
   10381           66 :             for idx in 0..10 {
   10382           60 :                 assert_eq!(
   10383           60 :                     tline
   10384           60 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10385           60 :                         .await
   10386           60 :                         .unwrap(),
   10387           60 :                     &expected_result[idx]
   10388              :                 );
   10389           60 :                 assert_eq!(
   10390           60 :                     tline
   10391           60 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10392           60 :                         .await
   10393           60 :                         .unwrap(),
   10394           60 :                     &expected_result_at_gc_horizon[idx]
   10395              :                 );
   10396           60 :                 assert_eq!(
   10397           60 :                     tline
   10398           60 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10399           60 :                         .await
   10400           60 :                         .unwrap(),
   10401           60 :                     &expected_result_at_lsn_20[idx]
   10402              :                 );
   10403           60 :                 assert_eq!(
   10404           60 :                     tline
   10405           60 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10406           60 :                         .await
   10407           60 :                         .unwrap(),
   10408           60 :                     &expected_result_at_lsn_10[idx]
   10409              :                 );
   10410              :             }
   10411           12 :         };
   10412              : 
   10413            1 :         verify_result().await;
   10414              : 
   10415            1 :         let cancel = CancellationToken::new();
   10416            1 :         let mut dryrun_flags = EnumSet::new();
   10417            1 :         dryrun_flags.insert(CompactFlags::DryRun);
   10418              : 
   10419            1 :         tline
   10420            1 :             .compact_with_gc(
   10421            1 :                 &cancel,
   10422            1 :                 CompactOptions {
   10423            1 :                     flags: dryrun_flags,
   10424            1 :                     ..Default::default()
   10425            1 :                 },
   10426            1 :                 &ctx,
   10427            1 :             )
   10428            1 :             .await
   10429            1 :             .unwrap();
   10430              :         // 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
   10431              :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10432            1 :         verify_result().await;
   10433              : 
   10434            1 :         tline
   10435            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10436            1 :             .await
   10437            1 :             .unwrap();
   10438            1 :         verify_result().await;
   10439              : 
   10440              :         // compact again
   10441            1 :         tline
   10442            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10443            1 :             .await
   10444            1 :             .unwrap();
   10445            1 :         verify_result().await;
   10446              : 
   10447              :         // increase GC horizon and compact again
   10448              :         {
   10449            1 :             tline
   10450            1 :                 .applied_gc_cutoff_lsn
   10451            1 :                 .lock_for_write()
   10452            1 :                 .store_and_unlock(Lsn(0x38))
   10453            1 :                 .wait()
   10454            1 :                 .await;
   10455              :             // Update GC info
   10456            1 :             let mut guard = tline.gc_info.write().unwrap();
   10457            1 :             guard.cutoffs.time = Some(Lsn(0x38));
   10458            1 :             guard.cutoffs.space = Lsn(0x38);
   10459              :         }
   10460            1 :         tline
   10461            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10462            1 :             .await
   10463            1 :             .unwrap();
   10464            1 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
   10465              : 
   10466              :         // not increasing the GC horizon and compact again
   10467            1 :         tline
   10468            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10469            1 :             .await
   10470            1 :             .unwrap();
   10471            1 :         verify_result().await;
   10472              : 
   10473            2 :         Ok(())
   10474            1 :     }
   10475              : 
   10476              :     #[cfg(feature = "testing")]
   10477              :     #[tokio::test]
   10478            1 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
   10479            1 :     {
   10480            1 :         let harness =
   10481            1 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
   10482            1 :                 .await?;
   10483            1 :         let (tenant, ctx) = harness.load().await;
   10484              : 
   10485          176 :         fn get_key(id: u32) -> Key {
   10486              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10487          176 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10488          176 :             key.field6 = id;
   10489          176 :             key
   10490          176 :         }
   10491              : 
   10492            1 :         let img_layer = (0..10)
   10493           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10494            1 :             .collect_vec();
   10495              : 
   10496            1 :         let delta1 = vec![
   10497            1 :             (
   10498            1 :                 get_key(1),
   10499            1 :                 Lsn(0x20),
   10500            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10501            1 :             ),
   10502            1 :             (
   10503            1 :                 get_key(1),
   10504            1 :                 Lsn(0x28),
   10505            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10506            1 :             ),
   10507              :         ];
   10508            1 :         let delta2 = vec![
   10509            1 :             (
   10510            1 :                 get_key(1),
   10511            1 :                 Lsn(0x30),
   10512            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10513            1 :             ),
   10514            1 :             (
   10515            1 :                 get_key(1),
   10516            1 :                 Lsn(0x38),
   10517            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10518            1 :             ),
   10519              :         ];
   10520            1 :         let delta3 = vec![
   10521            1 :             (
   10522            1 :                 get_key(8),
   10523            1 :                 Lsn(0x48),
   10524            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10525            1 :             ),
   10526            1 :             (
   10527            1 :                 get_key(9),
   10528            1 :                 Lsn(0x48),
   10529            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10530            1 :             ),
   10531              :         ];
   10532              : 
   10533            1 :         let tline = tenant
   10534            1 :             .create_test_timeline_with_layers(
   10535            1 :                 TIMELINE_ID,
   10536            1 :                 Lsn(0x10),
   10537            1 :                 DEFAULT_PG_VERSION,
   10538            1 :                 &ctx,
   10539            1 :                 Vec::new(), // in-memory layers
   10540            1 :                 vec![
   10541            1 :                     // delta1 and delta 2 only contain a single key but multiple updates
   10542            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
   10543            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10544            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
   10545            1 :                 ], // delta layers
   10546            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10547            1 :                 Lsn(0x50),
   10548            1 :             )
   10549            1 :             .await?;
   10550              :         {
   10551            1 :             tline
   10552            1 :                 .applied_gc_cutoff_lsn
   10553            1 :                 .lock_for_write()
   10554            1 :                 .store_and_unlock(Lsn(0x30))
   10555            1 :                 .wait()
   10556            1 :                 .await;
   10557              :             // Update GC info
   10558            1 :             let mut guard = tline.gc_info.write().unwrap();
   10559            1 :             *guard = GcInfo {
   10560            1 :                 retain_lsns: vec![
   10561            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10562            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10563            1 :                 ],
   10564            1 :                 cutoffs: GcCutoffs {
   10565            1 :                     time: Some(Lsn(0x30)),
   10566            1 :                     space: Lsn(0x30),
   10567            1 :                 },
   10568            1 :                 leases: Default::default(),
   10569            1 :                 within_ancestor_pitr: false,
   10570            1 :             };
   10571              :         }
   10572              : 
   10573            1 :         let expected_result = [
   10574            1 :             Bytes::from_static(b"value 0@0x10"),
   10575            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10576            1 :             Bytes::from_static(b"value 2@0x10"),
   10577            1 :             Bytes::from_static(b"value 3@0x10"),
   10578            1 :             Bytes::from_static(b"value 4@0x10"),
   10579            1 :             Bytes::from_static(b"value 5@0x10"),
   10580            1 :             Bytes::from_static(b"value 6@0x10"),
   10581            1 :             Bytes::from_static(b"value 7@0x10"),
   10582            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10583            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10584            1 :         ];
   10585              : 
   10586            1 :         let expected_result_at_gc_horizon = [
   10587            1 :             Bytes::from_static(b"value 0@0x10"),
   10588            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10589            1 :             Bytes::from_static(b"value 2@0x10"),
   10590            1 :             Bytes::from_static(b"value 3@0x10"),
   10591            1 :             Bytes::from_static(b"value 4@0x10"),
   10592            1 :             Bytes::from_static(b"value 5@0x10"),
   10593            1 :             Bytes::from_static(b"value 6@0x10"),
   10594            1 :             Bytes::from_static(b"value 7@0x10"),
   10595            1 :             Bytes::from_static(b"value 8@0x10"),
   10596            1 :             Bytes::from_static(b"value 9@0x10"),
   10597            1 :         ];
   10598              : 
   10599            1 :         let expected_result_at_lsn_20 = [
   10600            1 :             Bytes::from_static(b"value 0@0x10"),
   10601            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10602            1 :             Bytes::from_static(b"value 2@0x10"),
   10603            1 :             Bytes::from_static(b"value 3@0x10"),
   10604            1 :             Bytes::from_static(b"value 4@0x10"),
   10605            1 :             Bytes::from_static(b"value 5@0x10"),
   10606            1 :             Bytes::from_static(b"value 6@0x10"),
   10607            1 :             Bytes::from_static(b"value 7@0x10"),
   10608            1 :             Bytes::from_static(b"value 8@0x10"),
   10609            1 :             Bytes::from_static(b"value 9@0x10"),
   10610            1 :         ];
   10611              : 
   10612            1 :         let expected_result_at_lsn_10 = [
   10613            1 :             Bytes::from_static(b"value 0@0x10"),
   10614            1 :             Bytes::from_static(b"value 1@0x10"),
   10615            1 :             Bytes::from_static(b"value 2@0x10"),
   10616            1 :             Bytes::from_static(b"value 3@0x10"),
   10617            1 :             Bytes::from_static(b"value 4@0x10"),
   10618            1 :             Bytes::from_static(b"value 5@0x10"),
   10619            1 :             Bytes::from_static(b"value 6@0x10"),
   10620            1 :             Bytes::from_static(b"value 7@0x10"),
   10621            1 :             Bytes::from_static(b"value 8@0x10"),
   10622            1 :             Bytes::from_static(b"value 9@0x10"),
   10623            1 :         ];
   10624              : 
   10625            4 :         let verify_result = || async {
   10626            4 :             let gc_horizon = {
   10627            4 :                 let gc_info = tline.gc_info.read().unwrap();
   10628            4 :                 gc_info.cutoffs.time.unwrap_or_default()
   10629              :             };
   10630           44 :             for idx in 0..10 {
   10631           40 :                 assert_eq!(
   10632           40 :                     tline
   10633           40 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10634           40 :                         .await
   10635           40 :                         .unwrap(),
   10636           40 :                     &expected_result[idx]
   10637              :                 );
   10638           40 :                 assert_eq!(
   10639           40 :                     tline
   10640           40 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10641           40 :                         .await
   10642           40 :                         .unwrap(),
   10643           40 :                     &expected_result_at_gc_horizon[idx]
   10644              :                 );
   10645           40 :                 assert_eq!(
   10646           40 :                     tline
   10647           40 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10648           40 :                         .await
   10649           40 :                         .unwrap(),
   10650           40 :                     &expected_result_at_lsn_20[idx]
   10651              :                 );
   10652           40 :                 assert_eq!(
   10653           40 :                     tline
   10654           40 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10655           40 :                         .await
   10656           40 :                         .unwrap(),
   10657           40 :                     &expected_result_at_lsn_10[idx]
   10658              :                 );
   10659              :             }
   10660            8 :         };
   10661              : 
   10662            1 :         verify_result().await;
   10663              : 
   10664            1 :         let cancel = CancellationToken::new();
   10665            1 :         let mut dryrun_flags = EnumSet::new();
   10666            1 :         dryrun_flags.insert(CompactFlags::DryRun);
   10667              : 
   10668            1 :         tline
   10669            1 :             .compact_with_gc(
   10670            1 :                 &cancel,
   10671            1 :                 CompactOptions {
   10672            1 :                     flags: dryrun_flags,
   10673            1 :                     ..Default::default()
   10674            1 :                 },
   10675            1 :                 &ctx,
   10676            1 :             )
   10677            1 :             .await
   10678            1 :             .unwrap();
   10679              :         // 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
   10680              :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10681            1 :         verify_result().await;
   10682              : 
   10683            1 :         tline
   10684            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10685            1 :             .await
   10686            1 :             .unwrap();
   10687            1 :         verify_result().await;
   10688              : 
   10689              :         // compact again
   10690            1 :         tline
   10691            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10692            1 :             .await
   10693            1 :             .unwrap();
   10694            1 :         verify_result().await;
   10695              : 
   10696            2 :         Ok(())
   10697            1 :     }
   10698              : 
   10699              :     #[cfg(feature = "testing")]
   10700              :     #[tokio::test]
   10701            1 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
   10702              :         use models::CompactLsnRange;
   10703              : 
   10704            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
   10705            1 :         let (tenant, ctx) = harness.load().await;
   10706              : 
   10707           83 :         fn get_key(id: u32) -> Key {
   10708           83 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
   10709           83 :             key.field6 = id;
   10710           83 :             key
   10711           83 :         }
   10712              : 
   10713            1 :         let img_layer = (0..10)
   10714           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10715            1 :             .collect_vec();
   10716              : 
   10717            1 :         let delta1 = vec![
   10718            1 :             (
   10719            1 :                 get_key(1),
   10720            1 :                 Lsn(0x20),
   10721            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10722            1 :             ),
   10723            1 :             (
   10724            1 :                 get_key(2),
   10725            1 :                 Lsn(0x30),
   10726            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10727            1 :             ),
   10728            1 :             (
   10729            1 :                 get_key(3),
   10730            1 :                 Lsn(0x28),
   10731            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10732            1 :             ),
   10733            1 :             (
   10734            1 :                 get_key(3),
   10735            1 :                 Lsn(0x30),
   10736            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10737            1 :             ),
   10738            1 :             (
   10739            1 :                 get_key(3),
   10740            1 :                 Lsn(0x40),
   10741            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10742            1 :             ),
   10743              :         ];
   10744            1 :         let delta2 = vec![
   10745            1 :             (
   10746            1 :                 get_key(5),
   10747            1 :                 Lsn(0x20),
   10748            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10749            1 :             ),
   10750            1 :             (
   10751            1 :                 get_key(6),
   10752            1 :                 Lsn(0x20),
   10753            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10754            1 :             ),
   10755              :         ];
   10756            1 :         let delta3 = vec![
   10757            1 :             (
   10758            1 :                 get_key(8),
   10759            1 :                 Lsn(0x48),
   10760            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10761            1 :             ),
   10762            1 :             (
   10763            1 :                 get_key(9),
   10764            1 :                 Lsn(0x48),
   10765            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10766            1 :             ),
   10767              :         ];
   10768              : 
   10769            1 :         let parent_tline = tenant
   10770            1 :             .create_test_timeline_with_layers(
   10771            1 :                 TIMELINE_ID,
   10772            1 :                 Lsn(0x10),
   10773            1 :                 DEFAULT_PG_VERSION,
   10774            1 :                 &ctx,
   10775            1 :                 vec![],                       // in-memory layers
   10776            1 :                 vec![],                       // delta layers
   10777            1 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10778            1 :                 Lsn(0x18),
   10779            1 :             )
   10780            1 :             .await?;
   10781              : 
   10782            1 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10783              : 
   10784            1 :         let branch_tline = tenant
   10785            1 :             .branch_timeline_test_with_layers(
   10786            1 :                 &parent_tline,
   10787            1 :                 NEW_TIMELINE_ID,
   10788            1 :                 Some(Lsn(0x18)),
   10789            1 :                 &ctx,
   10790            1 :                 vec![
   10791            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10792            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10793            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10794            1 :                 ], // delta layers
   10795            1 :                 vec![], // image layers
   10796            1 :                 Lsn(0x50),
   10797            1 :             )
   10798            1 :             .await?;
   10799              : 
   10800            1 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10801              : 
   10802              :         {
   10803            1 :             parent_tline
   10804            1 :                 .applied_gc_cutoff_lsn
   10805            1 :                 .lock_for_write()
   10806            1 :                 .store_and_unlock(Lsn(0x10))
   10807            1 :                 .wait()
   10808            1 :                 .await;
   10809              :             // Update GC info
   10810            1 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10811            1 :             *guard = GcInfo {
   10812            1 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10813            1 :                 cutoffs: GcCutoffs {
   10814            1 :                     time: Some(Lsn(0x10)),
   10815            1 :                     space: Lsn(0x10),
   10816            1 :                 },
   10817            1 :                 leases: Default::default(),
   10818            1 :                 within_ancestor_pitr: false,
   10819            1 :             };
   10820              :         }
   10821              : 
   10822              :         {
   10823            1 :             branch_tline
   10824            1 :                 .applied_gc_cutoff_lsn
   10825            1 :                 .lock_for_write()
   10826            1 :                 .store_and_unlock(Lsn(0x50))
   10827            1 :                 .wait()
   10828            1 :                 .await;
   10829              :             // Update GC info
   10830            1 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10831            1 :             *guard = GcInfo {
   10832            1 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10833            1 :                 cutoffs: GcCutoffs {
   10834            1 :                     time: Some(Lsn(0x50)),
   10835            1 :                     space: Lsn(0x50),
   10836            1 :                 },
   10837            1 :                 leases: Default::default(),
   10838            1 :                 within_ancestor_pitr: false,
   10839            1 :             };
   10840              :         }
   10841              : 
   10842            1 :         let expected_result_at_gc_horizon = [
   10843            1 :             Bytes::from_static(b"value 0@0x10"),
   10844            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10845            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10846            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10847            1 :             Bytes::from_static(b"value 4@0x10"),
   10848            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10849            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10850            1 :             Bytes::from_static(b"value 7@0x10"),
   10851            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10852            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10853            1 :         ];
   10854              : 
   10855            1 :         let expected_result_at_lsn_40 = [
   10856            1 :             Bytes::from_static(b"value 0@0x10"),
   10857            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10858            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10859            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10860            1 :             Bytes::from_static(b"value 4@0x10"),
   10861            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10862            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10863            1 :             Bytes::from_static(b"value 7@0x10"),
   10864            1 :             Bytes::from_static(b"value 8@0x10"),
   10865            1 :             Bytes::from_static(b"value 9@0x10"),
   10866            1 :         ];
   10867              : 
   10868            3 :         let verify_result = || async {
   10869           33 :             for idx in 0..10 {
   10870           30 :                 assert_eq!(
   10871           30 :                     branch_tline
   10872           30 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10873           30 :                         .await
   10874           30 :                         .unwrap(),
   10875           30 :                     &expected_result_at_gc_horizon[idx]
   10876              :                 );
   10877           30 :                 assert_eq!(
   10878           30 :                     branch_tline
   10879           30 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10880           30 :                         .await
   10881           30 :                         .unwrap(),
   10882           30 :                     &expected_result_at_lsn_40[idx]
   10883              :                 );
   10884              :             }
   10885            6 :         };
   10886              : 
   10887            1 :         verify_result().await;
   10888              : 
   10889            1 :         let cancel = CancellationToken::new();
   10890            1 :         branch_tline
   10891            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10892            1 :             .await
   10893            1 :             .unwrap();
   10894              : 
   10895            1 :         verify_result().await;
   10896              : 
   10897              :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10898              :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10899            1 :         branch_tline
   10900            1 :             .compact_with_gc(
   10901            1 :                 &cancel,
   10902            1 :                 CompactOptions {
   10903            1 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10904            1 :                     ..Default::default()
   10905            1 :                 },
   10906            1 :                 &ctx,
   10907            1 :             )
   10908            1 :             .await
   10909            1 :             .unwrap();
   10910              : 
   10911            1 :         verify_result().await;
   10912              : 
   10913            2 :         Ok(())
   10914            1 :     }
   10915              : 
   10916              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
   10917              :     // Create an image arrangement where we have to read at different LSN ranges
   10918              :     // from a delta layer. This is achieved by overlapping an image layer on top of
   10919              :     // a delta layer. Like so:
   10920              :     //
   10921              :     //     A      B
   10922              :     // +----------------+ -> delta_layer
   10923              :     // |                |                           ^ lsn
   10924              :     // |       =========|-> nested_image_layer      |
   10925              :     // |       C        |                           |
   10926              :     // +----------------+                           |
   10927              :     // ======== -> baseline_image_layer             +-------> key
   10928              :     //
   10929              :     //
   10930              :     // When querying the key range [A, B) we need to read at different LSN ranges
   10931              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   10932              :     #[cfg(feature = "testing")]
   10933              :     #[tokio::test]
   10934            1 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10935            1 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10936            1 :         let (tenant, ctx) = harness.load().await;
   10937              : 
   10938            1 :         let will_init_keys = [2, 6];
   10939           22 :         fn get_key(id: u32) -> Key {
   10940           22 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10941           22 :             key.field6 = id;
   10942           22 :             key
   10943           22 :         }
   10944              : 
   10945            1 :         let mut expected_key_values = HashMap::new();
   10946              : 
   10947            1 :         let baseline_image_layer_lsn = Lsn(0x10);
   10948            1 :         let mut baseline_img_layer = Vec::new();
   10949            6 :         for i in 0..5 {
   10950            5 :             let key = get_key(i);
   10951            5 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10952              : 
   10953            5 :             let removed = expected_key_values.insert(key, value.clone());
   10954            5 :             assert!(removed.is_none());
   10955              : 
   10956            5 :             baseline_img_layer.push((key, Bytes::from(value)));
   10957              :         }
   10958              : 
   10959            1 :         let nested_image_layer_lsn = Lsn(0x50);
   10960            1 :         let mut nested_img_layer = Vec::new();
   10961            6 :         for i in 5..10 {
   10962            5 :             let key = get_key(i);
   10963            5 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10964              : 
   10965            5 :             let removed = expected_key_values.insert(key, value.clone());
   10966            5 :             assert!(removed.is_none());
   10967              : 
   10968            5 :             nested_img_layer.push((key, Bytes::from(value)));
   10969              :         }
   10970              : 
   10971            1 :         let mut delta_layer_spec = Vec::default();
   10972            1 :         let delta_layer_start_lsn = Lsn(0x20);
   10973            1 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10974              : 
   10975           11 :         for i in 0..10 {
   10976           10 :             let key = get_key(i);
   10977           10 :             let key_in_nested = nested_img_layer
   10978           10 :                 .iter()
   10979           40 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10980           10 :             let lsn = {
   10981           10 :                 if key_in_nested {
   10982            5 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   10983              :                 } else {
   10984            5 :                     delta_layer_start_lsn
   10985              :                 }
   10986              :             };
   10987              : 
   10988           10 :             let will_init = will_init_keys.contains(&i);
   10989           10 :             if will_init {
   10990            2 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10991            2 : 
   10992            2 :                 expected_key_values.insert(key, "".to_string());
   10993            8 :             } else {
   10994            8 :                 let delta = format!("@{lsn}");
   10995            8 :                 delta_layer_spec.push((
   10996            8 :                     key,
   10997            8 :                     lsn,
   10998            8 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10999            8 :                 ));
   11000            8 : 
   11001            8 :                 expected_key_values
   11002            8 :                     .get_mut(&key)
   11003            8 :                     .expect("An image exists for each key")
   11004            8 :                     .push_str(delta.as_str());
   11005            8 :             }
   11006           10 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   11007              :         }
   11008              : 
   11009            1 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   11010              : 
   11011            1 :         assert!(
   11012            1 :             nested_image_layer_lsn > delta_layer_start_lsn
   11013            1 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   11014              :         );
   11015              : 
   11016            1 :         let tline = tenant
   11017            1 :             .create_test_timeline_with_layers(
   11018            1 :                 TIMELINE_ID,
   11019            1 :                 baseline_image_layer_lsn,
   11020            1 :                 DEFAULT_PG_VERSION,
   11021            1 :                 &ctx,
   11022            1 :                 vec![], // in-memory layers
   11023            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   11024            1 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   11025            1 :                     delta_layer_spec,
   11026            1 :                 )], // delta layers
   11027            1 :                 vec![
   11028            1 :                     (baseline_image_layer_lsn, baseline_img_layer),
   11029            1 :                     (nested_image_layer_lsn, nested_img_layer),
   11030            1 :                 ], // image layers
   11031            1 :                 delta_layer_end_lsn,
   11032            1 :             )
   11033            1 :             .await?;
   11034              : 
   11035            1 :         let query = VersionedKeySpaceQuery::uniform(
   11036            1 :             KeySpace::single(get_key(0)..get_key(10)),
   11037            1 :             delta_layer_end_lsn,
   11038              :         );
   11039              : 
   11040            1 :         let results = tline
   11041            1 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   11042            1 :             .await
   11043            1 :             .expect("No vectored errors");
   11044           11 :         for (key, res) in results {
   11045           10 :             let value = res.expect("No key errors");
   11046           10 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   11047           10 :             assert_eq!(value, Bytes::from(expected_value));
   11048            1 :         }
   11049            1 : 
   11050            1 :         Ok(())
   11051            1 :     }
   11052              : 
   11053              :     #[cfg(feature = "testing")]
   11054              :     #[tokio::test]
   11055            1 :     async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
   11056            1 :         let harness =
   11057            1 :             TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
   11058            1 :         let (tenant, ctx) = harness.load().await;
   11059              : 
   11060            1 :         let will_init_keys = [2, 6];
   11061           32 :         fn get_key(id: u32) -> Key {
   11062           32 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   11063           32 :             key.field6 = id;
   11064           32 :             key
   11065           32 :         }
   11066              : 
   11067            1 :         let mut expected_key_values = HashMap::new();
   11068              : 
   11069            1 :         let baseline_image_layer_lsn = Lsn(0x10);
   11070            1 :         let mut baseline_img_layer = Vec::new();
   11071            6 :         for i in 0..5 {
   11072            5 :             let key = get_key(i);
   11073            5 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   11074              : 
   11075            5 :             let removed = expected_key_values.insert(key, value.clone());
   11076            5 :             assert!(removed.is_none());
   11077              : 
   11078            5 :             baseline_img_layer.push((key, Bytes::from(value)));
   11079              :         }
   11080              : 
   11081            1 :         let nested_image_layer_lsn = Lsn(0x50);
   11082            1 :         let mut nested_img_layer = Vec::new();
   11083            6 :         for i in 5..10 {
   11084            5 :             let key = get_key(i);
   11085            5 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   11086              : 
   11087            5 :             let removed = expected_key_values.insert(key, value.clone());
   11088            5 :             assert!(removed.is_none());
   11089              : 
   11090            5 :             nested_img_layer.push((key, Bytes::from(value)));
   11091              :         }
   11092              : 
   11093            1 :         let frozen_layer = {
   11094            1 :             let lsn_range = Lsn(0x40)..Lsn(0x60);
   11095            1 :             let mut data = Vec::new();
   11096           11 :             for i in 0..10 {
   11097           10 :                 let key = get_key(i);
   11098           10 :                 let key_in_nested = nested_img_layer
   11099           10 :                     .iter()
   11100           40 :                     .any(|(key_with_img, _)| *key_with_img == key);
   11101           10 :                 let lsn = {
   11102           10 :                     if key_in_nested {
   11103            5 :                         Lsn(nested_image_layer_lsn.0 + 5)
   11104              :                     } else {
   11105            5 :                         lsn_range.start
   11106              :                     }
   11107              :                 };
   11108              : 
   11109           10 :                 let will_init = will_init_keys.contains(&i);
   11110           10 :                 if will_init {
   11111            2 :                     data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   11112            2 : 
   11113            2 :                     expected_key_values.insert(key, "".to_string());
   11114            8 :                 } else {
   11115            8 :                     let delta = format!("@{lsn}");
   11116            8 :                     data.push((
   11117            8 :                         key,
   11118            8 :                         lsn,
   11119            8 :                         Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11120            8 :                     ));
   11121            8 : 
   11122            8 :                     expected_key_values
   11123            8 :                         .get_mut(&key)
   11124            8 :                         .expect("An image exists for each key")
   11125            8 :                         .push_str(delta.as_str());
   11126            8 :                 }
   11127              :             }
   11128              : 
   11129            1 :             InMemoryLayerTestDesc {
   11130            1 :                 lsn_range,
   11131            1 :                 is_open: false,
   11132            1 :                 data,
   11133            1 :             }
   11134              :         };
   11135              : 
   11136            1 :         let (open_layer, last_record_lsn) = {
   11137            1 :             let start_lsn = Lsn(0x70);
   11138            1 :             let mut data = Vec::new();
   11139            1 :             let mut end_lsn = Lsn(0);
   11140           11 :             for i in 0..10 {
   11141           10 :                 let key = get_key(i);
   11142           10 :                 let lsn = Lsn(start_lsn.0 + i as u64);
   11143           10 :                 let delta = format!("@{lsn}");
   11144           10 :                 data.push((
   11145           10 :                     key,
   11146           10 :                     lsn,
   11147           10 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11148           10 :                 ));
   11149           10 : 
   11150           10 :                 expected_key_values
   11151           10 :                     .get_mut(&key)
   11152           10 :                     .expect("An image exists for each key")
   11153           10 :                     .push_str(delta.as_str());
   11154           10 : 
   11155           10 :                 end_lsn = std::cmp::max(end_lsn, lsn);
   11156           10 :             }
   11157              : 
   11158            1 :             (
   11159            1 :                 InMemoryLayerTestDesc {
   11160            1 :                     lsn_range: start_lsn..Lsn::MAX,
   11161            1 :                     is_open: true,
   11162            1 :                     data,
   11163            1 :                 },
   11164            1 :                 end_lsn,
   11165            1 :             )
   11166              :         };
   11167              : 
   11168            1 :         assert!(
   11169            1 :             nested_image_layer_lsn > frozen_layer.lsn_range.start
   11170            1 :                 && nested_image_layer_lsn < frozen_layer.lsn_range.end
   11171              :         );
   11172              : 
   11173            1 :         let tline = tenant
   11174            1 :             .create_test_timeline_with_layers(
   11175            1 :                 TIMELINE_ID,
   11176            1 :                 baseline_image_layer_lsn,
   11177            1 :                 DEFAULT_PG_VERSION,
   11178            1 :                 &ctx,
   11179            1 :                 vec![open_layer, frozen_layer], // in-memory layers
   11180            1 :                 Vec::new(),                     // delta layers
   11181            1 :                 vec![
   11182            1 :                     (baseline_image_layer_lsn, baseline_img_layer),
   11183            1 :                     (nested_image_layer_lsn, nested_img_layer),
   11184            1 :                 ], // image layers
   11185            1 :                 last_record_lsn,
   11186            1 :             )
   11187            1 :             .await?;
   11188              : 
   11189            1 :         let query = VersionedKeySpaceQuery::uniform(
   11190            1 :             KeySpace::single(get_key(0)..get_key(10)),
   11191            1 :             last_record_lsn,
   11192              :         );
   11193              : 
   11194            1 :         let results = tline
   11195            1 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   11196            1 :             .await
   11197            1 :             .expect("No vectored errors");
   11198           11 :         for (key, res) in results {
   11199           10 :             let value = res.expect("No key errors");
   11200           10 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   11201           10 :             assert_eq!(value, Bytes::from(expected_value.clone()));
   11202            1 : 
   11203           10 :             tracing::info!("key={key} value={expected_value}");
   11204            1 :         }
   11205            1 : 
   11206            1 :         Ok(())
   11207            1 :     }
   11208              : 
   11209              :     // A randomized read path test. Generates a layer map according to a deterministic
   11210              :     // specification. Fills the (key, LSN) space in random manner and then performs
   11211              :     // random scattered queries validating the results against in-memory storage.
   11212              :     //
   11213              :     // See this internal Notion page for a diagram of the layer map:
   11214              :     // https://www.notion.so/neondatabase/Read-Path-Unit-Testing-Fuzzing-1d1f189e0047806c8e5cd37781b0a350?pvs=4
   11215              :     //
   11216              :     // A fuzzing mode is also supported. In this mode, the test will use a random
   11217              :     // seed instead of a hardcoded one. Use it in conjunction with `cargo stress`
   11218              :     // to run multiple instances in parallel:
   11219              :     //
   11220              :     // $ RUST_BACKTRACE=1 RUST_LOG=INFO \
   11221              :     //   cargo stress --package=pageserver --features=testing,fuzz-read-path --release -- test_read_path
   11222              :     #[cfg(feature = "testing")]
   11223              :     #[tokio::test]
   11224            1 :     async fn test_read_path() -> anyhow::Result<()> {
   11225              :         use rand::seq::SliceRandom;
   11226              : 
   11227            1 :         let seed = if cfg!(feature = "fuzz-read-path") {
   11228            0 :             let seed: u64 = thread_rng().r#gen();
   11229            0 :             seed
   11230              :         } else {
   11231              :             // Use a hard-coded seed when not in fuzzing mode.
   11232              :             // Note that with the current approach results are not reproducible
   11233              :             // accross platforms and Rust releases.
   11234              :             const SEED: u64 = 0;
   11235            1 :             SEED
   11236              :         };
   11237              : 
   11238            1 :         let mut random = StdRng::seed_from_u64(seed);
   11239              : 
   11240            1 :         let (queries, will_init_chance, gap_chance) = if cfg!(feature = "fuzz-read-path") {
   11241              :             const QUERIES: u64 = 5000;
   11242            0 :             let will_init_chance: u8 = random.gen_range(0..=10);
   11243            0 :             let gap_chance: u8 = random.gen_range(0..=50);
   11244              : 
   11245            0 :             (QUERIES, will_init_chance, gap_chance)
   11246              :         } else {
   11247              :             const QUERIES: u64 = 1000;
   11248              :             const WILL_INIT_CHANCE: u8 = 1;
   11249              :             const GAP_CHANCE: u8 = 5;
   11250              : 
   11251            1 :             (QUERIES, WILL_INIT_CHANCE, GAP_CHANCE)
   11252              :         };
   11253              : 
   11254            1 :         let harness = TenantHarness::create("test_read_path").await?;
   11255            1 :         let (tenant, ctx) = harness.load().await;
   11256              : 
   11257            1 :         tracing::info!("Using random seed: {seed}");
   11258            1 :         tracing::info!(%will_init_chance, %gap_chance, "Fill params");
   11259              : 
   11260              :         // Define the layer map shape. Note that this part is not randomized.
   11261              : 
   11262              :         const KEY_DIMENSION_SIZE: u32 = 99;
   11263            1 :         let start_key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   11264            1 :         let end_key = start_key.add(KEY_DIMENSION_SIZE);
   11265            1 :         let total_key_range = start_key..end_key;
   11266            1 :         let total_key_range_size = end_key.to_i128() - start_key.to_i128();
   11267            1 :         let total_start_lsn = Lsn(104);
   11268            1 :         let last_record_lsn = Lsn(504);
   11269              : 
   11270            1 :         assert!(total_key_range_size % 3 == 0);
   11271              : 
   11272            1 :         let in_memory_layers_shape = vec![
   11273            1 :             (total_key_range.clone(), Lsn(304)..Lsn(400)),
   11274            1 :             (total_key_range.clone(), Lsn(400)..last_record_lsn),
   11275              :         ];
   11276              : 
   11277            1 :         let delta_layers_shape = vec![
   11278            1 :             (
   11279            1 :                 start_key..(start_key.add((total_key_range_size / 3) as u32)),
   11280            1 :                 Lsn(200)..Lsn(304),
   11281            1 :             ),
   11282            1 :             (
   11283            1 :                 (start_key.add((total_key_range_size / 3) as u32))
   11284            1 :                     ..(start_key.add((total_key_range_size * 2 / 3) as u32)),
   11285            1 :                 Lsn(200)..Lsn(304),
   11286            1 :             ),
   11287            1 :             (
   11288            1 :                 (start_key.add((total_key_range_size * 2 / 3) as u32))
   11289            1 :                     ..(start_key.add(total_key_range_size as u32)),
   11290            1 :                 Lsn(200)..Lsn(304),
   11291            1 :             ),
   11292              :         ];
   11293              : 
   11294            1 :         let image_layers_shape = vec![
   11295            1 :             (
   11296            1 :                 start_key.add((total_key_range_size * 2 / 3 - 10) as u32)
   11297            1 :                     ..start_key.add((total_key_range_size * 2 / 3 + 10) as u32),
   11298            1 :                 Lsn(456),
   11299            1 :             ),
   11300            1 :             (
   11301            1 :                 start_key.add((total_key_range_size / 3 - 10) as u32)
   11302            1 :                     ..start_key.add((total_key_range_size / 3 + 10) as u32),
   11303            1 :                 Lsn(256),
   11304            1 :             ),
   11305            1 :             (total_key_range.clone(), total_start_lsn),
   11306              :         ];
   11307              : 
   11308            1 :         let specification = TestTimelineSpecification {
   11309            1 :             start_lsn: total_start_lsn,
   11310            1 :             last_record_lsn,
   11311            1 :             in_memory_layers_shape,
   11312            1 :             delta_layers_shape,
   11313            1 :             image_layers_shape,
   11314            1 :             gap_chance,
   11315            1 :             will_init_chance,
   11316            1 :         };
   11317              : 
   11318              :         // Create and randomly fill in the layers according to the specification
   11319            1 :         let (tline, storage, interesting_lsns) = randomize_timeline(
   11320            1 :             &tenant,
   11321            1 :             TIMELINE_ID,
   11322            1 :             DEFAULT_PG_VERSION,
   11323            1 :             specification,
   11324            1 :             &mut random,
   11325            1 :             &ctx,
   11326            1 :         )
   11327            1 :         .await?;
   11328              : 
   11329              :         // Now generate queries based on the interesting lsns that we've collected.
   11330              :         //
   11331              :         // While there's still room in the query, pick and interesting LSN and a random
   11332              :         // key. Then roll the dice to see if the next key should also be included in
   11333              :         // the query. When the roll fails, break the "batch" and pick another point in the
   11334              :         // (key, LSN) space.
   11335              : 
   11336              :         const PICK_NEXT_CHANCE: u8 = 50;
   11337            1 :         for _ in 0..queries {
   11338         1000 :             let query = {
   11339         1000 :                 let mut keyspaces_at_lsn: HashMap<Lsn, KeySpaceRandomAccum> = HashMap::default();
   11340         1000 :                 let mut used_keys: HashSet<Key> = HashSet::default();
   11341            1 : 
   11342        22536 :                 while used_keys.len() < tenant.conf.max_get_vectored_keys.get() {
   11343        21536 :                     let selected_lsn = interesting_lsns.choose(&mut random).expect("not empty");
   11344        21536 :                     let mut selected_key = start_key.add(random.gen_range(0..KEY_DIMENSION_SIZE));
   11345            1 : 
   11346        37614 :                     while used_keys.len() < tenant.conf.max_get_vectored_keys.get() {
   11347        37093 :                         if used_keys.contains(&selected_key)
   11348        32154 :                             || selected_key >= start_key.add(KEY_DIMENSION_SIZE)
   11349            1 :                         {
   11350         5093 :                             break;
   11351        32000 :                         }
   11352            1 : 
   11353        32000 :                         keyspaces_at_lsn
   11354        32000 :                             .entry(*selected_lsn)
   11355        32000 :                             .or_default()
   11356        32000 :                             .add_key(selected_key);
   11357        32000 :                         used_keys.insert(selected_key);
   11358            1 : 
   11359        32000 :                         let pick_next = random.gen_range(0..=100) <= PICK_NEXT_CHANCE;
   11360        32000 :                         if pick_next {
   11361        16078 :                             selected_key = selected_key.next();
   11362        16078 :                         } else {
   11363        15922 :                             break;
   11364            1 :                         }
   11365            1 :                     }
   11366            1 :                 }
   11367            1 : 
   11368         1000 :                 VersionedKeySpaceQuery::scattered(
   11369         1000 :                     keyspaces_at_lsn
   11370         1000 :                         .into_iter()
   11371        11917 :                         .map(|(lsn, acc)| (lsn, acc.to_keyspace()))
   11372         1000 :                         .collect(),
   11373            1 :                 )
   11374            1 :             };
   11375            1 : 
   11376            1 :             // Run the query and validate the results
   11377            1 : 
   11378         1000 :             let results = tline
   11379         1000 :                 .get_vectored(query.clone(), IoConcurrency::Sequential, &ctx)
   11380         1000 :                 .await;
   11381            1 : 
   11382         1000 :             let blobs = match results {
   11383         1000 :                 Ok(ok) => ok,
   11384            1 :                 Err(err) => {
   11385            1 :                     panic!("seed={seed} Error returned for query {query}: {err}");
   11386            1 :                 }
   11387            1 :             };
   11388            1 : 
   11389        32000 :             for (key, key_res) in blobs.into_iter() {
   11390        32000 :                 match key_res {
   11391        32000 :                     Ok(blob) => {
   11392        32000 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11393        32000 :                         let expected = storage.get(key, requested_at_lsn);
   11394            1 : 
   11395        32000 :                         if blob != expected {
   11396            1 :                             tracing::error!(
   11397            1 :                                 "seed={seed} Mismatch for {key}@{requested_at_lsn} from query: {query}"
   11398            1 :                             );
   11399        32000 :                         }
   11400            1 : 
   11401        32000 :                         assert_eq!(blob, expected);
   11402            1 :                     }
   11403            1 :                     Err(err) => {
   11404            1 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11405            1 : 
   11406            1 :                         panic!(
   11407            1 :                             "seed={seed} Error returned for {key}@{requested_at_lsn} from query {query}: {err}"
   11408            1 :                         );
   11409            1 :                     }
   11410            1 :                 }
   11411            1 :             }
   11412            1 :         }
   11413            1 : 
   11414            1 :         Ok(())
   11415            1 :     }
   11416              : 
   11417          107 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   11418          107 :         (
   11419          107 :             k1.is_delta,
   11420          107 :             k1.key_range.start,
   11421          107 :             k1.key_range.end,
   11422          107 :             k1.lsn_range.start,
   11423          107 :             k1.lsn_range.end,
   11424          107 :         )
   11425          107 :             .cmp(&(
   11426          107 :                 k2.is_delta,
   11427          107 :                 k2.key_range.start,
   11428          107 :                 k2.key_range.end,
   11429          107 :                 k2.lsn_range.start,
   11430          107 :                 k2.lsn_range.end,
   11431          107 :             ))
   11432          107 :     }
   11433              : 
   11434           12 :     async fn inspect_and_sort(
   11435           12 :         tline: &Arc<Timeline>,
   11436           12 :         filter: Option<std::ops::Range<Key>>,
   11437           12 :     ) -> Vec<PersistentLayerKey> {
   11438           12 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   11439           12 :         if let Some(filter) = filter {
   11440           54 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   11441            1 :         }
   11442           12 :         all_layers.sort_by(sort_layer_key);
   11443           12 :         all_layers
   11444           12 :     }
   11445              : 
   11446              :     #[cfg(feature = "testing")]
   11447           11 :     fn check_layer_map_key_eq(
   11448           11 :         mut left: Vec<PersistentLayerKey>,
   11449           11 :         mut right: Vec<PersistentLayerKey>,
   11450           11 :     ) {
   11451           11 :         left.sort_by(sort_layer_key);
   11452           11 :         right.sort_by(sort_layer_key);
   11453           11 :         if left != right {
   11454            0 :             eprintln!("---LEFT---");
   11455            0 :             for left in left.iter() {
   11456            0 :                 eprintln!("{left}");
   11457            0 :             }
   11458            0 :             eprintln!("---RIGHT---");
   11459            0 :             for right in right.iter() {
   11460            0 :                 eprintln!("{right}");
   11461            0 :             }
   11462            0 :             assert_eq!(left, right);
   11463           11 :         }
   11464           11 :     }
   11465              : 
   11466              :     #[cfg(feature = "testing")]
   11467              :     #[tokio::test]
   11468            1 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   11469            1 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   11470            1 :         let (tenant, ctx) = harness.load().await;
   11471              : 
   11472           91 :         fn get_key(id: u32) -> Key {
   11473              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11474           91 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11475           91 :             key.field6 = id;
   11476           91 :             key
   11477           91 :         }
   11478              : 
   11479              :         // img layer at 0x10
   11480            1 :         let img_layer = (0..10)
   11481           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11482            1 :             .collect_vec();
   11483              : 
   11484            1 :         let delta1 = vec![
   11485            1 :             (
   11486            1 :                 get_key(1),
   11487            1 :                 Lsn(0x20),
   11488            1 :                 Value::Image(Bytes::from("value 1@0x20")),
   11489            1 :             ),
   11490            1 :             (
   11491            1 :                 get_key(2),
   11492            1 :                 Lsn(0x30),
   11493            1 :                 Value::Image(Bytes::from("value 2@0x30")),
   11494            1 :             ),
   11495            1 :             (
   11496            1 :                 get_key(3),
   11497            1 :                 Lsn(0x40),
   11498            1 :                 Value::Image(Bytes::from("value 3@0x40")),
   11499            1 :             ),
   11500              :         ];
   11501            1 :         let delta2 = vec![
   11502            1 :             (
   11503            1 :                 get_key(5),
   11504            1 :                 Lsn(0x20),
   11505            1 :                 Value::Image(Bytes::from("value 5@0x20")),
   11506            1 :             ),
   11507            1 :             (
   11508            1 :                 get_key(6),
   11509            1 :                 Lsn(0x20),
   11510            1 :                 Value::Image(Bytes::from("value 6@0x20")),
   11511            1 :             ),
   11512              :         ];
   11513            1 :         let delta3 = vec![
   11514            1 :             (
   11515            1 :                 get_key(8),
   11516            1 :                 Lsn(0x48),
   11517            1 :                 Value::Image(Bytes::from("value 8@0x48")),
   11518            1 :             ),
   11519            1 :             (
   11520            1 :                 get_key(9),
   11521            1 :                 Lsn(0x48),
   11522            1 :                 Value::Image(Bytes::from("value 9@0x48")),
   11523            1 :             ),
   11524              :         ];
   11525              : 
   11526            1 :         let tline = tenant
   11527            1 :             .create_test_timeline_with_layers(
   11528            1 :                 TIMELINE_ID,
   11529            1 :                 Lsn(0x10),
   11530            1 :                 DEFAULT_PG_VERSION,
   11531            1 :                 &ctx,
   11532            1 :                 vec![], // in-memory layers
   11533            1 :                 vec![
   11534            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   11535            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   11536            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   11537            1 :                 ], // delta layers
   11538            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11539            1 :                 Lsn(0x50),
   11540            1 :             )
   11541            1 :             .await?;
   11542              : 
   11543              :         {
   11544            1 :             tline
   11545            1 :                 .applied_gc_cutoff_lsn
   11546            1 :                 .lock_for_write()
   11547            1 :                 .store_and_unlock(Lsn(0x30))
   11548            1 :                 .wait()
   11549            1 :                 .await;
   11550              :             // Update GC info
   11551            1 :             let mut guard = tline.gc_info.write().unwrap();
   11552            1 :             *guard = GcInfo {
   11553            1 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   11554            1 :                 cutoffs: GcCutoffs {
   11555            1 :                     time: Some(Lsn(0x30)),
   11556            1 :                     space: Lsn(0x30),
   11557            1 :                 },
   11558            1 :                 leases: Default::default(),
   11559            1 :                 within_ancestor_pitr: false,
   11560            1 :             };
   11561              :         }
   11562              : 
   11563            1 :         let cancel = CancellationToken::new();
   11564              : 
   11565              :         // Do a partial compaction on key range 0..2
   11566            1 :         tline
   11567            1 :             .compact_with_gc(
   11568            1 :                 &cancel,
   11569            1 :                 CompactOptions {
   11570            1 :                     flags: EnumSet::new(),
   11571            1 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11572            1 :                     ..Default::default()
   11573            1 :                 },
   11574            1 :                 &ctx,
   11575            1 :             )
   11576            1 :             .await
   11577            1 :             .unwrap();
   11578            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11579            1 :         check_layer_map_key_eq(
   11580            1 :             all_layers,
   11581            1 :             vec![
   11582              :                 // newly-generated image layer for the partial compaction range 0-2
   11583            1 :                 PersistentLayerKey {
   11584            1 :                     key_range: get_key(0)..get_key(2),
   11585            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11586            1 :                     is_delta: false,
   11587            1 :                 },
   11588            1 :                 PersistentLayerKey {
   11589            1 :                     key_range: get_key(0)..get_key(10),
   11590            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11591            1 :                     is_delta: false,
   11592            1 :                 },
   11593              :                 // delta1 is split and the second part is rewritten
   11594            1 :                 PersistentLayerKey {
   11595            1 :                     key_range: get_key(2)..get_key(4),
   11596            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11597            1 :                     is_delta: true,
   11598            1 :                 },
   11599            1 :                 PersistentLayerKey {
   11600            1 :                     key_range: get_key(5)..get_key(7),
   11601            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11602            1 :                     is_delta: true,
   11603            1 :                 },
   11604            1 :                 PersistentLayerKey {
   11605            1 :                     key_range: get_key(8)..get_key(10),
   11606            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11607            1 :                     is_delta: true,
   11608            1 :                 },
   11609              :             ],
   11610              :         );
   11611              : 
   11612              :         // Do a partial compaction on key range 2..4
   11613            1 :         tline
   11614            1 :             .compact_with_gc(
   11615            1 :                 &cancel,
   11616            1 :                 CompactOptions {
   11617            1 :                     flags: EnumSet::new(),
   11618            1 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   11619            1 :                     ..Default::default()
   11620            1 :                 },
   11621            1 :                 &ctx,
   11622            1 :             )
   11623            1 :             .await
   11624            1 :             .unwrap();
   11625            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11626            1 :         check_layer_map_key_eq(
   11627            1 :             all_layers,
   11628            1 :             vec![
   11629            1 :                 PersistentLayerKey {
   11630            1 :                     key_range: get_key(0)..get_key(2),
   11631            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11632            1 :                     is_delta: false,
   11633            1 :                 },
   11634            1 :                 PersistentLayerKey {
   11635            1 :                     key_range: get_key(0)..get_key(10),
   11636            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11637            1 :                     is_delta: false,
   11638            1 :                 },
   11639              :                 // image layer generated for the compaction range 2-4
   11640            1 :                 PersistentLayerKey {
   11641            1 :                     key_range: get_key(2)..get_key(4),
   11642            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11643            1 :                     is_delta: false,
   11644            1 :                 },
   11645              :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   11646            1 :                 PersistentLayerKey {
   11647            1 :                     key_range: get_key(2)..get_key(4),
   11648            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11649            1 :                     is_delta: true,
   11650            1 :                 },
   11651            1 :                 PersistentLayerKey {
   11652            1 :                     key_range: get_key(5)..get_key(7),
   11653            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11654            1 :                     is_delta: true,
   11655            1 :                 },
   11656            1 :                 PersistentLayerKey {
   11657            1 :                     key_range: get_key(8)..get_key(10),
   11658            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11659            1 :                     is_delta: true,
   11660            1 :                 },
   11661              :             ],
   11662              :         );
   11663              : 
   11664              :         // Do a partial compaction on key range 4..9
   11665            1 :         tline
   11666            1 :             .compact_with_gc(
   11667            1 :                 &cancel,
   11668            1 :                 CompactOptions {
   11669            1 :                     flags: EnumSet::new(),
   11670            1 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   11671            1 :                     ..Default::default()
   11672            1 :                 },
   11673            1 :                 &ctx,
   11674            1 :             )
   11675            1 :             .await
   11676            1 :             .unwrap();
   11677            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11678            1 :         check_layer_map_key_eq(
   11679            1 :             all_layers,
   11680            1 :             vec![
   11681            1 :                 PersistentLayerKey {
   11682            1 :                     key_range: get_key(0)..get_key(2),
   11683            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11684            1 :                     is_delta: false,
   11685            1 :                 },
   11686            1 :                 PersistentLayerKey {
   11687            1 :                     key_range: get_key(0)..get_key(10),
   11688            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11689            1 :                     is_delta: false,
   11690            1 :                 },
   11691            1 :                 PersistentLayerKey {
   11692            1 :                     key_range: get_key(2)..get_key(4),
   11693            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11694            1 :                     is_delta: false,
   11695            1 :                 },
   11696            1 :                 PersistentLayerKey {
   11697            1 :                     key_range: get_key(2)..get_key(4),
   11698            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11699            1 :                     is_delta: true,
   11700            1 :                 },
   11701              :                 // image layer generated for this compaction range
   11702            1 :                 PersistentLayerKey {
   11703            1 :                     key_range: get_key(4)..get_key(9),
   11704            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11705            1 :                     is_delta: false,
   11706            1 :                 },
   11707            1 :                 PersistentLayerKey {
   11708            1 :                     key_range: get_key(8)..get_key(10),
   11709            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11710            1 :                     is_delta: true,
   11711            1 :                 },
   11712              :             ],
   11713              :         );
   11714              : 
   11715              :         // Do a partial compaction on key range 9..10
   11716            1 :         tline
   11717            1 :             .compact_with_gc(
   11718            1 :                 &cancel,
   11719            1 :                 CompactOptions {
   11720            1 :                     flags: EnumSet::new(),
   11721            1 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   11722            1 :                     ..Default::default()
   11723            1 :                 },
   11724            1 :                 &ctx,
   11725            1 :             )
   11726            1 :             .await
   11727            1 :             .unwrap();
   11728            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11729            1 :         check_layer_map_key_eq(
   11730            1 :             all_layers,
   11731            1 :             vec![
   11732            1 :                 PersistentLayerKey {
   11733            1 :                     key_range: get_key(0)..get_key(2),
   11734            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11735            1 :                     is_delta: false,
   11736            1 :                 },
   11737            1 :                 PersistentLayerKey {
   11738            1 :                     key_range: get_key(0)..get_key(10),
   11739            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11740            1 :                     is_delta: false,
   11741            1 :                 },
   11742            1 :                 PersistentLayerKey {
   11743            1 :                     key_range: get_key(2)..get_key(4),
   11744            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11745            1 :                     is_delta: false,
   11746            1 :                 },
   11747            1 :                 PersistentLayerKey {
   11748            1 :                     key_range: get_key(2)..get_key(4),
   11749            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11750            1 :                     is_delta: true,
   11751            1 :                 },
   11752            1 :                 PersistentLayerKey {
   11753            1 :                     key_range: get_key(4)..get_key(9),
   11754            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11755            1 :                     is_delta: false,
   11756            1 :                 },
   11757              :                 // image layer generated for the compaction range
   11758            1 :                 PersistentLayerKey {
   11759            1 :                     key_range: get_key(9)..get_key(10),
   11760            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11761            1 :                     is_delta: false,
   11762            1 :                 },
   11763            1 :                 PersistentLayerKey {
   11764            1 :                     key_range: get_key(8)..get_key(10),
   11765            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11766            1 :                     is_delta: true,
   11767            1 :                 },
   11768              :             ],
   11769              :         );
   11770              : 
   11771              :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   11772            1 :         tline
   11773            1 :             .compact_with_gc(
   11774            1 :                 &cancel,
   11775            1 :                 CompactOptions {
   11776            1 :                     flags: EnumSet::new(),
   11777            1 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   11778            1 :                     ..Default::default()
   11779            1 :                 },
   11780            1 :                 &ctx,
   11781            1 :             )
   11782            1 :             .await
   11783            1 :             .unwrap();
   11784            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11785            1 :         check_layer_map_key_eq(
   11786            1 :             all_layers,
   11787            1 :             vec![
   11788              :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   11789            1 :                 PersistentLayerKey {
   11790            1 :                     key_range: get_key(0)..get_key(10),
   11791            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11792            1 :                     is_delta: false,
   11793            1 :                 },
   11794            1 :                 PersistentLayerKey {
   11795            1 :                     key_range: get_key(2)..get_key(4),
   11796            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11797            1 :                     is_delta: true,
   11798            1 :                 },
   11799            1 :                 PersistentLayerKey {
   11800            1 :                     key_range: get_key(8)..get_key(10),
   11801            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11802            1 :                     is_delta: true,
   11803            1 :                 },
   11804              :             ],
   11805              :         );
   11806            2 :         Ok(())
   11807            1 :     }
   11808              : 
   11809              :     #[cfg(feature = "testing")]
   11810              :     #[tokio::test]
   11811            1 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   11812            1 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   11813            1 :             .await
   11814            1 :             .unwrap();
   11815            1 :         let (tenant, ctx) = harness.load().await;
   11816            1 :         let tline_parent = tenant
   11817            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   11818            1 :             .await
   11819            1 :             .unwrap();
   11820            1 :         let tline_child = tenant
   11821            1 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   11822            1 :             .await
   11823            1 :             .unwrap();
   11824              :         {
   11825            1 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11826            1 :             assert_eq!(
   11827            1 :                 gc_info_parent.retain_lsns,
   11828            1 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   11829              :             );
   11830              :         }
   11831              :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   11832            1 :         tline_child
   11833            1 :             .remote_client
   11834            1 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   11835            1 :             .unwrap();
   11836            1 :         tline_child.remote_client.wait_completion().await.unwrap();
   11837            1 :         offload_timeline(&tenant, &tline_child)
   11838            1 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   11839            1 :             .await.unwrap();
   11840            1 :         let child_timeline_id = tline_child.timeline_id;
   11841            1 :         Arc::try_unwrap(tline_child).unwrap();
   11842              : 
   11843              :         {
   11844            1 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11845            1 :             assert_eq!(
   11846            1 :                 gc_info_parent.retain_lsns,
   11847            1 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   11848              :             );
   11849              :         }
   11850              : 
   11851            1 :         tenant
   11852            1 :             .get_offloaded_timeline(child_timeline_id)
   11853            1 :             .unwrap()
   11854            1 :             .defuse_for_tenant_drop();
   11855              : 
   11856            2 :         Ok(())
   11857            1 :     }
   11858              : 
   11859              :     #[cfg(feature = "testing")]
   11860              :     #[tokio::test]
   11861            1 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   11862            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   11863            1 :         let (tenant, ctx) = harness.load().await;
   11864              : 
   11865          148 :         fn get_key(id: u32) -> Key {
   11866              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11867          148 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11868          148 :             key.field6 = id;
   11869          148 :             key
   11870          148 :         }
   11871              : 
   11872            1 :         let img_layer = (0..10)
   11873           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11874            1 :             .collect_vec();
   11875              : 
   11876            1 :         let delta1 = vec![(
   11877            1 :             get_key(1),
   11878            1 :             Lsn(0x20),
   11879            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11880            1 :         )];
   11881            1 :         let delta4 = vec![(
   11882            1 :             get_key(1),
   11883            1 :             Lsn(0x28),
   11884            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11885            1 :         )];
   11886            1 :         let delta2 = vec![
   11887            1 :             (
   11888            1 :                 get_key(1),
   11889            1 :                 Lsn(0x30),
   11890            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11891            1 :             ),
   11892            1 :             (
   11893            1 :                 get_key(1),
   11894            1 :                 Lsn(0x38),
   11895            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11896            1 :             ),
   11897              :         ];
   11898            1 :         let delta3 = vec![
   11899            1 :             (
   11900            1 :                 get_key(8),
   11901            1 :                 Lsn(0x48),
   11902            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11903            1 :             ),
   11904            1 :             (
   11905            1 :                 get_key(9),
   11906            1 :                 Lsn(0x48),
   11907            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11908            1 :             ),
   11909              :         ];
   11910              : 
   11911            1 :         let tline = tenant
   11912            1 :             .create_test_timeline_with_layers(
   11913            1 :                 TIMELINE_ID,
   11914            1 :                 Lsn(0x10),
   11915            1 :                 DEFAULT_PG_VERSION,
   11916            1 :                 &ctx,
   11917            1 :                 vec![], // in-memory layers
   11918            1 :                 vec![
   11919            1 :                     // delta1/2/4 only contain a single key but multiple updates
   11920            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11921            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11922            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11923            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11924            1 :                 ], // delta layers
   11925            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11926            1 :                 Lsn(0x50),
   11927            1 :             )
   11928            1 :             .await?;
   11929              :         {
   11930            1 :             tline
   11931            1 :                 .applied_gc_cutoff_lsn
   11932            1 :                 .lock_for_write()
   11933            1 :                 .store_and_unlock(Lsn(0x30))
   11934            1 :                 .wait()
   11935            1 :                 .await;
   11936              :             // Update GC info
   11937            1 :             let mut guard = tline.gc_info.write().unwrap();
   11938            1 :             *guard = GcInfo {
   11939            1 :                 retain_lsns: vec![
   11940            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11941            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11942            1 :                 ],
   11943            1 :                 cutoffs: GcCutoffs {
   11944            1 :                     time: Some(Lsn(0x30)),
   11945            1 :                     space: Lsn(0x30),
   11946            1 :                 },
   11947            1 :                 leases: Default::default(),
   11948            1 :                 within_ancestor_pitr: false,
   11949            1 :             };
   11950              :         }
   11951              : 
   11952            1 :         let expected_result = [
   11953            1 :             Bytes::from_static(b"value 0@0x10"),
   11954            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11955            1 :             Bytes::from_static(b"value 2@0x10"),
   11956            1 :             Bytes::from_static(b"value 3@0x10"),
   11957            1 :             Bytes::from_static(b"value 4@0x10"),
   11958            1 :             Bytes::from_static(b"value 5@0x10"),
   11959            1 :             Bytes::from_static(b"value 6@0x10"),
   11960            1 :             Bytes::from_static(b"value 7@0x10"),
   11961            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11962            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11963            1 :         ];
   11964              : 
   11965            1 :         let expected_result_at_gc_horizon = [
   11966            1 :             Bytes::from_static(b"value 0@0x10"),
   11967            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11968            1 :             Bytes::from_static(b"value 2@0x10"),
   11969            1 :             Bytes::from_static(b"value 3@0x10"),
   11970            1 :             Bytes::from_static(b"value 4@0x10"),
   11971            1 :             Bytes::from_static(b"value 5@0x10"),
   11972            1 :             Bytes::from_static(b"value 6@0x10"),
   11973            1 :             Bytes::from_static(b"value 7@0x10"),
   11974            1 :             Bytes::from_static(b"value 8@0x10"),
   11975            1 :             Bytes::from_static(b"value 9@0x10"),
   11976            1 :         ];
   11977              : 
   11978            1 :         let expected_result_at_lsn_20 = [
   11979            1 :             Bytes::from_static(b"value 0@0x10"),
   11980            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11981            1 :             Bytes::from_static(b"value 2@0x10"),
   11982            1 :             Bytes::from_static(b"value 3@0x10"),
   11983            1 :             Bytes::from_static(b"value 4@0x10"),
   11984            1 :             Bytes::from_static(b"value 5@0x10"),
   11985            1 :             Bytes::from_static(b"value 6@0x10"),
   11986            1 :             Bytes::from_static(b"value 7@0x10"),
   11987            1 :             Bytes::from_static(b"value 8@0x10"),
   11988            1 :             Bytes::from_static(b"value 9@0x10"),
   11989            1 :         ];
   11990              : 
   11991            1 :         let expected_result_at_lsn_10 = [
   11992            1 :             Bytes::from_static(b"value 0@0x10"),
   11993            1 :             Bytes::from_static(b"value 1@0x10"),
   11994            1 :             Bytes::from_static(b"value 2@0x10"),
   11995            1 :             Bytes::from_static(b"value 3@0x10"),
   11996            1 :             Bytes::from_static(b"value 4@0x10"),
   11997            1 :             Bytes::from_static(b"value 5@0x10"),
   11998            1 :             Bytes::from_static(b"value 6@0x10"),
   11999            1 :             Bytes::from_static(b"value 7@0x10"),
   12000            1 :             Bytes::from_static(b"value 8@0x10"),
   12001            1 :             Bytes::from_static(b"value 9@0x10"),
   12002            1 :         ];
   12003              : 
   12004            3 :         let verify_result = || async {
   12005            3 :             let gc_horizon = {
   12006            3 :                 let gc_info = tline.gc_info.read().unwrap();
   12007            3 :                 gc_info.cutoffs.time.unwrap_or_default()
   12008              :             };
   12009           33 :             for idx in 0..10 {
   12010           30 :                 assert_eq!(
   12011           30 :                     tline
   12012           30 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   12013           30 :                         .await
   12014           30 :                         .unwrap(),
   12015           30 :                     &expected_result[idx]
   12016              :                 );
   12017           30 :                 assert_eq!(
   12018           30 :                     tline
   12019           30 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   12020           30 :                         .await
   12021           30 :                         .unwrap(),
   12022           30 :                     &expected_result_at_gc_horizon[idx]
   12023              :                 );
   12024           30 :                 assert_eq!(
   12025           30 :                     tline
   12026           30 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   12027           30 :                         .await
   12028           30 :                         .unwrap(),
   12029           30 :                     &expected_result_at_lsn_20[idx]
   12030              :                 );
   12031           30 :                 assert_eq!(
   12032           30 :                     tline
   12033           30 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   12034           30 :                         .await
   12035           30 :                         .unwrap(),
   12036           30 :                     &expected_result_at_lsn_10[idx]
   12037              :                 );
   12038              :             }
   12039            6 :         };
   12040              : 
   12041            1 :         verify_result().await;
   12042              : 
   12043            1 :         let cancel = CancellationToken::new();
   12044            1 :         tline
   12045            1 :             .compact_with_gc(
   12046            1 :                 &cancel,
   12047            1 :                 CompactOptions {
   12048            1 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   12049            1 :                     ..Default::default()
   12050            1 :                 },
   12051            1 :                 &ctx,
   12052            1 :             )
   12053            1 :             .await
   12054            1 :             .unwrap();
   12055            1 :         verify_result().await;
   12056              : 
   12057            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12058            1 :         check_layer_map_key_eq(
   12059            1 :             all_layers,
   12060            1 :             vec![
   12061              :                 // The original image layer, not compacted
   12062            1 :                 PersistentLayerKey {
   12063            1 :                     key_range: get_key(0)..get_key(10),
   12064            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12065            1 :                     is_delta: false,
   12066            1 :                 },
   12067              :                 // Delta layer below the specified above_lsn not compacted
   12068            1 :                 PersistentLayerKey {
   12069            1 :                     key_range: get_key(1)..get_key(2),
   12070            1 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   12071            1 :                     is_delta: true,
   12072            1 :                 },
   12073              :                 // Delta layer compacted above the LSN
   12074            1 :                 PersistentLayerKey {
   12075            1 :                     key_range: get_key(1)..get_key(10),
   12076            1 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   12077            1 :                     is_delta: true,
   12078            1 :                 },
   12079              :             ],
   12080              :         );
   12081              : 
   12082              :         // compact again
   12083            1 :         tline
   12084            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   12085            1 :             .await
   12086            1 :             .unwrap();
   12087            1 :         verify_result().await;
   12088              : 
   12089            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12090            1 :         check_layer_map_key_eq(
   12091            1 :             all_layers,
   12092            1 :             vec![
   12093              :                 // The compacted image layer (full key range)
   12094            1 :                 PersistentLayerKey {
   12095            1 :                     key_range: Key::MIN..Key::MAX,
   12096            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12097            1 :                     is_delta: false,
   12098            1 :                 },
   12099              :                 // All other data in the delta layer
   12100            1 :                 PersistentLayerKey {
   12101            1 :                     key_range: get_key(1)..get_key(10),
   12102            1 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12103            1 :                     is_delta: true,
   12104            1 :                 },
   12105              :             ],
   12106              :         );
   12107              : 
   12108            2 :         Ok(())
   12109            1 :     }
   12110              : 
   12111              :     #[cfg(feature = "testing")]
   12112              :     #[tokio::test]
   12113            1 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   12114            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   12115            1 :         let (tenant, ctx) = harness.load().await;
   12116              : 
   12117          254 :         fn get_key(id: u32) -> Key {
   12118              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12119          254 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12120          254 :             key.field6 = id;
   12121          254 :             key
   12122          254 :         }
   12123              : 
   12124            1 :         let img_layer = (0..10)
   12125           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12126            1 :             .collect_vec();
   12127              : 
   12128            1 :         let delta1 = vec![(
   12129            1 :             get_key(1),
   12130            1 :             Lsn(0x20),
   12131            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12132            1 :         )];
   12133            1 :         let delta4 = vec![(
   12134            1 :             get_key(1),
   12135            1 :             Lsn(0x28),
   12136            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   12137            1 :         )];
   12138            1 :         let delta2 = vec![
   12139            1 :             (
   12140            1 :                 get_key(1),
   12141            1 :                 Lsn(0x30),
   12142            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   12143            1 :             ),
   12144            1 :             (
   12145            1 :                 get_key(1),
   12146            1 :                 Lsn(0x38),
   12147            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   12148            1 :             ),
   12149              :         ];
   12150            1 :         let delta3 = vec![
   12151            1 :             (
   12152            1 :                 get_key(8),
   12153            1 :                 Lsn(0x48),
   12154            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   12155            1 :             ),
   12156            1 :             (
   12157            1 :                 get_key(9),
   12158            1 :                 Lsn(0x48),
   12159            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   12160            1 :             ),
   12161              :         ];
   12162              : 
   12163            1 :         let tline = tenant
   12164            1 :             .create_test_timeline_with_layers(
   12165            1 :                 TIMELINE_ID,
   12166            1 :                 Lsn(0x10),
   12167            1 :                 DEFAULT_PG_VERSION,
   12168            1 :                 &ctx,
   12169            1 :                 vec![], // in-memory layers
   12170            1 :                 vec![
   12171            1 :                     // delta1/2/4 only contain a single key but multiple updates
   12172            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   12173            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   12174            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   12175            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   12176            1 :                 ], // delta layers
   12177            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12178            1 :                 Lsn(0x50),
   12179            1 :             )
   12180            1 :             .await?;
   12181              :         {
   12182            1 :             tline
   12183            1 :                 .applied_gc_cutoff_lsn
   12184            1 :                 .lock_for_write()
   12185            1 :                 .store_and_unlock(Lsn(0x30))
   12186            1 :                 .wait()
   12187            1 :                 .await;
   12188              :             // Update GC info
   12189            1 :             let mut guard = tline.gc_info.write().unwrap();
   12190            1 :             *guard = GcInfo {
   12191            1 :                 retain_lsns: vec![
   12192            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   12193            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   12194            1 :                 ],
   12195            1 :                 cutoffs: GcCutoffs {
   12196            1 :                     time: Some(Lsn(0x30)),
   12197            1 :                     space: Lsn(0x30),
   12198            1 :                 },
   12199            1 :                 leases: Default::default(),
   12200            1 :                 within_ancestor_pitr: false,
   12201            1 :             };
   12202              :         }
   12203              : 
   12204            1 :         let expected_result = [
   12205            1 :             Bytes::from_static(b"value 0@0x10"),
   12206            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   12207            1 :             Bytes::from_static(b"value 2@0x10"),
   12208            1 :             Bytes::from_static(b"value 3@0x10"),
   12209            1 :             Bytes::from_static(b"value 4@0x10"),
   12210            1 :             Bytes::from_static(b"value 5@0x10"),
   12211            1 :             Bytes::from_static(b"value 6@0x10"),
   12212            1 :             Bytes::from_static(b"value 7@0x10"),
   12213            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   12214            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   12215            1 :         ];
   12216              : 
   12217            1 :         let expected_result_at_gc_horizon = [
   12218            1 :             Bytes::from_static(b"value 0@0x10"),
   12219            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   12220            1 :             Bytes::from_static(b"value 2@0x10"),
   12221            1 :             Bytes::from_static(b"value 3@0x10"),
   12222            1 :             Bytes::from_static(b"value 4@0x10"),
   12223            1 :             Bytes::from_static(b"value 5@0x10"),
   12224            1 :             Bytes::from_static(b"value 6@0x10"),
   12225            1 :             Bytes::from_static(b"value 7@0x10"),
   12226            1 :             Bytes::from_static(b"value 8@0x10"),
   12227            1 :             Bytes::from_static(b"value 9@0x10"),
   12228            1 :         ];
   12229              : 
   12230            1 :         let expected_result_at_lsn_20 = [
   12231            1 :             Bytes::from_static(b"value 0@0x10"),
   12232            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   12233            1 :             Bytes::from_static(b"value 2@0x10"),
   12234            1 :             Bytes::from_static(b"value 3@0x10"),
   12235            1 :             Bytes::from_static(b"value 4@0x10"),
   12236            1 :             Bytes::from_static(b"value 5@0x10"),
   12237            1 :             Bytes::from_static(b"value 6@0x10"),
   12238            1 :             Bytes::from_static(b"value 7@0x10"),
   12239            1 :             Bytes::from_static(b"value 8@0x10"),
   12240            1 :             Bytes::from_static(b"value 9@0x10"),
   12241            1 :         ];
   12242              : 
   12243            1 :         let expected_result_at_lsn_10 = [
   12244            1 :             Bytes::from_static(b"value 0@0x10"),
   12245            1 :             Bytes::from_static(b"value 1@0x10"),
   12246            1 :             Bytes::from_static(b"value 2@0x10"),
   12247            1 :             Bytes::from_static(b"value 3@0x10"),
   12248            1 :             Bytes::from_static(b"value 4@0x10"),
   12249            1 :             Bytes::from_static(b"value 5@0x10"),
   12250            1 :             Bytes::from_static(b"value 6@0x10"),
   12251            1 :             Bytes::from_static(b"value 7@0x10"),
   12252            1 :             Bytes::from_static(b"value 8@0x10"),
   12253            1 :             Bytes::from_static(b"value 9@0x10"),
   12254            1 :         ];
   12255              : 
   12256            5 :         let verify_result = || async {
   12257            5 :             let gc_horizon = {
   12258            5 :                 let gc_info = tline.gc_info.read().unwrap();
   12259            5 :                 gc_info.cutoffs.time.unwrap_or_default()
   12260              :             };
   12261           55 :             for idx in 0..10 {
   12262           50 :                 assert_eq!(
   12263           50 :                     tline
   12264           50 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   12265           50 :                         .await
   12266           50 :                         .unwrap(),
   12267           50 :                     &expected_result[idx]
   12268              :                 );
   12269           50 :                 assert_eq!(
   12270           50 :                     tline
   12271           50 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   12272           50 :                         .await
   12273           50 :                         .unwrap(),
   12274           50 :                     &expected_result_at_gc_horizon[idx]
   12275              :                 );
   12276           50 :                 assert_eq!(
   12277           50 :                     tline
   12278           50 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   12279           50 :                         .await
   12280           50 :                         .unwrap(),
   12281           50 :                     &expected_result_at_lsn_20[idx]
   12282              :                 );
   12283           50 :                 assert_eq!(
   12284           50 :                     tline
   12285           50 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   12286           50 :                         .await
   12287           50 :                         .unwrap(),
   12288           50 :                     &expected_result_at_lsn_10[idx]
   12289              :                 );
   12290              :             }
   12291           10 :         };
   12292              : 
   12293            1 :         verify_result().await;
   12294              : 
   12295            1 :         let cancel = CancellationToken::new();
   12296              : 
   12297            1 :         tline
   12298            1 :             .compact_with_gc(
   12299            1 :                 &cancel,
   12300            1 :                 CompactOptions {
   12301            1 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   12302            1 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   12303            1 :                     ..Default::default()
   12304            1 :                 },
   12305            1 :                 &ctx,
   12306            1 :             )
   12307            1 :             .await
   12308            1 :             .unwrap();
   12309            1 :         verify_result().await;
   12310              : 
   12311            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12312            1 :         check_layer_map_key_eq(
   12313            1 :             all_layers,
   12314            1 :             vec![
   12315              :                 // The original image layer, not compacted
   12316            1 :                 PersistentLayerKey {
   12317            1 :                     key_range: get_key(0)..get_key(10),
   12318            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12319            1 :                     is_delta: false,
   12320            1 :                 },
   12321              :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   12322              :                 // the layer 0x28-0x30 into one.
   12323            1 :                 PersistentLayerKey {
   12324            1 :                     key_range: get_key(1)..get_key(2),
   12325            1 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12326            1 :                     is_delta: true,
   12327            1 :                 },
   12328              :                 // Above the upper bound and untouched
   12329            1 :                 PersistentLayerKey {
   12330            1 :                     key_range: get_key(1)..get_key(2),
   12331            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12332            1 :                     is_delta: true,
   12333            1 :                 },
   12334              :                 // This layer is untouched
   12335            1 :                 PersistentLayerKey {
   12336            1 :                     key_range: get_key(8)..get_key(10),
   12337            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12338            1 :                     is_delta: true,
   12339            1 :                 },
   12340              :             ],
   12341              :         );
   12342              : 
   12343            1 :         tline
   12344            1 :             .compact_with_gc(
   12345            1 :                 &cancel,
   12346            1 :                 CompactOptions {
   12347            1 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   12348            1 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   12349            1 :                     ..Default::default()
   12350            1 :                 },
   12351            1 :                 &ctx,
   12352            1 :             )
   12353            1 :             .await
   12354            1 :             .unwrap();
   12355            1 :         verify_result().await;
   12356              : 
   12357            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12358            1 :         check_layer_map_key_eq(
   12359            1 :             all_layers,
   12360            1 :             vec![
   12361              :                 // The original image layer, not compacted
   12362            1 :                 PersistentLayerKey {
   12363            1 :                     key_range: get_key(0)..get_key(10),
   12364            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12365            1 :                     is_delta: false,
   12366            1 :                 },
   12367              :                 // Not in the compaction key range, uncompacted
   12368            1 :                 PersistentLayerKey {
   12369            1 :                     key_range: get_key(1)..get_key(2),
   12370            1 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12371            1 :                     is_delta: true,
   12372            1 :                 },
   12373              :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   12374            1 :                 PersistentLayerKey {
   12375            1 :                     key_range: get_key(1)..get_key(2),
   12376            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12377            1 :                     is_delta: true,
   12378            1 :                 },
   12379              :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   12380              :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   12381              :                 // becomes 0x50.
   12382            1 :                 PersistentLayerKey {
   12383            1 :                     key_range: get_key(8)..get_key(10),
   12384            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12385            1 :                     is_delta: true,
   12386            1 :                 },
   12387              :             ],
   12388              :         );
   12389              : 
   12390              :         // compact again
   12391            1 :         tline
   12392            1 :             .compact_with_gc(
   12393            1 :                 &cancel,
   12394            1 :                 CompactOptions {
   12395            1 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   12396            1 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   12397            1 :                     ..Default::default()
   12398            1 :                 },
   12399            1 :                 &ctx,
   12400            1 :             )
   12401            1 :             .await
   12402            1 :             .unwrap();
   12403            1 :         verify_result().await;
   12404              : 
   12405            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12406            1 :         check_layer_map_key_eq(
   12407            1 :             all_layers,
   12408            1 :             vec![
   12409              :                 // The original image layer, not compacted
   12410            1 :                 PersistentLayerKey {
   12411            1 :                     key_range: get_key(0)..get_key(10),
   12412            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12413            1 :                     is_delta: false,
   12414            1 :                 },
   12415              :                 // The range gets compacted
   12416            1 :                 PersistentLayerKey {
   12417            1 :                     key_range: get_key(1)..get_key(2),
   12418            1 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   12419            1 :                     is_delta: true,
   12420            1 :                 },
   12421              :                 // Not touched during this iteration of compaction
   12422            1 :                 PersistentLayerKey {
   12423            1 :                     key_range: get_key(8)..get_key(10),
   12424            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12425            1 :                     is_delta: true,
   12426            1 :                 },
   12427              :             ],
   12428              :         );
   12429              : 
   12430              :         // final full compaction
   12431            1 :         tline
   12432            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   12433            1 :             .await
   12434            1 :             .unwrap();
   12435            1 :         verify_result().await;
   12436              : 
   12437            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12438            1 :         check_layer_map_key_eq(
   12439            1 :             all_layers,
   12440            1 :             vec![
   12441              :                 // The compacted image layer (full key range)
   12442            1 :                 PersistentLayerKey {
   12443            1 :                     key_range: Key::MIN..Key::MAX,
   12444            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12445            1 :                     is_delta: false,
   12446            1 :                 },
   12447              :                 // All other data in the delta layer
   12448            1 :                 PersistentLayerKey {
   12449            1 :                     key_range: get_key(1)..get_key(10),
   12450            1 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12451            1 :                     is_delta: true,
   12452            1 :                 },
   12453              :             ],
   12454              :         );
   12455              : 
   12456            2 :         Ok(())
   12457            1 :     }
   12458              : 
   12459              :     #[cfg(feature = "testing")]
   12460              :     #[tokio::test]
   12461            1 :     async fn test_bottom_most_compation_redo_failure() -> anyhow::Result<()> {
   12462            1 :         let harness = TenantHarness::create("test_bottom_most_compation_redo_failure").await?;
   12463            1 :         let (tenant, ctx) = harness.load().await;
   12464              : 
   12465           13 :         fn get_key(id: u32) -> Key {
   12466              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12467           13 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12468           13 :             key.field6 = id;
   12469           13 :             key
   12470           13 :         }
   12471              : 
   12472            1 :         let img_layer = (0..10)
   12473           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12474            1 :             .collect_vec();
   12475              : 
   12476            1 :         let delta1 = vec![
   12477            1 :             (
   12478            1 :                 get_key(1),
   12479            1 :                 Lsn(0x20),
   12480            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12481            1 :             ),
   12482            1 :             (
   12483            1 :                 get_key(1),
   12484            1 :                 Lsn(0x24),
   12485            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x24")),
   12486            1 :             ),
   12487            1 :             (
   12488            1 :                 get_key(1),
   12489            1 :                 Lsn(0x28),
   12490            1 :                 // This record will fail to redo
   12491            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("@0x28", "???")),
   12492            1 :             ),
   12493              :         ];
   12494              : 
   12495            1 :         let tline = tenant
   12496            1 :             .create_test_timeline_with_layers(
   12497            1 :                 TIMELINE_ID,
   12498            1 :                 Lsn(0x10),
   12499            1 :                 DEFAULT_PG_VERSION,
   12500            1 :                 &ctx,
   12501            1 :                 vec![], // in-memory layers
   12502            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   12503            1 :                     Lsn(0x20)..Lsn(0x30),
   12504            1 :                     delta1,
   12505            1 :                 )], // delta layers
   12506            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12507            1 :                 Lsn(0x50),
   12508            1 :             )
   12509            1 :             .await?;
   12510              :         {
   12511            1 :             tline
   12512            1 :                 .applied_gc_cutoff_lsn
   12513            1 :                 .lock_for_write()
   12514            1 :                 .store_and_unlock(Lsn(0x30))
   12515            1 :                 .wait()
   12516            1 :                 .await;
   12517              :             // Update GC info
   12518            1 :             let mut guard = tline.gc_info.write().unwrap();
   12519            1 :             *guard = GcInfo {
   12520            1 :                 retain_lsns: vec![],
   12521            1 :                 cutoffs: GcCutoffs {
   12522            1 :                     time: Some(Lsn(0x30)),
   12523            1 :                     space: Lsn(0x30),
   12524            1 :                 },
   12525            1 :                 leases: Default::default(),
   12526            1 :                 within_ancestor_pitr: false,
   12527            1 :             };
   12528              :         }
   12529              : 
   12530            1 :         let cancel = CancellationToken::new();
   12531              : 
   12532              :         // Compaction will fail, but should not fire any critical error.
   12533              :         // Gc-compaction currently cannot figure out what keys are not in the keyspace during the compaction
   12534              :         // process. It will always try to redo the logs it reads and if it doesn't work, fail the entire
   12535              :         // compaction job. Tracked in <https://github.com/neondatabase/neon/issues/10395>.
   12536            1 :         let res = tline
   12537            1 :             .compact_with_gc(
   12538            1 :                 &cancel,
   12539            1 :                 CompactOptions {
   12540            1 :                     compact_key_range: None,
   12541            1 :                     compact_lsn_range: None,
   12542            1 :                     ..Default::default()
   12543            1 :                 },
   12544            1 :                 &ctx,
   12545            1 :             )
   12546            1 :             .await;
   12547            1 :         assert!(res.is_err());
   12548              : 
   12549            2 :         Ok(())
   12550            1 :     }
   12551              : 
   12552              :     #[cfg(feature = "testing")]
   12553              :     #[tokio::test]
   12554            1 :     async fn test_synthetic_size_calculation_with_invisible_branches() -> anyhow::Result<()> {
   12555              :         use pageserver_api::models::TimelineVisibilityState;
   12556              : 
   12557              :         use crate::tenant::size::gather_inputs;
   12558              : 
   12559            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
   12560            1 :             // Ensure that we don't compute gc_cutoffs (which needs reading the layer files)
   12561            1 :             pitr_interval: Some(Duration::ZERO),
   12562            1 :             ..Default::default()
   12563            1 :         };
   12564            1 :         let harness = TenantHarness::create_custom(
   12565            1 :             "test_synthetic_size_calculation_with_invisible_branches",
   12566            1 :             tenant_conf,
   12567            1 :             TenantId::generate(),
   12568            1 :             ShardIdentity::unsharded(),
   12569            1 :             Generation::new(0xdeadbeef),
   12570            1 :         )
   12571            1 :         .await?;
   12572            1 :         let (tenant, ctx) = harness.load().await;
   12573            1 :         let main_tline = tenant
   12574            1 :             .create_test_timeline_with_layers(
   12575            1 :                 TIMELINE_ID,
   12576            1 :                 Lsn(0x10),
   12577            1 :                 DEFAULT_PG_VERSION,
   12578            1 :                 &ctx,
   12579            1 :                 vec![],
   12580            1 :                 vec![],
   12581            1 :                 vec![],
   12582            1 :                 Lsn(0x100),
   12583            1 :             )
   12584            1 :             .await?;
   12585              : 
   12586            1 :         let snapshot1 = TimelineId::from_array(hex!("11223344556677881122334455667790"));
   12587            1 :         tenant
   12588            1 :             .branch_timeline_test_with_layers(
   12589            1 :                 &main_tline,
   12590            1 :                 snapshot1,
   12591            1 :                 Some(Lsn(0x20)),
   12592            1 :                 &ctx,
   12593            1 :                 vec![],
   12594            1 :                 vec![],
   12595            1 :                 Lsn(0x50),
   12596            1 :             )
   12597            1 :             .await?;
   12598            1 :         let snapshot2 = TimelineId::from_array(hex!("11223344556677881122334455667791"));
   12599            1 :         tenant
   12600            1 :             .branch_timeline_test_with_layers(
   12601            1 :                 &main_tline,
   12602            1 :                 snapshot2,
   12603            1 :                 Some(Lsn(0x30)),
   12604            1 :                 &ctx,
   12605            1 :                 vec![],
   12606            1 :                 vec![],
   12607            1 :                 Lsn(0x50),
   12608            1 :             )
   12609            1 :             .await?;
   12610            1 :         let snapshot3 = TimelineId::from_array(hex!("11223344556677881122334455667792"));
   12611            1 :         tenant
   12612            1 :             .branch_timeline_test_with_layers(
   12613            1 :                 &main_tline,
   12614            1 :                 snapshot3,
   12615            1 :                 Some(Lsn(0x40)),
   12616            1 :                 &ctx,
   12617            1 :                 vec![],
   12618            1 :                 vec![],
   12619            1 :                 Lsn(0x50),
   12620            1 :             )
   12621            1 :             .await?;
   12622            1 :         let limit = Arc::new(Semaphore::new(1));
   12623            1 :         let max_retention_period = None;
   12624            1 :         let mut logical_size_cache = HashMap::new();
   12625            1 :         let cause = LogicalSizeCalculationCause::EvictionTaskImitation;
   12626            1 :         let cancel = CancellationToken::new();
   12627              : 
   12628            1 :         let inputs = gather_inputs(
   12629            1 :             &tenant,
   12630            1 :             &limit,
   12631            1 :             max_retention_period,
   12632            1 :             &mut logical_size_cache,
   12633            1 :             cause,
   12634            1 :             &cancel,
   12635            1 :             &ctx,
   12636              :         )
   12637            1 :         .instrument(info_span!(
   12638              :             "gather_inputs",
   12639              :             tenant_id = "unknown",
   12640              :             shard_id = "unknown",
   12641              :         ))
   12642            1 :         .await?;
   12643              :         use crate::tenant::size::{LsnKind, ModelInputs, SegmentMeta};
   12644              :         use LsnKind::*;
   12645              :         use tenant_size_model::Segment;
   12646            1 :         let ModelInputs { mut segments, .. } = inputs;
   12647           15 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12648            6 :         for segment in segments.iter_mut() {
   12649            6 :             segment.segment.parent = None; // We don't care about the parent for the test
   12650            6 :             segment.segment.size = None; // We don't care about the size for the test
   12651            6 :         }
   12652            1 :         assert_eq!(
   12653              :             segments,
   12654              :             [
   12655              :                 SegmentMeta {
   12656              :                     segment: Segment {
   12657              :                         parent: None,
   12658              :                         lsn: 0x10,
   12659              :                         size: None,
   12660              :                         needed: false,
   12661              :                     },
   12662              :                     timeline_id: TIMELINE_ID,
   12663              :                     kind: BranchStart,
   12664              :                 },
   12665              :                 SegmentMeta {
   12666              :                     segment: Segment {
   12667              :                         parent: None,
   12668              :                         lsn: 0x20,
   12669              :                         size: None,
   12670              :                         needed: false,
   12671              :                     },
   12672              :                     timeline_id: TIMELINE_ID,
   12673              :                     kind: BranchPoint,
   12674              :                 },
   12675              :                 SegmentMeta {
   12676              :                     segment: Segment {
   12677              :                         parent: None,
   12678              :                         lsn: 0x30,
   12679              :                         size: None,
   12680              :                         needed: false,
   12681              :                     },
   12682              :                     timeline_id: TIMELINE_ID,
   12683              :                     kind: BranchPoint,
   12684              :                 },
   12685              :                 SegmentMeta {
   12686              :                     segment: Segment {
   12687              :                         parent: None,
   12688              :                         lsn: 0x40,
   12689              :                         size: None,
   12690              :                         needed: false,
   12691              :                     },
   12692              :                     timeline_id: TIMELINE_ID,
   12693              :                     kind: BranchPoint,
   12694              :                 },
   12695              :                 SegmentMeta {
   12696              :                     segment: Segment {
   12697              :                         parent: None,
   12698              :                         lsn: 0x100,
   12699              :                         size: None,
   12700              :                         needed: false,
   12701              :                     },
   12702              :                     timeline_id: TIMELINE_ID,
   12703              :                     kind: GcCutOff,
   12704              :                 }, // we need to retain everything above the last branch point
   12705              :                 SegmentMeta {
   12706              :                     segment: Segment {
   12707              :                         parent: None,
   12708              :                         lsn: 0x100,
   12709              :                         size: None,
   12710              :                         needed: true,
   12711              :                     },
   12712              :                     timeline_id: TIMELINE_ID,
   12713              :                     kind: BranchEnd,
   12714              :                 },
   12715              :             ]
   12716              :         );
   12717              : 
   12718            1 :         main_tline
   12719            1 :             .remote_client
   12720            1 :             .schedule_index_upload_for_timeline_invisible_state(
   12721            1 :                 TimelineVisibilityState::Invisible,
   12722            0 :             )?;
   12723            1 :         main_tline.remote_client.wait_completion().await?;
   12724            1 :         let inputs = gather_inputs(
   12725            1 :             &tenant,
   12726            1 :             &limit,
   12727            1 :             max_retention_period,
   12728            1 :             &mut logical_size_cache,
   12729            1 :             cause,
   12730            1 :             &cancel,
   12731            1 :             &ctx,
   12732              :         )
   12733            1 :         .instrument(info_span!(
   12734              :             "gather_inputs",
   12735              :             tenant_id = "unknown",
   12736              :             shard_id = "unknown",
   12737              :         ))
   12738            1 :         .await?;
   12739            1 :         let ModelInputs { mut segments, .. } = inputs;
   12740           14 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12741            5 :         for segment in segments.iter_mut() {
   12742            5 :             segment.segment.parent = None; // We don't care about the parent for the test
   12743            5 :             segment.segment.size = None; // We don't care about the size for the test
   12744            5 :         }
   12745            1 :         assert_eq!(
   12746              :             segments,
   12747              :             [
   12748              :                 SegmentMeta {
   12749              :                     segment: Segment {
   12750              :                         parent: None,
   12751              :                         lsn: 0x10,
   12752              :                         size: None,
   12753              :                         needed: false,
   12754              :                     },
   12755              :                     timeline_id: TIMELINE_ID,
   12756              :                     kind: BranchStart,
   12757              :                 },
   12758              :                 SegmentMeta {
   12759              :                     segment: Segment {
   12760              :                         parent: None,
   12761              :                         lsn: 0x20,
   12762              :                         size: None,
   12763              :                         needed: false,
   12764              :                     },
   12765              :                     timeline_id: TIMELINE_ID,
   12766              :                     kind: BranchPoint,
   12767              :                 },
   12768              :                 SegmentMeta {
   12769              :                     segment: Segment {
   12770              :                         parent: None,
   12771              :                         lsn: 0x30,
   12772              :                         size: None,
   12773              :                         needed: false,
   12774              :                     },
   12775              :                     timeline_id: TIMELINE_ID,
   12776              :                     kind: BranchPoint,
   12777              :                 },
   12778              :                 SegmentMeta {
   12779              :                     segment: Segment {
   12780              :                         parent: None,
   12781              :                         lsn: 0x40,
   12782              :                         size: None,
   12783              :                         needed: false,
   12784              :                     },
   12785              :                     timeline_id: TIMELINE_ID,
   12786              :                     kind: BranchPoint,
   12787              :                 },
   12788              :                 SegmentMeta {
   12789              :                     segment: Segment {
   12790              :                         parent: None,
   12791              :                         lsn: 0x40, // Branch end LSN == last branch point LSN
   12792              :                         size: None,
   12793              :                         needed: true,
   12794              :                     },
   12795              :                     timeline_id: TIMELINE_ID,
   12796              :                     kind: BranchEnd,
   12797              :                 },
   12798              :             ]
   12799              :         );
   12800            2 :         Ok(())
   12801            1 :     }
   12802              : }
        

Generated by: LCOV version 2.1-beta