LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: 157166bf1e7b60cf936c3c96f6e44d24268705a4.info Lines: 77.7 % 8395 6527
Test Date: 2025-07-08 19:05:57 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::Other(err) => {
    3325            0 :                 self.compaction_circuit_breaker
    3326            0 :                     .lock()
    3327            0 :                     .unwrap()
    3328            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3329            0 :             }
    3330              :         }
    3331            0 :     }
    3332              : 
    3333              :     /// Cancel scheduled compaction tasks
    3334            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3335            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3336            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3337            0 :             q.cancel_scheduled();
    3338            0 :         }
    3339            0 :     }
    3340              : 
    3341            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3342            0 :         &self,
    3343            0 :         timeline_id: TimelineId,
    3344            0 :     ) -> Vec<CompactInfoResponse> {
    3345            0 :         let res = {
    3346            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3347            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3348              :         };
    3349            0 :         let Some((running, remaining)) = res else {
    3350            0 :             return Vec::new();
    3351              :         };
    3352            0 :         let mut result = Vec::new();
    3353            0 :         if let Some((id, running)) = running {
    3354            0 :             result.extend(running.into_compact_info_resp(id, true));
    3355            0 :         }
    3356            0 :         for (id, job) in remaining {
    3357            0 :             result.extend(job.into_compact_info_resp(id, false));
    3358            0 :         }
    3359            0 :         result
    3360            0 :     }
    3361              : 
    3362              :     /// Schedule a compaction task for a timeline.
    3363            0 :     pub(crate) async fn schedule_compaction(
    3364            0 :         &self,
    3365            0 :         timeline_id: TimelineId,
    3366            0 :         options: CompactOptions,
    3367            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3368            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3369            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3370            0 :         let q = guard
    3371            0 :             .entry(timeline_id)
    3372            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3373            0 :         q.schedule_manual_compaction(options, Some(tx));
    3374            0 :         Ok(rx)
    3375            0 :     }
    3376              : 
    3377              :     /// Performs periodic housekeeping, via the tenant housekeeping background task.
    3378            0 :     async fn housekeeping(&self) {
    3379              :         // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
    3380              :         // during ingest, but we don't want idle timelines to hold open layers for too long.
    3381              :         //
    3382              :         // We don't do this if the tenant can't upload layers (i.e. it's in stale attachment mode).
    3383              :         // We don't run compaction in this case either, and don't want to keep flushing tiny L0
    3384              :         // layers that won't be compacted down.
    3385            0 :         if self.tenant_conf.load().location.may_upload_layers_hint() {
    3386            0 :             let timelines = self
    3387            0 :                 .timelines
    3388            0 :                 .lock()
    3389            0 :                 .unwrap()
    3390            0 :                 .values()
    3391            0 :                 .filter(|tli| tli.is_active())
    3392            0 :                 .cloned()
    3393            0 :                 .collect_vec();
    3394              : 
    3395            0 :             for timeline in timelines {
    3396            0 :                 timeline.maybe_freeze_ephemeral_layer().await;
    3397              :             }
    3398            0 :         }
    3399              : 
    3400              :         // Shut down walredo if idle.
    3401              :         const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
    3402            0 :         if let Some(ref walredo_mgr) = self.walredo_mgr {
    3403            0 :             walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
    3404            0 :         }
    3405              : 
    3406              :         // Update the feature resolver with the latest tenant-spcific data.
    3407            0 :         self.feature_resolver.refresh_properties_and_flags(self);
    3408            0 :     }
    3409              : 
    3410            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3411            0 :         let timelines = self.timelines.lock().unwrap();
    3412            0 :         !timelines
    3413            0 :             .iter()
    3414            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3415            0 :     }
    3416              : 
    3417         1369 :     pub fn current_state(&self) -> TenantState {
    3418         1369 :         self.state.borrow().clone()
    3419         1369 :     }
    3420              : 
    3421          988 :     pub fn is_active(&self) -> bool {
    3422          988 :         self.current_state() == TenantState::Active
    3423          988 :     }
    3424              : 
    3425            0 :     pub fn generation(&self) -> Generation {
    3426            0 :         self.generation
    3427            0 :     }
    3428              : 
    3429            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3430            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3431            0 :     }
    3432              : 
    3433              :     /// Changes tenant status to active, unless shutdown was already requested.
    3434              :     ///
    3435              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3436              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3437            0 :     fn activate(
    3438            0 :         self: &Arc<Self>,
    3439            0 :         broker_client: BrokerClientChannel,
    3440            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3441            0 :         ctx: &RequestContext,
    3442            0 :     ) {
    3443            0 :         span::debug_assert_current_span_has_tenant_id();
    3444              : 
    3445            0 :         let mut activating = false;
    3446            0 :         self.state.send_modify(|current_state| {
    3447              :             use pageserver_api::models::ActivatingFrom;
    3448            0 :             match &*current_state {
    3449              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3450            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {current_state:?}");
    3451              :                 }
    3452            0 :                 TenantState::Attaching => {
    3453            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3454            0 :                 }
    3455              :             }
    3456            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3457            0 :             activating = true;
    3458              :             // Continue outside the closure. We need to grab timelines.lock()
    3459              :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3460            0 :         });
    3461              : 
    3462            0 :         if activating {
    3463            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3464            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3465            0 :             let timelines_to_activate = timelines_accessor
    3466            0 :                 .values()
    3467            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3468              : 
    3469              :             // Spawn gc and compaction loops. The loops will shut themselves
    3470              :             // down when they notice that the tenant is inactive.
    3471            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3472              : 
    3473            0 :             let mut activated_timelines = 0;
    3474              : 
    3475            0 :             for timeline in timelines_to_activate {
    3476            0 :                 timeline.activate(
    3477            0 :                     self.clone(),
    3478            0 :                     broker_client.clone(),
    3479            0 :                     background_jobs_can_start,
    3480            0 :                     &ctx.with_scope_timeline(timeline),
    3481            0 :                 );
    3482            0 :                 activated_timelines += 1;
    3483            0 :             }
    3484              : 
    3485            0 :             let tid = self.tenant_shard_id.tenant_id.to_string();
    3486            0 :             let shard_id = self.tenant_shard_id.shard_slug().to_string();
    3487            0 :             let offloaded_timeline_count = timelines_offloaded_accessor.len();
    3488            0 :             TENANT_OFFLOADED_TIMELINES
    3489            0 :                 .with_label_values(&[&tid, &shard_id])
    3490            0 :                 .set(offloaded_timeline_count as u64);
    3491              : 
    3492            0 :             self.state.send_modify(move |current_state| {
    3493            0 :                 assert!(
    3494            0 :                     matches!(current_state, TenantState::Activating(_)),
    3495            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3496              :                 );
    3497            0 :                 *current_state = TenantState::Active;
    3498              : 
    3499            0 :                 let elapsed = self.constructed_at.elapsed();
    3500            0 :                 let total_timelines = timelines_accessor.len();
    3501              : 
    3502              :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3503              :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3504            0 :                 info!(
    3505            0 :                     since_creation_millis = elapsed.as_millis(),
    3506            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3507            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3508              :                     activated_timelines,
    3509              :                     total_timelines,
    3510            0 :                     post_state = <&'static str>::from(&*current_state),
    3511            0 :                     "activation attempt finished"
    3512              :                 );
    3513              : 
    3514            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3515            0 :             });
    3516            0 :         }
    3517            0 :     }
    3518              : 
    3519              :     /// Shutdown the tenant and join all of the spawned tasks.
    3520              :     ///
    3521              :     /// The method caters for all use-cases:
    3522              :     /// - pageserver shutdown (freeze_and_flush == true)
    3523              :     /// - detach + ignore (freeze_and_flush == false)
    3524              :     ///
    3525              :     /// This will attempt to shutdown even if tenant is broken.
    3526              :     ///
    3527              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3528              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3529              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3530              :     /// the ongoing shutdown.
    3531            3 :     async fn shutdown(
    3532            3 :         &self,
    3533            3 :         shutdown_progress: completion::Barrier,
    3534            3 :         shutdown_mode: timeline::ShutdownMode,
    3535            3 :     ) -> Result<(), completion::Barrier> {
    3536            3 :         span::debug_assert_current_span_has_tenant_id();
    3537              : 
    3538              :         // Set tenant (and its timlines) to Stoppping state.
    3539              :         //
    3540              :         // Since we can only transition into Stopping state after activation is complete,
    3541              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3542              :         //
    3543              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3544              :         // 1. Lock out any new requests to the tenants.
    3545              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3546              :         // 3. Signal cancellation for other tenant background loops.
    3547              :         // 4. ???
    3548              :         //
    3549              :         // The waiting for the cancellation is not done uniformly.
    3550              :         // We certainly wait for WAL receivers to shut down.
    3551              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3552              :         // But the tenant background loops are joined-on in our caller.
    3553              :         // It's mesed up.
    3554              :         // we just ignore the failure to stop
    3555              : 
    3556              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3557              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3558              :         // is very slow.
    3559            3 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3560            0 :             self.cancel.cancel();
    3561              : 
    3562              :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3563              :             // are children of ours, so their flush loops will have shut down already
    3564            0 :             timeline::ShutdownMode::Hard
    3565              :         } else {
    3566            3 :             shutdown_mode
    3567              :         };
    3568              : 
    3569            3 :         match self.set_stopping(shutdown_progress).await {
    3570            3 :             Ok(()) => {}
    3571            0 :             Err(SetStoppingError::Broken) => {
    3572            0 :                 // assume that this is acceptable
    3573            0 :             }
    3574            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3575              :                 // give caller the option to wait for this this shutdown
    3576            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3577            0 :                 return Err(other);
    3578              :             }
    3579              :         };
    3580              : 
    3581            3 :         let mut js = tokio::task::JoinSet::new();
    3582              :         {
    3583            3 :             let timelines = self.timelines.lock().unwrap();
    3584            3 :             timelines.values().for_each(|timeline| {
    3585            3 :                 let timeline = Arc::clone(timeline);
    3586            3 :                 let timeline_id = timeline.timeline_id;
    3587            3 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3588            3 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3589            3 :             });
    3590              :         }
    3591              :         {
    3592            3 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3593            3 :             timelines_offloaded.values().for_each(|timeline| {
    3594            0 :                 timeline.defuse_for_tenant_drop();
    3595            0 :             });
    3596              :         }
    3597              :         {
    3598            3 :             let mut timelines_importing = self.timelines_importing.lock().unwrap();
    3599            3 :             timelines_importing
    3600            3 :                 .drain()
    3601            3 :                 .for_each(|(timeline_id, importing_timeline)| {
    3602            0 :                     let span = tracing::info_span!("importing_timeline_shutdown", %timeline_id);
    3603            0 :                     js.spawn(async move { importing_timeline.shutdown().instrument(span).await });
    3604            0 :                 });
    3605              :         }
    3606              :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3607            3 :         tracing::info!("Waiting for timelines...");
    3608            6 :         while let Some(res) = js.join_next().await {
    3609            0 :             match res {
    3610            3 :                 Ok(()) => {}
    3611            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3612            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3613            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3614              :             }
    3615              :         }
    3616              : 
    3617            3 :         if let ShutdownMode::Reload = shutdown_mode {
    3618            0 :             tracing::info!("Flushing deletion queue");
    3619            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3620            0 :                 match e {
    3621            0 :                     DeletionQueueError::ShuttingDown => {
    3622            0 :                         // This is the only error we expect for now. In the future, if more error
    3623            0 :                         // variants are added, we should handle them here.
    3624            0 :                     }
    3625              :                 }
    3626            0 :             }
    3627            3 :         }
    3628              : 
    3629              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3630              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3631            3 :         tracing::debug!("Cancelling CancellationToken");
    3632            3 :         self.cancel.cancel();
    3633              : 
    3634              :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3635              :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3636              :         //
    3637              :         // this will additionally shutdown and await all timeline tasks.
    3638            3 :         tracing::debug!("Waiting for tasks...");
    3639            3 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3640              : 
    3641            3 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3642            3 :             walredo_mgr.shutdown().await;
    3643            0 :         }
    3644              : 
    3645              :         // Wait for any in-flight operations to complete
    3646            3 :         self.gate.close().await;
    3647              : 
    3648            3 :         remove_tenant_metrics(&self.tenant_shard_id);
    3649              : 
    3650            3 :         Ok(())
    3651            3 :     }
    3652              : 
    3653              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3654              :     ///
    3655              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3656              :     ///
    3657              :     /// This function is not cancel-safe!
    3658            3 :     async fn set_stopping(&self, progress: completion::Barrier) -> Result<(), SetStoppingError> {
    3659            3 :         let mut rx = self.state.subscribe();
    3660              : 
    3661              :         // cannot stop before we're done activating, so wait out until we're done activating
    3662            3 :         rx.wait_for(|state| match state {
    3663              :             TenantState::Activating(_) | TenantState::Attaching => {
    3664            0 :                 info!("waiting for {state} to turn Active|Broken|Stopping");
    3665            0 :                 false
    3666              :             }
    3667            3 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3668            3 :         })
    3669            3 :         .await
    3670            3 :         .expect("cannot drop self.state while on a &self method");
    3671              : 
    3672              :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3673            3 :         let mut err = None;
    3674            3 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3675              :             TenantState::Activating(_) | TenantState::Attaching => {
    3676            0 :                 unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3677              :             }
    3678              :             TenantState::Active => {
    3679              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3680              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3681              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3682            3 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3683              :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3684              :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3685            3 :                 true
    3686              :             }
    3687              :             TenantState::Stopping { progress: None } => {
    3688              :                 // An attach was cancelled, and the attach transitioned the tenant from Attaching to
    3689              :                 // Stopping(None) to let us know it exited. Register our progress and continue.
    3690            0 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3691            0 :                 true
    3692              :             }
    3693            0 :             TenantState::Broken { reason, .. } => {
    3694            0 :                 info!(
    3695            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3696              :                 );
    3697            0 :                 err = Some(SetStoppingError::Broken);
    3698            0 :                 false
    3699              :             }
    3700            0 :             TenantState::Stopping { progress: Some(progress) } => {
    3701            0 :                 info!("Tenant is already in Stopping state");
    3702            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3703            0 :                 false
    3704              :             }
    3705            3 :         });
    3706            3 :         match (stopping, err) {
    3707            3 :             (true, None) => {} // continue
    3708            0 :             (false, Some(err)) => return Err(err),
    3709            0 :             (true, Some(_)) => unreachable!(
    3710              :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3711              :             ),
    3712            0 :             (false, None) => unreachable!(
    3713              :                 "send_if_modified closure must return true if transitioning to Stopping"
    3714              :             ),
    3715              :         }
    3716              : 
    3717            3 :         let timelines_accessor = self.timelines.lock().unwrap();
    3718            3 :         let not_broken_timelines = timelines_accessor
    3719            3 :             .values()
    3720            3 :             .filter(|timeline| !timeline.is_broken());
    3721            6 :         for timeline in not_broken_timelines {
    3722            3 :             timeline.set_state(TimelineState::Stopping);
    3723            3 :         }
    3724            3 :         Ok(())
    3725            3 :     }
    3726              : 
    3727              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3728              :     /// `remove_tenant_from_memory`
    3729              :     ///
    3730              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3731              :     ///
    3732              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3733            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3734            0 :         let mut rx = self.state.subscribe();
    3735              : 
    3736              :         // The load & attach routines own the tenant state until it has reached `Active`.
    3737              :         // So, wait until it's done.
    3738            0 :         rx.wait_for(|state| match state {
    3739              :             TenantState::Activating(_) | TenantState::Attaching => {
    3740            0 :                 info!(
    3741            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3742            0 :                     <&'static str>::from(state)
    3743              :                 );
    3744            0 :                 false
    3745              :             }
    3746            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3747            0 :         })
    3748            0 :         .await
    3749            0 :         .expect("cannot drop self.state while on a &self method");
    3750              : 
    3751              :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3752            0 :         self.set_broken_no_wait(reason)
    3753            0 :     }
    3754              : 
    3755            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3756            0 :         let reason = reason.to_string();
    3757            0 :         self.state.send_modify(|current_state| {
    3758            0 :             match *current_state {
    3759              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3760            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3761              :                 }
    3762              :                 TenantState::Active => {
    3763            0 :                     if cfg!(feature = "testing") {
    3764            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3765            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3766              :                     } else {
    3767            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3768              :                     }
    3769              :                 }
    3770              :                 TenantState::Broken { .. } => {
    3771            0 :                     warn!("Tenant is already in Broken state");
    3772              :                 }
    3773              :                 // This is the only "expected" path, any other path is a bug.
    3774              :                 TenantState::Stopping { .. } => {
    3775            0 :                     warn!(
    3776            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3777              :                         reason
    3778              :                     );
    3779            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3780              :                 }
    3781              :            }
    3782            0 :         });
    3783            0 :     }
    3784              : 
    3785            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3786            0 :         self.state.subscribe()
    3787            0 :     }
    3788              : 
    3789              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3790              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3791            0 :     pub(crate) fn activate_now(&self) {
    3792            0 :         self.activate_now_sem.add_permits(1);
    3793            0 :     }
    3794              : 
    3795            0 :     pub(crate) async fn wait_to_become_active(
    3796            0 :         &self,
    3797            0 :         timeout: Duration,
    3798            0 :     ) -> Result<(), GetActiveTenantError> {
    3799            0 :         let mut receiver = self.state.subscribe();
    3800              :         loop {
    3801            0 :             let current_state = receiver.borrow_and_update().clone();
    3802            0 :             match current_state {
    3803              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3804              :                     // in these states, there's a chance that we can reach ::Active
    3805            0 :                     self.activate_now();
    3806            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3807            0 :                         Ok(r) => {
    3808            0 :                             r.map_err(
    3809              :                             |_e: tokio::sync::watch::error::RecvError|
    3810              :                                 // Tenant existed but was dropped: report it as non-existent
    3811            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3812            0 :                         )?
    3813              :                         }
    3814              :                         Err(TimeoutCancellableError::Cancelled) => {
    3815            0 :                             return Err(GetActiveTenantError::Cancelled);
    3816              :                         }
    3817              :                         Err(TimeoutCancellableError::Timeout) => {
    3818            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3819            0 :                                 latest_state: Some(self.current_state()),
    3820            0 :                                 wait_time: timeout,
    3821            0 :                             });
    3822              :                         }
    3823              :                     }
    3824              :                 }
    3825              :                 TenantState::Active => {
    3826            0 :                     return Ok(());
    3827              :                 }
    3828            0 :                 TenantState::Broken { reason, .. } => {
    3829              :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3830              :                     // it's logically a 500 to external API users (broken is always a bug).
    3831            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3832              :                 }
    3833              :                 TenantState::Stopping { .. } => {
    3834              :                     // There's no chance the tenant can transition back into ::Active
    3835            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3836              :                 }
    3837              :             }
    3838              :         }
    3839            0 :     }
    3840              : 
    3841            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3842            0 :         self.tenant_conf.load().location.attach_mode
    3843            0 :     }
    3844              : 
    3845              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3846              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3847              :     /// rare external API calls, like a reconciliation at startup.
    3848            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3849            0 :         let attached_tenant_conf = self.tenant_conf.load();
    3850              : 
    3851            0 :         let location_config_mode = match attached_tenant_conf.location.attach_mode {
    3852            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3853            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3854            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3855              :         };
    3856              : 
    3857            0 :         models::LocationConfig {
    3858            0 :             mode: location_config_mode,
    3859            0 :             generation: self.generation.into(),
    3860            0 :             secondary_conf: None,
    3861            0 :             shard_number: self.shard_identity.number.0,
    3862            0 :             shard_count: self.shard_identity.count.literal(),
    3863            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3864            0 :             tenant_conf: attached_tenant_conf.tenant_conf.clone(),
    3865            0 :         }
    3866            0 :     }
    3867              : 
    3868            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3869            0 :         &self.tenant_shard_id
    3870            0 :     }
    3871              : 
    3872            0 :     pub(crate) fn get_shard_identity(&self) -> ShardIdentity {
    3873            0 :         self.shard_identity
    3874            0 :     }
    3875              : 
    3876          119 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3877          119 :         self.shard_identity.stripe_size
    3878          119 :     }
    3879              : 
    3880            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3881            0 :         self.generation
    3882            0 :     }
    3883              : 
    3884              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3885              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3886              :     /// resetting this tenant to a valid state if we fail.
    3887            0 :     pub(crate) async fn split_prepare(
    3888            0 :         &self,
    3889            0 :         child_shards: &Vec<TenantShardId>,
    3890            0 :     ) -> anyhow::Result<()> {
    3891            0 :         let (timelines, offloaded) = {
    3892            0 :             let timelines = self.timelines.lock().unwrap();
    3893            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3894            0 :             (timelines.clone(), offloaded.clone())
    3895            0 :         };
    3896            0 :         let timelines_iter = timelines
    3897            0 :             .values()
    3898            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3899            0 :             .chain(
    3900            0 :                 offloaded
    3901            0 :                     .values()
    3902            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3903              :             );
    3904            0 :         for timeline in timelines_iter {
    3905              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3906              :             // to ensure that they do not start a split if currently in the process of doing these.
    3907              : 
    3908            0 :             let timeline_id = timeline.timeline_id();
    3909              : 
    3910            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3911              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3912              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3913              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3914            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3915            0 :                 timeline
    3916            0 :                     .remote_client
    3917            0 :                     .schedule_index_upload_for_file_changes()?;
    3918            0 :                 timeline.remote_client.wait_completion().await?;
    3919            0 :             }
    3920              : 
    3921            0 :             let remote_client = match timeline {
    3922            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3923            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3924            0 :                     let remote_client = self
    3925            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3926            0 :                     Arc::new(remote_client)
    3927              :                 }
    3928              :                 TimelineOrOffloadedArcRef::Importing(_) => {
    3929            0 :                     unreachable!("Importing timelines are not included in the iterator")
    3930              :                 }
    3931              :             };
    3932              : 
    3933              :             // Shut down the timeline's remote client: this means that the indices we write
    3934              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3935            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3936            0 :             remote_client.shutdown().await;
    3937              : 
    3938              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3939              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3940              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3941              :             // we use here really is the remotely persistent one).
    3942            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3943            0 :             let result = remote_client
    3944            0 :                 .download_index_file(&self.cancel)
    3945            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))
    3946            0 :                 .await?;
    3947            0 :             let index_part = match result {
    3948              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3949            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3950              :                 }
    3951            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3952              :             };
    3953              : 
    3954              :             // A shard split may not take place while a timeline import is on-going
    3955              :             // for the tenant. Timeline imports run as part of each tenant shard
    3956              :             // and rely on the sharding scheme to split the work among pageservers.
    3957              :             // If we were to split in the middle of this process, we would have to
    3958              :             // either ensure that it's driven to completion on the old shard set
    3959              :             // or transfer it to the new shard set. It's technically possible, but complex.
    3960            0 :             match index_part.import_pgdata {
    3961            0 :                 Some(ref import) if !import.is_done() => {
    3962            0 :                     anyhow::bail!(
    3963            0 :                         "Cannot split due to import with idempotency key: {:?}",
    3964            0 :                         import.idempotency_key()
    3965              :                     );
    3966              :                 }
    3967            0 :                 Some(_) | None => {
    3968            0 :                     // fallthrough
    3969            0 :                 }
    3970              :             }
    3971              : 
    3972            0 :             for child_shard in child_shards {
    3973            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3974            0 :                 upload_index_part(
    3975            0 :                     &self.remote_storage,
    3976            0 :                     child_shard,
    3977            0 :                     &timeline_id,
    3978            0 :                     self.generation,
    3979            0 :                     &index_part,
    3980            0 :                     &self.cancel,
    3981            0 :                 )
    3982            0 :                 .await?;
    3983              :             }
    3984              :         }
    3985              : 
    3986            0 :         let tenant_manifest = self.build_tenant_manifest();
    3987            0 :         for child_shard in child_shards {
    3988            0 :             tracing::info!(
    3989            0 :                 "Uploading tenant manifest for child {}",
    3990            0 :                 child_shard.to_index()
    3991              :             );
    3992            0 :             upload_tenant_manifest(
    3993            0 :                 &self.remote_storage,
    3994            0 :                 child_shard,
    3995            0 :                 self.generation,
    3996            0 :                 &tenant_manifest,
    3997            0 :                 &self.cancel,
    3998            0 :             )
    3999            0 :             .await?;
    4000              :         }
    4001              : 
    4002            0 :         Ok(())
    4003            0 :     }
    4004              : 
    4005            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    4006            0 :         let mut result = TopTenantShardItem {
    4007            0 :             id: self.tenant_shard_id,
    4008            0 :             resident_size: 0,
    4009            0 :             physical_size: 0,
    4010            0 :             max_logical_size: 0,
    4011            0 :             max_logical_size_per_shard: 0,
    4012            0 :         };
    4013              : 
    4014            0 :         for timeline in self.timelines.lock().unwrap().values() {
    4015            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    4016            0 : 
    4017            0 :             result.physical_size += timeline
    4018            0 :                 .remote_client
    4019            0 :                 .metrics
    4020            0 :                 .remote_physical_size_gauge
    4021            0 :                 .get();
    4022            0 :             result.max_logical_size = std::cmp::max(
    4023            0 :                 result.max_logical_size,
    4024            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    4025            0 :             );
    4026            0 :         }
    4027              : 
    4028            0 :         result.max_logical_size_per_shard = result
    4029            0 :             .max_logical_size
    4030            0 :             .div_ceil(self.tenant_shard_id.shard_count.count() as u64);
    4031              : 
    4032            0 :         result
    4033            0 :     }
    4034              : }
    4035              : 
    4036              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    4037              : /// perform a topological sort, so that the parent of each timeline comes
    4038              : /// before the children.
    4039              : /// E extracts the ancestor from T
    4040              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    4041          118 : fn tree_sort_timelines<T, E>(
    4042          118 :     timelines: HashMap<TimelineId, T>,
    4043          118 :     extractor: E,
    4044          118 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    4045          118 : where
    4046          118 :     E: Fn(&T) -> Option<TimelineId>,
    4047              : {
    4048          118 :     let mut result = Vec::with_capacity(timelines.len());
    4049              : 
    4050          118 :     let mut now = Vec::with_capacity(timelines.len());
    4051              :     // (ancestor, children)
    4052          118 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    4053          118 :         HashMap::with_capacity(timelines.len());
    4054              : 
    4055          121 :     for (timeline_id, value) in timelines {
    4056            3 :         if let Some(ancestor_id) = extractor(&value) {
    4057            1 :             let children = later.entry(ancestor_id).or_default();
    4058            1 :             children.push((timeline_id, value));
    4059            2 :         } else {
    4060            2 :             now.push((timeline_id, value));
    4061            2 :         }
    4062              :     }
    4063              : 
    4064          121 :     while let Some((timeline_id, metadata)) = now.pop() {
    4065            3 :         result.push((timeline_id, metadata));
    4066              :         // All children of this can be loaded now
    4067            3 :         if let Some(mut children) = later.remove(&timeline_id) {
    4068            1 :             now.append(&mut children);
    4069            2 :         }
    4070              :     }
    4071              : 
    4072              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    4073          118 :     if !later.is_empty() {
    4074            0 :         for (missing_id, orphan_ids) in later {
    4075            0 :             for (orphan_id, _) in orphan_ids {
    4076            0 :                 error!(
    4077            0 :                     "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
    4078              :                 );
    4079              :             }
    4080              :         }
    4081            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    4082          118 :     }
    4083              : 
    4084          118 :     Ok(result)
    4085          118 : }
    4086              : 
    4087              : impl TenantShard {
    4088            0 :     pub fn tenant_specific_overrides(&self) -> pageserver_api::models::TenantConfig {
    4089            0 :         self.tenant_conf.load().tenant_conf.clone()
    4090            0 :     }
    4091              : 
    4092            0 :     pub fn effective_config(&self) -> pageserver_api::config::TenantConfigToml {
    4093            0 :         self.tenant_specific_overrides()
    4094            0 :             .merge(self.conf.default_tenant_conf.clone())
    4095            0 :     }
    4096              : 
    4097            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    4098            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4099            0 :         tenant_conf
    4100            0 :             .checkpoint_distance
    4101            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    4102            0 :     }
    4103              : 
    4104            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    4105            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4106            0 :         tenant_conf
    4107            0 :             .checkpoint_timeout
    4108            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    4109            0 :     }
    4110              : 
    4111            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    4112            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4113            0 :         tenant_conf
    4114            0 :             .compaction_target_size
    4115            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    4116            0 :     }
    4117              : 
    4118            0 :     pub fn get_compaction_period(&self) -> Duration {
    4119            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4120            0 :         tenant_conf
    4121            0 :             .compaction_period
    4122            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    4123            0 :     }
    4124              : 
    4125            0 :     pub fn get_compaction_threshold(&self) -> usize {
    4126            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4127            0 :         tenant_conf
    4128            0 :             .compaction_threshold
    4129            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    4130            0 :     }
    4131              : 
    4132            0 :     pub fn get_rel_size_v2_enabled(&self) -> bool {
    4133            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4134            0 :         tenant_conf
    4135            0 :             .rel_size_v2_enabled
    4136            0 :             .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
    4137            0 :     }
    4138              : 
    4139            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    4140            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4141            0 :         tenant_conf
    4142            0 :             .compaction_upper_limit
    4143            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    4144            0 :     }
    4145              : 
    4146            0 :     pub fn get_compaction_l0_first(&self) -> bool {
    4147            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4148            0 :         tenant_conf
    4149            0 :             .compaction_l0_first
    4150            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
    4151            0 :     }
    4152              : 
    4153          120 :     pub fn get_gc_horizon(&self) -> u64 {
    4154          120 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4155          120 :         tenant_conf
    4156          120 :             .gc_horizon
    4157          120 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    4158          120 :     }
    4159              : 
    4160            0 :     pub fn get_gc_period(&self) -> Duration {
    4161            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4162            0 :         tenant_conf
    4163            0 :             .gc_period
    4164            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    4165            0 :     }
    4166              : 
    4167            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    4168            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4169            0 :         tenant_conf
    4170            0 :             .image_creation_threshold
    4171            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    4172            0 :     }
    4173              : 
    4174            2 :     pub fn get_pitr_interval(&self) -> Duration {
    4175            2 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4176            2 :         tenant_conf
    4177            2 :             .pitr_interval
    4178            2 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    4179            2 :     }
    4180              : 
    4181            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    4182            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4183            0 :         tenant_conf
    4184            0 :             .min_resident_size_override
    4185            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    4186            0 :     }
    4187              : 
    4188            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    4189            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4190            0 :         let heatmap_period = tenant_conf
    4191            0 :             .heatmap_period
    4192            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    4193            0 :         if heatmap_period.is_zero() {
    4194            0 :             None
    4195              :         } else {
    4196            0 :             Some(heatmap_period)
    4197              :         }
    4198            0 :     }
    4199              : 
    4200            0 :     pub fn get_lsn_lease_length(&self) -> Duration {
    4201            0 :         Self::get_lsn_lease_length_impl(self.conf, &self.tenant_conf.load().tenant_conf)
    4202            0 :     }
    4203              : 
    4204          118 :     pub fn get_lsn_lease_length_impl(
    4205          118 :         conf: &'static PageServerConf,
    4206          118 :         tenant_conf: &pageserver_api::models::TenantConfig,
    4207          118 :     ) -> Duration {
    4208          118 :         tenant_conf
    4209          118 :             .lsn_lease_length
    4210          118 :             .unwrap_or(conf.default_tenant_conf.lsn_lease_length)
    4211          118 :     }
    4212              : 
    4213            0 :     pub fn get_timeline_offloading_enabled(&self) -> bool {
    4214            0 :         if self.conf.timeline_offloading {
    4215            0 :             return true;
    4216            0 :         }
    4217            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4218            0 :         tenant_conf
    4219            0 :             .timeline_offloading
    4220            0 :             .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
    4221            0 :     }
    4222              : 
    4223              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    4224          119 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4225              :         // Collect the offloaded timelines, and sort them for deterministic output.
    4226          119 :         let offloaded_timelines = self
    4227          119 :             .timelines_offloaded
    4228          119 :             .lock()
    4229          119 :             .unwrap()
    4230          119 :             .values()
    4231          119 :             .map(|tli| tli.manifest())
    4232          119 :             .sorted_by_key(|m| m.timeline_id)
    4233          119 :             .collect_vec();
    4234              : 
    4235          119 :         TenantManifest {
    4236          119 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4237          119 :             stripe_size: Some(self.get_shard_stripe_size()),
    4238          119 :             offloaded_timelines,
    4239          119 :         }
    4240          119 :     }
    4241              : 
    4242            1 :     pub fn update_tenant_config<
    4243            1 :         F: Fn(
    4244            1 :             pageserver_api::models::TenantConfig,
    4245            1 :         ) -> anyhow::Result<pageserver_api::models::TenantConfig>,
    4246            1 :     >(
    4247            1 :         &self,
    4248            1 :         update: F,
    4249            1 :     ) -> anyhow::Result<pageserver_api::models::TenantConfig> {
    4250              :         // Use read-copy-update in order to avoid overwriting the location config
    4251              :         // state if this races with [`TenantShard::set_new_location_config`]. Note that
    4252              :         // this race is not possible if both request types come from the storage
    4253              :         // controller (as they should!) because an exclusive op lock is required
    4254              :         // on the storage controller side.
    4255              : 
    4256            1 :         self.tenant_conf
    4257            1 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    4258            1 :                 Ok(Arc::new(AttachedTenantConf {
    4259            1 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    4260            1 :                     location: attached_conf.location,
    4261            1 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    4262              :                 }))
    4263            1 :             })?;
    4264              : 
    4265            1 :         let updated = self.tenant_conf.load();
    4266              : 
    4267            1 :         self.tenant_conf_updated(&updated.tenant_conf);
    4268              :         // Don't hold self.timelines.lock() during the notifies.
    4269              :         // There's no risk of deadlock right now, but there could be if we consolidate
    4270              :         // mutexes in struct Timeline in the future.
    4271            1 :         let timelines = self.list_timelines();
    4272            1 :         for timeline in timelines {
    4273            0 :             timeline.tenant_conf_updated(&updated);
    4274            0 :         }
    4275              : 
    4276            1 :         Ok(updated.tenant_conf.clone())
    4277            1 :     }
    4278              : 
    4279            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    4280            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    4281              : 
    4282            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4283              : 
    4284            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4285              :         // Don't hold self.timelines.lock() during the notifies.
    4286              :         // There's no risk of deadlock right now, but there could be if we consolidate
    4287              :         // mutexes in struct Timeline in the future.
    4288            0 :         let timelines = self.list_timelines();
    4289            0 :         for timeline in timelines {
    4290            0 :             timeline.tenant_conf_updated(&new_conf);
    4291            0 :         }
    4292            0 :     }
    4293              : 
    4294          119 :     fn get_pagestream_throttle_config(
    4295          119 :         psconf: &'static PageServerConf,
    4296          119 :         overrides: &pageserver_api::models::TenantConfig,
    4297          119 :     ) -> throttle::Config {
    4298          119 :         overrides
    4299          119 :             .timeline_get_throttle
    4300          119 :             .clone()
    4301          119 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4302          119 :     }
    4303              : 
    4304            1 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &pageserver_api::models::TenantConfig) {
    4305            1 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4306            1 :         self.pagestream_throttle.reconfigure(conf)
    4307            1 :     }
    4308              : 
    4309              :     /// Helper function to create a new Timeline struct.
    4310              :     ///
    4311              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4312              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4313              :     /// map.
    4314              :     ///
    4315              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4316              :     /// and we might not have the ancestor present anymore which is fine for to be
    4317              :     /// deleted timelines.
    4318              :     #[allow(clippy::too_many_arguments)]
    4319          234 :     fn create_timeline_struct(
    4320          234 :         &self,
    4321          234 :         new_timeline_id: TimelineId,
    4322          234 :         new_metadata: &TimelineMetadata,
    4323          234 :         previous_heatmap: Option<PreviousHeatmap>,
    4324          234 :         ancestor: Option<Arc<Timeline>>,
    4325          234 :         resources: TimelineResources,
    4326          234 :         cause: CreateTimelineCause,
    4327          234 :         create_idempotency: CreateTimelineIdempotency,
    4328          234 :         gc_compaction_state: Option<GcCompactionState>,
    4329          234 :         rel_size_v2_status: Option<RelSizeMigration>,
    4330          234 :         ctx: &RequestContext,
    4331          234 :     ) -> anyhow::Result<(Arc<Timeline>, RequestContext)> {
    4332          234 :         let state = match cause {
    4333              :             CreateTimelineCause::Load => {
    4334          234 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4335          234 :                 anyhow::ensure!(
    4336          234 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4337            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4338              :                 );
    4339          234 :                 TimelineState::Loading
    4340              :             }
    4341            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4342              :         };
    4343              : 
    4344          234 :         let pg_version = new_metadata.pg_version();
    4345              : 
    4346          234 :         let timeline = Timeline::new(
    4347          234 :             self.conf,
    4348          234 :             Arc::clone(&self.tenant_conf),
    4349          234 :             new_metadata,
    4350          234 :             previous_heatmap,
    4351          234 :             ancestor,
    4352          234 :             new_timeline_id,
    4353          234 :             self.tenant_shard_id,
    4354          234 :             self.generation,
    4355          234 :             self.shard_identity,
    4356          234 :             self.walredo_mgr.clone(),
    4357          234 :             resources,
    4358          234 :             pg_version,
    4359          234 :             state,
    4360          234 :             self.attach_wal_lag_cooldown.clone(),
    4361          234 :             create_idempotency,
    4362          234 :             gc_compaction_state,
    4363          234 :             rel_size_v2_status,
    4364          234 :             self.cancel.child_token(),
    4365              :         );
    4366              : 
    4367          234 :         let timeline_ctx = RequestContextBuilder::from(ctx)
    4368          234 :             .scope(context::Scope::new_timeline(&timeline))
    4369          234 :             .detached_child();
    4370              : 
    4371          234 :         Ok((timeline, timeline_ctx))
    4372          234 :     }
    4373              : 
    4374              :     /// [`TenantShard::shutdown`] must be called before dropping the returned [`TenantShard`] object
    4375              :     /// to ensure proper cleanup of background tasks and metrics.
    4376              :     //
    4377              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4378              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4379              :     #[allow(clippy::too_many_arguments)]
    4380          118 :     fn new(
    4381          118 :         state: TenantState,
    4382          118 :         conf: &'static PageServerConf,
    4383          118 :         attached_conf: AttachedTenantConf,
    4384          118 :         shard_identity: ShardIdentity,
    4385          118 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4386          118 :         tenant_shard_id: TenantShardId,
    4387          118 :         remote_storage: GenericRemoteStorage,
    4388          118 :         deletion_queue_client: DeletionQueueClient,
    4389          118 :         l0_flush_global_state: L0FlushGlobalState,
    4390          118 :         basebackup_cache: Arc<BasebackupCache>,
    4391          118 :         feature_resolver: FeatureResolver,
    4392          118 :     ) -> TenantShard {
    4393          118 :         assert!(!attached_conf.location.generation.is_none());
    4394              : 
    4395          118 :         let (state, mut rx) = watch::channel(state);
    4396              : 
    4397          118 :         tokio::spawn(async move {
    4398              :             // reflect tenant state in metrics:
    4399              :             // - global per tenant state: TENANT_STATE_METRIC
    4400              :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4401              :             //
    4402              :             // set of broken tenants should not have zero counts so that it remains accessible for
    4403              :             // alerting.
    4404              : 
    4405          118 :             let tid = tenant_shard_id.to_string();
    4406          118 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4407          118 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4408              : 
    4409          236 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4410          236 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4411          236 :             }
    4412              : 
    4413          118 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4414              : 
    4415          118 :             let is_broken = tuple.1;
    4416          118 :             let mut counted_broken = if is_broken {
    4417              :                 // add the id to the set right away, there should not be any updates on the channel
    4418              :                 // after before tenant is removed, if ever
    4419            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4420            0 :                 true
    4421              :             } else {
    4422          118 :                 false
    4423              :             };
    4424              : 
    4425              :             loop {
    4426          236 :                 let labels = &tuple.0;
    4427          236 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4428          236 :                 current.inc();
    4429              : 
    4430          236 :                 if rx.changed().await.is_err() {
    4431              :                     // tenant has been dropped
    4432            7 :                     current.dec();
    4433            7 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4434            7 :                     break;
    4435          118 :                 }
    4436              : 
    4437          118 :                 current.dec();
    4438          118 :                 tuple = inspect_state(&rx.borrow_and_update());
    4439              : 
    4440          118 :                 let is_broken = tuple.1;
    4441          118 :                 if is_broken && !counted_broken {
    4442            0 :                     counted_broken = true;
    4443            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4444            0 :                     // access
    4445            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4446          118 :                 }
    4447              :             }
    4448            7 :         });
    4449              : 
    4450          118 :         TenantShard {
    4451          118 :             tenant_shard_id,
    4452          118 :             shard_identity,
    4453          118 :             generation: attached_conf.location.generation,
    4454          118 :             conf,
    4455          118 :             // using now here is good enough approximation to catch tenants with really long
    4456          118 :             // activation times.
    4457          118 :             constructed_at: Instant::now(),
    4458          118 :             timelines: Mutex::new(HashMap::new()),
    4459          118 :             timelines_creating: Mutex::new(HashSet::new()),
    4460          118 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4461          118 :             timelines_importing: Mutex::new(HashMap::new()),
    4462          118 :             remote_tenant_manifest: Default::default(),
    4463          118 :             gc_cs: tokio::sync::Mutex::new(()),
    4464          118 :             walredo_mgr,
    4465          118 :             remote_storage,
    4466          118 :             deletion_queue_client,
    4467          118 :             state,
    4468          118 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4469          118 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4470          118 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4471          118 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4472          118 :                 format!("compaction-{tenant_shard_id}"),
    4473          118 :                 5,
    4474          118 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4475          118 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4476          118 :                 // use an extremely long backoff.
    4477          118 :                 Some(Duration::from_secs(3600 * 24)),
    4478          118 :             )),
    4479          118 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4480          118 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4481          118 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4482          118 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4483          118 :             cancel: CancellationToken::default(),
    4484          118 :             gate: Gate::default(),
    4485          118 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4486          118 :                 TenantShard::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4487          118 :             )),
    4488          118 :             pagestream_throttle_metrics: Arc::new(
    4489          118 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4490          118 :             ),
    4491          118 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4492          118 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4493          118 :             gc_block: Default::default(),
    4494          118 :             l0_flush_global_state,
    4495          118 :             basebackup_cache,
    4496          118 :             feature_resolver: Arc::new(TenantFeatureResolver::new(
    4497          118 :                 feature_resolver,
    4498          118 :                 tenant_shard_id.tenant_id,
    4499          118 :             )),
    4500          118 :         }
    4501          118 :     }
    4502              : 
    4503              :     /// Locate and load config
    4504            0 :     pub(super) fn load_tenant_config(
    4505            0 :         conf: &'static PageServerConf,
    4506            0 :         tenant_shard_id: &TenantShardId,
    4507            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4508            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4509              : 
    4510            0 :         info!("loading tenant configuration from {config_path}");
    4511              : 
    4512              :         // load and parse file
    4513            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4514            0 :             match e.kind() {
    4515              :                 std::io::ErrorKind::NotFound => {
    4516              :                     // The config should almost always exist for a tenant directory:
    4517              :                     //  - When attaching a tenant, the config is the first thing we write
    4518              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4519              :                     //    before deleting contents.
    4520              :                     //
    4521              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4522              :                     // between creating directory and writing config.  Callers should handle that as if the
    4523              :                     // directory didn't exist.
    4524              : 
    4525            0 :                     LoadConfigError::NotFound(config_path)
    4526              :                 }
    4527              :                 _ => {
    4528              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4529              :                     // that we cannot cleanly recover
    4530            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4531              :                 }
    4532              :             }
    4533            0 :         })?;
    4534              : 
    4535            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4536            0 :     }
    4537              : 
    4538              :     /// Stores a tenant location config to disk.
    4539              :     ///
    4540              :     /// NB: make sure to call `ShardIdentity::assert_equal` before persisting a new config, to avoid
    4541              :     /// changes to shard parameters that may result in data corruption.
    4542              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4543              :     pub(super) async fn persist_tenant_config(
    4544              :         conf: &'static PageServerConf,
    4545              :         tenant_shard_id: &TenantShardId,
    4546              :         location_conf: &LocationConf,
    4547              :     ) -> std::io::Result<()> {
    4548              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4549              : 
    4550              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4551              :     }
    4552              : 
    4553              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4554              :     pub(super) async fn persist_tenant_config_at(
    4555              :         tenant_shard_id: &TenantShardId,
    4556              :         config_path: &Utf8Path,
    4557              :         location_conf: &LocationConf,
    4558              :     ) -> std::io::Result<()> {
    4559              :         debug!("persisting tenantconf to {config_path}");
    4560              : 
    4561              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4562              : #  It is read in case of pageserver restart.
    4563              : "#
    4564              :         .to_string();
    4565              : 
    4566            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4567            0 :             Err(std::io::Error::other("tenant-config-before-write"))
    4568            0 :         });
    4569              : 
    4570              :         // Convert the config to a toml file.
    4571              :         conf_content +=
    4572              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4573              : 
    4574              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4575              : 
    4576              :         let conf_content = conf_content.into_bytes();
    4577              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4578              :     }
    4579              : 
    4580              :     //
    4581              :     // How garbage collection works:
    4582              :     //
    4583              :     //                    +--bar------------->
    4584              :     //                   /
    4585              :     //             +----+-----foo---------------->
    4586              :     //            /
    4587              :     // ----main--+-------------------------->
    4588              :     //                \
    4589              :     //                 +-----baz-------->
    4590              :     //
    4591              :     //
    4592              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4593              :     //    `gc_infos` are being refreshed
    4594              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4595              :     //    all the points where other timelines have been branched off.
    4596              :     //    We will refrain from removing page versions at those LSNs.
    4597              :     // 3. For each timeline, scan all layer files on the timeline.
    4598              :     //    Remove all files for which a newer file exists and which
    4599              :     //    don't cover any branch point LSNs.
    4600              :     //
    4601              :     // TODO:
    4602              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4603              :     //   don't need to keep that in the parent anymore. But currently
    4604              :     //   we do.
    4605          377 :     async fn gc_iteration_internal(
    4606          377 :         &self,
    4607          377 :         target_timeline_id: Option<TimelineId>,
    4608          377 :         horizon: u64,
    4609          377 :         pitr: Duration,
    4610          377 :         cancel: &CancellationToken,
    4611          377 :         ctx: &RequestContext,
    4612          377 :     ) -> Result<GcResult, GcError> {
    4613          377 :         let mut totals: GcResult = Default::default();
    4614          377 :         let now = Instant::now();
    4615              : 
    4616          377 :         let gc_timelines = self
    4617          377 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4618          377 :             .await?;
    4619              : 
    4620          377 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4621              : 
    4622              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4623          377 :         if !gc_timelines.is_empty() {
    4624          377 :             info!("{} timelines need GC", gc_timelines.len());
    4625              :         } else {
    4626            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4627              :         }
    4628              : 
    4629              :         // Perform GC for each timeline.
    4630              :         //
    4631              :         // Note that we don't hold the `TenantShard::gc_cs` lock here because we don't want to delay the
    4632              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4633              :         // with branch creation.
    4634              :         //
    4635              :         // See comments in [`TenantShard::branch_timeline`] for more information about why branch
    4636              :         // creation task can run concurrently with timeline's GC iteration.
    4637          754 :         for timeline in gc_timelines {
    4638          377 :             if cancel.is_cancelled() {
    4639              :                 // We were requested to shut down. Stop and return with the progress we
    4640              :                 // made.
    4641            0 :                 break;
    4642          377 :             }
    4643          377 :             let result = match timeline.gc().await {
    4644              :                 Err(GcError::TimelineCancelled) => {
    4645            0 :                     if target_timeline_id.is_some() {
    4646              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4647            0 :                         return Err(GcError::TimelineCancelled);
    4648              :                     } else {
    4649              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4650              :                         // skip past this and proceed to try GC on other timelines.
    4651            0 :                         continue;
    4652              :                     }
    4653              :                 }
    4654          377 :                 r => r?,
    4655              :             };
    4656          377 :             totals += result;
    4657              :         }
    4658              : 
    4659          377 :         totals.elapsed = now.elapsed();
    4660          377 :         Ok(totals)
    4661          377 :     }
    4662              : 
    4663              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4664              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4665              :     /// [`TenantShard::get_gc_horizon`].
    4666              :     ///
    4667              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4668            2 :     pub(crate) async fn refresh_gc_info(
    4669            2 :         &self,
    4670            2 :         cancel: &CancellationToken,
    4671            2 :         ctx: &RequestContext,
    4672            2 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4673              :         // since this method can now be called at different rates than the configured gc loop, it
    4674              :         // might be that these configuration values get applied faster than what it was previously,
    4675              :         // since these were only read from the gc task.
    4676            2 :         let horizon = self.get_gc_horizon();
    4677            2 :         let pitr = self.get_pitr_interval();
    4678              : 
    4679              :         // refresh all timelines
    4680            2 :         let target_timeline_id = None;
    4681              : 
    4682            2 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4683            2 :             .await
    4684            2 :     }
    4685              : 
    4686              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4687              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4688              :     ///
    4689              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4690          118 :     fn initialize_gc_info(
    4691          118 :         &self,
    4692          118 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4693          118 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4694          118 :         restrict_to_timeline: Option<TimelineId>,
    4695          118 :     ) {
    4696          118 :         if restrict_to_timeline.is_none() {
    4697              :             // This function must be called before activation: after activation timeline create/delete operations
    4698              :             // might happen, and this function is not safe to run concurrently with those.
    4699          118 :             assert!(!self.is_active());
    4700            0 :         }
    4701              : 
    4702              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4703              :         // the branch point where it was created.
    4704          118 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4705          118 :             BTreeMap::new();
    4706          118 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4707            3 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4708            1 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4709            1 :                 ancestor_children.push((
    4710            1 :                     timeline_entry.get_ancestor_lsn(),
    4711            1 :                     *timeline_id,
    4712            1 :                     MaybeOffloaded::No,
    4713            1 :                 ));
    4714            2 :             }
    4715            3 :         });
    4716          118 :         timelines_offloaded
    4717          118 :             .iter()
    4718          118 :             .for_each(|(timeline_id, timeline_entry)| {
    4719            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4720            0 :                     return;
    4721              :                 };
    4722            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4723            0 :                     return;
    4724              :                 };
    4725            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4726            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4727            0 :             });
    4728              : 
    4729              :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4730          118 :         let horizon = self.get_gc_horizon();
    4731              : 
    4732              :         // Populate each timeline's GcInfo with information about its child branches
    4733          118 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4734            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4735              :         } else {
    4736          118 :             itertools::Either::Right(timelines.values())
    4737              :         };
    4738          121 :         for timeline in timelines_to_write {
    4739            3 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4740            3 :                 .remove(&timeline.timeline_id)
    4741            3 :                 .unwrap_or_default();
    4742              : 
    4743            3 :             branchpoints.sort_by_key(|b| b.0);
    4744              : 
    4745            3 :             let mut target = timeline.gc_info.write().unwrap();
    4746              : 
    4747            3 :             target.retain_lsns = branchpoints;
    4748              : 
    4749            3 :             let space_cutoff = timeline
    4750            3 :                 .get_last_record_lsn()
    4751            3 :                 .checked_sub(horizon)
    4752            3 :                 .unwrap_or(Lsn(0));
    4753              : 
    4754            3 :             target.cutoffs = GcCutoffs {
    4755            3 :                 space: space_cutoff,
    4756            3 :                 time: None,
    4757            3 :             };
    4758              :         }
    4759          118 :     }
    4760              : 
    4761          379 :     async fn refresh_gc_info_internal(
    4762          379 :         &self,
    4763          379 :         target_timeline_id: Option<TimelineId>,
    4764          379 :         horizon: u64,
    4765          379 :         pitr: Duration,
    4766          379 :         cancel: &CancellationToken,
    4767          379 :         ctx: &RequestContext,
    4768          379 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4769              :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4770              :         // currently visible timelines.
    4771          379 :         let timelines = self
    4772          379 :             .timelines
    4773          379 :             .lock()
    4774          379 :             .unwrap()
    4775          379 :             .values()
    4776         1663 :             .filter(|tl| match target_timeline_id.as_ref() {
    4777         1655 :                 Some(target) => &tl.timeline_id == target,
    4778            8 :                 None => true,
    4779         1663 :             })
    4780          379 :             .cloned()
    4781          379 :             .collect::<Vec<_>>();
    4782              : 
    4783          379 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4784              :             // We were to act on a particular timeline and it wasn't found
    4785            0 :             return Err(GcError::TimelineNotFound);
    4786          379 :         }
    4787              : 
    4788          379 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4789          379 :             HashMap::with_capacity(timelines.len());
    4790              : 
    4791              :         // Ensures all timelines use the same start time when computing the time cutoff.
    4792          379 :         let now_ts_for_pitr_calc = SystemTime::now();
    4793          385 :         for timeline in timelines.iter() {
    4794          385 :             let ctx = &ctx.with_scope_timeline(timeline);
    4795          385 :             let cutoff = timeline
    4796          385 :                 .get_last_record_lsn()
    4797          385 :                 .checked_sub(horizon)
    4798          385 :                 .unwrap_or(Lsn(0));
    4799              : 
    4800          385 :             let cutoffs = timeline
    4801          385 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4802          385 :                 .await?;
    4803          385 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4804          385 :             assert!(old.is_none());
    4805              :         }
    4806              : 
    4807          379 :         if !self.is_active() || self.cancel.is_cancelled() {
    4808            0 :             return Err(GcError::TenantCancelled);
    4809          379 :         }
    4810              : 
    4811              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4812              :         // because that will stall branch creation.
    4813          379 :         let gc_cs = self.gc_cs.lock().await;
    4814              : 
    4815              :         // Ok, we now know all the branch points.
    4816              :         // Update the GC information for each timeline.
    4817          379 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4818          764 :         for timeline in timelines {
    4819              :             // We filtered the timeline list above
    4820          385 :             if let Some(target_timeline_id) = target_timeline_id {
    4821          377 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4822            8 :             }
    4823              : 
    4824              :             {
    4825          385 :                 let mut target = timeline.gc_info.write().unwrap();
    4826              : 
    4827              :                 // Cull any expired leases
    4828          385 :                 let now = SystemTime::now();
    4829          385 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4830              : 
    4831          385 :                 timeline
    4832          385 :                     .metrics
    4833          385 :                     .valid_lsn_lease_count_gauge
    4834          385 :                     .set(target.leases.len() as u64);
    4835              : 
    4836              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4837          385 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4838           56 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4839            6 :                         target.within_ancestor_pitr =
    4840            6 :                             Some(timeline.get_ancestor_lsn()) >= ancestor_gc_cutoffs.time;
    4841           50 :                     }
    4842          329 :                 }
    4843              : 
    4844              :                 // Update metrics that depend on GC state
    4845          385 :                 timeline
    4846          385 :                     .metrics
    4847          385 :                     .archival_size
    4848          385 :                     .set(if target.within_ancestor_pitr {
    4849            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4850              :                     } else {
    4851          385 :                         0
    4852              :                     });
    4853          385 :                 if let Some(time_cutoff) = target.cutoffs.time {
    4854          319 :                     timeline.metrics.pitr_history_size.set(
    4855          319 :                         timeline
    4856          319 :                             .get_last_record_lsn()
    4857          319 :                             .checked_sub(time_cutoff)
    4858          319 :                             .unwrap_or_default()
    4859          319 :                             .0,
    4860          319 :                     );
    4861          319 :                 }
    4862              : 
    4863              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4864              :                 // - this timeline was created while we were finding cutoffs
    4865              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4866          385 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4867          385 :                     let original_cutoffs = target.cutoffs.clone();
    4868              :                     // GC cutoffs should never go back
    4869          385 :                     target.cutoffs = GcCutoffs {
    4870          385 :                         space: cutoffs.space.max(original_cutoffs.space),
    4871          385 :                         time: cutoffs.time.max(original_cutoffs.time),
    4872          385 :                     }
    4873            0 :                 }
    4874              :             }
    4875              : 
    4876          385 :             gc_timelines.push(timeline);
    4877              :         }
    4878          379 :         drop(gc_cs);
    4879          379 :         Ok(gc_timelines)
    4880          379 :     }
    4881              : 
    4882              :     /// A substitute for `branch_timeline` for use in unit tests.
    4883              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4884              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4885              :     /// timeline background tasks are launched, except the flush loop.
    4886              :     #[cfg(test)]
    4887          119 :     async fn branch_timeline_test(
    4888          119 :         self: &Arc<Self>,
    4889          119 :         src_timeline: &Arc<Timeline>,
    4890          119 :         dst_id: TimelineId,
    4891          119 :         ancestor_lsn: Option<Lsn>,
    4892          119 :         ctx: &RequestContext,
    4893          119 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4894          119 :         let tl = self
    4895          119 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4896          119 :             .await?
    4897          117 :             .into_timeline_for_test();
    4898          117 :         tl.set_state(TimelineState::Active);
    4899          117 :         Ok(tl)
    4900          119 :     }
    4901              : 
    4902              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4903              :     #[cfg(test)]
    4904              :     #[allow(clippy::too_many_arguments)]
    4905            6 :     pub async fn branch_timeline_test_with_layers(
    4906            6 :         self: &Arc<Self>,
    4907            6 :         src_timeline: &Arc<Timeline>,
    4908            6 :         dst_id: TimelineId,
    4909            6 :         ancestor_lsn: Option<Lsn>,
    4910            6 :         ctx: &RequestContext,
    4911            6 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4912            6 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4913            6 :         end_lsn: Lsn,
    4914            6 :     ) -> anyhow::Result<Arc<Timeline>> {
    4915              :         use checks::check_valid_layermap;
    4916              :         use itertools::Itertools;
    4917              : 
    4918            6 :         let tline = self
    4919            6 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4920            6 :             .await?;
    4921            6 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4922            6 :             ancestor_lsn
    4923              :         } else {
    4924            0 :             tline.get_last_record_lsn()
    4925              :         };
    4926            6 :         assert!(end_lsn >= ancestor_lsn);
    4927            6 :         tline.force_advance_lsn(end_lsn);
    4928            9 :         for deltas in delta_layer_desc {
    4929            3 :             tline
    4930            3 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4931            3 :                 .await?;
    4932              :         }
    4933            8 :         for (lsn, images) in image_layer_desc {
    4934            2 :             tline
    4935            2 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4936            2 :                 .await?;
    4937              :         }
    4938            6 :         let layer_names = tline
    4939            6 :             .layers
    4940            6 :             .read(LayerManagerLockHolder::Testing)
    4941            6 :             .await
    4942            6 :             .layer_map()
    4943            6 :             .unwrap()
    4944            6 :             .iter_historic_layers()
    4945            6 :             .map(|layer| layer.layer_name())
    4946            6 :             .collect_vec();
    4947            6 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4948            0 :             bail!("invalid layermap: {err}");
    4949            6 :         }
    4950            6 :         Ok(tline)
    4951            6 :     }
    4952              : 
    4953              :     /// Branch an existing timeline.
    4954            0 :     async fn branch_timeline(
    4955            0 :         self: &Arc<Self>,
    4956            0 :         src_timeline: &Arc<Timeline>,
    4957            0 :         dst_id: TimelineId,
    4958            0 :         start_lsn: Option<Lsn>,
    4959            0 :         ctx: &RequestContext,
    4960            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4961            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4962            0 :             .await
    4963            0 :     }
    4964              : 
    4965          119 :     async fn branch_timeline_impl(
    4966          119 :         self: &Arc<Self>,
    4967          119 :         src_timeline: &Arc<Timeline>,
    4968          119 :         dst_id: TimelineId,
    4969          119 :         start_lsn: Option<Lsn>,
    4970          119 :         ctx: &RequestContext,
    4971          119 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4972          119 :         let src_id = src_timeline.timeline_id;
    4973              : 
    4974              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4975              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4976              :         // valid while we are creating the branch.
    4977          119 :         let _gc_cs = self.gc_cs.lock().await;
    4978              : 
    4979              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4980          119 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4981            1 :             let lsn = src_timeline.get_last_record_lsn();
    4982            1 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4983            1 :             lsn
    4984            1 :         });
    4985              : 
    4986              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4987          119 :         let timeline_create_guard = match self
    4988          119 :             .start_creating_timeline(
    4989          119 :                 dst_id,
    4990          119 :                 CreateTimelineIdempotency::Branch {
    4991          119 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4992          119 :                     ancestor_start_lsn: start_lsn,
    4993          119 :                 },
    4994          119 :             )
    4995          119 :             .await?
    4996              :         {
    4997          119 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4998            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    4999            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5000              :             }
    5001              :         };
    5002              : 
    5003              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    5004              :         // horizon on the source timeline
    5005              :         //
    5006              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    5007              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    5008              :         // planned GC cutoff in 'gc_info' is normally larger than
    5009              :         // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
    5010              :         // changed the GC settings for the tenant to make the PITR window
    5011              :         // larger, but some of the data was already removed by an earlier GC
    5012              :         // iteration.
    5013              : 
    5014              :         // check against last actual 'latest_gc_cutoff' first
    5015          119 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    5016              :         {
    5017          119 :             let gc_info = src_timeline.gc_info.read().unwrap();
    5018          119 :             let planned_cutoff = gc_info.min_cutoff();
    5019          119 :             if gc_info.lsn_covered_by_lease(start_lsn) {
    5020            0 :                 tracing::info!(
    5021            0 :                     "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
    5022            0 :                     *applied_gc_cutoff_lsn
    5023              :                 );
    5024              :             } else {
    5025          119 :                 src_timeline
    5026          119 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    5027          119 :                     .context(format!(
    5028          119 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    5029          119 :                         *applied_gc_cutoff_lsn,
    5030              :                     ))
    5031          119 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    5032              : 
    5033              :                 // and then the planned GC cutoff
    5034          117 :                 if start_lsn < planned_cutoff {
    5035            0 :                     return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    5036            0 :                         "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
    5037            0 :                     )));
    5038          117 :                 }
    5039              :             }
    5040              :         }
    5041              : 
    5042              :         //
    5043              :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    5044              :         // so that GC cannot advance the GC cutoff until we are finished.
    5045              :         // Proceed with the branch creation.
    5046              :         //
    5047              : 
    5048              :         // Determine prev-LSN for the new timeline. We can only determine it if
    5049              :         // the timeline was branched at the current end of the source timeline.
    5050              :         let RecordLsn {
    5051          117 :             last: src_last,
    5052          117 :             prev: src_prev,
    5053          117 :         } = src_timeline.get_last_record_rlsn();
    5054          117 :         let dst_prev = if src_last == start_lsn {
    5055          108 :             Some(src_prev)
    5056              :         } else {
    5057            9 :             None
    5058              :         };
    5059              : 
    5060              :         // Create the metadata file, noting the ancestor of the new timeline.
    5061              :         // There is initially no data in it, but all the read-calls know to look
    5062              :         // into the ancestor.
    5063          117 :         let metadata = TimelineMetadata::new(
    5064          117 :             start_lsn,
    5065          117 :             dst_prev,
    5066          117 :             Some(src_id),
    5067          117 :             start_lsn,
    5068          117 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    5069          117 :             src_timeline.initdb_lsn,
    5070          117 :             src_timeline.pg_version,
    5071              :         );
    5072              : 
    5073          117 :         let (uninitialized_timeline, _timeline_ctx) = self
    5074          117 :             .prepare_new_timeline(
    5075          117 :                 dst_id,
    5076          117 :                 &metadata,
    5077          117 :                 timeline_create_guard,
    5078          117 :                 start_lsn + 1,
    5079          117 :                 Some(Arc::clone(src_timeline)),
    5080          117 :                 Some(src_timeline.get_rel_size_v2_status()),
    5081          117 :                 ctx,
    5082          117 :             )
    5083          117 :             .await?;
    5084              : 
    5085          117 :         let new_timeline = uninitialized_timeline.finish_creation().await?;
    5086              : 
    5087              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    5088              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    5089              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    5090              :         // could get incorrect information and remove more layers, than needed.
    5091              :         // See also https://github.com/neondatabase/neon/issues/3865
    5092          117 :         new_timeline
    5093          117 :             .remote_client
    5094          117 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    5095          117 :             .context("branch initial metadata upload")?;
    5096              : 
    5097              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5098              : 
    5099          117 :         Ok(CreateTimelineResult::Created(new_timeline))
    5100          119 :     }
    5101              : 
    5102              :     /// For unit tests, make this visible so that other modules can directly create timelines
    5103              :     #[cfg(test)]
    5104              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    5105              :     pub(crate) async fn bootstrap_timeline_test(
    5106              :         self: &Arc<Self>,
    5107              :         timeline_id: TimelineId,
    5108              :         pg_version: PgMajorVersion,
    5109              :         load_existing_initdb: Option<TimelineId>,
    5110              :         ctx: &RequestContext,
    5111              :     ) -> anyhow::Result<Arc<Timeline>> {
    5112              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    5113              :             .await
    5114              :             .map_err(anyhow::Error::new)
    5115            1 :             .map(|r| r.into_timeline_for_test())
    5116              :     }
    5117              : 
    5118              :     /// Get exclusive access to the timeline ID for creation.
    5119              :     ///
    5120              :     /// Timeline-creating code paths must use this function before making changes
    5121              :     /// to in-memory or persistent state.
    5122              :     ///
    5123              :     /// The `state` parameter is a description of the timeline creation operation
    5124              :     /// we intend to perform.
    5125              :     /// If the timeline was already created in the meantime, we check whether this
    5126              :     /// request conflicts or is idempotent , based on `state`.
    5127          234 :     async fn start_creating_timeline(
    5128          234 :         self: &Arc<Self>,
    5129          234 :         new_timeline_id: TimelineId,
    5130          234 :         idempotency: CreateTimelineIdempotency,
    5131          234 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    5132          234 :         let allow_offloaded = false;
    5133          234 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    5134          233 :             Ok(create_guard) => {
    5135          233 :                 pausable_failpoint!("timeline-creation-after-uninit");
    5136          233 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    5137              :             }
    5138            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    5139              :             Err(TimelineExclusionError::AlreadyCreating) => {
    5140              :                 // Creation is in progress, we cannot create it again, and we cannot
    5141              :                 // check if this request matches the existing one, so caller must try
    5142              :                 // again later.
    5143            0 :                 Err(CreateTimelineError::AlreadyCreating)
    5144              :             }
    5145            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    5146              :             Err(TimelineExclusionError::AlreadyExists {
    5147            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    5148              :                 ..
    5149              :             }) => {
    5150            0 :                 info!("timeline already exists but is offloaded");
    5151            0 :                 Err(CreateTimelineError::Conflict)
    5152              :             }
    5153              :             Err(TimelineExclusionError::AlreadyExists {
    5154            0 :                 existing: TimelineOrOffloaded::Importing(_existing),
    5155              :                 ..
    5156              :             }) => {
    5157              :                 // If there's a timeline already importing, then we would hit
    5158              :                 // the [`TimelineExclusionError::AlreadyCreating`] branch above.
    5159            0 :                 unreachable!("Importing timelines hold the creation guard")
    5160              :             }
    5161              :             Err(TimelineExclusionError::AlreadyExists {
    5162            1 :                 existing: TimelineOrOffloaded::Timeline(existing),
    5163            1 :                 arg,
    5164              :             }) => {
    5165              :                 {
    5166            1 :                     let existing = &existing.create_idempotency;
    5167            1 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    5168            1 :                     debug!("timeline already exists");
    5169              : 
    5170            1 :                     match (existing, &arg) {
    5171              :                         // FailWithConflict => no idempotency check
    5172              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    5173              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    5174            1 :                             warn!("timeline already exists, failing request");
    5175            1 :                             return Err(CreateTimelineError::Conflict);
    5176              :                         }
    5177              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    5178            0 :                         (x, y) if x == y => {
    5179            0 :                             info!(
    5180            0 :                                 "timeline already exists and idempotency matches, succeeding request"
    5181              :                             );
    5182              :                             // fallthrough
    5183              :                         }
    5184              :                         (_, _) => {
    5185            0 :                             warn!("idempotency conflict, failing request");
    5186            0 :                             return Err(CreateTimelineError::Conflict);
    5187              :                         }
    5188              :                     }
    5189              :                 }
    5190              : 
    5191            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    5192              :             }
    5193              :         }
    5194          234 :     }
    5195              : 
    5196            0 :     async fn upload_initdb(
    5197            0 :         &self,
    5198            0 :         timelines_path: &Utf8PathBuf,
    5199            0 :         pgdata_path: &Utf8PathBuf,
    5200            0 :         timeline_id: &TimelineId,
    5201            0 :     ) -> anyhow::Result<()> {
    5202            0 :         let temp_path = timelines_path.join(format!(
    5203            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    5204            0 :         ));
    5205              : 
    5206            0 :         scopeguard::defer! {
    5207              :             if let Err(e) = fs::remove_file(&temp_path) {
    5208              :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    5209              :             }
    5210              :         }
    5211              : 
    5212            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    5213              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    5214            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    5215            0 :             warn!(
    5216            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    5217              :             );
    5218            0 :         }
    5219              : 
    5220            0 :         pausable_failpoint!("before-initdb-upload");
    5221              : 
    5222            0 :         backoff::retry(
    5223            0 :             || async {
    5224            0 :                 self::remote_timeline_client::upload_initdb_dir(
    5225            0 :                     &self.remote_storage,
    5226            0 :                     &self.tenant_shard_id.tenant_id,
    5227            0 :                     timeline_id,
    5228            0 :                     pgdata_zstd.try_clone().await?,
    5229            0 :                     tar_zst_size,
    5230            0 :                     &self.cancel,
    5231              :                 )
    5232            0 :                 .await
    5233            0 :             },
    5234              :             |_| false,
    5235              :             3,
    5236              :             u32::MAX,
    5237            0 :             "persist_initdb_tar_zst",
    5238            0 :             &self.cancel,
    5239              :         )
    5240            0 :         .await
    5241            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    5242            0 :         .and_then(|x| x)
    5243            0 :     }
    5244              : 
    5245              :     /// - run initdb to init temporary instance and get bootstrap data
    5246              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    5247            1 :     async fn bootstrap_timeline(
    5248            1 :         self: &Arc<Self>,
    5249            1 :         timeline_id: TimelineId,
    5250            1 :         pg_version: PgMajorVersion,
    5251            1 :         load_existing_initdb: Option<TimelineId>,
    5252            1 :         ctx: &RequestContext,
    5253            1 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5254            1 :         let timeline_create_guard = match self
    5255            1 :             .start_creating_timeline(
    5256            1 :                 timeline_id,
    5257            1 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5258            1 :             )
    5259            1 :             .await?
    5260              :         {
    5261            1 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5262            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5263            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5264              :             }
    5265              :         };
    5266              : 
    5267              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    5268              :         // temporary directory for basebackup files for the given timeline.
    5269              : 
    5270            1 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5271            1 :         let pgdata_path = path_with_suffix_extension(
    5272            1 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5273            1 :             TEMP_FILE_SUFFIX,
    5274              :         );
    5275              : 
    5276              :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5277              :         // we won't race with other creations or existent timelines with the same path.
    5278            1 :         if pgdata_path.exists() {
    5279            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    5280            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    5281            0 :             })?;
    5282            0 :             tracing::info!("removed previous attempt's temporary initdb directory '{pgdata_path}'");
    5283            1 :         }
    5284              : 
    5285              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5286            1 :         let pgdata_path_deferred = pgdata_path.clone();
    5287            1 :         scopeguard::defer! {
    5288              :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred).or_else(fs_ext::ignore_not_found) {
    5289              :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5290              :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5291              :             } else {
    5292              :                 tracing::info!("removed temporary initdb directory '{pgdata_path_deferred}'");
    5293              :             }
    5294              :         }
    5295            1 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5296            1 :             if existing_initdb_timeline_id != timeline_id {
    5297            0 :                 let source_path = &remote_initdb_archive_path(
    5298            0 :                     &self.tenant_shard_id.tenant_id,
    5299            0 :                     &existing_initdb_timeline_id,
    5300            0 :                 );
    5301            0 :                 let dest_path =
    5302            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    5303              : 
    5304              :                 // if this fails, it will get retried by retried control plane requests
    5305            0 :                 self.remote_storage
    5306            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    5307            0 :                     .await
    5308            0 :                     .context("copy initdb tar")?;
    5309            1 :             }
    5310            1 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5311            1 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5312            1 :                     self.conf,
    5313            1 :                     &self.remote_storage,
    5314            1 :                     &self.tenant_shard_id,
    5315            1 :                     &existing_initdb_timeline_id,
    5316            1 :                     &self.cancel,
    5317            1 :                 )
    5318            1 :                 .await
    5319            1 :                 .context("download initdb tar")?;
    5320              : 
    5321            1 :             scopeguard::defer! {
    5322              :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5323              :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5324              :                 }
    5325              :             }
    5326              : 
    5327            1 :             let buf_read =
    5328            1 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5329            1 :             extract_zst_tarball(&pgdata_path, buf_read)
    5330            1 :                 .await
    5331            1 :                 .context("extract initdb tar")?;
    5332              :         } else {
    5333              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    5334            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    5335            0 :                 .await
    5336            0 :                 .context("run initdb")?;
    5337              : 
    5338              :             // Upload the created data dir to S3
    5339            0 :             if self.tenant_shard_id().is_shard_zero() {
    5340            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5341            0 :                     .await?;
    5342            0 :             }
    5343              :         }
    5344            1 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5345              : 
    5346              :         // Import the contents of the data directory at the initial checkpoint
    5347              :         // LSN, and any WAL after that.
    5348              :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5349              :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5350            1 :         let new_metadata = TimelineMetadata::new(
    5351            1 :             Lsn(0),
    5352            1 :             None,
    5353            1 :             None,
    5354            1 :             Lsn(0),
    5355            1 :             pgdata_lsn,
    5356            1 :             pgdata_lsn,
    5357            1 :             pg_version,
    5358              :         );
    5359            1 :         let (mut raw_timeline, timeline_ctx) = self
    5360            1 :             .prepare_new_timeline(
    5361            1 :                 timeline_id,
    5362            1 :                 &new_metadata,
    5363            1 :                 timeline_create_guard,
    5364            1 :                 pgdata_lsn,
    5365            1 :                 None,
    5366            1 :                 None,
    5367            1 :                 ctx,
    5368            1 :             )
    5369            1 :             .await?;
    5370              : 
    5371            1 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5372            1 :         raw_timeline
    5373            1 :             .write(|unfinished_timeline| async move {
    5374            1 :                 import_datadir::import_timeline_from_postgres_datadir(
    5375            1 :                     &unfinished_timeline,
    5376            1 :                     &pgdata_path,
    5377            1 :                     pgdata_lsn,
    5378            1 :                     &timeline_ctx,
    5379            1 :                 )
    5380            1 :                 .await
    5381            1 :                 .with_context(|| {
    5382            0 :                     format!(
    5383            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5384              :                     )
    5385            0 :                 })?;
    5386              : 
    5387            1 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5388            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5389            0 :                         "failpoint before-checkpoint-new-timeline"
    5390            0 :                     )))
    5391            0 :                 });
    5392              : 
    5393            1 :                 Ok(())
    5394            2 :             })
    5395            1 :             .await?;
    5396              : 
    5397              :         // All done!
    5398            1 :         let timeline = raw_timeline.finish_creation().await?;
    5399              : 
    5400              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5401              : 
    5402            1 :         Ok(CreateTimelineResult::Created(timeline))
    5403            1 :     }
    5404              : 
    5405          231 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5406          231 :         RemoteTimelineClient::new(
    5407          231 :             self.remote_storage.clone(),
    5408          231 :             self.deletion_queue_client.clone(),
    5409          231 :             self.conf,
    5410          231 :             self.tenant_shard_id,
    5411          231 :             timeline_id,
    5412          231 :             self.generation,
    5413          231 :             &self.tenant_conf.load().location,
    5414              :         )
    5415          231 :     }
    5416              : 
    5417              :     /// Builds required resources for a new timeline.
    5418          231 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5419          231 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5420          231 :         self.get_timeline_resources_for(remote_client)
    5421          231 :     }
    5422              : 
    5423              :     /// Builds timeline resources for the given remote client.
    5424          234 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5425          234 :         TimelineResources {
    5426          234 :             remote_client,
    5427          234 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5428          234 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5429          234 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5430          234 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5431          234 :             basebackup_cache: self.basebackup_cache.clone(),
    5432          234 :             feature_resolver: self.feature_resolver.clone(),
    5433          234 :         }
    5434          234 :     }
    5435              : 
    5436              :     /// Creates intermediate timeline structure and its files.
    5437              :     ///
    5438              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5439              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5440              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5441              :     #[allow(clippy::too_many_arguments)]
    5442          231 :     async fn prepare_new_timeline<'a>(
    5443          231 :         &'a self,
    5444          231 :         new_timeline_id: TimelineId,
    5445          231 :         new_metadata: &TimelineMetadata,
    5446          231 :         create_guard: TimelineCreateGuard,
    5447          231 :         start_lsn: Lsn,
    5448          231 :         ancestor: Option<Arc<Timeline>>,
    5449          231 :         rel_size_v2_status: Option<RelSizeMigration>,
    5450          231 :         ctx: &RequestContext,
    5451          231 :     ) -> anyhow::Result<(UninitializedTimeline<'a>, RequestContext)> {
    5452          231 :         let tenant_shard_id = self.tenant_shard_id;
    5453              : 
    5454          231 :         let resources = self.build_timeline_resources(new_timeline_id);
    5455          231 :         resources
    5456          231 :             .remote_client
    5457          231 :             .init_upload_queue_for_empty_remote(new_metadata, rel_size_v2_status.clone())?;
    5458              : 
    5459          231 :         let (timeline_struct, timeline_ctx) = self
    5460          231 :             .create_timeline_struct(
    5461          231 :                 new_timeline_id,
    5462          231 :                 new_metadata,
    5463          231 :                 None,
    5464          231 :                 ancestor,
    5465          231 :                 resources,
    5466          231 :                 CreateTimelineCause::Load,
    5467          231 :                 create_guard.idempotency.clone(),
    5468          231 :                 None,
    5469          231 :                 rel_size_v2_status,
    5470          231 :                 ctx,
    5471              :             )
    5472          231 :             .context("Failed to create timeline data structure")?;
    5473              : 
    5474          231 :         timeline_struct.init_empty_layer_map(start_lsn);
    5475              : 
    5476          231 :         if let Err(e) = self
    5477          231 :             .create_timeline_files(&create_guard.timeline_path)
    5478          231 :             .await
    5479              :         {
    5480            0 :             error!(
    5481            0 :                 "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
    5482              :             );
    5483            0 :             cleanup_timeline_directory(create_guard);
    5484            0 :             return Err(e);
    5485          231 :         }
    5486              : 
    5487          231 :         debug!(
    5488            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5489              :         );
    5490              : 
    5491          231 :         Ok((
    5492          231 :             UninitializedTimeline::new(
    5493          231 :                 self,
    5494          231 :                 new_timeline_id,
    5495          231 :                 Some((timeline_struct, create_guard)),
    5496          231 :             ),
    5497          231 :             timeline_ctx,
    5498          231 :         ))
    5499          231 :     }
    5500              : 
    5501          231 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5502          231 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5503              : 
    5504          231 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5505            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5506            0 :         });
    5507              : 
    5508          231 :         Ok(())
    5509          231 :     }
    5510              : 
    5511              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5512              :     /// concurrent attempts to create the same timeline.
    5513              :     ///
    5514              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5515              :     /// offloaded timelines or not.
    5516          234 :     fn create_timeline_create_guard(
    5517          234 :         self: &Arc<Self>,
    5518          234 :         timeline_id: TimelineId,
    5519          234 :         idempotency: CreateTimelineIdempotency,
    5520          234 :         allow_offloaded: bool,
    5521          234 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5522          234 :         let tenant_shard_id = self.tenant_shard_id;
    5523              : 
    5524          234 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5525              : 
    5526          234 :         let create_guard = TimelineCreateGuard::new(
    5527          234 :             self,
    5528          234 :             timeline_id,
    5529          234 :             timeline_path.clone(),
    5530          234 :             idempotency,
    5531          234 :             allow_offloaded,
    5532            1 :         )?;
    5533              : 
    5534              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5535              :         // for creation.
    5536              :         // A timeline directory should never exist on disk already:
    5537              :         // - a previous failed creation would have cleaned up after itself
    5538              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5539              :         //
    5540              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5541              :         // this error may indicate a bug in cleanup on failed creations.
    5542          233 :         if timeline_path.exists() {
    5543            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5544            0 :                 "Timeline directory already exists! This is a bug."
    5545            0 :             )));
    5546          233 :         }
    5547              : 
    5548          233 :         Ok(create_guard)
    5549          234 :     }
    5550              : 
    5551              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5552              :     ///
    5553              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5554              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5555              :     pub async fn gather_size_inputs(
    5556              :         &self,
    5557              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5558              :         // (only if it is shorter than the real cutoff).
    5559              :         max_retention_period: Option<u64>,
    5560              :         cause: LogicalSizeCalculationCause,
    5561              :         cancel: &CancellationToken,
    5562              :         ctx: &RequestContext,
    5563              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5564              :         let logical_sizes_at_once = self
    5565              :             .conf
    5566              :             .concurrent_tenant_size_logical_size_queries
    5567              :             .inner();
    5568              : 
    5569              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5570              :         //
    5571              :         // But the only case where we need to run multiple of these at once is when we
    5572              :         // request a size for a tenant manually via API, while another background calculation
    5573              :         // is in progress (which is not a common case).
    5574              :         //
    5575              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5576              :         let mut shared_cache = tokio::select! {
    5577              :             locked = self.cached_logical_sizes.lock() => locked,
    5578              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5579              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5580              :         };
    5581              : 
    5582              :         size::gather_inputs(
    5583              :             self,
    5584              :             logical_sizes_at_once,
    5585              :             max_retention_period,
    5586              :             &mut shared_cache,
    5587              :             cause,
    5588              :             cancel,
    5589              :             ctx,
    5590              :         )
    5591              :         .await
    5592              :     }
    5593              : 
    5594              :     /// Calculate synthetic tenant size and cache the result.
    5595              :     /// This is periodically called by background worker.
    5596              :     /// result is cached in tenant struct
    5597              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5598              :     pub async fn calculate_synthetic_size(
    5599              :         &self,
    5600              :         cause: LogicalSizeCalculationCause,
    5601              :         cancel: &CancellationToken,
    5602              :         ctx: &RequestContext,
    5603              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5604              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5605              : 
    5606              :         let size = inputs.calculate();
    5607              : 
    5608              :         self.set_cached_synthetic_size(size);
    5609              : 
    5610              :         Ok(size)
    5611              :     }
    5612              : 
    5613              :     /// Cache given synthetic size and update the metric value
    5614            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5615            0 :         self.cached_synthetic_tenant_size
    5616            0 :             .store(size, Ordering::Relaxed);
    5617              : 
    5618              :         // Only shard zero should be calculating synthetic sizes
    5619            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5620              : 
    5621            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5622            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5623            0 :             .unwrap()
    5624            0 :             .set(size);
    5625            0 :     }
    5626              : 
    5627            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5628            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5629            0 :     }
    5630              : 
    5631              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5632              :     ///
    5633              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5634              :     /// from an external API handler.
    5635              :     ///
    5636              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5637              :     /// still bounded by tenant/timeline shutdown.
    5638              :     #[tracing::instrument(skip_all)]
    5639              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5640              :         let timelines = self.timelines.lock().unwrap().clone();
    5641              : 
    5642            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5643            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5644            0 :             timeline.freeze_and_flush().await?;
    5645            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5646            0 :             timeline.remote_client.wait_completion().await?;
    5647              : 
    5648            0 :             Ok(())
    5649            0 :         }
    5650              : 
    5651              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5652              :         // aborted when this function's future is cancelled: they should stay alive
    5653              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5654              :         // before Timeline shutdown completes.
    5655              :         let mut results = FuturesUnordered::new();
    5656              : 
    5657              :         for (_timeline_id, timeline) in timelines {
    5658              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5659              :             // means that if this function's future is cancelled, the Timeline shutdown
    5660              :             // will still wait for any I/O in here to complete.
    5661              :             let Ok(gate) = timeline.gate.enter() else {
    5662              :                 continue;
    5663              :             };
    5664            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5665              :             results.push(jh);
    5666              :         }
    5667              : 
    5668              :         while let Some(r) = results.next().await {
    5669              :             if let Err(e) = r {
    5670              :                 if !e.is_cancelled() && !e.is_panic() {
    5671              :                     tracing::error!("unexpected join error: {e:?}");
    5672              :                 }
    5673              :             }
    5674              :         }
    5675              : 
    5676              :         // The flushes we did above were just writes, but the TenantShard might have had
    5677              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5678              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5679              :         // because it's typically a no-op.
    5680              :         match self.deletion_queue_client.flush_execute().await {
    5681              :             Ok(_) => {}
    5682              :             Err(DeletionQueueError::ShuttingDown) => {}
    5683              :         }
    5684              : 
    5685              :         Ok(())
    5686              :     }
    5687              : 
    5688            0 :     pub(crate) fn get_tenant_conf(&self) -> pageserver_api::models::TenantConfig {
    5689            0 :         self.tenant_conf.load().tenant_conf.clone()
    5690            0 :     }
    5691              : 
    5692              :     /// How much local storage would this tenant like to have?  It can cope with
    5693              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5694              :     /// the TenantShard to advertise how much storage it would prefer to have to provide fast I/O
    5695              :     /// by keeping important things on local disk.
    5696              :     ///
    5697              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5698              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5699              :     /// actually use more than they report here.
    5700            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5701            0 :         let timelines = self.timelines.lock().unwrap();
    5702              : 
    5703              :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5704              :         // reflects the observation that on tenants with multiple large branches, typically only one
    5705              :         // of them is used actively enough to occupy space on disk.
    5706            0 :         timelines
    5707            0 :             .values()
    5708            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5709            0 :             .max()
    5710            0 :             .unwrap_or(0)
    5711            0 :     }
    5712              : 
    5713              :     /// Builds a new tenant manifest, and uploads it if it differs from the last-known tenant
    5714              :     /// manifest in `Self::remote_tenant_manifest`.
    5715              :     ///
    5716              :     /// TODO: instead of requiring callers to remember to call `maybe_upload_tenant_manifest` after
    5717              :     /// changing any `TenantShard` state that's included in the manifest, consider making the manifest
    5718              :     /// the authoritative source of data with an API that automatically uploads on changes. Revisit
    5719              :     /// this when the manifest is more widely used and we have a better idea of the data model.
    5720          119 :     pub(crate) async fn maybe_upload_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5721              :         // Multiple tasks may call this function concurrently after mutating the TenantShard runtime
    5722              :         // state, affecting the manifest generated by `build_tenant_manifest`. We use an async mutex
    5723              :         // to serialize these callers. `eq_ignoring_version` acts as a slightly inefficient but
    5724              :         // simple coalescing mechanism.
    5725          119 :         let mut guard = tokio::select! {
    5726          119 :             guard = self.remote_tenant_manifest.lock() => guard,
    5727          119 :             _ = self.cancel.cancelled() => return Err(TenantManifestError::Cancelled),
    5728              :         };
    5729              : 
    5730              :         // Build a new manifest.
    5731          119 :         let manifest = self.build_tenant_manifest();
    5732              : 
    5733              :         // Check if the manifest has changed. We ignore the version number here, to avoid
    5734              :         // uploading every manifest on version number bumps.
    5735          119 :         if let Some(old) = guard.as_ref() {
    5736            4 :             if manifest.eq_ignoring_version(old) {
    5737            3 :                 return Ok(());
    5738            1 :             }
    5739          115 :         }
    5740              : 
    5741              :         // Update metrics
    5742          116 :         let tid = self.tenant_shard_id.to_string();
    5743          116 :         let shard_id = self.tenant_shard_id.shard_slug().to_string();
    5744          116 :         let set_key = &[tid.as_str(), shard_id.as_str()][..];
    5745          116 :         TENANT_OFFLOADED_TIMELINES
    5746          116 :             .with_label_values(set_key)
    5747          116 :             .set(manifest.offloaded_timelines.len() as u64);
    5748              : 
    5749              :         // Upload the manifest. Remote storage does no retries internally, so retry here.
    5750          116 :         match backoff::retry(
    5751          116 :             || async {
    5752          116 :                 upload_tenant_manifest(
    5753          116 :                     &self.remote_storage,
    5754          116 :                     &self.tenant_shard_id,
    5755          116 :                     self.generation,
    5756          116 :                     &manifest,
    5757          116 :                     &self.cancel,
    5758          116 :                 )
    5759          116 :                 .await
    5760          232 :             },
    5761            0 :             |_| self.cancel.is_cancelled(),
    5762              :             FAILED_UPLOAD_WARN_THRESHOLD,
    5763              :             FAILED_REMOTE_OP_RETRIES,
    5764          116 :             "uploading tenant manifest",
    5765          116 :             &self.cancel,
    5766              :         )
    5767          116 :         .await
    5768              :         {
    5769            0 :             None => Err(TenantManifestError::Cancelled),
    5770            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5771            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5772              :             Some(Ok(_)) => {
    5773              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5774              :                 // re-uploading the same thing.
    5775          116 :                 *guard = Some(manifest);
    5776              : 
    5777          116 :                 Ok(())
    5778              :             }
    5779              :         }
    5780          119 :     }
    5781              : }
    5782              : 
    5783              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5784              : /// to get bootstrap data for timeline initialization.
    5785            0 : async fn run_initdb(
    5786            0 :     conf: &'static PageServerConf,
    5787            0 :     initdb_target_dir: &Utf8Path,
    5788            0 :     pg_version: PgMajorVersion,
    5789            0 :     cancel: &CancellationToken,
    5790            0 : ) -> Result<(), InitdbError> {
    5791            0 :     let initdb_bin_path = conf
    5792            0 :         .pg_bin_dir(pg_version)
    5793            0 :         .map_err(InitdbError::Other)?
    5794            0 :         .join("initdb");
    5795            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5796            0 :     info!(
    5797            0 :         "running {} in {}, libdir: {}",
    5798              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5799              :     );
    5800              : 
    5801            0 :     let _permit = {
    5802            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5803            0 :         INIT_DB_SEMAPHORE.acquire().await
    5804              :     };
    5805              : 
    5806            0 :     CONCURRENT_INITDBS.inc();
    5807            0 :     scopeguard::defer! {
    5808              :         CONCURRENT_INITDBS.dec();
    5809              :     }
    5810              : 
    5811            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5812            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5813            0 :         superuser: &conf.superuser,
    5814            0 :         locale: &conf.locale,
    5815            0 :         initdb_bin: &initdb_bin_path,
    5816            0 :         pg_version,
    5817            0 :         library_search_path: &initdb_lib_dir,
    5818            0 :         pgdata: initdb_target_dir,
    5819            0 :     })
    5820            0 :     .await
    5821            0 :     .map_err(InitdbError::Inner);
    5822              : 
    5823              :     // This isn't true cancellation support, see above. Still return an error to
    5824              :     // excercise the cancellation code path.
    5825            0 :     if cancel.is_cancelled() {
    5826            0 :         return Err(InitdbError::Cancelled);
    5827            0 :     }
    5828              : 
    5829            0 :     res
    5830            0 : }
    5831              : 
    5832              : /// Dump contents of a layer file to stdout.
    5833            0 : pub async fn dump_layerfile_from_path(
    5834            0 :     path: &Utf8Path,
    5835            0 :     verbose: bool,
    5836            0 :     ctx: &RequestContext,
    5837            0 : ) -> anyhow::Result<()> {
    5838              :     use std::os::unix::fs::FileExt;
    5839              : 
    5840              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5841              :     // file.
    5842            0 :     let file = File::open(path)?;
    5843            0 :     let mut header_buf = [0u8; 2];
    5844            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5845              : 
    5846            0 :     match u16::from_be_bytes(header_buf) {
    5847              :         crate::IMAGE_FILE_MAGIC => {
    5848            0 :             ImageLayer::new_for_path(path, file)?
    5849            0 :                 .dump(verbose, ctx)
    5850            0 :                 .await?
    5851              :         }
    5852              :         crate::DELTA_FILE_MAGIC => {
    5853            0 :             DeltaLayer::new_for_path(path, file)?
    5854            0 :                 .dump(verbose, ctx)
    5855            0 :                 .await?
    5856              :         }
    5857            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5858              :     }
    5859              : 
    5860            0 :     Ok(())
    5861            0 : }
    5862              : 
    5863              : #[cfg(test)]
    5864              : pub(crate) mod harness {
    5865              :     use bytes::{Bytes, BytesMut};
    5866              :     use hex_literal::hex;
    5867              :     use once_cell::sync::OnceCell;
    5868              :     use pageserver_api::key::Key;
    5869              :     use pageserver_api::models::ShardParameters;
    5870              :     use pageserver_api::shard::ShardIndex;
    5871              :     use utils::id::TenantId;
    5872              :     use utils::logging;
    5873              :     use wal_decoder::models::record::NeonWalRecord;
    5874              : 
    5875              :     use super::*;
    5876              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5877              :     use crate::l0_flush::L0FlushConfig;
    5878              :     use crate::walredo::apply_neon;
    5879              : 
    5880              :     pub const TIMELINE_ID: TimelineId =
    5881              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5882              :     pub const NEW_TIMELINE_ID: TimelineId =
    5883              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5884              : 
    5885              :     /// Convenience function to create a page image with given string as the only content
    5886      2514428 :     pub fn test_img(s: &str) -> Bytes {
    5887      2514428 :         let mut buf = BytesMut::new();
    5888      2514428 :         buf.extend_from_slice(s.as_bytes());
    5889      2514428 :         buf.resize(64, 0);
    5890              : 
    5891      2514428 :         buf.freeze()
    5892      2514428 :     }
    5893              : 
    5894              :     pub struct TenantHarness {
    5895              :         pub conf: &'static PageServerConf,
    5896              :         pub tenant_conf: pageserver_api::models::TenantConfig,
    5897              :         pub tenant_shard_id: TenantShardId,
    5898              :         pub shard_identity: ShardIdentity,
    5899              :         pub generation: Generation,
    5900              :         pub shard: ShardIndex,
    5901              :         pub remote_storage: GenericRemoteStorage,
    5902              :         pub remote_fs_dir: Utf8PathBuf,
    5903              :         pub deletion_queue: MockDeletionQueue,
    5904              :     }
    5905              : 
    5906              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5907              : 
    5908          130 :     pub(crate) fn setup_logging() {
    5909          130 :         LOG_HANDLE.get_or_init(|| {
    5910          124 :             logging::init(
    5911          124 :                 logging::LogFormat::Test,
    5912              :                 // enable it in case the tests exercise code paths that use
    5913              :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5914          124 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5915          124 :                 logging::Output::Stdout,
    5916              :             )
    5917          124 :             .expect("Failed to init test logging");
    5918          124 :         });
    5919          130 :     }
    5920              : 
    5921              :     impl TenantHarness {
    5922          118 :         pub async fn create_custom(
    5923          118 :             test_name: &'static str,
    5924          118 :             tenant_conf: pageserver_api::models::TenantConfig,
    5925          118 :             tenant_id: TenantId,
    5926          118 :             shard_identity: ShardIdentity,
    5927          118 :             generation: Generation,
    5928          118 :         ) -> anyhow::Result<Self> {
    5929          118 :             setup_logging();
    5930              : 
    5931          118 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5932          118 :             let _ = fs::remove_dir_all(&repo_dir);
    5933          118 :             fs::create_dir_all(&repo_dir)?;
    5934              : 
    5935          118 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5936              :             // Make a static copy of the config. This can never be free'd, but that's
    5937              :             // OK in a test.
    5938          118 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5939              : 
    5940          118 :             let shard = shard_identity.shard_index();
    5941          118 :             let tenant_shard_id = TenantShardId {
    5942          118 :                 tenant_id,
    5943          118 :                 shard_number: shard.shard_number,
    5944          118 :                 shard_count: shard.shard_count,
    5945          118 :             };
    5946          118 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5947          118 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5948              : 
    5949              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5950          118 :             let remote_fs_dir = conf.workdir.join("localfs");
    5951          118 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5952          118 :             let config = RemoteStorageConfig {
    5953          118 :                 storage: RemoteStorageKind::LocalFs {
    5954          118 :                     local_path: remote_fs_dir.clone(),
    5955          118 :                 },
    5956          118 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5957          118 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5958          118 :             };
    5959          118 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5960          118 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5961              : 
    5962          118 :             Ok(Self {
    5963          118 :                 conf,
    5964          118 :                 tenant_conf,
    5965          118 :                 tenant_shard_id,
    5966          118 :                 shard_identity,
    5967          118 :                 generation,
    5968          118 :                 shard,
    5969          118 :                 remote_storage,
    5970          118 :                 remote_fs_dir,
    5971          118 :                 deletion_queue,
    5972          118 :             })
    5973          118 :         }
    5974              : 
    5975          110 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5976              :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5977              :             // The tests perform them manually if needed.
    5978          110 :             let tenant_conf = pageserver_api::models::TenantConfig {
    5979          110 :                 gc_period: Some(Duration::ZERO),
    5980          110 :                 compaction_period: Some(Duration::ZERO),
    5981          110 :                 ..Default::default()
    5982          110 :             };
    5983          110 :             let tenant_id = TenantId::generate();
    5984          110 :             let shard = ShardIdentity::unsharded();
    5985          110 :             Self::create_custom(
    5986          110 :                 test_name,
    5987          110 :                 tenant_conf,
    5988          110 :                 tenant_id,
    5989          110 :                 shard,
    5990          110 :                 Generation::new(0xdeadbeef),
    5991          110 :             )
    5992          110 :             .await
    5993          110 :         }
    5994              : 
    5995           10 :         pub fn span(&self) -> tracing::Span {
    5996           10 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5997           10 :         }
    5998              : 
    5999          118 :         pub(crate) async fn load(&self) -> (Arc<TenantShard>, RequestContext) {
    6000          118 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error)
    6001          118 :                 .with_scope_unit_test();
    6002              :             (
    6003          118 :                 self.do_try_load(&ctx)
    6004          118 :                     .await
    6005          118 :                     .expect("failed to load test tenant"),
    6006          118 :                 ctx,
    6007              :             )
    6008          118 :         }
    6009              : 
    6010              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    6011              :         pub(crate) async fn do_try_load(
    6012              :             &self,
    6013              :             ctx: &RequestContext,
    6014              :         ) -> anyhow::Result<Arc<TenantShard>> {
    6015              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    6016              : 
    6017              :             let (basebackup_cache, _) = BasebackupCache::new(Utf8PathBuf::new(), None);
    6018              : 
    6019              :             let tenant = Arc::new(TenantShard::new(
    6020              :                 TenantState::Attaching,
    6021              :                 self.conf,
    6022              :                 AttachedTenantConf::try_from(
    6023              :                     self.conf,
    6024              :                     LocationConf::attached_single(
    6025              :                         self.tenant_conf.clone(),
    6026              :                         self.generation,
    6027              :                         ShardParameters::default(),
    6028              :                     ),
    6029              :                 )
    6030              :                 .unwrap(),
    6031              :                 self.shard_identity,
    6032              :                 Some(walredo_mgr),
    6033              :                 self.tenant_shard_id,
    6034              :                 self.remote_storage.clone(),
    6035              :                 self.deletion_queue.new_client(),
    6036              :                 // TODO: ideally we should run all unit tests with both configs
    6037              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    6038              :                 basebackup_cache,
    6039              :                 FeatureResolver::new_disabled(),
    6040              :             ));
    6041              : 
    6042              :             let preload = tenant
    6043              :                 .preload(&self.remote_storage, CancellationToken::new())
    6044              :                 .await?;
    6045              :             tenant.attach(Some(preload), ctx).await?;
    6046              : 
    6047              :             tenant.state.send_replace(TenantState::Active);
    6048              :             for timeline in tenant.timelines.lock().unwrap().values() {
    6049              :                 timeline.set_state(TimelineState::Active);
    6050              :             }
    6051              :             Ok(tenant)
    6052              :         }
    6053              : 
    6054            1 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    6055            1 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    6056            1 :         }
    6057              :     }
    6058              : 
    6059              :     // Mock WAL redo manager that doesn't do much
    6060              :     pub(crate) struct TestRedoManager;
    6061              : 
    6062              :     impl TestRedoManager {
    6063              :         /// # Cancel-Safety
    6064              :         ///
    6065              :         /// This method is cancellation-safe.
    6066        26774 :         pub async fn request_redo(
    6067        26774 :             &self,
    6068        26774 :             key: Key,
    6069        26774 :             lsn: Lsn,
    6070        26774 :             base_img: Option<(Lsn, Bytes)>,
    6071        26774 :             records: Vec<(Lsn, NeonWalRecord)>,
    6072        26774 :             _pg_version: PgMajorVersion,
    6073        26774 :             _redo_attempt_type: RedoAttemptType,
    6074        26774 :         ) -> Result<Bytes, walredo::Error> {
    6075      1403510 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    6076        26774 :             if records_neon {
    6077              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    6078        26774 :                 let mut page = match (base_img, records.first()) {
    6079        13029 :                     (Some((_lsn, img)), _) => {
    6080        13029 :                         let mut page = BytesMut::new();
    6081        13029 :                         page.extend_from_slice(&img);
    6082        13029 :                         page
    6083              :                     }
    6084        13745 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    6085              :                     _ => {
    6086            0 :                         panic!("Neon WAL redo requires base image or will init record");
    6087              :                     }
    6088              :                 };
    6089              : 
    6090      1430283 :                 for (record_lsn, record) in records {
    6091      1403510 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    6092              :                 }
    6093        26773 :                 Ok(page.freeze())
    6094              :             } else {
    6095              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    6096            0 :                 let s = format!(
    6097            0 :                     "redo for {} to get to {}, with {} and {} records",
    6098              :                     key,
    6099              :                     lsn,
    6100            0 :                     if base_img.is_some() {
    6101            0 :                         "base image"
    6102              :                     } else {
    6103            0 :                         "no base image"
    6104              :                     },
    6105            0 :                     records.len()
    6106              :                 );
    6107            0 :                 println!("{s}");
    6108              : 
    6109            0 :                 Ok(test_img(&s))
    6110              :             }
    6111        26774 :         }
    6112              :     }
    6113              : }
    6114              : 
    6115              : #[cfg(test)]
    6116              : mod tests {
    6117              :     use std::collections::{BTreeMap, BTreeSet};
    6118              : 
    6119              :     use bytes::{Bytes, BytesMut};
    6120              :     use hex_literal::hex;
    6121              :     use itertools::Itertools;
    6122              :     #[cfg(feature = "testing")]
    6123              :     use models::CompactLsnRange;
    6124              :     use pageserver_api::key::{
    6125              :         AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX, repl_origin_key,
    6126              :     };
    6127              :     use pageserver_api::keyspace::KeySpace;
    6128              :     #[cfg(feature = "testing")]
    6129              :     use pageserver_api::keyspace::KeySpaceRandomAccum;
    6130              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings, LsnLease};
    6131              :     use pageserver_compaction::helpers::overlaps_with;
    6132              :     #[cfg(feature = "testing")]
    6133              :     use rand::SeedableRng;
    6134              :     #[cfg(feature = "testing")]
    6135              :     use rand::rngs::StdRng;
    6136              :     use rand::{Rng, thread_rng};
    6137              :     #[cfg(feature = "testing")]
    6138              :     use std::ops::Range;
    6139              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    6140              :     use tests::storage_layer::ValuesReconstructState;
    6141              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    6142              :     #[cfg(feature = "testing")]
    6143              :     use timeline::GcInfo;
    6144              :     #[cfg(feature = "testing")]
    6145              :     use timeline::InMemoryLayerTestDesc;
    6146              :     #[cfg(feature = "testing")]
    6147              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    6148              :     use timeline::{CompactOptions, DeltaLayerTestDesc, VersionedKeySpaceQuery};
    6149              :     use utils::id::TenantId;
    6150              :     use utils::shard::{ShardCount, ShardNumber};
    6151              :     #[cfg(feature = "testing")]
    6152              :     use wal_decoder::models::record::NeonWalRecord;
    6153              :     use wal_decoder::models::value::Value;
    6154              : 
    6155              :     use super::*;
    6156              :     use crate::DEFAULT_PG_VERSION;
    6157              :     use crate::keyspace::KeySpaceAccum;
    6158              :     use crate::tenant::harness::*;
    6159              :     use crate::tenant::timeline::CompactFlags;
    6160              : 
    6161              :     static TEST_KEY: Lazy<Key> =
    6162           10 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    6163              : 
    6164              :     #[cfg(feature = "testing")]
    6165              :     struct TestTimelineSpecification {
    6166              :         start_lsn: Lsn,
    6167              :         last_record_lsn: Lsn,
    6168              : 
    6169              :         in_memory_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    6170              :         delta_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    6171              :         image_layers_shape: Vec<(Range<Key>, Lsn)>,
    6172              : 
    6173              :         gap_chance: u8,
    6174              :         will_init_chance: u8,
    6175              :     }
    6176              : 
    6177              :     #[cfg(feature = "testing")]
    6178              :     struct Storage {
    6179              :         storage: HashMap<(Key, Lsn), Value>,
    6180              :         start_lsn: Lsn,
    6181              :     }
    6182              : 
    6183              :     #[cfg(feature = "testing")]
    6184              :     impl Storage {
    6185        32000 :         fn get(&self, key: Key, lsn: Lsn) -> Bytes {
    6186              :             use bytes::BufMut;
    6187              : 
    6188        32000 :             let mut crnt_lsn = lsn;
    6189        32000 :             let mut got_base = false;
    6190              : 
    6191        32000 :             let mut acc = Vec::new();
    6192              : 
    6193      2831871 :             while crnt_lsn >= self.start_lsn {
    6194      2831871 :                 if let Some(value) = self.storage.get(&(key, crnt_lsn)) {
    6195      1421172 :                     acc.push(value.clone());
    6196              : 
    6197      1402881 :                     match value {
    6198      1402881 :                         Value::WalRecord(NeonWalRecord::Test { will_init, .. }) => {
    6199      1402881 :                             if *will_init {
    6200        13709 :                                 got_base = true;
    6201        13709 :                                 break;
    6202      1389172 :                             }
    6203              :                         }
    6204              :                         Value::Image(_) => {
    6205        18291 :                             got_base = true;
    6206        18291 :                             break;
    6207              :                         }
    6208            0 :                         _ => unreachable!(),
    6209              :                     }
    6210      1410699 :                 }
    6211              : 
    6212      2799871 :                 crnt_lsn = crnt_lsn.checked_sub(1u64).unwrap();
    6213              :             }
    6214              : 
    6215        32000 :             assert!(
    6216        32000 :                 got_base,
    6217            0 :                 "Input data was incorrect. No base image for {key}@{lsn}"
    6218              :             );
    6219              : 
    6220        32000 :             tracing::debug!("Wal redo depth for {key}@{lsn} is {}", acc.len());
    6221              : 
    6222        32000 :             let mut blob = BytesMut::new();
    6223      1421172 :             for value in acc.into_iter().rev() {
    6224      1402881 :                 match value {
    6225      1402881 :                     Value::WalRecord(NeonWalRecord::Test { append, .. }) => {
    6226      1402881 :                         blob.extend_from_slice(append.as_bytes());
    6227      1402881 :                     }
    6228        18291 :                     Value::Image(img) => {
    6229        18291 :                         blob.put(img);
    6230        18291 :                     }
    6231            0 :                     _ => unreachable!(),
    6232              :                 }
    6233              :             }
    6234              : 
    6235        32000 :             blob.into()
    6236        32000 :         }
    6237              :     }
    6238              : 
    6239              :     #[cfg(feature = "testing")]
    6240              :     #[allow(clippy::too_many_arguments)]
    6241            1 :     async fn randomize_timeline(
    6242            1 :         tenant: &Arc<TenantShard>,
    6243            1 :         new_timeline_id: TimelineId,
    6244            1 :         pg_version: PgMajorVersion,
    6245            1 :         spec: TestTimelineSpecification,
    6246            1 :         random: &mut rand::rngs::StdRng,
    6247            1 :         ctx: &RequestContext,
    6248            1 :     ) -> anyhow::Result<(Arc<Timeline>, Storage, Vec<Lsn>)> {
    6249            1 :         let mut storage: HashMap<(Key, Lsn), Value> = HashMap::default();
    6250            1 :         let mut interesting_lsns = vec![spec.last_record_lsn];
    6251              : 
    6252            2 :         for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6253            2 :             let mut lsn = lsn_range.start;
    6254          202 :             while lsn < lsn_range.end {
    6255          200 :                 let mut key = key_range.start;
    6256        21018 :                 while key < key_range.end {
    6257        20818 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6258        20818 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6259              : 
    6260        20818 :                     if gap {
    6261         1018 :                         continue;
    6262        19800 :                     }
    6263              : 
    6264        19800 :                     let record = if will_init {
    6265          191 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6266              :                     } else {
    6267        19609 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6268              :                     };
    6269              : 
    6270        19800 :                     storage.insert((key, lsn), record);
    6271              : 
    6272        19800 :                     key = key.next();
    6273              :                 }
    6274          200 :                 lsn = Lsn(lsn.0 + 1);
    6275              :             }
    6276              : 
    6277              :             // Stash some interesting LSN for future use
    6278            6 :             for offset in [0, 5, 100].iter() {
    6279            6 :                 if *offset == 0 {
    6280            2 :                     interesting_lsns.push(lsn_range.start);
    6281            2 :                 } else {
    6282            4 :                     let below = lsn_range.start.checked_sub(*offset);
    6283            4 :                     match below {
    6284            4 :                         Some(v) if v >= spec.start_lsn => {
    6285            4 :                             interesting_lsns.push(v);
    6286            4 :                         }
    6287            0 :                         _ => {}
    6288              :                     }
    6289              : 
    6290            4 :                     let above = Lsn(lsn_range.start.0 + offset);
    6291            4 :                     interesting_lsns.push(above);
    6292              :                 }
    6293              :             }
    6294              :         }
    6295              : 
    6296            3 :         for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6297            3 :             let mut lsn = lsn_range.start;
    6298          315 :             while lsn < lsn_range.end {
    6299          312 :                 let mut key = key_range.start;
    6300        11112 :                 while key < key_range.end {
    6301        10800 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6302        10800 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6303              : 
    6304        10800 :                     if gap {
    6305          504 :                         continue;
    6306        10296 :                     }
    6307              : 
    6308        10296 :                     let record = if will_init {
    6309          103 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6310              :                     } else {
    6311        10193 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6312              :                     };
    6313              : 
    6314        10296 :                     storage.insert((key, lsn), record);
    6315              : 
    6316        10296 :                     key = key.next();
    6317              :                 }
    6318          312 :                 lsn = Lsn(lsn.0 + 1);
    6319              :             }
    6320              : 
    6321              :             // Stash some interesting LSN for future use
    6322            9 :             for offset in [0, 5, 100].iter() {
    6323            9 :                 if *offset == 0 {
    6324            3 :                     interesting_lsns.push(lsn_range.start);
    6325            3 :                 } else {
    6326            6 :                     let below = lsn_range.start.checked_sub(*offset);
    6327            6 :                     match below {
    6328            6 :                         Some(v) if v >= spec.start_lsn => {
    6329            3 :                             interesting_lsns.push(v);
    6330            3 :                         }
    6331            3 :                         _ => {}
    6332              :                     }
    6333              : 
    6334            6 :                     let above = Lsn(lsn_range.start.0 + offset);
    6335            6 :                     interesting_lsns.push(above);
    6336              :                 }
    6337              :             }
    6338              :         }
    6339              : 
    6340            3 :         for (key_range, lsn) in spec.image_layers_shape.iter() {
    6341            3 :             let mut key = key_range.start;
    6342          142 :             while key < key_range.end {
    6343          139 :                 let blob = Bytes::from(format!("[image {key}@{lsn}]"));
    6344          139 :                 let record = Value::Image(blob.clone());
    6345          139 :                 storage.insert((key, *lsn), record);
    6346          139 : 
    6347          139 :                 key = key.next();
    6348          139 :             }
    6349              : 
    6350              :             // Stash some interesting LSN for future use
    6351            9 :             for offset in [0, 5, 100].iter() {
    6352            9 :                 if *offset == 0 {
    6353            3 :                     interesting_lsns.push(*lsn);
    6354            3 :                 } else {
    6355            6 :                     let below = lsn.checked_sub(*offset);
    6356            6 :                     match below {
    6357            6 :                         Some(v) if v >= spec.start_lsn => {
    6358            4 :                             interesting_lsns.push(v);
    6359            4 :                         }
    6360            2 :                         _ => {}
    6361              :                     }
    6362              : 
    6363            6 :                     let above = Lsn(lsn.0 + offset);
    6364            6 :                     interesting_lsns.push(above);
    6365              :                 }
    6366              :             }
    6367              :         }
    6368              : 
    6369            1 :         let in_memory_test_layers = {
    6370            1 :             let mut acc = Vec::new();
    6371              : 
    6372            2 :             for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6373            2 :                 let mut data = Vec::new();
    6374              : 
    6375            2 :                 let mut lsn = lsn_range.start;
    6376          202 :                 while lsn < lsn_range.end {
    6377          200 :                     let mut key = key_range.start;
    6378        20000 :                     while key < key_range.end {
    6379        19800 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6380        19800 :                             data.push((key, lsn, record.clone()));
    6381        19800 :                         }
    6382              : 
    6383        19800 :                         key = key.next();
    6384              :                     }
    6385          200 :                     lsn = Lsn(lsn.0 + 1);
    6386              :                 }
    6387              : 
    6388            2 :                 acc.push(InMemoryLayerTestDesc {
    6389            2 :                     data,
    6390            2 :                     lsn_range: lsn_range.clone(),
    6391            2 :                     is_open: false,
    6392            2 :                 })
    6393              :             }
    6394              : 
    6395            1 :             acc
    6396              :         };
    6397              : 
    6398            1 :         let delta_test_layers = {
    6399            1 :             let mut acc = Vec::new();
    6400              : 
    6401            3 :             for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6402            3 :                 let mut data = Vec::new();
    6403              : 
    6404            3 :                 let mut lsn = lsn_range.start;
    6405          315 :                 while lsn < lsn_range.end {
    6406          312 :                     let mut key = key_range.start;
    6407        10608 :                     while key < key_range.end {
    6408        10296 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6409        10296 :                             data.push((key, lsn, record.clone()));
    6410        10296 :                         }
    6411              : 
    6412        10296 :                         key = key.next();
    6413              :                     }
    6414          312 :                     lsn = Lsn(lsn.0 + 1);
    6415              :                 }
    6416              : 
    6417            3 :                 acc.push(DeltaLayerTestDesc {
    6418            3 :                     data,
    6419            3 :                     lsn_range: lsn_range.clone(),
    6420            3 :                     key_range: key_range.clone(),
    6421            3 :                 })
    6422              :             }
    6423              : 
    6424            1 :             acc
    6425              :         };
    6426              : 
    6427            1 :         let image_test_layers = {
    6428            1 :             let mut acc = Vec::new();
    6429              : 
    6430            3 :             for (key_range, lsn) in spec.image_layers_shape.iter() {
    6431            3 :                 let mut data = Vec::new();
    6432              : 
    6433            3 :                 let mut key = key_range.start;
    6434          142 :                 while key < key_range.end {
    6435          139 :                     if let Some(record) = storage.get(&(key, *lsn)) {
    6436          139 :                         let blob = match record {
    6437          139 :                             Value::Image(blob) => blob.clone(),
    6438            0 :                             _ => unreachable!(),
    6439              :                         };
    6440              : 
    6441          139 :                         data.push((key, blob));
    6442            0 :                     }
    6443              : 
    6444          139 :                     key = key.next();
    6445              :                 }
    6446              : 
    6447            3 :                 acc.push((*lsn, data));
    6448              :             }
    6449              : 
    6450            1 :             acc
    6451              :         };
    6452              : 
    6453            1 :         let tline = tenant
    6454            1 :             .create_test_timeline_with_layers(
    6455            1 :                 new_timeline_id,
    6456            1 :                 spec.start_lsn,
    6457            1 :                 pg_version,
    6458            1 :                 ctx,
    6459            1 :                 in_memory_test_layers,
    6460            1 :                 delta_test_layers,
    6461            1 :                 image_test_layers,
    6462            1 :                 spec.last_record_lsn,
    6463            1 :             )
    6464            1 :             .await?;
    6465              : 
    6466            1 :         Ok((
    6467            1 :             tline,
    6468            1 :             Storage {
    6469            1 :                 storage,
    6470            1 :                 start_lsn: spec.start_lsn,
    6471            1 :             },
    6472            1 :             interesting_lsns,
    6473            1 :         ))
    6474            1 :     }
    6475              : 
    6476              :     #[tokio::test]
    6477            1 :     async fn test_basic() -> anyhow::Result<()> {
    6478            1 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    6479            1 :         let tline = tenant
    6480            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6481            1 :             .await?;
    6482              : 
    6483            1 :         let mut writer = tline.writer().await;
    6484            1 :         writer
    6485            1 :             .put(
    6486            1 :                 *TEST_KEY,
    6487            1 :                 Lsn(0x10),
    6488            1 :                 &Value::Image(test_img("foo at 0x10")),
    6489            1 :                 &ctx,
    6490            1 :             )
    6491            1 :             .await?;
    6492            1 :         writer.finish_write(Lsn(0x10));
    6493            1 :         drop(writer);
    6494              : 
    6495            1 :         let mut writer = tline.writer().await;
    6496            1 :         writer
    6497            1 :             .put(
    6498            1 :                 *TEST_KEY,
    6499            1 :                 Lsn(0x20),
    6500            1 :                 &Value::Image(test_img("foo at 0x20")),
    6501            1 :                 &ctx,
    6502            1 :             )
    6503            1 :             .await?;
    6504            1 :         writer.finish_write(Lsn(0x20));
    6505            1 :         drop(writer);
    6506              : 
    6507            1 :         assert_eq!(
    6508            1 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6509            1 :             test_img("foo at 0x10")
    6510              :         );
    6511            1 :         assert_eq!(
    6512            1 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6513            1 :             test_img("foo at 0x10")
    6514              :         );
    6515            1 :         assert_eq!(
    6516            1 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6517            1 :             test_img("foo at 0x20")
    6518              :         );
    6519              : 
    6520            2 :         Ok(())
    6521            1 :     }
    6522              : 
    6523              :     #[tokio::test]
    6524            1 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    6525            1 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    6526            1 :             .await?
    6527            1 :             .load()
    6528            1 :             .await;
    6529            1 :         let _ = tenant
    6530            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6531            1 :             .await?;
    6532              : 
    6533            1 :         match tenant
    6534            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6535            1 :             .await
    6536            1 :         {
    6537            1 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    6538            1 :             Err(e) => assert_eq!(
    6539            1 :                 e.to_string(),
    6540            1 :                 "timeline already exists with different parameters".to_string()
    6541            1 :             ),
    6542            1 :         }
    6543            1 : 
    6544            1 :         Ok(())
    6545            1 :     }
    6546              : 
    6547              :     /// Convenience function to create a page image with given string as the only content
    6548            5 :     pub fn test_value(s: &str) -> Value {
    6549            5 :         let mut buf = BytesMut::new();
    6550            5 :         buf.extend_from_slice(s.as_bytes());
    6551            5 :         Value::Image(buf.freeze())
    6552            5 :     }
    6553              : 
    6554              :     ///
    6555              :     /// Test branch creation
    6556              :     ///
    6557              :     #[tokio::test]
    6558            1 :     async fn test_branch() -> anyhow::Result<()> {
    6559              :         use std::str::from_utf8;
    6560              : 
    6561            1 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    6562            1 :         let tline = tenant
    6563            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6564            1 :             .await?;
    6565            1 :         let mut writer = tline.writer().await;
    6566              : 
    6567              :         #[allow(non_snake_case)]
    6568            1 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6569              :         #[allow(non_snake_case)]
    6570            1 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6571              : 
    6572              :         // Insert a value on the timeline
    6573            1 :         writer
    6574            1 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6575            1 :             .await?;
    6576            1 :         writer
    6577            1 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6578            1 :             .await?;
    6579            1 :         writer.finish_write(Lsn(0x20));
    6580              : 
    6581            1 :         writer
    6582            1 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6583            1 :             .await?;
    6584            1 :         writer.finish_write(Lsn(0x30));
    6585            1 :         writer
    6586            1 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6587            1 :             .await?;
    6588            1 :         writer.finish_write(Lsn(0x40));
    6589              : 
    6590              :         //assert_current_logical_size(&tline, Lsn(0x40));
    6591              : 
    6592              :         // Branch the history, modify relation differently on the new timeline
    6593            1 :         tenant
    6594            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6595            1 :             .await?;
    6596            1 :         let newtline = tenant
    6597            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6598            1 :             .expect("Should have a local timeline");
    6599            1 :         let mut new_writer = newtline.writer().await;
    6600            1 :         new_writer
    6601            1 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6602            1 :             .await?;
    6603            1 :         new_writer.finish_write(Lsn(0x40));
    6604              : 
    6605              :         // Check page contents on both branches
    6606            1 :         assert_eq!(
    6607            1 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6608              :             "foo at 0x40"
    6609              :         );
    6610            1 :         assert_eq!(
    6611            1 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6612              :             "bar at 0x40"
    6613              :         );
    6614            1 :         assert_eq!(
    6615            1 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6616              :             "foobar at 0x20"
    6617              :         );
    6618              : 
    6619              :         //assert_current_logical_size(&tline, Lsn(0x40));
    6620              : 
    6621            2 :         Ok(())
    6622            1 :     }
    6623              : 
    6624           10 :     async fn make_some_layers(
    6625           10 :         tline: &Timeline,
    6626           10 :         start_lsn: Lsn,
    6627           10 :         ctx: &RequestContext,
    6628           10 :     ) -> anyhow::Result<()> {
    6629           10 :         let mut lsn = start_lsn;
    6630              :         {
    6631           10 :             let mut writer = tline.writer().await;
    6632              :             // Create a relation on the timeline
    6633           10 :             writer
    6634           10 :                 .put(
    6635           10 :                     *TEST_KEY,
    6636           10 :                     lsn,
    6637           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6638           10 :                     ctx,
    6639           10 :                 )
    6640           10 :                 .await?;
    6641           10 :             writer.finish_write(lsn);
    6642           10 :             lsn += 0x10;
    6643           10 :             writer
    6644           10 :                 .put(
    6645           10 :                     *TEST_KEY,
    6646           10 :                     lsn,
    6647           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6648           10 :                     ctx,
    6649           10 :                 )
    6650           10 :                 .await?;
    6651           10 :             writer.finish_write(lsn);
    6652           10 :             lsn += 0x10;
    6653              :         }
    6654           10 :         tline.freeze_and_flush().await?;
    6655              :         {
    6656           10 :             let mut writer = tline.writer().await;
    6657           10 :             writer
    6658           10 :                 .put(
    6659           10 :                     *TEST_KEY,
    6660           10 :                     lsn,
    6661           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6662           10 :                     ctx,
    6663           10 :                 )
    6664           10 :                 .await?;
    6665           10 :             writer.finish_write(lsn);
    6666           10 :             lsn += 0x10;
    6667           10 :             writer
    6668           10 :                 .put(
    6669           10 :                     *TEST_KEY,
    6670           10 :                     lsn,
    6671           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6672           10 :                     ctx,
    6673           10 :                 )
    6674           10 :                 .await?;
    6675           10 :             writer.finish_write(lsn);
    6676              :         }
    6677           10 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6678           10 :     }
    6679              : 
    6680              :     #[tokio::test]
    6681            1 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6682            1 :         let (tenant, ctx) =
    6683            1 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6684            1 :                 .await?
    6685            1 :                 .load()
    6686            1 :                 .await;
    6687            1 :         let tline = tenant
    6688            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6689            1 :             .await?;
    6690            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6691              : 
    6692              :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6693              :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6694              :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6695              :         // below should fail.
    6696            1 :         tenant
    6697            1 :             .gc_iteration(
    6698            1 :                 Some(TIMELINE_ID),
    6699            1 :                 0x10,
    6700            1 :                 Duration::ZERO,
    6701            1 :                 &CancellationToken::new(),
    6702            1 :                 &ctx,
    6703            1 :             )
    6704            1 :             .await?;
    6705              : 
    6706              :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6707            1 :         match tenant
    6708            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6709            1 :             .await
    6710            1 :         {
    6711            1 :             Ok(_) => panic!("branching should have failed"),
    6712            1 :             Err(err) => {
    6713            1 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6714            1 :                     panic!("wrong error type")
    6715            1 :                 };
    6716            1 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6717            1 :                 assert!(
    6718            1 :                     err.source()
    6719            1 :                         .unwrap()
    6720            1 :                         .to_string()
    6721            1 :                         .contains("we might've already garbage collected needed data")
    6722            1 :                 )
    6723            1 :             }
    6724            1 :         }
    6725            1 : 
    6726            1 :         Ok(())
    6727            1 :     }
    6728              : 
    6729              :     #[tokio::test]
    6730            1 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6731            1 :         let (tenant, ctx) =
    6732            1 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6733            1 :                 .await?
    6734            1 :                 .load()
    6735            1 :                 .await;
    6736              : 
    6737            1 :         let tline = tenant
    6738            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6739            1 :             .await?;
    6740              :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6741            1 :         match tenant
    6742            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6743            1 :             .await
    6744            1 :         {
    6745            1 :             Ok(_) => panic!("branching should have failed"),
    6746            1 :             Err(err) => {
    6747            1 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6748            1 :                     panic!("wrong error type");
    6749            1 :                 };
    6750            1 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6751            1 :                 assert!(
    6752            1 :                     &err.source()
    6753            1 :                         .unwrap()
    6754            1 :                         .to_string()
    6755            1 :                         .contains("is earlier than latest GC cutoff")
    6756            1 :                 );
    6757            1 :             }
    6758            1 :         }
    6759            1 : 
    6760            1 :         Ok(())
    6761            1 :     }
    6762              : 
    6763              :     /*
    6764              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6765              :     // remove the old value, we'd need to work a little harder
    6766              :     #[tokio::test]
    6767              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6768              :         let repo =
    6769              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6770              :             .load();
    6771              : 
    6772              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6773              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6774              : 
    6775              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6776              :         let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
    6777              :         assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
    6778              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6779              :             Ok(_) => panic!("request for page should have failed"),
    6780              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6781              :         }
    6782              :         Ok(())
    6783              :     }
    6784              :      */
    6785              : 
    6786              :     #[tokio::test]
    6787            1 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6788            1 :         let (tenant, ctx) =
    6789            1 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6790            1 :                 .await?
    6791            1 :                 .load()
    6792            1 :                 .await;
    6793            1 :         let tline = tenant
    6794            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6795            1 :             .await?;
    6796            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6797              : 
    6798            1 :         tenant
    6799            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6800            1 :             .await?;
    6801            1 :         let newtline = tenant
    6802            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6803            1 :             .expect("Should have a local timeline");
    6804              : 
    6805            1 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6806              : 
    6807            1 :         tline.set_broken("test".to_owned());
    6808              : 
    6809            1 :         tenant
    6810            1 :             .gc_iteration(
    6811            1 :                 Some(TIMELINE_ID),
    6812            1 :                 0x10,
    6813            1 :                 Duration::ZERO,
    6814            1 :                 &CancellationToken::new(),
    6815            1 :                 &ctx,
    6816            1 :             )
    6817            1 :             .await?;
    6818              : 
    6819              :         // The branchpoints should contain all timelines, even ones marked
    6820              :         // as Broken.
    6821              :         {
    6822            1 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6823            1 :             assert_eq!(branchpoints.len(), 1);
    6824            1 :             assert_eq!(
    6825            1 :                 branchpoints[0],
    6826              :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6827              :             );
    6828              :         }
    6829              : 
    6830              :         // You can read the key from the child branch even though the parent is
    6831              :         // Broken, as long as you don't need to access data from the parent.
    6832            1 :         assert_eq!(
    6833            1 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6834            1 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6835              :         );
    6836              : 
    6837              :         // This needs to traverse to the parent, and fails.
    6838            1 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6839            1 :         assert!(
    6840            1 :             err.to_string().starts_with(&format!(
    6841            1 :                 "bad state on timeline {}: Broken",
    6842            1 :                 tline.timeline_id
    6843            1 :             )),
    6844            0 :             "{err}"
    6845              :         );
    6846              : 
    6847            2 :         Ok(())
    6848            1 :     }
    6849              : 
    6850              :     #[tokio::test]
    6851            1 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6852            1 :         let (tenant, ctx) =
    6853            1 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6854            1 :                 .await?
    6855            1 :                 .load()
    6856            1 :                 .await;
    6857            1 :         let tline = tenant
    6858            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6859            1 :             .await?;
    6860            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6861              : 
    6862            1 :         tenant
    6863            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6864            1 :             .await?;
    6865            1 :         let newtline = tenant
    6866            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6867            1 :             .expect("Should have a local timeline");
    6868              :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6869            1 :         tenant
    6870            1 :             .gc_iteration(
    6871            1 :                 Some(TIMELINE_ID),
    6872            1 :                 0x10,
    6873            1 :                 Duration::ZERO,
    6874            1 :                 &CancellationToken::new(),
    6875            1 :                 &ctx,
    6876            1 :             )
    6877            1 :             .await?;
    6878            1 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6879              : 
    6880            2 :         Ok(())
    6881            1 :     }
    6882              :     #[tokio::test]
    6883            1 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6884            1 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6885            1 :             .await?
    6886            1 :             .load()
    6887            1 :             .await;
    6888            1 :         let tline = tenant
    6889            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6890            1 :             .await?;
    6891            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6892              : 
    6893            1 :         tenant
    6894            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6895            1 :             .await?;
    6896            1 :         let newtline = tenant
    6897            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6898            1 :             .expect("Should have a local timeline");
    6899              : 
    6900            1 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6901              : 
    6902              :         // run gc on parent
    6903            1 :         tenant
    6904            1 :             .gc_iteration(
    6905            1 :                 Some(TIMELINE_ID),
    6906            1 :                 0x10,
    6907            1 :                 Duration::ZERO,
    6908            1 :                 &CancellationToken::new(),
    6909            1 :                 &ctx,
    6910            1 :             )
    6911            1 :             .await?;
    6912              : 
    6913              :         // Check that the data is still accessible on the branch.
    6914            1 :         assert_eq!(
    6915            1 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6916            1 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6917              :         );
    6918              : 
    6919            2 :         Ok(())
    6920            1 :     }
    6921              : 
    6922              :     #[tokio::test]
    6923            1 :     async fn timeline_load() -> anyhow::Result<()> {
    6924              :         const TEST_NAME: &str = "timeline_load";
    6925            1 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6926              :         {
    6927            1 :             let (tenant, ctx) = harness.load().await;
    6928            1 :             let tline = tenant
    6929            1 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6930            1 :                 .await?;
    6931            1 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6932              :             // so that all uploads finish & we can call harness.load() below again
    6933            1 :             tenant
    6934            1 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6935            1 :                 .instrument(harness.span())
    6936            1 :                 .await
    6937            1 :                 .ok()
    6938            1 :                 .unwrap();
    6939              :         }
    6940              : 
    6941            1 :         let (tenant, _ctx) = harness.load().await;
    6942            1 :         tenant
    6943            1 :             .get_timeline(TIMELINE_ID, true)
    6944            1 :             .expect("cannot load timeline");
    6945              : 
    6946            2 :         Ok(())
    6947            1 :     }
    6948              : 
    6949              :     #[tokio::test]
    6950            1 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6951              :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6952            1 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6953              :         // create two timelines
    6954              :         {
    6955            1 :             let (tenant, ctx) = harness.load().await;
    6956            1 :             let tline = tenant
    6957            1 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6958            1 :                 .await?;
    6959              : 
    6960            1 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6961              : 
    6962            1 :             let child_tline = tenant
    6963            1 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6964            1 :                 .await?;
    6965            1 :             child_tline.set_state(TimelineState::Active);
    6966              : 
    6967            1 :             let newtline = tenant
    6968            1 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6969            1 :                 .expect("Should have a local timeline");
    6970              : 
    6971            1 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6972              : 
    6973              :             // so that all uploads finish & we can call harness.load() below again
    6974            1 :             tenant
    6975            1 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6976            1 :                 .instrument(harness.span())
    6977            1 :                 .await
    6978            1 :                 .ok()
    6979            1 :                 .unwrap();
    6980              :         }
    6981              : 
    6982              :         // check that both of them are initially unloaded
    6983            1 :         let (tenant, _ctx) = harness.load().await;
    6984              : 
    6985              :         // check that both, child and ancestor are loaded
    6986            1 :         let _child_tline = tenant
    6987            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6988            1 :             .expect("cannot get child timeline loaded");
    6989              : 
    6990            1 :         let _ancestor_tline = tenant
    6991            1 :             .get_timeline(TIMELINE_ID, true)
    6992            1 :             .expect("cannot get ancestor timeline loaded");
    6993              : 
    6994            2 :         Ok(())
    6995            1 :     }
    6996              : 
    6997              :     #[tokio::test]
    6998            1 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    6999              :         use storage_layer::AsLayerDesc;
    7000            1 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    7001            1 :             .await?
    7002            1 :             .load()
    7003            1 :             .await;
    7004            1 :         let tline = tenant
    7005            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7006            1 :             .await?;
    7007            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    7008              : 
    7009            1 :         let layer_map = tline.layers.read(LayerManagerLockHolder::Testing).await;
    7010            1 :         let level0_deltas = layer_map
    7011            1 :             .layer_map()?
    7012            1 :             .level0_deltas()
    7013            1 :             .iter()
    7014            2 :             .map(|desc| layer_map.get_from_desc(desc))
    7015            1 :             .collect::<Vec<_>>();
    7016              : 
    7017            1 :         assert!(!level0_deltas.is_empty());
    7018              : 
    7019            3 :         for delta in level0_deltas {
    7020            1 :             // Ensure we are dumping a delta layer here
    7021            2 :             assert!(delta.layer_desc().is_delta);
    7022            2 :             delta.dump(true, &ctx).await.unwrap();
    7023            1 :         }
    7024            1 : 
    7025            1 :         Ok(())
    7026            1 :     }
    7027              : 
    7028              :     #[tokio::test]
    7029            1 :     async fn test_images() -> anyhow::Result<()> {
    7030            1 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    7031            1 :         let tline = tenant
    7032            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7033            1 :             .await?;
    7034              : 
    7035            1 :         let mut writer = tline.writer().await;
    7036            1 :         writer
    7037            1 :             .put(
    7038            1 :                 *TEST_KEY,
    7039            1 :                 Lsn(0x10),
    7040            1 :                 &Value::Image(test_img("foo at 0x10")),
    7041            1 :                 &ctx,
    7042            1 :             )
    7043            1 :             .await?;
    7044            1 :         writer.finish_write(Lsn(0x10));
    7045            1 :         drop(writer);
    7046              : 
    7047            1 :         tline.freeze_and_flush().await?;
    7048            1 :         tline
    7049            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7050            1 :             .await?;
    7051              : 
    7052            1 :         let mut writer = tline.writer().await;
    7053            1 :         writer
    7054            1 :             .put(
    7055            1 :                 *TEST_KEY,
    7056            1 :                 Lsn(0x20),
    7057            1 :                 &Value::Image(test_img("foo at 0x20")),
    7058            1 :                 &ctx,
    7059            1 :             )
    7060            1 :             .await?;
    7061            1 :         writer.finish_write(Lsn(0x20));
    7062            1 :         drop(writer);
    7063              : 
    7064            1 :         tline.freeze_and_flush().await?;
    7065            1 :         tline
    7066            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7067            1 :             .await?;
    7068              : 
    7069            1 :         let mut writer = tline.writer().await;
    7070            1 :         writer
    7071            1 :             .put(
    7072            1 :                 *TEST_KEY,
    7073            1 :                 Lsn(0x30),
    7074            1 :                 &Value::Image(test_img("foo at 0x30")),
    7075            1 :                 &ctx,
    7076            1 :             )
    7077            1 :             .await?;
    7078            1 :         writer.finish_write(Lsn(0x30));
    7079            1 :         drop(writer);
    7080              : 
    7081            1 :         tline.freeze_and_flush().await?;
    7082            1 :         tline
    7083            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7084            1 :             .await?;
    7085              : 
    7086            1 :         let mut writer = tline.writer().await;
    7087            1 :         writer
    7088            1 :             .put(
    7089            1 :                 *TEST_KEY,
    7090            1 :                 Lsn(0x40),
    7091            1 :                 &Value::Image(test_img("foo at 0x40")),
    7092            1 :                 &ctx,
    7093            1 :             )
    7094            1 :             .await?;
    7095            1 :         writer.finish_write(Lsn(0x40));
    7096            1 :         drop(writer);
    7097              : 
    7098            1 :         tline.freeze_and_flush().await?;
    7099            1 :         tline
    7100            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7101            1 :             .await?;
    7102              : 
    7103            1 :         assert_eq!(
    7104            1 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    7105            1 :             test_img("foo at 0x10")
    7106              :         );
    7107            1 :         assert_eq!(
    7108            1 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    7109            1 :             test_img("foo at 0x10")
    7110              :         );
    7111            1 :         assert_eq!(
    7112            1 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    7113            1 :             test_img("foo at 0x20")
    7114              :         );
    7115            1 :         assert_eq!(
    7116            1 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    7117            1 :             test_img("foo at 0x30")
    7118              :         );
    7119            1 :         assert_eq!(
    7120            1 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    7121            1 :             test_img("foo at 0x40")
    7122              :         );
    7123              : 
    7124            2 :         Ok(())
    7125            1 :     }
    7126              : 
    7127            2 :     async fn bulk_insert_compact_gc(
    7128            2 :         tenant: &TenantShard,
    7129            2 :         timeline: &Arc<Timeline>,
    7130            2 :         ctx: &RequestContext,
    7131            2 :         lsn: Lsn,
    7132            2 :         repeat: usize,
    7133            2 :         key_count: usize,
    7134            2 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    7135            2 :         let compact = true;
    7136            2 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    7137            2 :     }
    7138              : 
    7139            4 :     async fn bulk_insert_maybe_compact_gc(
    7140            4 :         tenant: &TenantShard,
    7141            4 :         timeline: &Arc<Timeline>,
    7142            4 :         ctx: &RequestContext,
    7143            4 :         mut lsn: Lsn,
    7144            4 :         repeat: usize,
    7145            4 :         key_count: usize,
    7146            4 :         compact: bool,
    7147            4 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    7148            4 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    7149              : 
    7150            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7151            4 :         let mut blknum = 0;
    7152              : 
    7153              :         // Enforce that key range is monotonously increasing
    7154            4 :         let mut keyspace = KeySpaceAccum::new();
    7155              : 
    7156            4 :         let cancel = CancellationToken::new();
    7157              : 
    7158            4 :         for _ in 0..repeat {
    7159          200 :             for _ in 0..key_count {
    7160      2000000 :                 test_key.field6 = blknum;
    7161      2000000 :                 let mut writer = timeline.writer().await;
    7162      2000000 :                 writer
    7163      2000000 :                     .put(
    7164      2000000 :                         test_key,
    7165      2000000 :                         lsn,
    7166      2000000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7167      2000000 :                         ctx,
    7168      2000000 :                     )
    7169      2000000 :                     .await?;
    7170      2000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    7171      2000000 :                 writer.finish_write(lsn);
    7172      2000000 :                 drop(writer);
    7173              : 
    7174      2000000 :                 keyspace.add_key(test_key);
    7175              : 
    7176      2000000 :                 lsn = Lsn(lsn.0 + 0x10);
    7177      2000000 :                 blknum += 1;
    7178              :             }
    7179              : 
    7180          200 :             timeline.freeze_and_flush().await?;
    7181          200 :             if compact {
    7182              :                 // this requires timeline to be &Arc<Timeline>
    7183          100 :                 timeline.compact(&cancel, EnumSet::default(), ctx).await?;
    7184          100 :             }
    7185              : 
    7186              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    7187              :             // originally was.
    7188          200 :             let res = tenant
    7189          200 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    7190          200 :                 .await?;
    7191              : 
    7192          200 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    7193              :         }
    7194              : 
    7195            4 :         Ok(inserted)
    7196            4 :     }
    7197              : 
    7198              :     //
    7199              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    7200              :     // Repeat 50 times.
    7201              :     //
    7202              :     #[tokio::test]
    7203            1 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    7204            1 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    7205            1 :         let (tenant, ctx) = harness.load().await;
    7206            1 :         let tline = tenant
    7207            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7208            1 :             .await?;
    7209              : 
    7210            1 :         let lsn = Lsn(0x10);
    7211            1 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7212              : 
    7213            2 :         Ok(())
    7214            1 :     }
    7215              : 
    7216              :     // Test the vectored get real implementation against a simple sequential implementation.
    7217              :     //
    7218              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    7219              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    7220              :     // grow to the right on the X axis.
    7221              :     //                       [Delta]
    7222              :     //                 [Delta]
    7223              :     //           [Delta]
    7224              :     //    [Delta]
    7225              :     // ------------ Image ---------------
    7226              :     //
    7227              :     // After layer generation we pick the ranges to query as follows:
    7228              :     // 1. The beginning of each delta layer
    7229              :     // 2. At the seam between two adjacent delta layers
    7230              :     //
    7231              :     // There's one major downside to this test: delta layers only contains images,
    7232              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    7233              :     #[tokio::test]
    7234            1 :     async fn test_get_vectored() -> anyhow::Result<()> {
    7235            1 :         let harness = TenantHarness::create("test_get_vectored").await?;
    7236            1 :         let (tenant, ctx) = harness.load().await;
    7237            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7238            1 :         let tline = tenant
    7239            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7240            1 :             .await?;
    7241              : 
    7242            1 :         let lsn = Lsn(0x10);
    7243            1 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7244              : 
    7245            1 :         let guard = tline.layers.read(LayerManagerLockHolder::Testing).await;
    7246            1 :         let lm = guard.layer_map()?;
    7247              : 
    7248            1 :         lm.dump(true, &ctx).await?;
    7249              : 
    7250            1 :         let mut reads = Vec::new();
    7251            1 :         let mut prev = None;
    7252            6 :         lm.iter_historic_layers().for_each(|desc| {
    7253            6 :             if !desc.is_delta() {
    7254            1 :                 prev = Some(desc.clone());
    7255            1 :                 return;
    7256            5 :             }
    7257              : 
    7258            5 :             let start = desc.key_range.start;
    7259            5 :             let end = desc
    7260            5 :                 .key_range
    7261            5 :                 .start
    7262            5 :                 .add(tenant.conf.max_get_vectored_keys.get() as u32);
    7263            5 :             reads.push(KeySpace {
    7264            5 :                 ranges: vec![start..end],
    7265            5 :             });
    7266              : 
    7267            5 :             if let Some(prev) = &prev {
    7268            5 :                 if !prev.is_delta() {
    7269            5 :                     return;
    7270            0 :                 }
    7271              : 
    7272            0 :                 let first_range = Key {
    7273            0 :                     field6: prev.key_range.end.field6 - 4,
    7274            0 :                     ..prev.key_range.end
    7275            0 :                 }..prev.key_range.end;
    7276              : 
    7277            0 :                 let second_range = desc.key_range.start..Key {
    7278            0 :                     field6: desc.key_range.start.field6 + 4,
    7279            0 :                     ..desc.key_range.start
    7280            0 :                 };
    7281              : 
    7282            0 :                 reads.push(KeySpace {
    7283            0 :                     ranges: vec![first_range, second_range],
    7284            0 :                 });
    7285            0 :             };
    7286              : 
    7287            0 :             prev = Some(desc.clone());
    7288            6 :         });
    7289              : 
    7290            1 :         drop(guard);
    7291              : 
    7292              :         // Pick a big LSN such that we query over all the changes.
    7293            1 :         let reads_lsn = Lsn(u64::MAX - 1);
    7294              : 
    7295            6 :         for read in reads {
    7296            5 :             info!("Doing vectored read on {:?}", read);
    7297            1 : 
    7298            5 :             let query = VersionedKeySpaceQuery::uniform(read.clone(), reads_lsn);
    7299            1 : 
    7300            5 :             let vectored_res = tline
    7301            5 :                 .get_vectored_impl(
    7302            5 :                     query,
    7303            5 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7304            5 :                     &ctx,
    7305            5 :                 )
    7306            5 :                 .await;
    7307            1 : 
    7308            5 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    7309            5 :             let mut expect_missing = false;
    7310            5 :             let mut key = read.start().unwrap();
    7311          165 :             while key != read.end().unwrap() {
    7312          160 :                 if let Some(lsns) = inserted.get(&key) {
    7313          160 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    7314          160 :                     match expected_lsn {
    7315          160 :                         Some(lsn) => {
    7316          160 :                             expected_lsns.insert(key, *lsn);
    7317          160 :                         }
    7318            1 :                         None => {
    7319            1 :                             expect_missing = true;
    7320            1 :                             break;
    7321            1 :                         }
    7322            1 :                     }
    7323            1 :                 } else {
    7324            1 :                     expect_missing = true;
    7325            1 :                     break;
    7326            1 :                 }
    7327            1 : 
    7328          160 :                 key = key.next();
    7329            1 :             }
    7330            1 : 
    7331            5 :             if expect_missing {
    7332            1 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    7333            1 :             } else {
    7334          160 :                 for (key, image) in vectored_res? {
    7335          160 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    7336          160 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    7337          160 :                     assert_eq!(image?, expected_image);
    7338            1 :                 }
    7339            1 :             }
    7340            1 :         }
    7341            1 : 
    7342            1 :         Ok(())
    7343            1 :     }
    7344              : 
    7345              :     #[tokio::test]
    7346            1 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    7347            1 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    7348              : 
    7349            1 :         let (tenant, ctx) = harness.load().await;
    7350            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7351            1 :         let (tline, ctx) = tenant
    7352            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7353            1 :             .await?;
    7354            1 :         let tline = tline.raw_timeline().unwrap();
    7355              : 
    7356            1 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    7357            1 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    7358            1 :         modification.set_lsn(Lsn(0x1008))?;
    7359            1 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    7360            1 :         modification.commit(&ctx).await?;
    7361              : 
    7362            1 :         let child_timeline_id = TimelineId::generate();
    7363            1 :         tenant
    7364            1 :             .branch_timeline_test(
    7365            1 :                 tline,
    7366            1 :                 child_timeline_id,
    7367            1 :                 Some(tline.get_last_record_lsn()),
    7368            1 :                 &ctx,
    7369            1 :             )
    7370            1 :             .await?;
    7371              : 
    7372            1 :         let child_timeline = tenant
    7373            1 :             .get_timeline(child_timeline_id, true)
    7374            1 :             .expect("Should have the branched timeline");
    7375              : 
    7376            1 :         let aux_keyspace = KeySpace {
    7377            1 :             ranges: vec![NON_INHERITED_RANGE],
    7378            1 :         };
    7379            1 :         let read_lsn = child_timeline.get_last_record_lsn();
    7380              : 
    7381            1 :         let query = VersionedKeySpaceQuery::uniform(aux_keyspace.clone(), read_lsn);
    7382              : 
    7383            1 :         let vectored_res = child_timeline
    7384            1 :             .get_vectored_impl(
    7385            1 :                 query,
    7386            1 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7387            1 :                 &ctx,
    7388            1 :             )
    7389            1 :             .await;
    7390              : 
    7391            1 :         let images = vectored_res?;
    7392            1 :         assert!(images.is_empty());
    7393            2 :         Ok(())
    7394            1 :     }
    7395              : 
    7396              :     // Test that vectored get handles layer gaps correctly
    7397              :     // by advancing into the next ancestor timeline if required.
    7398              :     //
    7399              :     // The test generates timelines that look like the diagram below.
    7400              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    7401              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    7402              :     //
    7403              :     // ```
    7404              :     //-------------------------------+
    7405              :     //                          ...  |
    7406              :     //               [   L1   ]      |
    7407              :     //     [ / L1   ]                | Child Timeline
    7408              :     // ...                           |
    7409              :     // ------------------------------+
    7410              :     //     [ X L1   ]                | Parent Timeline
    7411              :     // ------------------------------+
    7412              :     // ```
    7413              :     #[tokio::test]
    7414            1 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    7415            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
    7416            1 :             // Make compaction deterministic
    7417            1 :             gc_period: Some(Duration::ZERO),
    7418            1 :             compaction_period: Some(Duration::ZERO),
    7419            1 :             // Encourage creation of L1 layers
    7420            1 :             checkpoint_distance: Some(16 * 1024),
    7421            1 :             compaction_target_size: Some(8 * 1024),
    7422            1 :             ..Default::default()
    7423            1 :         };
    7424              : 
    7425            1 :         let harness = TenantHarness::create_custom(
    7426            1 :             "test_get_vectored_key_gap",
    7427            1 :             tenant_conf,
    7428            1 :             TenantId::generate(),
    7429            1 :             ShardIdentity::unsharded(),
    7430            1 :             Generation::new(0xdeadbeef),
    7431            1 :         )
    7432            1 :         .await?;
    7433            1 :         let (tenant, ctx) = harness.load().await;
    7434            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7435              : 
    7436            1 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7437            1 :         let gap_at_key = current_key.add(100);
    7438            1 :         let mut current_lsn = Lsn(0x10);
    7439              : 
    7440              :         const KEY_COUNT: usize = 10_000;
    7441              : 
    7442            1 :         let timeline_id = TimelineId::generate();
    7443            1 :         let current_timeline = tenant
    7444            1 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7445            1 :             .await?;
    7446              : 
    7447            1 :         current_lsn += 0x100;
    7448              : 
    7449            1 :         let mut writer = current_timeline.writer().await;
    7450            1 :         writer
    7451            1 :             .put(
    7452            1 :                 gap_at_key,
    7453            1 :                 current_lsn,
    7454            1 :                 &Value::Image(test_img(&format!("{gap_at_key} at {current_lsn}"))),
    7455            1 :                 &ctx,
    7456            1 :             )
    7457            1 :             .await?;
    7458            1 :         writer.finish_write(current_lsn);
    7459            1 :         drop(writer);
    7460              : 
    7461            1 :         let mut latest_lsns = HashMap::new();
    7462            1 :         latest_lsns.insert(gap_at_key, current_lsn);
    7463              : 
    7464            1 :         current_timeline.freeze_and_flush().await?;
    7465              : 
    7466            1 :         let child_timeline_id = TimelineId::generate();
    7467              : 
    7468            1 :         tenant
    7469            1 :             .branch_timeline_test(
    7470            1 :                 &current_timeline,
    7471            1 :                 child_timeline_id,
    7472            1 :                 Some(current_lsn),
    7473            1 :                 &ctx,
    7474            1 :             )
    7475            1 :             .await?;
    7476            1 :         let child_timeline = tenant
    7477            1 :             .get_timeline(child_timeline_id, true)
    7478            1 :             .expect("Should have the branched timeline");
    7479              : 
    7480        10001 :         for i in 0..KEY_COUNT {
    7481        10000 :             if current_key == gap_at_key {
    7482            1 :                 current_key = current_key.next();
    7483            1 :                 continue;
    7484         9999 :             }
    7485              : 
    7486         9999 :             current_lsn += 0x10;
    7487              : 
    7488         9999 :             let mut writer = child_timeline.writer().await;
    7489         9999 :             writer
    7490         9999 :                 .put(
    7491         9999 :                     current_key,
    7492         9999 :                     current_lsn,
    7493         9999 :                     &Value::Image(test_img(&format!("{current_key} at {current_lsn}"))),
    7494         9999 :                     &ctx,
    7495         9999 :                 )
    7496         9999 :                 .await?;
    7497         9999 :             writer.finish_write(current_lsn);
    7498         9999 :             drop(writer);
    7499              : 
    7500         9999 :             latest_lsns.insert(current_key, current_lsn);
    7501         9999 :             current_key = current_key.next();
    7502              : 
    7503              :             // Flush every now and then to encourage layer file creation.
    7504         9999 :             if i % 500 == 0 {
    7505           20 :                 child_timeline.freeze_and_flush().await?;
    7506         9979 :             }
    7507              :         }
    7508              : 
    7509            1 :         child_timeline.freeze_and_flush().await?;
    7510            1 :         let mut flags = EnumSet::new();
    7511            1 :         flags.insert(CompactFlags::ForceRepartition);
    7512            1 :         child_timeline
    7513            1 :             .compact(&CancellationToken::new(), flags, &ctx)
    7514            1 :             .await?;
    7515              : 
    7516            1 :         let key_near_end = {
    7517            1 :             let mut tmp = current_key;
    7518            1 :             tmp.field6 -= 10;
    7519            1 :             tmp
    7520              :         };
    7521              : 
    7522            1 :         let key_near_gap = {
    7523            1 :             let mut tmp = gap_at_key;
    7524            1 :             tmp.field6 -= 10;
    7525            1 :             tmp
    7526              :         };
    7527              : 
    7528            1 :         let read = KeySpace {
    7529            1 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    7530            1 :         };
    7531              : 
    7532            1 :         let query = VersionedKeySpaceQuery::uniform(read.clone(), current_lsn);
    7533              : 
    7534            1 :         let results = child_timeline
    7535            1 :             .get_vectored_impl(
    7536            1 :                 query,
    7537            1 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7538            1 :                 &ctx,
    7539            1 :             )
    7540            1 :             .await?;
    7541              : 
    7542           22 :         for (key, img_res) in results {
    7543           21 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    7544           21 :             assert_eq!(img_res?, expected);
    7545            1 :         }
    7546            1 : 
    7547            1 :         Ok(())
    7548            1 :     }
    7549              : 
    7550              :     // Test that vectored get descends into ancestor timelines correctly and
    7551              :     // does not return an image that's newer than requested.
    7552              :     //
    7553              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    7554              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    7555              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    7556              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    7557              :     // order to avoid returning an image that's too new. The test below constructs such
    7558              :     // a timeline setup and does a few queries around the Lsn of each page image.
    7559              :     // ```
    7560              :     //    LSN
    7561              :     //     ^
    7562              :     //     |
    7563              :     //     |
    7564              :     // 500 | --------------------------------------> branch point
    7565              :     // 400 |        X
    7566              :     // 300 |        X
    7567              :     // 200 | --------------------------------------> requested lsn
    7568              :     // 100 |        X
    7569              :     //     |---------------------------------------> Key
    7570              :     //              |
    7571              :     //              ------> requested key
    7572              :     //
    7573              :     // Legend:
    7574              :     // * X - page images
    7575              :     // ```
    7576              :     #[tokio::test]
    7577            1 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7578            1 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7579            1 :         let (tenant, ctx) = harness.load().await;
    7580            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7581              : 
    7582            1 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7583            1 :         let end_key = start_key.add(1000);
    7584            1 :         let child_gap_at_key = start_key.add(500);
    7585            1 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7586              : 
    7587            1 :         let mut current_lsn = Lsn(0x10);
    7588              : 
    7589            1 :         let timeline_id = TimelineId::generate();
    7590            1 :         let parent_timeline = tenant
    7591            1 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7592            1 :             .await?;
    7593              : 
    7594            1 :         current_lsn += 0x100;
    7595              : 
    7596            4 :         for _ in 0..3 {
    7597            3 :             let mut key = start_key;
    7598         3003 :             while key < end_key {
    7599         3000 :                 current_lsn += 0x10;
    7600              : 
    7601         3000 :                 let image_value = format!("{child_gap_at_key} at {current_lsn}");
    7602              : 
    7603         3000 :                 let mut writer = parent_timeline.writer().await;
    7604         3000 :                 writer
    7605         3000 :                     .put(
    7606         3000 :                         key,
    7607         3000 :                         current_lsn,
    7608         3000 :                         &Value::Image(test_img(&image_value)),
    7609         3000 :                         &ctx,
    7610         3000 :                     )
    7611         3000 :                     .await?;
    7612         3000 :                 writer.finish_write(current_lsn);
    7613              : 
    7614         3000 :                 if key == child_gap_at_key {
    7615            3 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7616         2997 :                 }
    7617              : 
    7618         3000 :                 key = key.next();
    7619              :             }
    7620              : 
    7621            3 :             parent_timeline.freeze_and_flush().await?;
    7622              :         }
    7623              : 
    7624            1 :         let child_timeline_id = TimelineId::generate();
    7625              : 
    7626            1 :         let child_timeline = tenant
    7627            1 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7628            1 :             .await?;
    7629              : 
    7630            1 :         let mut key = start_key;
    7631         1001 :         while key < end_key {
    7632         1000 :             if key == child_gap_at_key {
    7633            1 :                 key = key.next();
    7634            1 :                 continue;
    7635          999 :             }
    7636              : 
    7637          999 :             current_lsn += 0x10;
    7638              : 
    7639          999 :             let mut writer = child_timeline.writer().await;
    7640          999 :             writer
    7641          999 :                 .put(
    7642          999 :                     key,
    7643          999 :                     current_lsn,
    7644          999 :                     &Value::Image(test_img(&format!("{key} at {current_lsn}"))),
    7645          999 :                     &ctx,
    7646          999 :                 )
    7647          999 :                 .await?;
    7648          999 :             writer.finish_write(current_lsn);
    7649              : 
    7650          999 :             key = key.next();
    7651              :         }
    7652              : 
    7653            1 :         child_timeline.freeze_and_flush().await?;
    7654              : 
    7655            1 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7656            1 :         let mut query_lsns = Vec::new();
    7657            3 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7658           18 :             for offset in lsn_offsets {
    7659           15 :                 query_lsns.push(Lsn(image_lsn
    7660           15 :                     .0
    7661           15 :                     .checked_add_signed(offset)
    7662           15 :                     .expect("Shouldn't overflow")));
    7663           15 :             }
    7664            1 :         }
    7665            1 : 
    7666           16 :         for query_lsn in query_lsns {
    7667           15 :             let query = VersionedKeySpaceQuery::uniform(
    7668           15 :                 KeySpace {
    7669           15 :                     ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7670           15 :                 },
    7671           15 :                 query_lsn,
    7672            1 :             );
    7673            1 : 
    7674           15 :             let results = child_timeline
    7675           15 :                 .get_vectored_impl(
    7676           15 :                     query,
    7677           15 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7678           15 :                     &ctx,
    7679           15 :                 )
    7680           15 :                 .await;
    7681            1 : 
    7682           15 :             let expected_item = parent_gap_lsns
    7683           15 :                 .iter()
    7684           15 :                 .rev()
    7685           34 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7686            1 : 
    7687           15 :             info!(
    7688            1 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7689            1 :                 query_lsn, expected_item
    7690            1 :             );
    7691            1 : 
    7692           15 :             match expected_item {
    7693           13 :                 Some((_, img_value)) => {
    7694           13 :                     let key_results = results.expect("No vectored get error expected");
    7695           13 :                     let key_result = &key_results[&child_gap_at_key];
    7696           13 :                     let returned_img = key_result
    7697           13 :                         .as_ref()
    7698           13 :                         .expect("No page reconstruct error expected");
    7699            1 : 
    7700           13 :                     info!(
    7701            1 :                         "Vectored read at LSN {} returned image {}",
    7702            1 :                         query_lsn,
    7703            1 :                         std::str::from_utf8(returned_img)?
    7704            1 :                     );
    7705           13 :                     assert_eq!(*returned_img, test_img(img_value));
    7706            1 :                 }
    7707            1 :                 None => {
    7708            2 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7709            1 :                 }
    7710            1 :             }
    7711            1 :         }
    7712            1 : 
    7713            1 :         Ok(())
    7714            1 :     }
    7715              : 
    7716              :     #[tokio::test]
    7717            1 :     async fn test_random_updates() -> anyhow::Result<()> {
    7718            1 :         let names_algorithms = [
    7719            1 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7720            1 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7721            1 :         ];
    7722            3 :         for (name, algorithm) in names_algorithms {
    7723            2 :             test_random_updates_algorithm(name, algorithm).await?;
    7724            1 :         }
    7725            1 :         Ok(())
    7726            1 :     }
    7727              : 
    7728            2 :     async fn test_random_updates_algorithm(
    7729            2 :         name: &'static str,
    7730            2 :         compaction_algorithm: CompactionAlgorithm,
    7731            2 :     ) -> anyhow::Result<()> {
    7732            2 :         let mut harness = TenantHarness::create(name).await?;
    7733            2 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    7734            2 :             kind: compaction_algorithm,
    7735            2 :         });
    7736            2 :         let (tenant, ctx) = harness.load().await;
    7737            2 :         let tline = tenant
    7738            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7739            2 :             .await?;
    7740              : 
    7741              :         const NUM_KEYS: usize = 1000;
    7742            2 :         let cancel = CancellationToken::new();
    7743              : 
    7744            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7745            2 :         let mut test_key_end = test_key;
    7746            2 :         test_key_end.field6 = NUM_KEYS as u32;
    7747            2 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7748              : 
    7749            2 :         let mut keyspace = KeySpaceAccum::new();
    7750              : 
    7751              :         // Track when each page was last modified. Used to assert that
    7752              :         // a read sees the latest page version.
    7753            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    7754              : 
    7755            2 :         let mut lsn = Lsn(0x10);
    7756              :         #[allow(clippy::needless_range_loop)]
    7757         2002 :         for blknum in 0..NUM_KEYS {
    7758         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7759         2000 :             test_key.field6 = blknum as u32;
    7760         2000 :             let mut writer = tline.writer().await;
    7761         2000 :             writer
    7762         2000 :                 .put(
    7763         2000 :                     test_key,
    7764         2000 :                     lsn,
    7765         2000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7766         2000 :                     &ctx,
    7767         2000 :                 )
    7768         2000 :                 .await?;
    7769         2000 :             writer.finish_write(lsn);
    7770         2000 :             updated[blknum] = lsn;
    7771         2000 :             drop(writer);
    7772              : 
    7773         2000 :             keyspace.add_key(test_key);
    7774              :         }
    7775              : 
    7776          102 :         for _ in 0..50 {
    7777       100100 :             for _ in 0..NUM_KEYS {
    7778       100000 :                 lsn = Lsn(lsn.0 + 0x10);
    7779       100000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7780       100000 :                 test_key.field6 = blknum as u32;
    7781       100000 :                 let mut writer = tline.writer().await;
    7782       100000 :                 writer
    7783       100000 :                     .put(
    7784       100000 :                         test_key,
    7785       100000 :                         lsn,
    7786       100000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7787       100000 :                         &ctx,
    7788       100000 :                     )
    7789       100000 :                     .await?;
    7790       100000 :                 writer.finish_write(lsn);
    7791       100000 :                 drop(writer);
    7792       100000 :                 updated[blknum] = lsn;
    7793              :             }
    7794              : 
    7795              :             // Read all the blocks
    7796       100000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7797       100000 :                 test_key.field6 = blknum as u32;
    7798       100000 :                 assert_eq!(
    7799       100000 :                     tline.get(test_key, lsn, &ctx).await?,
    7800       100000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    7801              :                 );
    7802              :             }
    7803              : 
    7804              :             // Perform a cycle of flush, and GC
    7805          100 :             tline.freeze_and_flush().await?;
    7806          100 :             tenant
    7807          100 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7808          100 :                 .await?;
    7809              :         }
    7810              : 
    7811            2 :         Ok(())
    7812            2 :     }
    7813              : 
    7814              :     #[tokio::test]
    7815            1 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7816            1 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7817            1 :             .await?
    7818            1 :             .load()
    7819            1 :             .await;
    7820            1 :         let mut tline = tenant
    7821            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7822            1 :             .await?;
    7823              : 
    7824              :         const NUM_KEYS: usize = 1000;
    7825              : 
    7826            1 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7827              : 
    7828            1 :         let mut keyspace = KeySpaceAccum::new();
    7829              : 
    7830            1 :         let cancel = CancellationToken::new();
    7831              : 
    7832              :         // Track when each page was last modified. Used to assert that
    7833              :         // a read sees the latest page version.
    7834            1 :         let mut updated = [Lsn(0); NUM_KEYS];
    7835              : 
    7836            1 :         let mut lsn = Lsn(0x10);
    7837            1 :         #[allow(clippy::needless_range_loop)]
    7838         1001 :         for blknum in 0..NUM_KEYS {
    7839         1000 :             lsn = Lsn(lsn.0 + 0x10);
    7840         1000 :             test_key.field6 = blknum as u32;
    7841         1000 :             let mut writer = tline.writer().await;
    7842         1000 :             writer
    7843         1000 :                 .put(
    7844         1000 :                     test_key,
    7845         1000 :                     lsn,
    7846         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7847         1000 :                     &ctx,
    7848         1000 :                 )
    7849         1000 :                 .await?;
    7850         1000 :             writer.finish_write(lsn);
    7851         1000 :             updated[blknum] = lsn;
    7852         1000 :             drop(writer);
    7853            1 : 
    7854         1000 :             keyspace.add_key(test_key);
    7855            1 :         }
    7856            1 : 
    7857           51 :         for _ in 0..50 {
    7858           50 :             let new_tline_id = TimelineId::generate();
    7859           50 :             tenant
    7860           50 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7861           50 :                 .await?;
    7862           50 :             tline = tenant
    7863           50 :                 .get_timeline(new_tline_id, true)
    7864           50 :                 .expect("Should have the branched timeline");
    7865            1 : 
    7866        50050 :             for _ in 0..NUM_KEYS {
    7867        50000 :                 lsn = Lsn(lsn.0 + 0x10);
    7868        50000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7869        50000 :                 test_key.field6 = blknum as u32;
    7870        50000 :                 let mut writer = tline.writer().await;
    7871        50000 :                 writer
    7872        50000 :                     .put(
    7873        50000 :                         test_key,
    7874        50000 :                         lsn,
    7875        50000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7876        50000 :                         &ctx,
    7877        50000 :                     )
    7878        50000 :                     .await?;
    7879        50000 :                 println!("updating {blknum} at {lsn}");
    7880        50000 :                 writer.finish_write(lsn);
    7881        50000 :                 drop(writer);
    7882        50000 :                 updated[blknum] = lsn;
    7883            1 :             }
    7884            1 : 
    7885            1 :             // Read all the blocks
    7886        50000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7887        50000 :                 test_key.field6 = blknum as u32;
    7888        50000 :                 assert_eq!(
    7889        50000 :                     tline.get(test_key, lsn, &ctx).await?,
    7890        50000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    7891            1 :                 );
    7892            1 :             }
    7893            1 : 
    7894            1 :             // Perform a cycle of flush, compact, and GC
    7895           50 :             tline.freeze_and_flush().await?;
    7896           50 :             tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    7897           50 :             tenant
    7898           50 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7899           50 :                 .await?;
    7900            1 :         }
    7901            1 : 
    7902            1 :         Ok(())
    7903            1 :     }
    7904              : 
    7905              :     #[tokio::test]
    7906            1 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7907            1 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7908            1 :             .await?
    7909            1 :             .load()
    7910            1 :             .await;
    7911            1 :         let mut tline = tenant
    7912            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7913            1 :             .await?;
    7914              : 
    7915              :         const NUM_KEYS: usize = 100;
    7916              :         const NUM_TLINES: usize = 50;
    7917              : 
    7918            1 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7919              :         // Track page mutation lsns across different timelines.
    7920            1 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7921              : 
    7922            1 :         let mut lsn = Lsn(0x10);
    7923              : 
    7924            1 :         #[allow(clippy::needless_range_loop)]
    7925           51 :         for idx in 0..NUM_TLINES {
    7926           50 :             let new_tline_id = TimelineId::generate();
    7927           50 :             tenant
    7928           50 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7929           50 :                 .await?;
    7930           50 :             tline = tenant
    7931           50 :                 .get_timeline(new_tline_id, true)
    7932           50 :                 .expect("Should have the branched timeline");
    7933            1 : 
    7934         5050 :             for _ in 0..NUM_KEYS {
    7935         5000 :                 lsn = Lsn(lsn.0 + 0x10);
    7936         5000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7937         5000 :                 test_key.field6 = blknum as u32;
    7938         5000 :                 let mut writer = tline.writer().await;
    7939         5000 :                 writer
    7940         5000 :                     .put(
    7941         5000 :                         test_key,
    7942         5000 :                         lsn,
    7943         5000 :                         &Value::Image(test_img(&format!("{idx} {blknum} at {lsn}"))),
    7944         5000 :                         &ctx,
    7945         5000 :                     )
    7946         5000 :                     .await?;
    7947         5000 :                 println!("updating [{idx}][{blknum}] at {lsn}");
    7948         5000 :                 writer.finish_write(lsn);
    7949         5000 :                 drop(writer);
    7950         5000 :                 updated[idx][blknum] = lsn;
    7951            1 :             }
    7952            1 :         }
    7953            1 : 
    7954            1 :         // Read pages from leaf timeline across all ancestors.
    7955           50 :         for (idx, lsns) in updated.iter().enumerate() {
    7956         5000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7957            1 :                 // Skip empty mutations.
    7958         5000 :                 if lsn.0 == 0 {
    7959         1796 :                     continue;
    7960         3204 :                 }
    7961         3204 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7962         3204 :                 test_key.field6 = blknum as u32;
    7963         3204 :                 assert_eq!(
    7964         3204 :                     tline.get(test_key, *lsn, &ctx).await?,
    7965         3204 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7966            1 :                 );
    7967            1 :             }
    7968            1 :         }
    7969            1 :         Ok(())
    7970            1 :     }
    7971              : 
    7972              :     #[tokio::test]
    7973            1 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7974            1 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7975            1 :             .await?
    7976            1 :             .load()
    7977            1 :             .await;
    7978              : 
    7979            1 :         let initdb_lsn = Lsn(0x20);
    7980            1 :         let (utline, ctx) = tenant
    7981            1 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7982            1 :             .await?;
    7983            1 :         let tline = utline.raw_timeline().unwrap();
    7984              : 
    7985              :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7986            1 :         tline.maybe_spawn_flush_loop();
    7987              : 
    7988              :         // Make sure the timeline has the minimum set of required keys for operation.
    7989              :         // The only operation you can always do on an empty timeline is to `put` new data.
    7990              :         // Except if you `put` at `initdb_lsn`.
    7991              :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7992              :         // It uses `repartition()`, which assumes some keys to be present.
    7993              :         // Let's make sure the test timeline can handle that case.
    7994              :         {
    7995            1 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7996            1 :             assert_eq!(
    7997              :                 timeline::FlushLoopState::Running {
    7998              :                     expect_initdb_optimization: false,
    7999              :                     initdb_optimization_count: 0,
    8000              :                 },
    8001            1 :                 *state
    8002              :             );
    8003            1 :             *state = timeline::FlushLoopState::Running {
    8004            1 :                 expect_initdb_optimization: true,
    8005            1 :                 initdb_optimization_count: 0,
    8006            1 :             };
    8007              :         }
    8008              : 
    8009              :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    8010              :         // As explained above, the optimization requires some keys to be present.
    8011              :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    8012              :         // This is what `create_test_timeline` does, by the way.
    8013            1 :         let mut modification = tline.begin_modification(initdb_lsn);
    8014            1 :         modification
    8015            1 :             .init_empty_test_timeline()
    8016            1 :             .context("init_empty_test_timeline")?;
    8017            1 :         modification
    8018            1 :             .commit(&ctx)
    8019            1 :             .await
    8020            1 :             .context("commit init_empty_test_timeline modification")?;
    8021              : 
    8022              :         // Do the flush. The flush code will check the expectations that we set above.
    8023            1 :         tline.freeze_and_flush().await?;
    8024              : 
    8025              :         // assert freeze_and_flush exercised the initdb optimization
    8026            1 :         {
    8027            1 :             let state = tline.flush_loop_state.lock().unwrap();
    8028            1 :             let timeline::FlushLoopState::Running {
    8029            1 :                 expect_initdb_optimization,
    8030            1 :                 initdb_optimization_count,
    8031            1 :             } = *state
    8032            1 :             else {
    8033            1 :                 panic!("unexpected state: {:?}", *state);
    8034            1 :             };
    8035            1 :             assert!(expect_initdb_optimization);
    8036            1 :             assert!(initdb_optimization_count > 0);
    8037            1 :         }
    8038            1 :         Ok(())
    8039            1 :     }
    8040              : 
    8041              :     #[tokio::test]
    8042            1 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    8043            1 :         let name = "test_create_guard_crash";
    8044            1 :         let harness = TenantHarness::create(name).await?;
    8045              :         {
    8046            1 :             let (tenant, ctx) = harness.load().await;
    8047            1 :             let (tline, _ctx) = tenant
    8048            1 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    8049            1 :                 .await?;
    8050              :             // Leave the timeline ID in [`TenantShard::timelines_creating`] to exclude attempting to create it again
    8051            1 :             let raw_tline = tline.raw_timeline().unwrap();
    8052            1 :             raw_tline
    8053            1 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    8054            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))
    8055            1 :                 .await;
    8056            1 :             std::mem::forget(tline);
    8057              :         }
    8058              : 
    8059            1 :         let (tenant, _) = harness.load().await;
    8060            1 :         match tenant.get_timeline(TIMELINE_ID, false) {
    8061            0 :             Ok(_) => panic!("timeline should've been removed during load"),
    8062            1 :             Err(e) => {
    8063            1 :                 assert_eq!(
    8064              :                     e,
    8065            1 :                     GetTimelineError::NotFound {
    8066            1 :                         tenant_id: tenant.tenant_shard_id,
    8067            1 :                         timeline_id: TIMELINE_ID,
    8068            1 :                     }
    8069              :                 )
    8070              :             }
    8071              :         }
    8072              : 
    8073            1 :         assert!(
    8074            1 :             !harness
    8075            1 :                 .conf
    8076            1 :                 .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    8077            1 :                 .exists()
    8078              :         );
    8079              : 
    8080            2 :         Ok(())
    8081            1 :     }
    8082              : 
    8083              :     #[tokio::test]
    8084            1 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    8085            1 :         let names_algorithms = [
    8086            1 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    8087            1 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    8088            1 :         ];
    8089            3 :         for (name, algorithm) in names_algorithms {
    8090            2 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    8091            1 :         }
    8092            1 :         Ok(())
    8093            1 :     }
    8094              : 
    8095            2 :     async fn test_read_at_max_lsn_algorithm(
    8096            2 :         name: &'static str,
    8097            2 :         compaction_algorithm: CompactionAlgorithm,
    8098            2 :     ) -> anyhow::Result<()> {
    8099            2 :         let mut harness = TenantHarness::create(name).await?;
    8100            2 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    8101            2 :             kind: compaction_algorithm,
    8102            2 :         });
    8103            2 :         let (tenant, ctx) = harness.load().await;
    8104            2 :         let tline = tenant
    8105            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    8106            2 :             .await?;
    8107              : 
    8108            2 :         let lsn = Lsn(0x10);
    8109            2 :         let compact = false;
    8110            2 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    8111              : 
    8112            2 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8113            2 :         let read_lsn = Lsn(u64::MAX - 1);
    8114              : 
    8115            2 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    8116            2 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    8117              : 
    8118            2 :         Ok(())
    8119            2 :     }
    8120              : 
    8121              :     #[tokio::test]
    8122            1 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    8123            1 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    8124            1 :         let (tenant, ctx) = harness.load().await;
    8125            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8126            1 :         let tline = tenant
    8127            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8128            1 :             .await?;
    8129              : 
    8130              :         const NUM_KEYS: usize = 1000;
    8131              :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8132              : 
    8133            1 :         let cancel = CancellationToken::new();
    8134              : 
    8135            1 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8136            1 :         base_key.field1 = AUX_KEY_PREFIX;
    8137            1 :         let mut test_key = base_key;
    8138              : 
    8139              :         // Track when each page was last modified. Used to assert that
    8140              :         // a read sees the latest page version.
    8141            1 :         let mut updated = [Lsn(0); NUM_KEYS];
    8142              : 
    8143            1 :         let mut lsn = Lsn(0x10);
    8144              :         #[allow(clippy::needless_range_loop)]
    8145         1001 :         for blknum in 0..NUM_KEYS {
    8146         1000 :             lsn = Lsn(lsn.0 + 0x10);
    8147         1000 :             test_key.field6 = (blknum * STEP) as u32;
    8148         1000 :             let mut writer = tline.writer().await;
    8149         1000 :             writer
    8150         1000 :                 .put(
    8151         1000 :                     test_key,
    8152         1000 :                     lsn,
    8153         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8154         1000 :                     &ctx,
    8155         1000 :                 )
    8156         1000 :                 .await?;
    8157         1000 :             writer.finish_write(lsn);
    8158         1000 :             updated[blknum] = lsn;
    8159         1000 :             drop(writer);
    8160              :         }
    8161              : 
    8162            1 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8163              : 
    8164           12 :         for iter in 0..=10 {
    8165            1 :             // Read all the blocks
    8166        11000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    8167        11000 :                 test_key.field6 = (blknum * STEP) as u32;
    8168        11000 :                 assert_eq!(
    8169        11000 :                     tline.get(test_key, lsn, &ctx).await?,
    8170        11000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    8171            1 :                 );
    8172            1 :             }
    8173            1 : 
    8174           11 :             let mut cnt = 0;
    8175           11 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8176            1 : 
    8177        11000 :             for (key, value) in tline
    8178           11 :                 .get_vectored_impl(
    8179           11 :                     query,
    8180           11 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    8181           11 :                     &ctx,
    8182           11 :                 )
    8183           11 :                 .await?
    8184            1 :             {
    8185        11000 :                 let blknum = key.field6 as usize;
    8186        11000 :                 let value = value?;
    8187        11000 :                 assert!(blknum % STEP == 0);
    8188        11000 :                 let blknum = blknum / STEP;
    8189        11000 :                 assert_eq!(
    8190            1 :                     value,
    8191        11000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    8192            1 :                 );
    8193        11000 :                 cnt += 1;
    8194            1 :             }
    8195            1 : 
    8196           11 :             assert_eq!(cnt, NUM_KEYS);
    8197            1 : 
    8198        11011 :             for _ in 0..NUM_KEYS {
    8199        11000 :                 lsn = Lsn(lsn.0 + 0x10);
    8200        11000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8201        11000 :                 test_key.field6 = (blknum * STEP) as u32;
    8202        11000 :                 let mut writer = tline.writer().await;
    8203        11000 :                 writer
    8204        11000 :                     .put(
    8205        11000 :                         test_key,
    8206        11000 :                         lsn,
    8207        11000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8208        11000 :                         &ctx,
    8209        11000 :                     )
    8210        11000 :                     .await?;
    8211        11000 :                 writer.finish_write(lsn);
    8212        11000 :                 drop(writer);
    8213        11000 :                 updated[blknum] = lsn;
    8214            1 :             }
    8215            1 : 
    8216            1 :             // Perform two cycles of flush, compact, and GC
    8217           33 :             for round in 0..2 {
    8218           22 :                 tline.freeze_and_flush().await?;
    8219           22 :                 tline
    8220           22 :                     .compact(
    8221           22 :                         &cancel,
    8222           22 :                         if iter % 5 == 0 && round == 0 {
    8223            3 :                             let mut flags = EnumSet::new();
    8224            3 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8225            3 :                             flags.insert(CompactFlags::ForceRepartition);
    8226            3 :                             flags
    8227            1 :                         } else {
    8228           19 :                             EnumSet::empty()
    8229            1 :                         },
    8230           22 :                         &ctx,
    8231            1 :                     )
    8232           22 :                     .await?;
    8233           22 :                 tenant
    8234           22 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    8235           22 :                     .await?;
    8236            1 :             }
    8237            1 :         }
    8238            1 : 
    8239            1 :         Ok(())
    8240            1 :     }
    8241              : 
    8242              :     #[tokio::test]
    8243            1 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    8244            1 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    8245            1 :         let (tenant, ctx) = harness.load().await;
    8246            1 :         let tline = tenant
    8247            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8248            1 :             .await?;
    8249              : 
    8250            1 :         let cancel = CancellationToken::new();
    8251              : 
    8252            1 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8253            1 :         base_key.field1 = AUX_KEY_PREFIX;
    8254            1 :         let test_key = base_key;
    8255            1 :         let mut lsn = Lsn(0x10);
    8256              : 
    8257           21 :         for _ in 0..20 {
    8258           20 :             lsn = Lsn(lsn.0 + 0x10);
    8259           20 :             let mut writer = tline.writer().await;
    8260           20 :             writer
    8261           20 :                 .put(
    8262           20 :                     test_key,
    8263           20 :                     lsn,
    8264           20 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    8265           20 :                     &ctx,
    8266           20 :                 )
    8267           20 :                 .await?;
    8268           20 :             writer.finish_write(lsn);
    8269           20 :             drop(writer);
    8270           20 :             tline.freeze_and_flush().await?; // force create a delta layer
    8271              :         }
    8272              : 
    8273            1 :         let before_num_l0_delta_files = tline
    8274            1 :             .layers
    8275            1 :             .read(LayerManagerLockHolder::Testing)
    8276            1 :             .await
    8277            1 :             .layer_map()?
    8278            1 :             .level0_deltas()
    8279            1 :             .len();
    8280              : 
    8281            1 :         tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    8282              : 
    8283            1 :         let after_num_l0_delta_files = tline
    8284            1 :             .layers
    8285            1 :             .read(LayerManagerLockHolder::Testing)
    8286            1 :             .await
    8287            1 :             .layer_map()?
    8288            1 :             .level0_deltas()
    8289            1 :             .len();
    8290              : 
    8291            1 :         assert!(
    8292            1 :             after_num_l0_delta_files < before_num_l0_delta_files,
    8293            0 :             "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
    8294              :         );
    8295              : 
    8296            1 :         assert_eq!(
    8297            1 :             tline.get(test_key, lsn, &ctx).await?,
    8298            1 :             test_img(&format!("{} at {}", 0, lsn))
    8299              :         );
    8300              : 
    8301            2 :         Ok(())
    8302            1 :     }
    8303              : 
    8304              :     #[tokio::test]
    8305            1 :     async fn test_aux_file_e2e() {
    8306            1 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    8307              : 
    8308            1 :         let (tenant, ctx) = harness.load().await;
    8309            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8310              : 
    8311            1 :         let mut lsn = Lsn(0x08);
    8312              : 
    8313            1 :         let tline: Arc<Timeline> = tenant
    8314            1 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8315            1 :             .await
    8316            1 :             .unwrap();
    8317              : 
    8318              :         {
    8319            1 :             lsn += 8;
    8320            1 :             let mut modification = tline.begin_modification(lsn);
    8321            1 :             modification
    8322            1 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    8323            1 :                 .await
    8324            1 :                 .unwrap();
    8325            1 :             modification.commit(&ctx).await.unwrap();
    8326              :         }
    8327              : 
    8328              :         // we can read everything from the storage
    8329            1 :         let files = tline
    8330            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8331            1 :             .await
    8332            1 :             .unwrap();
    8333            1 :         assert_eq!(
    8334            1 :             files.get("pg_logical/mappings/test1"),
    8335            1 :             Some(&bytes::Bytes::from_static(b"first"))
    8336              :         );
    8337              : 
    8338              :         {
    8339            1 :             lsn += 8;
    8340            1 :             let mut modification = tline.begin_modification(lsn);
    8341            1 :             modification
    8342            1 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    8343            1 :                 .await
    8344            1 :                 .unwrap();
    8345            1 :             modification.commit(&ctx).await.unwrap();
    8346              :         }
    8347              : 
    8348            1 :         let files = tline
    8349            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8350            1 :             .await
    8351            1 :             .unwrap();
    8352            1 :         assert_eq!(
    8353            1 :             files.get("pg_logical/mappings/test2"),
    8354            1 :             Some(&bytes::Bytes::from_static(b"second"))
    8355              :         );
    8356              : 
    8357            1 :         let child = tenant
    8358            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    8359            1 :             .await
    8360            1 :             .unwrap();
    8361              : 
    8362            1 :         let files = child
    8363            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8364            1 :             .await
    8365            1 :             .unwrap();
    8366            1 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    8367            1 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    8368            1 :     }
    8369              : 
    8370              :     #[tokio::test]
    8371            1 :     async fn test_repl_origin_tombstones() {
    8372            1 :         let harness = TenantHarness::create("test_repl_origin_tombstones")
    8373            1 :             .await
    8374            1 :             .unwrap();
    8375              : 
    8376            1 :         let (tenant, ctx) = harness.load().await;
    8377            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8378              : 
    8379            1 :         let mut lsn = Lsn(0x08);
    8380              : 
    8381            1 :         let tline: Arc<Timeline> = tenant
    8382            1 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8383            1 :             .await
    8384            1 :             .unwrap();
    8385              : 
    8386            1 :         let repl_lsn = Lsn(0x10);
    8387              :         {
    8388            1 :             lsn += 8;
    8389            1 :             let mut modification = tline.begin_modification(lsn);
    8390            1 :             modification.put_for_unit_test(repl_origin_key(2), Value::Image(Bytes::new()));
    8391            1 :             modification.set_replorigin(1, repl_lsn).await.unwrap();
    8392            1 :             modification.commit(&ctx).await.unwrap();
    8393              :         }
    8394              : 
    8395              :         // we can read everything from the storage
    8396            1 :         let repl_origins = tline
    8397            1 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8398            1 :             .await
    8399            1 :             .unwrap();
    8400            1 :         assert_eq!(repl_origins.len(), 1);
    8401            1 :         assert_eq!(repl_origins[&1], lsn);
    8402              : 
    8403              :         {
    8404            1 :             lsn += 8;
    8405            1 :             let mut modification = tline.begin_modification(lsn);
    8406            1 :             modification.put_for_unit_test(
    8407            1 :                 repl_origin_key(3),
    8408            1 :                 Value::Image(Bytes::copy_from_slice(b"cannot_decode_this")),
    8409              :             );
    8410            1 :             modification.commit(&ctx).await.unwrap();
    8411              :         }
    8412            1 :         let result = tline
    8413            1 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8414            1 :             .await;
    8415            1 :         assert!(result.is_err());
    8416            1 :     }
    8417              : 
    8418              :     #[tokio::test]
    8419            1 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    8420            1 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    8421            1 :         let (tenant, ctx) = harness.load().await;
    8422            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8423            1 :         let tline = tenant
    8424            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8425            1 :             .await?;
    8426              : 
    8427              :         const NUM_KEYS: usize = 1000;
    8428              :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8429              : 
    8430            1 :         let cancel = CancellationToken::new();
    8431              : 
    8432            1 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8433            1 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8434            1 :         let mut test_key = base_key;
    8435            1 :         let mut lsn = Lsn(0x10);
    8436              : 
    8437            4 :         async fn scan_with_statistics(
    8438            4 :             tline: &Timeline,
    8439            4 :             keyspace: &KeySpace,
    8440            4 :             lsn: Lsn,
    8441            4 :             ctx: &RequestContext,
    8442            4 :             io_concurrency: IoConcurrency,
    8443            4 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    8444            4 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8445            4 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8446            4 :             let res = tline
    8447            4 :                 .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8448            4 :                 .await?;
    8449            4 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    8450            4 :         }
    8451              : 
    8452         1001 :         for blknum in 0..NUM_KEYS {
    8453         1000 :             lsn = Lsn(lsn.0 + 0x10);
    8454         1000 :             test_key.field6 = (blknum * STEP) as u32;
    8455         1000 :             let mut writer = tline.writer().await;
    8456         1000 :             writer
    8457         1000 :                 .put(
    8458         1000 :                     test_key,
    8459         1000 :                     lsn,
    8460         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8461         1000 :                     &ctx,
    8462         1000 :                 )
    8463         1000 :                 .await?;
    8464         1000 :             writer.finish_write(lsn);
    8465         1000 :             drop(writer);
    8466              :         }
    8467              : 
    8468            1 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8469              : 
    8470           11 :         for iter in 1..=10 {
    8471        10010 :             for _ in 0..NUM_KEYS {
    8472        10000 :                 lsn = Lsn(lsn.0 + 0x10);
    8473        10000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8474        10000 :                 test_key.field6 = (blknum * STEP) as u32;
    8475        10000 :                 let mut writer = tline.writer().await;
    8476        10000 :                 writer
    8477        10000 :                     .put(
    8478        10000 :                         test_key,
    8479        10000 :                         lsn,
    8480        10000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8481        10000 :                         &ctx,
    8482        10000 :                     )
    8483        10000 :                     .await?;
    8484        10000 :                 writer.finish_write(lsn);
    8485        10000 :                 drop(writer);
    8486            1 :             }
    8487            1 : 
    8488           10 :             tline.freeze_and_flush().await?;
    8489            1 :             // Force layers to L1
    8490           10 :             tline
    8491           10 :                 .compact(
    8492           10 :                     &cancel,
    8493           10 :                     {
    8494           10 :                         let mut flags = EnumSet::new();
    8495           10 :                         flags.insert(CompactFlags::ForceL0Compaction);
    8496           10 :                         flags
    8497           10 :                     },
    8498           10 :                     &ctx,
    8499           10 :                 )
    8500           10 :                 .await?;
    8501            1 : 
    8502           10 :             if iter % 5 == 0 {
    8503            2 :                 let scan_lsn = Lsn(lsn.0 + 1);
    8504            2 :                 info!("scanning at {}", scan_lsn);
    8505            2 :                 let (_, before_delta_file_accessed) =
    8506            2 :                     scan_with_statistics(&tline, &keyspace, scan_lsn, &ctx, io_concurrency.clone())
    8507            2 :                         .await?;
    8508            2 :                 tline
    8509            2 :                     .compact(
    8510            2 :                         &cancel,
    8511            2 :                         {
    8512            2 :                             let mut flags = EnumSet::new();
    8513            2 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8514            2 :                             flags.insert(CompactFlags::ForceRepartition);
    8515            2 :                             flags.insert(CompactFlags::ForceL0Compaction);
    8516            2 :                             flags
    8517            2 :                         },
    8518            2 :                         &ctx,
    8519            2 :                     )
    8520            2 :                     .await?;
    8521            2 :                 let (_, after_delta_file_accessed) =
    8522            2 :                     scan_with_statistics(&tline, &keyspace, scan_lsn, &ctx, io_concurrency.clone())
    8523            2 :                         .await?;
    8524            2 :                 assert!(
    8525            2 :                     after_delta_file_accessed < before_delta_file_accessed,
    8526            1 :                     "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
    8527            1 :                 );
    8528            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.
    8529            2 :                 assert!(
    8530            2 :                     after_delta_file_accessed <= 2,
    8531            1 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    8532            1 :                 );
    8533            8 :             }
    8534            1 :         }
    8535            1 : 
    8536            1 :         Ok(())
    8537            1 :     }
    8538              : 
    8539              :     #[tokio::test]
    8540            1 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    8541            1 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    8542            1 :         let (tenant, ctx) = harness.load().await;
    8543              : 
    8544            1 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8545            1 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    8546            1 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    8547              : 
    8548            1 :         let tline = tenant
    8549            1 :             .create_test_timeline_with_layers(
    8550            1 :                 TIMELINE_ID,
    8551            1 :                 Lsn(0x10),
    8552            1 :                 DEFAULT_PG_VERSION,
    8553            1 :                 &ctx,
    8554            1 :                 Vec::new(), // in-memory layers
    8555            1 :                 Vec::new(), // delta layers
    8556            1 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    8557            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
    8558            1 :             )
    8559            1 :             .await?;
    8560            1 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    8561              : 
    8562            1 :         let child = tenant
    8563            1 :             .branch_timeline_test_with_layers(
    8564            1 :                 &tline,
    8565            1 :                 NEW_TIMELINE_ID,
    8566            1 :                 Some(Lsn(0x20)),
    8567            1 :                 &ctx,
    8568            1 :                 Vec::new(), // delta layers
    8569            1 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    8570            1 :                 Lsn(0x30),
    8571            1 :             )
    8572            1 :             .await
    8573            1 :             .unwrap();
    8574              : 
    8575            1 :         let lsn = Lsn(0x30);
    8576              : 
    8577              :         // test vectored get on parent timeline
    8578            1 :         assert_eq!(
    8579            1 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8580            1 :             Some(test_img("data key 1"))
    8581              :         );
    8582            1 :         assert!(
    8583            1 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    8584            1 :                 .await
    8585            1 :                 .unwrap_err()
    8586            1 :                 .is_missing_key_error()
    8587              :         );
    8588            1 :         assert!(
    8589            1 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    8590            1 :                 .await
    8591            1 :                 .unwrap_err()
    8592            1 :                 .is_missing_key_error()
    8593              :         );
    8594              : 
    8595              :         // test vectored get on child timeline
    8596            1 :         assert_eq!(
    8597            1 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8598            1 :             Some(test_img("data key 1"))
    8599              :         );
    8600            1 :         assert_eq!(
    8601            1 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8602            1 :             Some(test_img("data key 2"))
    8603              :         );
    8604            1 :         assert!(
    8605            1 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    8606            1 :                 .await
    8607            1 :                 .unwrap_err()
    8608            1 :                 .is_missing_key_error()
    8609              :         );
    8610              : 
    8611            2 :         Ok(())
    8612            1 :     }
    8613              : 
    8614              :     #[tokio::test]
    8615            1 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    8616            1 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    8617            1 :         let (tenant, ctx) = harness.load().await;
    8618            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8619              : 
    8620            1 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8621            1 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8622            1 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8623            1 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8624              : 
    8625            1 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    8626            1 :         let base_inherited_key_child =
    8627            1 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    8628            1 :         let base_inherited_key_nonexist =
    8629            1 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    8630            1 :         let base_inherited_key_overwrite =
    8631            1 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    8632              : 
    8633            1 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8634            1 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    8635              : 
    8636            1 :         let tline = tenant
    8637            1 :             .create_test_timeline_with_layers(
    8638            1 :                 TIMELINE_ID,
    8639            1 :                 Lsn(0x10),
    8640            1 :                 DEFAULT_PG_VERSION,
    8641            1 :                 &ctx,
    8642            1 :                 Vec::new(), // in-memory layers
    8643            1 :                 Vec::new(), // delta layers
    8644            1 :                 vec![(
    8645            1 :                     Lsn(0x20),
    8646            1 :                     vec![
    8647            1 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    8648            1 :                         (
    8649            1 :                             base_inherited_key_overwrite,
    8650            1 :                             test_img("metadata key overwrite 1a"),
    8651            1 :                         ),
    8652            1 :                         (base_key, test_img("metadata key 1")),
    8653            1 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8654            1 :                     ],
    8655            1 :                 )], // image layers
    8656            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
    8657            1 :             )
    8658            1 :             .await?;
    8659              : 
    8660            1 :         let child = tenant
    8661            1 :             .branch_timeline_test_with_layers(
    8662            1 :                 &tline,
    8663            1 :                 NEW_TIMELINE_ID,
    8664            1 :                 Some(Lsn(0x20)),
    8665            1 :                 &ctx,
    8666            1 :                 Vec::new(), // delta layers
    8667            1 :                 vec![(
    8668            1 :                     Lsn(0x30),
    8669            1 :                     vec![
    8670            1 :                         (
    8671            1 :                             base_inherited_key_child,
    8672            1 :                             test_img("metadata inherited key 2"),
    8673            1 :                         ),
    8674            1 :                         (
    8675            1 :                             base_inherited_key_overwrite,
    8676            1 :                             test_img("metadata key overwrite 2a"),
    8677            1 :                         ),
    8678            1 :                         (base_key_child, test_img("metadata key 2")),
    8679            1 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8680            1 :                     ],
    8681            1 :                 )], // image layers
    8682            1 :                 Lsn(0x30),
    8683            1 :             )
    8684            1 :             .await
    8685            1 :             .unwrap();
    8686              : 
    8687            1 :         let lsn = Lsn(0x30);
    8688              : 
    8689              :         // test vectored get on parent timeline
    8690            1 :         assert_eq!(
    8691            1 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8692            1 :             Some(test_img("metadata key 1"))
    8693              :         );
    8694            1 :         assert_eq!(
    8695            1 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8696              :             None
    8697              :         );
    8698            1 :         assert_eq!(
    8699            1 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8700              :             None
    8701              :         );
    8702            1 :         assert_eq!(
    8703            1 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8704            1 :             Some(test_img("metadata key overwrite 1b"))
    8705              :         );
    8706            1 :         assert_eq!(
    8707            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8708            1 :             Some(test_img("metadata inherited key 1"))
    8709              :         );
    8710            1 :         assert_eq!(
    8711            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8712              :             None
    8713              :         );
    8714            1 :         assert_eq!(
    8715            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8716              :             None
    8717              :         );
    8718            1 :         assert_eq!(
    8719            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8720            1 :             Some(test_img("metadata key overwrite 1a"))
    8721              :         );
    8722              : 
    8723              :         // test vectored get on child timeline
    8724            1 :         assert_eq!(
    8725            1 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8726              :             None
    8727              :         );
    8728            1 :         assert_eq!(
    8729            1 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8730            1 :             Some(test_img("metadata key 2"))
    8731              :         );
    8732            1 :         assert_eq!(
    8733            1 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8734              :             None
    8735              :         );
    8736            1 :         assert_eq!(
    8737            1 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8738            1 :             Some(test_img("metadata inherited key 1"))
    8739              :         );
    8740            1 :         assert_eq!(
    8741            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8742            1 :             Some(test_img("metadata inherited key 2"))
    8743              :         );
    8744            1 :         assert_eq!(
    8745            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8746              :             None
    8747              :         );
    8748            1 :         assert_eq!(
    8749            1 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8750            1 :             Some(test_img("metadata key overwrite 2b"))
    8751              :         );
    8752            1 :         assert_eq!(
    8753            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8754            1 :             Some(test_img("metadata key overwrite 2a"))
    8755              :         );
    8756              : 
    8757              :         // test vectored scan on parent timeline
    8758            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8759            1 :         let query =
    8760            1 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8761            1 :         let res = tline
    8762            1 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8763            1 :             .await?;
    8764              : 
    8765            1 :         assert_eq!(
    8766            1 :             res.into_iter()
    8767            4 :                 .map(|(k, v)| (k, v.unwrap()))
    8768            1 :                 .collect::<Vec<_>>(),
    8769            1 :             vec![
    8770            1 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8771            1 :                 (
    8772            1 :                     base_inherited_key_overwrite,
    8773            1 :                     test_img("metadata key overwrite 1a")
    8774            1 :                 ),
    8775            1 :                 (base_key, test_img("metadata key 1")),
    8776            1 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8777              :             ]
    8778              :         );
    8779              : 
    8780              :         // test vectored scan on child timeline
    8781            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8782            1 :         let query =
    8783            1 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8784            1 :         let res = child
    8785            1 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8786            1 :             .await?;
    8787              : 
    8788            1 :         assert_eq!(
    8789            1 :             res.into_iter()
    8790            5 :                 .map(|(k, v)| (k, v.unwrap()))
    8791            1 :                 .collect::<Vec<_>>(),
    8792            1 :             vec![
    8793            1 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8794            1 :                 (
    8795            1 :                     base_inherited_key_child,
    8796            1 :                     test_img("metadata inherited key 2")
    8797            1 :                 ),
    8798            1 :                 (
    8799            1 :                     base_inherited_key_overwrite,
    8800            1 :                     test_img("metadata key overwrite 2a")
    8801            1 :                 ),
    8802            1 :                 (base_key_child, test_img("metadata key 2")),
    8803            1 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8804              :             ]
    8805              :         );
    8806              : 
    8807            2 :         Ok(())
    8808            1 :     }
    8809              : 
    8810           28 :     async fn get_vectored_impl_wrapper(
    8811           28 :         tline: &Arc<Timeline>,
    8812           28 :         key: Key,
    8813           28 :         lsn: Lsn,
    8814           28 :         ctx: &RequestContext,
    8815           28 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8816           28 :         let io_concurrency = IoConcurrency::spawn_from_conf(
    8817           28 :             tline.conf.get_vectored_concurrent_io,
    8818           28 :             tline.gate.enter().unwrap(),
    8819              :         );
    8820           28 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8821           28 :         let query = VersionedKeySpaceQuery::uniform(KeySpace::single(key..key.next()), lsn);
    8822           28 :         let mut res = tline
    8823           28 :             .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8824           28 :             .await?;
    8825           25 :         Ok(res.pop_last().map(|(k, v)| {
    8826           16 :             assert_eq!(k, key);
    8827           16 :             v.unwrap()
    8828           16 :         }))
    8829           28 :     }
    8830              : 
    8831              :     #[tokio::test]
    8832            1 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8833            1 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8834            1 :         let (tenant, ctx) = harness.load().await;
    8835            1 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8836            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8837            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8838            1 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8839              : 
    8840              :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8841              :         // Lsn 0x30 key0, key3, no key1+key2
    8842              :         // Lsn 0x20 key1+key2 tomestones
    8843              :         // Lsn 0x10 key1 in image, key2 in delta
    8844            1 :         let tline = tenant
    8845            1 :             .create_test_timeline_with_layers(
    8846            1 :                 TIMELINE_ID,
    8847            1 :                 Lsn(0x10),
    8848            1 :                 DEFAULT_PG_VERSION,
    8849            1 :                 &ctx,
    8850            1 :                 Vec::new(), // in-memory layers
    8851            1 :                 // delta layers
    8852            1 :                 vec![
    8853            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8854            1 :                         Lsn(0x10)..Lsn(0x20),
    8855            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8856            1 :                     ),
    8857            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8858            1 :                         Lsn(0x20)..Lsn(0x30),
    8859            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8860            1 :                     ),
    8861            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8862            1 :                         Lsn(0x20)..Lsn(0x30),
    8863            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8864            1 :                     ),
    8865            1 :                 ],
    8866            1 :                 // image layers
    8867            1 :                 vec![
    8868            1 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8869            1 :                     (
    8870            1 :                         Lsn(0x30),
    8871            1 :                         vec![
    8872            1 :                             (key0, test_img("metadata key 0")),
    8873            1 :                             (key3, test_img("metadata key 3")),
    8874            1 :                         ],
    8875            1 :                     ),
    8876            1 :                 ],
    8877            1 :                 Lsn(0x30),
    8878            1 :             )
    8879            1 :             .await?;
    8880              : 
    8881            1 :         let lsn = Lsn(0x30);
    8882            1 :         let old_lsn = Lsn(0x20);
    8883              : 
    8884            1 :         assert_eq!(
    8885            1 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8886            1 :             Some(test_img("metadata key 0"))
    8887              :         );
    8888            1 :         assert_eq!(
    8889            1 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8890              :             None,
    8891              :         );
    8892            1 :         assert_eq!(
    8893            1 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8894              :             None,
    8895              :         );
    8896            1 :         assert_eq!(
    8897            1 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8898            1 :             Some(Bytes::new()),
    8899              :         );
    8900            1 :         assert_eq!(
    8901            1 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8902            1 :             Some(Bytes::new()),
    8903              :         );
    8904            1 :         assert_eq!(
    8905            1 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8906            1 :             Some(test_img("metadata key 3"))
    8907              :         );
    8908              : 
    8909            2 :         Ok(())
    8910            1 :     }
    8911              : 
    8912              :     #[tokio::test]
    8913            1 :     async fn test_metadata_tombstone_image_creation() {
    8914            1 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8915            1 :             .await
    8916            1 :             .unwrap();
    8917            1 :         let (tenant, ctx) = harness.load().await;
    8918            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8919              : 
    8920            1 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8921            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8922            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8923            1 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8924              : 
    8925            1 :         let tline = tenant
    8926            1 :             .create_test_timeline_with_layers(
    8927            1 :                 TIMELINE_ID,
    8928            1 :                 Lsn(0x10),
    8929            1 :                 DEFAULT_PG_VERSION,
    8930            1 :                 &ctx,
    8931            1 :                 Vec::new(), // in-memory layers
    8932            1 :                 // delta layers
    8933            1 :                 vec![
    8934            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8935            1 :                         Lsn(0x10)..Lsn(0x20),
    8936            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8937            1 :                     ),
    8938            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8939            1 :                         Lsn(0x20)..Lsn(0x30),
    8940            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8941            1 :                     ),
    8942            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8943            1 :                         Lsn(0x20)..Lsn(0x30),
    8944            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8945            1 :                     ),
    8946            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8947            1 :                         Lsn(0x30)..Lsn(0x40),
    8948            1 :                         vec![
    8949            1 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8950            1 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8951            1 :                         ],
    8952            1 :                     ),
    8953            1 :                 ],
    8954            1 :                 // image layers
    8955            1 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8956            1 :                 Lsn(0x40),
    8957            1 :             )
    8958            1 :             .await
    8959            1 :             .unwrap();
    8960              : 
    8961            1 :         let cancel = CancellationToken::new();
    8962              : 
    8963              :         // Image layer creation happens on the disk_consistent_lsn so we need to force set it now.
    8964            1 :         tline.force_set_disk_consistent_lsn(Lsn(0x40));
    8965            1 :         tline
    8966            1 :             .compact(
    8967            1 :                 &cancel,
    8968            1 :                 {
    8969            1 :                     let mut flags = EnumSet::new();
    8970            1 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8971            1 :                     flags.insert(CompactFlags::ForceRepartition);
    8972            1 :                     flags
    8973            1 :                 },
    8974            1 :                 &ctx,
    8975            1 :             )
    8976            1 :             .await
    8977            1 :             .unwrap();
    8978              :         // Image layers are created at repartition LSN
    8979            1 :         let images = tline
    8980            1 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    8981            1 :             .await
    8982            1 :             .unwrap()
    8983            1 :             .into_iter()
    8984            9 :             .filter(|(k, _)| k.is_metadata_key())
    8985            1 :             .collect::<Vec<_>>();
    8986            1 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8987            1 :     }
    8988              : 
    8989              :     #[tokio::test]
    8990            1 :     async fn test_metadata_tombstone_empty_image_creation() {
    8991            1 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8992            1 :             .await
    8993            1 :             .unwrap();
    8994            1 :         let (tenant, ctx) = harness.load().await;
    8995            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8996              : 
    8997            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8998            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8999              : 
    9000            1 :         let tline = tenant
    9001            1 :             .create_test_timeline_with_layers(
    9002            1 :                 TIMELINE_ID,
    9003            1 :                 Lsn(0x10),
    9004            1 :                 DEFAULT_PG_VERSION,
    9005            1 :                 &ctx,
    9006            1 :                 Vec::new(), // in-memory layers
    9007            1 :                 // delta layers
    9008            1 :                 vec![
    9009            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9010            1 :                         Lsn(0x10)..Lsn(0x20),
    9011            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    9012            1 :                     ),
    9013            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9014            1 :                         Lsn(0x20)..Lsn(0x30),
    9015            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    9016            1 :                     ),
    9017            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9018            1 :                         Lsn(0x20)..Lsn(0x30),
    9019            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    9020            1 :                     ),
    9021            1 :                 ],
    9022            1 :                 // image layers
    9023            1 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    9024            1 :                 Lsn(0x30),
    9025            1 :             )
    9026            1 :             .await
    9027            1 :             .unwrap();
    9028              : 
    9029            1 :         let cancel = CancellationToken::new();
    9030              : 
    9031            1 :         tline
    9032            1 :             .compact(
    9033            1 :                 &cancel,
    9034            1 :                 {
    9035            1 :                     let mut flags = EnumSet::new();
    9036            1 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    9037            1 :                     flags.insert(CompactFlags::ForceRepartition);
    9038            1 :                     flags
    9039            1 :                 },
    9040            1 :                 &ctx,
    9041            1 :             )
    9042            1 :             .await
    9043            1 :             .unwrap();
    9044              : 
    9045              :         // Image layers are created at last_record_lsn
    9046            1 :         let images = tline
    9047            1 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    9048            1 :             .await
    9049            1 :             .unwrap()
    9050            1 :             .into_iter()
    9051            7 :             .filter(|(k, _)| k.is_metadata_key())
    9052            1 :             .collect::<Vec<_>>();
    9053            1 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    9054            1 :     }
    9055              : 
    9056              :     #[tokio::test]
    9057            1 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    9058            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    9059            1 :         let (tenant, ctx) = harness.load().await;
    9060            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    9061              : 
    9062           51 :         fn get_key(id: u32) -> Key {
    9063              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9064           51 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9065           51 :             key.field6 = id;
    9066           51 :             key
    9067           51 :         }
    9068              : 
    9069              :         // We create
    9070              :         // - one bottom-most image layer,
    9071              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9072              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9073              :         // - a delta layer D3 above the horizon.
    9074              :         //
    9075              :         //                             | D3 |
    9076              :         //  | D1 |
    9077              :         // -|    |-- gc horizon -----------------
    9078              :         //  |    |                | D2 |
    9079              :         // --------- img layer ------------------
    9080              :         //
    9081              :         // What we should expact from this compaction is:
    9082              :         //                             | D3 |
    9083              :         //  | Part of D1 |
    9084              :         // --------- img layer with D1+D2 at GC horizon------------------
    9085              : 
    9086              :         // img layer at 0x10
    9087            1 :         let img_layer = (0..10)
    9088           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9089            1 :             .collect_vec();
    9090              : 
    9091            1 :         let delta1 = vec![
    9092            1 :             (
    9093            1 :                 get_key(1),
    9094            1 :                 Lsn(0x20),
    9095            1 :                 Value::Image(Bytes::from("value 1@0x20")),
    9096            1 :             ),
    9097            1 :             (
    9098            1 :                 get_key(2),
    9099            1 :                 Lsn(0x30),
    9100            1 :                 Value::Image(Bytes::from("value 2@0x30")),
    9101            1 :             ),
    9102            1 :             (
    9103            1 :                 get_key(3),
    9104            1 :                 Lsn(0x40),
    9105            1 :                 Value::Image(Bytes::from("value 3@0x40")),
    9106            1 :             ),
    9107              :         ];
    9108            1 :         let delta2 = vec![
    9109            1 :             (
    9110            1 :                 get_key(5),
    9111            1 :                 Lsn(0x20),
    9112            1 :                 Value::Image(Bytes::from("value 5@0x20")),
    9113            1 :             ),
    9114            1 :             (
    9115            1 :                 get_key(6),
    9116            1 :                 Lsn(0x20),
    9117            1 :                 Value::Image(Bytes::from("value 6@0x20")),
    9118            1 :             ),
    9119              :         ];
    9120            1 :         let delta3 = vec![
    9121            1 :             (
    9122            1 :                 get_key(8),
    9123            1 :                 Lsn(0x48),
    9124            1 :                 Value::Image(Bytes::from("value 8@0x48")),
    9125            1 :             ),
    9126            1 :             (
    9127            1 :                 get_key(9),
    9128            1 :                 Lsn(0x48),
    9129            1 :                 Value::Image(Bytes::from("value 9@0x48")),
    9130            1 :             ),
    9131              :         ];
    9132              : 
    9133            1 :         let tline = tenant
    9134            1 :             .create_test_timeline_with_layers(
    9135            1 :                 TIMELINE_ID,
    9136            1 :                 Lsn(0x10),
    9137            1 :                 DEFAULT_PG_VERSION,
    9138            1 :                 &ctx,
    9139            1 :                 Vec::new(), // in-memory layers
    9140            1 :                 vec![
    9141            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9142            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9143            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9144            1 :                 ], // delta layers
    9145            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9146            1 :                 Lsn(0x50),
    9147            1 :             )
    9148            1 :             .await?;
    9149              :         {
    9150            1 :             tline
    9151            1 :                 .applied_gc_cutoff_lsn
    9152            1 :                 .lock_for_write()
    9153            1 :                 .store_and_unlock(Lsn(0x30))
    9154            1 :                 .wait()
    9155            1 :                 .await;
    9156              :             // Update GC info
    9157            1 :             let mut guard = tline.gc_info.write().unwrap();
    9158            1 :             guard.cutoffs.time = Some(Lsn(0x30));
    9159            1 :             guard.cutoffs.space = Lsn(0x30);
    9160              :         }
    9161              : 
    9162            1 :         let expected_result = [
    9163            1 :             Bytes::from_static(b"value 0@0x10"),
    9164            1 :             Bytes::from_static(b"value 1@0x20"),
    9165            1 :             Bytes::from_static(b"value 2@0x30"),
    9166            1 :             Bytes::from_static(b"value 3@0x40"),
    9167            1 :             Bytes::from_static(b"value 4@0x10"),
    9168            1 :             Bytes::from_static(b"value 5@0x20"),
    9169            1 :             Bytes::from_static(b"value 6@0x20"),
    9170            1 :             Bytes::from_static(b"value 7@0x10"),
    9171            1 :             Bytes::from_static(b"value 8@0x48"),
    9172            1 :             Bytes::from_static(b"value 9@0x48"),
    9173            1 :         ];
    9174              : 
    9175           10 :         for (idx, expected) in expected_result.iter().enumerate() {
    9176           10 :             assert_eq!(
    9177           10 :                 tline
    9178           10 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9179           10 :                     .await
    9180           10 :                     .unwrap(),
    9181              :                 expected
    9182              :             );
    9183              :         }
    9184              : 
    9185            1 :         let cancel = CancellationToken::new();
    9186            1 :         tline
    9187            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9188            1 :             .await
    9189            1 :             .unwrap();
    9190              : 
    9191           10 :         for (idx, expected) in expected_result.iter().enumerate() {
    9192           10 :             assert_eq!(
    9193           10 :                 tline
    9194           10 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9195           10 :                     .await
    9196           10 :                     .unwrap(),
    9197              :                 expected
    9198              :             );
    9199              :         }
    9200              : 
    9201              :         // Check if the image layer at the GC horizon contains exactly what we want
    9202            1 :         let image_at_gc_horizon = tline
    9203            1 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    9204            1 :             .await
    9205            1 :             .unwrap()
    9206            1 :             .into_iter()
    9207           17 :             .filter(|(k, _)| k.is_metadata_key())
    9208            1 :             .collect::<Vec<_>>();
    9209              : 
    9210            1 :         assert_eq!(image_at_gc_horizon.len(), 10);
    9211            1 :         let expected_result = [
    9212            1 :             Bytes::from_static(b"value 0@0x10"),
    9213            1 :             Bytes::from_static(b"value 1@0x20"),
    9214            1 :             Bytes::from_static(b"value 2@0x30"),
    9215            1 :             Bytes::from_static(b"value 3@0x10"),
    9216            1 :             Bytes::from_static(b"value 4@0x10"),
    9217            1 :             Bytes::from_static(b"value 5@0x20"),
    9218            1 :             Bytes::from_static(b"value 6@0x20"),
    9219            1 :             Bytes::from_static(b"value 7@0x10"),
    9220            1 :             Bytes::from_static(b"value 8@0x10"),
    9221            1 :             Bytes::from_static(b"value 9@0x10"),
    9222            1 :         ];
    9223           11 :         for idx in 0..10 {
    9224           10 :             assert_eq!(
    9225           10 :                 image_at_gc_horizon[idx],
    9226           10 :                 (get_key(idx as u32), expected_result[idx].clone())
    9227              :             );
    9228              :         }
    9229              : 
    9230              :         // Check if old layers are removed / new layers have the expected LSN
    9231            1 :         let all_layers = inspect_and_sort(&tline, None).await;
    9232            1 :         assert_eq!(
    9233              :             all_layers,
    9234            1 :             vec![
    9235              :                 // Image layer at GC horizon
    9236            1 :                 PersistentLayerKey {
    9237            1 :                     key_range: Key::MIN..Key::MAX,
    9238            1 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    9239            1 :                     is_delta: false
    9240            1 :                 },
    9241              :                 // The delta layer below the horizon
    9242            1 :                 PersistentLayerKey {
    9243            1 :                     key_range: get_key(3)..get_key(4),
    9244            1 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    9245            1 :                     is_delta: true
    9246            1 :                 },
    9247              :                 // The delta3 layer that should not be picked for the compaction
    9248            1 :                 PersistentLayerKey {
    9249            1 :                     key_range: get_key(8)..get_key(10),
    9250            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9251            1 :                     is_delta: true
    9252            1 :                 }
    9253              :             ]
    9254              :         );
    9255              : 
    9256              :         // increase GC horizon and compact again
    9257              :         {
    9258            1 :             tline
    9259            1 :                 .applied_gc_cutoff_lsn
    9260            1 :                 .lock_for_write()
    9261            1 :                 .store_and_unlock(Lsn(0x40))
    9262            1 :                 .wait()
    9263            1 :                 .await;
    9264              :             // Update GC info
    9265            1 :             let mut guard = tline.gc_info.write().unwrap();
    9266            1 :             guard.cutoffs.time = Some(Lsn(0x40));
    9267            1 :             guard.cutoffs.space = Lsn(0x40);
    9268              :         }
    9269            1 :         tline
    9270            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9271            1 :             .await
    9272            1 :             .unwrap();
    9273              : 
    9274            2 :         Ok(())
    9275            1 :     }
    9276              : 
    9277              :     #[cfg(feature = "testing")]
    9278              :     #[tokio::test]
    9279            1 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    9280            1 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    9281            1 :         let (tenant, ctx) = harness.load().await;
    9282              : 
    9283           17 :         fn get_key(id: u32) -> Key {
    9284              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9285           17 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9286           17 :             key.field6 = id;
    9287           17 :             key
    9288           17 :         }
    9289              : 
    9290            1 :         let delta1 = vec![
    9291            1 :             (
    9292            1 :                 get_key(1),
    9293            1 :                 Lsn(0x20),
    9294            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9295            1 :             ),
    9296            1 :             (
    9297            1 :                 get_key(1),
    9298            1 :                 Lsn(0x30),
    9299            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9300            1 :             ),
    9301            1 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    9302            1 :             (
    9303            1 :                 get_key(2),
    9304            1 :                 Lsn(0x20),
    9305            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9306            1 :             ),
    9307            1 :             (
    9308            1 :                 get_key(2),
    9309            1 :                 Lsn(0x30),
    9310            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9311            1 :             ),
    9312            1 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    9313            1 :             (
    9314            1 :                 get_key(3),
    9315            1 :                 Lsn(0x20),
    9316            1 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    9317            1 :             ),
    9318            1 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    9319            1 :             (
    9320            1 :                 get_key(4),
    9321            1 :                 Lsn(0x20),
    9322            1 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    9323            1 :             ),
    9324            1 :             (
    9325            1 :                 get_key(4),
    9326            1 :                 Lsn(0x30),
    9327            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "i")),
    9328            1 :             ),
    9329            1 :             (
    9330            1 :                 get_key(5),
    9331            1 :                 Lsn(0x20),
    9332            1 :                 Value::WalRecord(NeonWalRecord::wal_init("1")),
    9333            1 :             ),
    9334            1 :             (
    9335            1 :                 get_key(5),
    9336            1 :                 Lsn(0x30),
    9337            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "2")),
    9338            1 :             ),
    9339              :         ];
    9340            1 :         let image1 = vec![(get_key(1), "0x10".into())];
    9341              : 
    9342            1 :         let tline = tenant
    9343            1 :             .create_test_timeline_with_layers(
    9344            1 :                 TIMELINE_ID,
    9345            1 :                 Lsn(0x10),
    9346            1 :                 DEFAULT_PG_VERSION,
    9347            1 :                 &ctx,
    9348            1 :                 Vec::new(), // in-memory layers
    9349            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9350            1 :                     Lsn(0x10)..Lsn(0x40),
    9351            1 :                     delta1,
    9352            1 :                 )], // delta layers
    9353            1 :                 vec![(Lsn(0x10), image1)], // image layers
    9354            1 :                 Lsn(0x50),
    9355            1 :             )
    9356            1 :             .await?;
    9357              : 
    9358            1 :         assert_eq!(
    9359            1 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    9360            1 :             Bytes::from_static(b"0x10,0x20,0x30")
    9361              :         );
    9362            1 :         assert_eq!(
    9363            1 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    9364            1 :             Bytes::from_static(b"0x10,0x20,0x30")
    9365              :         );
    9366              : 
    9367              :         // Need to remove the limit of "Neon WAL redo requires base image".
    9368              : 
    9369            1 :         assert_eq!(
    9370            1 :             tline.get(get_key(3), Lsn(0x50), &ctx).await?,
    9371            1 :             Bytes::from_static(b"c")
    9372              :         );
    9373            1 :         assert_eq!(
    9374            1 :             tline.get(get_key(4), Lsn(0x50), &ctx).await?,
    9375            1 :             Bytes::from_static(b"ij")
    9376              :         );
    9377              : 
    9378              :         // Manual testing required: currently, read errors will panic the process in debug mode. So we
    9379              :         // cannot enable this assertion in the unit test.
    9380              :         // assert!(tline.get(get_key(5), Lsn(0x50), &ctx).await.is_err());
    9381              : 
    9382            2 :         Ok(())
    9383            1 :     }
    9384              : 
    9385              :     #[tokio::test]
    9386            1 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    9387            1 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    9388            1 :             .await
    9389            1 :             .unwrap()
    9390            1 :             .load()
    9391            1 :             .await;
    9392              :         // set a non-zero lease length to test the feature
    9393            1 :         tenant
    9394            1 :             .update_tenant_config(|mut conf| {
    9395            1 :                 conf.lsn_lease_length = Some(LsnLease::DEFAULT_LENGTH);
    9396            1 :                 Ok(conf)
    9397            1 :             })
    9398            1 :             .unwrap();
    9399              : 
    9400            1 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9401              : 
    9402            1 :         let end_lsn = Lsn(0x100);
    9403            1 :         let image_layers = (0x20..=0x90)
    9404            1 :             .step_by(0x10)
    9405            8 :             .map(|n| (Lsn(n), vec![(key, test_img(&format!("data key at {n:x}")))]))
    9406            1 :             .collect();
    9407              : 
    9408            1 :         let timeline = tenant
    9409            1 :             .create_test_timeline_with_layers(
    9410            1 :                 TIMELINE_ID,
    9411            1 :                 Lsn(0x10),
    9412            1 :                 DEFAULT_PG_VERSION,
    9413            1 :                 &ctx,
    9414            1 :                 Vec::new(), // in-memory layers
    9415            1 :                 Vec::new(),
    9416            1 :                 image_layers,
    9417            1 :                 end_lsn,
    9418            1 :             )
    9419            1 :             .await?;
    9420              : 
    9421            1 :         let leased_lsns = [0x30, 0x50, 0x70];
    9422            1 :         let mut leases = Vec::new();
    9423            3 :         leased_lsns.iter().for_each(|n| {
    9424            3 :             leases.push(
    9425            3 :                 timeline
    9426            3 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    9427            3 :                     .expect("lease request should succeed"),
    9428              :             );
    9429            3 :         });
    9430              : 
    9431            1 :         let updated_lease_0 = timeline
    9432            1 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    9433            1 :             .expect("lease renewal should succeed");
    9434            1 :         assert_eq!(
    9435            1 :             updated_lease_0.valid_until, leases[0].valid_until,
    9436            0 :             " Renewing with shorter lease should not change the lease."
    9437              :         );
    9438              : 
    9439            1 :         let updated_lease_1 = timeline
    9440            1 :             .renew_lsn_lease(
    9441            1 :                 Lsn(leased_lsns[1]),
    9442            1 :                 timeline.get_lsn_lease_length() * 2,
    9443            1 :                 &ctx,
    9444            1 :             )
    9445            1 :             .expect("lease renewal should succeed");
    9446            1 :         assert!(
    9447            1 :             updated_lease_1.valid_until > leases[1].valid_until,
    9448            0 :             "Renewing with a long lease should renew lease with later expiration time."
    9449              :         );
    9450              : 
    9451              :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    9452            1 :         info!(
    9453            0 :             "applied_gc_cutoff_lsn: {}",
    9454            0 :             *timeline.get_applied_gc_cutoff_lsn()
    9455              :         );
    9456            1 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    9457              : 
    9458            1 :         let res = tenant
    9459            1 :             .gc_iteration(
    9460            1 :                 Some(TIMELINE_ID),
    9461            1 :                 0,
    9462            1 :                 Duration::ZERO,
    9463            1 :                 &CancellationToken::new(),
    9464            1 :                 &ctx,
    9465            1 :             )
    9466            1 :             .await
    9467            1 :             .unwrap();
    9468              : 
    9469              :         // Keeping everything <= Lsn(0x80) b/c leases:
    9470              :         // 0/10: initdb layer
    9471              :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    9472            1 :         assert_eq!(res.layers_needed_by_leases, 7);
    9473              :         // Keeping 0/90 b/c it is the latest layer.
    9474            1 :         assert_eq!(res.layers_not_updated, 1);
    9475              :         // Removed 0/80.
    9476            1 :         assert_eq!(res.layers_removed, 1);
    9477              : 
    9478              :         // Make lease on a already GC-ed LSN.
    9479              :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    9480            1 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    9481            1 :         timeline
    9482            1 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    9483            1 :             .expect_err("lease request on GC-ed LSN should fail");
    9484              : 
    9485              :         // Should still be able to renew a currently valid lease
    9486              :         // Assumption: original lease to is still valid for 0/50.
    9487              :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    9488            1 :         timeline
    9489            1 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    9490            1 :             .expect("lease renewal with validation should succeed");
    9491              : 
    9492            2 :         Ok(())
    9493            1 :     }
    9494              : 
    9495              :     #[tokio::test]
    9496            1 :     async fn test_failed_flush_should_not_update_disk_consistent_lsn() -> anyhow::Result<()> {
    9497              :         //
    9498              :         // Setup
    9499              :         //
    9500            1 :         let harness = TenantHarness::create_custom(
    9501            1 :             "test_failed_flush_should_not_upload_disk_consistent_lsn",
    9502            1 :             pageserver_api::models::TenantConfig::default(),
    9503            1 :             TenantId::generate(),
    9504            1 :             ShardIdentity::new(ShardNumber(0), ShardCount(4), ShardStripeSize(128)).unwrap(),
    9505            1 :             Generation::new(1),
    9506            1 :         )
    9507            1 :         .await?;
    9508            1 :         let (tenant, ctx) = harness.load().await;
    9509              : 
    9510            1 :         let timeline = tenant
    9511            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9512            1 :             .await?;
    9513            1 :         assert_eq!(timeline.get_shard_identity().count, ShardCount(4));
    9514            1 :         let mut writer = timeline.writer().await;
    9515            1 :         writer
    9516            1 :             .put(
    9517            1 :                 *TEST_KEY,
    9518            1 :                 Lsn(0x20),
    9519            1 :                 &Value::Image(test_img("foo at 0x20")),
    9520            1 :                 &ctx,
    9521            1 :             )
    9522            1 :             .await?;
    9523            1 :         writer.finish_write(Lsn(0x20));
    9524            1 :         drop(writer);
    9525            1 :         timeline.freeze_and_flush().await.unwrap();
    9526              : 
    9527            1 :         timeline.remote_client.wait_completion().await.unwrap();
    9528            1 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    9529            1 :         let remote_consistent_lsn = timeline.get_remote_consistent_lsn_projected();
    9530            1 :         assert_eq!(Some(disk_consistent_lsn), remote_consistent_lsn);
    9531              : 
    9532              :         //
    9533              :         // Test
    9534              :         //
    9535              : 
    9536            1 :         let mut writer = timeline.writer().await;
    9537            1 :         writer
    9538            1 :             .put(
    9539            1 :                 *TEST_KEY,
    9540            1 :                 Lsn(0x30),
    9541            1 :                 &Value::Image(test_img("foo at 0x30")),
    9542            1 :                 &ctx,
    9543            1 :             )
    9544            1 :             .await?;
    9545            1 :         writer.finish_write(Lsn(0x30));
    9546            1 :         drop(writer);
    9547              : 
    9548            1 :         fail::cfg(
    9549              :             "flush-layer-before-update-remote-consistent-lsn",
    9550            1 :             "return()",
    9551              :         )
    9552            1 :         .unwrap();
    9553              : 
    9554            1 :         let flush_res = timeline.freeze_and_flush().await;
    9555              :         // if flush failed, the disk/remote consistent LSN should not be updated
    9556            1 :         assert!(flush_res.is_err());
    9557            1 :         assert_eq!(disk_consistent_lsn, timeline.get_disk_consistent_lsn());
    9558            1 :         assert_eq!(
    9559              :             remote_consistent_lsn,
    9560            1 :             timeline.get_remote_consistent_lsn_projected()
    9561              :         );
    9562              : 
    9563            2 :         Ok(())
    9564            1 :     }
    9565              : 
    9566              :     #[cfg(feature = "testing")]
    9567              :     #[tokio::test]
    9568            1 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    9569            2 :         test_simple_bottom_most_compaction_deltas_helper(
    9570            2 :             "test_simple_bottom_most_compaction_deltas_1",
    9571            2 :             false,
    9572            2 :         )
    9573            2 :         .await
    9574            1 :     }
    9575              : 
    9576              :     #[cfg(feature = "testing")]
    9577              :     #[tokio::test]
    9578            1 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    9579            2 :         test_simple_bottom_most_compaction_deltas_helper(
    9580            2 :             "test_simple_bottom_most_compaction_deltas_2",
    9581            2 :             true,
    9582            2 :         )
    9583            2 :         .await
    9584            1 :     }
    9585              : 
    9586              :     #[cfg(feature = "testing")]
    9587            2 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    9588            2 :         test_name: &'static str,
    9589            2 :         use_delta_bottom_layer: bool,
    9590            2 :     ) -> anyhow::Result<()> {
    9591            2 :         let harness = TenantHarness::create(test_name).await?;
    9592            2 :         let (tenant, ctx) = harness.load().await;
    9593              : 
    9594          138 :         fn get_key(id: u32) -> Key {
    9595              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9596          138 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9597          138 :             key.field6 = id;
    9598          138 :             key
    9599          138 :         }
    9600              : 
    9601              :         // We create
    9602              :         // - one bottom-most image layer,
    9603              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9604              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9605              :         // - a delta layer D3 above the horizon.
    9606              :         //
    9607              :         //                             | D3 |
    9608              :         //  | D1 |
    9609              :         // -|    |-- gc horizon -----------------
    9610              :         //  |    |                | D2 |
    9611              :         // --------- img layer ------------------
    9612              :         //
    9613              :         // What we should expact from this compaction is:
    9614              :         //                             | D3 |
    9615              :         //  | Part of D1 |
    9616              :         // --------- img layer with D1+D2 at GC horizon------------------
    9617              : 
    9618              :         // img layer at 0x10
    9619            2 :         let img_layer = (0..10)
    9620           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9621            2 :             .collect_vec();
    9622              :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    9623            2 :         let delta4 = (0..10)
    9624           20 :             .map(|id| {
    9625           20 :                 (
    9626           20 :                     get_key(id),
    9627           20 :                     Lsn(0x08),
    9628           20 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    9629           20 :                 )
    9630           20 :             })
    9631            2 :             .collect_vec();
    9632              : 
    9633            2 :         let delta1 = vec![
    9634            2 :             (
    9635            2 :                 get_key(1),
    9636            2 :                 Lsn(0x20),
    9637            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9638            2 :             ),
    9639            2 :             (
    9640            2 :                 get_key(2),
    9641            2 :                 Lsn(0x30),
    9642            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9643            2 :             ),
    9644            2 :             (
    9645            2 :                 get_key(3),
    9646            2 :                 Lsn(0x28),
    9647            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9648            2 :             ),
    9649            2 :             (
    9650            2 :                 get_key(3),
    9651            2 :                 Lsn(0x30),
    9652            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9653            2 :             ),
    9654            2 :             (
    9655            2 :                 get_key(3),
    9656            2 :                 Lsn(0x40),
    9657            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9658            2 :             ),
    9659              :         ];
    9660            2 :         let delta2 = vec![
    9661            2 :             (
    9662            2 :                 get_key(5),
    9663            2 :                 Lsn(0x20),
    9664            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9665            2 :             ),
    9666            2 :             (
    9667            2 :                 get_key(6),
    9668            2 :                 Lsn(0x20),
    9669            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9670            2 :             ),
    9671              :         ];
    9672            2 :         let delta3 = vec![
    9673            2 :             (
    9674            2 :                 get_key(8),
    9675            2 :                 Lsn(0x48),
    9676            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9677            2 :             ),
    9678            2 :             (
    9679            2 :                 get_key(9),
    9680            2 :                 Lsn(0x48),
    9681            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9682            2 :             ),
    9683              :         ];
    9684              : 
    9685            2 :         let tline = if use_delta_bottom_layer {
    9686            1 :             tenant
    9687            1 :                 .create_test_timeline_with_layers(
    9688            1 :                     TIMELINE_ID,
    9689            1 :                     Lsn(0x08),
    9690            1 :                     DEFAULT_PG_VERSION,
    9691            1 :                     &ctx,
    9692            1 :                     Vec::new(), // in-memory layers
    9693            1 :                     vec![
    9694            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9695            1 :                             Lsn(0x08)..Lsn(0x10),
    9696            1 :                             delta4,
    9697            1 :                         ),
    9698            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9699            1 :                             Lsn(0x20)..Lsn(0x48),
    9700            1 :                             delta1,
    9701            1 :                         ),
    9702            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9703            1 :                             Lsn(0x20)..Lsn(0x48),
    9704            1 :                             delta2,
    9705            1 :                         ),
    9706            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9707            1 :                             Lsn(0x48)..Lsn(0x50),
    9708            1 :                             delta3,
    9709            1 :                         ),
    9710            1 :                     ], // delta layers
    9711            1 :                     vec![],     // image layers
    9712            1 :                     Lsn(0x50),
    9713            1 :                 )
    9714            1 :                 .await?
    9715              :         } else {
    9716            1 :             tenant
    9717            1 :                 .create_test_timeline_with_layers(
    9718            1 :                     TIMELINE_ID,
    9719            1 :                     Lsn(0x10),
    9720            1 :                     DEFAULT_PG_VERSION,
    9721            1 :                     &ctx,
    9722            1 :                     Vec::new(), // in-memory layers
    9723            1 :                     vec![
    9724            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9725            1 :                             Lsn(0x10)..Lsn(0x48),
    9726            1 :                             delta1,
    9727            1 :                         ),
    9728            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9729            1 :                             Lsn(0x10)..Lsn(0x48),
    9730            1 :                             delta2,
    9731            1 :                         ),
    9732            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9733            1 :                             Lsn(0x48)..Lsn(0x50),
    9734            1 :                             delta3,
    9735            1 :                         ),
    9736            1 :                     ], // delta layers
    9737            1 :                     vec![(Lsn(0x10), img_layer)], // image layers
    9738            1 :                     Lsn(0x50),
    9739            1 :                 )
    9740            1 :                 .await?
    9741              :         };
    9742              :         {
    9743            2 :             tline
    9744            2 :                 .applied_gc_cutoff_lsn
    9745            2 :                 .lock_for_write()
    9746            2 :                 .store_and_unlock(Lsn(0x30))
    9747            2 :                 .wait()
    9748            2 :                 .await;
    9749              :             // Update GC info
    9750            2 :             let mut guard = tline.gc_info.write().unwrap();
    9751            2 :             *guard = GcInfo {
    9752            2 :                 retain_lsns: vec![],
    9753            2 :                 cutoffs: GcCutoffs {
    9754            2 :                     time: Some(Lsn(0x30)),
    9755            2 :                     space: Lsn(0x30),
    9756            2 :                 },
    9757            2 :                 leases: Default::default(),
    9758            2 :                 within_ancestor_pitr: false,
    9759            2 :             };
    9760              :         }
    9761              : 
    9762            2 :         let expected_result = [
    9763            2 :             Bytes::from_static(b"value 0@0x10"),
    9764            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9765            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9766            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9767            2 :             Bytes::from_static(b"value 4@0x10"),
    9768            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9769            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9770            2 :             Bytes::from_static(b"value 7@0x10"),
    9771            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9772            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9773            2 :         ];
    9774              : 
    9775            2 :         let expected_result_at_gc_horizon = [
    9776            2 :             Bytes::from_static(b"value 0@0x10"),
    9777            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9778            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9779            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9780            2 :             Bytes::from_static(b"value 4@0x10"),
    9781            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9782            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9783            2 :             Bytes::from_static(b"value 7@0x10"),
    9784            2 :             Bytes::from_static(b"value 8@0x10"),
    9785            2 :             Bytes::from_static(b"value 9@0x10"),
    9786            2 :         ];
    9787              : 
    9788           22 :         for idx in 0..10 {
    9789           20 :             assert_eq!(
    9790           20 :                 tline
    9791           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9792           20 :                     .await
    9793           20 :                     .unwrap(),
    9794           20 :                 &expected_result[idx]
    9795              :             );
    9796           20 :             assert_eq!(
    9797           20 :                 tline
    9798           20 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9799           20 :                     .await
    9800           20 :                     .unwrap(),
    9801           20 :                 &expected_result_at_gc_horizon[idx]
    9802              :             );
    9803              :         }
    9804              : 
    9805            2 :         let cancel = CancellationToken::new();
    9806            2 :         tline
    9807            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9808            2 :             .await
    9809            2 :             .unwrap();
    9810              : 
    9811           22 :         for idx in 0..10 {
    9812           20 :             assert_eq!(
    9813           20 :                 tline
    9814           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9815           20 :                     .await
    9816           20 :                     .unwrap(),
    9817           20 :                 &expected_result[idx]
    9818              :             );
    9819           20 :             assert_eq!(
    9820           20 :                 tline
    9821           20 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9822           20 :                     .await
    9823           20 :                     .unwrap(),
    9824           20 :                 &expected_result_at_gc_horizon[idx]
    9825              :             );
    9826              :         }
    9827              : 
    9828              :         // increase GC horizon and compact again
    9829              :         {
    9830            2 :             tline
    9831            2 :                 .applied_gc_cutoff_lsn
    9832            2 :                 .lock_for_write()
    9833            2 :                 .store_and_unlock(Lsn(0x40))
    9834            2 :                 .wait()
    9835            2 :                 .await;
    9836              :             // Update GC info
    9837            2 :             let mut guard = tline.gc_info.write().unwrap();
    9838            2 :             guard.cutoffs.time = Some(Lsn(0x40));
    9839            2 :             guard.cutoffs.space = Lsn(0x40);
    9840              :         }
    9841            2 :         tline
    9842            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9843            2 :             .await
    9844            2 :             .unwrap();
    9845              : 
    9846            2 :         Ok(())
    9847            2 :     }
    9848              : 
    9849              :     #[cfg(feature = "testing")]
    9850              :     #[tokio::test]
    9851            1 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9852            1 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9853            1 :         let (tenant, ctx) = harness.load().await;
    9854            1 :         let tline = tenant
    9855            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9856            1 :             .await?;
    9857            1 :         tline.force_advance_lsn(Lsn(0x70));
    9858            1 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9859            1 :         let history = vec![
    9860            1 :             (
    9861            1 :                 key,
    9862            1 :                 Lsn(0x10),
    9863            1 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9864            1 :             ),
    9865            1 :             (
    9866            1 :                 key,
    9867            1 :                 Lsn(0x20),
    9868            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9869            1 :             ),
    9870            1 :             (
    9871            1 :                 key,
    9872            1 :                 Lsn(0x30),
    9873            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9874            1 :             ),
    9875            1 :             (
    9876            1 :                 key,
    9877            1 :                 Lsn(0x40),
    9878            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9879            1 :             ),
    9880            1 :             (
    9881            1 :                 key,
    9882            1 :                 Lsn(0x50),
    9883            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9884            1 :             ),
    9885            1 :             (
    9886            1 :                 key,
    9887            1 :                 Lsn(0x60),
    9888            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9889            1 :             ),
    9890            1 :             (
    9891            1 :                 key,
    9892            1 :                 Lsn(0x70),
    9893            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9894            1 :             ),
    9895            1 :             (
    9896            1 :                 key,
    9897            1 :                 Lsn(0x80),
    9898            1 :                 Value::Image(Bytes::copy_from_slice(
    9899            1 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9900            1 :                 )),
    9901            1 :             ),
    9902            1 :             (
    9903            1 :                 key,
    9904            1 :                 Lsn(0x90),
    9905            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9906            1 :             ),
    9907              :         ];
    9908            1 :         let res = tline
    9909            1 :             .generate_key_retention(
    9910            1 :                 key,
    9911            1 :                 &history,
    9912            1 :                 Lsn(0x60),
    9913            1 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9914            1 :                 3,
    9915            1 :                 None,
    9916            1 :                 true,
    9917            1 :             )
    9918            1 :             .await
    9919            1 :             .unwrap();
    9920            1 :         let expected_res = KeyHistoryRetention {
    9921            1 :             below_horizon: vec![
    9922            1 :                 (
    9923            1 :                     Lsn(0x20),
    9924            1 :                     KeyLogAtLsn(vec![(
    9925            1 :                         Lsn(0x20),
    9926            1 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9927            1 :                     )]),
    9928            1 :                 ),
    9929            1 :                 (
    9930            1 :                     Lsn(0x40),
    9931            1 :                     KeyLogAtLsn(vec![
    9932            1 :                         (
    9933            1 :                             Lsn(0x30),
    9934            1 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9935            1 :                         ),
    9936            1 :                         (
    9937            1 :                             Lsn(0x40),
    9938            1 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9939            1 :                         ),
    9940            1 :                     ]),
    9941            1 :                 ),
    9942            1 :                 (
    9943            1 :                     Lsn(0x50),
    9944            1 :                     KeyLogAtLsn(vec![(
    9945            1 :                         Lsn(0x50),
    9946            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9947            1 :                     )]),
    9948            1 :                 ),
    9949            1 :                 (
    9950            1 :                     Lsn(0x60),
    9951            1 :                     KeyLogAtLsn(vec![(
    9952            1 :                         Lsn(0x60),
    9953            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9954            1 :                     )]),
    9955            1 :                 ),
    9956            1 :             ],
    9957            1 :             above_horizon: KeyLogAtLsn(vec![
    9958            1 :                 (
    9959            1 :                     Lsn(0x70),
    9960            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9961            1 :                 ),
    9962            1 :                 (
    9963            1 :                     Lsn(0x80),
    9964            1 :                     Value::Image(Bytes::copy_from_slice(
    9965            1 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9966            1 :                     )),
    9967            1 :                 ),
    9968            1 :                 (
    9969            1 :                     Lsn(0x90),
    9970            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9971            1 :                 ),
    9972            1 :             ]),
    9973            1 :         };
    9974            1 :         assert_eq!(res, expected_res);
    9975              : 
    9976              :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9977              :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9978              :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9979              :         // For example, we have
    9980              :         // ```plain
    9981              :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9982              :         // ```
    9983              :         // Now the GC horizon moves up, and we have
    9984              :         // ```plain
    9985              :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9986              :         // ```
    9987              :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9988              :         // We will end up with
    9989              :         // ```plain
    9990              :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9991              :         // ```
    9992              :         // Now we run the GC-compaction, and this key does not have a full history.
    9993              :         // We should be able to handle this partial history and drop everything before the
    9994              :         // gc_horizon image.
    9995              : 
    9996            1 :         let history = vec![
    9997            1 :             (
    9998            1 :                 key,
    9999            1 :                 Lsn(0x20),
   10000            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10001            1 :             ),
   10002            1 :             (
   10003            1 :                 key,
   10004            1 :                 Lsn(0x30),
   10005            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
   10006            1 :             ),
   10007            1 :             (
   10008            1 :                 key,
   10009            1 :                 Lsn(0x40),
   10010            1 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
   10011            1 :             ),
   10012            1 :             (
   10013            1 :                 key,
   10014            1 :                 Lsn(0x50),
   10015            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
   10016            1 :             ),
   10017            1 :             (
   10018            1 :                 key,
   10019            1 :                 Lsn(0x60),
   10020            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10021            1 :             ),
   10022            1 :             (
   10023            1 :                 key,
   10024            1 :                 Lsn(0x70),
   10025            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10026            1 :             ),
   10027            1 :             (
   10028            1 :                 key,
   10029            1 :                 Lsn(0x80),
   10030            1 :                 Value::Image(Bytes::copy_from_slice(
   10031            1 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
   10032            1 :                 )),
   10033            1 :             ),
   10034            1 :             (
   10035            1 :                 key,
   10036            1 :                 Lsn(0x90),
   10037            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
   10038            1 :             ),
   10039              :         ];
   10040            1 :         let res = tline
   10041            1 :             .generate_key_retention(
   10042            1 :                 key,
   10043            1 :                 &history,
   10044            1 :                 Lsn(0x60),
   10045            1 :                 &[Lsn(0x40), Lsn(0x50)],
   10046            1 :                 3,
   10047            1 :                 None,
   10048            1 :                 true,
   10049            1 :             )
   10050            1 :             .await
   10051            1 :             .unwrap();
   10052            1 :         let expected_res = KeyHistoryRetention {
   10053            1 :             below_horizon: vec![
   10054            1 :                 (
   10055            1 :                     Lsn(0x40),
   10056            1 :                     KeyLogAtLsn(vec![(
   10057            1 :                         Lsn(0x40),
   10058            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
   10059            1 :                     )]),
   10060            1 :                 ),
   10061            1 :                 (
   10062            1 :                     Lsn(0x50),
   10063            1 :                     KeyLogAtLsn(vec![(
   10064            1 :                         Lsn(0x50),
   10065            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
   10066            1 :                     )]),
   10067            1 :                 ),
   10068            1 :                 (
   10069            1 :                     Lsn(0x60),
   10070            1 :                     KeyLogAtLsn(vec![(
   10071            1 :                         Lsn(0x60),
   10072            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10073            1 :                     )]),
   10074            1 :                 ),
   10075            1 :             ],
   10076            1 :             above_horizon: KeyLogAtLsn(vec![
   10077            1 :                 (
   10078            1 :                     Lsn(0x70),
   10079            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10080            1 :                 ),
   10081            1 :                 (
   10082            1 :                     Lsn(0x80),
   10083            1 :                     Value::Image(Bytes::copy_from_slice(
   10084            1 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
   10085            1 :                     )),
   10086            1 :                 ),
   10087            1 :                 (
   10088            1 :                     Lsn(0x90),
   10089            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
   10090            1 :                 ),
   10091            1 :             ]),
   10092            1 :         };
   10093            1 :         assert_eq!(res, expected_res);
   10094              : 
   10095              :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
   10096              :         // the ancestor image in the test case.
   10097              : 
   10098            1 :         let history = vec![
   10099            1 :             (
   10100            1 :                 key,
   10101            1 :                 Lsn(0x20),
   10102            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10103            1 :             ),
   10104            1 :             (
   10105            1 :                 key,
   10106            1 :                 Lsn(0x30),
   10107            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
   10108            1 :             ),
   10109            1 :             (
   10110            1 :                 key,
   10111            1 :                 Lsn(0x40),
   10112            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
   10113            1 :             ),
   10114            1 :             (
   10115            1 :                 key,
   10116            1 :                 Lsn(0x70),
   10117            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10118            1 :             ),
   10119              :         ];
   10120            1 :         let res = tline
   10121            1 :             .generate_key_retention(
   10122            1 :                 key,
   10123            1 :                 &history,
   10124            1 :                 Lsn(0x60),
   10125            1 :                 &[],
   10126            1 :                 3,
   10127            1 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
   10128            1 :                 true,
   10129            1 :             )
   10130            1 :             .await
   10131            1 :             .unwrap();
   10132            1 :         let expected_res = KeyHistoryRetention {
   10133            1 :             below_horizon: vec![(
   10134            1 :                 Lsn(0x60),
   10135            1 :                 KeyLogAtLsn(vec![(
   10136            1 :                     Lsn(0x60),
   10137            1 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
   10138            1 :                 )]),
   10139            1 :             )],
   10140            1 :             above_horizon: KeyLogAtLsn(vec![(
   10141            1 :                 Lsn(0x70),
   10142            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10143            1 :             )]),
   10144            1 :         };
   10145            1 :         assert_eq!(res, expected_res);
   10146              : 
   10147            1 :         let history = vec![
   10148            1 :             (
   10149            1 :                 key,
   10150            1 :                 Lsn(0x20),
   10151            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10152            1 :             ),
   10153            1 :             (
   10154            1 :                 key,
   10155            1 :                 Lsn(0x40),
   10156            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
   10157            1 :             ),
   10158            1 :             (
   10159            1 :                 key,
   10160            1 :                 Lsn(0x60),
   10161            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10162            1 :             ),
   10163            1 :             (
   10164            1 :                 key,
   10165            1 :                 Lsn(0x70),
   10166            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10167            1 :             ),
   10168              :         ];
   10169            1 :         let res = tline
   10170            1 :             .generate_key_retention(
   10171            1 :                 key,
   10172            1 :                 &history,
   10173            1 :                 Lsn(0x60),
   10174            1 :                 &[Lsn(0x30)],
   10175            1 :                 3,
   10176            1 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
   10177            1 :                 true,
   10178            1 :             )
   10179            1 :             .await
   10180            1 :             .unwrap();
   10181            1 :         let expected_res = KeyHistoryRetention {
   10182            1 :             below_horizon: vec![
   10183            1 :                 (
   10184            1 :                     Lsn(0x30),
   10185            1 :                     KeyLogAtLsn(vec![(
   10186            1 :                         Lsn(0x20),
   10187            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10188            1 :                     )]),
   10189            1 :                 ),
   10190            1 :                 (
   10191            1 :                     Lsn(0x60),
   10192            1 :                     KeyLogAtLsn(vec![(
   10193            1 :                         Lsn(0x60),
   10194            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
   10195            1 :                     )]),
   10196            1 :                 ),
   10197            1 :             ],
   10198            1 :             above_horizon: KeyLogAtLsn(vec![(
   10199            1 :                 Lsn(0x70),
   10200            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10201            1 :             )]),
   10202            1 :         };
   10203            1 :         assert_eq!(res, expected_res);
   10204              : 
   10205            2 :         Ok(())
   10206            1 :     }
   10207              : 
   10208              :     #[cfg(feature = "testing")]
   10209              :     #[tokio::test]
   10210            1 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
   10211            1 :         let harness =
   10212            1 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
   10213            1 :         let (tenant, ctx) = harness.load().await;
   10214              : 
   10215          259 :         fn get_key(id: u32) -> Key {
   10216              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10217          259 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10218          259 :             key.field6 = id;
   10219          259 :             key
   10220          259 :         }
   10221              : 
   10222            1 :         let img_layer = (0..10)
   10223           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10224            1 :             .collect_vec();
   10225              : 
   10226            1 :         let delta1 = vec![
   10227            1 :             (
   10228            1 :                 get_key(1),
   10229            1 :                 Lsn(0x20),
   10230            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10231            1 :             ),
   10232            1 :             (
   10233            1 :                 get_key(2),
   10234            1 :                 Lsn(0x30),
   10235            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10236            1 :             ),
   10237            1 :             (
   10238            1 :                 get_key(3),
   10239            1 :                 Lsn(0x28),
   10240            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10241            1 :             ),
   10242            1 :             (
   10243            1 :                 get_key(3),
   10244            1 :                 Lsn(0x30),
   10245            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10246            1 :             ),
   10247            1 :             (
   10248            1 :                 get_key(3),
   10249            1 :                 Lsn(0x40),
   10250            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10251            1 :             ),
   10252              :         ];
   10253            1 :         let delta2 = vec![
   10254            1 :             (
   10255            1 :                 get_key(5),
   10256            1 :                 Lsn(0x20),
   10257            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10258            1 :             ),
   10259            1 :             (
   10260            1 :                 get_key(6),
   10261            1 :                 Lsn(0x20),
   10262            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10263            1 :             ),
   10264              :         ];
   10265            1 :         let delta3 = vec![
   10266            1 :             (
   10267            1 :                 get_key(8),
   10268            1 :                 Lsn(0x48),
   10269            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10270            1 :             ),
   10271            1 :             (
   10272            1 :                 get_key(9),
   10273            1 :                 Lsn(0x48),
   10274            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10275            1 :             ),
   10276              :         ];
   10277              : 
   10278            1 :         let tline = tenant
   10279            1 :             .create_test_timeline_with_layers(
   10280            1 :                 TIMELINE_ID,
   10281            1 :                 Lsn(0x10),
   10282            1 :                 DEFAULT_PG_VERSION,
   10283            1 :                 &ctx,
   10284            1 :                 Vec::new(), // in-memory layers
   10285            1 :                 vec![
   10286            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
   10287            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
   10288            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10289            1 :                 ], // delta layers
   10290            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10291            1 :                 Lsn(0x50),
   10292            1 :             )
   10293            1 :             .await?;
   10294              :         {
   10295            1 :             tline
   10296            1 :                 .applied_gc_cutoff_lsn
   10297            1 :                 .lock_for_write()
   10298            1 :                 .store_and_unlock(Lsn(0x30))
   10299            1 :                 .wait()
   10300            1 :                 .await;
   10301              :             // Update GC info
   10302            1 :             let mut guard = tline.gc_info.write().unwrap();
   10303            1 :             *guard = GcInfo {
   10304            1 :                 retain_lsns: vec![
   10305            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10306            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10307            1 :                 ],
   10308            1 :                 cutoffs: GcCutoffs {
   10309            1 :                     time: Some(Lsn(0x30)),
   10310            1 :                     space: Lsn(0x30),
   10311            1 :                 },
   10312            1 :                 leases: Default::default(),
   10313            1 :                 within_ancestor_pitr: false,
   10314            1 :             };
   10315              :         }
   10316              : 
   10317            1 :         let expected_result = [
   10318            1 :             Bytes::from_static(b"value 0@0x10"),
   10319            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10320            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10321            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10322            1 :             Bytes::from_static(b"value 4@0x10"),
   10323            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10324            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10325            1 :             Bytes::from_static(b"value 7@0x10"),
   10326            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10327            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10328            1 :         ];
   10329              : 
   10330            1 :         let expected_result_at_gc_horizon = [
   10331            1 :             Bytes::from_static(b"value 0@0x10"),
   10332            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10333            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10334            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
   10335            1 :             Bytes::from_static(b"value 4@0x10"),
   10336            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10337            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10338            1 :             Bytes::from_static(b"value 7@0x10"),
   10339            1 :             Bytes::from_static(b"value 8@0x10"),
   10340            1 :             Bytes::from_static(b"value 9@0x10"),
   10341            1 :         ];
   10342              : 
   10343            1 :         let expected_result_at_lsn_20 = [
   10344            1 :             Bytes::from_static(b"value 0@0x10"),
   10345            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10346            1 :             Bytes::from_static(b"value 2@0x10"),
   10347            1 :             Bytes::from_static(b"value 3@0x10"),
   10348            1 :             Bytes::from_static(b"value 4@0x10"),
   10349            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10350            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10351            1 :             Bytes::from_static(b"value 7@0x10"),
   10352            1 :             Bytes::from_static(b"value 8@0x10"),
   10353            1 :             Bytes::from_static(b"value 9@0x10"),
   10354            1 :         ];
   10355              : 
   10356            1 :         let expected_result_at_lsn_10 = [
   10357            1 :             Bytes::from_static(b"value 0@0x10"),
   10358            1 :             Bytes::from_static(b"value 1@0x10"),
   10359            1 :             Bytes::from_static(b"value 2@0x10"),
   10360            1 :             Bytes::from_static(b"value 3@0x10"),
   10361            1 :             Bytes::from_static(b"value 4@0x10"),
   10362            1 :             Bytes::from_static(b"value 5@0x10"),
   10363            1 :             Bytes::from_static(b"value 6@0x10"),
   10364            1 :             Bytes::from_static(b"value 7@0x10"),
   10365            1 :             Bytes::from_static(b"value 8@0x10"),
   10366            1 :             Bytes::from_static(b"value 9@0x10"),
   10367            1 :         ];
   10368              : 
   10369            6 :         let verify_result = || async {
   10370            6 :             let gc_horizon = {
   10371            6 :                 let gc_info = tline.gc_info.read().unwrap();
   10372            6 :                 gc_info.cutoffs.time.unwrap_or_default()
   10373              :             };
   10374           66 :             for idx in 0..10 {
   10375           60 :                 assert_eq!(
   10376           60 :                     tline
   10377           60 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10378           60 :                         .await
   10379           60 :                         .unwrap(),
   10380           60 :                     &expected_result[idx]
   10381              :                 );
   10382           60 :                 assert_eq!(
   10383           60 :                     tline
   10384           60 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10385           60 :                         .await
   10386           60 :                         .unwrap(),
   10387           60 :                     &expected_result_at_gc_horizon[idx]
   10388              :                 );
   10389           60 :                 assert_eq!(
   10390           60 :                     tline
   10391           60 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10392           60 :                         .await
   10393           60 :                         .unwrap(),
   10394           60 :                     &expected_result_at_lsn_20[idx]
   10395              :                 );
   10396           60 :                 assert_eq!(
   10397           60 :                     tline
   10398           60 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10399           60 :                         .await
   10400           60 :                         .unwrap(),
   10401           60 :                     &expected_result_at_lsn_10[idx]
   10402              :                 );
   10403              :             }
   10404           12 :         };
   10405              : 
   10406            1 :         verify_result().await;
   10407              : 
   10408            1 :         let cancel = CancellationToken::new();
   10409            1 :         let mut dryrun_flags = EnumSet::new();
   10410            1 :         dryrun_flags.insert(CompactFlags::DryRun);
   10411              : 
   10412            1 :         tline
   10413            1 :             .compact_with_gc(
   10414            1 :                 &cancel,
   10415            1 :                 CompactOptions {
   10416            1 :                     flags: dryrun_flags,
   10417            1 :                     ..Default::default()
   10418            1 :                 },
   10419            1 :                 &ctx,
   10420            1 :             )
   10421            1 :             .await
   10422            1 :             .unwrap();
   10423              :         // 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
   10424              :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10425            1 :         verify_result().await;
   10426              : 
   10427            1 :         tline
   10428            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10429            1 :             .await
   10430            1 :             .unwrap();
   10431            1 :         verify_result().await;
   10432              : 
   10433              :         // compact again
   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              :         // increase GC horizon and compact again
   10441              :         {
   10442            1 :             tline
   10443            1 :                 .applied_gc_cutoff_lsn
   10444            1 :                 .lock_for_write()
   10445            1 :                 .store_and_unlock(Lsn(0x38))
   10446            1 :                 .wait()
   10447            1 :                 .await;
   10448              :             // Update GC info
   10449            1 :             let mut guard = tline.gc_info.write().unwrap();
   10450            1 :             guard.cutoffs.time = Some(Lsn(0x38));
   10451            1 :             guard.cutoffs.space = Lsn(0x38);
   10452              :         }
   10453            1 :         tline
   10454            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10455            1 :             .await
   10456            1 :             .unwrap();
   10457            1 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
   10458              : 
   10459              :         // not increasing the GC horizon and compact again
   10460            1 :         tline
   10461            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10462            1 :             .await
   10463            1 :             .unwrap();
   10464            1 :         verify_result().await;
   10465              : 
   10466            2 :         Ok(())
   10467            1 :     }
   10468              : 
   10469              :     #[cfg(feature = "testing")]
   10470              :     #[tokio::test]
   10471            1 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
   10472            1 :     {
   10473            1 :         let harness =
   10474            1 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
   10475            1 :                 .await?;
   10476            1 :         let (tenant, ctx) = harness.load().await;
   10477              : 
   10478          176 :         fn get_key(id: u32) -> Key {
   10479              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10480          176 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10481          176 :             key.field6 = id;
   10482          176 :             key
   10483          176 :         }
   10484              : 
   10485            1 :         let img_layer = (0..10)
   10486           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10487            1 :             .collect_vec();
   10488              : 
   10489            1 :         let delta1 = vec![
   10490            1 :             (
   10491            1 :                 get_key(1),
   10492            1 :                 Lsn(0x20),
   10493            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10494            1 :             ),
   10495            1 :             (
   10496            1 :                 get_key(1),
   10497            1 :                 Lsn(0x28),
   10498            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10499            1 :             ),
   10500              :         ];
   10501            1 :         let delta2 = vec![
   10502            1 :             (
   10503            1 :                 get_key(1),
   10504            1 :                 Lsn(0x30),
   10505            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10506            1 :             ),
   10507            1 :             (
   10508            1 :                 get_key(1),
   10509            1 :                 Lsn(0x38),
   10510            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10511            1 :             ),
   10512              :         ];
   10513            1 :         let delta3 = vec![
   10514            1 :             (
   10515            1 :                 get_key(8),
   10516            1 :                 Lsn(0x48),
   10517            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10518            1 :             ),
   10519            1 :             (
   10520            1 :                 get_key(9),
   10521            1 :                 Lsn(0x48),
   10522            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10523            1 :             ),
   10524              :         ];
   10525              : 
   10526            1 :         let tline = tenant
   10527            1 :             .create_test_timeline_with_layers(
   10528            1 :                 TIMELINE_ID,
   10529            1 :                 Lsn(0x10),
   10530            1 :                 DEFAULT_PG_VERSION,
   10531            1 :                 &ctx,
   10532            1 :                 Vec::new(), // in-memory layers
   10533            1 :                 vec![
   10534            1 :                     // delta1 and delta 2 only contain a single key but multiple updates
   10535            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
   10536            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10537            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
   10538            1 :                 ], // delta layers
   10539            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10540            1 :                 Lsn(0x50),
   10541            1 :             )
   10542            1 :             .await?;
   10543              :         {
   10544            1 :             tline
   10545            1 :                 .applied_gc_cutoff_lsn
   10546            1 :                 .lock_for_write()
   10547            1 :                 .store_and_unlock(Lsn(0x30))
   10548            1 :                 .wait()
   10549            1 :                 .await;
   10550              :             // Update GC info
   10551            1 :             let mut guard = tline.gc_info.write().unwrap();
   10552            1 :             *guard = GcInfo {
   10553            1 :                 retain_lsns: vec![
   10554            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10555            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10556            1 :                 ],
   10557            1 :                 cutoffs: GcCutoffs {
   10558            1 :                     time: Some(Lsn(0x30)),
   10559            1 :                     space: Lsn(0x30),
   10560            1 :                 },
   10561            1 :                 leases: Default::default(),
   10562            1 :                 within_ancestor_pitr: false,
   10563            1 :             };
   10564              :         }
   10565              : 
   10566            1 :         let expected_result = [
   10567            1 :             Bytes::from_static(b"value 0@0x10"),
   10568            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10569            1 :             Bytes::from_static(b"value 2@0x10"),
   10570            1 :             Bytes::from_static(b"value 3@0x10"),
   10571            1 :             Bytes::from_static(b"value 4@0x10"),
   10572            1 :             Bytes::from_static(b"value 5@0x10"),
   10573            1 :             Bytes::from_static(b"value 6@0x10"),
   10574            1 :             Bytes::from_static(b"value 7@0x10"),
   10575            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10576            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10577            1 :         ];
   10578              : 
   10579            1 :         let expected_result_at_gc_horizon = [
   10580            1 :             Bytes::from_static(b"value 0@0x10"),
   10581            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10582            1 :             Bytes::from_static(b"value 2@0x10"),
   10583            1 :             Bytes::from_static(b"value 3@0x10"),
   10584            1 :             Bytes::from_static(b"value 4@0x10"),
   10585            1 :             Bytes::from_static(b"value 5@0x10"),
   10586            1 :             Bytes::from_static(b"value 6@0x10"),
   10587            1 :             Bytes::from_static(b"value 7@0x10"),
   10588            1 :             Bytes::from_static(b"value 8@0x10"),
   10589            1 :             Bytes::from_static(b"value 9@0x10"),
   10590            1 :         ];
   10591              : 
   10592            1 :         let expected_result_at_lsn_20 = [
   10593            1 :             Bytes::from_static(b"value 0@0x10"),
   10594            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10595            1 :             Bytes::from_static(b"value 2@0x10"),
   10596            1 :             Bytes::from_static(b"value 3@0x10"),
   10597            1 :             Bytes::from_static(b"value 4@0x10"),
   10598            1 :             Bytes::from_static(b"value 5@0x10"),
   10599            1 :             Bytes::from_static(b"value 6@0x10"),
   10600            1 :             Bytes::from_static(b"value 7@0x10"),
   10601            1 :             Bytes::from_static(b"value 8@0x10"),
   10602            1 :             Bytes::from_static(b"value 9@0x10"),
   10603            1 :         ];
   10604              : 
   10605            1 :         let expected_result_at_lsn_10 = [
   10606            1 :             Bytes::from_static(b"value 0@0x10"),
   10607            1 :             Bytes::from_static(b"value 1@0x10"),
   10608            1 :             Bytes::from_static(b"value 2@0x10"),
   10609            1 :             Bytes::from_static(b"value 3@0x10"),
   10610            1 :             Bytes::from_static(b"value 4@0x10"),
   10611            1 :             Bytes::from_static(b"value 5@0x10"),
   10612            1 :             Bytes::from_static(b"value 6@0x10"),
   10613            1 :             Bytes::from_static(b"value 7@0x10"),
   10614            1 :             Bytes::from_static(b"value 8@0x10"),
   10615            1 :             Bytes::from_static(b"value 9@0x10"),
   10616            1 :         ];
   10617              : 
   10618            4 :         let verify_result = || async {
   10619            4 :             let gc_horizon = {
   10620            4 :                 let gc_info = tline.gc_info.read().unwrap();
   10621            4 :                 gc_info.cutoffs.time.unwrap_or_default()
   10622              :             };
   10623           44 :             for idx in 0..10 {
   10624           40 :                 assert_eq!(
   10625           40 :                     tline
   10626           40 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10627           40 :                         .await
   10628           40 :                         .unwrap(),
   10629           40 :                     &expected_result[idx]
   10630              :                 );
   10631           40 :                 assert_eq!(
   10632           40 :                     tline
   10633           40 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10634           40 :                         .await
   10635           40 :                         .unwrap(),
   10636           40 :                     &expected_result_at_gc_horizon[idx]
   10637              :                 );
   10638           40 :                 assert_eq!(
   10639           40 :                     tline
   10640           40 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10641           40 :                         .await
   10642           40 :                         .unwrap(),
   10643           40 :                     &expected_result_at_lsn_20[idx]
   10644              :                 );
   10645           40 :                 assert_eq!(
   10646           40 :                     tline
   10647           40 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10648           40 :                         .await
   10649           40 :                         .unwrap(),
   10650           40 :                     &expected_result_at_lsn_10[idx]
   10651              :                 );
   10652              :             }
   10653            8 :         };
   10654              : 
   10655            1 :         verify_result().await;
   10656              : 
   10657            1 :         let cancel = CancellationToken::new();
   10658            1 :         let mut dryrun_flags = EnumSet::new();
   10659            1 :         dryrun_flags.insert(CompactFlags::DryRun);
   10660              : 
   10661            1 :         tline
   10662            1 :             .compact_with_gc(
   10663            1 :                 &cancel,
   10664            1 :                 CompactOptions {
   10665            1 :                     flags: dryrun_flags,
   10666            1 :                     ..Default::default()
   10667            1 :                 },
   10668            1 :                 &ctx,
   10669            1 :             )
   10670            1 :             .await
   10671            1 :             .unwrap();
   10672              :         // 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
   10673              :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10674            1 :         verify_result().await;
   10675              : 
   10676            1 :         tline
   10677            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10678            1 :             .await
   10679            1 :             .unwrap();
   10680            1 :         verify_result().await;
   10681              : 
   10682              :         // compact again
   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            2 :         Ok(())
   10690            1 :     }
   10691              : 
   10692              :     #[cfg(feature = "testing")]
   10693              :     #[tokio::test]
   10694            1 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
   10695              :         use models::CompactLsnRange;
   10696              : 
   10697            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
   10698            1 :         let (tenant, ctx) = harness.load().await;
   10699              : 
   10700           83 :         fn get_key(id: u32) -> Key {
   10701           83 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
   10702           83 :             key.field6 = id;
   10703           83 :             key
   10704           83 :         }
   10705              : 
   10706            1 :         let img_layer = (0..10)
   10707           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10708            1 :             .collect_vec();
   10709              : 
   10710            1 :         let delta1 = vec![
   10711            1 :             (
   10712            1 :                 get_key(1),
   10713            1 :                 Lsn(0x20),
   10714            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10715            1 :             ),
   10716            1 :             (
   10717            1 :                 get_key(2),
   10718            1 :                 Lsn(0x30),
   10719            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10720            1 :             ),
   10721            1 :             (
   10722            1 :                 get_key(3),
   10723            1 :                 Lsn(0x28),
   10724            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10725            1 :             ),
   10726            1 :             (
   10727            1 :                 get_key(3),
   10728            1 :                 Lsn(0x30),
   10729            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10730            1 :             ),
   10731            1 :             (
   10732            1 :                 get_key(3),
   10733            1 :                 Lsn(0x40),
   10734            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10735            1 :             ),
   10736              :         ];
   10737            1 :         let delta2 = vec![
   10738            1 :             (
   10739            1 :                 get_key(5),
   10740            1 :                 Lsn(0x20),
   10741            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10742            1 :             ),
   10743            1 :             (
   10744            1 :                 get_key(6),
   10745            1 :                 Lsn(0x20),
   10746            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10747            1 :             ),
   10748              :         ];
   10749            1 :         let delta3 = vec![
   10750            1 :             (
   10751            1 :                 get_key(8),
   10752            1 :                 Lsn(0x48),
   10753            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10754            1 :             ),
   10755            1 :             (
   10756            1 :                 get_key(9),
   10757            1 :                 Lsn(0x48),
   10758            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10759            1 :             ),
   10760              :         ];
   10761              : 
   10762            1 :         let parent_tline = tenant
   10763            1 :             .create_test_timeline_with_layers(
   10764            1 :                 TIMELINE_ID,
   10765            1 :                 Lsn(0x10),
   10766            1 :                 DEFAULT_PG_VERSION,
   10767            1 :                 &ctx,
   10768            1 :                 vec![],                       // in-memory layers
   10769            1 :                 vec![],                       // delta layers
   10770            1 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10771            1 :                 Lsn(0x18),
   10772            1 :             )
   10773            1 :             .await?;
   10774              : 
   10775            1 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10776              : 
   10777            1 :         let branch_tline = tenant
   10778            1 :             .branch_timeline_test_with_layers(
   10779            1 :                 &parent_tline,
   10780            1 :                 NEW_TIMELINE_ID,
   10781            1 :                 Some(Lsn(0x18)),
   10782            1 :                 &ctx,
   10783            1 :                 vec![
   10784            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10785            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10786            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10787            1 :                 ], // delta layers
   10788            1 :                 vec![], // image layers
   10789            1 :                 Lsn(0x50),
   10790            1 :             )
   10791            1 :             .await?;
   10792              : 
   10793            1 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10794              : 
   10795              :         {
   10796            1 :             parent_tline
   10797            1 :                 .applied_gc_cutoff_lsn
   10798            1 :                 .lock_for_write()
   10799            1 :                 .store_and_unlock(Lsn(0x10))
   10800            1 :                 .wait()
   10801            1 :                 .await;
   10802              :             // Update GC info
   10803            1 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10804            1 :             *guard = GcInfo {
   10805            1 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10806            1 :                 cutoffs: GcCutoffs {
   10807            1 :                     time: Some(Lsn(0x10)),
   10808            1 :                     space: Lsn(0x10),
   10809            1 :                 },
   10810            1 :                 leases: Default::default(),
   10811            1 :                 within_ancestor_pitr: false,
   10812            1 :             };
   10813              :         }
   10814              : 
   10815              :         {
   10816            1 :             branch_tline
   10817            1 :                 .applied_gc_cutoff_lsn
   10818            1 :                 .lock_for_write()
   10819            1 :                 .store_and_unlock(Lsn(0x50))
   10820            1 :                 .wait()
   10821            1 :                 .await;
   10822              :             // Update GC info
   10823            1 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10824            1 :             *guard = GcInfo {
   10825            1 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10826            1 :                 cutoffs: GcCutoffs {
   10827            1 :                     time: Some(Lsn(0x50)),
   10828            1 :                     space: Lsn(0x50),
   10829            1 :                 },
   10830            1 :                 leases: Default::default(),
   10831            1 :                 within_ancestor_pitr: false,
   10832            1 :             };
   10833              :         }
   10834              : 
   10835            1 :         let expected_result_at_gc_horizon = [
   10836            1 :             Bytes::from_static(b"value 0@0x10"),
   10837            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10838            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10839            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10840            1 :             Bytes::from_static(b"value 4@0x10"),
   10841            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10842            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10843            1 :             Bytes::from_static(b"value 7@0x10"),
   10844            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10845            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10846            1 :         ];
   10847              : 
   10848            1 :         let expected_result_at_lsn_40 = [
   10849            1 :             Bytes::from_static(b"value 0@0x10"),
   10850            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10851            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10852            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10853            1 :             Bytes::from_static(b"value 4@0x10"),
   10854            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10855            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10856            1 :             Bytes::from_static(b"value 7@0x10"),
   10857            1 :             Bytes::from_static(b"value 8@0x10"),
   10858            1 :             Bytes::from_static(b"value 9@0x10"),
   10859            1 :         ];
   10860              : 
   10861            3 :         let verify_result = || async {
   10862           33 :             for idx in 0..10 {
   10863           30 :                 assert_eq!(
   10864           30 :                     branch_tline
   10865           30 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10866           30 :                         .await
   10867           30 :                         .unwrap(),
   10868           30 :                     &expected_result_at_gc_horizon[idx]
   10869              :                 );
   10870           30 :                 assert_eq!(
   10871           30 :                     branch_tline
   10872           30 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10873           30 :                         .await
   10874           30 :                         .unwrap(),
   10875           30 :                     &expected_result_at_lsn_40[idx]
   10876              :                 );
   10877              :             }
   10878            6 :         };
   10879              : 
   10880            1 :         verify_result().await;
   10881              : 
   10882            1 :         let cancel = CancellationToken::new();
   10883            1 :         branch_tline
   10884            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10885            1 :             .await
   10886            1 :             .unwrap();
   10887              : 
   10888            1 :         verify_result().await;
   10889              : 
   10890              :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10891              :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10892            1 :         branch_tline
   10893            1 :             .compact_with_gc(
   10894            1 :                 &cancel,
   10895            1 :                 CompactOptions {
   10896            1 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10897            1 :                     ..Default::default()
   10898            1 :                 },
   10899            1 :                 &ctx,
   10900            1 :             )
   10901            1 :             .await
   10902            1 :             .unwrap();
   10903              : 
   10904            1 :         verify_result().await;
   10905              : 
   10906            2 :         Ok(())
   10907            1 :     }
   10908              : 
   10909              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
   10910              :     // Create an image arrangement where we have to read at different LSN ranges
   10911              :     // from a delta layer. This is achieved by overlapping an image layer on top of
   10912              :     // a delta layer. Like so:
   10913              :     //
   10914              :     //     A      B
   10915              :     // +----------------+ -> delta_layer
   10916              :     // |                |                           ^ lsn
   10917              :     // |       =========|-> nested_image_layer      |
   10918              :     // |       C        |                           |
   10919              :     // +----------------+                           |
   10920              :     // ======== -> baseline_image_layer             +-------> key
   10921              :     //
   10922              :     //
   10923              :     // When querying the key range [A, B) we need to read at different LSN ranges
   10924              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   10925              :     #[cfg(feature = "testing")]
   10926              :     #[tokio::test]
   10927            1 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10928            1 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10929            1 :         let (tenant, ctx) = harness.load().await;
   10930              : 
   10931            1 :         let will_init_keys = [2, 6];
   10932           22 :         fn get_key(id: u32) -> Key {
   10933           22 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10934           22 :             key.field6 = id;
   10935           22 :             key
   10936           22 :         }
   10937              : 
   10938            1 :         let mut expected_key_values = HashMap::new();
   10939              : 
   10940            1 :         let baseline_image_layer_lsn = Lsn(0x10);
   10941            1 :         let mut baseline_img_layer = Vec::new();
   10942            6 :         for i in 0..5 {
   10943            5 :             let key = get_key(i);
   10944            5 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10945              : 
   10946            5 :             let removed = expected_key_values.insert(key, value.clone());
   10947            5 :             assert!(removed.is_none());
   10948              : 
   10949            5 :             baseline_img_layer.push((key, Bytes::from(value)));
   10950              :         }
   10951              : 
   10952            1 :         let nested_image_layer_lsn = Lsn(0x50);
   10953            1 :         let mut nested_img_layer = Vec::new();
   10954            6 :         for i in 5..10 {
   10955            5 :             let key = get_key(i);
   10956            5 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10957              : 
   10958            5 :             let removed = expected_key_values.insert(key, value.clone());
   10959            5 :             assert!(removed.is_none());
   10960              : 
   10961            5 :             nested_img_layer.push((key, Bytes::from(value)));
   10962              :         }
   10963              : 
   10964            1 :         let mut delta_layer_spec = Vec::default();
   10965            1 :         let delta_layer_start_lsn = Lsn(0x20);
   10966            1 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10967              : 
   10968           11 :         for i in 0..10 {
   10969           10 :             let key = get_key(i);
   10970           10 :             let key_in_nested = nested_img_layer
   10971           10 :                 .iter()
   10972           40 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10973           10 :             let lsn = {
   10974           10 :                 if key_in_nested {
   10975            5 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   10976              :                 } else {
   10977            5 :                     delta_layer_start_lsn
   10978              :                 }
   10979              :             };
   10980              : 
   10981           10 :             let will_init = will_init_keys.contains(&i);
   10982           10 :             if will_init {
   10983            2 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10984            2 : 
   10985            2 :                 expected_key_values.insert(key, "".to_string());
   10986            8 :             } else {
   10987            8 :                 let delta = format!("@{lsn}");
   10988            8 :                 delta_layer_spec.push((
   10989            8 :                     key,
   10990            8 :                     lsn,
   10991            8 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10992            8 :                 ));
   10993            8 : 
   10994            8 :                 expected_key_values
   10995            8 :                     .get_mut(&key)
   10996            8 :                     .expect("An image exists for each key")
   10997            8 :                     .push_str(delta.as_str());
   10998            8 :             }
   10999           10 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   11000              :         }
   11001              : 
   11002            1 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   11003              : 
   11004            1 :         assert!(
   11005            1 :             nested_image_layer_lsn > delta_layer_start_lsn
   11006            1 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   11007              :         );
   11008              : 
   11009            1 :         let tline = tenant
   11010            1 :             .create_test_timeline_with_layers(
   11011            1 :                 TIMELINE_ID,
   11012            1 :                 baseline_image_layer_lsn,
   11013            1 :                 DEFAULT_PG_VERSION,
   11014            1 :                 &ctx,
   11015            1 :                 vec![], // in-memory layers
   11016            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   11017            1 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   11018            1 :                     delta_layer_spec,
   11019            1 :                 )], // delta layers
   11020            1 :                 vec![
   11021            1 :                     (baseline_image_layer_lsn, baseline_img_layer),
   11022            1 :                     (nested_image_layer_lsn, nested_img_layer),
   11023            1 :                 ], // image layers
   11024            1 :                 delta_layer_end_lsn,
   11025            1 :             )
   11026            1 :             .await?;
   11027              : 
   11028            1 :         let query = VersionedKeySpaceQuery::uniform(
   11029            1 :             KeySpace::single(get_key(0)..get_key(10)),
   11030            1 :             delta_layer_end_lsn,
   11031              :         );
   11032              : 
   11033            1 :         let results = tline
   11034            1 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   11035            1 :             .await
   11036            1 :             .expect("No vectored errors");
   11037           11 :         for (key, res) in results {
   11038           10 :             let value = res.expect("No key errors");
   11039           10 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   11040           10 :             assert_eq!(value, Bytes::from(expected_value));
   11041            1 :         }
   11042            1 : 
   11043            1 :         Ok(())
   11044            1 :     }
   11045              : 
   11046              :     #[cfg(feature = "testing")]
   11047              :     #[tokio::test]
   11048            1 :     async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
   11049            1 :         let harness =
   11050            1 :             TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
   11051            1 :         let (tenant, ctx) = harness.load().await;
   11052              : 
   11053            1 :         let will_init_keys = [2, 6];
   11054           32 :         fn get_key(id: u32) -> Key {
   11055           32 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   11056           32 :             key.field6 = id;
   11057           32 :             key
   11058           32 :         }
   11059              : 
   11060            1 :         let mut expected_key_values = HashMap::new();
   11061              : 
   11062            1 :         let baseline_image_layer_lsn = Lsn(0x10);
   11063            1 :         let mut baseline_img_layer = Vec::new();
   11064            6 :         for i in 0..5 {
   11065            5 :             let key = get_key(i);
   11066            5 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   11067              : 
   11068            5 :             let removed = expected_key_values.insert(key, value.clone());
   11069            5 :             assert!(removed.is_none());
   11070              : 
   11071            5 :             baseline_img_layer.push((key, Bytes::from(value)));
   11072              :         }
   11073              : 
   11074            1 :         let nested_image_layer_lsn = Lsn(0x50);
   11075            1 :         let mut nested_img_layer = Vec::new();
   11076            6 :         for i in 5..10 {
   11077            5 :             let key = get_key(i);
   11078            5 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   11079              : 
   11080            5 :             let removed = expected_key_values.insert(key, value.clone());
   11081            5 :             assert!(removed.is_none());
   11082              : 
   11083            5 :             nested_img_layer.push((key, Bytes::from(value)));
   11084              :         }
   11085              : 
   11086            1 :         let frozen_layer = {
   11087            1 :             let lsn_range = Lsn(0x40)..Lsn(0x60);
   11088            1 :             let mut data = Vec::new();
   11089           11 :             for i in 0..10 {
   11090           10 :                 let key = get_key(i);
   11091           10 :                 let key_in_nested = nested_img_layer
   11092           10 :                     .iter()
   11093           40 :                     .any(|(key_with_img, _)| *key_with_img == key);
   11094           10 :                 let lsn = {
   11095           10 :                     if key_in_nested {
   11096            5 :                         Lsn(nested_image_layer_lsn.0 + 5)
   11097              :                     } else {
   11098            5 :                         lsn_range.start
   11099              :                     }
   11100              :                 };
   11101              : 
   11102           10 :                 let will_init = will_init_keys.contains(&i);
   11103           10 :                 if will_init {
   11104            2 :                     data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   11105            2 : 
   11106            2 :                     expected_key_values.insert(key, "".to_string());
   11107            8 :                 } else {
   11108            8 :                     let delta = format!("@{lsn}");
   11109            8 :                     data.push((
   11110            8 :                         key,
   11111            8 :                         lsn,
   11112            8 :                         Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11113            8 :                     ));
   11114            8 : 
   11115            8 :                     expected_key_values
   11116            8 :                         .get_mut(&key)
   11117            8 :                         .expect("An image exists for each key")
   11118            8 :                         .push_str(delta.as_str());
   11119            8 :                 }
   11120              :             }
   11121              : 
   11122            1 :             InMemoryLayerTestDesc {
   11123            1 :                 lsn_range,
   11124            1 :                 is_open: false,
   11125            1 :                 data,
   11126            1 :             }
   11127              :         };
   11128              : 
   11129            1 :         let (open_layer, last_record_lsn) = {
   11130            1 :             let start_lsn = Lsn(0x70);
   11131            1 :             let mut data = Vec::new();
   11132            1 :             let mut end_lsn = Lsn(0);
   11133           11 :             for i in 0..10 {
   11134           10 :                 let key = get_key(i);
   11135           10 :                 let lsn = Lsn(start_lsn.0 + i as u64);
   11136           10 :                 let delta = format!("@{lsn}");
   11137           10 :                 data.push((
   11138           10 :                     key,
   11139           10 :                     lsn,
   11140           10 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11141           10 :                 ));
   11142           10 : 
   11143           10 :                 expected_key_values
   11144           10 :                     .get_mut(&key)
   11145           10 :                     .expect("An image exists for each key")
   11146           10 :                     .push_str(delta.as_str());
   11147           10 : 
   11148           10 :                 end_lsn = std::cmp::max(end_lsn, lsn);
   11149           10 :             }
   11150              : 
   11151            1 :             (
   11152            1 :                 InMemoryLayerTestDesc {
   11153            1 :                     lsn_range: start_lsn..Lsn::MAX,
   11154            1 :                     is_open: true,
   11155            1 :                     data,
   11156            1 :                 },
   11157            1 :                 end_lsn,
   11158            1 :             )
   11159              :         };
   11160              : 
   11161            1 :         assert!(
   11162            1 :             nested_image_layer_lsn > frozen_layer.lsn_range.start
   11163            1 :                 && nested_image_layer_lsn < frozen_layer.lsn_range.end
   11164              :         );
   11165              : 
   11166            1 :         let tline = tenant
   11167            1 :             .create_test_timeline_with_layers(
   11168            1 :                 TIMELINE_ID,
   11169            1 :                 baseline_image_layer_lsn,
   11170            1 :                 DEFAULT_PG_VERSION,
   11171            1 :                 &ctx,
   11172            1 :                 vec![open_layer, frozen_layer], // in-memory layers
   11173            1 :                 Vec::new(),                     // delta layers
   11174            1 :                 vec![
   11175            1 :                     (baseline_image_layer_lsn, baseline_img_layer),
   11176            1 :                     (nested_image_layer_lsn, nested_img_layer),
   11177            1 :                 ], // image layers
   11178            1 :                 last_record_lsn,
   11179            1 :             )
   11180            1 :             .await?;
   11181              : 
   11182            1 :         let query = VersionedKeySpaceQuery::uniform(
   11183            1 :             KeySpace::single(get_key(0)..get_key(10)),
   11184            1 :             last_record_lsn,
   11185              :         );
   11186              : 
   11187            1 :         let results = tline
   11188            1 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   11189            1 :             .await
   11190            1 :             .expect("No vectored errors");
   11191           11 :         for (key, res) in results {
   11192           10 :             let value = res.expect("No key errors");
   11193           10 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   11194           10 :             assert_eq!(value, Bytes::from(expected_value.clone()));
   11195            1 : 
   11196           10 :             tracing::info!("key={key} value={expected_value}");
   11197            1 :         }
   11198            1 : 
   11199            1 :         Ok(())
   11200            1 :     }
   11201              : 
   11202              :     // A randomized read path test. Generates a layer map according to a deterministic
   11203              :     // specification. Fills the (key, LSN) space in random manner and then performs
   11204              :     // random scattered queries validating the results against in-memory storage.
   11205              :     //
   11206              :     // See this internal Notion page for a diagram of the layer map:
   11207              :     // https://www.notion.so/neondatabase/Read-Path-Unit-Testing-Fuzzing-1d1f189e0047806c8e5cd37781b0a350?pvs=4
   11208              :     //
   11209              :     // A fuzzing mode is also supported. In this mode, the test will use a random
   11210              :     // seed instead of a hardcoded one. Use it in conjunction with `cargo stress`
   11211              :     // to run multiple instances in parallel:
   11212              :     //
   11213              :     // $ RUST_BACKTRACE=1 RUST_LOG=INFO \
   11214              :     //   cargo stress --package=pageserver --features=testing,fuzz-read-path --release -- test_read_path
   11215              :     #[cfg(feature = "testing")]
   11216              :     #[tokio::test]
   11217            1 :     async fn test_read_path() -> anyhow::Result<()> {
   11218              :         use rand::seq::SliceRandom;
   11219              : 
   11220            1 :         let seed = if cfg!(feature = "fuzz-read-path") {
   11221            0 :             let seed: u64 = thread_rng().r#gen();
   11222            0 :             seed
   11223              :         } else {
   11224              :             // Use a hard-coded seed when not in fuzzing mode.
   11225              :             // Note that with the current approach results are not reproducible
   11226              :             // accross platforms and Rust releases.
   11227              :             const SEED: u64 = 0;
   11228            1 :             SEED
   11229              :         };
   11230              : 
   11231            1 :         let mut random = StdRng::seed_from_u64(seed);
   11232              : 
   11233            1 :         let (queries, will_init_chance, gap_chance) = if cfg!(feature = "fuzz-read-path") {
   11234              :             const QUERIES: u64 = 5000;
   11235            0 :             let will_init_chance: u8 = random.gen_range(0..=10);
   11236            0 :             let gap_chance: u8 = random.gen_range(0..=50);
   11237              : 
   11238            0 :             (QUERIES, will_init_chance, gap_chance)
   11239              :         } else {
   11240              :             const QUERIES: u64 = 1000;
   11241              :             const WILL_INIT_CHANCE: u8 = 1;
   11242              :             const GAP_CHANCE: u8 = 5;
   11243              : 
   11244            1 :             (QUERIES, WILL_INIT_CHANCE, GAP_CHANCE)
   11245              :         };
   11246              : 
   11247            1 :         let harness = TenantHarness::create("test_read_path").await?;
   11248            1 :         let (tenant, ctx) = harness.load().await;
   11249              : 
   11250            1 :         tracing::info!("Using random seed: {seed}");
   11251            1 :         tracing::info!(%will_init_chance, %gap_chance, "Fill params");
   11252              : 
   11253              :         // Define the layer map shape. Note that this part is not randomized.
   11254              : 
   11255              :         const KEY_DIMENSION_SIZE: u32 = 99;
   11256            1 :         let start_key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   11257            1 :         let end_key = start_key.add(KEY_DIMENSION_SIZE);
   11258            1 :         let total_key_range = start_key..end_key;
   11259            1 :         let total_key_range_size = end_key.to_i128() - start_key.to_i128();
   11260            1 :         let total_start_lsn = Lsn(104);
   11261            1 :         let last_record_lsn = Lsn(504);
   11262              : 
   11263            1 :         assert!(total_key_range_size % 3 == 0);
   11264              : 
   11265            1 :         let in_memory_layers_shape = vec![
   11266            1 :             (total_key_range.clone(), Lsn(304)..Lsn(400)),
   11267            1 :             (total_key_range.clone(), Lsn(400)..last_record_lsn),
   11268              :         ];
   11269              : 
   11270            1 :         let delta_layers_shape = vec![
   11271            1 :             (
   11272            1 :                 start_key..(start_key.add((total_key_range_size / 3) as u32)),
   11273            1 :                 Lsn(200)..Lsn(304),
   11274            1 :             ),
   11275            1 :             (
   11276            1 :                 (start_key.add((total_key_range_size / 3) as u32))
   11277            1 :                     ..(start_key.add((total_key_range_size * 2 / 3) as u32)),
   11278            1 :                 Lsn(200)..Lsn(304),
   11279            1 :             ),
   11280            1 :             (
   11281            1 :                 (start_key.add((total_key_range_size * 2 / 3) as u32))
   11282            1 :                     ..(start_key.add(total_key_range_size as u32)),
   11283            1 :                 Lsn(200)..Lsn(304),
   11284            1 :             ),
   11285              :         ];
   11286              : 
   11287            1 :         let image_layers_shape = vec![
   11288            1 :             (
   11289            1 :                 start_key.add((total_key_range_size * 2 / 3 - 10) as u32)
   11290            1 :                     ..start_key.add((total_key_range_size * 2 / 3 + 10) as u32),
   11291            1 :                 Lsn(456),
   11292            1 :             ),
   11293            1 :             (
   11294            1 :                 start_key.add((total_key_range_size / 3 - 10) as u32)
   11295            1 :                     ..start_key.add((total_key_range_size / 3 + 10) as u32),
   11296            1 :                 Lsn(256),
   11297            1 :             ),
   11298            1 :             (total_key_range.clone(), total_start_lsn),
   11299              :         ];
   11300              : 
   11301            1 :         let specification = TestTimelineSpecification {
   11302            1 :             start_lsn: total_start_lsn,
   11303            1 :             last_record_lsn,
   11304            1 :             in_memory_layers_shape,
   11305            1 :             delta_layers_shape,
   11306            1 :             image_layers_shape,
   11307            1 :             gap_chance,
   11308            1 :             will_init_chance,
   11309            1 :         };
   11310              : 
   11311              :         // Create and randomly fill in the layers according to the specification
   11312            1 :         let (tline, storage, interesting_lsns) = randomize_timeline(
   11313            1 :             &tenant,
   11314            1 :             TIMELINE_ID,
   11315            1 :             DEFAULT_PG_VERSION,
   11316            1 :             specification,
   11317            1 :             &mut random,
   11318            1 :             &ctx,
   11319            1 :         )
   11320            1 :         .await?;
   11321              : 
   11322              :         // Now generate queries based on the interesting lsns that we've collected.
   11323              :         //
   11324              :         // While there's still room in the query, pick and interesting LSN and a random
   11325              :         // key. Then roll the dice to see if the next key should also be included in
   11326              :         // the query. When the roll fails, break the "batch" and pick another point in the
   11327              :         // (key, LSN) space.
   11328              : 
   11329              :         const PICK_NEXT_CHANCE: u8 = 50;
   11330            1 :         for _ in 0..queries {
   11331         1000 :             let query = {
   11332         1000 :                 let mut keyspaces_at_lsn: HashMap<Lsn, KeySpaceRandomAccum> = HashMap::default();
   11333         1000 :                 let mut used_keys: HashSet<Key> = HashSet::default();
   11334            1 : 
   11335        22536 :                 while used_keys.len() < tenant.conf.max_get_vectored_keys.get() {
   11336        21536 :                     let selected_lsn = interesting_lsns.choose(&mut random).expect("not empty");
   11337        21536 :                     let mut selected_key = start_key.add(random.gen_range(0..KEY_DIMENSION_SIZE));
   11338            1 : 
   11339        37614 :                     while used_keys.len() < tenant.conf.max_get_vectored_keys.get() {
   11340        37093 :                         if used_keys.contains(&selected_key)
   11341        32154 :                             || selected_key >= start_key.add(KEY_DIMENSION_SIZE)
   11342            1 :                         {
   11343         5093 :                             break;
   11344        32000 :                         }
   11345            1 : 
   11346        32000 :                         keyspaces_at_lsn
   11347        32000 :                             .entry(*selected_lsn)
   11348        32000 :                             .or_default()
   11349        32000 :                             .add_key(selected_key);
   11350        32000 :                         used_keys.insert(selected_key);
   11351            1 : 
   11352        32000 :                         let pick_next = random.gen_range(0..=100) <= PICK_NEXT_CHANCE;
   11353        32000 :                         if pick_next {
   11354        16078 :                             selected_key = selected_key.next();
   11355        16078 :                         } else {
   11356        15922 :                             break;
   11357            1 :                         }
   11358            1 :                     }
   11359            1 :                 }
   11360            1 : 
   11361         1000 :                 VersionedKeySpaceQuery::scattered(
   11362         1000 :                     keyspaces_at_lsn
   11363         1000 :                         .into_iter()
   11364        11917 :                         .map(|(lsn, acc)| (lsn, acc.to_keyspace()))
   11365         1000 :                         .collect(),
   11366            1 :                 )
   11367            1 :             };
   11368            1 : 
   11369            1 :             // Run the query and validate the results
   11370            1 : 
   11371         1000 :             let results = tline
   11372         1000 :                 .get_vectored(query.clone(), IoConcurrency::Sequential, &ctx)
   11373         1000 :                 .await;
   11374            1 : 
   11375         1000 :             let blobs = match results {
   11376         1000 :                 Ok(ok) => ok,
   11377            1 :                 Err(err) => {
   11378            1 :                     panic!("seed={seed} Error returned for query {query}: {err}");
   11379            1 :                 }
   11380            1 :             };
   11381            1 : 
   11382        32000 :             for (key, key_res) in blobs.into_iter() {
   11383        32000 :                 match key_res {
   11384        32000 :                     Ok(blob) => {
   11385        32000 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11386        32000 :                         let expected = storage.get(key, requested_at_lsn);
   11387            1 : 
   11388        32000 :                         if blob != expected {
   11389            1 :                             tracing::error!(
   11390            1 :                                 "seed={seed} Mismatch for {key}@{requested_at_lsn} from query: {query}"
   11391            1 :                             );
   11392        32000 :                         }
   11393            1 : 
   11394        32000 :                         assert_eq!(blob, expected);
   11395            1 :                     }
   11396            1 :                     Err(err) => {
   11397            1 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11398            1 : 
   11399            1 :                         panic!(
   11400            1 :                             "seed={seed} Error returned for {key}@{requested_at_lsn} from query {query}: {err}"
   11401            1 :                         );
   11402            1 :                     }
   11403            1 :                 }
   11404            1 :             }
   11405            1 :         }
   11406            1 : 
   11407            1 :         Ok(())
   11408            1 :     }
   11409              : 
   11410          107 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   11411          107 :         (
   11412          107 :             k1.is_delta,
   11413          107 :             k1.key_range.start,
   11414          107 :             k1.key_range.end,
   11415          107 :             k1.lsn_range.start,
   11416          107 :             k1.lsn_range.end,
   11417          107 :         )
   11418          107 :             .cmp(&(
   11419          107 :                 k2.is_delta,
   11420          107 :                 k2.key_range.start,
   11421          107 :                 k2.key_range.end,
   11422          107 :                 k2.lsn_range.start,
   11423          107 :                 k2.lsn_range.end,
   11424          107 :             ))
   11425          107 :     }
   11426              : 
   11427           12 :     async fn inspect_and_sort(
   11428           12 :         tline: &Arc<Timeline>,
   11429           12 :         filter: Option<std::ops::Range<Key>>,
   11430           12 :     ) -> Vec<PersistentLayerKey> {
   11431           12 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   11432           12 :         if let Some(filter) = filter {
   11433           54 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   11434            1 :         }
   11435           12 :         all_layers.sort_by(sort_layer_key);
   11436           12 :         all_layers
   11437           12 :     }
   11438              : 
   11439              :     #[cfg(feature = "testing")]
   11440           11 :     fn check_layer_map_key_eq(
   11441           11 :         mut left: Vec<PersistentLayerKey>,
   11442           11 :         mut right: Vec<PersistentLayerKey>,
   11443           11 :     ) {
   11444           11 :         left.sort_by(sort_layer_key);
   11445           11 :         right.sort_by(sort_layer_key);
   11446           11 :         if left != right {
   11447            0 :             eprintln!("---LEFT---");
   11448            0 :             for left in left.iter() {
   11449            0 :                 eprintln!("{left}");
   11450            0 :             }
   11451            0 :             eprintln!("---RIGHT---");
   11452            0 :             for right in right.iter() {
   11453            0 :                 eprintln!("{right}");
   11454            0 :             }
   11455            0 :             assert_eq!(left, right);
   11456           11 :         }
   11457           11 :     }
   11458              : 
   11459              :     #[cfg(feature = "testing")]
   11460              :     #[tokio::test]
   11461            1 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   11462            1 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   11463            1 :         let (tenant, ctx) = harness.load().await;
   11464              : 
   11465           91 :         fn get_key(id: u32) -> Key {
   11466              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11467           91 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11468           91 :             key.field6 = id;
   11469           91 :             key
   11470           91 :         }
   11471              : 
   11472              :         // img layer at 0x10
   11473            1 :         let img_layer = (0..10)
   11474           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11475            1 :             .collect_vec();
   11476              : 
   11477            1 :         let delta1 = vec![
   11478            1 :             (
   11479            1 :                 get_key(1),
   11480            1 :                 Lsn(0x20),
   11481            1 :                 Value::Image(Bytes::from("value 1@0x20")),
   11482            1 :             ),
   11483            1 :             (
   11484            1 :                 get_key(2),
   11485            1 :                 Lsn(0x30),
   11486            1 :                 Value::Image(Bytes::from("value 2@0x30")),
   11487            1 :             ),
   11488            1 :             (
   11489            1 :                 get_key(3),
   11490            1 :                 Lsn(0x40),
   11491            1 :                 Value::Image(Bytes::from("value 3@0x40")),
   11492            1 :             ),
   11493              :         ];
   11494            1 :         let delta2 = vec![
   11495            1 :             (
   11496            1 :                 get_key(5),
   11497            1 :                 Lsn(0x20),
   11498            1 :                 Value::Image(Bytes::from("value 5@0x20")),
   11499            1 :             ),
   11500            1 :             (
   11501            1 :                 get_key(6),
   11502            1 :                 Lsn(0x20),
   11503            1 :                 Value::Image(Bytes::from("value 6@0x20")),
   11504            1 :             ),
   11505              :         ];
   11506            1 :         let delta3 = vec![
   11507            1 :             (
   11508            1 :                 get_key(8),
   11509            1 :                 Lsn(0x48),
   11510            1 :                 Value::Image(Bytes::from("value 8@0x48")),
   11511            1 :             ),
   11512            1 :             (
   11513            1 :                 get_key(9),
   11514            1 :                 Lsn(0x48),
   11515            1 :                 Value::Image(Bytes::from("value 9@0x48")),
   11516            1 :             ),
   11517              :         ];
   11518              : 
   11519            1 :         let tline = tenant
   11520            1 :             .create_test_timeline_with_layers(
   11521            1 :                 TIMELINE_ID,
   11522            1 :                 Lsn(0x10),
   11523            1 :                 DEFAULT_PG_VERSION,
   11524            1 :                 &ctx,
   11525            1 :                 vec![], // in-memory layers
   11526            1 :                 vec![
   11527            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   11528            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   11529            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   11530            1 :                 ], // delta layers
   11531            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11532            1 :                 Lsn(0x50),
   11533            1 :             )
   11534            1 :             .await?;
   11535              : 
   11536              :         {
   11537            1 :             tline
   11538            1 :                 .applied_gc_cutoff_lsn
   11539            1 :                 .lock_for_write()
   11540            1 :                 .store_and_unlock(Lsn(0x30))
   11541            1 :                 .wait()
   11542            1 :                 .await;
   11543              :             // Update GC info
   11544            1 :             let mut guard = tline.gc_info.write().unwrap();
   11545            1 :             *guard = GcInfo {
   11546            1 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   11547            1 :                 cutoffs: GcCutoffs {
   11548            1 :                     time: Some(Lsn(0x30)),
   11549            1 :                     space: Lsn(0x30),
   11550            1 :                 },
   11551            1 :                 leases: Default::default(),
   11552            1 :                 within_ancestor_pitr: false,
   11553            1 :             };
   11554              :         }
   11555              : 
   11556            1 :         let cancel = CancellationToken::new();
   11557              : 
   11558              :         // Do a partial compaction on key range 0..2
   11559            1 :         tline
   11560            1 :             .compact_with_gc(
   11561            1 :                 &cancel,
   11562            1 :                 CompactOptions {
   11563            1 :                     flags: EnumSet::new(),
   11564            1 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11565            1 :                     ..Default::default()
   11566            1 :                 },
   11567            1 :                 &ctx,
   11568            1 :             )
   11569            1 :             .await
   11570            1 :             .unwrap();
   11571            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11572            1 :         check_layer_map_key_eq(
   11573            1 :             all_layers,
   11574            1 :             vec![
   11575              :                 // newly-generated image layer for the partial compaction range 0-2
   11576            1 :                 PersistentLayerKey {
   11577            1 :                     key_range: get_key(0)..get_key(2),
   11578            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11579            1 :                     is_delta: false,
   11580            1 :                 },
   11581            1 :                 PersistentLayerKey {
   11582            1 :                     key_range: get_key(0)..get_key(10),
   11583            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11584            1 :                     is_delta: false,
   11585            1 :                 },
   11586              :                 // delta1 is split and the second part is rewritten
   11587            1 :                 PersistentLayerKey {
   11588            1 :                     key_range: get_key(2)..get_key(4),
   11589            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11590            1 :                     is_delta: true,
   11591            1 :                 },
   11592            1 :                 PersistentLayerKey {
   11593            1 :                     key_range: get_key(5)..get_key(7),
   11594            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11595            1 :                     is_delta: true,
   11596            1 :                 },
   11597            1 :                 PersistentLayerKey {
   11598            1 :                     key_range: get_key(8)..get_key(10),
   11599            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11600            1 :                     is_delta: true,
   11601            1 :                 },
   11602              :             ],
   11603              :         );
   11604              : 
   11605              :         // Do a partial compaction on key range 2..4
   11606            1 :         tline
   11607            1 :             .compact_with_gc(
   11608            1 :                 &cancel,
   11609            1 :                 CompactOptions {
   11610            1 :                     flags: EnumSet::new(),
   11611            1 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   11612            1 :                     ..Default::default()
   11613            1 :                 },
   11614            1 :                 &ctx,
   11615            1 :             )
   11616            1 :             .await
   11617            1 :             .unwrap();
   11618            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11619            1 :         check_layer_map_key_eq(
   11620            1 :             all_layers,
   11621            1 :             vec![
   11622            1 :                 PersistentLayerKey {
   11623            1 :                     key_range: get_key(0)..get_key(2),
   11624            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11625            1 :                     is_delta: false,
   11626            1 :                 },
   11627            1 :                 PersistentLayerKey {
   11628            1 :                     key_range: get_key(0)..get_key(10),
   11629            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11630            1 :                     is_delta: false,
   11631            1 :                 },
   11632              :                 // image layer generated for the compaction range 2-4
   11633            1 :                 PersistentLayerKey {
   11634            1 :                     key_range: get_key(2)..get_key(4),
   11635            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11636            1 :                     is_delta: false,
   11637            1 :                 },
   11638              :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   11639            1 :                 PersistentLayerKey {
   11640            1 :                     key_range: get_key(2)..get_key(4),
   11641            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11642            1 :                     is_delta: true,
   11643            1 :                 },
   11644            1 :                 PersistentLayerKey {
   11645            1 :                     key_range: get_key(5)..get_key(7),
   11646            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11647            1 :                     is_delta: true,
   11648            1 :                 },
   11649            1 :                 PersistentLayerKey {
   11650            1 :                     key_range: get_key(8)..get_key(10),
   11651            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11652            1 :                     is_delta: true,
   11653            1 :                 },
   11654              :             ],
   11655              :         );
   11656              : 
   11657              :         // Do a partial compaction on key range 4..9
   11658            1 :         tline
   11659            1 :             .compact_with_gc(
   11660            1 :                 &cancel,
   11661            1 :                 CompactOptions {
   11662            1 :                     flags: EnumSet::new(),
   11663            1 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   11664            1 :                     ..Default::default()
   11665            1 :                 },
   11666            1 :                 &ctx,
   11667            1 :             )
   11668            1 :             .await
   11669            1 :             .unwrap();
   11670            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11671            1 :         check_layer_map_key_eq(
   11672            1 :             all_layers,
   11673            1 :             vec![
   11674            1 :                 PersistentLayerKey {
   11675            1 :                     key_range: get_key(0)..get_key(2),
   11676            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11677            1 :                     is_delta: false,
   11678            1 :                 },
   11679            1 :                 PersistentLayerKey {
   11680            1 :                     key_range: get_key(0)..get_key(10),
   11681            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11682            1 :                     is_delta: false,
   11683            1 :                 },
   11684            1 :                 PersistentLayerKey {
   11685            1 :                     key_range: get_key(2)..get_key(4),
   11686            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11687            1 :                     is_delta: false,
   11688            1 :                 },
   11689            1 :                 PersistentLayerKey {
   11690            1 :                     key_range: get_key(2)..get_key(4),
   11691            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11692            1 :                     is_delta: true,
   11693            1 :                 },
   11694              :                 // image layer generated for this compaction range
   11695            1 :                 PersistentLayerKey {
   11696            1 :                     key_range: get_key(4)..get_key(9),
   11697            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11698            1 :                     is_delta: false,
   11699            1 :                 },
   11700            1 :                 PersistentLayerKey {
   11701            1 :                     key_range: get_key(8)..get_key(10),
   11702            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11703            1 :                     is_delta: true,
   11704            1 :                 },
   11705              :             ],
   11706              :         );
   11707              : 
   11708              :         // Do a partial compaction on key range 9..10
   11709            1 :         tline
   11710            1 :             .compact_with_gc(
   11711            1 :                 &cancel,
   11712            1 :                 CompactOptions {
   11713            1 :                     flags: EnumSet::new(),
   11714            1 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   11715            1 :                     ..Default::default()
   11716            1 :                 },
   11717            1 :                 &ctx,
   11718            1 :             )
   11719            1 :             .await
   11720            1 :             .unwrap();
   11721            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11722            1 :         check_layer_map_key_eq(
   11723            1 :             all_layers,
   11724            1 :             vec![
   11725            1 :                 PersistentLayerKey {
   11726            1 :                     key_range: get_key(0)..get_key(2),
   11727            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11728            1 :                     is_delta: false,
   11729            1 :                 },
   11730            1 :                 PersistentLayerKey {
   11731            1 :                     key_range: get_key(0)..get_key(10),
   11732            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11733            1 :                     is_delta: false,
   11734            1 :                 },
   11735            1 :                 PersistentLayerKey {
   11736            1 :                     key_range: get_key(2)..get_key(4),
   11737            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11738            1 :                     is_delta: false,
   11739            1 :                 },
   11740            1 :                 PersistentLayerKey {
   11741            1 :                     key_range: get_key(2)..get_key(4),
   11742            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11743            1 :                     is_delta: true,
   11744            1 :                 },
   11745            1 :                 PersistentLayerKey {
   11746            1 :                     key_range: get_key(4)..get_key(9),
   11747            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11748            1 :                     is_delta: false,
   11749            1 :                 },
   11750              :                 // image layer generated for the compaction range
   11751            1 :                 PersistentLayerKey {
   11752            1 :                     key_range: get_key(9)..get_key(10),
   11753            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11754            1 :                     is_delta: false,
   11755            1 :                 },
   11756            1 :                 PersistentLayerKey {
   11757            1 :                     key_range: get_key(8)..get_key(10),
   11758            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11759            1 :                     is_delta: true,
   11760            1 :                 },
   11761              :             ],
   11762              :         );
   11763              : 
   11764              :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   11765            1 :         tline
   11766            1 :             .compact_with_gc(
   11767            1 :                 &cancel,
   11768            1 :                 CompactOptions {
   11769            1 :                     flags: EnumSet::new(),
   11770            1 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   11771            1 :                     ..Default::default()
   11772            1 :                 },
   11773            1 :                 &ctx,
   11774            1 :             )
   11775            1 :             .await
   11776            1 :             .unwrap();
   11777            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11778            1 :         check_layer_map_key_eq(
   11779            1 :             all_layers,
   11780            1 :             vec![
   11781              :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   11782            1 :                 PersistentLayerKey {
   11783            1 :                     key_range: get_key(0)..get_key(10),
   11784            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11785            1 :                     is_delta: false,
   11786            1 :                 },
   11787            1 :                 PersistentLayerKey {
   11788            1 :                     key_range: get_key(2)..get_key(4),
   11789            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11790            1 :                     is_delta: true,
   11791            1 :                 },
   11792            1 :                 PersistentLayerKey {
   11793            1 :                     key_range: get_key(8)..get_key(10),
   11794            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11795            1 :                     is_delta: true,
   11796            1 :                 },
   11797              :             ],
   11798              :         );
   11799            2 :         Ok(())
   11800            1 :     }
   11801              : 
   11802              :     #[cfg(feature = "testing")]
   11803              :     #[tokio::test]
   11804            1 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   11805            1 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   11806            1 :             .await
   11807            1 :             .unwrap();
   11808            1 :         let (tenant, ctx) = harness.load().await;
   11809            1 :         let tline_parent = tenant
   11810            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   11811            1 :             .await
   11812            1 :             .unwrap();
   11813            1 :         let tline_child = tenant
   11814            1 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   11815            1 :             .await
   11816            1 :             .unwrap();
   11817              :         {
   11818            1 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11819            1 :             assert_eq!(
   11820            1 :                 gc_info_parent.retain_lsns,
   11821            1 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   11822              :             );
   11823              :         }
   11824              :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   11825            1 :         tline_child
   11826            1 :             .remote_client
   11827            1 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   11828            1 :             .unwrap();
   11829            1 :         tline_child.remote_client.wait_completion().await.unwrap();
   11830            1 :         offload_timeline(&tenant, &tline_child)
   11831            1 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   11832            1 :             .await.unwrap();
   11833            1 :         let child_timeline_id = tline_child.timeline_id;
   11834            1 :         Arc::try_unwrap(tline_child).unwrap();
   11835              : 
   11836              :         {
   11837            1 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11838            1 :             assert_eq!(
   11839            1 :                 gc_info_parent.retain_lsns,
   11840            1 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   11841              :             );
   11842              :         }
   11843              : 
   11844            1 :         tenant
   11845            1 :             .get_offloaded_timeline(child_timeline_id)
   11846            1 :             .unwrap()
   11847            1 :             .defuse_for_tenant_drop();
   11848              : 
   11849            2 :         Ok(())
   11850            1 :     }
   11851              : 
   11852              :     #[cfg(feature = "testing")]
   11853              :     #[tokio::test]
   11854            1 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   11855            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   11856            1 :         let (tenant, ctx) = harness.load().await;
   11857              : 
   11858          148 :         fn get_key(id: u32) -> Key {
   11859              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11860          148 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11861          148 :             key.field6 = id;
   11862          148 :             key
   11863          148 :         }
   11864              : 
   11865            1 :         let img_layer = (0..10)
   11866           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11867            1 :             .collect_vec();
   11868              : 
   11869            1 :         let delta1 = vec![(
   11870            1 :             get_key(1),
   11871            1 :             Lsn(0x20),
   11872            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11873            1 :         )];
   11874            1 :         let delta4 = vec![(
   11875            1 :             get_key(1),
   11876            1 :             Lsn(0x28),
   11877            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11878            1 :         )];
   11879            1 :         let delta2 = vec![
   11880            1 :             (
   11881            1 :                 get_key(1),
   11882            1 :                 Lsn(0x30),
   11883            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11884            1 :             ),
   11885            1 :             (
   11886            1 :                 get_key(1),
   11887            1 :                 Lsn(0x38),
   11888            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11889            1 :             ),
   11890              :         ];
   11891            1 :         let delta3 = vec![
   11892            1 :             (
   11893            1 :                 get_key(8),
   11894            1 :                 Lsn(0x48),
   11895            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11896            1 :             ),
   11897            1 :             (
   11898            1 :                 get_key(9),
   11899            1 :                 Lsn(0x48),
   11900            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11901            1 :             ),
   11902              :         ];
   11903              : 
   11904            1 :         let tline = tenant
   11905            1 :             .create_test_timeline_with_layers(
   11906            1 :                 TIMELINE_ID,
   11907            1 :                 Lsn(0x10),
   11908            1 :                 DEFAULT_PG_VERSION,
   11909            1 :                 &ctx,
   11910            1 :                 vec![], // in-memory layers
   11911            1 :                 vec![
   11912            1 :                     // delta1/2/4 only contain a single key but multiple updates
   11913            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11914            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11915            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11916            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11917            1 :                 ], // delta layers
   11918            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11919            1 :                 Lsn(0x50),
   11920            1 :             )
   11921            1 :             .await?;
   11922              :         {
   11923            1 :             tline
   11924            1 :                 .applied_gc_cutoff_lsn
   11925            1 :                 .lock_for_write()
   11926            1 :                 .store_and_unlock(Lsn(0x30))
   11927            1 :                 .wait()
   11928            1 :                 .await;
   11929              :             // Update GC info
   11930            1 :             let mut guard = tline.gc_info.write().unwrap();
   11931            1 :             *guard = GcInfo {
   11932            1 :                 retain_lsns: vec![
   11933            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11934            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11935            1 :                 ],
   11936            1 :                 cutoffs: GcCutoffs {
   11937            1 :                     time: Some(Lsn(0x30)),
   11938            1 :                     space: Lsn(0x30),
   11939            1 :                 },
   11940            1 :                 leases: Default::default(),
   11941            1 :                 within_ancestor_pitr: false,
   11942            1 :             };
   11943              :         }
   11944              : 
   11945            1 :         let expected_result = [
   11946            1 :             Bytes::from_static(b"value 0@0x10"),
   11947            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11948            1 :             Bytes::from_static(b"value 2@0x10"),
   11949            1 :             Bytes::from_static(b"value 3@0x10"),
   11950            1 :             Bytes::from_static(b"value 4@0x10"),
   11951            1 :             Bytes::from_static(b"value 5@0x10"),
   11952            1 :             Bytes::from_static(b"value 6@0x10"),
   11953            1 :             Bytes::from_static(b"value 7@0x10"),
   11954            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11955            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11956            1 :         ];
   11957              : 
   11958            1 :         let expected_result_at_gc_horizon = [
   11959            1 :             Bytes::from_static(b"value 0@0x10"),
   11960            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11961            1 :             Bytes::from_static(b"value 2@0x10"),
   11962            1 :             Bytes::from_static(b"value 3@0x10"),
   11963            1 :             Bytes::from_static(b"value 4@0x10"),
   11964            1 :             Bytes::from_static(b"value 5@0x10"),
   11965            1 :             Bytes::from_static(b"value 6@0x10"),
   11966            1 :             Bytes::from_static(b"value 7@0x10"),
   11967            1 :             Bytes::from_static(b"value 8@0x10"),
   11968            1 :             Bytes::from_static(b"value 9@0x10"),
   11969            1 :         ];
   11970              : 
   11971            1 :         let expected_result_at_lsn_20 = [
   11972            1 :             Bytes::from_static(b"value 0@0x10"),
   11973            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11974            1 :             Bytes::from_static(b"value 2@0x10"),
   11975            1 :             Bytes::from_static(b"value 3@0x10"),
   11976            1 :             Bytes::from_static(b"value 4@0x10"),
   11977            1 :             Bytes::from_static(b"value 5@0x10"),
   11978            1 :             Bytes::from_static(b"value 6@0x10"),
   11979            1 :             Bytes::from_static(b"value 7@0x10"),
   11980            1 :             Bytes::from_static(b"value 8@0x10"),
   11981            1 :             Bytes::from_static(b"value 9@0x10"),
   11982            1 :         ];
   11983              : 
   11984            1 :         let expected_result_at_lsn_10 = [
   11985            1 :             Bytes::from_static(b"value 0@0x10"),
   11986            1 :             Bytes::from_static(b"value 1@0x10"),
   11987            1 :             Bytes::from_static(b"value 2@0x10"),
   11988            1 :             Bytes::from_static(b"value 3@0x10"),
   11989            1 :             Bytes::from_static(b"value 4@0x10"),
   11990            1 :             Bytes::from_static(b"value 5@0x10"),
   11991            1 :             Bytes::from_static(b"value 6@0x10"),
   11992            1 :             Bytes::from_static(b"value 7@0x10"),
   11993            1 :             Bytes::from_static(b"value 8@0x10"),
   11994            1 :             Bytes::from_static(b"value 9@0x10"),
   11995            1 :         ];
   11996              : 
   11997            3 :         let verify_result = || async {
   11998            3 :             let gc_horizon = {
   11999            3 :                 let gc_info = tline.gc_info.read().unwrap();
   12000            3 :                 gc_info.cutoffs.time.unwrap_or_default()
   12001              :             };
   12002           33 :             for idx in 0..10 {
   12003           30 :                 assert_eq!(
   12004           30 :                     tline
   12005           30 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   12006           30 :                         .await
   12007           30 :                         .unwrap(),
   12008           30 :                     &expected_result[idx]
   12009              :                 );
   12010           30 :                 assert_eq!(
   12011           30 :                     tline
   12012           30 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   12013           30 :                         .await
   12014           30 :                         .unwrap(),
   12015           30 :                     &expected_result_at_gc_horizon[idx]
   12016              :                 );
   12017           30 :                 assert_eq!(
   12018           30 :                     tline
   12019           30 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   12020           30 :                         .await
   12021           30 :                         .unwrap(),
   12022           30 :                     &expected_result_at_lsn_20[idx]
   12023              :                 );
   12024           30 :                 assert_eq!(
   12025           30 :                     tline
   12026           30 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   12027           30 :                         .await
   12028           30 :                         .unwrap(),
   12029           30 :                     &expected_result_at_lsn_10[idx]
   12030              :                 );
   12031              :             }
   12032            6 :         };
   12033              : 
   12034            1 :         verify_result().await;
   12035              : 
   12036            1 :         let cancel = CancellationToken::new();
   12037            1 :         tline
   12038            1 :             .compact_with_gc(
   12039            1 :                 &cancel,
   12040            1 :                 CompactOptions {
   12041            1 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   12042            1 :                     ..Default::default()
   12043            1 :                 },
   12044            1 :                 &ctx,
   12045            1 :             )
   12046            1 :             .await
   12047            1 :             .unwrap();
   12048            1 :         verify_result().await;
   12049              : 
   12050            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12051            1 :         check_layer_map_key_eq(
   12052            1 :             all_layers,
   12053            1 :             vec![
   12054              :                 // The original image layer, not compacted
   12055            1 :                 PersistentLayerKey {
   12056            1 :                     key_range: get_key(0)..get_key(10),
   12057            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12058            1 :                     is_delta: false,
   12059            1 :                 },
   12060              :                 // Delta layer below the specified above_lsn not compacted
   12061            1 :                 PersistentLayerKey {
   12062            1 :                     key_range: get_key(1)..get_key(2),
   12063            1 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   12064            1 :                     is_delta: true,
   12065            1 :                 },
   12066              :                 // Delta layer compacted above the LSN
   12067            1 :                 PersistentLayerKey {
   12068            1 :                     key_range: get_key(1)..get_key(10),
   12069            1 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   12070            1 :                     is_delta: true,
   12071            1 :                 },
   12072              :             ],
   12073              :         );
   12074              : 
   12075              :         // compact again
   12076            1 :         tline
   12077            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   12078            1 :             .await
   12079            1 :             .unwrap();
   12080            1 :         verify_result().await;
   12081              : 
   12082            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12083            1 :         check_layer_map_key_eq(
   12084            1 :             all_layers,
   12085            1 :             vec![
   12086              :                 // The compacted image layer (full key range)
   12087            1 :                 PersistentLayerKey {
   12088            1 :                     key_range: Key::MIN..Key::MAX,
   12089            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12090            1 :                     is_delta: false,
   12091            1 :                 },
   12092              :                 // All other data in the delta layer
   12093            1 :                 PersistentLayerKey {
   12094            1 :                     key_range: get_key(1)..get_key(10),
   12095            1 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12096            1 :                     is_delta: true,
   12097            1 :                 },
   12098              :             ],
   12099              :         );
   12100              : 
   12101            2 :         Ok(())
   12102            1 :     }
   12103              : 
   12104              :     #[cfg(feature = "testing")]
   12105              :     #[tokio::test]
   12106            1 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   12107            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   12108            1 :         let (tenant, ctx) = harness.load().await;
   12109              : 
   12110          254 :         fn get_key(id: u32) -> Key {
   12111              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12112          254 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12113          254 :             key.field6 = id;
   12114          254 :             key
   12115          254 :         }
   12116              : 
   12117            1 :         let img_layer = (0..10)
   12118           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12119            1 :             .collect_vec();
   12120              : 
   12121            1 :         let delta1 = vec![(
   12122            1 :             get_key(1),
   12123            1 :             Lsn(0x20),
   12124            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12125            1 :         )];
   12126            1 :         let delta4 = vec![(
   12127            1 :             get_key(1),
   12128            1 :             Lsn(0x28),
   12129            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   12130            1 :         )];
   12131            1 :         let delta2 = vec![
   12132            1 :             (
   12133            1 :                 get_key(1),
   12134            1 :                 Lsn(0x30),
   12135            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   12136            1 :             ),
   12137            1 :             (
   12138            1 :                 get_key(1),
   12139            1 :                 Lsn(0x38),
   12140            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   12141            1 :             ),
   12142              :         ];
   12143            1 :         let delta3 = vec![
   12144            1 :             (
   12145            1 :                 get_key(8),
   12146            1 :                 Lsn(0x48),
   12147            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   12148            1 :             ),
   12149            1 :             (
   12150            1 :                 get_key(9),
   12151            1 :                 Lsn(0x48),
   12152            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   12153            1 :             ),
   12154              :         ];
   12155              : 
   12156            1 :         let tline = tenant
   12157            1 :             .create_test_timeline_with_layers(
   12158            1 :                 TIMELINE_ID,
   12159            1 :                 Lsn(0x10),
   12160            1 :                 DEFAULT_PG_VERSION,
   12161            1 :                 &ctx,
   12162            1 :                 vec![], // in-memory layers
   12163            1 :                 vec![
   12164            1 :                     // delta1/2/4 only contain a single key but multiple updates
   12165            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   12166            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   12167            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   12168            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   12169            1 :                 ], // delta layers
   12170            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12171            1 :                 Lsn(0x50),
   12172            1 :             )
   12173            1 :             .await?;
   12174              :         {
   12175            1 :             tline
   12176            1 :                 .applied_gc_cutoff_lsn
   12177            1 :                 .lock_for_write()
   12178            1 :                 .store_and_unlock(Lsn(0x30))
   12179            1 :                 .wait()
   12180            1 :                 .await;
   12181              :             // Update GC info
   12182            1 :             let mut guard = tline.gc_info.write().unwrap();
   12183            1 :             *guard = GcInfo {
   12184            1 :                 retain_lsns: vec![
   12185            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   12186            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   12187            1 :                 ],
   12188            1 :                 cutoffs: GcCutoffs {
   12189            1 :                     time: Some(Lsn(0x30)),
   12190            1 :                     space: Lsn(0x30),
   12191            1 :                 },
   12192            1 :                 leases: Default::default(),
   12193            1 :                 within_ancestor_pitr: false,
   12194            1 :             };
   12195              :         }
   12196              : 
   12197            1 :         let expected_result = [
   12198            1 :             Bytes::from_static(b"value 0@0x10"),
   12199            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   12200            1 :             Bytes::from_static(b"value 2@0x10"),
   12201            1 :             Bytes::from_static(b"value 3@0x10"),
   12202            1 :             Bytes::from_static(b"value 4@0x10"),
   12203            1 :             Bytes::from_static(b"value 5@0x10"),
   12204            1 :             Bytes::from_static(b"value 6@0x10"),
   12205            1 :             Bytes::from_static(b"value 7@0x10"),
   12206            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   12207            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   12208            1 :         ];
   12209              : 
   12210            1 :         let expected_result_at_gc_horizon = [
   12211            1 :             Bytes::from_static(b"value 0@0x10"),
   12212            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   12213            1 :             Bytes::from_static(b"value 2@0x10"),
   12214            1 :             Bytes::from_static(b"value 3@0x10"),
   12215            1 :             Bytes::from_static(b"value 4@0x10"),
   12216            1 :             Bytes::from_static(b"value 5@0x10"),
   12217            1 :             Bytes::from_static(b"value 6@0x10"),
   12218            1 :             Bytes::from_static(b"value 7@0x10"),
   12219            1 :             Bytes::from_static(b"value 8@0x10"),
   12220            1 :             Bytes::from_static(b"value 9@0x10"),
   12221            1 :         ];
   12222              : 
   12223            1 :         let expected_result_at_lsn_20 = [
   12224            1 :             Bytes::from_static(b"value 0@0x10"),
   12225            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   12226            1 :             Bytes::from_static(b"value 2@0x10"),
   12227            1 :             Bytes::from_static(b"value 3@0x10"),
   12228            1 :             Bytes::from_static(b"value 4@0x10"),
   12229            1 :             Bytes::from_static(b"value 5@0x10"),
   12230            1 :             Bytes::from_static(b"value 6@0x10"),
   12231            1 :             Bytes::from_static(b"value 7@0x10"),
   12232            1 :             Bytes::from_static(b"value 8@0x10"),
   12233            1 :             Bytes::from_static(b"value 9@0x10"),
   12234            1 :         ];
   12235              : 
   12236            1 :         let expected_result_at_lsn_10 = [
   12237            1 :             Bytes::from_static(b"value 0@0x10"),
   12238            1 :             Bytes::from_static(b"value 1@0x10"),
   12239            1 :             Bytes::from_static(b"value 2@0x10"),
   12240            1 :             Bytes::from_static(b"value 3@0x10"),
   12241            1 :             Bytes::from_static(b"value 4@0x10"),
   12242            1 :             Bytes::from_static(b"value 5@0x10"),
   12243            1 :             Bytes::from_static(b"value 6@0x10"),
   12244            1 :             Bytes::from_static(b"value 7@0x10"),
   12245            1 :             Bytes::from_static(b"value 8@0x10"),
   12246            1 :             Bytes::from_static(b"value 9@0x10"),
   12247            1 :         ];
   12248              : 
   12249            5 :         let verify_result = || async {
   12250            5 :             let gc_horizon = {
   12251            5 :                 let gc_info = tline.gc_info.read().unwrap();
   12252            5 :                 gc_info.cutoffs.time.unwrap_or_default()
   12253              :             };
   12254           55 :             for idx in 0..10 {
   12255           50 :                 assert_eq!(
   12256           50 :                     tline
   12257           50 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   12258           50 :                         .await
   12259           50 :                         .unwrap(),
   12260           50 :                     &expected_result[idx]
   12261              :                 );
   12262           50 :                 assert_eq!(
   12263           50 :                     tline
   12264           50 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   12265           50 :                         .await
   12266           50 :                         .unwrap(),
   12267           50 :                     &expected_result_at_gc_horizon[idx]
   12268              :                 );
   12269           50 :                 assert_eq!(
   12270           50 :                     tline
   12271           50 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   12272           50 :                         .await
   12273           50 :                         .unwrap(),
   12274           50 :                     &expected_result_at_lsn_20[idx]
   12275              :                 );
   12276           50 :                 assert_eq!(
   12277           50 :                     tline
   12278           50 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   12279           50 :                         .await
   12280           50 :                         .unwrap(),
   12281           50 :                     &expected_result_at_lsn_10[idx]
   12282              :                 );
   12283              :             }
   12284           10 :         };
   12285              : 
   12286            1 :         verify_result().await;
   12287              : 
   12288            1 :         let cancel = CancellationToken::new();
   12289              : 
   12290            1 :         tline
   12291            1 :             .compact_with_gc(
   12292            1 :                 &cancel,
   12293            1 :                 CompactOptions {
   12294            1 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   12295            1 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   12296            1 :                     ..Default::default()
   12297            1 :                 },
   12298            1 :                 &ctx,
   12299            1 :             )
   12300            1 :             .await
   12301            1 :             .unwrap();
   12302            1 :         verify_result().await;
   12303              : 
   12304            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12305            1 :         check_layer_map_key_eq(
   12306            1 :             all_layers,
   12307            1 :             vec![
   12308              :                 // The original image layer, not compacted
   12309            1 :                 PersistentLayerKey {
   12310            1 :                     key_range: get_key(0)..get_key(10),
   12311            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12312            1 :                     is_delta: false,
   12313            1 :                 },
   12314              :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   12315              :                 // the layer 0x28-0x30 into one.
   12316            1 :                 PersistentLayerKey {
   12317            1 :                     key_range: get_key(1)..get_key(2),
   12318            1 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12319            1 :                     is_delta: true,
   12320            1 :                 },
   12321              :                 // Above the upper bound and untouched
   12322            1 :                 PersistentLayerKey {
   12323            1 :                     key_range: get_key(1)..get_key(2),
   12324            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12325            1 :                     is_delta: true,
   12326            1 :                 },
   12327              :                 // This layer is untouched
   12328            1 :                 PersistentLayerKey {
   12329            1 :                     key_range: get_key(8)..get_key(10),
   12330            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12331            1 :                     is_delta: true,
   12332            1 :                 },
   12333              :             ],
   12334              :         );
   12335              : 
   12336            1 :         tline
   12337            1 :             .compact_with_gc(
   12338            1 :                 &cancel,
   12339            1 :                 CompactOptions {
   12340            1 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   12341            1 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   12342            1 :                     ..Default::default()
   12343            1 :                 },
   12344            1 :                 &ctx,
   12345            1 :             )
   12346            1 :             .await
   12347            1 :             .unwrap();
   12348            1 :         verify_result().await;
   12349              : 
   12350            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12351            1 :         check_layer_map_key_eq(
   12352            1 :             all_layers,
   12353            1 :             vec![
   12354              :                 // The original image layer, not compacted
   12355            1 :                 PersistentLayerKey {
   12356            1 :                     key_range: get_key(0)..get_key(10),
   12357            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12358            1 :                     is_delta: false,
   12359            1 :                 },
   12360              :                 // Not in the compaction key range, uncompacted
   12361            1 :                 PersistentLayerKey {
   12362            1 :                     key_range: get_key(1)..get_key(2),
   12363            1 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12364            1 :                     is_delta: true,
   12365            1 :                 },
   12366              :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   12367            1 :                 PersistentLayerKey {
   12368            1 :                     key_range: get_key(1)..get_key(2),
   12369            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12370            1 :                     is_delta: true,
   12371            1 :                 },
   12372              :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   12373              :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   12374              :                 // becomes 0x50.
   12375            1 :                 PersistentLayerKey {
   12376            1 :                     key_range: get_key(8)..get_key(10),
   12377            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12378            1 :                     is_delta: true,
   12379            1 :                 },
   12380              :             ],
   12381              :         );
   12382              : 
   12383              :         // compact again
   12384            1 :         tline
   12385            1 :             .compact_with_gc(
   12386            1 :                 &cancel,
   12387            1 :                 CompactOptions {
   12388            1 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   12389            1 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   12390            1 :                     ..Default::default()
   12391            1 :                 },
   12392            1 :                 &ctx,
   12393            1 :             )
   12394            1 :             .await
   12395            1 :             .unwrap();
   12396            1 :         verify_result().await;
   12397              : 
   12398            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12399            1 :         check_layer_map_key_eq(
   12400            1 :             all_layers,
   12401            1 :             vec![
   12402              :                 // The original image layer, not compacted
   12403            1 :                 PersistentLayerKey {
   12404            1 :                     key_range: get_key(0)..get_key(10),
   12405            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12406            1 :                     is_delta: false,
   12407            1 :                 },
   12408              :                 // The range gets compacted
   12409            1 :                 PersistentLayerKey {
   12410            1 :                     key_range: get_key(1)..get_key(2),
   12411            1 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   12412            1 :                     is_delta: true,
   12413            1 :                 },
   12414              :                 // Not touched during this iteration of compaction
   12415            1 :                 PersistentLayerKey {
   12416            1 :                     key_range: get_key(8)..get_key(10),
   12417            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12418            1 :                     is_delta: true,
   12419            1 :                 },
   12420              :             ],
   12421              :         );
   12422              : 
   12423              :         // final full compaction
   12424            1 :         tline
   12425            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   12426            1 :             .await
   12427            1 :             .unwrap();
   12428            1 :         verify_result().await;
   12429              : 
   12430            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12431            1 :         check_layer_map_key_eq(
   12432            1 :             all_layers,
   12433            1 :             vec![
   12434              :                 // The compacted image layer (full key range)
   12435            1 :                 PersistentLayerKey {
   12436            1 :                     key_range: Key::MIN..Key::MAX,
   12437            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12438            1 :                     is_delta: false,
   12439            1 :                 },
   12440              :                 // All other data in the delta layer
   12441            1 :                 PersistentLayerKey {
   12442            1 :                     key_range: get_key(1)..get_key(10),
   12443            1 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12444            1 :                     is_delta: true,
   12445            1 :                 },
   12446              :             ],
   12447              :         );
   12448              : 
   12449            2 :         Ok(())
   12450            1 :     }
   12451              : 
   12452              :     #[cfg(feature = "testing")]
   12453              :     #[tokio::test]
   12454            1 :     async fn test_bottom_most_compation_redo_failure() -> anyhow::Result<()> {
   12455            1 :         let harness = TenantHarness::create("test_bottom_most_compation_redo_failure").await?;
   12456            1 :         let (tenant, ctx) = harness.load().await;
   12457              : 
   12458           13 :         fn get_key(id: u32) -> Key {
   12459              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12460           13 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12461           13 :             key.field6 = id;
   12462           13 :             key
   12463           13 :         }
   12464              : 
   12465            1 :         let img_layer = (0..10)
   12466           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12467            1 :             .collect_vec();
   12468              : 
   12469            1 :         let delta1 = vec![
   12470            1 :             (
   12471            1 :                 get_key(1),
   12472            1 :                 Lsn(0x20),
   12473            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12474            1 :             ),
   12475            1 :             (
   12476            1 :                 get_key(1),
   12477            1 :                 Lsn(0x24),
   12478            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x24")),
   12479            1 :             ),
   12480            1 :             (
   12481            1 :                 get_key(1),
   12482            1 :                 Lsn(0x28),
   12483            1 :                 // This record will fail to redo
   12484            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("@0x28", "???")),
   12485            1 :             ),
   12486              :         ];
   12487              : 
   12488            1 :         let tline = tenant
   12489            1 :             .create_test_timeline_with_layers(
   12490            1 :                 TIMELINE_ID,
   12491            1 :                 Lsn(0x10),
   12492            1 :                 DEFAULT_PG_VERSION,
   12493            1 :                 &ctx,
   12494            1 :                 vec![], // in-memory layers
   12495            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   12496            1 :                     Lsn(0x20)..Lsn(0x30),
   12497            1 :                     delta1,
   12498            1 :                 )], // delta layers
   12499            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12500            1 :                 Lsn(0x50),
   12501            1 :             )
   12502            1 :             .await?;
   12503              :         {
   12504            1 :             tline
   12505            1 :                 .applied_gc_cutoff_lsn
   12506            1 :                 .lock_for_write()
   12507            1 :                 .store_and_unlock(Lsn(0x30))
   12508            1 :                 .wait()
   12509            1 :                 .await;
   12510              :             // Update GC info
   12511            1 :             let mut guard = tline.gc_info.write().unwrap();
   12512            1 :             *guard = GcInfo {
   12513            1 :                 retain_lsns: vec![],
   12514            1 :                 cutoffs: GcCutoffs {
   12515            1 :                     time: Some(Lsn(0x30)),
   12516            1 :                     space: Lsn(0x30),
   12517            1 :                 },
   12518            1 :                 leases: Default::default(),
   12519            1 :                 within_ancestor_pitr: false,
   12520            1 :             };
   12521              :         }
   12522              : 
   12523            1 :         let cancel = CancellationToken::new();
   12524              : 
   12525              :         // Compaction will fail, but should not fire any critical error.
   12526              :         // Gc-compaction currently cannot figure out what keys are not in the keyspace during the compaction
   12527              :         // process. It will always try to redo the logs it reads and if it doesn't work, fail the entire
   12528              :         // compaction job. Tracked in <https://github.com/neondatabase/neon/issues/10395>.
   12529            1 :         let res = tline
   12530            1 :             .compact_with_gc(
   12531            1 :                 &cancel,
   12532            1 :                 CompactOptions {
   12533            1 :                     compact_key_range: None,
   12534            1 :                     compact_lsn_range: None,
   12535            1 :                     ..Default::default()
   12536            1 :                 },
   12537            1 :                 &ctx,
   12538            1 :             )
   12539            1 :             .await;
   12540            1 :         assert!(res.is_err());
   12541              : 
   12542            2 :         Ok(())
   12543            1 :     }
   12544              : 
   12545              :     #[cfg(feature = "testing")]
   12546              :     #[tokio::test]
   12547            1 :     async fn test_synthetic_size_calculation_with_invisible_branches() -> anyhow::Result<()> {
   12548              :         use pageserver_api::models::TimelineVisibilityState;
   12549              : 
   12550              :         use crate::tenant::size::gather_inputs;
   12551              : 
   12552            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
   12553            1 :             // Ensure that we don't compute gc_cutoffs (which needs reading the layer files)
   12554            1 :             pitr_interval: Some(Duration::ZERO),
   12555            1 :             ..Default::default()
   12556            1 :         };
   12557            1 :         let harness = TenantHarness::create_custom(
   12558            1 :             "test_synthetic_size_calculation_with_invisible_branches",
   12559            1 :             tenant_conf,
   12560            1 :             TenantId::generate(),
   12561            1 :             ShardIdentity::unsharded(),
   12562            1 :             Generation::new(0xdeadbeef),
   12563            1 :         )
   12564            1 :         .await?;
   12565            1 :         let (tenant, ctx) = harness.load().await;
   12566            1 :         let main_tline = tenant
   12567            1 :             .create_test_timeline_with_layers(
   12568            1 :                 TIMELINE_ID,
   12569            1 :                 Lsn(0x10),
   12570            1 :                 DEFAULT_PG_VERSION,
   12571            1 :                 &ctx,
   12572            1 :                 vec![],
   12573            1 :                 vec![],
   12574            1 :                 vec![],
   12575            1 :                 Lsn(0x100),
   12576            1 :             )
   12577            1 :             .await?;
   12578              : 
   12579            1 :         let snapshot1 = TimelineId::from_array(hex!("11223344556677881122334455667790"));
   12580            1 :         tenant
   12581            1 :             .branch_timeline_test_with_layers(
   12582            1 :                 &main_tline,
   12583            1 :                 snapshot1,
   12584            1 :                 Some(Lsn(0x20)),
   12585            1 :                 &ctx,
   12586            1 :                 vec![],
   12587            1 :                 vec![],
   12588            1 :                 Lsn(0x50),
   12589            1 :             )
   12590            1 :             .await?;
   12591            1 :         let snapshot2 = TimelineId::from_array(hex!("11223344556677881122334455667791"));
   12592            1 :         tenant
   12593            1 :             .branch_timeline_test_with_layers(
   12594            1 :                 &main_tline,
   12595            1 :                 snapshot2,
   12596            1 :                 Some(Lsn(0x30)),
   12597            1 :                 &ctx,
   12598            1 :                 vec![],
   12599            1 :                 vec![],
   12600            1 :                 Lsn(0x50),
   12601            1 :             )
   12602            1 :             .await?;
   12603            1 :         let snapshot3 = TimelineId::from_array(hex!("11223344556677881122334455667792"));
   12604            1 :         tenant
   12605            1 :             .branch_timeline_test_with_layers(
   12606            1 :                 &main_tline,
   12607            1 :                 snapshot3,
   12608            1 :                 Some(Lsn(0x40)),
   12609            1 :                 &ctx,
   12610            1 :                 vec![],
   12611            1 :                 vec![],
   12612            1 :                 Lsn(0x50),
   12613            1 :             )
   12614            1 :             .await?;
   12615            1 :         let limit = Arc::new(Semaphore::new(1));
   12616            1 :         let max_retention_period = None;
   12617            1 :         let mut logical_size_cache = HashMap::new();
   12618            1 :         let cause = LogicalSizeCalculationCause::EvictionTaskImitation;
   12619            1 :         let cancel = CancellationToken::new();
   12620              : 
   12621            1 :         let inputs = gather_inputs(
   12622            1 :             &tenant,
   12623            1 :             &limit,
   12624            1 :             max_retention_period,
   12625            1 :             &mut logical_size_cache,
   12626            1 :             cause,
   12627            1 :             &cancel,
   12628            1 :             &ctx,
   12629              :         )
   12630            1 :         .instrument(info_span!(
   12631              :             "gather_inputs",
   12632              :             tenant_id = "unknown",
   12633              :             shard_id = "unknown",
   12634              :         ))
   12635            1 :         .await?;
   12636              :         use crate::tenant::size::{LsnKind, ModelInputs, SegmentMeta};
   12637              :         use LsnKind::*;
   12638              :         use tenant_size_model::Segment;
   12639            1 :         let ModelInputs { mut segments, .. } = inputs;
   12640           15 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12641            6 :         for segment in segments.iter_mut() {
   12642            6 :             segment.segment.parent = None; // We don't care about the parent for the test
   12643            6 :             segment.segment.size = None; // We don't care about the size for the test
   12644            6 :         }
   12645            1 :         assert_eq!(
   12646              :             segments,
   12647              :             [
   12648              :                 SegmentMeta {
   12649              :                     segment: Segment {
   12650              :                         parent: None,
   12651              :                         lsn: 0x10,
   12652              :                         size: None,
   12653              :                         needed: false,
   12654              :                     },
   12655              :                     timeline_id: TIMELINE_ID,
   12656              :                     kind: BranchStart,
   12657              :                 },
   12658              :                 SegmentMeta {
   12659              :                     segment: Segment {
   12660              :                         parent: None,
   12661              :                         lsn: 0x20,
   12662              :                         size: None,
   12663              :                         needed: false,
   12664              :                     },
   12665              :                     timeline_id: TIMELINE_ID,
   12666              :                     kind: BranchPoint,
   12667              :                 },
   12668              :                 SegmentMeta {
   12669              :                     segment: Segment {
   12670              :                         parent: None,
   12671              :                         lsn: 0x30,
   12672              :                         size: None,
   12673              :                         needed: false,
   12674              :                     },
   12675              :                     timeline_id: TIMELINE_ID,
   12676              :                     kind: BranchPoint,
   12677              :                 },
   12678              :                 SegmentMeta {
   12679              :                     segment: Segment {
   12680              :                         parent: None,
   12681              :                         lsn: 0x40,
   12682              :                         size: None,
   12683              :                         needed: false,
   12684              :                     },
   12685              :                     timeline_id: TIMELINE_ID,
   12686              :                     kind: BranchPoint,
   12687              :                 },
   12688              :                 SegmentMeta {
   12689              :                     segment: Segment {
   12690              :                         parent: None,
   12691              :                         lsn: 0x100,
   12692              :                         size: None,
   12693              :                         needed: false,
   12694              :                     },
   12695              :                     timeline_id: TIMELINE_ID,
   12696              :                     kind: GcCutOff,
   12697              :                 }, // we need to retain everything above the last branch point
   12698              :                 SegmentMeta {
   12699              :                     segment: Segment {
   12700              :                         parent: None,
   12701              :                         lsn: 0x100,
   12702              :                         size: None,
   12703              :                         needed: true,
   12704              :                     },
   12705              :                     timeline_id: TIMELINE_ID,
   12706              :                     kind: BranchEnd,
   12707              :                 },
   12708              :             ]
   12709              :         );
   12710              : 
   12711            1 :         main_tline
   12712            1 :             .remote_client
   12713            1 :             .schedule_index_upload_for_timeline_invisible_state(
   12714            1 :                 TimelineVisibilityState::Invisible,
   12715            0 :             )?;
   12716            1 :         main_tline.remote_client.wait_completion().await?;
   12717            1 :         let inputs = gather_inputs(
   12718            1 :             &tenant,
   12719            1 :             &limit,
   12720            1 :             max_retention_period,
   12721            1 :             &mut logical_size_cache,
   12722            1 :             cause,
   12723            1 :             &cancel,
   12724            1 :             &ctx,
   12725              :         )
   12726            1 :         .instrument(info_span!(
   12727              :             "gather_inputs",
   12728              :             tenant_id = "unknown",
   12729              :             shard_id = "unknown",
   12730              :         ))
   12731            1 :         .await?;
   12732            1 :         let ModelInputs { mut segments, .. } = inputs;
   12733           14 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12734            5 :         for segment in segments.iter_mut() {
   12735            5 :             segment.segment.parent = None; // We don't care about the parent for the test
   12736            5 :             segment.segment.size = None; // We don't care about the size for the test
   12737            5 :         }
   12738            1 :         assert_eq!(
   12739              :             segments,
   12740              :             [
   12741              :                 SegmentMeta {
   12742              :                     segment: Segment {
   12743              :                         parent: None,
   12744              :                         lsn: 0x10,
   12745              :                         size: None,
   12746              :                         needed: false,
   12747              :                     },
   12748              :                     timeline_id: TIMELINE_ID,
   12749              :                     kind: BranchStart,
   12750              :                 },
   12751              :                 SegmentMeta {
   12752              :                     segment: Segment {
   12753              :                         parent: None,
   12754              :                         lsn: 0x20,
   12755              :                         size: None,
   12756              :                         needed: false,
   12757              :                     },
   12758              :                     timeline_id: TIMELINE_ID,
   12759              :                     kind: BranchPoint,
   12760              :                 },
   12761              :                 SegmentMeta {
   12762              :                     segment: Segment {
   12763              :                         parent: None,
   12764              :                         lsn: 0x30,
   12765              :                         size: None,
   12766              :                         needed: false,
   12767              :                     },
   12768              :                     timeline_id: TIMELINE_ID,
   12769              :                     kind: BranchPoint,
   12770              :                 },
   12771              :                 SegmentMeta {
   12772              :                     segment: Segment {
   12773              :                         parent: None,
   12774              :                         lsn: 0x40,
   12775              :                         size: None,
   12776              :                         needed: false,
   12777              :                     },
   12778              :                     timeline_id: TIMELINE_ID,
   12779              :                     kind: BranchPoint,
   12780              :                 },
   12781              :                 SegmentMeta {
   12782              :                     segment: Segment {
   12783              :                         parent: None,
   12784              :                         lsn: 0x40, // Branch end LSN == last branch point LSN
   12785              :                         size: None,
   12786              :                         needed: true,
   12787              :                     },
   12788              :                     timeline_id: TIMELINE_ID,
   12789              :                     kind: BranchEnd,
   12790              :                 },
   12791              :             ]
   12792              :         );
   12793            2 :         Ok(())
   12794            1 :     }
   12795              : }
        

Generated by: LCOV version 2.1-beta