LCOV - code coverage report
Current view: top level - pageserver/src - tenant.rs (source / functions) Coverage Total Hit
Test: ac1e0b9bf1b4ead74961174b01ba016322d3f9a6.info Lines: 77.4 % 8394 6498
Test Date: 2025-07-08 09:16:10 Functions: 62.8 % 476 299

            Line data    Source code
       1              : //! Timeline repository implementation that keeps old data in layer files, and
       2              : //! the recent changes in ephemeral files.
       3              : //!
       4              : //! See tenant/*_layer.rs files. The functions here are responsible for locating
       5              : //! the correct layer for the get/put call, walking back the timeline branching
       6              : //! history as needed.
       7              : //!
       8              : //! The files are stored in the .neon/tenants/<tenant_id>/timelines/<timeline_id>
       9              : //! directory. See docs/pageserver-storage.md for how the files are managed.
      10              : //! In addition to the layer files, there is a metadata file in the same
      11              : //! directory that contains information about the timeline, in particular its
      12              : //! parent timeline, and the last LSN that has been written to disk.
      13              : //!
      14              : 
      15              : use std::collections::hash_map::Entry;
      16              : use std::collections::{BTreeMap, HashMap, HashSet};
      17              : use std::fmt::{Debug, Display};
      18              : use std::fs::File;
      19              : use std::future::Future;
      20              : use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
      21              : use std::sync::{Arc, Mutex, Weak};
      22              : use std::time::{Duration, Instant, SystemTime};
      23              : use std::{fmt, fs};
      24              : 
      25              : use anyhow::{Context, bail};
      26              : use arc_swap::ArcSwap;
      27              : use camino::{Utf8Path, Utf8PathBuf};
      28              : use chrono::NaiveDateTime;
      29              : use enumset::EnumSet;
      30              : use futures::StreamExt;
      31              : use futures::stream::FuturesUnordered;
      32              : use itertools::Itertools as _;
      33              : use once_cell::sync::Lazy;
      34              : pub use pageserver_api::models::TenantState;
      35              : use pageserver_api::models::{self, RelSizeMigration};
      36              : use pageserver_api::models::{
      37              :     CompactInfoResponse, LsnLease, TimelineArchivalState, TimelineState, TopTenantShardItem,
      38              :     WalRedoManagerStatus,
      39              : };
      40              : use pageserver_api::shard::{ShardIdentity, ShardStripeSize, TenantShardId};
      41              : use 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 :         tenant_conf: pageserver_api::models::TenantConfig,
     184          118 :         location: AttachedLocationConfig,
     185          118 :     ) -> Self {
     186              :         // Sets a deadline before which we cannot proceed to GC due to lsn lease.
     187              :         //
     188              :         // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
     189              :         // length, we guarantee that all the leases we granted before will have a chance to renew
     190              :         // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
     191          118 :         let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
     192          118 :             Some(
     193          118 :                 tokio::time::Instant::now()
     194          118 :                     + tenant_conf
     195          118 :                         .lsn_lease_length
     196          118 :                         .unwrap_or(LsnLease::DEFAULT_LENGTH),
     197          118 :             )
     198              :         } else {
     199              :             // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
     200              :             // because we don't do GC in these modes.
     201            0 :             None
     202              :         };
     203              : 
     204          118 :         Self {
     205          118 :             tenant_conf,
     206          118 :             location,
     207          118 :             lsn_lease_deadline,
     208          118 :         }
     209          118 :     }
     210              : 
     211          118 :     fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
     212          118 :         match &location_conf.mode {
     213          118 :             LocationMode::Attached(attach_conf) => {
     214          118 :                 Ok(Self::new(location_conf.tenant_conf, *attach_conf))
     215              :             }
     216              :             LocationMode::Secondary(_) => {
     217            0 :                 anyhow::bail!(
     218            0 :                     "Attempted to construct AttachedTenantConf from a LocationConf in secondary mode"
     219              :                 )
     220              :             }
     221              :         }
     222          118 :     }
     223              : 
     224          381 :     fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
     225          381 :         self.lsn_lease_deadline
     226          381 :             .map(|d| tokio::time::Instant::now() < d)
     227          381 :             .unwrap_or(false)
     228          381 :     }
     229              : }
     230              : struct TimelinePreload {
     231              :     timeline_id: TimelineId,
     232              :     client: RemoteTimelineClient,
     233              :     index_part: Result<MaybeDeletedIndexPart, DownloadError>,
     234              :     previous_heatmap: Option<PreviousHeatmap>,
     235              : }
     236              : 
     237              : pub(crate) struct TenantPreload {
     238              :     /// The tenant manifest from remote storage, or None if no manifest was found.
     239              :     tenant_manifest: Option<TenantManifest>,
     240              :     /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
     241              :     timelines: HashMap<TimelineId, Option<TimelinePreload>>,
     242              : }
     243              : 
     244              : /// When we spawn a tenant, there is a special mode for tenant creation that
     245              : /// avoids trying to read anything from remote storage.
     246              : pub(crate) enum SpawnMode {
     247              :     /// Activate as soon as possible
     248              :     Eager,
     249              :     /// Lazy activation in the background, with the option to skip the queue if the need comes up
     250              :     Lazy,
     251              : }
     252              : 
     253              : ///
     254              : /// Tenant consists of multiple timelines. Keep them in a hash table.
     255              : ///
     256              : pub struct TenantShard {
     257              :     // Global pageserver config parameters
     258              :     pub conf: &'static PageServerConf,
     259              : 
     260              :     /// The value creation timestamp, used to measure activation delay, see:
     261              :     /// <https://github.com/neondatabase/neon/issues/4025>
     262              :     constructed_at: Instant,
     263              : 
     264              :     state: watch::Sender<TenantState>,
     265              : 
     266              :     // Overridden tenant-specific config parameters.
     267              :     // We keep pageserver_api::models::TenantConfig sturct here to preserve the information
     268              :     // about parameters that are not set.
     269              :     // This is necessary to allow global config updates.
     270              :     tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
     271              : 
     272              :     tenant_shard_id: TenantShardId,
     273              : 
     274              :     // The detailed sharding information, beyond the number/count in tenant_shard_id
     275              :     shard_identity: ShardIdentity,
     276              : 
     277              :     /// The remote storage generation, used to protect S3 objects from split-brain.
     278              :     /// Does not change over the lifetime of the [`TenantShard`] object.
     279              :     ///
     280              :     /// This duplicates the generation stored in LocationConf, but that structure is mutable:
     281              :     /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
     282              :     generation: Generation,
     283              : 
     284              :     timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
     285              : 
     286              :     /// During timeline creation, we first insert the TimelineId to the
     287              :     /// creating map, then `timelines`, then remove it from the creating map.
     288              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     289              :     timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
     290              : 
     291              :     /// Possibly offloaded and archived timelines
     292              :     /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
     293              :     timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
     294              : 
     295              :     /// Tracks the timelines that are currently importing into this tenant shard.
     296              :     ///
     297              :     /// Note that importing timelines are also present in [`Self::timelines_creating`].
     298              :     /// Keep this in mind when ordering lock acquisition.
     299              :     ///
     300              :     /// Lifetime:
     301              :     /// * An imported timeline is created while scanning the bucket on tenant attach
     302              :     ///   if the index part contains an `import_pgdata` entry and said field marks the import
     303              :     ///   as in progress.
     304              :     /// * Imported timelines are removed when the storage controller calls the post timeline
     305              :     ///   import activation endpoint.
     306              :     timelines_importing: std::sync::Mutex<HashMap<TimelineId, Arc<ImportingTimeline>>>,
     307              : 
     308              :     /// The last tenant manifest known to be in remote storage. None if the manifest has not yet
     309              :     /// been either downloaded or uploaded. Always Some after tenant attach.
     310              :     ///
     311              :     /// Initially populated during tenant attach, updated via `maybe_upload_tenant_manifest`.
     312              :     ///
     313              :     /// Do not modify this directly. It is used to check whether a new manifest needs to be
     314              :     /// uploaded. The manifest is constructed in `build_tenant_manifest`, and uploaded via
     315              :     /// `maybe_upload_tenant_manifest`.
     316              :     remote_tenant_manifest: tokio::sync::Mutex<Option<TenantManifest>>,
     317              : 
     318              :     // This mutex prevents creation of new timelines during GC.
     319              :     // Adding yet another mutex (in addition to `timelines`) is needed because holding
     320              :     // `timelines` mutex during all GC iteration
     321              :     // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
     322              :     // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
     323              :     // timeout...
     324              :     gc_cs: tokio::sync::Mutex<()>,
     325              :     walredo_mgr: Option<Arc<WalRedoManager>>,
     326              : 
     327              :     /// Provides access to timeline data sitting in the remote storage.
     328              :     pub(crate) remote_storage: GenericRemoteStorage,
     329              : 
     330              :     /// Access to global deletion queue for when this tenant wants to schedule a deletion.
     331              :     deletion_queue_client: DeletionQueueClient,
     332              : 
     333              :     /// A channel to send async requests to prepare a basebackup for the basebackup cache.
     334              :     basebackup_cache: Arc<BasebackupCache>,
     335              : 
     336              :     /// Cached logical sizes updated updated on each [`TenantShard::gather_size_inputs`].
     337              :     cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
     338              :     cached_synthetic_tenant_size: Arc<AtomicU64>,
     339              : 
     340              :     eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
     341              : 
     342              :     /// Track repeated failures to compact, so that we can back off.
     343              :     /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
     344              :     compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
     345              : 
     346              :     /// Signals the tenant compaction loop that there is L0 compaction work to be done.
     347              :     pub(crate) l0_compaction_trigger: Arc<Notify>,
     348              : 
     349              :     /// Scheduled gc-compaction tasks.
     350              :     scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
     351              : 
     352              :     /// If the tenant is in Activating state, notify this to encourage it
     353              :     /// to proceed to Active as soon as possible, rather than waiting for lazy
     354              :     /// background warmup.
     355              :     pub(crate) activate_now_sem: tokio::sync::Semaphore,
     356              : 
     357              :     /// Time it took for the tenant to activate. Zero if not active yet.
     358              :     attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
     359              : 
     360              :     // Cancellation token fires when we have entered shutdown().  This is a parent of
     361              :     // Timelines' cancellation token.
     362              :     pub(crate) cancel: CancellationToken,
     363              : 
     364              :     // Users of the TenantShard such as the page service must take this Gate to avoid
     365              :     // trying to use a TenantShard which is shutting down.
     366              :     pub(crate) gate: Gate,
     367              : 
     368              :     /// Throttle applied at the top of [`Timeline::get`].
     369              :     /// All [`TenantShard::timelines`] of a given [`TenantShard`] instance share the same [`throttle::Throttle`] instance.
     370              :     pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
     371              : 
     372              :     pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
     373              : 
     374              :     /// An ongoing timeline detach concurrency limiter.
     375              :     ///
     376              :     /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
     377              :     /// to have two running at the same time. A different one can be started if an earlier one
     378              :     /// has failed for whatever reason.
     379              :     ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
     380              : 
     381              :     /// `index_part.json` based gc blocking reason tracking.
     382              :     ///
     383              :     /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
     384              :     /// proceeding.
     385              :     pub(crate) gc_block: gc_block::GcBlock,
     386              : 
     387              :     l0_flush_global_state: L0FlushGlobalState,
     388              : 
     389              :     pub(crate) feature_resolver: TenantFeatureResolver,
     390              : }
     391              : impl std::fmt::Debug for TenantShard {
     392            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     393            0 :         write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
     394            0 :     }
     395              : }
     396              : 
     397              : pub(crate) enum WalRedoManager {
     398              :     Prod(WalredoManagerId, PostgresRedoManager),
     399              :     #[cfg(test)]
     400              :     Test(harness::TestRedoManager),
     401              : }
     402              : 
     403              : #[derive(thiserror::Error, Debug)]
     404              : #[error("pageserver is shutting down")]
     405              : pub(crate) struct GlobalShutDown;
     406              : 
     407              : impl WalRedoManager {
     408            0 :     pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
     409            0 :         let id = WalredoManagerId::next();
     410            0 :         let arc = Arc::new(Self::Prod(id, mgr));
     411            0 :         let mut guard = WALREDO_MANAGERS.lock().unwrap();
     412            0 :         match &mut *guard {
     413            0 :             Some(map) => {
     414            0 :                 map.insert(id, Arc::downgrade(&arc));
     415            0 :                 Ok(arc)
     416              :             }
     417            0 :             None => Err(GlobalShutDown),
     418              :         }
     419            0 :     }
     420              : }
     421              : 
     422              : impl Drop for WalRedoManager {
     423            5 :     fn drop(&mut self) {
     424            5 :         match self {
     425            0 :             Self::Prod(id, _) => {
     426            0 :                 let mut guard = WALREDO_MANAGERS.lock().unwrap();
     427            0 :                 if let Some(map) = &mut *guard {
     428            0 :                     map.remove(id).expect("new() registers, drop() unregisters");
     429            0 :                 }
     430              :             }
     431              :             #[cfg(test)]
     432            5 :             Self::Test(_) => {
     433            5 :                 // Not applicable to test redo manager
     434            5 :             }
     435              :         }
     436            5 :     }
     437              : }
     438              : 
     439              : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
     440              : /// the walredo processes outside of the regular order.
     441              : ///
     442              : /// This is necessary to work around a systemd bug where it freezes if there are
     443              : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
     444              : #[allow(clippy::type_complexity)]
     445              : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
     446              :     Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
     447            0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
     448              : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
     449              : pub(crate) struct WalredoManagerId(u64);
     450              : impl WalredoManagerId {
     451            0 :     pub fn next() -> Self {
     452              :         static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
     453            0 :         let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     454            0 :         if id == 0 {
     455            0 :             panic!(
     456            0 :                 "WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique"
     457              :             );
     458            0 :         }
     459            0 :         Self(id)
     460            0 :     }
     461              : }
     462              : 
     463              : #[cfg(test)]
     464              : impl From<harness::TestRedoManager> for WalRedoManager {
     465          118 :     fn from(mgr: harness::TestRedoManager) -> Self {
     466          118 :         Self::Test(mgr)
     467          118 :     }
     468              : }
     469              : 
     470              : impl WalRedoManager {
     471            3 :     pub(crate) async fn shutdown(&self) -> bool {
     472            3 :         match self {
     473            0 :             Self::Prod(_, mgr) => mgr.shutdown().await,
     474              :             #[cfg(test)]
     475              :             Self::Test(_) => {
     476              :                 // Not applicable to test redo manager
     477            3 :                 true
     478              :             }
     479              :         }
     480            3 :     }
     481              : 
     482            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     483            0 :         match self {
     484            0 :             Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
     485              :             #[cfg(test)]
     486            0 :             Self::Test(_) => {
     487            0 :                 // Not applicable to test redo manager
     488            0 :             }
     489              :         }
     490            0 :     }
     491              : 
     492              :     /// # Cancel-Safety
     493              :     ///
     494              :     /// This method is cancellation-safe.
     495        26774 :     pub async fn request_redo(
     496        26774 :         &self,
     497        26774 :         key: pageserver_api::key::Key,
     498        26774 :         lsn: Lsn,
     499        26774 :         base_img: Option<(Lsn, bytes::Bytes)>,
     500        26774 :         records: Vec<(Lsn, wal_decoder::models::record::NeonWalRecord)>,
     501        26774 :         pg_version: PgMajorVersion,
     502        26774 :         redo_attempt_type: RedoAttemptType,
     503        26774 :     ) -> Result<bytes::Bytes, walredo::Error> {
     504        26774 :         match self {
     505            0 :             Self::Prod(_, mgr) => {
     506            0 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     507            0 :                     .await
     508              :             }
     509              :             #[cfg(test)]
     510        26774 :             Self::Test(mgr) => {
     511        26774 :                 mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
     512        26774 :                     .await
     513              :             }
     514              :         }
     515        26774 :     }
     516              : 
     517            0 :     pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
     518            0 :         match self {
     519            0 :             WalRedoManager::Prod(_, m) => Some(m.status()),
     520              :             #[cfg(test)]
     521            0 :             WalRedoManager::Test(_) => None,
     522              :         }
     523            0 :     }
     524              : }
     525              : 
     526              : /// A very lightweight memory representation of an offloaded timeline.
     527              : ///
     528              : /// We need to store the list of offloaded timelines so that we can perform operations on them,
     529              : /// like unoffloading them, or (at a later date), decide to perform flattening.
     530              : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
     531              : /// more offloaded timelines than we can manage ones that aren't.
     532              : pub struct OffloadedTimeline {
     533              :     pub tenant_shard_id: TenantShardId,
     534              :     pub timeline_id: TimelineId,
     535              :     pub ancestor_timeline_id: Option<TimelineId>,
     536              :     /// Whether to retain the branch lsn at the ancestor or not
     537              :     pub ancestor_retain_lsn: Option<Lsn>,
     538              : 
     539              :     /// When the timeline was archived.
     540              :     ///
     541              :     /// Present for future flattening deliberations.
     542              :     pub archived_at: NaiveDateTime,
     543              : 
     544              :     /// Prevent two tasks from deleting the timeline at the same time. If held, the
     545              :     /// timeline is being deleted. If 'true', the timeline has already been deleted.
     546              :     pub delete_progress: TimelineDeleteProgress,
     547              : 
     548              :     /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
     549              :     pub deleted_from_ancestor: AtomicBool,
     550              : 
     551              :     _metrics_guard: OffloadedTimelineMetricsGuard,
     552              : }
     553              : 
     554              : /// Increases the offloaded timeline count metric when created, and decreases when dropped.
     555              : struct OffloadedTimelineMetricsGuard;
     556              : 
     557              : impl OffloadedTimelineMetricsGuard {
     558            1 :     fn new() -> Self {
     559            1 :         TIMELINE_STATE_METRIC
     560            1 :             .with_label_values(&["offloaded"])
     561            1 :             .inc();
     562            1 :         Self
     563            1 :     }
     564              : }
     565              : 
     566              : impl Drop for OffloadedTimelineMetricsGuard {
     567            1 :     fn drop(&mut self) {
     568            1 :         TIMELINE_STATE_METRIC
     569            1 :             .with_label_values(&["offloaded"])
     570            1 :             .dec();
     571            1 :     }
     572              : }
     573              : 
     574              : impl OffloadedTimeline {
     575              :     /// Obtains an offloaded timeline from a given timeline object.
     576              :     ///
     577              :     /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
     578              :     /// the timeline is not in a stopped state.
     579              :     /// Panics if the timeline is not archived.
     580            1 :     fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
     581            1 :         let (ancestor_retain_lsn, ancestor_timeline_id) =
     582            1 :             if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
     583            1 :                 let ancestor_lsn = timeline.get_ancestor_lsn();
     584            1 :                 let ancestor_timeline_id = ancestor_timeline.timeline_id;
     585            1 :                 let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
     586            1 :                 gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
     587            1 :                 (Some(ancestor_lsn), Some(ancestor_timeline_id))
     588              :             } else {
     589            0 :                 (None, None)
     590              :             };
     591            1 :         let archived_at = timeline
     592            1 :             .remote_client
     593            1 :             .archived_at_stopped_queue()?
     594            1 :             .expect("must be called on an archived timeline");
     595            1 :         Ok(Self {
     596            1 :             tenant_shard_id: timeline.tenant_shard_id,
     597            1 :             timeline_id: timeline.timeline_id,
     598            1 :             ancestor_timeline_id,
     599            1 :             ancestor_retain_lsn,
     600            1 :             archived_at,
     601            1 : 
     602            1 :             delete_progress: timeline.delete_progress.clone(),
     603            1 :             deleted_from_ancestor: AtomicBool::new(false),
     604            1 : 
     605            1 :             _metrics_guard: OffloadedTimelineMetricsGuard::new(),
     606            1 :         })
     607            1 :     }
     608            0 :     fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
     609              :         // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
     610              :         // by the `initialize_gc_info` function.
     611              :         let OffloadedTimelineManifest {
     612            0 :             timeline_id,
     613            0 :             ancestor_timeline_id,
     614            0 :             ancestor_retain_lsn,
     615            0 :             archived_at,
     616            0 :         } = *manifest;
     617            0 :         Self {
     618            0 :             tenant_shard_id,
     619            0 :             timeline_id,
     620            0 :             ancestor_timeline_id,
     621            0 :             ancestor_retain_lsn,
     622            0 :             archived_at,
     623            0 :             delete_progress: TimelineDeleteProgress::default(),
     624            0 :             deleted_from_ancestor: AtomicBool::new(false),
     625            0 :             _metrics_guard: OffloadedTimelineMetricsGuard::new(),
     626            0 :         }
     627            0 :     }
     628            1 :     fn manifest(&self) -> OffloadedTimelineManifest {
     629              :         let Self {
     630            1 :             timeline_id,
     631            1 :             ancestor_timeline_id,
     632            1 :             ancestor_retain_lsn,
     633            1 :             archived_at,
     634              :             ..
     635            1 :         } = self;
     636            1 :         OffloadedTimelineManifest {
     637            1 :             timeline_id: *timeline_id,
     638            1 :             ancestor_timeline_id: *ancestor_timeline_id,
     639            1 :             ancestor_retain_lsn: *ancestor_retain_lsn,
     640            1 :             archived_at: *archived_at,
     641            1 :         }
     642            1 :     }
     643              :     /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
     644            0 :     fn delete_from_ancestor_with_timelines(
     645            0 :         &self,
     646            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
     647            0 :     ) {
     648            0 :         if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
     649            0 :             (self.ancestor_retain_lsn, self.ancestor_timeline_id)
     650              :         {
     651            0 :             if let Some((_, ancestor_timeline)) = timelines
     652            0 :                 .iter()
     653            0 :                 .find(|(tid, _tl)| **tid == ancestor_timeline_id)
     654              :             {
     655            0 :                 let removal_happened = ancestor_timeline
     656            0 :                     .gc_info
     657            0 :                     .write()
     658            0 :                     .unwrap()
     659            0 :                     .remove_child_offloaded(self.timeline_id);
     660            0 :                 if !removal_happened {
     661            0 :                     tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
     662            0 :                         "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
     663            0 :                 }
     664            0 :             }
     665            0 :         }
     666            0 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     667            0 :     }
     668              :     /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
     669              :     ///
     670              :     /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
     671            1 :     fn defuse_for_tenant_drop(&self) {
     672            1 :         self.deleted_from_ancestor.store(true, Ordering::Release);
     673            1 :     }
     674              : }
     675              : 
     676              : impl fmt::Debug for OffloadedTimeline {
     677            0 :     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
     678            0 :         write!(f, "OffloadedTimeline<{}>", self.timeline_id)
     679            0 :     }
     680              : }
     681              : 
     682              : impl Drop for OffloadedTimeline {
     683            1 :     fn drop(&mut self) {
     684            1 :         if !self.deleted_from_ancestor.load(Ordering::Acquire) {
     685            0 :             tracing::warn!(
     686            0 :                 "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
     687              :                 self.timeline_id
     688              :             );
     689            1 :         }
     690            1 :     }
     691              : }
     692              : 
     693              : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
     694              : pub enum MaybeOffloaded {
     695              :     Yes,
     696              :     No,
     697              : }
     698              : 
     699              : #[derive(Clone, Debug)]
     700              : pub enum TimelineOrOffloaded {
     701              :     Timeline(Arc<Timeline>),
     702              :     Offloaded(Arc<OffloadedTimeline>),
     703              :     Importing(Arc<ImportingTimeline>),
     704              : }
     705              : 
     706              : impl TimelineOrOffloaded {
     707            0 :     pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
     708            0 :         match self {
     709            0 :             TimelineOrOffloaded::Timeline(timeline) => {
     710            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline)
     711              :             }
     712            0 :             TimelineOrOffloaded::Offloaded(offloaded) => {
     713            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded)
     714              :             }
     715            0 :             TimelineOrOffloaded::Importing(importing) => {
     716            0 :                 TimelineOrOffloadedArcRef::Importing(importing)
     717              :             }
     718              :         }
     719            0 :     }
     720            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     721            0 :         self.arc_ref().tenant_shard_id()
     722            0 :     }
     723            0 :     pub fn timeline_id(&self) -> TimelineId {
     724            0 :         self.arc_ref().timeline_id()
     725            0 :     }
     726            1 :     pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
     727            1 :         match self {
     728            1 :             TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
     729            0 :             TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
     730            0 :             TimelineOrOffloaded::Importing(importing) => &importing.delete_progress,
     731              :         }
     732            1 :     }
     733            0 :     fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
     734            0 :         match self {
     735            0 :             TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
     736            0 :             TimelineOrOffloaded::Offloaded(_offloaded) => None,
     737            0 :             TimelineOrOffloaded::Importing(importing) => {
     738            0 :                 Some(importing.timeline.remote_client.clone())
     739              :             }
     740              :         }
     741            0 :     }
     742              : }
     743              : 
     744              : pub enum TimelineOrOffloadedArcRef<'a> {
     745              :     Timeline(&'a Arc<Timeline>),
     746              :     Offloaded(&'a Arc<OffloadedTimeline>),
     747              :     Importing(&'a Arc<ImportingTimeline>),
     748              : }
     749              : 
     750              : impl TimelineOrOffloadedArcRef<'_> {
     751            0 :     pub fn tenant_shard_id(&self) -> TenantShardId {
     752            0 :         match self {
     753            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
     754            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
     755            0 :             TimelineOrOffloadedArcRef::Importing(importing) => importing.timeline.tenant_shard_id,
     756              :         }
     757            0 :     }
     758            0 :     pub fn timeline_id(&self) -> TimelineId {
     759            0 :         match self {
     760            0 :             TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
     761            0 :             TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
     762            0 :             TimelineOrOffloadedArcRef::Importing(importing) => importing.timeline.timeline_id,
     763              :         }
     764            0 :     }
     765              : }
     766              : 
     767              : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
     768            0 :     fn from(timeline: &'a Arc<Timeline>) -> Self {
     769            0 :         Self::Timeline(timeline)
     770            0 :     }
     771              : }
     772              : 
     773              : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
     774            0 :     fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
     775            0 :         Self::Offloaded(timeline)
     776            0 :     }
     777              : }
     778              : 
     779              : impl<'a> From<&'a Arc<ImportingTimeline>> for TimelineOrOffloadedArcRef<'a> {
     780            0 :     fn from(timeline: &'a Arc<ImportingTimeline>) -> Self {
     781            0 :         Self::Importing(timeline)
     782            0 :     }
     783              : }
     784              : 
     785              : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
     786              : pub enum GetTimelineError {
     787              :     #[error("Timeline is shutting down")]
     788              :     ShuttingDown,
     789              :     #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
     790              :     NotActive {
     791              :         tenant_id: TenantShardId,
     792              :         timeline_id: TimelineId,
     793              :         state: TimelineState,
     794              :     },
     795              :     #[error("Timeline {tenant_id}/{timeline_id} was not found")]
     796              :     NotFound {
     797              :         tenant_id: TenantShardId,
     798              :         timeline_id: TimelineId,
     799              :     },
     800              : }
     801              : 
     802              : #[derive(Debug, thiserror::Error)]
     803              : pub enum LoadLocalTimelineError {
     804              :     #[error("FailedToLoad")]
     805              :     Load(#[source] anyhow::Error),
     806              :     #[error("FailedToResumeDeletion")]
     807              :     ResumeDeletion(#[source] anyhow::Error),
     808              : }
     809              : 
     810              : #[derive(thiserror::Error)]
     811              : pub enum DeleteTimelineError {
     812              :     #[error("NotFound")]
     813              :     NotFound,
     814              : 
     815              :     #[error("HasChildren")]
     816              :     HasChildren(Vec<TimelineId>),
     817              : 
     818              :     #[error("Timeline deletion is already in progress")]
     819              :     AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
     820              : 
     821              :     #[error("Cancelled")]
     822              :     Cancelled,
     823              : 
     824              :     #[error(transparent)]
     825              :     Other(#[from] anyhow::Error),
     826              : }
     827              : 
     828              : impl Debug for DeleteTimelineError {
     829            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     830            0 :         match self {
     831            0 :             Self::NotFound => write!(f, "NotFound"),
     832            0 :             Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
     833            0 :             Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
     834            0 :             Self::Cancelled => f.debug_tuple("Cancelled").finish(),
     835            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     836              :         }
     837            0 :     }
     838              : }
     839              : 
     840              : #[derive(thiserror::Error)]
     841              : pub enum TimelineArchivalError {
     842              :     #[error("NotFound")]
     843              :     NotFound,
     844              : 
     845              :     #[error("Timeout")]
     846              :     Timeout,
     847              : 
     848              :     #[error("Cancelled")]
     849              :     Cancelled,
     850              : 
     851              :     #[error("ancestor is archived: {}", .0)]
     852              :     HasArchivedParent(TimelineId),
     853              : 
     854              :     #[error("HasUnarchivedChildren")]
     855              :     HasUnarchivedChildren(Vec<TimelineId>),
     856              : 
     857              :     #[error("Timeline archival is already in progress")]
     858              :     AlreadyInProgress,
     859              : 
     860              :     #[error(transparent)]
     861              :     Other(anyhow::Error),
     862              : }
     863              : 
     864              : #[derive(thiserror::Error, Debug)]
     865              : pub(crate) enum TenantManifestError {
     866              :     #[error("Remote storage error: {0}")]
     867              :     RemoteStorage(anyhow::Error),
     868              : 
     869              :     #[error("Cancelled")]
     870              :     Cancelled,
     871              : }
     872              : 
     873              : impl From<TenantManifestError> for TimelineArchivalError {
     874            0 :     fn from(e: TenantManifestError) -> Self {
     875            0 :         match e {
     876            0 :             TenantManifestError::RemoteStorage(e) => Self::Other(e),
     877            0 :             TenantManifestError::Cancelled => Self::Cancelled,
     878              :         }
     879            0 :     }
     880              : }
     881              : 
     882              : impl Debug for TimelineArchivalError {
     883            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     884            0 :         match self {
     885            0 :             Self::NotFound => write!(f, "NotFound"),
     886            0 :             Self::Timeout => write!(f, "Timeout"),
     887            0 :             Self::Cancelled => write!(f, "Cancelled"),
     888            0 :             Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
     889            0 :             Self::HasUnarchivedChildren(c) => {
     890            0 :                 f.debug_tuple("HasUnarchivedChildren").field(c).finish()
     891              :             }
     892            0 :             Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
     893            0 :             Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
     894              :         }
     895            0 :     }
     896              : }
     897              : 
     898              : pub enum SetStoppingError {
     899              :     AlreadyStopping(completion::Barrier),
     900              :     Broken,
     901              : }
     902              : 
     903              : impl Debug for SetStoppingError {
     904            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     905            0 :         match self {
     906            0 :             Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
     907            0 :             Self::Broken => write!(f, "Broken"),
     908              :         }
     909            0 :     }
     910              : }
     911              : 
     912              : #[derive(thiserror::Error, Debug)]
     913              : pub(crate) enum FinalizeTimelineImportError {
     914              :     #[error("Import task not done yet")]
     915              :     ImportTaskStillRunning,
     916              :     #[error("Shutting down")]
     917              :     ShuttingDown,
     918              : }
     919              : 
     920              : /// Arguments to [`TenantShard::create_timeline`].
     921              : ///
     922              : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
     923              : /// is `None`, the result of the timeline create call is not deterministic.
     924              : ///
     925              : /// See [`CreateTimelineIdempotency`] for an idempotency key.
     926              : #[derive(Debug)]
     927              : pub(crate) enum CreateTimelineParams {
     928              :     Bootstrap(CreateTimelineParamsBootstrap),
     929              :     Branch(CreateTimelineParamsBranch),
     930              :     ImportPgdata(CreateTimelineParamsImportPgdata),
     931              : }
     932              : 
     933              : #[derive(Debug)]
     934              : pub(crate) struct CreateTimelineParamsBootstrap {
     935              :     pub(crate) new_timeline_id: TimelineId,
     936              :     pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
     937              :     pub(crate) pg_version: PgMajorVersion,
     938              : }
     939              : 
     940              : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
     941              : #[derive(Debug)]
     942              : pub(crate) struct CreateTimelineParamsBranch {
     943              :     pub(crate) new_timeline_id: TimelineId,
     944              :     pub(crate) ancestor_timeline_id: TimelineId,
     945              :     pub(crate) ancestor_start_lsn: Option<Lsn>,
     946              : }
     947              : 
     948              : #[derive(Debug)]
     949              : pub(crate) struct CreateTimelineParamsImportPgdata {
     950              :     pub(crate) new_timeline_id: TimelineId,
     951              :     pub(crate) location: import_pgdata::index_part_format::Location,
     952              :     pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     953              : }
     954              : 
     955              : /// What is used to determine idempotency of a [`TenantShard::create_timeline`] call in  [`TenantShard::start_creating_timeline`] in  [`TenantShard::start_creating_timeline`].
     956              : ///
     957              : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
     958              : ///
     959              : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
     960              : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
     961              : ///
     962              : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
     963              : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
     964              : ///
     965              : /// Notes:
     966              : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
     967              : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
     968              : ///   is not considered for idempotency. We can improve on this over time if we deem it necessary.
     969              : ///
     970              : #[derive(Debug, Clone, PartialEq, Eq)]
     971              : pub(crate) enum CreateTimelineIdempotency {
     972              :     /// NB: special treatment, see comment in [`Self`].
     973              :     FailWithConflict,
     974              :     Bootstrap {
     975              :         pg_version: PgMajorVersion,
     976              :     },
     977              :     /// NB: branches always have the same `pg_version` as their ancestor.
     978              :     /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
     979              :     /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
     980              :     /// determining the child branch pg_version.
     981              :     Branch {
     982              :         ancestor_timeline_id: TimelineId,
     983              :         ancestor_start_lsn: Lsn,
     984              :     },
     985              :     ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
     986              : }
     987              : 
     988              : #[derive(Debug, Clone, PartialEq, Eq)]
     989              : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
     990              :     idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
     991              : }
     992              : 
     993              : /// What is returned by [`TenantShard::start_creating_timeline`].
     994              : #[must_use]
     995              : enum StartCreatingTimelineResult {
     996              :     CreateGuard(TimelineCreateGuard),
     997              :     Idempotent(Arc<Timeline>),
     998              : }
     999              : 
    1000              : #[allow(clippy::large_enum_variant, reason = "TODO")]
    1001              : enum TimelineInitAndSyncResult {
    1002              :     ReadyToActivate,
    1003              :     NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
    1004              : }
    1005              : 
    1006              : #[must_use]
    1007              : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
    1008              :     timeline: Arc<Timeline>,
    1009              :     import_pgdata: import_pgdata::index_part_format::Root,
    1010              :     guard: TimelineCreateGuard,
    1011              : }
    1012              : 
    1013              : /// What is returned by [`TenantShard::create_timeline`].
    1014              : enum CreateTimelineResult {
    1015              :     Created(Arc<Timeline>),
    1016              :     Idempotent(Arc<Timeline>),
    1017              :     /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`TenantShard::timelines`] when
    1018              :     /// we return this result, nor will this concrete object ever be added there.
    1019              :     /// Cf method comment on [`TenantShard::create_timeline_import_pgdata`].
    1020              :     ImportSpawned(Arc<Timeline>),
    1021              : }
    1022              : 
    1023              : impl CreateTimelineResult {
    1024            0 :     fn discriminant(&self) -> &'static str {
    1025            0 :         match self {
    1026            0 :             Self::Created(_) => "Created",
    1027            0 :             Self::Idempotent(_) => "Idempotent",
    1028            0 :             Self::ImportSpawned(_) => "ImportSpawned",
    1029              :         }
    1030            0 :     }
    1031            0 :     fn timeline(&self) -> &Arc<Timeline> {
    1032            0 :         match self {
    1033            0 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
    1034              :         }
    1035            0 :     }
    1036              :     /// Unit test timelines aren't activated, test has to do it if it needs to.
    1037              :     #[cfg(test)]
    1038          118 :     fn into_timeline_for_test(self) -> Arc<Timeline> {
    1039          118 :         match self {
    1040          118 :             Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
    1041              :         }
    1042          118 :     }
    1043              : }
    1044              : 
    1045              : #[derive(thiserror::Error, Debug)]
    1046              : pub enum CreateTimelineError {
    1047              :     #[error("creation of timeline with the given ID is in progress")]
    1048              :     AlreadyCreating,
    1049              :     #[error("timeline already exists with different parameters")]
    1050              :     Conflict,
    1051              :     #[error(transparent)]
    1052              :     AncestorLsn(anyhow::Error),
    1053              :     #[error("ancestor timeline is not active")]
    1054              :     AncestorNotActive,
    1055              :     #[error("ancestor timeline is archived")]
    1056              :     AncestorArchived,
    1057              :     #[error("tenant shutting down")]
    1058              :     ShuttingDown,
    1059              :     #[error(transparent)]
    1060              :     Other(#[from] anyhow::Error),
    1061              : }
    1062              : 
    1063              : #[derive(thiserror::Error, Debug)]
    1064              : pub enum InitdbError {
    1065              :     #[error("Operation was cancelled")]
    1066              :     Cancelled,
    1067              :     #[error(transparent)]
    1068              :     Other(anyhow::Error),
    1069              :     #[error(transparent)]
    1070              :     Inner(postgres_initdb::Error),
    1071              : }
    1072              : 
    1073              : enum CreateTimelineCause {
    1074              :     Load,
    1075              :     Delete,
    1076              : }
    1077              : 
    1078              : #[allow(clippy::large_enum_variant, reason = "TODO")]
    1079              : enum LoadTimelineCause {
    1080              :     Attach,
    1081              :     Unoffload,
    1082              : }
    1083              : 
    1084              : #[derive(thiserror::Error, Debug)]
    1085              : pub(crate) enum GcError {
    1086              :     // The tenant is shutting down
    1087              :     #[error("tenant shutting down")]
    1088              :     TenantCancelled,
    1089              : 
    1090              :     // The tenant is shutting down
    1091              :     #[error("timeline shutting down")]
    1092              :     TimelineCancelled,
    1093              : 
    1094              :     // The tenant is in a state inelegible to run GC
    1095              :     #[error("not active")]
    1096              :     NotActive,
    1097              : 
    1098              :     // A requested GC cutoff LSN was invalid, for example it tried to move backwards
    1099              :     #[error("not active")]
    1100              :     BadLsn { why: String },
    1101              : 
    1102              :     // A remote storage error while scheduling updates after compaction
    1103              :     #[error(transparent)]
    1104              :     Remote(anyhow::Error),
    1105              : 
    1106              :     // An error reading while calculating GC cutoffs
    1107              :     #[error(transparent)]
    1108              :     GcCutoffs(PageReconstructError),
    1109              : 
    1110              :     // If GC was invoked for a particular timeline, this error means it didn't exist
    1111              :     #[error("timeline not found")]
    1112              :     TimelineNotFound,
    1113              : }
    1114              : 
    1115              : impl From<PageReconstructError> for GcError {
    1116            0 :     fn from(value: PageReconstructError) -> Self {
    1117            0 :         match value {
    1118            0 :             PageReconstructError::Cancelled => Self::TimelineCancelled,
    1119            0 :             other => Self::GcCutoffs(other),
    1120              :         }
    1121            0 :     }
    1122              : }
    1123              : 
    1124              : impl From<NotInitialized> for GcError {
    1125            0 :     fn from(value: NotInitialized) -> Self {
    1126            0 :         match value {
    1127            0 :             NotInitialized::Uninitialized => GcError::Remote(value.into()),
    1128            0 :             NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
    1129              :         }
    1130            0 :     }
    1131              : }
    1132              : 
    1133              : impl From<timeline::layer_manager::Shutdown> for GcError {
    1134            0 :     fn from(_: timeline::layer_manager::Shutdown) -> Self {
    1135            0 :         GcError::TimelineCancelled
    1136            0 :     }
    1137              : }
    1138              : 
    1139              : #[derive(thiserror::Error, Debug)]
    1140              : pub(crate) enum LoadConfigError {
    1141              :     #[error("TOML deserialization error: '{0}'")]
    1142              :     DeserializeToml(#[from] toml_edit::de::Error),
    1143              : 
    1144              :     #[error("Config not found at {0}")]
    1145              :     NotFound(Utf8PathBuf),
    1146              : }
    1147              : 
    1148              : impl TenantShard {
    1149              :     /// Yet another helper for timeline initialization.
    1150              :     ///
    1151              :     /// - Initializes the Timeline struct and inserts it into the tenant's hash map
    1152              :     /// - Scans the local timeline directory for layer files and builds the layer map
    1153              :     /// - Downloads remote index file and adds remote files to the layer map
    1154              :     /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
    1155              :     ///
    1156              :     /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
    1157              :     /// it is marked as Active.
    1158              :     #[allow(clippy::too_many_arguments)]
    1159            3 :     async fn timeline_init_and_sync(
    1160            3 :         self: &Arc<Self>,
    1161            3 :         timeline_id: TimelineId,
    1162            3 :         resources: TimelineResources,
    1163            3 :         index_part: IndexPart,
    1164            3 :         metadata: TimelineMetadata,
    1165            3 :         previous_heatmap: Option<PreviousHeatmap>,
    1166            3 :         ancestor: Option<Arc<Timeline>>,
    1167            3 :         cause: LoadTimelineCause,
    1168            3 :         ctx: &RequestContext,
    1169            3 :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    1170            3 :         let tenant_id = self.tenant_shard_id;
    1171              : 
    1172            3 :         let import_pgdata = index_part.import_pgdata.clone();
    1173            3 :         let idempotency = match &import_pgdata {
    1174            0 :             Some(import_pgdata) => {
    1175            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    1176            0 :                     idempotency_key: import_pgdata.idempotency_key().clone(),
    1177            0 :                 })
    1178              :             }
    1179              :             None => {
    1180            3 :                 if metadata.ancestor_timeline().is_none() {
    1181            2 :                     CreateTimelineIdempotency::Bootstrap {
    1182            2 :                         pg_version: metadata.pg_version(),
    1183            2 :                     }
    1184              :                 } else {
    1185            1 :                     CreateTimelineIdempotency::Branch {
    1186            1 :                         ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
    1187            1 :                         ancestor_start_lsn: metadata.ancestor_lsn(),
    1188            1 :                     }
    1189              :                 }
    1190              :             }
    1191              :         };
    1192              : 
    1193            3 :         let (timeline, _timeline_ctx) = self.create_timeline_struct(
    1194            3 :             timeline_id,
    1195            3 :             &metadata,
    1196            3 :             previous_heatmap,
    1197            3 :             ancestor.clone(),
    1198            3 :             resources,
    1199            3 :             CreateTimelineCause::Load,
    1200            3 :             idempotency.clone(),
    1201            3 :             index_part.gc_compaction.clone(),
    1202            3 :             index_part.rel_size_migration.clone(),
    1203            3 :             ctx,
    1204            3 :         )?;
    1205            3 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    1206              : 
    1207            3 :         if !disk_consistent_lsn.is_valid() {
    1208              :             // As opposed to normal timelines which get initialised with a disk consitent LSN
    1209              :             // via initdb, imported timelines start from 0. If the import task stops before
    1210              :             // it advances disk consitent LSN, allow it to resume.
    1211            0 :             let in_progress_import = import_pgdata
    1212            0 :                 .as_ref()
    1213            0 :                 .map(|import| !import.is_done())
    1214            0 :                 .unwrap_or(false);
    1215            0 :             if !in_progress_import {
    1216            0 :                 anyhow::bail!("Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn");
    1217            0 :             }
    1218            3 :         }
    1219              : 
    1220            3 :         assert_eq!(
    1221              :             disk_consistent_lsn,
    1222            3 :             metadata.disk_consistent_lsn(),
    1223            0 :             "these are used interchangeably"
    1224              :         );
    1225              : 
    1226            3 :         timeline.remote_client.init_upload_queue(&index_part)?;
    1227              : 
    1228            3 :         timeline
    1229            3 :             .load_layer_map(disk_consistent_lsn, index_part)
    1230            3 :             .await
    1231            3 :             .with_context(|| {
    1232            0 :                 format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
    1233            0 :             })?;
    1234              : 
    1235              :         // When unarchiving, we've mostly likely lost the heatmap generated prior
    1236              :         // to the archival operation. To allow warming this timeline up, generate
    1237              :         // a previous heatmap which contains all visible layers in the layer map.
    1238              :         // This previous heatmap will be used whenever a fresh heatmap is generated
    1239              :         // for the timeline.
    1240            3 :         if self.conf.generate_unarchival_heatmap && matches!(cause, LoadTimelineCause::Unoffload) {
    1241            0 :             let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
    1242            0 :             while let Some((tline, end_lsn)) = tline_ending_at {
    1243            0 :                 let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
    1244              :                 // Another unearchived timeline might have generated a heatmap for this ancestor.
    1245              :                 // If the current branch point greater than the previous one use the the heatmap
    1246              :                 // we just generated - it should include more layers.
    1247            0 :                 if !tline.should_keep_previous_heatmap(end_lsn) {
    1248            0 :                     tline
    1249            0 :                         .previous_heatmap
    1250            0 :                         .store(Some(Arc::new(unarchival_heatmap)));
    1251            0 :                 } else {
    1252            0 :                     tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
    1253              :                 }
    1254              : 
    1255            0 :                 match tline.ancestor_timeline() {
    1256            0 :                     Some(ancestor) => {
    1257            0 :                         if ancestor.update_layer_visibility().await.is_err() {
    1258              :                             // Ancestor timeline is shutting down.
    1259            0 :                             break;
    1260            0 :                         }
    1261              : 
    1262            0 :                         tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
    1263              :                     }
    1264            0 :                     None => {
    1265            0 :                         tline_ending_at = None;
    1266            0 :                     }
    1267              :                 }
    1268              :             }
    1269            3 :         }
    1270              : 
    1271            0 :         match import_pgdata {
    1272            0 :             Some(import_pgdata) if !import_pgdata.is_done() => {
    1273            0 :                 let mut guard = self.timelines_creating.lock().unwrap();
    1274            0 :                 if !guard.insert(timeline_id) {
    1275              :                     // We should never try and load the same timeline twice during startup
    1276            0 :                     unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
    1277            0 :                 }
    1278            0 :                 let timeline_create_guard = TimelineCreateGuard {
    1279            0 :                     _tenant_gate_guard: self.gate.enter()?,
    1280            0 :                     owning_tenant: self.clone(),
    1281            0 :                     timeline_id,
    1282            0 :                     idempotency,
    1283              :                     // The users of this specific return value don't need the timline_path in there.
    1284            0 :                     timeline_path: timeline
    1285            0 :                         .conf
    1286            0 :                         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
    1287              :                 };
    1288            0 :                 Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1289            0 :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1290            0 :                         timeline,
    1291            0 :                         import_pgdata,
    1292            0 :                         guard: timeline_create_guard,
    1293            0 :                     },
    1294            0 :                 ))
    1295              :             }
    1296              :             Some(_) | None => {
    1297              :                 {
    1298            3 :                     let mut timelines_accessor = self.timelines.lock().unwrap();
    1299            3 :                     match timelines_accessor.entry(timeline_id) {
    1300              :                         // We should never try and load the same timeline twice during startup
    1301              :                         Entry::Occupied(_) => {
    1302            0 :                             unreachable!(
    1303              :                                 "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
    1304              :                             );
    1305              :                         }
    1306            3 :                         Entry::Vacant(v) => {
    1307            3 :                             v.insert(Arc::clone(&timeline));
    1308            3 :                             timeline.maybe_spawn_flush_loop();
    1309            3 :                         }
    1310              :                     }
    1311              :                 }
    1312              : 
    1313            3 :                 if disk_consistent_lsn.is_valid() {
    1314              :                     // Sanity check: a timeline should have some content.
    1315              :                     // Exception: importing timelines might not yet have any
    1316            3 :                     anyhow::ensure!(
    1317            3 :                         ancestor.is_some()
    1318            2 :                             || timeline
    1319            2 :                                 .layers
    1320            2 :                                 .read(LayerManagerLockHolder::LoadLayerMap)
    1321            2 :                                 .await
    1322            2 :                                 .layer_map()
    1323            2 :                                 .expect(
    1324            2 :                                     "currently loading, layer manager cannot be shutdown already"
    1325              :                                 )
    1326            2 :                                 .iter_historic_layers()
    1327            2 :                                 .next()
    1328            2 :                                 .is_some(),
    1329            0 :                         "Timeline has no ancestor and no layer files"
    1330              :                     );
    1331            0 :                 }
    1332              : 
    1333            3 :                 Ok(TimelineInitAndSyncResult::ReadyToActivate)
    1334              :             }
    1335              :         }
    1336            3 :     }
    1337              : 
    1338              :     /// Attach a tenant that's available in cloud storage.
    1339              :     ///
    1340              :     /// This returns quickly, after just creating the in-memory object
    1341              :     /// Tenant struct and launching a background task to download
    1342              :     /// the remote index files.  On return, the tenant is most likely still in
    1343              :     /// Attaching state, and it will become Active once the background task
    1344              :     /// finishes. You can use wait_until_active() to wait for the task to
    1345              :     /// complete.
    1346              :     ///
    1347              :     #[allow(clippy::too_many_arguments)]
    1348            0 :     pub(crate) fn spawn(
    1349            0 :         conf: &'static PageServerConf,
    1350            0 :         tenant_shard_id: TenantShardId,
    1351            0 :         resources: TenantSharedResources,
    1352            0 :         attached_conf: AttachedTenantConf,
    1353            0 :         shard_identity: ShardIdentity,
    1354            0 :         init_order: Option<InitializationOrder>,
    1355            0 :         mode: SpawnMode,
    1356            0 :         ctx: &RequestContext,
    1357            0 :     ) -> Result<Arc<TenantShard>, GlobalShutDown> {
    1358            0 :         let wal_redo_manager =
    1359            0 :             WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
    1360              : 
    1361              :         let TenantSharedResources {
    1362            0 :             broker_client,
    1363            0 :             remote_storage,
    1364            0 :             deletion_queue_client,
    1365            0 :             l0_flush_global_state,
    1366            0 :             basebackup_cache,
    1367            0 :             feature_resolver,
    1368            0 :         } = resources;
    1369              : 
    1370            0 :         let attach_mode = attached_conf.location.attach_mode;
    1371            0 :         let generation = attached_conf.location.generation;
    1372              : 
    1373            0 :         let tenant = Arc::new(TenantShard::new(
    1374            0 :             TenantState::Attaching,
    1375            0 :             conf,
    1376            0 :             attached_conf,
    1377            0 :             shard_identity,
    1378            0 :             Some(wal_redo_manager),
    1379            0 :             tenant_shard_id,
    1380            0 :             remote_storage.clone(),
    1381            0 :             deletion_queue_client,
    1382            0 :             l0_flush_global_state,
    1383            0 :             basebackup_cache,
    1384            0 :             feature_resolver,
    1385              :         ));
    1386              : 
    1387              :         // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
    1388              :         // we shut down while attaching.
    1389            0 :         let attach_gate_guard = tenant
    1390            0 :             .gate
    1391            0 :             .enter()
    1392            0 :             .expect("We just created the TenantShard: nothing else can have shut it down yet");
    1393              : 
    1394              :         // Do all the hard work in the background
    1395            0 :         let tenant_clone = Arc::clone(&tenant);
    1396            0 :         let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
    1397            0 :         task_mgr::spawn(
    1398            0 :             &tokio::runtime::Handle::current(),
    1399            0 :             TaskKind::Attach,
    1400            0 :             tenant_shard_id,
    1401            0 :             None,
    1402            0 :             "attach tenant",
    1403            0 :             async move {
    1404              : 
    1405            0 :                 info!(
    1406              :                     ?attach_mode,
    1407            0 :                     "Attaching tenant"
    1408              :                 );
    1409              : 
    1410            0 :                 let _gate_guard = attach_gate_guard;
    1411              : 
    1412              :                 // Is this tenant being spawned as part of process startup?
    1413            0 :                 let starting_up = init_order.is_some();
    1414            0 :                 scopeguard::defer! {
    1415              :                     if starting_up {
    1416              :                         TENANT.startup_complete.inc();
    1417              :                     }
    1418              :                 }
    1419              : 
    1420            0 :                 fn make_broken_or_stopping(t: &TenantShard, err: anyhow::Error) {
    1421            0 :                     t.state.send_modify(|state| match state {
    1422              :                         // TODO: the old code alluded to DeleteTenantFlow sometimes setting
    1423              :                         // TenantState::Stopping before we get here, but this may be outdated.
    1424              :                         // Let's find out with a testing assertion. If this doesn't fire, and the
    1425              :                         // logs don't show this happening in production, remove the Stopping cases.
    1426            0 :                         TenantState::Stopping{..} if cfg!(any(test, feature = "testing")) => {
    1427            0 :                             panic!("unexpected TenantState::Stopping during attach")
    1428              :                         }
    1429              :                         // If the tenant is cancelled, assume the error was caused by cancellation.
    1430            0 :                         TenantState::Attaching if t.cancel.is_cancelled() => {
    1431            0 :                             info!("attach cancelled, setting tenant state to Stopping: {err}");
    1432              :                             // NB: progress None tells `set_stopping` that attach has cancelled.
    1433            0 :                             *state = TenantState::Stopping { progress: None };
    1434              :                         }
    1435              :                         // According to the old code, DeleteTenantFlow may already have set this to
    1436              :                         // Stopping. Retain its progress.
    1437              :                         // TODO: there is no DeleteTenantFlow. Is this still needed? See above.
    1438            0 :                         TenantState::Stopping { progress } if t.cancel.is_cancelled() => {
    1439            0 :                             assert!(progress.is_some(), "concurrent attach cancellation");
    1440            0 :                             info!("attach cancelled, already Stopping: {err}");
    1441              :                         }
    1442              :                         // Mark the tenant as broken.
    1443              :                         TenantState::Attaching | TenantState::Stopping { .. } => {
    1444            0 :                             error!("attach failed, setting tenant state to Broken (was {state}): {err:?}");
    1445            0 :                             *state = TenantState::broken_from_reason(err.to_string())
    1446              :                         }
    1447              :                         // The attach task owns the tenant state until activated.
    1448            0 :                         state => panic!("invalid tenant state {state} during attach: {err:?}"),
    1449            0 :                     });
    1450            0 :                 }
    1451              : 
    1452              :                 // TODO: should also be rejecting tenant conf changes that violate this check.
    1453            0 :                 if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
    1454            0 :                     make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1455            0 :                     return Ok(());
    1456            0 :                 }
    1457              : 
    1458            0 :                 let mut init_order = init_order;
    1459              :                 // take the completion because initial tenant loading will complete when all of
    1460              :                 // these tasks complete.
    1461            0 :                 let _completion = init_order
    1462            0 :                     .as_mut()
    1463            0 :                     .and_then(|x| x.initial_tenant_load.take());
    1464            0 :                 let remote_load_completion = init_order
    1465            0 :                     .as_mut()
    1466            0 :                     .and_then(|x| x.initial_tenant_load_remote.take());
    1467              : 
    1468              :                 enum AttachType<'a> {
    1469              :                     /// We are attaching this tenant lazily in the background.
    1470              :                     Warmup {
    1471              :                         _permit: tokio::sync::SemaphorePermit<'a>,
    1472              :                         during_startup: bool
    1473              :                     },
    1474              :                     /// We are attaching this tenant as soon as we can, because for example an
    1475              :                     /// endpoint tried to access it.
    1476              :                     OnDemand,
    1477              :                     /// During normal operations after startup, we are attaching a tenant, and
    1478              :                     /// eager attach was requested.
    1479              :                     Normal,
    1480              :                 }
    1481              : 
    1482            0 :                 let attach_type = if matches!(mode, SpawnMode::Lazy) {
    1483              :                     // Before doing any I/O, wait for at least one of:
    1484              :                     // - A client attempting to access to this tenant (on-demand loading)
    1485              :                     // - A permit becoming available in the warmup semaphore (background warmup)
    1486              : 
    1487            0 :                     tokio::select!(
    1488            0 :                         permit = tenant_clone.activate_now_sem.acquire() => {
    1489            0 :                             let _ = permit.expect("activate_now_sem is never closed");
    1490            0 :                             tracing::info!("Activating tenant (on-demand)");
    1491            0 :                             AttachType::OnDemand
    1492              :                         },
    1493            0 :                         permit = conf.concurrent_tenant_warmup.inner().acquire() => {
    1494            0 :                             let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
    1495            0 :                             tracing::info!("Activating tenant (warmup)");
    1496            0 :                             AttachType::Warmup {
    1497            0 :                                 _permit,
    1498            0 :                                 during_startup: init_order.is_some()
    1499            0 :                             }
    1500              :                         }
    1501            0 :                         _ = tenant_clone.cancel.cancelled() => {
    1502              :                             // This is safe, but should be pretty rare: it is interesting if a tenant
    1503              :                             // stayed in Activating for such a long time that shutdown found it in
    1504              :                             // that state.
    1505            0 :                             tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
    1506              :                             // Set the tenant to Stopping to signal `set_stopping` that we're done.
    1507            0 :                             make_broken_or_stopping(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"));
    1508            0 :                             return Ok(());
    1509              :                         },
    1510              :                     )
    1511              :                 } else {
    1512              :                     // SpawnMode::{Create,Eager} always cause jumping ahead of the
    1513              :                     // concurrent_tenant_warmup queue
    1514            0 :                     AttachType::Normal
    1515              :                 };
    1516              : 
    1517            0 :                 let preload = match &mode {
    1518              :                     SpawnMode::Eager | SpawnMode::Lazy => {
    1519            0 :                         let _preload_timer = TENANT.preload.start_timer();
    1520            0 :                         let res = tenant_clone
    1521            0 :                             .preload(&remote_storage, task_mgr::shutdown_token())
    1522            0 :                             .await;
    1523            0 :                         match res {
    1524            0 :                             Ok(p) => Some(p),
    1525            0 :                             Err(e) => {
    1526            0 :                                 make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
    1527            0 :                                 return Ok(());
    1528              :                             }
    1529              :                         }
    1530              :                     }
    1531              : 
    1532              :                 };
    1533              : 
    1534              :                 // Remote preload is complete.
    1535            0 :                 drop(remote_load_completion);
    1536              : 
    1537              : 
    1538              :                 // We will time the duration of the attach phase unless this is a creation (attach will do no work)
    1539            0 :                 let attach_start = std::time::Instant::now();
    1540            0 :                 let attached = {
    1541            0 :                     let _attach_timer = Some(TENANT.attach.start_timer());
    1542            0 :                     tenant_clone.attach(preload, &ctx).await
    1543              :                 };
    1544            0 :                 let attach_duration = attach_start.elapsed();
    1545            0 :                 _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
    1546              : 
    1547            0 :                 match attached {
    1548              :                     Ok(()) => {
    1549            0 :                         info!("attach finished, activating");
    1550            0 :                         tenant_clone.activate(broker_client, None, &ctx);
    1551              :                     }
    1552            0 :                     Err(e) => make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e)),
    1553              :                 }
    1554              : 
    1555              :                 // If we are doing an opportunistic warmup attachment at startup, initialize
    1556              :                 // logical size at the same time.  This is better than starting a bunch of idle tenants
    1557              :                 // with cold caches and then coming back later to initialize their logical sizes.
    1558              :                 //
    1559              :                 // It also prevents the warmup proccess competing with the concurrency limit on
    1560              :                 // logical size calculations: if logical size calculation semaphore is saturated,
    1561              :                 // then warmup will wait for that before proceeding to the next tenant.
    1562            0 :                 if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
    1563            0 :                     let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
    1564            0 :                     tracing::info!("Waiting for initial logical sizes while warming up...");
    1565            0 :                     while futs.next().await.is_some() {}
    1566            0 :                     tracing::info!("Warm-up complete");
    1567            0 :                 }
    1568              : 
    1569            0 :                 Ok(())
    1570            0 :             }
    1571            0 :             .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
    1572              :         );
    1573            0 :         Ok(tenant)
    1574            0 :     }
    1575              : 
    1576              :     #[instrument(skip_all)]
    1577              :     pub(crate) async fn preload(
    1578              :         self: &Arc<Self>,
    1579              :         remote_storage: &GenericRemoteStorage,
    1580              :         cancel: CancellationToken,
    1581              :     ) -> anyhow::Result<TenantPreload> {
    1582              :         span::debug_assert_current_span_has_tenant_id();
    1583              :         // Get list of remote timelines
    1584              :         // download index files for every tenant timeline
    1585              :         info!("listing remote timelines");
    1586              :         let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
    1587              :             remote_storage,
    1588              :             self.tenant_shard_id,
    1589              :             cancel.clone(),
    1590              :         )
    1591              :         .await?;
    1592              : 
    1593              :         let tenant_manifest = match download_tenant_manifest(
    1594              :             remote_storage,
    1595              :             &self.tenant_shard_id,
    1596              :             self.generation,
    1597              :             &cancel,
    1598              :         )
    1599              :         .await
    1600              :         {
    1601              :             Ok((tenant_manifest, _, _)) => Some(tenant_manifest),
    1602              :             Err(DownloadError::NotFound) => None,
    1603              :             Err(err) => return Err(err.into()),
    1604              :         };
    1605              : 
    1606              :         info!(
    1607              :             "found {} timelines ({} offloaded timelines)",
    1608              :             remote_timeline_ids.len(),
    1609              :             tenant_manifest
    1610              :                 .as_ref()
    1611            3 :                 .map(|m| m.offloaded_timelines.len())
    1612              :                 .unwrap_or(0)
    1613              :         );
    1614              : 
    1615              :         for k in other_keys {
    1616              :             warn!("Unexpected non timeline key {k}");
    1617              :         }
    1618              : 
    1619              :         // Avoid downloading IndexPart of offloaded timelines.
    1620              :         let mut offloaded_with_prefix = HashSet::new();
    1621              :         if let Some(tenant_manifest) = &tenant_manifest {
    1622              :             for offloaded in tenant_manifest.offloaded_timelines.iter() {
    1623              :                 if remote_timeline_ids.remove(&offloaded.timeline_id) {
    1624              :                     offloaded_with_prefix.insert(offloaded.timeline_id);
    1625              :                 } else {
    1626              :                     // We'll take care later of timelines in the manifest without a prefix
    1627              :                 }
    1628              :             }
    1629              :         }
    1630              : 
    1631              :         // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
    1632              :         // pulled the first heatmap. Not entirely necessary since the storage controller
    1633              :         // will kick the secondary in any case and cause a download.
    1634              :         let maybe_heatmap_at = self.read_on_disk_heatmap().await;
    1635              : 
    1636              :         let timelines = self
    1637              :             .load_timelines_metadata(
    1638              :                 remote_timeline_ids,
    1639              :                 remote_storage,
    1640              :                 maybe_heatmap_at,
    1641              :                 cancel,
    1642              :             )
    1643              :             .await?;
    1644              : 
    1645              :         Ok(TenantPreload {
    1646              :             tenant_manifest,
    1647              :             timelines: timelines
    1648              :                 .into_iter()
    1649            3 :                 .map(|(id, tl)| (id, Some(tl)))
    1650            0 :                 .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
    1651              :                 .collect(),
    1652              :         })
    1653              :     }
    1654              : 
    1655          118 :     async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
    1656          118 :         if !self.conf.load_previous_heatmap {
    1657            0 :             return None;
    1658          118 :         }
    1659              : 
    1660          118 :         let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
    1661          118 :         match tokio::fs::read_to_string(on_disk_heatmap_path).await {
    1662            0 :             Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
    1663            0 :                 Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
    1664            0 :                 Err(err) => {
    1665            0 :                     error!("Failed to deserialize old heatmap: {err}");
    1666            0 :                     None
    1667              :                 }
    1668              :             },
    1669          118 :             Err(err) => match err.kind() {
    1670          118 :                 std::io::ErrorKind::NotFound => None,
    1671              :                 _ => {
    1672            0 :                     error!("Unexpected IO error reading old heatmap: {err}");
    1673            0 :                     None
    1674              :                 }
    1675              :             },
    1676              :         }
    1677          118 :     }
    1678              : 
    1679              :     ///
    1680              :     /// Background task that downloads all data for a tenant and brings it to Active state.
    1681              :     ///
    1682              :     /// No background tasks are started as part of this routine.
    1683              :     ///
    1684          118 :     async fn attach(
    1685          118 :         self: &Arc<TenantShard>,
    1686          118 :         preload: Option<TenantPreload>,
    1687          118 :         ctx: &RequestContext,
    1688          118 :     ) -> anyhow::Result<()> {
    1689          118 :         span::debug_assert_current_span_has_tenant_id();
    1690              : 
    1691          118 :         failpoint_support::sleep_millis_async!("before-attaching-tenant");
    1692              : 
    1693          118 :         let Some(preload) = preload else {
    1694            0 :             anyhow::bail!(
    1695            0 :                 "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
    1696              :             );
    1697              :         };
    1698              : 
    1699          118 :         let mut offloaded_timeline_ids = HashSet::new();
    1700          118 :         let mut offloaded_timelines_list = Vec::new();
    1701          118 :         if let Some(tenant_manifest) = &preload.tenant_manifest {
    1702            3 :             for timeline_manifest in tenant_manifest.offloaded_timelines.iter() {
    1703            0 :                 let timeline_id = timeline_manifest.timeline_id;
    1704            0 :                 let offloaded_timeline =
    1705            0 :                     OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
    1706            0 :                 offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
    1707            0 :                 offloaded_timeline_ids.insert(timeline_id);
    1708            0 :             }
    1709          115 :         }
    1710              :         // Complete deletions for offloaded timeline id's from manifest.
    1711              :         // The manifest will be uploaded later in this function.
    1712          118 :         offloaded_timelines_list
    1713          118 :             .retain(|(offloaded_id, offloaded)| {
    1714              :                 // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
    1715              :                 // If there is dangling references in another location, they need to be cleaned up.
    1716            0 :                 let delete = !preload.timelines.contains_key(offloaded_id);
    1717            0 :                 if delete {
    1718            0 :                     tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
    1719            0 :                     offloaded.defuse_for_tenant_drop();
    1720            0 :                 }
    1721            0 :                 !delete
    1722            0 :         });
    1723              : 
    1724          118 :         let mut timelines_to_resume_deletions = vec![];
    1725              : 
    1726          118 :         let mut remote_index_and_client = HashMap::new();
    1727          118 :         let mut timeline_ancestors = HashMap::new();
    1728          118 :         let mut existent_timelines = HashSet::new();
    1729          121 :         for (timeline_id, preload) in preload.timelines {
    1730            3 :             let Some(preload) = preload else { continue };
    1731              :             // This is an invariant of the `preload` function's API
    1732            3 :             assert!(!offloaded_timeline_ids.contains(&timeline_id));
    1733            3 :             let index_part = match preload.index_part {
    1734            3 :                 Ok(i) => {
    1735            3 :                     debug!("remote index part exists for timeline {timeline_id}");
    1736              :                     // We found index_part on the remote, this is the standard case.
    1737            3 :                     existent_timelines.insert(timeline_id);
    1738            3 :                     i
    1739              :                 }
    1740              :                 Err(DownloadError::NotFound) => {
    1741              :                     // There is no index_part on the remote. We only get here
    1742              :                     // if there is some prefix for the timeline in the remote storage.
    1743              :                     // This can e.g. be the initdb.tar.zst archive, maybe a
    1744              :                     // remnant from a prior incomplete creation or deletion attempt.
    1745              :                     // Delete the local directory as the deciding criterion for a
    1746              :                     // timeline's existence is presence of index_part.
    1747            0 :                     info!(%timeline_id, "index_part not found on remote");
    1748            0 :                     continue;
    1749              :                 }
    1750            0 :                 Err(DownloadError::Fatal(why)) => {
    1751              :                     // If, while loading one remote timeline, we saw an indication that our generation
    1752              :                     // number is likely invalid, then we should not load the whole tenant.
    1753            0 :                     error!(%timeline_id, "Fatal error loading timeline: {why}");
    1754            0 :                     anyhow::bail!(why.to_string());
    1755              :                 }
    1756            0 :                 Err(e) => {
    1757              :                     // Some (possibly ephemeral) error happened during index_part download.
    1758              :                     // Pretend the timeline exists to not delete the timeline directory,
    1759              :                     // as it might be a temporary issue and we don't want to re-download
    1760              :                     // everything after it resolves.
    1761            0 :                     warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    1762              : 
    1763            0 :                     existent_timelines.insert(timeline_id);
    1764            0 :                     continue;
    1765              :                 }
    1766              :             };
    1767            3 :             match index_part {
    1768            3 :                 MaybeDeletedIndexPart::IndexPart(index_part) => {
    1769            3 :                     timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
    1770            3 :                     remote_index_and_client.insert(
    1771            3 :                         timeline_id,
    1772            3 :                         (index_part, preload.client, preload.previous_heatmap),
    1773            3 :                     );
    1774            3 :                 }
    1775            0 :                 MaybeDeletedIndexPart::Deleted(index_part) => {
    1776            0 :                     info!(
    1777            0 :                         "timeline {} is deleted, picking to resume deletion",
    1778              :                         timeline_id
    1779              :                     );
    1780            0 :                     timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
    1781              :                 }
    1782              :             }
    1783              :         }
    1784              : 
    1785          118 :         let mut gc_blocks = HashMap::new();
    1786              : 
    1787              :         // For every timeline, download the metadata file, scan the local directory,
    1788              :         // and build a layer map that contains an entry for each remote and local
    1789              :         // layer file.
    1790          118 :         let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
    1791          121 :         for (timeline_id, remote_metadata) in sorted_timelines {
    1792            3 :             let (index_part, remote_client, previous_heatmap) = remote_index_and_client
    1793            3 :                 .remove(&timeline_id)
    1794            3 :                 .expect("just put it in above");
    1795              : 
    1796            3 :             if let Some(blocking) = index_part.gc_blocking.as_ref() {
    1797              :                 // could just filter these away, but it helps while testing
    1798            0 :                 anyhow::ensure!(
    1799            0 :                     !blocking.reasons.is_empty(),
    1800            0 :                     "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
    1801              :                 );
    1802            0 :                 let prev = gc_blocks.insert(timeline_id, blocking.reasons);
    1803            0 :                 assert!(prev.is_none());
    1804            3 :             }
    1805              : 
    1806              :             // TODO again handle early failure
    1807            3 :             let effect = self
    1808            3 :                 .load_remote_timeline(
    1809            3 :                     timeline_id,
    1810            3 :                     index_part,
    1811            3 :                     remote_metadata,
    1812            3 :                     previous_heatmap,
    1813            3 :                     self.get_timeline_resources_for(remote_client),
    1814            3 :                     LoadTimelineCause::Attach,
    1815            3 :                     ctx,
    1816            3 :                 )
    1817            3 :                 .await
    1818            3 :                 .with_context(|| {
    1819            0 :                     format!(
    1820            0 :                         "failed to load remote timeline {} for tenant {}",
    1821            0 :                         timeline_id, self.tenant_shard_id
    1822              :                     )
    1823            0 :                 })?;
    1824              : 
    1825            3 :             match effect {
    1826            3 :                 TimelineInitAndSyncResult::ReadyToActivate => {
    1827            3 :                     // activation happens later, on Tenant::activate
    1828            3 :                 }
    1829              :                 TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
    1830              :                     TimelineInitAndSyncNeedsSpawnImportPgdata {
    1831            0 :                         timeline,
    1832            0 :                         import_pgdata,
    1833            0 :                         guard,
    1834              :                     },
    1835              :                 ) => {
    1836            0 :                     let timeline_id = timeline.timeline_id;
    1837            0 :                     let import_task_gate = Gate::default();
    1838            0 :                     let import_task_guard = import_task_gate.enter().unwrap();
    1839            0 :                     let import_task_handle =
    1840            0 :                         tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
    1841            0 :                             timeline.clone(),
    1842            0 :                             import_pgdata,
    1843            0 :                             guard,
    1844            0 :                             import_task_guard,
    1845            0 :                             ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    1846              :                         ));
    1847              : 
    1848            0 :                     let prev = self.timelines_importing.lock().unwrap().insert(
    1849            0 :                         timeline_id,
    1850            0 :                         Arc::new(ImportingTimeline {
    1851            0 :                             timeline: timeline.clone(),
    1852            0 :                             import_task_handle,
    1853            0 :                             import_task_gate,
    1854            0 :                             delete_progress: TimelineDeleteProgress::default(),
    1855            0 :                         }),
    1856            0 :                     );
    1857              : 
    1858            0 :                     assert!(prev.is_none());
    1859              :                 }
    1860              :             }
    1861              :         }
    1862              : 
    1863              :         // At this point we've initialized all timelines and are tracking them.
    1864              :         // Now compute the layer visibility for all (not offloaded) timelines.
    1865          118 :         let compute_visiblity_for = {
    1866          118 :             let timelines_accessor = self.timelines.lock().unwrap();
    1867          118 :             let mut timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    1868              : 
    1869          118 :             timelines_offloaded_accessor.extend(offloaded_timelines_list.into_iter());
    1870              : 
    1871              :             // Before activation, populate each Timeline's GcInfo with information about its children
    1872          118 :             self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
    1873              : 
    1874          118 :             timelines_accessor.values().cloned().collect::<Vec<_>>()
    1875              :         };
    1876              : 
    1877          121 :         for tl in compute_visiblity_for {
    1878            3 :             tl.update_layer_visibility().await.with_context(|| {
    1879            0 :                 format!(
    1880            0 :                     "failed initial timeline visibility computation {} for tenant {}",
    1881            0 :                     tl.timeline_id, self.tenant_shard_id
    1882              :                 )
    1883            0 :             })?;
    1884              :         }
    1885              : 
    1886              :         // Walk through deleted timelines, resume deletion
    1887          118 :         for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
    1888            0 :             remote_timeline_client
    1889            0 :                 .init_upload_queue_stopped_to_continue_deletion(&index_part)
    1890            0 :                 .context("init queue stopped")
    1891            0 :                 .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1892              : 
    1893            0 :             DeleteTimelineFlow::resume_deletion(
    1894            0 :                 Arc::clone(self),
    1895            0 :                 timeline_id,
    1896            0 :                 &index_part.metadata,
    1897            0 :                 remote_timeline_client,
    1898            0 :                 ctx,
    1899              :             )
    1900            0 :             .instrument(tracing::info_span!("timeline_delete", %timeline_id))
    1901            0 :             .await
    1902            0 :             .context("resume_deletion")
    1903            0 :             .map_err(LoadLocalTimelineError::ResumeDeletion)?;
    1904              :         }
    1905              : 
    1906              :         // Stash the preloaded tenant manifest, and upload a new manifest if changed.
    1907              :         //
    1908              :         // NB: this must happen after the tenant is fully populated above. In particular the
    1909              :         // offloaded timelines, which are included in the manifest.
    1910              :         {
    1911          118 :             let mut guard = self.remote_tenant_manifest.lock().await;
    1912          118 :             assert!(guard.is_none(), "tenant manifest set before preload"); // first populated here
    1913          118 :             *guard = preload.tenant_manifest;
    1914              :         }
    1915          118 :         self.maybe_upload_tenant_manifest().await?;
    1916              : 
    1917              :         // The local filesystem contents are a cache of what's in the remote IndexPart;
    1918              :         // IndexPart is the source of truth.
    1919          118 :         self.clean_up_timelines(&existent_timelines)?;
    1920              : 
    1921          118 :         self.gc_block.set_scanned(gc_blocks);
    1922              : 
    1923          118 :         fail::fail_point!("attach-before-activate", |_| {
    1924            0 :             anyhow::bail!("attach-before-activate");
    1925            0 :         });
    1926          118 :         failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
    1927              : 
    1928          118 :         info!("Done");
    1929              : 
    1930          118 :         Ok(())
    1931          118 :     }
    1932              : 
    1933              :     /// Check for any local timeline directories that are temporary, or do not correspond to a
    1934              :     /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
    1935              :     /// if a timeline was deleted while the tenant was attached to a different pageserver.
    1936          118 :     fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
    1937          118 :         let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
    1938              : 
    1939          118 :         let entries = match timelines_dir.read_dir_utf8() {
    1940          118 :             Ok(d) => d,
    1941            0 :             Err(e) => {
    1942            0 :                 if e.kind() == std::io::ErrorKind::NotFound {
    1943            0 :                     return Ok(());
    1944              :                 } else {
    1945            0 :                     return Err(e).context("list timelines directory for tenant");
    1946              :                 }
    1947              :             }
    1948              :         };
    1949              : 
    1950          122 :         for entry in entries {
    1951            4 :             let entry = entry.context("read timeline dir entry")?;
    1952            4 :             let entry_path = entry.path();
    1953              : 
    1954            4 :             let purge = if crate::is_temporary(entry_path) {
    1955            0 :                 true
    1956              :             } else {
    1957            4 :                 match TimelineId::try_from(entry_path.file_name()) {
    1958            4 :                     Ok(i) => {
    1959              :                         // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
    1960            4 :                         !existent_timelines.contains(&i)
    1961              :                     }
    1962            0 :                     Err(e) => {
    1963            0 :                         tracing::warn!(
    1964            0 :                             "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
    1965              :                         );
    1966              :                         // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
    1967            0 :                         false
    1968              :                     }
    1969              :                 }
    1970              :             };
    1971              : 
    1972            4 :             if purge {
    1973            1 :                 tracing::info!("Purging stale timeline dentry {entry_path}");
    1974            1 :                 if let Err(e) = match entry.file_type() {
    1975            1 :                     Ok(t) => if t.is_dir() {
    1976            1 :                         std::fs::remove_dir_all(entry_path)
    1977              :                     } else {
    1978            0 :                         std::fs::remove_file(entry_path)
    1979              :                     }
    1980            1 :                     .or_else(fs_ext::ignore_not_found),
    1981            0 :                     Err(e) => Err(e),
    1982              :                 } {
    1983            0 :                     tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
    1984            1 :                 }
    1985            3 :             }
    1986              :         }
    1987              : 
    1988          118 :         Ok(())
    1989          118 :     }
    1990              : 
    1991              :     /// Get sum of all remote timelines sizes
    1992              :     ///
    1993              :     /// This function relies on the index_part instead of listing the remote storage
    1994            0 :     pub fn remote_size(&self) -> u64 {
    1995            0 :         let mut size = 0;
    1996              : 
    1997            0 :         for timeline in self.list_timelines() {
    1998            0 :             size += timeline.remote_client.get_remote_physical_size();
    1999            0 :         }
    2000              : 
    2001            0 :         size
    2002            0 :     }
    2003              : 
    2004              :     #[instrument(skip_all, fields(timeline_id=%timeline_id))]
    2005              :     #[allow(clippy::too_many_arguments)]
    2006              :     async fn load_remote_timeline(
    2007              :         self: &Arc<Self>,
    2008              :         timeline_id: TimelineId,
    2009              :         index_part: IndexPart,
    2010              :         remote_metadata: TimelineMetadata,
    2011              :         previous_heatmap: Option<PreviousHeatmap>,
    2012              :         resources: TimelineResources,
    2013              :         cause: LoadTimelineCause,
    2014              :         ctx: &RequestContext,
    2015              :     ) -> anyhow::Result<TimelineInitAndSyncResult> {
    2016              :         span::debug_assert_current_span_has_tenant_id();
    2017              : 
    2018              :         info!("downloading index file for timeline {}", timeline_id);
    2019              :         tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
    2020              :             .await
    2021              :             .context("Failed to create new timeline directory")?;
    2022              : 
    2023              :         let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
    2024              :             let timelines = self.timelines.lock().unwrap();
    2025              :             Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
    2026            0 :                 || {
    2027            0 :                     anyhow::anyhow!(
    2028            0 :                         "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
    2029              :                     )
    2030            0 :                 },
    2031              :             )?))
    2032              :         } else {
    2033              :             None
    2034              :         };
    2035              : 
    2036              :         self.timeline_init_and_sync(
    2037              :             timeline_id,
    2038              :             resources,
    2039              :             index_part,
    2040              :             remote_metadata,
    2041              :             previous_heatmap,
    2042              :             ancestor,
    2043              :             cause,
    2044              :             ctx,
    2045              :         )
    2046              :         .await
    2047              :     }
    2048              : 
    2049          118 :     async fn load_timelines_metadata(
    2050          118 :         self: &Arc<TenantShard>,
    2051          118 :         timeline_ids: HashSet<TimelineId>,
    2052          118 :         remote_storage: &GenericRemoteStorage,
    2053          118 :         heatmap: Option<(HeatMapTenant, std::time::Instant)>,
    2054          118 :         cancel: CancellationToken,
    2055          118 :     ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
    2056          118 :         let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
    2057              : 
    2058          118 :         let mut part_downloads = JoinSet::new();
    2059          121 :         for timeline_id in timeline_ids {
    2060            3 :             let cancel_clone = cancel.clone();
    2061              : 
    2062            3 :             let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
    2063            0 :                 hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
    2064            0 :                     heatmap: h,
    2065            0 :                     read_at: hs.1,
    2066            0 :                     end_lsn: None,
    2067            0 :                 })
    2068            0 :             });
    2069            3 :             part_downloads.spawn(
    2070            3 :                 self.load_timeline_metadata(
    2071            3 :                     timeline_id,
    2072            3 :                     remote_storage.clone(),
    2073            3 :                     previous_timeline_heatmap,
    2074            3 :                     cancel_clone,
    2075              :                 )
    2076            3 :                 .instrument(info_span!("download_index_part", %timeline_id)),
    2077              :             );
    2078              :         }
    2079              : 
    2080          118 :         let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
    2081              : 
    2082              :         loop {
    2083          121 :             tokio::select!(
    2084          121 :                 next = part_downloads.join_next() => {
    2085          121 :                     match next {
    2086            3 :                         Some(result) => {
    2087            3 :                             let preload = result.context("join preload task")?;
    2088            3 :                             timeline_preloads.insert(preload.timeline_id, preload);
    2089              :                         },
    2090              :                         None => {
    2091          118 :                             break;
    2092              :                         }
    2093              :                     }
    2094              :                 },
    2095          121 :                 _ = cancel.cancelled() => {
    2096            0 :                     anyhow::bail!("Cancelled while waiting for remote index download")
    2097              :                 }
    2098              :             )
    2099              :         }
    2100              : 
    2101          118 :         Ok(timeline_preloads)
    2102          118 :     }
    2103              : 
    2104            3 :     fn build_timeline_client(
    2105            3 :         &self,
    2106            3 :         timeline_id: TimelineId,
    2107            3 :         remote_storage: GenericRemoteStorage,
    2108            3 :     ) -> RemoteTimelineClient {
    2109            3 :         RemoteTimelineClient::new(
    2110            3 :             remote_storage.clone(),
    2111            3 :             self.deletion_queue_client.clone(),
    2112            3 :             self.conf,
    2113            3 :             self.tenant_shard_id,
    2114            3 :             timeline_id,
    2115            3 :             self.generation,
    2116            3 :             &self.tenant_conf.load().location,
    2117              :         )
    2118            3 :     }
    2119              : 
    2120            3 :     fn load_timeline_metadata(
    2121            3 :         self: &Arc<TenantShard>,
    2122            3 :         timeline_id: TimelineId,
    2123            3 :         remote_storage: GenericRemoteStorage,
    2124            3 :         previous_heatmap: Option<PreviousHeatmap>,
    2125            3 :         cancel: CancellationToken,
    2126            3 :     ) -> impl Future<Output = TimelinePreload> + use<> {
    2127            3 :         let client = self.build_timeline_client(timeline_id, remote_storage);
    2128            3 :         async move {
    2129            3 :             debug_assert_current_span_has_tenant_and_timeline_id();
    2130            3 :             debug!("starting index part download");
    2131              : 
    2132            3 :             let index_part = client.download_index_file(&cancel).await;
    2133              : 
    2134            3 :             debug!("finished index part download");
    2135              : 
    2136            3 :             TimelinePreload {
    2137            3 :                 client,
    2138            3 :                 timeline_id,
    2139            3 :                 index_part,
    2140            3 :                 previous_heatmap,
    2141            3 :             }
    2142            3 :         }
    2143            3 :     }
    2144              : 
    2145            0 :     fn check_to_be_archived_has_no_unarchived_children(
    2146            0 :         timeline_id: TimelineId,
    2147            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2148            0 :     ) -> Result<(), TimelineArchivalError> {
    2149            0 :         let children: Vec<TimelineId> = timelines
    2150            0 :             .iter()
    2151            0 :             .filter_map(|(id, entry)| {
    2152            0 :                 if entry.get_ancestor_timeline_id() != Some(timeline_id) {
    2153            0 :                     return None;
    2154            0 :                 }
    2155            0 :                 if entry.is_archived() == Some(true) {
    2156            0 :                     return None;
    2157            0 :                 }
    2158            0 :                 Some(*id)
    2159            0 :             })
    2160            0 :             .collect();
    2161              : 
    2162            0 :         if !children.is_empty() {
    2163            0 :             return Err(TimelineArchivalError::HasUnarchivedChildren(children));
    2164            0 :         }
    2165            0 :         Ok(())
    2166            0 :     }
    2167              : 
    2168            0 :     fn check_ancestor_of_to_be_unarchived_is_not_archived(
    2169            0 :         ancestor_timeline_id: TimelineId,
    2170            0 :         timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
    2171            0 :         offloaded_timelines: &std::sync::MutexGuard<
    2172            0 :             '_,
    2173            0 :             HashMap<TimelineId, Arc<OffloadedTimeline>>,
    2174            0 :         >,
    2175            0 :     ) -> Result<(), TimelineArchivalError> {
    2176            0 :         let has_archived_parent =
    2177            0 :             if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
    2178            0 :                 ancestor_timeline.is_archived() == Some(true)
    2179            0 :             } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
    2180            0 :                 true
    2181              :             } else {
    2182            0 :                 error!("ancestor timeline {ancestor_timeline_id} not found");
    2183            0 :                 if cfg!(debug_assertions) {
    2184            0 :                     panic!("ancestor timeline {ancestor_timeline_id} not found");
    2185            0 :                 }
    2186            0 :                 return Err(TimelineArchivalError::NotFound);
    2187              :             };
    2188            0 :         if has_archived_parent {
    2189            0 :             return Err(TimelineArchivalError::HasArchivedParent(
    2190            0 :                 ancestor_timeline_id,
    2191            0 :             ));
    2192            0 :         }
    2193            0 :         Ok(())
    2194            0 :     }
    2195              : 
    2196            0 :     fn check_to_be_unarchived_timeline_has_no_archived_parent(
    2197            0 :         timeline: &Arc<Timeline>,
    2198            0 :     ) -> Result<(), TimelineArchivalError> {
    2199            0 :         if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
    2200            0 :             if ancestor_timeline.is_archived() == Some(true) {
    2201            0 :                 return Err(TimelineArchivalError::HasArchivedParent(
    2202            0 :                     ancestor_timeline.timeline_id,
    2203            0 :                 ));
    2204            0 :             }
    2205            0 :         }
    2206            0 :         Ok(())
    2207            0 :     }
    2208              : 
    2209              :     /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
    2210              :     ///
    2211              :     /// Counterpart to [`offload_timeline`].
    2212            0 :     async fn unoffload_timeline(
    2213            0 :         self: &Arc<Self>,
    2214            0 :         timeline_id: TimelineId,
    2215            0 :         broker_client: storage_broker::BrokerClientChannel,
    2216            0 :         ctx: RequestContext,
    2217            0 :     ) -> Result<Arc<Timeline>, TimelineArchivalError> {
    2218            0 :         info!("unoffloading timeline");
    2219              : 
    2220              :         // We activate the timeline below manually, so this must be called on an active tenant.
    2221              :         // We expect callers of this function to ensure this.
    2222            0 :         match self.current_state() {
    2223              :             TenantState::Activating { .. }
    2224              :             | TenantState::Attaching
    2225              :             | TenantState::Broken { .. } => {
    2226            0 :                 panic!("Timeline expected to be active")
    2227              :             }
    2228            0 :             TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
    2229            0 :             TenantState::Active => {}
    2230              :         }
    2231            0 :         let cancel = self.cancel.clone();
    2232              : 
    2233              :         // Protect against concurrent attempts to use this TimelineId
    2234              :         // We don't care much about idempotency, as it's ensured a layer above.
    2235            0 :         let allow_offloaded = true;
    2236            0 :         let _create_guard = self
    2237            0 :             .create_timeline_create_guard(
    2238            0 :                 timeline_id,
    2239            0 :                 CreateTimelineIdempotency::FailWithConflict,
    2240            0 :                 allow_offloaded,
    2241              :             )
    2242            0 :             .map_err(|err| match err {
    2243            0 :                 TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
    2244              :                 TimelineExclusionError::AlreadyExists { .. } => {
    2245            0 :                     TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
    2246              :                 }
    2247            0 :                 TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
    2248            0 :                 TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
    2249            0 :             })?;
    2250              : 
    2251            0 :         let timeline_preload = self
    2252            0 :             .load_timeline_metadata(
    2253            0 :                 timeline_id,
    2254            0 :                 self.remote_storage.clone(),
    2255            0 :                 None,
    2256            0 :                 cancel.clone(),
    2257            0 :             )
    2258            0 :             .await;
    2259              : 
    2260            0 :         let index_part = match timeline_preload.index_part {
    2261            0 :             Ok(index_part) => {
    2262            0 :                 debug!("remote index part exists for timeline {timeline_id}");
    2263            0 :                 index_part
    2264              :             }
    2265              :             Err(DownloadError::NotFound) => {
    2266            0 :                 error!(%timeline_id, "index_part not found on remote");
    2267            0 :                 return Err(TimelineArchivalError::NotFound);
    2268              :             }
    2269            0 :             Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
    2270            0 :             Err(e) => {
    2271              :                 // Some (possibly ephemeral) error happened during index_part download.
    2272            0 :                 warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
    2273            0 :                 return Err(TimelineArchivalError::Other(
    2274            0 :                     anyhow::Error::new(e).context("downloading index_part from remote storage"),
    2275            0 :                 ));
    2276              :             }
    2277              :         };
    2278            0 :         let index_part = match index_part {
    2279            0 :             MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
    2280            0 :             MaybeDeletedIndexPart::Deleted(_index_part) => {
    2281            0 :                 info!("timeline is deleted according to index_part.json");
    2282            0 :                 return Err(TimelineArchivalError::NotFound);
    2283              :             }
    2284              :         };
    2285            0 :         let remote_metadata = index_part.metadata.clone();
    2286            0 :         let timeline_resources = self.build_timeline_resources(timeline_id);
    2287            0 :         self.load_remote_timeline(
    2288            0 :             timeline_id,
    2289            0 :             index_part,
    2290            0 :             remote_metadata,
    2291            0 :             None,
    2292            0 :             timeline_resources,
    2293            0 :             LoadTimelineCause::Unoffload,
    2294            0 :             &ctx,
    2295            0 :         )
    2296            0 :         .await
    2297            0 :         .with_context(|| {
    2298            0 :             format!(
    2299            0 :                 "failed to load remote timeline {} for tenant {}",
    2300            0 :                 timeline_id, self.tenant_shard_id
    2301              :             )
    2302            0 :         })
    2303            0 :         .map_err(TimelineArchivalError::Other)?;
    2304              : 
    2305            0 :         let timeline = {
    2306            0 :             let timelines = self.timelines.lock().unwrap();
    2307            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2308            0 :                 warn!("timeline not available directly after attach");
    2309              :                 // This is not a panic because no locks are held between `load_remote_timeline`
    2310              :                 // which puts the timeline into timelines, and our look into the timeline map.
    2311            0 :                 return Err(TimelineArchivalError::Other(anyhow::anyhow!(
    2312            0 :                     "timeline not available directly after attach"
    2313            0 :                 )));
    2314              :             };
    2315            0 :             let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2316            0 :             match offloaded_timelines.remove(&timeline_id) {
    2317            0 :                 Some(offloaded) => {
    2318            0 :                     offloaded.delete_from_ancestor_with_timelines(&timelines);
    2319            0 :                 }
    2320            0 :                 None => warn!("timeline already removed from offloaded timelines"),
    2321              :             }
    2322              : 
    2323            0 :             self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
    2324              : 
    2325            0 :             Arc::clone(timeline)
    2326              :         };
    2327              : 
    2328              :         // Upload new list of offloaded timelines to S3
    2329            0 :         self.maybe_upload_tenant_manifest().await?;
    2330              : 
    2331              :         // Activate the timeline (if it makes sense)
    2332            0 :         if !(timeline.is_broken() || timeline.is_stopping()) {
    2333            0 :             let background_jobs_can_start = None;
    2334            0 :             timeline.activate(
    2335            0 :                 self.clone(),
    2336            0 :                 broker_client.clone(),
    2337            0 :                 background_jobs_can_start,
    2338            0 :                 &ctx.with_scope_timeline(&timeline),
    2339            0 :             );
    2340            0 :         }
    2341              : 
    2342            0 :         info!("timeline unoffloading complete");
    2343            0 :         Ok(timeline)
    2344            0 :     }
    2345              : 
    2346            0 :     pub(crate) async fn apply_timeline_archival_config(
    2347            0 :         self: &Arc<Self>,
    2348            0 :         timeline_id: TimelineId,
    2349            0 :         new_state: TimelineArchivalState,
    2350            0 :         broker_client: storage_broker::BrokerClientChannel,
    2351            0 :         ctx: RequestContext,
    2352            0 :     ) -> Result<(), TimelineArchivalError> {
    2353            0 :         info!("setting timeline archival config");
    2354              :         // First part: figure out what is needed to do, and do validation
    2355            0 :         let timeline_or_unarchive_offloaded = 'outer: {
    2356            0 :             let timelines = self.timelines.lock().unwrap();
    2357              : 
    2358            0 :             let Some(timeline) = timelines.get(&timeline_id) else {
    2359            0 :                 let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
    2360            0 :                 let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
    2361            0 :                     return Err(TimelineArchivalError::NotFound);
    2362              :                 };
    2363            0 :                 if new_state == TimelineArchivalState::Archived {
    2364              :                     // It's offloaded already, so nothing to do
    2365            0 :                     return Ok(());
    2366            0 :                 }
    2367            0 :                 if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
    2368            0 :                     Self::check_ancestor_of_to_be_unarchived_is_not_archived(
    2369            0 :                         ancestor_timeline_id,
    2370            0 :                         &timelines,
    2371            0 :                         &offloaded_timelines,
    2372            0 :                     )?;
    2373            0 :                 }
    2374            0 :                 break 'outer None;
    2375              :             };
    2376              : 
    2377              :             // Do some validation. We release the timelines lock below, so there is potential
    2378              :             // for race conditions: these checks are more present to prevent misunderstandings of
    2379              :             // the API's capabilities, instead of serving as the sole way to defend their invariants.
    2380            0 :             match new_state {
    2381              :                 TimelineArchivalState::Unarchived => {
    2382            0 :                     Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
    2383              :                 }
    2384              :                 TimelineArchivalState::Archived => {
    2385            0 :                     Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
    2386              :                 }
    2387              :             }
    2388            0 :             Some(Arc::clone(timeline))
    2389              :         };
    2390              : 
    2391              :         // Second part: unoffload timeline (if needed)
    2392            0 :         let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
    2393            0 :             timeline
    2394              :         } else {
    2395              :             // Turn offloaded timeline into a non-offloaded one
    2396            0 :             self.unoffload_timeline(timeline_id, broker_client, ctx)
    2397            0 :                 .await?
    2398              :         };
    2399              : 
    2400              :         // Third part: upload new timeline archival state and block until it is present in S3
    2401            0 :         let upload_needed = match timeline
    2402            0 :             .remote_client
    2403            0 :             .schedule_index_upload_for_timeline_archival_state(new_state)
    2404              :         {
    2405            0 :             Ok(upload_needed) => upload_needed,
    2406            0 :             Err(e) => {
    2407            0 :                 if timeline.cancel.is_cancelled() {
    2408            0 :                     return Err(TimelineArchivalError::Cancelled);
    2409              :                 } else {
    2410            0 :                     return Err(TimelineArchivalError::Other(e));
    2411              :                 }
    2412              :             }
    2413              :         };
    2414              : 
    2415            0 :         if upload_needed {
    2416            0 :             info!("Uploading new state");
    2417              :             const MAX_WAIT: Duration = Duration::from_secs(10);
    2418            0 :             let Ok(v) =
    2419            0 :                 tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
    2420              :             else {
    2421            0 :                 tracing::warn!("reached timeout for waiting on upload queue");
    2422            0 :                 return Err(TimelineArchivalError::Timeout);
    2423              :             };
    2424            0 :             v.map_err(|e| match e {
    2425            0 :                 WaitCompletionError::NotInitialized(e) => {
    2426            0 :                     TimelineArchivalError::Other(anyhow::anyhow!(e))
    2427              :                 }
    2428              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2429            0 :                     TimelineArchivalError::Cancelled
    2430              :                 }
    2431            0 :             })?;
    2432            0 :         }
    2433            0 :         Ok(())
    2434            0 :     }
    2435              : 
    2436            1 :     pub fn get_offloaded_timeline(
    2437            1 :         &self,
    2438            1 :         timeline_id: TimelineId,
    2439            1 :     ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
    2440            1 :         self.timelines_offloaded
    2441            1 :             .lock()
    2442            1 :             .unwrap()
    2443            1 :             .get(&timeline_id)
    2444            1 :             .map(Arc::clone)
    2445            1 :             .ok_or(GetTimelineError::NotFound {
    2446            1 :                 tenant_id: self.tenant_shard_id,
    2447            1 :                 timeline_id,
    2448            1 :             })
    2449            1 :     }
    2450              : 
    2451            2 :     pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
    2452            2 :         self.tenant_shard_id
    2453            2 :     }
    2454              : 
    2455              :     /// Get Timeline handle for given Neon timeline ID.
    2456              :     /// This function is idempotent. It doesn't change internal state in any way.
    2457          111 :     pub fn get_timeline(
    2458          111 :         &self,
    2459          111 :         timeline_id: TimelineId,
    2460          111 :         active_only: bool,
    2461          111 :     ) -> Result<Arc<Timeline>, GetTimelineError> {
    2462          111 :         let timelines_accessor = self.timelines.lock().unwrap();
    2463          111 :         let timeline = timelines_accessor
    2464          111 :             .get(&timeline_id)
    2465          111 :             .ok_or(GetTimelineError::NotFound {
    2466          111 :                 tenant_id: self.tenant_shard_id,
    2467          111 :                 timeline_id,
    2468          111 :             })?;
    2469              : 
    2470          110 :         if active_only && !timeline.is_active() {
    2471            0 :             Err(GetTimelineError::NotActive {
    2472            0 :                 tenant_id: self.tenant_shard_id,
    2473            0 :                 timeline_id,
    2474            0 :                 state: timeline.current_state(),
    2475            0 :             })
    2476              :         } else {
    2477          110 :             Ok(Arc::clone(timeline))
    2478              :         }
    2479          111 :     }
    2480              : 
    2481              :     /// Lists timelines the tenant contains.
    2482              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2483            2 :     pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
    2484            2 :         self.timelines
    2485            2 :             .lock()
    2486            2 :             .unwrap()
    2487            2 :             .values()
    2488            2 :             .map(Arc::clone)
    2489            2 :             .collect()
    2490            2 :     }
    2491              : 
    2492              :     /// Lists timelines the tenant contains.
    2493              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2494            0 :     pub fn list_importing_timelines(&self) -> Vec<Arc<ImportingTimeline>> {
    2495            0 :         self.timelines_importing
    2496            0 :             .lock()
    2497            0 :             .unwrap()
    2498            0 :             .values()
    2499            0 :             .map(Arc::clone)
    2500            0 :             .collect()
    2501            0 :     }
    2502              : 
    2503              :     /// Lists timelines the tenant manages, including offloaded ones.
    2504              :     ///
    2505              :     /// It's up to callers to omit certain timelines that are not considered ready for use.
    2506            0 :     pub fn list_timelines_and_offloaded(
    2507            0 :         &self,
    2508            0 :     ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
    2509            0 :         let timelines = self
    2510            0 :             .timelines
    2511            0 :             .lock()
    2512            0 :             .unwrap()
    2513            0 :             .values()
    2514            0 :             .map(Arc::clone)
    2515            0 :             .collect();
    2516            0 :         let offloaded = self
    2517            0 :             .timelines_offloaded
    2518            0 :             .lock()
    2519            0 :             .unwrap()
    2520            0 :             .values()
    2521            0 :             .map(Arc::clone)
    2522            0 :             .collect();
    2523            0 :         (timelines, offloaded)
    2524            0 :     }
    2525              : 
    2526            0 :     pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
    2527            0 :         self.timelines.lock().unwrap().keys().cloned().collect()
    2528            0 :     }
    2529              : 
    2530              :     /// This is used by tests & import-from-basebackup.
    2531              :     ///
    2532              :     /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
    2533              :     /// a state that will fail [`TenantShard::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
    2534              :     ///
    2535              :     /// The caller is responsible for getting the timeline into a state that will be accepted
    2536              :     /// by [`TenantShard::load_remote_timeline`] / [`TenantShard::attach`].
    2537              :     /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
    2538              :     /// to the [`TenantShard::timelines`].
    2539              :     ///
    2540              :     /// Tests should use `TenantShard::create_test_timeline` to set up the minimum required metadata keys.
    2541          114 :     pub(crate) async fn create_empty_timeline(
    2542          114 :         self: &Arc<Self>,
    2543          114 :         new_timeline_id: TimelineId,
    2544          114 :         initdb_lsn: Lsn,
    2545          114 :         pg_version: PgMajorVersion,
    2546          114 :         ctx: &RequestContext,
    2547          114 :     ) -> anyhow::Result<(UninitializedTimeline, RequestContext)> {
    2548          114 :         anyhow::ensure!(
    2549          114 :             self.is_active(),
    2550            0 :             "Cannot create empty timelines on inactive tenant"
    2551              :         );
    2552              : 
    2553              :         // Protect against concurrent attempts to use this TimelineId
    2554          114 :         let create_guard = match self
    2555          114 :             .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
    2556          114 :             .await?
    2557              :         {
    2558          113 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2559              :             StartCreatingTimelineResult::Idempotent(_) => {
    2560            0 :                 unreachable!("FailWithConflict implies we get an error instead")
    2561              :             }
    2562              :         };
    2563              : 
    2564          113 :         let new_metadata = TimelineMetadata::new(
    2565              :             // Initialize disk_consistent LSN to 0, The caller must import some data to
    2566              :             // make it valid, before calling finish_creation()
    2567          113 :             Lsn(0),
    2568          113 :             None,
    2569          113 :             None,
    2570          113 :             Lsn(0),
    2571          113 :             initdb_lsn,
    2572          113 :             initdb_lsn,
    2573          113 :             pg_version,
    2574              :         );
    2575          113 :         self.prepare_new_timeline(
    2576          113 :             new_timeline_id,
    2577          113 :             &new_metadata,
    2578          113 :             create_guard,
    2579          113 :             initdb_lsn,
    2580          113 :             None,
    2581          113 :             None,
    2582          113 :             ctx,
    2583          113 :         )
    2584          113 :         .await
    2585          114 :     }
    2586              : 
    2587              :     /// Helper for unit tests to create an empty timeline.
    2588              :     ///
    2589              :     /// The timeline is has state value `Active` but its background loops are not running.
    2590              :     // This makes the various functions which anyhow::ensure! for Active state work in tests.
    2591              :     // Our current tests don't need the background loops.
    2592              :     #[cfg(test)]
    2593          109 :     pub async fn create_test_timeline(
    2594          109 :         self: &Arc<Self>,
    2595          109 :         new_timeline_id: TimelineId,
    2596          109 :         initdb_lsn: Lsn,
    2597          109 :         pg_version: PgMajorVersion,
    2598          109 :         ctx: &RequestContext,
    2599          109 :     ) -> anyhow::Result<Arc<Timeline>> {
    2600          109 :         let (uninit_tl, ctx) = self
    2601          109 :             .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2602          109 :             .await?;
    2603          109 :         let tline = uninit_tl.raw_timeline().expect("we just created it");
    2604          109 :         assert_eq!(tline.get_last_record_lsn(), Lsn(0));
    2605              : 
    2606              :         // Setup minimum keys required for the timeline to be usable.
    2607          109 :         let mut modification = tline.begin_modification(initdb_lsn);
    2608          109 :         modification
    2609          109 :             .init_empty_test_timeline()
    2610          109 :             .context("init_empty_test_timeline")?;
    2611          109 :         modification
    2612          109 :             .commit(&ctx)
    2613          109 :             .await
    2614          109 :             .context("commit init_empty_test_timeline modification")?;
    2615              : 
    2616              :         // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
    2617          109 :         tline.maybe_spawn_flush_loop();
    2618          109 :         tline.freeze_and_flush().await.context("freeze_and_flush")?;
    2619              : 
    2620              :         // Make sure the freeze_and_flush reaches remote storage.
    2621          109 :         tline.remote_client.wait_completion().await.unwrap();
    2622              : 
    2623          109 :         let tl = uninit_tl.finish_creation().await?;
    2624              :         // The non-test code would call tl.activate() here.
    2625          109 :         tl.set_state(TimelineState::Active);
    2626          109 :         Ok(tl)
    2627          109 :     }
    2628              : 
    2629              :     /// Helper for unit tests to create a timeline with some pre-loaded states.
    2630              :     #[cfg(test)]
    2631              :     #[allow(clippy::too_many_arguments)]
    2632           24 :     pub async fn create_test_timeline_with_layers(
    2633           24 :         self: &Arc<Self>,
    2634           24 :         new_timeline_id: TimelineId,
    2635           24 :         initdb_lsn: Lsn,
    2636           24 :         pg_version: PgMajorVersion,
    2637           24 :         ctx: &RequestContext,
    2638           24 :         in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
    2639           24 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    2640           24 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    2641           24 :         end_lsn: Lsn,
    2642           24 :     ) -> anyhow::Result<Arc<Timeline>> {
    2643              :         use checks::check_valid_layermap;
    2644              :         use itertools::Itertools;
    2645              : 
    2646           24 :         let tline = self
    2647           24 :             .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
    2648           24 :             .await?;
    2649           24 :         tline.force_advance_lsn(end_lsn);
    2650           71 :         for deltas in delta_layer_desc {
    2651           47 :             tline
    2652           47 :                 .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
    2653           47 :                 .await?;
    2654              :         }
    2655           58 :         for (lsn, images) in image_layer_desc {
    2656           34 :             tline
    2657           34 :                 .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
    2658           34 :                 .await?;
    2659              :         }
    2660           28 :         for in_memory in in_memory_layer_desc {
    2661            4 :             tline
    2662            4 :                 .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
    2663            4 :                 .await?;
    2664              :         }
    2665           24 :         let layer_names = tline
    2666           24 :             .layers
    2667           24 :             .read(LayerManagerLockHolder::Testing)
    2668           24 :             .await
    2669           24 :             .layer_map()
    2670           24 :             .unwrap()
    2671           24 :             .iter_historic_layers()
    2672          105 :             .map(|layer| layer.layer_name())
    2673           24 :             .collect_vec();
    2674           24 :         if let Some(err) = check_valid_layermap(&layer_names) {
    2675            0 :             bail!("invalid layermap: {err}");
    2676           24 :         }
    2677           24 :         Ok(tline)
    2678           24 :     }
    2679              : 
    2680              :     /// Create a new timeline.
    2681              :     ///
    2682              :     /// Returns the new timeline ID and reference to its Timeline object.
    2683              :     ///
    2684              :     /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
    2685              :     /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
    2686              :     #[allow(clippy::too_many_arguments)]
    2687            0 :     pub(crate) async fn create_timeline(
    2688            0 :         self: &Arc<TenantShard>,
    2689            0 :         params: CreateTimelineParams,
    2690            0 :         broker_client: storage_broker::BrokerClientChannel,
    2691            0 :         ctx: &RequestContext,
    2692            0 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    2693            0 :         if !self.is_active() {
    2694            0 :             if matches!(self.current_state(), TenantState::Stopping { .. }) {
    2695            0 :                 return Err(CreateTimelineError::ShuttingDown);
    2696              :             } else {
    2697            0 :                 return Err(CreateTimelineError::Other(anyhow::anyhow!(
    2698            0 :                     "Cannot create timelines on inactive tenant"
    2699            0 :                 )));
    2700              :             }
    2701            0 :         }
    2702              : 
    2703            0 :         let _gate = self
    2704            0 :             .gate
    2705            0 :             .enter()
    2706            0 :             .map_err(|_| CreateTimelineError::ShuttingDown)?;
    2707              : 
    2708            0 :         let result: CreateTimelineResult = match params {
    2709              :             CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
    2710            0 :                 new_timeline_id,
    2711            0 :                 existing_initdb_timeline_id,
    2712            0 :                 pg_version,
    2713              :             }) => {
    2714            0 :                 self.bootstrap_timeline(
    2715            0 :                     new_timeline_id,
    2716            0 :                     pg_version,
    2717            0 :                     existing_initdb_timeline_id,
    2718            0 :                     ctx,
    2719            0 :                 )
    2720            0 :                 .await?
    2721              :             }
    2722              :             CreateTimelineParams::Branch(CreateTimelineParamsBranch {
    2723            0 :                 new_timeline_id,
    2724            0 :                 ancestor_timeline_id,
    2725            0 :                 mut ancestor_start_lsn,
    2726              :             }) => {
    2727            0 :                 let ancestor_timeline = self
    2728            0 :                     .get_timeline(ancestor_timeline_id, false)
    2729            0 :                     .context("Cannot branch off the timeline that's not present in pageserver")?;
    2730              : 
    2731              :                 // instead of waiting around, just deny the request because ancestor is not yet
    2732              :                 // ready for other purposes either.
    2733            0 :                 if !ancestor_timeline.is_active() {
    2734            0 :                     return Err(CreateTimelineError::AncestorNotActive);
    2735            0 :                 }
    2736              : 
    2737            0 :                 if ancestor_timeline.is_archived() == Some(true) {
    2738            0 :                     info!("tried to branch archived timeline");
    2739            0 :                     return Err(CreateTimelineError::AncestorArchived);
    2740            0 :                 }
    2741              : 
    2742            0 :                 if let Some(lsn) = ancestor_start_lsn.as_mut() {
    2743            0 :                     *lsn = lsn.align();
    2744              : 
    2745            0 :                     let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
    2746            0 :                     if ancestor_ancestor_lsn > *lsn {
    2747              :                         // can we safely just branch from the ancestor instead?
    2748            0 :                         return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    2749            0 :                             "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
    2750            0 :                             lsn,
    2751            0 :                             ancestor_timeline_id,
    2752            0 :                             ancestor_ancestor_lsn,
    2753            0 :                         )));
    2754            0 :                     }
    2755              : 
    2756              :                     // Wait for the WAL to arrive and be processed on the parent branch up
    2757              :                     // to the requested branch point. The repository code itself doesn't
    2758              :                     // require it, but if we start to receive WAL on the new timeline,
    2759              :                     // decoding the new WAL might need to look up previous pages, relation
    2760              :                     // sizes etc. and that would get confused if the previous page versions
    2761              :                     // are not in the repository yet.
    2762            0 :                     ancestor_timeline
    2763            0 :                         .wait_lsn(
    2764            0 :                             *lsn,
    2765            0 :                             timeline::WaitLsnWaiter::Tenant,
    2766            0 :                             timeline::WaitLsnTimeout::Default,
    2767            0 :                             ctx,
    2768            0 :                         )
    2769            0 :                         .await
    2770            0 :                         .map_err(|e| match e {
    2771            0 :                             e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
    2772            0 :                                 CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
    2773              :                             }
    2774            0 :                             WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
    2775            0 :                         })?;
    2776            0 :                 }
    2777              : 
    2778            0 :                 self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
    2779            0 :                     .await?
    2780              :             }
    2781            0 :             CreateTimelineParams::ImportPgdata(params) => {
    2782            0 :                 self.create_timeline_import_pgdata(params, ctx).await?
    2783              :             }
    2784              :         };
    2785              : 
    2786              :         // At this point we have dropped our guard on [`Self::timelines_creating`], and
    2787              :         // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet.  We must
    2788              :         // not send a success to the caller until it is.  The same applies to idempotent retries.
    2789              :         //
    2790              :         // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
    2791              :         // assume that, because they can see the timeline via API, that the creation is done and
    2792              :         // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
    2793              :         // until it is durable, e.g., by extending the time we hold the creation guard. This also
    2794              :         // interacts with UninitializedTimeline and is generally a bit tricky.
    2795              :         //
    2796              :         // To re-emphasize: the only correct way to create a timeline is to repeat calling the
    2797              :         // creation API until it returns success. Only then is durability guaranteed.
    2798            0 :         info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
    2799            0 :         result
    2800            0 :             .timeline()
    2801            0 :             .remote_client
    2802            0 :             .wait_completion()
    2803            0 :             .await
    2804            0 :             .map_err(|e| match e {
    2805              :                 WaitCompletionError::NotInitialized(
    2806            0 :                     e, // If the queue is already stopped, it's a shutdown error.
    2807            0 :                 ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
    2808              :                 WaitCompletionError::NotInitialized(_) => {
    2809              :                     // This is a bug: we should never try to wait for uploads before initializing the timeline
    2810            0 :                     debug_assert!(false);
    2811            0 :                     CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
    2812              :                 }
    2813              :                 WaitCompletionError::UploadQueueShutDownOrStopped => {
    2814            0 :                     CreateTimelineError::ShuttingDown
    2815              :                 }
    2816            0 :             })?;
    2817              : 
    2818              :         // The creating task is responsible for activating the timeline.
    2819              :         // We do this after `wait_completion()` so that we don't spin up tasks that start
    2820              :         // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
    2821            0 :         let activated_timeline = match result {
    2822            0 :             CreateTimelineResult::Created(timeline) => {
    2823            0 :                 timeline.activate(
    2824            0 :                     self.clone(),
    2825            0 :                     broker_client,
    2826            0 :                     None,
    2827            0 :                     &ctx.with_scope_timeline(&timeline),
    2828              :                 );
    2829            0 :                 timeline
    2830              :             }
    2831            0 :             CreateTimelineResult::Idempotent(timeline) => {
    2832            0 :                 info!(
    2833            0 :                     "request was deemed idempotent, activation will be done by the creating task"
    2834              :                 );
    2835            0 :                 timeline
    2836              :             }
    2837            0 :             CreateTimelineResult::ImportSpawned(timeline) => {
    2838            0 :                 info!(
    2839            0 :                     "import task spawned, timeline will become visible and activated once the import is done"
    2840              :                 );
    2841            0 :                 timeline
    2842              :             }
    2843              :         };
    2844              : 
    2845            0 :         Ok(activated_timeline)
    2846            0 :     }
    2847              : 
    2848              :     /// The returned [`Arc<Timeline>`] is NOT in the [`TenantShard::timelines`] map until the import
    2849              :     /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
    2850              :     /// [`TenantShard::timelines`] map when the import completes.
    2851              :     /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
    2852              :     /// for the response.
    2853            0 :     async fn create_timeline_import_pgdata(
    2854            0 :         self: &Arc<Self>,
    2855            0 :         params: CreateTimelineParamsImportPgdata,
    2856            0 :         ctx: &RequestContext,
    2857            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    2858              :         let CreateTimelineParamsImportPgdata {
    2859            0 :             new_timeline_id,
    2860            0 :             location,
    2861            0 :             idempotency_key,
    2862            0 :         } = params;
    2863              : 
    2864            0 :         let started_at = chrono::Utc::now().naive_utc();
    2865              : 
    2866              :         //
    2867              :         // There's probably a simpler way to upload an index part, but, remote_timeline_client
    2868              :         // is the canonical way we do it.
    2869              :         // - create an empty timeline in-memory
    2870              :         // - use its remote_timeline_client to do the upload
    2871              :         // - dispose of the uninit timeline
    2872              :         // - keep the creation guard alive
    2873              : 
    2874            0 :         let timeline_create_guard = match self
    2875            0 :             .start_creating_timeline(
    2876            0 :                 new_timeline_id,
    2877            0 :                 CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
    2878            0 :                     idempotency_key: idempotency_key.clone(),
    2879            0 :                 }),
    2880            0 :             )
    2881            0 :             .await?
    2882              :         {
    2883            0 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    2884            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    2885            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    2886              :             }
    2887              :         };
    2888              : 
    2889            0 :         let (mut uninit_timeline, timeline_ctx) = {
    2890            0 :             let this = &self;
    2891            0 :             let initdb_lsn = Lsn(0);
    2892            0 :             async move {
    2893            0 :                 let new_metadata = TimelineMetadata::new(
    2894              :                     // Initialize disk_consistent LSN to 0, The caller must import some data to
    2895              :                     // make it valid, before calling finish_creation()
    2896            0 :                     Lsn(0),
    2897            0 :                     None,
    2898            0 :                     None,
    2899            0 :                     Lsn(0),
    2900            0 :                     initdb_lsn,
    2901            0 :                     initdb_lsn,
    2902            0 :                     PgMajorVersion::PG15,
    2903              :                 );
    2904            0 :                 this.prepare_new_timeline(
    2905            0 :                     new_timeline_id,
    2906            0 :                     &new_metadata,
    2907            0 :                     timeline_create_guard,
    2908            0 :                     initdb_lsn,
    2909            0 :                     None,
    2910            0 :                     None,
    2911            0 :                     ctx,
    2912            0 :                 )
    2913            0 :                 .await
    2914            0 :             }
    2915              :         }
    2916            0 :         .await?;
    2917              : 
    2918            0 :         let in_progress = import_pgdata::index_part_format::InProgress {
    2919            0 :             idempotency_key,
    2920            0 :             location,
    2921            0 :             started_at,
    2922            0 :         };
    2923            0 :         let index_part = import_pgdata::index_part_format::Root::V1(
    2924            0 :             import_pgdata::index_part_format::V1::InProgress(in_progress),
    2925            0 :         );
    2926            0 :         uninit_timeline
    2927            0 :             .raw_timeline()
    2928            0 :             .unwrap()
    2929            0 :             .remote_client
    2930            0 :             .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
    2931              : 
    2932              :         // wait_completion happens in caller
    2933              : 
    2934            0 :         let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
    2935              : 
    2936            0 :         let import_task_gate = Gate::default();
    2937            0 :         let import_task_guard = import_task_gate.enter().unwrap();
    2938              : 
    2939            0 :         let import_task_handle = tokio::spawn(self.clone().create_timeline_import_pgdata_task(
    2940            0 :             timeline.clone(),
    2941            0 :             index_part,
    2942            0 :             timeline_create_guard,
    2943            0 :             import_task_guard,
    2944            0 :             timeline_ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
    2945              :         ));
    2946              : 
    2947            0 :         let prev = self.timelines_importing.lock().unwrap().insert(
    2948            0 :             timeline.timeline_id,
    2949            0 :             Arc::new(ImportingTimeline {
    2950            0 :                 timeline: timeline.clone(),
    2951            0 :                 import_task_handle,
    2952            0 :                 import_task_gate,
    2953            0 :                 delete_progress: TimelineDeleteProgress::default(),
    2954            0 :             }),
    2955            0 :         );
    2956              : 
    2957              :         // Idempotency is enforced higher up the stack
    2958            0 :         assert!(prev.is_none());
    2959              : 
    2960              :         // NB: the timeline doesn't exist in self.timelines at this point
    2961            0 :         Ok(CreateTimelineResult::ImportSpawned(timeline))
    2962            0 :     }
    2963              : 
    2964              :     /// Finalize the import of a timeline on this shard by marking it complete in
    2965              :     /// the index part. If the import task hasn't finished yet, returns an error.
    2966              :     ///
    2967              :     /// This method is idempotent. If the import was finalized once, the next call
    2968              :     /// will be a no-op.
    2969            0 :     pub(crate) async fn finalize_importing_timeline(
    2970            0 :         &self,
    2971            0 :         timeline_id: TimelineId,
    2972            0 :     ) -> Result<(), FinalizeTimelineImportError> {
    2973            0 :         let timeline = {
    2974            0 :             let locked = self.timelines_importing.lock().unwrap();
    2975            0 :             match locked.get(&timeline_id) {
    2976            0 :                 Some(importing_timeline) => {
    2977            0 :                     if !importing_timeline.import_task_handle.is_finished() {
    2978            0 :                         return Err(FinalizeTimelineImportError::ImportTaskStillRunning);
    2979            0 :                     }
    2980              : 
    2981            0 :                     importing_timeline.timeline.clone()
    2982              :                 }
    2983              :                 None => {
    2984            0 :                     return Ok(());
    2985              :                 }
    2986              :             }
    2987              :         };
    2988              : 
    2989            0 :         timeline
    2990            0 :             .remote_client
    2991            0 :             .schedule_index_upload_for_import_pgdata_finalize()
    2992            0 :             .map_err(|_err| FinalizeTimelineImportError::ShuttingDown)?;
    2993            0 :         timeline
    2994            0 :             .remote_client
    2995            0 :             .wait_completion()
    2996            0 :             .await
    2997            0 :             .map_err(|_err| FinalizeTimelineImportError::ShuttingDown)?;
    2998              : 
    2999            0 :         self.timelines_importing
    3000            0 :             .lock()
    3001            0 :             .unwrap()
    3002            0 :             .remove(&timeline_id);
    3003              : 
    3004            0 :         Ok(())
    3005            0 :     }
    3006              : 
    3007              :     #[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))]
    3008              :     async fn create_timeline_import_pgdata_task(
    3009              :         self: Arc<TenantShard>,
    3010              :         timeline: Arc<Timeline>,
    3011              :         index_part: import_pgdata::index_part_format::Root,
    3012              :         timeline_create_guard: TimelineCreateGuard,
    3013              :         _import_task_guard: GateGuard,
    3014              :         ctx: RequestContext,
    3015              :     ) {
    3016              :         debug_assert_current_span_has_tenant_and_timeline_id();
    3017              :         info!("starting");
    3018              :         scopeguard::defer! {info!("exiting")};
    3019              : 
    3020              :         let res = self
    3021              :             .create_timeline_import_pgdata_task_impl(
    3022              :                 timeline,
    3023              :                 index_part,
    3024              :                 timeline_create_guard,
    3025              :                 ctx,
    3026              :             )
    3027              :             .await;
    3028              :         if let Err(err) = &res {
    3029              :             error!(?err, "task failed");
    3030              :             // TODO sleep & retry, sensitive to tenant shutdown
    3031              :             // TODO: allow timeline deletion requests => should cancel the task
    3032              :         }
    3033              :     }
    3034              : 
    3035            0 :     async fn create_timeline_import_pgdata_task_impl(
    3036            0 :         self: Arc<TenantShard>,
    3037            0 :         timeline: Arc<Timeline>,
    3038            0 :         index_part: import_pgdata::index_part_format::Root,
    3039            0 :         _timeline_create_guard: TimelineCreateGuard,
    3040            0 :         ctx: RequestContext,
    3041            0 :     ) -> Result<(), anyhow::Error> {
    3042            0 :         info!("importing pgdata");
    3043            0 :         let ctx = ctx.with_scope_timeline(&timeline);
    3044            0 :         import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
    3045            0 :             .await
    3046            0 :             .context("import")?;
    3047            0 :         info!("import done - waiting for activation");
    3048              : 
    3049            0 :         anyhow::Ok(())
    3050            0 :     }
    3051              : 
    3052            0 :     pub(crate) async fn delete_timeline(
    3053            0 :         self: Arc<Self>,
    3054            0 :         timeline_id: TimelineId,
    3055            0 :     ) -> Result<(), DeleteTimelineError> {
    3056            0 :         DeleteTimelineFlow::run(&self, timeline_id).await?;
    3057              : 
    3058            0 :         Ok(())
    3059            0 :     }
    3060              : 
    3061              :     /// perform one garbage collection iteration, removing old data files from disk.
    3062              :     /// this function is periodically called by gc task.
    3063              :     /// also it can be explicitly requested through page server api 'do_gc' command.
    3064              :     ///
    3065              :     /// `target_timeline_id` specifies the timeline to GC, or None for all.
    3066              :     ///
    3067              :     /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
    3068              :     /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
    3069              :     /// the amount of history, as LSN difference from current latest LSN on each timeline.
    3070              :     /// `pitr` specifies the same as a time difference from the current time. The effective
    3071              :     /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
    3072              :     /// requires more history to be retained.
    3073              :     //
    3074          377 :     pub(crate) async fn gc_iteration(
    3075          377 :         &self,
    3076          377 :         target_timeline_id: Option<TimelineId>,
    3077          377 :         horizon: u64,
    3078          377 :         pitr: Duration,
    3079          377 :         cancel: &CancellationToken,
    3080          377 :         ctx: &RequestContext,
    3081          377 :     ) -> Result<GcResult, GcError> {
    3082              :         // Don't start doing work during shutdown
    3083          377 :         if let TenantState::Stopping { .. } = self.current_state() {
    3084            0 :             return Ok(GcResult::default());
    3085          377 :         }
    3086              : 
    3087              :         // there is a global allowed_error for this
    3088          377 :         if !self.is_active() {
    3089            0 :             return Err(GcError::NotActive);
    3090          377 :         }
    3091              : 
    3092              :         {
    3093          377 :             let conf = self.tenant_conf.load();
    3094              : 
    3095              :             // If we may not delete layers, then simply skip GC.  Even though a tenant
    3096              :             // in AttachedMulti state could do GC and just enqueue the blocked deletions,
    3097              :             // the only advantage to doing it is to perhaps shrink the LayerMap metadata
    3098              :             // a bit sooner than we would achieve by waiting for AttachedSingle status.
    3099          377 :             if !conf.location.may_delete_layers_hint() {
    3100            0 :                 info!("Skipping GC in location state {:?}", conf.location);
    3101            0 :                 return Ok(GcResult::default());
    3102          377 :             }
    3103              : 
    3104          377 :             if conf.is_gc_blocked_by_lsn_lease_deadline() {
    3105          375 :                 info!("Skipping GC because lsn lease deadline is not reached");
    3106          375 :                 return Ok(GcResult::default());
    3107            2 :             }
    3108              :         }
    3109              : 
    3110            2 :         let _guard = match self.gc_block.start().await {
    3111            2 :             Ok(guard) => guard,
    3112            0 :             Err(reasons) => {
    3113            0 :                 info!("Skipping GC: {reasons}");
    3114            0 :                 return Ok(GcResult::default());
    3115              :             }
    3116              :         };
    3117              : 
    3118            2 :         self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    3119            2 :             .await
    3120          377 :     }
    3121              : 
    3122              :     /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
    3123              :     /// whether another compaction is needed, if we still have pending work or if we yield for
    3124              :     /// immediate L0 compaction.
    3125              :     ///
    3126              :     /// Compaction can also be explicitly requested for a timeline via the HTTP API.
    3127            0 :     async fn compaction_iteration(
    3128            0 :         self: &Arc<Self>,
    3129            0 :         cancel: &CancellationToken,
    3130            0 :         ctx: &RequestContext,
    3131            0 :     ) -> Result<CompactionOutcome, CompactionError> {
    3132              :         // Don't compact inactive tenants.
    3133            0 :         if !self.is_active() {
    3134            0 :             return Ok(CompactionOutcome::Skipped);
    3135            0 :         }
    3136              : 
    3137              :         // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
    3138              :         // since we need to compact L0 even in AttachedMulti to bound read amplification.
    3139            0 :         let location = self.tenant_conf.load().location;
    3140            0 :         if !location.may_upload_layers_hint() {
    3141            0 :             info!("skipping compaction in location state {location:?}");
    3142            0 :             return Ok(CompactionOutcome::Skipped);
    3143            0 :         }
    3144              : 
    3145              :         // Don't compact if the circuit breaker is tripped.
    3146            0 :         if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
    3147            0 :             info!("skipping compaction due to previous failures");
    3148            0 :             return Ok(CompactionOutcome::Skipped);
    3149            0 :         }
    3150              : 
    3151              :         // Collect all timelines to compact, along with offload instructions and L0 counts.
    3152            0 :         let mut compact: Vec<Arc<Timeline>> = Vec::new();
    3153            0 :         let mut offload: HashSet<TimelineId> = HashSet::new();
    3154            0 :         let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
    3155              : 
    3156              :         {
    3157            0 :             let offload_enabled = self.get_timeline_offloading_enabled();
    3158            0 :             let timelines = self.timelines.lock().unwrap();
    3159            0 :             for (&timeline_id, timeline) in timelines.iter() {
    3160              :                 // Skip inactive timelines.
    3161            0 :                 if !timeline.is_active() {
    3162            0 :                     continue;
    3163            0 :                 }
    3164              : 
    3165              :                 // Schedule the timeline for compaction.
    3166            0 :                 compact.push(timeline.clone());
    3167              : 
    3168              :                 // Schedule the timeline for offloading if eligible.
    3169            0 :                 let can_offload = offload_enabled
    3170            0 :                     && timeline.can_offload().0
    3171            0 :                     && !timelines
    3172            0 :                         .iter()
    3173            0 :                         .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
    3174            0 :                 if can_offload {
    3175            0 :                     offload.insert(timeline_id);
    3176            0 :                 }
    3177              :             }
    3178              :         } // release timelines lock
    3179              : 
    3180            0 :         for timeline in &compact {
    3181              :             // Collect L0 counts. Can't await while holding lock above.
    3182            0 :             if let Ok(lm) = timeline
    3183            0 :                 .layers
    3184            0 :                 .read(LayerManagerLockHolder::Compaction)
    3185            0 :                 .await
    3186            0 :                 .layer_map()
    3187            0 :             {
    3188            0 :                 l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
    3189            0 :             }
    3190              :         }
    3191              : 
    3192              :         // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
    3193              :         // bound read amplification.
    3194              :         //
    3195              :         // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
    3196              :         // compaction and offloading. We leave that as a potential problem to solve later. Consider
    3197              :         // splitting L0 and image/GC compaction to separate background jobs.
    3198            0 :         if self.get_compaction_l0_first() {
    3199            0 :             let compaction_threshold = self.get_compaction_threshold();
    3200            0 :             let compact_l0 = compact
    3201            0 :                 .iter()
    3202            0 :                 .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
    3203            0 :                 .filter(|&(_, l0)| l0 >= compaction_threshold)
    3204            0 :                 .sorted_by_key(|&(_, l0)| l0)
    3205            0 :                 .rev()
    3206            0 :                 .map(|(tli, _)| tli.clone())
    3207            0 :                 .collect_vec();
    3208              : 
    3209            0 :             let mut has_pending_l0 = false;
    3210            0 :             for timeline in compact_l0 {
    3211            0 :                 let ctx = &ctx.with_scope_timeline(&timeline);
    3212              :                 // NB: don't set CompactFlags::YieldForL0, since this is an L0-only compaction pass.
    3213            0 :                 let outcome = timeline
    3214            0 :                     .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
    3215            0 :                     .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3216            0 :                     .await
    3217            0 :                     .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3218            0 :                 match outcome {
    3219            0 :                     CompactionOutcome::Done => {}
    3220            0 :                     CompactionOutcome::Skipped => {}
    3221            0 :                     CompactionOutcome::Pending => has_pending_l0 = true,
    3222            0 :                     CompactionOutcome::YieldForL0 => has_pending_l0 = true,
    3223              :                 }
    3224              :             }
    3225            0 :             if has_pending_l0 {
    3226            0 :                 return Ok(CompactionOutcome::YieldForL0); // do another pass
    3227            0 :             }
    3228            0 :         }
    3229              : 
    3230              :         // Pass 2: image compaction and timeline offloading. If any timelines have accumulated more
    3231              :         // L0 layers, they may also be compacted here. Image compaction will yield if there is
    3232              :         // pending L0 compaction on any tenant timeline.
    3233              :         //
    3234              :         // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
    3235              :         // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
    3236            0 :         let mut has_pending = false;
    3237            0 :         for timeline in compact {
    3238            0 :             if !timeline.is_active() {
    3239            0 :                 continue;
    3240            0 :             }
    3241            0 :             let ctx = &ctx.with_scope_timeline(&timeline);
    3242              : 
    3243              :             // Yield for L0 if the separate L0 pass is enabled (otherwise there's no point).
    3244            0 :             let mut flags = EnumSet::default();
    3245            0 :             if self.get_compaction_l0_first() {
    3246            0 :                 flags |= CompactFlags::YieldForL0;
    3247            0 :             }
    3248              : 
    3249            0 :             let mut outcome = timeline
    3250            0 :                 .compact(cancel, flags, ctx)
    3251            0 :                 .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
    3252            0 :                 .await
    3253            0 :                 .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
    3254              : 
    3255              :             // If we're done compacting, check the scheduled GC compaction queue for more work.
    3256            0 :             if outcome == CompactionOutcome::Done {
    3257            0 :                 let queue = {
    3258            0 :                     let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3259            0 :                     guard
    3260            0 :                         .entry(timeline.timeline_id)
    3261            0 :                         .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
    3262            0 :                         .clone()
    3263              :                 };
    3264            0 :                 let gc_compaction_strategy = self
    3265            0 :                     .feature_resolver
    3266            0 :                     .evaluate_multivariate("gc-comapction-strategy")
    3267            0 :                     .ok();
    3268            0 :                 let span = if let Some(gc_compaction_strategy) = gc_compaction_strategy {
    3269            0 :                     info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id, strategy = %gc_compaction_strategy)
    3270              :                 } else {
    3271            0 :                     info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id)
    3272              :                 };
    3273            0 :                 outcome = queue
    3274            0 :                     .iteration(cancel, ctx, &self.gc_block, &timeline)
    3275            0 :                     .instrument(span)
    3276            0 :                     .await?;
    3277            0 :             }
    3278              : 
    3279              :             // If we're done compacting, offload the timeline if requested.
    3280            0 :             if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
    3281            0 :                 pausable_failpoint!("before-timeline-auto-offload");
    3282            0 :                 offload_timeline(self, &timeline)
    3283            0 :                     .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
    3284            0 :                     .await
    3285            0 :                     .or_else(|err| match err {
    3286              :                         // Ignore this, we likely raced with unarchival.
    3287            0 :                         OffloadError::NotArchived => Ok(()),
    3288            0 :                         OffloadError::AlreadyInProgress => Ok(()),
    3289            0 :                         err => Err(err),
    3290            0 :                     })?;
    3291            0 :             }
    3292              : 
    3293            0 :             match outcome {
    3294            0 :                 CompactionOutcome::Done => {}
    3295            0 :                 CompactionOutcome::Skipped => {}
    3296            0 :                 CompactionOutcome::Pending => has_pending = true,
    3297              :                 // This mostly makes sense when the L0-only pass above is enabled, since there's
    3298              :                 // otherwise no guarantee that we'll start with the timeline that has high L0.
    3299            0 :                 CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
    3300              :             }
    3301              :         }
    3302              : 
    3303              :         // Success! Untrip the breaker if necessary.
    3304            0 :         self.compaction_circuit_breaker
    3305            0 :             .lock()
    3306            0 :             .unwrap()
    3307            0 :             .success(&CIRCUIT_BREAKERS_UNBROKEN);
    3308              : 
    3309            0 :         match has_pending {
    3310            0 :             true => Ok(CompactionOutcome::Pending),
    3311            0 :             false => Ok(CompactionOutcome::Done),
    3312              :         }
    3313            0 :     }
    3314              : 
    3315              :     /// Trips the compaction circuit breaker if appropriate.
    3316            0 :     pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
    3317            0 :         match err {
    3318            0 :             err if err.is_cancel() => {}
    3319            0 :             CompactionError::ShuttingDown => (),
    3320              :             // Offload failures don't trip the circuit breaker, since they're cheap to retry and
    3321              :             // shouldn't block compaction.
    3322            0 :             CompactionError::Offload(_) => {}
    3323            0 :             CompactionError::CollectKeySpaceError(err) => {
    3324            0 :                 // CollectKeySpaceError::Cancelled and PageRead::Cancelled are handled in `err.is_cancel` branch.
    3325            0 :                 self.compaction_circuit_breaker
    3326            0 :                     .lock()
    3327            0 :                     .unwrap()
    3328            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3329            0 :             }
    3330            0 :             CompactionError::Other(err) => {
    3331            0 :                 self.compaction_circuit_breaker
    3332            0 :                     .lock()
    3333            0 :                     .unwrap()
    3334            0 :                     .fail(&CIRCUIT_BREAKERS_BROKEN, err);
    3335            0 :             }
    3336            0 :             CompactionError::AlreadyRunning(_) => {}
    3337              :         }
    3338            0 :     }
    3339              : 
    3340              :     /// Cancel scheduled compaction tasks
    3341            0 :     pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
    3342            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3343            0 :         if let Some(q) = guard.get_mut(&timeline_id) {
    3344            0 :             q.cancel_scheduled();
    3345            0 :         }
    3346            0 :     }
    3347              : 
    3348            0 :     pub(crate) fn get_scheduled_compaction_tasks(
    3349            0 :         &self,
    3350            0 :         timeline_id: TimelineId,
    3351            0 :     ) -> Vec<CompactInfoResponse> {
    3352            0 :         let res = {
    3353            0 :             let guard = self.scheduled_compaction_tasks.lock().unwrap();
    3354            0 :             guard.get(&timeline_id).map(|q| q.remaining_jobs())
    3355              :         };
    3356            0 :         let Some((running, remaining)) = res else {
    3357            0 :             return Vec::new();
    3358              :         };
    3359            0 :         let mut result = Vec::new();
    3360            0 :         if let Some((id, running)) = running {
    3361            0 :             result.extend(running.into_compact_info_resp(id, true));
    3362            0 :         }
    3363            0 :         for (id, job) in remaining {
    3364            0 :             result.extend(job.into_compact_info_resp(id, false));
    3365            0 :         }
    3366            0 :         result
    3367            0 :     }
    3368              : 
    3369              :     /// Schedule a compaction task for a timeline.
    3370            0 :     pub(crate) async fn schedule_compaction(
    3371            0 :         &self,
    3372            0 :         timeline_id: TimelineId,
    3373            0 :         options: CompactOptions,
    3374            0 :     ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
    3375            0 :         let (tx, rx) = tokio::sync::oneshot::channel();
    3376            0 :         let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
    3377            0 :         let q = guard
    3378            0 :             .entry(timeline_id)
    3379            0 :             .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
    3380            0 :         q.schedule_manual_compaction(options, Some(tx));
    3381            0 :         Ok(rx)
    3382            0 :     }
    3383              : 
    3384              :     /// Performs periodic housekeeping, via the tenant housekeeping background task.
    3385            0 :     async fn housekeeping(&self) {
    3386              :         // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
    3387              :         // during ingest, but we don't want idle timelines to hold open layers for too long.
    3388              :         //
    3389              :         // We don't do this if the tenant can't upload layers (i.e. it's in stale attachment mode).
    3390              :         // We don't run compaction in this case either, and don't want to keep flushing tiny L0
    3391              :         // layers that won't be compacted down.
    3392            0 :         if self.tenant_conf.load().location.may_upload_layers_hint() {
    3393            0 :             let timelines = self
    3394            0 :                 .timelines
    3395            0 :                 .lock()
    3396            0 :                 .unwrap()
    3397            0 :                 .values()
    3398            0 :                 .filter(|tli| tli.is_active())
    3399            0 :                 .cloned()
    3400            0 :                 .collect_vec();
    3401              : 
    3402            0 :             for timeline in timelines {
    3403            0 :                 timeline.maybe_freeze_ephemeral_layer().await;
    3404              :             }
    3405            0 :         }
    3406              : 
    3407              :         // Shut down walredo if idle.
    3408              :         const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
    3409            0 :         if let Some(ref walredo_mgr) = self.walredo_mgr {
    3410            0 :             walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
    3411            0 :         }
    3412              : 
    3413              :         // Update the feature resolver with the latest tenant-spcific data.
    3414            0 :         self.feature_resolver.update_cached_tenant_properties(self);
    3415            0 :     }
    3416              : 
    3417            0 :     pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
    3418            0 :         let timelines = self.timelines.lock().unwrap();
    3419            0 :         !timelines
    3420            0 :             .iter()
    3421            0 :             .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
    3422            0 :     }
    3423              : 
    3424          994 :     pub fn current_state(&self) -> TenantState {
    3425          994 :         self.state.borrow().clone()
    3426          994 :     }
    3427              : 
    3428          613 :     pub fn is_active(&self) -> bool {
    3429          613 :         self.current_state() == TenantState::Active
    3430          613 :     }
    3431              : 
    3432            0 :     pub fn generation(&self) -> Generation {
    3433            0 :         self.generation
    3434            0 :     }
    3435              : 
    3436            0 :     pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
    3437            0 :         self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
    3438            0 :     }
    3439              : 
    3440              :     /// Changes tenant status to active, unless shutdown was already requested.
    3441              :     ///
    3442              :     /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
    3443              :     /// to delay background jobs. Background jobs can be started right away when None is given.
    3444            0 :     fn activate(
    3445            0 :         self: &Arc<Self>,
    3446            0 :         broker_client: BrokerClientChannel,
    3447            0 :         background_jobs_can_start: Option<&completion::Barrier>,
    3448            0 :         ctx: &RequestContext,
    3449            0 :     ) {
    3450            0 :         span::debug_assert_current_span_has_tenant_id();
    3451              : 
    3452            0 :         let mut activating = false;
    3453            0 :         self.state.send_modify(|current_state| {
    3454              :             use pageserver_api::models::ActivatingFrom;
    3455            0 :             match &*current_state {
    3456              :                 TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
    3457            0 :                     panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {current_state:?}");
    3458              :                 }
    3459            0 :                 TenantState::Attaching => {
    3460            0 :                     *current_state = TenantState::Activating(ActivatingFrom::Attaching);
    3461            0 :                 }
    3462              :             }
    3463            0 :             debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
    3464            0 :             activating = true;
    3465              :             // Continue outside the closure. We need to grab timelines.lock()
    3466              :             // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3467            0 :         });
    3468              : 
    3469            0 :         if activating {
    3470            0 :             let timelines_accessor = self.timelines.lock().unwrap();
    3471            0 :             let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
    3472            0 :             let timelines_to_activate = timelines_accessor
    3473            0 :                 .values()
    3474            0 :                 .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
    3475              : 
    3476              :             // Spawn gc and compaction loops. The loops will shut themselves
    3477              :             // down when they notice that the tenant is inactive.
    3478            0 :             tasks::start_background_loops(self, background_jobs_can_start);
    3479              : 
    3480            0 :             let mut activated_timelines = 0;
    3481              : 
    3482            0 :             for timeline in timelines_to_activate {
    3483            0 :                 timeline.activate(
    3484            0 :                     self.clone(),
    3485            0 :                     broker_client.clone(),
    3486            0 :                     background_jobs_can_start,
    3487            0 :                     &ctx.with_scope_timeline(timeline),
    3488            0 :                 );
    3489            0 :                 activated_timelines += 1;
    3490            0 :             }
    3491              : 
    3492            0 :             let tid = self.tenant_shard_id.tenant_id.to_string();
    3493            0 :             let shard_id = self.tenant_shard_id.shard_slug().to_string();
    3494            0 :             let offloaded_timeline_count = timelines_offloaded_accessor.len();
    3495            0 :             TENANT_OFFLOADED_TIMELINES
    3496            0 :                 .with_label_values(&[&tid, &shard_id])
    3497            0 :                 .set(offloaded_timeline_count as u64);
    3498              : 
    3499            0 :             self.state.send_modify(move |current_state| {
    3500            0 :                 assert!(
    3501            0 :                     matches!(current_state, TenantState::Activating(_)),
    3502            0 :                     "set_stopping and set_broken wait for us to leave Activating state",
    3503              :                 );
    3504            0 :                 *current_state = TenantState::Active;
    3505              : 
    3506            0 :                 let elapsed = self.constructed_at.elapsed();
    3507            0 :                 let total_timelines = timelines_accessor.len();
    3508              : 
    3509              :                 // log a lot of stuff, because some tenants sometimes suffer from user-visible
    3510              :                 // times to activate. see https://github.com/neondatabase/neon/issues/4025
    3511            0 :                 info!(
    3512            0 :                     since_creation_millis = elapsed.as_millis(),
    3513            0 :                     tenant_id = %self.tenant_shard_id.tenant_id,
    3514            0 :                     shard_id = %self.tenant_shard_id.shard_slug(),
    3515              :                     activated_timelines,
    3516              :                     total_timelines,
    3517            0 :                     post_state = <&'static str>::from(&*current_state),
    3518            0 :                     "activation attempt finished"
    3519              :                 );
    3520              : 
    3521            0 :                 TENANT.activation.observe(elapsed.as_secs_f64());
    3522            0 :             });
    3523            0 :         }
    3524            0 :     }
    3525              : 
    3526              :     /// Shutdown the tenant and join all of the spawned tasks.
    3527              :     ///
    3528              :     /// The method caters for all use-cases:
    3529              :     /// - pageserver shutdown (freeze_and_flush == true)
    3530              :     /// - detach + ignore (freeze_and_flush == false)
    3531              :     ///
    3532              :     /// This will attempt to shutdown even if tenant is broken.
    3533              :     ///
    3534              :     /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
    3535              :     /// If the tenant is already shutting down, we return a clone of the first shutdown call's
    3536              :     /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
    3537              :     /// the ongoing shutdown.
    3538            3 :     async fn shutdown(
    3539            3 :         &self,
    3540            3 :         shutdown_progress: completion::Barrier,
    3541            3 :         shutdown_mode: timeline::ShutdownMode,
    3542            3 :     ) -> Result<(), completion::Barrier> {
    3543            3 :         span::debug_assert_current_span_has_tenant_id();
    3544              : 
    3545              :         // Set tenant (and its timlines) to Stoppping state.
    3546              :         //
    3547              :         // Since we can only transition into Stopping state after activation is complete,
    3548              :         // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
    3549              :         //
    3550              :         // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
    3551              :         // 1. Lock out any new requests to the tenants.
    3552              :         // 2. Signal cancellation to WAL receivers (we wait on it below).
    3553              :         // 3. Signal cancellation for other tenant background loops.
    3554              :         // 4. ???
    3555              :         //
    3556              :         // The waiting for the cancellation is not done uniformly.
    3557              :         // We certainly wait for WAL receivers to shut down.
    3558              :         // That is necessary so that no new data comes in before the freeze_and_flush.
    3559              :         // But the tenant background loops are joined-on in our caller.
    3560              :         // It's mesed up.
    3561              :         // we just ignore the failure to stop
    3562              : 
    3563              :         // If we're still attaching, fire the cancellation token early to drop out: this
    3564              :         // will prevent us flushing, but ensures timely shutdown if some I/O during attach
    3565              :         // is very slow.
    3566            3 :         let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
    3567            0 :             self.cancel.cancel();
    3568              : 
    3569              :             // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
    3570              :             // are children of ours, so their flush loops will have shut down already
    3571            0 :             timeline::ShutdownMode::Hard
    3572              :         } else {
    3573            3 :             shutdown_mode
    3574              :         };
    3575              : 
    3576            3 :         match self.set_stopping(shutdown_progress).await {
    3577            3 :             Ok(()) => {}
    3578            0 :             Err(SetStoppingError::Broken) => {
    3579            0 :                 // assume that this is acceptable
    3580            0 :             }
    3581            0 :             Err(SetStoppingError::AlreadyStopping(other)) => {
    3582              :                 // give caller the option to wait for this this shutdown
    3583            0 :                 info!("Tenant::shutdown: AlreadyStopping");
    3584            0 :                 return Err(other);
    3585              :             }
    3586              :         };
    3587              : 
    3588            3 :         let mut js = tokio::task::JoinSet::new();
    3589              :         {
    3590            3 :             let timelines = self.timelines.lock().unwrap();
    3591            3 :             timelines.values().for_each(|timeline| {
    3592            3 :                 let timeline = Arc::clone(timeline);
    3593            3 :                 let timeline_id = timeline.timeline_id;
    3594            3 :                 let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
    3595            3 :                 js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
    3596            3 :             });
    3597              :         }
    3598              :         {
    3599            3 :             let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
    3600            3 :             timelines_offloaded.values().for_each(|timeline| {
    3601            0 :                 timeline.defuse_for_tenant_drop();
    3602            0 :             });
    3603              :         }
    3604              :         {
    3605            3 :             let mut timelines_importing = self.timelines_importing.lock().unwrap();
    3606            3 :             timelines_importing
    3607            3 :                 .drain()
    3608            3 :                 .for_each(|(timeline_id, importing_timeline)| {
    3609            0 :                     let span = tracing::info_span!("importing_timeline_shutdown", %timeline_id);
    3610            0 :                     js.spawn(async move { importing_timeline.shutdown().instrument(span).await });
    3611            0 :                 });
    3612              :         }
    3613              :         // test_long_timeline_create_then_tenant_delete is leaning on this message
    3614            3 :         tracing::info!("Waiting for timelines...");
    3615            6 :         while let Some(res) = js.join_next().await {
    3616            0 :             match res {
    3617            3 :                 Ok(()) => {}
    3618            0 :                 Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
    3619            0 :                 Err(je) if je.is_panic() => { /* logged already */ }
    3620            0 :                 Err(je) => warn!("unexpected JoinError: {je:?}"),
    3621              :             }
    3622              :         }
    3623              : 
    3624            3 :         if let ShutdownMode::Reload = shutdown_mode {
    3625            0 :             tracing::info!("Flushing deletion queue");
    3626            0 :             if let Err(e) = self.deletion_queue_client.flush().await {
    3627            0 :                 match e {
    3628            0 :                     DeletionQueueError::ShuttingDown => {
    3629            0 :                         // This is the only error we expect for now. In the future, if more error
    3630            0 :                         // variants are added, we should handle them here.
    3631            0 :                     }
    3632              :                 }
    3633            0 :             }
    3634            3 :         }
    3635              : 
    3636              :         // We cancel the Tenant's cancellation token _after_ the timelines have all shut down.  This permits
    3637              :         // them to continue to do work during their shutdown methods, e.g. flushing data.
    3638            3 :         tracing::debug!("Cancelling CancellationToken");
    3639            3 :         self.cancel.cancel();
    3640              : 
    3641              :         // shutdown all tenant and timeline tasks: gc, compaction, page service
    3642              :         // No new tasks will be started for this tenant because it's in `Stopping` state.
    3643              :         //
    3644              :         // this will additionally shutdown and await all timeline tasks.
    3645            3 :         tracing::debug!("Waiting for tasks...");
    3646            3 :         task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
    3647              : 
    3648            3 :         if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
    3649            3 :             walredo_mgr.shutdown().await;
    3650            0 :         }
    3651              : 
    3652              :         // Wait for any in-flight operations to complete
    3653            3 :         self.gate.close().await;
    3654              : 
    3655            3 :         remove_tenant_metrics(&self.tenant_shard_id);
    3656              : 
    3657            3 :         Ok(())
    3658            3 :     }
    3659              : 
    3660              :     /// Change tenant status to Stopping, to mark that it is being shut down.
    3661              :     ///
    3662              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3663              :     ///
    3664              :     /// This function is not cancel-safe!
    3665            3 :     async fn set_stopping(&self, progress: completion::Barrier) -> Result<(), SetStoppingError> {
    3666            3 :         let mut rx = self.state.subscribe();
    3667              : 
    3668              :         // cannot stop before we're done activating, so wait out until we're done activating
    3669            3 :         rx.wait_for(|state| match state {
    3670              :             TenantState::Activating(_) | TenantState::Attaching => {
    3671            0 :                 info!("waiting for {state} to turn Active|Broken|Stopping");
    3672            0 :                 false
    3673              :             }
    3674            3 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3675            3 :         })
    3676            3 :         .await
    3677            3 :         .expect("cannot drop self.state while on a &self method");
    3678              : 
    3679              :         // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
    3680            3 :         let mut err = None;
    3681            3 :         let stopping = self.state.send_if_modified(|current_state| match current_state {
    3682              :             TenantState::Activating(_) | TenantState::Attaching => {
    3683            0 :                 unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3684              :             }
    3685              :             TenantState::Active => {
    3686              :                 // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
    3687              :                 // are created after the transition to Stopping. That's harmless, as the Timelines
    3688              :                 // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
    3689            3 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3690              :                 // Continue stopping outside the closure. We need to grab timelines.lock()
    3691              :                 // and we plan to turn it into a tokio::sync::Mutex in a future patch.
    3692            3 :                 true
    3693              :             }
    3694              :             TenantState::Stopping { progress: None } => {
    3695              :                 // An attach was cancelled, and the attach transitioned the tenant from Attaching to
    3696              :                 // Stopping(None) to let us know it exited. Register our progress and continue.
    3697            0 :                 *current_state = TenantState::Stopping { progress: Some(progress) };
    3698            0 :                 true
    3699              :             }
    3700            0 :             TenantState::Broken { reason, .. } => {
    3701            0 :                 info!(
    3702            0 :                     "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
    3703              :                 );
    3704            0 :                 err = Some(SetStoppingError::Broken);
    3705            0 :                 false
    3706              :             }
    3707            0 :             TenantState::Stopping { progress: Some(progress) } => {
    3708            0 :                 info!("Tenant is already in Stopping state");
    3709            0 :                 err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
    3710            0 :                 false
    3711              :             }
    3712            3 :         });
    3713            3 :         match (stopping, err) {
    3714            3 :             (true, None) => {} // continue
    3715            0 :             (false, Some(err)) => return Err(err),
    3716            0 :             (true, Some(_)) => unreachable!(
    3717              :                 "send_if_modified closure must error out if not transitioning to Stopping"
    3718              :             ),
    3719            0 :             (false, None) => unreachable!(
    3720              :                 "send_if_modified closure must return true if transitioning to Stopping"
    3721              :             ),
    3722              :         }
    3723              : 
    3724            3 :         let timelines_accessor = self.timelines.lock().unwrap();
    3725            3 :         let not_broken_timelines = timelines_accessor
    3726            3 :             .values()
    3727            3 :             .filter(|timeline| !timeline.is_broken());
    3728            6 :         for timeline in not_broken_timelines {
    3729            3 :             timeline.set_state(TimelineState::Stopping);
    3730            3 :         }
    3731            3 :         Ok(())
    3732            3 :     }
    3733              : 
    3734              :     /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
    3735              :     /// `remove_tenant_from_memory`
    3736              :     ///
    3737              :     /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
    3738              :     ///
    3739              :     /// In tests, we also use this to set tenants to Broken state on purpose.
    3740            0 :     pub(crate) async fn set_broken(&self, reason: String) {
    3741            0 :         let mut rx = self.state.subscribe();
    3742              : 
    3743              :         // The load & attach routines own the tenant state until it has reached `Active`.
    3744              :         // So, wait until it's done.
    3745            0 :         rx.wait_for(|state| match state {
    3746              :             TenantState::Activating(_) | TenantState::Attaching => {
    3747            0 :                 info!(
    3748            0 :                     "waiting for {} to turn Active|Broken|Stopping",
    3749            0 :                     <&'static str>::from(state)
    3750              :                 );
    3751            0 :                 false
    3752              :             }
    3753            0 :             TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
    3754            0 :         })
    3755            0 :         .await
    3756            0 :         .expect("cannot drop self.state while on a &self method");
    3757              : 
    3758              :         // we now know we're done activating, let's see whether this task is the winner to transition into Broken
    3759            0 :         self.set_broken_no_wait(reason)
    3760            0 :     }
    3761              : 
    3762            0 :     pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
    3763            0 :         let reason = reason.to_string();
    3764            0 :         self.state.send_modify(|current_state| {
    3765            0 :             match *current_state {
    3766              :                 TenantState::Activating(_) | TenantState::Attaching => {
    3767            0 :                     unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
    3768              :                 }
    3769              :                 TenantState::Active => {
    3770            0 :                     if cfg!(feature = "testing") {
    3771            0 :                         warn!("Changing Active tenant to Broken state, reason: {}", reason);
    3772            0 :                         *current_state = TenantState::broken_from_reason(reason);
    3773              :                     } else {
    3774            0 :                         unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
    3775              :                     }
    3776              :                 }
    3777              :                 TenantState::Broken { .. } => {
    3778            0 :                     warn!("Tenant is already in Broken state");
    3779              :                 }
    3780              :                 // This is the only "expected" path, any other path is a bug.
    3781              :                 TenantState::Stopping { .. } => {
    3782            0 :                     warn!(
    3783            0 :                         "Marking Stopping tenant as Broken state, reason: {}",
    3784              :                         reason
    3785              :                     );
    3786            0 :                     *current_state = TenantState::broken_from_reason(reason);
    3787              :                 }
    3788              :            }
    3789            0 :         });
    3790            0 :     }
    3791              : 
    3792            0 :     pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
    3793            0 :         self.state.subscribe()
    3794            0 :     }
    3795              : 
    3796              :     /// The activate_now semaphore is initialized with zero units.  As soon as
    3797              :     /// we add a unit, waiters will be able to acquire a unit and proceed.
    3798            0 :     pub(crate) fn activate_now(&self) {
    3799            0 :         self.activate_now_sem.add_permits(1);
    3800            0 :     }
    3801              : 
    3802            0 :     pub(crate) async fn wait_to_become_active(
    3803            0 :         &self,
    3804            0 :         timeout: Duration,
    3805            0 :     ) -> Result<(), GetActiveTenantError> {
    3806            0 :         let mut receiver = self.state.subscribe();
    3807              :         loop {
    3808            0 :             let current_state = receiver.borrow_and_update().clone();
    3809            0 :             match current_state {
    3810              :                 TenantState::Attaching | TenantState::Activating(_) => {
    3811              :                     // in these states, there's a chance that we can reach ::Active
    3812            0 :                     self.activate_now();
    3813            0 :                     match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
    3814            0 :                         Ok(r) => {
    3815            0 :                             r.map_err(
    3816              :                             |_e: tokio::sync::watch::error::RecvError|
    3817              :                                 // Tenant existed but was dropped: report it as non-existent
    3818            0 :                                 GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
    3819            0 :                         )?
    3820              :                         }
    3821              :                         Err(TimeoutCancellableError::Cancelled) => {
    3822            0 :                             return Err(GetActiveTenantError::Cancelled);
    3823              :                         }
    3824              :                         Err(TimeoutCancellableError::Timeout) => {
    3825            0 :                             return Err(GetActiveTenantError::WaitForActiveTimeout {
    3826            0 :                                 latest_state: Some(self.current_state()),
    3827            0 :                                 wait_time: timeout,
    3828            0 :                             });
    3829              :                         }
    3830              :                     }
    3831              :                 }
    3832              :                 TenantState::Active => {
    3833            0 :                     return Ok(());
    3834              :                 }
    3835            0 :                 TenantState::Broken { reason, .. } => {
    3836              :                     // This is fatal, and reported distinctly from the general case of "will never be active" because
    3837              :                     // it's logically a 500 to external API users (broken is always a bug).
    3838            0 :                     return Err(GetActiveTenantError::Broken(reason));
    3839              :                 }
    3840              :                 TenantState::Stopping { .. } => {
    3841              :                     // There's no chance the tenant can transition back into ::Active
    3842            0 :                     return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
    3843              :                 }
    3844              :             }
    3845              :         }
    3846            0 :     }
    3847              : 
    3848            0 :     pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
    3849            0 :         self.tenant_conf.load().location.attach_mode
    3850            0 :     }
    3851              : 
    3852              :     /// For API access: generate a LocationConfig equivalent to the one that would be used to
    3853              :     /// create a Tenant in the same state.  Do not use this in hot paths: it's for relatively
    3854              :     /// rare external API calls, like a reconciliation at startup.
    3855            0 :     pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
    3856            0 :         let attached_tenant_conf = self.tenant_conf.load();
    3857              : 
    3858            0 :         let location_config_mode = match attached_tenant_conf.location.attach_mode {
    3859            0 :             AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
    3860            0 :             AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
    3861            0 :             AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
    3862              :         };
    3863              : 
    3864            0 :         models::LocationConfig {
    3865            0 :             mode: location_config_mode,
    3866            0 :             generation: self.generation.into(),
    3867            0 :             secondary_conf: None,
    3868            0 :             shard_number: self.shard_identity.number.0,
    3869            0 :             shard_count: self.shard_identity.count.literal(),
    3870            0 :             shard_stripe_size: self.shard_identity.stripe_size.0,
    3871            0 :             tenant_conf: attached_tenant_conf.tenant_conf.clone(),
    3872            0 :         }
    3873            0 :     }
    3874              : 
    3875            0 :     pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
    3876            0 :         &self.tenant_shard_id
    3877            0 :     }
    3878              : 
    3879            0 :     pub(crate) fn get_shard_identity(&self) -> ShardIdentity {
    3880            0 :         self.shard_identity
    3881            0 :     }
    3882              : 
    3883          119 :     pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
    3884          119 :         self.shard_identity.stripe_size
    3885          119 :     }
    3886              : 
    3887            0 :     pub(crate) fn get_generation(&self) -> Generation {
    3888            0 :         self.generation
    3889            0 :     }
    3890              : 
    3891              :     /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
    3892              :     /// and can leave the tenant in a bad state if it fails.  The caller is responsible for
    3893              :     /// resetting this tenant to a valid state if we fail.
    3894            0 :     pub(crate) async fn split_prepare(
    3895            0 :         &self,
    3896            0 :         child_shards: &Vec<TenantShardId>,
    3897            0 :     ) -> anyhow::Result<()> {
    3898            0 :         let (timelines, offloaded) = {
    3899            0 :             let timelines = self.timelines.lock().unwrap();
    3900            0 :             let offloaded = self.timelines_offloaded.lock().unwrap();
    3901            0 :             (timelines.clone(), offloaded.clone())
    3902            0 :         };
    3903            0 :         let timelines_iter = timelines
    3904            0 :             .values()
    3905            0 :             .map(TimelineOrOffloadedArcRef::<'_>::from)
    3906            0 :             .chain(
    3907            0 :                 offloaded
    3908            0 :                     .values()
    3909            0 :                     .map(TimelineOrOffloadedArcRef::<'_>::from),
    3910              :             );
    3911            0 :         for timeline in timelines_iter {
    3912              :             // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
    3913              :             // to ensure that they do not start a split if currently in the process of doing these.
    3914              : 
    3915            0 :             let timeline_id = timeline.timeline_id();
    3916              : 
    3917            0 :             if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
    3918              :                 // Upload an index from the parent: this is partly to provide freshness for the
    3919              :                 // child tenants that will copy it, and partly for general ease-of-debugging: there will
    3920              :                 // always be a parent shard index in the same generation as we wrote the child shard index.
    3921            0 :                 tracing::info!(%timeline_id, "Uploading index");
    3922            0 :                 timeline
    3923            0 :                     .remote_client
    3924            0 :                     .schedule_index_upload_for_file_changes()?;
    3925            0 :                 timeline.remote_client.wait_completion().await?;
    3926            0 :             }
    3927              : 
    3928            0 :             let remote_client = match timeline {
    3929            0 :                 TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
    3930            0 :                 TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
    3931            0 :                     let remote_client = self
    3932            0 :                         .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
    3933            0 :                     Arc::new(remote_client)
    3934              :                 }
    3935              :                 TimelineOrOffloadedArcRef::Importing(_) => {
    3936            0 :                     unreachable!("Importing timelines are not included in the iterator")
    3937              :                 }
    3938              :             };
    3939              : 
    3940              :             // Shut down the timeline's remote client: this means that the indices we write
    3941              :             // for child shards will not be invalidated by the parent shard deleting layers.
    3942            0 :             tracing::info!(%timeline_id, "Shutting down remote storage client");
    3943            0 :             remote_client.shutdown().await;
    3944              : 
    3945              :             // Download methods can still be used after shutdown, as they don't flow through the remote client's
    3946              :             // queue.  In principal the RemoteTimelineClient could provide this without downloading it, but this
    3947              :             // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
    3948              :             // we use here really is the remotely persistent one).
    3949            0 :             tracing::info!(%timeline_id, "Downloading index_part from parent");
    3950            0 :             let result = remote_client
    3951            0 :                 .download_index_file(&self.cancel)
    3952            0 :                 .instrument(info_span!("download_index_file", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))
    3953            0 :                 .await?;
    3954            0 :             let index_part = match result {
    3955              :                 MaybeDeletedIndexPart::Deleted(_) => {
    3956            0 :                     anyhow::bail!("Timeline deletion happened concurrently with split")
    3957              :                 }
    3958            0 :                 MaybeDeletedIndexPart::IndexPart(p) => p,
    3959              :             };
    3960              : 
    3961              :             // A shard split may not take place while a timeline import is on-going
    3962              :             // for the tenant. Timeline imports run as part of each tenant shard
    3963              :             // and rely on the sharding scheme to split the work among pageservers.
    3964              :             // If we were to split in the middle of this process, we would have to
    3965              :             // either ensure that it's driven to completion on the old shard set
    3966              :             // or transfer it to the new shard set. It's technically possible, but complex.
    3967            0 :             match index_part.import_pgdata {
    3968            0 :                 Some(ref import) if !import.is_done() => {
    3969            0 :                     anyhow::bail!(
    3970            0 :                         "Cannot split due to import with idempotency key: {:?}",
    3971            0 :                         import.idempotency_key()
    3972              :                     );
    3973              :                 }
    3974            0 :                 Some(_) | None => {
    3975            0 :                     // fallthrough
    3976            0 :                 }
    3977              :             }
    3978              : 
    3979            0 :             for child_shard in child_shards {
    3980            0 :                 tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
    3981            0 :                 upload_index_part(
    3982            0 :                     &self.remote_storage,
    3983            0 :                     child_shard,
    3984            0 :                     &timeline_id,
    3985            0 :                     self.generation,
    3986            0 :                     &index_part,
    3987            0 :                     &self.cancel,
    3988            0 :                 )
    3989            0 :                 .await?;
    3990              :             }
    3991              :         }
    3992              : 
    3993            0 :         let tenant_manifest = self.build_tenant_manifest();
    3994            0 :         for child_shard in child_shards {
    3995            0 :             tracing::info!(
    3996            0 :                 "Uploading tenant manifest for child {}",
    3997            0 :                 child_shard.to_index()
    3998              :             );
    3999            0 :             upload_tenant_manifest(
    4000            0 :                 &self.remote_storage,
    4001            0 :                 child_shard,
    4002            0 :                 self.generation,
    4003            0 :                 &tenant_manifest,
    4004            0 :                 &self.cancel,
    4005            0 :             )
    4006            0 :             .await?;
    4007              :         }
    4008              : 
    4009            0 :         Ok(())
    4010            0 :     }
    4011              : 
    4012            0 :     pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
    4013            0 :         let mut result = TopTenantShardItem {
    4014            0 :             id: self.tenant_shard_id,
    4015            0 :             resident_size: 0,
    4016            0 :             physical_size: 0,
    4017            0 :             max_logical_size: 0,
    4018            0 :             max_logical_size_per_shard: 0,
    4019            0 :         };
    4020              : 
    4021            0 :         for timeline in self.timelines.lock().unwrap().values() {
    4022            0 :             result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
    4023            0 : 
    4024            0 :             result.physical_size += timeline
    4025            0 :                 .remote_client
    4026            0 :                 .metrics
    4027            0 :                 .remote_physical_size_gauge
    4028            0 :                 .get();
    4029            0 :             result.max_logical_size = std::cmp::max(
    4030            0 :                 result.max_logical_size,
    4031            0 :                 timeline.metrics.current_logical_size_gauge.get(),
    4032            0 :             );
    4033            0 :         }
    4034              : 
    4035            0 :         result.max_logical_size_per_shard = result
    4036            0 :             .max_logical_size
    4037            0 :             .div_ceil(self.tenant_shard_id.shard_count.count() as u64);
    4038              : 
    4039            0 :         result
    4040            0 :     }
    4041              : }
    4042              : 
    4043              : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
    4044              : /// perform a topological sort, so that the parent of each timeline comes
    4045              : /// before the children.
    4046              : /// E extracts the ancestor from T
    4047              : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
    4048          118 : fn tree_sort_timelines<T, E>(
    4049          118 :     timelines: HashMap<TimelineId, T>,
    4050          118 :     extractor: E,
    4051          118 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
    4052          118 : where
    4053          118 :     E: Fn(&T) -> Option<TimelineId>,
    4054              : {
    4055          118 :     let mut result = Vec::with_capacity(timelines.len());
    4056              : 
    4057          118 :     let mut now = Vec::with_capacity(timelines.len());
    4058              :     // (ancestor, children)
    4059          118 :     let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
    4060          118 :         HashMap::with_capacity(timelines.len());
    4061              : 
    4062          121 :     for (timeline_id, value) in timelines {
    4063            3 :         if let Some(ancestor_id) = extractor(&value) {
    4064            1 :             let children = later.entry(ancestor_id).or_default();
    4065            1 :             children.push((timeline_id, value));
    4066            2 :         } else {
    4067            2 :             now.push((timeline_id, value));
    4068            2 :         }
    4069              :     }
    4070              : 
    4071          121 :     while let Some((timeline_id, metadata)) = now.pop() {
    4072            3 :         result.push((timeline_id, metadata));
    4073              :         // All children of this can be loaded now
    4074            3 :         if let Some(mut children) = later.remove(&timeline_id) {
    4075            1 :             now.append(&mut children);
    4076            2 :         }
    4077              :     }
    4078              : 
    4079              :     // All timelines should be visited now. Unless there were timelines with missing ancestors.
    4080          118 :     if !later.is_empty() {
    4081            0 :         for (missing_id, orphan_ids) in later {
    4082            0 :             for (orphan_id, _) in orphan_ids {
    4083            0 :                 error!(
    4084            0 :                     "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
    4085              :                 );
    4086              :             }
    4087              :         }
    4088            0 :         bail!("could not load tenant because some timelines are missing ancestors");
    4089          118 :     }
    4090              : 
    4091          118 :     Ok(result)
    4092          118 : }
    4093              : 
    4094              : impl TenantShard {
    4095            0 :     pub fn tenant_specific_overrides(&self) -> pageserver_api::models::TenantConfig {
    4096            0 :         self.tenant_conf.load().tenant_conf.clone()
    4097            0 :     }
    4098              : 
    4099            0 :     pub fn effective_config(&self) -> pageserver_api::config::TenantConfigToml {
    4100            0 :         self.tenant_specific_overrides()
    4101            0 :             .merge(self.conf.default_tenant_conf.clone())
    4102            0 :     }
    4103              : 
    4104            0 :     pub fn get_checkpoint_distance(&self) -> u64 {
    4105            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4106            0 :         tenant_conf
    4107            0 :             .checkpoint_distance
    4108            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
    4109            0 :     }
    4110              : 
    4111            0 :     pub fn get_checkpoint_timeout(&self) -> Duration {
    4112            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4113            0 :         tenant_conf
    4114            0 :             .checkpoint_timeout
    4115            0 :             .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
    4116            0 :     }
    4117              : 
    4118            0 :     pub fn get_compaction_target_size(&self) -> u64 {
    4119            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4120            0 :         tenant_conf
    4121            0 :             .compaction_target_size
    4122            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
    4123            0 :     }
    4124              : 
    4125            0 :     pub fn get_compaction_period(&self) -> Duration {
    4126            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4127            0 :         tenant_conf
    4128            0 :             .compaction_period
    4129            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_period)
    4130            0 :     }
    4131              : 
    4132            0 :     pub fn get_compaction_threshold(&self) -> usize {
    4133            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4134            0 :         tenant_conf
    4135            0 :             .compaction_threshold
    4136            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
    4137            0 :     }
    4138              : 
    4139            0 :     pub fn get_rel_size_v2_enabled(&self) -> bool {
    4140            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4141            0 :         tenant_conf
    4142            0 :             .rel_size_v2_enabled
    4143            0 :             .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
    4144            0 :     }
    4145              : 
    4146            0 :     pub fn get_compaction_upper_limit(&self) -> usize {
    4147            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4148            0 :         tenant_conf
    4149            0 :             .compaction_upper_limit
    4150            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
    4151            0 :     }
    4152              : 
    4153            0 :     pub fn get_compaction_l0_first(&self) -> bool {
    4154            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4155            0 :         tenant_conf
    4156            0 :             .compaction_l0_first
    4157            0 :             .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
    4158            0 :     }
    4159              : 
    4160          120 :     pub fn get_gc_horizon(&self) -> u64 {
    4161          120 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4162          120 :         tenant_conf
    4163          120 :             .gc_horizon
    4164          120 :             .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
    4165          120 :     }
    4166              : 
    4167            0 :     pub fn get_gc_period(&self) -> Duration {
    4168            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4169            0 :         tenant_conf
    4170            0 :             .gc_period
    4171            0 :             .unwrap_or(self.conf.default_tenant_conf.gc_period)
    4172            0 :     }
    4173              : 
    4174            0 :     pub fn get_image_creation_threshold(&self) -> usize {
    4175            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4176            0 :         tenant_conf
    4177            0 :             .image_creation_threshold
    4178            0 :             .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
    4179            0 :     }
    4180              : 
    4181            2 :     pub fn get_pitr_interval(&self) -> Duration {
    4182            2 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4183            2 :         tenant_conf
    4184            2 :             .pitr_interval
    4185            2 :             .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
    4186            2 :     }
    4187              : 
    4188            0 :     pub fn get_min_resident_size_override(&self) -> Option<u64> {
    4189            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4190            0 :         tenant_conf
    4191            0 :             .min_resident_size_override
    4192            0 :             .or(self.conf.default_tenant_conf.min_resident_size_override)
    4193            0 :     }
    4194              : 
    4195            0 :     pub fn get_heatmap_period(&self) -> Option<Duration> {
    4196            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4197            0 :         let heatmap_period = tenant_conf
    4198            0 :             .heatmap_period
    4199            0 :             .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
    4200            0 :         if heatmap_period.is_zero() {
    4201            0 :             None
    4202              :         } else {
    4203            0 :             Some(heatmap_period)
    4204              :         }
    4205            0 :     }
    4206              : 
    4207            2 :     pub fn get_lsn_lease_length(&self) -> Duration {
    4208            2 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4209            2 :         tenant_conf
    4210            2 :             .lsn_lease_length
    4211            2 :             .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
    4212            2 :     }
    4213              : 
    4214            0 :     pub fn get_timeline_offloading_enabled(&self) -> bool {
    4215            0 :         if self.conf.timeline_offloading {
    4216            0 :             return true;
    4217            0 :         }
    4218            0 :         let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
    4219            0 :         tenant_conf
    4220            0 :             .timeline_offloading
    4221            0 :             .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
    4222            0 :     }
    4223              : 
    4224              :     /// Generate an up-to-date TenantManifest based on the state of this Tenant.
    4225          119 :     fn build_tenant_manifest(&self) -> TenantManifest {
    4226              :         // Collect the offloaded timelines, and sort them for deterministic output.
    4227          119 :         let offloaded_timelines = self
    4228          119 :             .timelines_offloaded
    4229          119 :             .lock()
    4230          119 :             .unwrap()
    4231          119 :             .values()
    4232          119 :             .map(|tli| tli.manifest())
    4233          119 :             .sorted_by_key(|m| m.timeline_id)
    4234          119 :             .collect_vec();
    4235              : 
    4236          119 :         TenantManifest {
    4237          119 :             version: LATEST_TENANT_MANIFEST_VERSION,
    4238          119 :             stripe_size: Some(self.get_shard_stripe_size()),
    4239          119 :             offloaded_timelines,
    4240          119 :         }
    4241          119 :     }
    4242              : 
    4243            0 :     pub fn update_tenant_config<
    4244            0 :         F: Fn(
    4245            0 :             pageserver_api::models::TenantConfig,
    4246            0 :         ) -> anyhow::Result<pageserver_api::models::TenantConfig>,
    4247            0 :     >(
    4248            0 :         &self,
    4249            0 :         update: F,
    4250            0 :     ) -> anyhow::Result<pageserver_api::models::TenantConfig> {
    4251              :         // Use read-copy-update in order to avoid overwriting the location config
    4252              :         // state if this races with [`TenantShard::set_new_location_config`]. Note that
    4253              :         // this race is not possible if both request types come from the storage
    4254              :         // controller (as they should!) because an exclusive op lock is required
    4255              :         // on the storage controller side.
    4256              : 
    4257            0 :         self.tenant_conf
    4258            0 :             .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
    4259            0 :                 Ok(Arc::new(AttachedTenantConf {
    4260            0 :                     tenant_conf: update(attached_conf.tenant_conf.clone())?,
    4261            0 :                     location: attached_conf.location,
    4262            0 :                     lsn_lease_deadline: attached_conf.lsn_lease_deadline,
    4263              :                 }))
    4264            0 :             })?;
    4265              : 
    4266            0 :         let updated = self.tenant_conf.load();
    4267              : 
    4268            0 :         self.tenant_conf_updated(&updated.tenant_conf);
    4269              :         // Don't hold self.timelines.lock() during the notifies.
    4270              :         // There's no risk of deadlock right now, but there could be if we consolidate
    4271              :         // mutexes in struct Timeline in the future.
    4272            0 :         let timelines = self.list_timelines();
    4273            0 :         for timeline in timelines {
    4274            0 :             timeline.tenant_conf_updated(&updated);
    4275            0 :         }
    4276              : 
    4277            0 :         Ok(updated.tenant_conf.clone())
    4278            0 :     }
    4279              : 
    4280            0 :     pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
    4281            0 :         let new_tenant_conf = new_conf.tenant_conf.clone();
    4282              : 
    4283            0 :         self.tenant_conf.store(Arc::new(new_conf.clone()));
    4284              : 
    4285            0 :         self.tenant_conf_updated(&new_tenant_conf);
    4286              :         // Don't hold self.timelines.lock() during the notifies.
    4287              :         // There's no risk of deadlock right now, but there could be if we consolidate
    4288              :         // mutexes in struct Timeline in the future.
    4289            0 :         let timelines = self.list_timelines();
    4290            0 :         for timeline in timelines {
    4291            0 :             timeline.tenant_conf_updated(&new_conf);
    4292            0 :         }
    4293            0 :     }
    4294              : 
    4295          118 :     fn get_pagestream_throttle_config(
    4296          118 :         psconf: &'static PageServerConf,
    4297          118 :         overrides: &pageserver_api::models::TenantConfig,
    4298          118 :     ) -> throttle::Config {
    4299          118 :         overrides
    4300          118 :             .timeline_get_throttle
    4301          118 :             .clone()
    4302          118 :             .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
    4303          118 :     }
    4304              : 
    4305            0 :     pub(crate) fn tenant_conf_updated(&self, new_conf: &pageserver_api::models::TenantConfig) {
    4306            0 :         let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
    4307            0 :         self.pagestream_throttle.reconfigure(conf)
    4308            0 :     }
    4309              : 
    4310              :     /// Helper function to create a new Timeline struct.
    4311              :     ///
    4312              :     /// The returned Timeline is in Loading state. The caller is responsible for
    4313              :     /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
    4314              :     /// map.
    4315              :     ///
    4316              :     /// `validate_ancestor == false` is used when a timeline is created for deletion
    4317              :     /// and we might not have the ancestor present anymore which is fine for to be
    4318              :     /// deleted timelines.
    4319              :     #[allow(clippy::too_many_arguments)]
    4320          234 :     fn create_timeline_struct(
    4321          234 :         &self,
    4322          234 :         new_timeline_id: TimelineId,
    4323          234 :         new_metadata: &TimelineMetadata,
    4324          234 :         previous_heatmap: Option<PreviousHeatmap>,
    4325          234 :         ancestor: Option<Arc<Timeline>>,
    4326          234 :         resources: TimelineResources,
    4327          234 :         cause: CreateTimelineCause,
    4328          234 :         create_idempotency: CreateTimelineIdempotency,
    4329          234 :         gc_compaction_state: Option<GcCompactionState>,
    4330          234 :         rel_size_v2_status: Option<RelSizeMigration>,
    4331          234 :         ctx: &RequestContext,
    4332          234 :     ) -> anyhow::Result<(Arc<Timeline>, RequestContext)> {
    4333          234 :         let state = match cause {
    4334              :             CreateTimelineCause::Load => {
    4335          234 :                 let ancestor_id = new_metadata.ancestor_timeline();
    4336          234 :                 anyhow::ensure!(
    4337          234 :                     ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
    4338            0 :                     "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
    4339              :                 );
    4340          234 :                 TimelineState::Loading
    4341              :             }
    4342            0 :             CreateTimelineCause::Delete => TimelineState::Stopping,
    4343              :         };
    4344              : 
    4345          234 :         let pg_version = new_metadata.pg_version();
    4346              : 
    4347          234 :         let timeline = Timeline::new(
    4348          234 :             self.conf,
    4349          234 :             Arc::clone(&self.tenant_conf),
    4350          234 :             new_metadata,
    4351          234 :             previous_heatmap,
    4352          234 :             ancestor,
    4353          234 :             new_timeline_id,
    4354          234 :             self.tenant_shard_id,
    4355          234 :             self.generation,
    4356          234 :             self.shard_identity,
    4357          234 :             self.walredo_mgr.clone(),
    4358          234 :             resources,
    4359          234 :             pg_version,
    4360          234 :             state,
    4361          234 :             self.attach_wal_lag_cooldown.clone(),
    4362          234 :             create_idempotency,
    4363          234 :             gc_compaction_state,
    4364          234 :             rel_size_v2_status,
    4365          234 :             self.cancel.child_token(),
    4366              :         );
    4367              : 
    4368          234 :         let timeline_ctx = RequestContextBuilder::from(ctx)
    4369          234 :             .scope(context::Scope::new_timeline(&timeline))
    4370          234 :             .detached_child();
    4371              : 
    4372          234 :         Ok((timeline, timeline_ctx))
    4373          234 :     }
    4374              : 
    4375              :     /// [`TenantShard::shutdown`] must be called before dropping the returned [`TenantShard`] object
    4376              :     /// to ensure proper cleanup of background tasks and metrics.
    4377              :     //
    4378              :     // Allow too_many_arguments because a constructor's argument list naturally grows with the
    4379              :     // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
    4380              :     #[allow(clippy::too_many_arguments)]
    4381          118 :     fn new(
    4382          118 :         state: TenantState,
    4383          118 :         conf: &'static PageServerConf,
    4384          118 :         attached_conf: AttachedTenantConf,
    4385          118 :         shard_identity: ShardIdentity,
    4386          118 :         walredo_mgr: Option<Arc<WalRedoManager>>,
    4387          118 :         tenant_shard_id: TenantShardId,
    4388          118 :         remote_storage: GenericRemoteStorage,
    4389          118 :         deletion_queue_client: DeletionQueueClient,
    4390          118 :         l0_flush_global_state: L0FlushGlobalState,
    4391          118 :         basebackup_cache: Arc<BasebackupCache>,
    4392          118 :         feature_resolver: FeatureResolver,
    4393          118 :     ) -> TenantShard {
    4394          118 :         assert!(!attached_conf.location.generation.is_none());
    4395              : 
    4396          118 :         let (state, mut rx) = watch::channel(state);
    4397              : 
    4398          118 :         tokio::spawn(async move {
    4399              :             // reflect tenant state in metrics:
    4400              :             // - global per tenant state: TENANT_STATE_METRIC
    4401              :             // - "set" of broken tenants: BROKEN_TENANTS_SET
    4402              :             //
    4403              :             // set of broken tenants should not have zero counts so that it remains accessible for
    4404              :             // alerting.
    4405              : 
    4406          118 :             let tid = tenant_shard_id.to_string();
    4407          118 :             let shard_id = tenant_shard_id.shard_slug().to_string();
    4408          118 :             let set_key = &[tid.as_str(), shard_id.as_str()][..];
    4409              : 
    4410          236 :             fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
    4411          236 :                 ([state.into()], matches!(state, TenantState::Broken { .. }))
    4412          236 :             }
    4413              : 
    4414          118 :             let mut tuple = inspect_state(&rx.borrow_and_update());
    4415              : 
    4416          118 :             let is_broken = tuple.1;
    4417          118 :             let mut counted_broken = if is_broken {
    4418              :                 // add the id to the set right away, there should not be any updates on the channel
    4419              :                 // after before tenant is removed, if ever
    4420            0 :                 BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4421            0 :                 true
    4422              :             } else {
    4423          118 :                 false
    4424              :             };
    4425              : 
    4426              :             loop {
    4427          236 :                 let labels = &tuple.0;
    4428          236 :                 let current = TENANT_STATE_METRIC.with_label_values(labels);
    4429          236 :                 current.inc();
    4430              : 
    4431          236 :                 if rx.changed().await.is_err() {
    4432              :                     // tenant has been dropped
    4433            7 :                     current.dec();
    4434            7 :                     drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
    4435            7 :                     break;
    4436          118 :                 }
    4437              : 
    4438          118 :                 current.dec();
    4439          118 :                 tuple = inspect_state(&rx.borrow_and_update());
    4440              : 
    4441          118 :                 let is_broken = tuple.1;
    4442          118 :                 if is_broken && !counted_broken {
    4443            0 :                     counted_broken = true;
    4444            0 :                     // insert the tenant_id (back) into the set while avoiding needless counter
    4445            0 :                     // access
    4446            0 :                     BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
    4447          118 :                 }
    4448              :             }
    4449            7 :         });
    4450              : 
    4451          118 :         TenantShard {
    4452          118 :             tenant_shard_id,
    4453          118 :             shard_identity,
    4454          118 :             generation: attached_conf.location.generation,
    4455          118 :             conf,
    4456          118 :             // using now here is good enough approximation to catch tenants with really long
    4457          118 :             // activation times.
    4458          118 :             constructed_at: Instant::now(),
    4459          118 :             timelines: Mutex::new(HashMap::new()),
    4460          118 :             timelines_creating: Mutex::new(HashSet::new()),
    4461          118 :             timelines_offloaded: Mutex::new(HashMap::new()),
    4462          118 :             timelines_importing: Mutex::new(HashMap::new()),
    4463          118 :             remote_tenant_manifest: Default::default(),
    4464          118 :             gc_cs: tokio::sync::Mutex::new(()),
    4465          118 :             walredo_mgr,
    4466          118 :             remote_storage,
    4467          118 :             deletion_queue_client,
    4468          118 :             state,
    4469          118 :             cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
    4470          118 :             cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
    4471          118 :             eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
    4472          118 :             compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
    4473          118 :                 format!("compaction-{tenant_shard_id}"),
    4474          118 :                 5,
    4475          118 :                 // Compaction can be a very expensive operation, and might leak disk space.  It also ought
    4476          118 :                 // to be infallible, as long as remote storage is available.  So if it repeatedly fails,
    4477          118 :                 // use an extremely long backoff.
    4478          118 :                 Some(Duration::from_secs(3600 * 24)),
    4479          118 :             )),
    4480          118 :             l0_compaction_trigger: Arc::new(Notify::new()),
    4481          118 :             scheduled_compaction_tasks: Mutex::new(Default::default()),
    4482          118 :             activate_now_sem: tokio::sync::Semaphore::new(0),
    4483          118 :             attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
    4484          118 :             cancel: CancellationToken::default(),
    4485          118 :             gate: Gate::default(),
    4486          118 :             pagestream_throttle: Arc::new(throttle::Throttle::new(
    4487          118 :                 TenantShard::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
    4488          118 :             )),
    4489          118 :             pagestream_throttle_metrics: Arc::new(
    4490          118 :                 crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
    4491          118 :             ),
    4492          118 :             tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
    4493          118 :             ongoing_timeline_detach: std::sync::Mutex::default(),
    4494          118 :             gc_block: Default::default(),
    4495          118 :             l0_flush_global_state,
    4496          118 :             basebackup_cache,
    4497          118 :             feature_resolver: TenantFeatureResolver::new(
    4498          118 :                 feature_resolver,
    4499          118 :                 tenant_shard_id.tenant_id,
    4500          118 :             ),
    4501          118 :         }
    4502          118 :     }
    4503              : 
    4504              :     /// Locate and load config
    4505            0 :     pub(super) fn load_tenant_config(
    4506            0 :         conf: &'static PageServerConf,
    4507            0 :         tenant_shard_id: &TenantShardId,
    4508            0 :     ) -> Result<LocationConf, LoadConfigError> {
    4509            0 :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4510              : 
    4511            0 :         info!("loading tenant configuration from {config_path}");
    4512              : 
    4513              :         // load and parse file
    4514            0 :         let config = fs::read_to_string(&config_path).map_err(|e| {
    4515            0 :             match e.kind() {
    4516              :                 std::io::ErrorKind::NotFound => {
    4517              :                     // The config should almost always exist for a tenant directory:
    4518              :                     //  - When attaching a tenant, the config is the first thing we write
    4519              :                     //  - When detaching a tenant, we atomically move the directory to a tmp location
    4520              :                     //    before deleting contents.
    4521              :                     //
    4522              :                     // The very rare edge case that can result in a missing config is if we crash during attach
    4523              :                     // between creating directory and writing config.  Callers should handle that as if the
    4524              :                     // directory didn't exist.
    4525              : 
    4526            0 :                     LoadConfigError::NotFound(config_path)
    4527              :                 }
    4528              :                 _ => {
    4529              :                     // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
    4530              :                     // that we cannot cleanly recover
    4531            0 :                     crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
    4532              :                 }
    4533              :             }
    4534            0 :         })?;
    4535              : 
    4536            0 :         Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
    4537            0 :     }
    4538              : 
    4539              :     /// Stores a tenant location config to disk.
    4540              :     ///
    4541              :     /// NB: make sure to call `ShardIdentity::assert_equal` before persisting a new config, to avoid
    4542              :     /// changes to shard parameters that may result in data corruption.
    4543              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4544              :     pub(super) async fn persist_tenant_config(
    4545              :         conf: &'static PageServerConf,
    4546              :         tenant_shard_id: &TenantShardId,
    4547              :         location_conf: &LocationConf,
    4548              :     ) -> std::io::Result<()> {
    4549              :         let config_path = conf.tenant_location_config_path(tenant_shard_id);
    4550              : 
    4551              :         Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
    4552              :     }
    4553              : 
    4554              :     #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
    4555              :     pub(super) async fn persist_tenant_config_at(
    4556              :         tenant_shard_id: &TenantShardId,
    4557              :         config_path: &Utf8Path,
    4558              :         location_conf: &LocationConf,
    4559              :     ) -> std::io::Result<()> {
    4560              :         debug!("persisting tenantconf to {config_path}");
    4561              : 
    4562              :         let mut conf_content = r#"# This file contains a specific per-tenant's config.
    4563              : #  It is read in case of pageserver restart.
    4564              : "#
    4565              :         .to_string();
    4566              : 
    4567            0 :         fail::fail_point!("tenant-config-before-write", |_| {
    4568            0 :             Err(std::io::Error::other("tenant-config-before-write"))
    4569            0 :         });
    4570              : 
    4571              :         // Convert the config to a toml file.
    4572              :         conf_content +=
    4573              :             &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
    4574              : 
    4575              :         let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
    4576              : 
    4577              :         let conf_content = conf_content.into_bytes();
    4578              :         VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
    4579              :     }
    4580              : 
    4581              :     //
    4582              :     // How garbage collection works:
    4583              :     //
    4584              :     //                    +--bar------------->
    4585              :     //                   /
    4586              :     //             +----+-----foo---------------->
    4587              :     //            /
    4588              :     // ----main--+-------------------------->
    4589              :     //                \
    4590              :     //                 +-----baz-------->
    4591              :     //
    4592              :     //
    4593              :     // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
    4594              :     //    `gc_infos` are being refreshed
    4595              :     // 2. Scan collected timelines, and on each timeline, make note of the
    4596              :     //    all the points where other timelines have been branched off.
    4597              :     //    We will refrain from removing page versions at those LSNs.
    4598              :     // 3. For each timeline, scan all layer files on the timeline.
    4599              :     //    Remove all files for which a newer file exists and which
    4600              :     //    don't cover any branch point LSNs.
    4601              :     //
    4602              :     // TODO:
    4603              :     // - if a relation has a non-incremental persistent layer on a child branch, then we
    4604              :     //   don't need to keep that in the parent anymore. But currently
    4605              :     //   we do.
    4606            2 :     async fn gc_iteration_internal(
    4607            2 :         &self,
    4608            2 :         target_timeline_id: Option<TimelineId>,
    4609            2 :         horizon: u64,
    4610            2 :         pitr: Duration,
    4611            2 :         cancel: &CancellationToken,
    4612            2 :         ctx: &RequestContext,
    4613            2 :     ) -> Result<GcResult, GcError> {
    4614            2 :         let mut totals: GcResult = Default::default();
    4615            2 :         let now = Instant::now();
    4616              : 
    4617            2 :         let gc_timelines = self
    4618            2 :             .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4619            2 :             .await?;
    4620              : 
    4621            2 :         failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
    4622              : 
    4623              :         // If there is nothing to GC, we don't want any messages in the INFO log.
    4624            2 :         if !gc_timelines.is_empty() {
    4625            2 :             info!("{} timelines need GC", gc_timelines.len());
    4626              :         } else {
    4627            0 :             debug!("{} timelines need GC", gc_timelines.len());
    4628              :         }
    4629              : 
    4630              :         // Perform GC for each timeline.
    4631              :         //
    4632              :         // Note that we don't hold the `TenantShard::gc_cs` lock here because we don't want to delay the
    4633              :         // branch creation task, which requires the GC lock. A GC iteration can run concurrently
    4634              :         // with branch creation.
    4635              :         //
    4636              :         // See comments in [`TenantShard::branch_timeline`] for more information about why branch
    4637              :         // creation task can run concurrently with timeline's GC iteration.
    4638            4 :         for timeline in gc_timelines {
    4639            2 :             if cancel.is_cancelled() {
    4640              :                 // We were requested to shut down. Stop and return with the progress we
    4641              :                 // made.
    4642            0 :                 break;
    4643            2 :             }
    4644            2 :             let result = match timeline.gc().await {
    4645              :                 Err(GcError::TimelineCancelled) => {
    4646            0 :                     if target_timeline_id.is_some() {
    4647              :                         // If we were targetting this specific timeline, surface cancellation to caller
    4648            0 :                         return Err(GcError::TimelineCancelled);
    4649              :                     } else {
    4650              :                         // A timeline may be shutting down independently of the tenant's lifecycle: we should
    4651              :                         // skip past this and proceed to try GC on other timelines.
    4652            0 :                         continue;
    4653              :                     }
    4654              :                 }
    4655            2 :                 r => r?,
    4656              :             };
    4657            2 :             totals += result;
    4658              :         }
    4659              : 
    4660            2 :         totals.elapsed = now.elapsed();
    4661            2 :         Ok(totals)
    4662            2 :     }
    4663              : 
    4664              :     /// Refreshes the Timeline::gc_info for all timelines, returning the
    4665              :     /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
    4666              :     /// [`TenantShard::get_gc_horizon`].
    4667              :     ///
    4668              :     /// This is usually executed as part of periodic gc, but can now be triggered more often.
    4669            2 :     pub(crate) async fn refresh_gc_info(
    4670            2 :         &self,
    4671            2 :         cancel: &CancellationToken,
    4672            2 :         ctx: &RequestContext,
    4673            2 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4674              :         // since this method can now be called at different rates than the configured gc loop, it
    4675              :         // might be that these configuration values get applied faster than what it was previously,
    4676              :         // since these were only read from the gc task.
    4677            2 :         let horizon = self.get_gc_horizon();
    4678            2 :         let pitr = self.get_pitr_interval();
    4679              : 
    4680              :         // refresh all timelines
    4681            2 :         let target_timeline_id = None;
    4682              : 
    4683            2 :         self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
    4684            2 :             .await
    4685            2 :     }
    4686              : 
    4687              :     /// Populate all Timelines' `GcInfo` with information about their children.  We do not set the
    4688              :     /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
    4689              :     ///
    4690              :     /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
    4691          118 :     fn initialize_gc_info(
    4692          118 :         &self,
    4693          118 :         timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
    4694          118 :         timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
    4695          118 :         restrict_to_timeline: Option<TimelineId>,
    4696          118 :     ) {
    4697          118 :         if restrict_to_timeline.is_none() {
    4698              :             // This function must be called before activation: after activation timeline create/delete operations
    4699              :             // might happen, and this function is not safe to run concurrently with those.
    4700          118 :             assert!(!self.is_active());
    4701            0 :         }
    4702              : 
    4703              :         // Scan all timelines. For each timeline, remember the timeline ID and
    4704              :         // the branch point where it was created.
    4705          118 :         let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
    4706          118 :             BTreeMap::new();
    4707          118 :         timelines.iter().for_each(|(timeline_id, timeline_entry)| {
    4708            3 :             if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
    4709            1 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4710            1 :                 ancestor_children.push((
    4711            1 :                     timeline_entry.get_ancestor_lsn(),
    4712            1 :                     *timeline_id,
    4713            1 :                     MaybeOffloaded::No,
    4714            1 :                 ));
    4715            2 :             }
    4716            3 :         });
    4717          118 :         timelines_offloaded
    4718          118 :             .iter()
    4719          118 :             .for_each(|(timeline_id, timeline_entry)| {
    4720            0 :                 let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
    4721            0 :                     return;
    4722              :                 };
    4723            0 :                 let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
    4724            0 :                     return;
    4725              :                 };
    4726            0 :                 let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
    4727            0 :                 ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
    4728            0 :             });
    4729              : 
    4730              :         // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
    4731          118 :         let horizon = self.get_gc_horizon();
    4732              : 
    4733              :         // Populate each timeline's GcInfo with information about its child branches
    4734          118 :         let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
    4735            0 :             itertools::Either::Left(timelines.get(&timeline_id).into_iter())
    4736              :         } else {
    4737          118 :             itertools::Either::Right(timelines.values())
    4738              :         };
    4739          121 :         for timeline in timelines_to_write {
    4740            3 :             let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
    4741            3 :                 .remove(&timeline.timeline_id)
    4742            3 :                 .unwrap_or_default();
    4743              : 
    4744            3 :             branchpoints.sort_by_key(|b| b.0);
    4745              : 
    4746            3 :             let mut target = timeline.gc_info.write().unwrap();
    4747              : 
    4748            3 :             target.retain_lsns = branchpoints;
    4749              : 
    4750            3 :             let space_cutoff = timeline
    4751            3 :                 .get_last_record_lsn()
    4752            3 :                 .checked_sub(horizon)
    4753            3 :                 .unwrap_or(Lsn(0));
    4754              : 
    4755            3 :             target.cutoffs = GcCutoffs {
    4756            3 :                 space: space_cutoff,
    4757            3 :                 time: None,
    4758            3 :             };
    4759              :         }
    4760          118 :     }
    4761              : 
    4762            4 :     async fn refresh_gc_info_internal(
    4763            4 :         &self,
    4764            4 :         target_timeline_id: Option<TimelineId>,
    4765            4 :         horizon: u64,
    4766            4 :         pitr: Duration,
    4767            4 :         cancel: &CancellationToken,
    4768            4 :         ctx: &RequestContext,
    4769            4 :     ) -> Result<Vec<Arc<Timeline>>, GcError> {
    4770              :         // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
    4771              :         // currently visible timelines.
    4772            4 :         let timelines = self
    4773            4 :             .timelines
    4774            4 :             .lock()
    4775            4 :             .unwrap()
    4776            4 :             .values()
    4777           10 :             .filter(|tl| match target_timeline_id.as_ref() {
    4778            2 :                 Some(target) => &tl.timeline_id == target,
    4779            8 :                 None => true,
    4780           10 :             })
    4781            4 :             .cloned()
    4782            4 :             .collect::<Vec<_>>();
    4783              : 
    4784            4 :         if target_timeline_id.is_some() && timelines.is_empty() {
    4785              :             // We were to act on a particular timeline and it wasn't found
    4786            0 :             return Err(GcError::TimelineNotFound);
    4787            4 :         }
    4788              : 
    4789            4 :         let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
    4790            4 :             HashMap::with_capacity(timelines.len());
    4791              : 
    4792              :         // Ensures all timelines use the same start time when computing the time cutoff.
    4793            4 :         let now_ts_for_pitr_calc = SystemTime::now();
    4794           10 :         for timeline in timelines.iter() {
    4795           10 :             let ctx = &ctx.with_scope_timeline(timeline);
    4796           10 :             let cutoff = timeline
    4797           10 :                 .get_last_record_lsn()
    4798           10 :                 .checked_sub(horizon)
    4799           10 :                 .unwrap_or(Lsn(0));
    4800              : 
    4801           10 :             let cutoffs = timeline
    4802           10 :                 .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
    4803           10 :                 .await?;
    4804           10 :             let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
    4805           10 :             assert!(old.is_none());
    4806              :         }
    4807              : 
    4808            4 :         if !self.is_active() || self.cancel.is_cancelled() {
    4809            0 :             return Err(GcError::TenantCancelled);
    4810            4 :         }
    4811              : 
    4812              :         // grab mutex to prevent new timelines from being created here; avoid doing long operations
    4813              :         // because that will stall branch creation.
    4814            4 :         let gc_cs = self.gc_cs.lock().await;
    4815              : 
    4816              :         // Ok, we now know all the branch points.
    4817              :         // Update the GC information for each timeline.
    4818            4 :         let mut gc_timelines = Vec::with_capacity(timelines.len());
    4819           14 :         for timeline in timelines {
    4820              :             // We filtered the timeline list above
    4821           10 :             if let Some(target_timeline_id) = target_timeline_id {
    4822            2 :                 assert_eq!(target_timeline_id, timeline.timeline_id);
    4823            8 :             }
    4824              : 
    4825              :             {
    4826           10 :                 let mut target = timeline.gc_info.write().unwrap();
    4827              : 
    4828              :                 // Cull any expired leases
    4829           10 :                 let now = SystemTime::now();
    4830           10 :                 target.leases.retain(|_, lease| !lease.is_expired(&now));
    4831              : 
    4832           10 :                 timeline
    4833           10 :                     .metrics
    4834           10 :                     .valid_lsn_lease_count_gauge
    4835           10 :                     .set(target.leases.len() as u64);
    4836              : 
    4837              :                 // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
    4838           10 :                 if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
    4839            6 :                     if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
    4840            6 :                         target.within_ancestor_pitr =
    4841            6 :                             Some(timeline.get_ancestor_lsn()) >= ancestor_gc_cutoffs.time;
    4842            6 :                     }
    4843            4 :                 }
    4844              : 
    4845              :                 // Update metrics that depend on GC state
    4846           10 :                 timeline
    4847           10 :                     .metrics
    4848           10 :                     .archival_size
    4849           10 :                     .set(if target.within_ancestor_pitr {
    4850            0 :                         timeline.metrics.current_logical_size_gauge.get()
    4851              :                     } else {
    4852           10 :                         0
    4853              :                     });
    4854           10 :                 if let Some(time_cutoff) = target.cutoffs.time {
    4855            4 :                     timeline.metrics.pitr_history_size.set(
    4856            4 :                         timeline
    4857            4 :                             .get_last_record_lsn()
    4858            4 :                             .checked_sub(time_cutoff)
    4859            4 :                             .unwrap_or_default()
    4860            4 :                             .0,
    4861            4 :                     );
    4862            6 :                 }
    4863              : 
    4864              :                 // Apply the cutoffs we found to the Timeline's GcInfo.  Why might we _not_ have cutoffs for a timeline?
    4865              :                 // - this timeline was created while we were finding cutoffs
    4866              :                 // - lsn for timestamp search fails for this timeline repeatedly
    4867           10 :                 if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
    4868           10 :                     let original_cutoffs = target.cutoffs.clone();
    4869              :                     // GC cutoffs should never go back
    4870           10 :                     target.cutoffs = GcCutoffs {
    4871           10 :                         space: cutoffs.space.max(original_cutoffs.space),
    4872           10 :                         time: cutoffs.time.max(original_cutoffs.time),
    4873           10 :                     }
    4874            0 :                 }
    4875              :             }
    4876              : 
    4877           10 :             gc_timelines.push(timeline);
    4878              :         }
    4879            4 :         drop(gc_cs);
    4880            4 :         Ok(gc_timelines)
    4881            4 :     }
    4882              : 
    4883              :     /// A substitute for `branch_timeline` for use in unit tests.
    4884              :     /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
    4885              :     /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
    4886              :     /// timeline background tasks are launched, except the flush loop.
    4887              :     #[cfg(test)]
    4888          119 :     async fn branch_timeline_test(
    4889          119 :         self: &Arc<Self>,
    4890          119 :         src_timeline: &Arc<Timeline>,
    4891          119 :         dst_id: TimelineId,
    4892          119 :         ancestor_lsn: Option<Lsn>,
    4893          119 :         ctx: &RequestContext,
    4894          119 :     ) -> Result<Arc<Timeline>, CreateTimelineError> {
    4895          119 :         let tl = self
    4896          119 :             .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
    4897          119 :             .await?
    4898          117 :             .into_timeline_for_test();
    4899          117 :         tl.set_state(TimelineState::Active);
    4900          117 :         Ok(tl)
    4901          119 :     }
    4902              : 
    4903              :     /// Helper for unit tests to branch a timeline with some pre-loaded states.
    4904              :     #[cfg(test)]
    4905              :     #[allow(clippy::too_many_arguments)]
    4906            6 :     pub async fn branch_timeline_test_with_layers(
    4907            6 :         self: &Arc<Self>,
    4908            6 :         src_timeline: &Arc<Timeline>,
    4909            6 :         dst_id: TimelineId,
    4910            6 :         ancestor_lsn: Option<Lsn>,
    4911            6 :         ctx: &RequestContext,
    4912            6 :         delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
    4913            6 :         image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
    4914            6 :         end_lsn: Lsn,
    4915            6 :     ) -> anyhow::Result<Arc<Timeline>> {
    4916              :         use checks::check_valid_layermap;
    4917              :         use itertools::Itertools;
    4918              : 
    4919            6 :         let tline = self
    4920            6 :             .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
    4921            6 :             .await?;
    4922            6 :         let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
    4923            6 :             ancestor_lsn
    4924              :         } else {
    4925            0 :             tline.get_last_record_lsn()
    4926              :         };
    4927            6 :         assert!(end_lsn >= ancestor_lsn);
    4928            6 :         tline.force_advance_lsn(end_lsn);
    4929            9 :         for deltas in delta_layer_desc {
    4930            3 :             tline
    4931            3 :                 .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
    4932            3 :                 .await?;
    4933              :         }
    4934            8 :         for (lsn, images) in image_layer_desc {
    4935            2 :             tline
    4936            2 :                 .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
    4937            2 :                 .await?;
    4938              :         }
    4939            6 :         let layer_names = tline
    4940            6 :             .layers
    4941            6 :             .read(LayerManagerLockHolder::Testing)
    4942            6 :             .await
    4943            6 :             .layer_map()
    4944            6 :             .unwrap()
    4945            6 :             .iter_historic_layers()
    4946            6 :             .map(|layer| layer.layer_name())
    4947            6 :             .collect_vec();
    4948            6 :         if let Some(err) = check_valid_layermap(&layer_names) {
    4949            0 :             bail!("invalid layermap: {err}");
    4950            6 :         }
    4951            6 :         Ok(tline)
    4952            6 :     }
    4953              : 
    4954              :     /// Branch an existing timeline.
    4955            0 :     async fn branch_timeline(
    4956            0 :         self: &Arc<Self>,
    4957            0 :         src_timeline: &Arc<Timeline>,
    4958            0 :         dst_id: TimelineId,
    4959            0 :         start_lsn: Option<Lsn>,
    4960            0 :         ctx: &RequestContext,
    4961            0 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4962            0 :         self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
    4963            0 :             .await
    4964            0 :     }
    4965              : 
    4966          119 :     async fn branch_timeline_impl(
    4967          119 :         self: &Arc<Self>,
    4968          119 :         src_timeline: &Arc<Timeline>,
    4969          119 :         dst_id: TimelineId,
    4970          119 :         start_lsn: Option<Lsn>,
    4971          119 :         ctx: &RequestContext,
    4972          119 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    4973          119 :         let src_id = src_timeline.timeline_id;
    4974              : 
    4975              :         // We will validate our ancestor LSN in this function.  Acquire the GC lock so that
    4976              :         // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
    4977              :         // valid while we are creating the branch.
    4978          119 :         let _gc_cs = self.gc_cs.lock().await;
    4979              : 
    4980              :         // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
    4981          119 :         let start_lsn = start_lsn.unwrap_or_else(|| {
    4982            1 :             let lsn = src_timeline.get_last_record_lsn();
    4983            1 :             info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
    4984            1 :             lsn
    4985            1 :         });
    4986              : 
    4987              :         // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
    4988          119 :         let timeline_create_guard = match self
    4989          119 :             .start_creating_timeline(
    4990          119 :                 dst_id,
    4991          119 :                 CreateTimelineIdempotency::Branch {
    4992          119 :                     ancestor_timeline_id: src_timeline.timeline_id,
    4993          119 :                     ancestor_start_lsn: start_lsn,
    4994          119 :                 },
    4995          119 :             )
    4996          119 :             .await?
    4997              :         {
    4998          119 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    4999            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5000            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5001              :             }
    5002              :         };
    5003              : 
    5004              :         // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
    5005              :         // horizon on the source timeline
    5006              :         //
    5007              :         // We check it against both the planned GC cutoff stored in 'gc_info',
    5008              :         // and the 'latest_gc_cutoff' of the last GC that was performed.  The
    5009              :         // planned GC cutoff in 'gc_info' is normally larger than
    5010              :         // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
    5011              :         // changed the GC settings for the tenant to make the PITR window
    5012              :         // larger, but some of the data was already removed by an earlier GC
    5013              :         // iteration.
    5014              : 
    5015              :         // check against last actual 'latest_gc_cutoff' first
    5016          119 :         let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
    5017              :         {
    5018          119 :             let gc_info = src_timeline.gc_info.read().unwrap();
    5019          119 :             let planned_cutoff = gc_info.min_cutoff();
    5020          119 :             if gc_info.lsn_covered_by_lease(start_lsn) {
    5021            0 :                 tracing::info!(
    5022            0 :                     "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
    5023            0 :                     *applied_gc_cutoff_lsn
    5024              :                 );
    5025              :             } else {
    5026          119 :                 src_timeline
    5027          119 :                     .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
    5028          119 :                     .context(format!(
    5029          119 :                         "invalid branch start lsn: less than latest GC cutoff {}",
    5030          119 :                         *applied_gc_cutoff_lsn,
    5031              :                     ))
    5032          119 :                     .map_err(CreateTimelineError::AncestorLsn)?;
    5033              : 
    5034              :                 // and then the planned GC cutoff
    5035          117 :                 if start_lsn < planned_cutoff {
    5036            0 :                     return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
    5037            0 :                         "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
    5038            0 :                     )));
    5039          117 :                 }
    5040              :             }
    5041              :         }
    5042              : 
    5043              :         //
    5044              :         // The branch point is valid, and we are still holding the 'gc_cs' lock
    5045              :         // so that GC cannot advance the GC cutoff until we are finished.
    5046              :         // Proceed with the branch creation.
    5047              :         //
    5048              : 
    5049              :         // Determine prev-LSN for the new timeline. We can only determine it if
    5050              :         // the timeline was branched at the current end of the source timeline.
    5051              :         let RecordLsn {
    5052          117 :             last: src_last,
    5053          117 :             prev: src_prev,
    5054          117 :         } = src_timeline.get_last_record_rlsn();
    5055          117 :         let dst_prev = if src_last == start_lsn {
    5056          108 :             Some(src_prev)
    5057              :         } else {
    5058            9 :             None
    5059              :         };
    5060              : 
    5061              :         // Create the metadata file, noting the ancestor of the new timeline.
    5062              :         // There is initially no data in it, but all the read-calls know to look
    5063              :         // into the ancestor.
    5064          117 :         let metadata = TimelineMetadata::new(
    5065          117 :             start_lsn,
    5066          117 :             dst_prev,
    5067          117 :             Some(src_id),
    5068          117 :             start_lsn,
    5069          117 :             *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
    5070          117 :             src_timeline.initdb_lsn,
    5071          117 :             src_timeline.pg_version,
    5072              :         );
    5073              : 
    5074          117 :         let (uninitialized_timeline, _timeline_ctx) = self
    5075          117 :             .prepare_new_timeline(
    5076          117 :                 dst_id,
    5077          117 :                 &metadata,
    5078          117 :                 timeline_create_guard,
    5079          117 :                 start_lsn + 1,
    5080          117 :                 Some(Arc::clone(src_timeline)),
    5081          117 :                 Some(src_timeline.get_rel_size_v2_status()),
    5082          117 :                 ctx,
    5083          117 :             )
    5084          117 :             .await?;
    5085              : 
    5086          117 :         let new_timeline = uninitialized_timeline.finish_creation().await?;
    5087              : 
    5088              :         // Root timeline gets its layers during creation and uploads them along with the metadata.
    5089              :         // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
    5090              :         // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
    5091              :         // could get incorrect information and remove more layers, than needed.
    5092              :         // See also https://github.com/neondatabase/neon/issues/3865
    5093          117 :         new_timeline
    5094          117 :             .remote_client
    5095          117 :             .schedule_index_upload_for_full_metadata_update(&metadata)
    5096          117 :             .context("branch initial metadata upload")?;
    5097              : 
    5098              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5099              : 
    5100          117 :         Ok(CreateTimelineResult::Created(new_timeline))
    5101          119 :     }
    5102              : 
    5103              :     /// For unit tests, make this visible so that other modules can directly create timelines
    5104              :     #[cfg(test)]
    5105              :     #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
    5106              :     pub(crate) async fn bootstrap_timeline_test(
    5107              :         self: &Arc<Self>,
    5108              :         timeline_id: TimelineId,
    5109              :         pg_version: PgMajorVersion,
    5110              :         load_existing_initdb: Option<TimelineId>,
    5111              :         ctx: &RequestContext,
    5112              :     ) -> anyhow::Result<Arc<Timeline>> {
    5113              :         self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
    5114              :             .await
    5115              :             .map_err(anyhow::Error::new)
    5116            1 :             .map(|r| r.into_timeline_for_test())
    5117              :     }
    5118              : 
    5119              :     /// Get exclusive access to the timeline ID for creation.
    5120              :     ///
    5121              :     /// Timeline-creating code paths must use this function before making changes
    5122              :     /// to in-memory or persistent state.
    5123              :     ///
    5124              :     /// The `state` parameter is a description of the timeline creation operation
    5125              :     /// we intend to perform.
    5126              :     /// If the timeline was already created in the meantime, we check whether this
    5127              :     /// request conflicts or is idempotent , based on `state`.
    5128          234 :     async fn start_creating_timeline(
    5129          234 :         self: &Arc<Self>,
    5130          234 :         new_timeline_id: TimelineId,
    5131          234 :         idempotency: CreateTimelineIdempotency,
    5132          234 :     ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
    5133          234 :         let allow_offloaded = false;
    5134          234 :         match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
    5135          233 :             Ok(create_guard) => {
    5136          233 :                 pausable_failpoint!("timeline-creation-after-uninit");
    5137          233 :                 Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
    5138              :             }
    5139            0 :             Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
    5140              :             Err(TimelineExclusionError::AlreadyCreating) => {
    5141              :                 // Creation is in progress, we cannot create it again, and we cannot
    5142              :                 // check if this request matches the existing one, so caller must try
    5143              :                 // again later.
    5144            0 :                 Err(CreateTimelineError::AlreadyCreating)
    5145              :             }
    5146            0 :             Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
    5147              :             Err(TimelineExclusionError::AlreadyExists {
    5148            0 :                 existing: TimelineOrOffloaded::Offloaded(_existing),
    5149              :                 ..
    5150              :             }) => {
    5151            0 :                 info!("timeline already exists but is offloaded");
    5152            0 :                 Err(CreateTimelineError::Conflict)
    5153              :             }
    5154              :             Err(TimelineExclusionError::AlreadyExists {
    5155            0 :                 existing: TimelineOrOffloaded::Importing(_existing),
    5156              :                 ..
    5157              :             }) => {
    5158              :                 // If there's a timeline already importing, then we would hit
    5159              :                 // the [`TimelineExclusionError::AlreadyCreating`] branch above.
    5160            0 :                 unreachable!("Importing timelines hold the creation guard")
    5161              :             }
    5162              :             Err(TimelineExclusionError::AlreadyExists {
    5163            1 :                 existing: TimelineOrOffloaded::Timeline(existing),
    5164            1 :                 arg,
    5165              :             }) => {
    5166              :                 {
    5167            1 :                     let existing = &existing.create_idempotency;
    5168            1 :                     let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
    5169            1 :                     debug!("timeline already exists");
    5170              : 
    5171            1 :                     match (existing, &arg) {
    5172              :                         // FailWithConflict => no idempotency check
    5173              :                         (CreateTimelineIdempotency::FailWithConflict, _)
    5174              :                         | (_, CreateTimelineIdempotency::FailWithConflict) => {
    5175            1 :                             warn!("timeline already exists, failing request");
    5176            1 :                             return Err(CreateTimelineError::Conflict);
    5177              :                         }
    5178              :                         // Idempotent <=> CreateTimelineIdempotency is identical
    5179            0 :                         (x, y) if x == y => {
    5180            0 :                             info!(
    5181            0 :                                 "timeline already exists and idempotency matches, succeeding request"
    5182              :                             );
    5183              :                             // fallthrough
    5184              :                         }
    5185              :                         (_, _) => {
    5186            0 :                             warn!("idempotency conflict, failing request");
    5187            0 :                             return Err(CreateTimelineError::Conflict);
    5188              :                         }
    5189              :                     }
    5190              :                 }
    5191              : 
    5192            0 :                 Ok(StartCreatingTimelineResult::Idempotent(existing))
    5193              :             }
    5194              :         }
    5195          234 :     }
    5196              : 
    5197            0 :     async fn upload_initdb(
    5198            0 :         &self,
    5199            0 :         timelines_path: &Utf8PathBuf,
    5200            0 :         pgdata_path: &Utf8PathBuf,
    5201            0 :         timeline_id: &TimelineId,
    5202            0 :     ) -> anyhow::Result<()> {
    5203            0 :         let temp_path = timelines_path.join(format!(
    5204            0 :             "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
    5205            0 :         ));
    5206              : 
    5207            0 :         scopeguard::defer! {
    5208              :             if let Err(e) = fs::remove_file(&temp_path) {
    5209              :                 error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
    5210              :             }
    5211              :         }
    5212              : 
    5213            0 :         let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
    5214              :         const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
    5215            0 :         if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
    5216            0 :             warn!(
    5217            0 :                 "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
    5218              :             );
    5219            0 :         }
    5220              : 
    5221            0 :         pausable_failpoint!("before-initdb-upload");
    5222              : 
    5223            0 :         backoff::retry(
    5224            0 :             || async {
    5225            0 :                 self::remote_timeline_client::upload_initdb_dir(
    5226            0 :                     &self.remote_storage,
    5227            0 :                     &self.tenant_shard_id.tenant_id,
    5228            0 :                     timeline_id,
    5229            0 :                     pgdata_zstd.try_clone().await?,
    5230            0 :                     tar_zst_size,
    5231            0 :                     &self.cancel,
    5232              :                 )
    5233            0 :                 .await
    5234            0 :             },
    5235              :             |_| false,
    5236              :             3,
    5237              :             u32::MAX,
    5238            0 :             "persist_initdb_tar_zst",
    5239            0 :             &self.cancel,
    5240              :         )
    5241            0 :         .await
    5242            0 :         .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
    5243            0 :         .and_then(|x| x)
    5244            0 :     }
    5245              : 
    5246              :     /// - run initdb to init temporary instance and get bootstrap data
    5247              :     /// - after initialization completes, tar up the temp dir and upload it to S3.
    5248            1 :     async fn bootstrap_timeline(
    5249            1 :         self: &Arc<Self>,
    5250            1 :         timeline_id: TimelineId,
    5251            1 :         pg_version: PgMajorVersion,
    5252            1 :         load_existing_initdb: Option<TimelineId>,
    5253            1 :         ctx: &RequestContext,
    5254            1 :     ) -> Result<CreateTimelineResult, CreateTimelineError> {
    5255            1 :         let timeline_create_guard = match self
    5256            1 :             .start_creating_timeline(
    5257            1 :                 timeline_id,
    5258            1 :                 CreateTimelineIdempotency::Bootstrap { pg_version },
    5259            1 :             )
    5260            1 :             .await?
    5261              :         {
    5262            1 :             StartCreatingTimelineResult::CreateGuard(guard) => guard,
    5263            0 :             StartCreatingTimelineResult::Idempotent(timeline) => {
    5264            0 :                 return Ok(CreateTimelineResult::Idempotent(timeline));
    5265              :             }
    5266              :         };
    5267              : 
    5268              :         // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
    5269              :         // temporary directory for basebackup files for the given timeline.
    5270              : 
    5271            1 :         let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
    5272            1 :         let pgdata_path = path_with_suffix_extension(
    5273            1 :             timelines_path.join(format!("basebackup-{timeline_id}")),
    5274            1 :             TEMP_FILE_SUFFIX,
    5275              :         );
    5276              : 
    5277              :         // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
    5278              :         // we won't race with other creations or existent timelines with the same path.
    5279            1 :         if pgdata_path.exists() {
    5280            0 :             fs::remove_dir_all(&pgdata_path).with_context(|| {
    5281            0 :                 format!("Failed to remove already existing initdb directory: {pgdata_path}")
    5282            0 :             })?;
    5283            0 :             tracing::info!("removed previous attempt's temporary initdb directory '{pgdata_path}'");
    5284            1 :         }
    5285              : 
    5286              :         // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
    5287            1 :         let pgdata_path_deferred = pgdata_path.clone();
    5288            1 :         scopeguard::defer! {
    5289              :             if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred).or_else(fs_ext::ignore_not_found) {
    5290              :                 // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
    5291              :                 error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
    5292              :             } else {
    5293              :                 tracing::info!("removed temporary initdb directory '{pgdata_path_deferred}'");
    5294              :             }
    5295              :         }
    5296            1 :         if let Some(existing_initdb_timeline_id) = load_existing_initdb {
    5297            1 :             if existing_initdb_timeline_id != timeline_id {
    5298            0 :                 let source_path = &remote_initdb_archive_path(
    5299            0 :                     &self.tenant_shard_id.tenant_id,
    5300            0 :                     &existing_initdb_timeline_id,
    5301            0 :                 );
    5302            0 :                 let dest_path =
    5303            0 :                     &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
    5304              : 
    5305              :                 // if this fails, it will get retried by retried control plane requests
    5306            0 :                 self.remote_storage
    5307            0 :                     .copy_object(source_path, dest_path, &self.cancel)
    5308            0 :                     .await
    5309            0 :                     .context("copy initdb tar")?;
    5310            1 :             }
    5311            1 :             let (initdb_tar_zst_path, initdb_tar_zst) =
    5312            1 :                 self::remote_timeline_client::download_initdb_tar_zst(
    5313            1 :                     self.conf,
    5314            1 :                     &self.remote_storage,
    5315            1 :                     &self.tenant_shard_id,
    5316            1 :                     &existing_initdb_timeline_id,
    5317            1 :                     &self.cancel,
    5318            1 :                 )
    5319            1 :                 .await
    5320            1 :                 .context("download initdb tar")?;
    5321              : 
    5322            1 :             scopeguard::defer! {
    5323              :                 if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
    5324              :                     error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
    5325              :                 }
    5326              :             }
    5327              : 
    5328            1 :             let buf_read =
    5329            1 :                 BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
    5330            1 :             extract_zst_tarball(&pgdata_path, buf_read)
    5331            1 :                 .await
    5332            1 :                 .context("extract initdb tar")?;
    5333              :         } else {
    5334              :             // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
    5335            0 :             run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
    5336            0 :                 .await
    5337            0 :                 .context("run initdb")?;
    5338              : 
    5339              :             // Upload the created data dir to S3
    5340            0 :             if self.tenant_shard_id().is_shard_zero() {
    5341            0 :                 self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
    5342            0 :                     .await?;
    5343            0 :             }
    5344              :         }
    5345            1 :         let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
    5346              : 
    5347              :         // Import the contents of the data directory at the initial checkpoint
    5348              :         // LSN, and any WAL after that.
    5349              :         // Initdb lsn will be equal to last_record_lsn which will be set after import.
    5350              :         // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
    5351            1 :         let new_metadata = TimelineMetadata::new(
    5352            1 :             Lsn(0),
    5353            1 :             None,
    5354            1 :             None,
    5355            1 :             Lsn(0),
    5356            1 :             pgdata_lsn,
    5357            1 :             pgdata_lsn,
    5358            1 :             pg_version,
    5359              :         );
    5360            1 :         let (mut raw_timeline, timeline_ctx) = self
    5361            1 :             .prepare_new_timeline(
    5362            1 :                 timeline_id,
    5363            1 :                 &new_metadata,
    5364            1 :                 timeline_create_guard,
    5365            1 :                 pgdata_lsn,
    5366            1 :                 None,
    5367            1 :                 None,
    5368            1 :                 ctx,
    5369            1 :             )
    5370            1 :             .await?;
    5371              : 
    5372            1 :         let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
    5373            1 :         raw_timeline
    5374            1 :             .write(|unfinished_timeline| async move {
    5375            1 :                 import_datadir::import_timeline_from_postgres_datadir(
    5376            1 :                     &unfinished_timeline,
    5377            1 :                     &pgdata_path,
    5378            1 :                     pgdata_lsn,
    5379            1 :                     &timeline_ctx,
    5380            1 :                 )
    5381            1 :                 .await
    5382            1 :                 .with_context(|| {
    5383            0 :                     format!(
    5384            0 :                         "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
    5385              :                     )
    5386            0 :                 })?;
    5387              : 
    5388            1 :                 fail::fail_point!("before-checkpoint-new-timeline", |_| {
    5389            0 :                     Err(CreateTimelineError::Other(anyhow::anyhow!(
    5390            0 :                         "failpoint before-checkpoint-new-timeline"
    5391            0 :                     )))
    5392            0 :                 });
    5393              : 
    5394            1 :                 Ok(())
    5395            2 :             })
    5396            1 :             .await?;
    5397              : 
    5398              :         // All done!
    5399            1 :         let timeline = raw_timeline.finish_creation().await?;
    5400              : 
    5401              :         // Callers are responsible to wait for uploads to complete and for activating the timeline.
    5402              : 
    5403            1 :         Ok(CreateTimelineResult::Created(timeline))
    5404            1 :     }
    5405              : 
    5406          231 :     fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
    5407          231 :         RemoteTimelineClient::new(
    5408          231 :             self.remote_storage.clone(),
    5409          231 :             self.deletion_queue_client.clone(),
    5410          231 :             self.conf,
    5411          231 :             self.tenant_shard_id,
    5412          231 :             timeline_id,
    5413          231 :             self.generation,
    5414          231 :             &self.tenant_conf.load().location,
    5415              :         )
    5416          231 :     }
    5417              : 
    5418              :     /// Builds required resources for a new timeline.
    5419          231 :     fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
    5420          231 :         let remote_client = self.build_timeline_remote_client(timeline_id);
    5421          231 :         self.get_timeline_resources_for(remote_client)
    5422          231 :     }
    5423              : 
    5424              :     /// Builds timeline resources for the given remote client.
    5425          234 :     fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
    5426          234 :         TimelineResources {
    5427          234 :             remote_client,
    5428          234 :             pagestream_throttle: self.pagestream_throttle.clone(),
    5429          234 :             pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
    5430          234 :             l0_compaction_trigger: self.l0_compaction_trigger.clone(),
    5431          234 :             l0_flush_global_state: self.l0_flush_global_state.clone(),
    5432          234 :             basebackup_cache: self.basebackup_cache.clone(),
    5433          234 :             feature_resolver: self.feature_resolver.clone(),
    5434          234 :         }
    5435          234 :     }
    5436              : 
    5437              :     /// Creates intermediate timeline structure and its files.
    5438              :     ///
    5439              :     /// An empty layer map is initialized, and new data and WAL can be imported starting
    5440              :     /// at 'disk_consistent_lsn'. After any initial data has been imported, call
    5441              :     /// `finish_creation` to insert the Timeline into the timelines map.
    5442              :     #[allow(clippy::too_many_arguments)]
    5443          231 :     async fn prepare_new_timeline<'a>(
    5444          231 :         &'a self,
    5445          231 :         new_timeline_id: TimelineId,
    5446          231 :         new_metadata: &TimelineMetadata,
    5447          231 :         create_guard: TimelineCreateGuard,
    5448          231 :         start_lsn: Lsn,
    5449          231 :         ancestor: Option<Arc<Timeline>>,
    5450          231 :         rel_size_v2_status: Option<RelSizeMigration>,
    5451          231 :         ctx: &RequestContext,
    5452          231 :     ) -> anyhow::Result<(UninitializedTimeline<'a>, RequestContext)> {
    5453          231 :         let tenant_shard_id = self.tenant_shard_id;
    5454              : 
    5455          231 :         let resources = self.build_timeline_resources(new_timeline_id);
    5456          231 :         resources
    5457          231 :             .remote_client
    5458          231 :             .init_upload_queue_for_empty_remote(new_metadata, rel_size_v2_status.clone())?;
    5459              : 
    5460          231 :         let (timeline_struct, timeline_ctx) = self
    5461          231 :             .create_timeline_struct(
    5462          231 :                 new_timeline_id,
    5463          231 :                 new_metadata,
    5464          231 :                 None,
    5465          231 :                 ancestor,
    5466          231 :                 resources,
    5467          231 :                 CreateTimelineCause::Load,
    5468          231 :                 create_guard.idempotency.clone(),
    5469          231 :                 None,
    5470          231 :                 rel_size_v2_status,
    5471          231 :                 ctx,
    5472              :             )
    5473          231 :             .context("Failed to create timeline data structure")?;
    5474              : 
    5475          231 :         timeline_struct.init_empty_layer_map(start_lsn);
    5476              : 
    5477          231 :         if let Err(e) = self
    5478          231 :             .create_timeline_files(&create_guard.timeline_path)
    5479          231 :             .await
    5480              :         {
    5481            0 :             error!(
    5482            0 :                 "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
    5483              :             );
    5484            0 :             cleanup_timeline_directory(create_guard);
    5485            0 :             return Err(e);
    5486          231 :         }
    5487              : 
    5488          231 :         debug!(
    5489            0 :             "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
    5490              :         );
    5491              : 
    5492          231 :         Ok((
    5493          231 :             UninitializedTimeline::new(
    5494          231 :                 self,
    5495          231 :                 new_timeline_id,
    5496          231 :                 Some((timeline_struct, create_guard)),
    5497          231 :             ),
    5498          231 :             timeline_ctx,
    5499          231 :         ))
    5500          231 :     }
    5501              : 
    5502          231 :     async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
    5503          231 :         crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
    5504              : 
    5505          231 :         fail::fail_point!("after-timeline-dir-creation", |_| {
    5506            0 :             anyhow::bail!("failpoint after-timeline-dir-creation");
    5507            0 :         });
    5508              : 
    5509          231 :         Ok(())
    5510          231 :     }
    5511              : 
    5512              :     /// Get a guard that provides exclusive access to the timeline directory, preventing
    5513              :     /// concurrent attempts to create the same timeline.
    5514              :     ///
    5515              :     /// The `allow_offloaded` parameter controls whether to tolerate the existence of
    5516              :     /// offloaded timelines or not.
    5517          234 :     fn create_timeline_create_guard(
    5518          234 :         self: &Arc<Self>,
    5519          234 :         timeline_id: TimelineId,
    5520          234 :         idempotency: CreateTimelineIdempotency,
    5521          234 :         allow_offloaded: bool,
    5522          234 :     ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
    5523          234 :         let tenant_shard_id = self.tenant_shard_id;
    5524              : 
    5525          234 :         let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
    5526              : 
    5527          234 :         let create_guard = TimelineCreateGuard::new(
    5528          234 :             self,
    5529          234 :             timeline_id,
    5530          234 :             timeline_path.clone(),
    5531          234 :             idempotency,
    5532          234 :             allow_offloaded,
    5533            1 :         )?;
    5534              : 
    5535              :         // At this stage, we have got exclusive access to in-memory state for this timeline ID
    5536              :         // for creation.
    5537              :         // A timeline directory should never exist on disk already:
    5538              :         // - a previous failed creation would have cleaned up after itself
    5539              :         // - a pageserver restart would clean up timeline directories that don't have valid remote state
    5540              :         //
    5541              :         // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
    5542              :         // this error may indicate a bug in cleanup on failed creations.
    5543          233 :         if timeline_path.exists() {
    5544            0 :             return Err(TimelineExclusionError::Other(anyhow::anyhow!(
    5545            0 :                 "Timeline directory already exists! This is a bug."
    5546            0 :             )));
    5547          233 :         }
    5548              : 
    5549          233 :         Ok(create_guard)
    5550          234 :     }
    5551              : 
    5552              :     /// Gathers inputs from all of the timelines to produce a sizing model input.
    5553              :     ///
    5554              :     /// Future is cancellation safe. Only one calculation can be running at once per tenant.
    5555              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5556              :     pub async fn gather_size_inputs(
    5557              :         &self,
    5558              :         // `max_retention_period` overrides the cutoff that is used to calculate the size
    5559              :         // (only if it is shorter than the real cutoff).
    5560              :         max_retention_period: Option<u64>,
    5561              :         cause: LogicalSizeCalculationCause,
    5562              :         cancel: &CancellationToken,
    5563              :         ctx: &RequestContext,
    5564              :     ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
    5565              :         let logical_sizes_at_once = self
    5566              :             .conf
    5567              :             .concurrent_tenant_size_logical_size_queries
    5568              :             .inner();
    5569              : 
    5570              :         // TODO: Having a single mutex block concurrent reads is not great for performance.
    5571              :         //
    5572              :         // But the only case where we need to run multiple of these at once is when we
    5573              :         // request a size for a tenant manually via API, while another background calculation
    5574              :         // is in progress (which is not a common case).
    5575              :         //
    5576              :         // See more for on the issue #2748 condenced out of the initial PR review.
    5577              :         let mut shared_cache = tokio::select! {
    5578              :             locked = self.cached_logical_sizes.lock() => locked,
    5579              :             _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5580              :             _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
    5581              :         };
    5582              : 
    5583              :         size::gather_inputs(
    5584              :             self,
    5585              :             logical_sizes_at_once,
    5586              :             max_retention_period,
    5587              :             &mut shared_cache,
    5588              :             cause,
    5589              :             cancel,
    5590              :             ctx,
    5591              :         )
    5592              :         .await
    5593              :     }
    5594              : 
    5595              :     /// Calculate synthetic tenant size and cache the result.
    5596              :     /// This is periodically called by background worker.
    5597              :     /// result is cached in tenant struct
    5598              :     #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    5599              :     pub async fn calculate_synthetic_size(
    5600              :         &self,
    5601              :         cause: LogicalSizeCalculationCause,
    5602              :         cancel: &CancellationToken,
    5603              :         ctx: &RequestContext,
    5604              :     ) -> Result<u64, size::CalculateSyntheticSizeError> {
    5605              :         let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
    5606              : 
    5607              :         let size = inputs.calculate();
    5608              : 
    5609              :         self.set_cached_synthetic_size(size);
    5610              : 
    5611              :         Ok(size)
    5612              :     }
    5613              : 
    5614              :     /// Cache given synthetic size and update the metric value
    5615            0 :     pub fn set_cached_synthetic_size(&self, size: u64) {
    5616            0 :         self.cached_synthetic_tenant_size
    5617            0 :             .store(size, Ordering::Relaxed);
    5618              : 
    5619              :         // Only shard zero should be calculating synthetic sizes
    5620            0 :         debug_assert!(self.shard_identity.is_shard_zero());
    5621              : 
    5622            0 :         TENANT_SYNTHETIC_SIZE_METRIC
    5623            0 :             .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
    5624            0 :             .unwrap()
    5625            0 :             .set(size);
    5626            0 :     }
    5627              : 
    5628            0 :     pub fn cached_synthetic_size(&self) -> u64 {
    5629            0 :         self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
    5630            0 :     }
    5631              : 
    5632              :     /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
    5633              :     ///
    5634              :     /// This function can take a long time: callers should wrap it in a timeout if calling
    5635              :     /// from an external API handler.
    5636              :     ///
    5637              :     /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
    5638              :     /// still bounded by tenant/timeline shutdown.
    5639              :     #[tracing::instrument(skip_all)]
    5640              :     pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
    5641              :         let timelines = self.timelines.lock().unwrap().clone();
    5642              : 
    5643            0 :         async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
    5644            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
    5645            0 :             timeline.freeze_and_flush().await?;
    5646            0 :             tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
    5647            0 :             timeline.remote_client.wait_completion().await?;
    5648              : 
    5649            0 :             Ok(())
    5650            0 :         }
    5651              : 
    5652              :         // We do not use a JoinSet for these tasks, because we don't want them to be
    5653              :         // aborted when this function's future is cancelled: they should stay alive
    5654              :         // holding their GateGuard until they complete, to ensure their I/Os complete
    5655              :         // before Timeline shutdown completes.
    5656              :         let mut results = FuturesUnordered::new();
    5657              : 
    5658              :         for (_timeline_id, timeline) in timelines {
    5659              :             // Run each timeline's flush in a task holding the timeline's gate: this
    5660              :             // means that if this function's future is cancelled, the Timeline shutdown
    5661              :             // will still wait for any I/O in here to complete.
    5662              :             let Ok(gate) = timeline.gate.enter() else {
    5663              :                 continue;
    5664              :             };
    5665            0 :             let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
    5666              :             results.push(jh);
    5667              :         }
    5668              : 
    5669              :         while let Some(r) = results.next().await {
    5670              :             if let Err(e) = r {
    5671              :                 if !e.is_cancelled() && !e.is_panic() {
    5672              :                     tracing::error!("unexpected join error: {e:?}");
    5673              :                 }
    5674              :             }
    5675              :         }
    5676              : 
    5677              :         // The flushes we did above were just writes, but the TenantShard might have had
    5678              :         // pending deletions as well from recent compaction/gc: we want to flush those
    5679              :         // as well.  This requires flushing the global delete queue.  This is cheap
    5680              :         // because it's typically a no-op.
    5681              :         match self.deletion_queue_client.flush_execute().await {
    5682              :             Ok(_) => {}
    5683              :             Err(DeletionQueueError::ShuttingDown) => {}
    5684              :         }
    5685              : 
    5686              :         Ok(())
    5687              :     }
    5688              : 
    5689            0 :     pub(crate) fn get_tenant_conf(&self) -> pageserver_api::models::TenantConfig {
    5690            0 :         self.tenant_conf.load().tenant_conf.clone()
    5691            0 :     }
    5692              : 
    5693              :     /// How much local storage would this tenant like to have?  It can cope with
    5694              :     /// less than this (via eviction and on-demand downloads), but this function enables
    5695              :     /// the TenantShard to advertise how much storage it would prefer to have to provide fast I/O
    5696              :     /// by keeping important things on local disk.
    5697              :     ///
    5698              :     /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
    5699              :     /// than they report here, due to layer eviction.  Tenants with many active branches may
    5700              :     /// actually use more than they report here.
    5701            0 :     pub(crate) fn local_storage_wanted(&self) -> u64 {
    5702            0 :         let timelines = self.timelines.lock().unwrap();
    5703              : 
    5704              :         // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum.  This
    5705              :         // reflects the observation that on tenants with multiple large branches, typically only one
    5706              :         // of them is used actively enough to occupy space on disk.
    5707            0 :         timelines
    5708            0 :             .values()
    5709            0 :             .map(|t| t.metrics.visible_physical_size_gauge.get())
    5710            0 :             .max()
    5711            0 :             .unwrap_or(0)
    5712            0 :     }
    5713              : 
    5714              :     /// Builds a new tenant manifest, and uploads it if it differs from the last-known tenant
    5715              :     /// manifest in `Self::remote_tenant_manifest`.
    5716              :     ///
    5717              :     /// TODO: instead of requiring callers to remember to call `maybe_upload_tenant_manifest` after
    5718              :     /// changing any `TenantShard` state that's included in the manifest, consider making the manifest
    5719              :     /// the authoritative source of data with an API that automatically uploads on changes. Revisit
    5720              :     /// this when the manifest is more widely used and we have a better idea of the data model.
    5721          119 :     pub(crate) async fn maybe_upload_tenant_manifest(&self) -> Result<(), TenantManifestError> {
    5722              :         // Multiple tasks may call this function concurrently after mutating the TenantShard runtime
    5723              :         // state, affecting the manifest generated by `build_tenant_manifest`. We use an async mutex
    5724              :         // to serialize these callers. `eq_ignoring_version` acts as a slightly inefficient but
    5725              :         // simple coalescing mechanism.
    5726          119 :         let mut guard = tokio::select! {
    5727          119 :             guard = self.remote_tenant_manifest.lock() => guard,
    5728          119 :             _ = self.cancel.cancelled() => return Err(TenantManifestError::Cancelled),
    5729              :         };
    5730              : 
    5731              :         // Build a new manifest.
    5732          119 :         let manifest = self.build_tenant_manifest();
    5733              : 
    5734              :         // Check if the manifest has changed. We ignore the version number here, to avoid
    5735              :         // uploading every manifest on version number bumps.
    5736          119 :         if let Some(old) = guard.as_ref() {
    5737            4 :             if manifest.eq_ignoring_version(old) {
    5738            3 :                 return Ok(());
    5739            1 :             }
    5740          115 :         }
    5741              : 
    5742              :         // Update metrics
    5743          116 :         let tid = self.tenant_shard_id.to_string();
    5744          116 :         let shard_id = self.tenant_shard_id.shard_slug().to_string();
    5745          116 :         let set_key = &[tid.as_str(), shard_id.as_str()][..];
    5746          116 :         TENANT_OFFLOADED_TIMELINES
    5747          116 :             .with_label_values(set_key)
    5748          116 :             .set(manifest.offloaded_timelines.len() as u64);
    5749              : 
    5750              :         // Upload the manifest. Remote storage does no retries internally, so retry here.
    5751          116 :         match backoff::retry(
    5752          116 :             || async {
    5753          116 :                 upload_tenant_manifest(
    5754          116 :                     &self.remote_storage,
    5755          116 :                     &self.tenant_shard_id,
    5756          116 :                     self.generation,
    5757          116 :                     &manifest,
    5758          116 :                     &self.cancel,
    5759          116 :                 )
    5760          116 :                 .await
    5761          232 :             },
    5762            0 :             |_| self.cancel.is_cancelled(),
    5763              :             FAILED_UPLOAD_WARN_THRESHOLD,
    5764              :             FAILED_REMOTE_OP_RETRIES,
    5765          116 :             "uploading tenant manifest",
    5766          116 :             &self.cancel,
    5767              :         )
    5768          116 :         .await
    5769              :         {
    5770            0 :             None => Err(TenantManifestError::Cancelled),
    5771            0 :             Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
    5772            0 :             Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
    5773              :             Some(Ok(_)) => {
    5774              :                 // Store the successfully uploaded manifest, so that future callers can avoid
    5775              :                 // re-uploading the same thing.
    5776          116 :                 *guard = Some(manifest);
    5777              : 
    5778          116 :                 Ok(())
    5779              :             }
    5780              :         }
    5781          119 :     }
    5782              : }
    5783              : 
    5784              : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
    5785              : /// to get bootstrap data for timeline initialization.
    5786            0 : async fn run_initdb(
    5787            0 :     conf: &'static PageServerConf,
    5788            0 :     initdb_target_dir: &Utf8Path,
    5789            0 :     pg_version: PgMajorVersion,
    5790            0 :     cancel: &CancellationToken,
    5791            0 : ) -> Result<(), InitdbError> {
    5792            0 :     let initdb_bin_path = conf
    5793            0 :         .pg_bin_dir(pg_version)
    5794            0 :         .map_err(InitdbError::Other)?
    5795            0 :         .join("initdb");
    5796            0 :     let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
    5797            0 :     info!(
    5798            0 :         "running {} in {}, libdir: {}",
    5799              :         initdb_bin_path, initdb_target_dir, initdb_lib_dir,
    5800              :     );
    5801              : 
    5802            0 :     let _permit = {
    5803            0 :         let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
    5804            0 :         INIT_DB_SEMAPHORE.acquire().await
    5805              :     };
    5806              : 
    5807            0 :     CONCURRENT_INITDBS.inc();
    5808            0 :     scopeguard::defer! {
    5809              :         CONCURRENT_INITDBS.dec();
    5810              :     }
    5811              : 
    5812            0 :     let _timer = INITDB_RUN_TIME.start_timer();
    5813            0 :     let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
    5814            0 :         superuser: &conf.superuser,
    5815            0 :         locale: &conf.locale,
    5816            0 :         initdb_bin: &initdb_bin_path,
    5817            0 :         pg_version,
    5818            0 :         library_search_path: &initdb_lib_dir,
    5819            0 :         pgdata: initdb_target_dir,
    5820            0 :     })
    5821            0 :     .await
    5822            0 :     .map_err(InitdbError::Inner);
    5823              : 
    5824              :     // This isn't true cancellation support, see above. Still return an error to
    5825              :     // excercise the cancellation code path.
    5826            0 :     if cancel.is_cancelled() {
    5827            0 :         return Err(InitdbError::Cancelled);
    5828            0 :     }
    5829              : 
    5830            0 :     res
    5831            0 : }
    5832              : 
    5833              : /// Dump contents of a layer file to stdout.
    5834            0 : pub async fn dump_layerfile_from_path(
    5835            0 :     path: &Utf8Path,
    5836            0 :     verbose: bool,
    5837            0 :     ctx: &RequestContext,
    5838            0 : ) -> anyhow::Result<()> {
    5839              :     use std::os::unix::fs::FileExt;
    5840              : 
    5841              :     // All layer files start with a two-byte "magic" value, to identify the kind of
    5842              :     // file.
    5843            0 :     let file = File::open(path)?;
    5844            0 :     let mut header_buf = [0u8; 2];
    5845            0 :     file.read_exact_at(&mut header_buf, 0)?;
    5846              : 
    5847            0 :     match u16::from_be_bytes(header_buf) {
    5848              :         crate::IMAGE_FILE_MAGIC => {
    5849            0 :             ImageLayer::new_for_path(path, file)?
    5850            0 :                 .dump(verbose, ctx)
    5851            0 :                 .await?
    5852              :         }
    5853              :         crate::DELTA_FILE_MAGIC => {
    5854            0 :             DeltaLayer::new_for_path(path, file)?
    5855            0 :                 .dump(verbose, ctx)
    5856            0 :                 .await?
    5857              :         }
    5858            0 :         magic => bail!("unrecognized magic identifier: {:?}", magic),
    5859              :     }
    5860              : 
    5861            0 :     Ok(())
    5862            0 : }
    5863              : 
    5864              : #[cfg(test)]
    5865              : pub(crate) mod harness {
    5866              :     use bytes::{Bytes, BytesMut};
    5867              :     use hex_literal::hex;
    5868              :     use once_cell::sync::OnceCell;
    5869              :     use pageserver_api::key::Key;
    5870              :     use pageserver_api::models::ShardParameters;
    5871              :     use pageserver_api::shard::ShardIndex;
    5872              :     use utils::id::TenantId;
    5873              :     use utils::logging;
    5874              :     use wal_decoder::models::record::NeonWalRecord;
    5875              : 
    5876              :     use super::*;
    5877              :     use crate::deletion_queue::mock::MockDeletionQueue;
    5878              :     use crate::l0_flush::L0FlushConfig;
    5879              :     use crate::walredo::apply_neon;
    5880              : 
    5881              :     pub const TIMELINE_ID: TimelineId =
    5882              :         TimelineId::from_array(hex!("11223344556677881122334455667788"));
    5883              :     pub const NEW_TIMELINE_ID: TimelineId =
    5884              :         TimelineId::from_array(hex!("AA223344556677881122334455667788"));
    5885              : 
    5886              :     /// Convenience function to create a page image with given string as the only content
    5887      2514347 :     pub fn test_img(s: &str) -> Bytes {
    5888      2514347 :         let mut buf = BytesMut::new();
    5889      2514347 :         buf.extend_from_slice(s.as_bytes());
    5890      2514347 :         buf.resize(64, 0);
    5891              : 
    5892      2514347 :         buf.freeze()
    5893      2514347 :     }
    5894              : 
    5895              :     pub struct TenantHarness {
    5896              :         pub conf: &'static PageServerConf,
    5897              :         pub tenant_conf: pageserver_api::models::TenantConfig,
    5898              :         pub tenant_shard_id: TenantShardId,
    5899              :         pub shard_identity: ShardIdentity,
    5900              :         pub generation: Generation,
    5901              :         pub shard: ShardIndex,
    5902              :         pub remote_storage: GenericRemoteStorage,
    5903              :         pub remote_fs_dir: Utf8PathBuf,
    5904              :         pub deletion_queue: MockDeletionQueue,
    5905              :     }
    5906              : 
    5907              :     static LOG_HANDLE: OnceCell<()> = OnceCell::new();
    5908              : 
    5909          130 :     pub(crate) fn setup_logging() {
    5910          130 :         LOG_HANDLE.get_or_init(|| {
    5911          124 :             logging::init(
    5912          124 :                 logging::LogFormat::Test,
    5913              :                 // enable it in case the tests exercise code paths that use
    5914              :                 // debug_assert_current_span_has_tenant_and_timeline_id
    5915          124 :                 logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
    5916          124 :                 logging::Output::Stdout,
    5917              :             )
    5918          124 :             .expect("Failed to init test logging");
    5919          124 :         });
    5920          130 :     }
    5921              : 
    5922              :     impl TenantHarness {
    5923          118 :         pub async fn create_custom(
    5924          118 :             test_name: &'static str,
    5925          118 :             tenant_conf: pageserver_api::models::TenantConfig,
    5926          118 :             tenant_id: TenantId,
    5927          118 :             shard_identity: ShardIdentity,
    5928          118 :             generation: Generation,
    5929          118 :         ) -> anyhow::Result<Self> {
    5930          118 :             setup_logging();
    5931              : 
    5932          118 :             let repo_dir = PageServerConf::test_repo_dir(test_name);
    5933          118 :             let _ = fs::remove_dir_all(&repo_dir);
    5934          118 :             fs::create_dir_all(&repo_dir)?;
    5935              : 
    5936          118 :             let conf = PageServerConf::dummy_conf(repo_dir);
    5937              :             // Make a static copy of the config. This can never be free'd, but that's
    5938              :             // OK in a test.
    5939          118 :             let conf: &'static PageServerConf = Box::leak(Box::new(conf));
    5940              : 
    5941          118 :             let shard = shard_identity.shard_index();
    5942          118 :             let tenant_shard_id = TenantShardId {
    5943          118 :                 tenant_id,
    5944          118 :                 shard_number: shard.shard_number,
    5945          118 :                 shard_count: shard.shard_count,
    5946          118 :             };
    5947          118 :             fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
    5948          118 :             fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
    5949              : 
    5950              :             use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
    5951          118 :             let remote_fs_dir = conf.workdir.join("localfs");
    5952          118 :             std::fs::create_dir_all(&remote_fs_dir).unwrap();
    5953          118 :             let config = RemoteStorageConfig {
    5954          118 :                 storage: RemoteStorageKind::LocalFs {
    5955          118 :                     local_path: remote_fs_dir.clone(),
    5956          118 :                 },
    5957          118 :                 timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
    5958          118 :                 small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
    5959          118 :             };
    5960          118 :             let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
    5961          118 :             let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
    5962              : 
    5963          118 :             Ok(Self {
    5964          118 :                 conf,
    5965          118 :                 tenant_conf,
    5966          118 :                 tenant_shard_id,
    5967          118 :                 shard_identity,
    5968          118 :                 generation,
    5969          118 :                 shard,
    5970          118 :                 remote_storage,
    5971          118 :                 remote_fs_dir,
    5972          118 :                 deletion_queue,
    5973          118 :             })
    5974          118 :         }
    5975              : 
    5976          110 :         pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
    5977              :             // Disable automatic GC and compaction to make the unit tests more deterministic.
    5978              :             // The tests perform them manually if needed.
    5979          110 :             let tenant_conf = pageserver_api::models::TenantConfig {
    5980          110 :                 gc_period: Some(Duration::ZERO),
    5981          110 :                 compaction_period: Some(Duration::ZERO),
    5982          110 :                 ..Default::default()
    5983          110 :             };
    5984          110 :             let tenant_id = TenantId::generate();
    5985          110 :             let shard = ShardIdentity::unsharded();
    5986          110 :             Self::create_custom(
    5987          110 :                 test_name,
    5988          110 :                 tenant_conf,
    5989          110 :                 tenant_id,
    5990          110 :                 shard,
    5991          110 :                 Generation::new(0xdeadbeef),
    5992          110 :             )
    5993          110 :             .await
    5994          110 :         }
    5995              : 
    5996           10 :         pub fn span(&self) -> tracing::Span {
    5997           10 :             info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
    5998           10 :         }
    5999              : 
    6000          118 :         pub(crate) async fn load(&self) -> (Arc<TenantShard>, RequestContext) {
    6001          118 :             let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error)
    6002          118 :                 .with_scope_unit_test();
    6003              :             (
    6004          118 :                 self.do_try_load(&ctx)
    6005          118 :                     .await
    6006          118 :                     .expect("failed to load test tenant"),
    6007          118 :                 ctx,
    6008              :             )
    6009          118 :         }
    6010              : 
    6011              :         #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
    6012              :         pub(crate) async fn do_try_load(
    6013              :             &self,
    6014              :             ctx: &RequestContext,
    6015              :         ) -> anyhow::Result<Arc<TenantShard>> {
    6016              :             let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
    6017              : 
    6018              :             let (basebackup_cache, _) = BasebackupCache::new(Utf8PathBuf::new(), None);
    6019              : 
    6020              :             let tenant = Arc::new(TenantShard::new(
    6021              :                 TenantState::Attaching,
    6022              :                 self.conf,
    6023              :                 AttachedTenantConf::try_from(LocationConf::attached_single(
    6024              :                     self.tenant_conf.clone(),
    6025              :                     self.generation,
    6026              :                     ShardParameters::default(),
    6027              :                 ))
    6028              :                 .unwrap(),
    6029              :                 self.shard_identity,
    6030              :                 Some(walredo_mgr),
    6031              :                 self.tenant_shard_id,
    6032              :                 self.remote_storage.clone(),
    6033              :                 self.deletion_queue.new_client(),
    6034              :                 // TODO: ideally we should run all unit tests with both configs
    6035              :                 L0FlushGlobalState::new(L0FlushConfig::default()),
    6036              :                 basebackup_cache,
    6037              :                 FeatureResolver::new_disabled(),
    6038              :             ));
    6039              : 
    6040              :             let preload = tenant
    6041              :                 .preload(&self.remote_storage, CancellationToken::new())
    6042              :                 .await?;
    6043              :             tenant.attach(Some(preload), ctx).await?;
    6044              : 
    6045              :             tenant.state.send_replace(TenantState::Active);
    6046              :             for timeline in tenant.timelines.lock().unwrap().values() {
    6047              :                 timeline.set_state(TimelineState::Active);
    6048              :             }
    6049              :             Ok(tenant)
    6050              :         }
    6051              : 
    6052            1 :         pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
    6053            1 :             self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
    6054            1 :         }
    6055              :     }
    6056              : 
    6057              :     // Mock WAL redo manager that doesn't do much
    6058              :     pub(crate) struct TestRedoManager;
    6059              : 
    6060              :     impl TestRedoManager {
    6061              :         /// # Cancel-Safety
    6062              :         ///
    6063              :         /// This method is cancellation-safe.
    6064        26774 :         pub async fn request_redo(
    6065        26774 :             &self,
    6066        26774 :             key: Key,
    6067        26774 :             lsn: Lsn,
    6068        26774 :             base_img: Option<(Lsn, Bytes)>,
    6069        26774 :             records: Vec<(Lsn, NeonWalRecord)>,
    6070        26774 :             _pg_version: PgMajorVersion,
    6071        26774 :             _redo_attempt_type: RedoAttemptType,
    6072        26774 :         ) -> Result<Bytes, walredo::Error> {
    6073      1403510 :             let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
    6074        26774 :             if records_neon {
    6075              :                 // For Neon wal records, we can decode without spawning postgres, so do so.
    6076        26774 :                 let mut page = match (base_img, records.first()) {
    6077        13029 :                     (Some((_lsn, img)), _) => {
    6078        13029 :                         let mut page = BytesMut::new();
    6079        13029 :                         page.extend_from_slice(&img);
    6080        13029 :                         page
    6081              :                     }
    6082        13745 :                     (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
    6083              :                     _ => {
    6084            0 :                         panic!("Neon WAL redo requires base image or will init record");
    6085              :                     }
    6086              :                 };
    6087              : 
    6088      1430283 :                 for (record_lsn, record) in records {
    6089      1403510 :                     apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
    6090              :                 }
    6091        26773 :                 Ok(page.freeze())
    6092              :             } else {
    6093              :                 // We never spawn a postgres walredo process in unit tests: just log what we might have done.
    6094            0 :                 let s = format!(
    6095            0 :                     "redo for {} to get to {}, with {} and {} records",
    6096              :                     key,
    6097              :                     lsn,
    6098            0 :                     if base_img.is_some() {
    6099            0 :                         "base image"
    6100              :                     } else {
    6101            0 :                         "no base image"
    6102              :                     },
    6103            0 :                     records.len()
    6104              :                 );
    6105            0 :                 println!("{s}");
    6106              : 
    6107            0 :                 Ok(test_img(&s))
    6108              :             }
    6109        26774 :         }
    6110              :     }
    6111              : }
    6112              : 
    6113              : #[cfg(test)]
    6114              : mod tests {
    6115              :     use std::collections::{BTreeMap, BTreeSet};
    6116              : 
    6117              :     use bytes::{Bytes, BytesMut};
    6118              :     use hex_literal::hex;
    6119              :     use itertools::Itertools;
    6120              :     #[cfg(feature = "testing")]
    6121              :     use models::CompactLsnRange;
    6122              :     use pageserver_api::key::{
    6123              :         AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX, repl_origin_key,
    6124              :     };
    6125              :     use pageserver_api::keyspace::KeySpace;
    6126              :     #[cfg(feature = "testing")]
    6127              :     use pageserver_api::keyspace::KeySpaceRandomAccum;
    6128              :     use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
    6129              :     use pageserver_compaction::helpers::overlaps_with;
    6130              :     #[cfg(feature = "testing")]
    6131              :     use rand::SeedableRng;
    6132              :     #[cfg(feature = "testing")]
    6133              :     use rand::rngs::StdRng;
    6134              :     use rand::{Rng, thread_rng};
    6135              :     #[cfg(feature = "testing")]
    6136              :     use std::ops::Range;
    6137              :     use storage_layer::{IoConcurrency, PersistentLayerKey};
    6138              :     use tests::storage_layer::ValuesReconstructState;
    6139              :     use tests::timeline::{GetVectoredError, ShutdownMode};
    6140              :     #[cfg(feature = "testing")]
    6141              :     use timeline::GcInfo;
    6142              :     #[cfg(feature = "testing")]
    6143              :     use timeline::InMemoryLayerTestDesc;
    6144              :     #[cfg(feature = "testing")]
    6145              :     use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
    6146              :     use timeline::{CompactOptions, DeltaLayerTestDesc, VersionedKeySpaceQuery};
    6147              :     use utils::id::TenantId;
    6148              :     use utils::shard::{ShardCount, ShardNumber};
    6149              :     #[cfg(feature = "testing")]
    6150              :     use wal_decoder::models::record::NeonWalRecord;
    6151              :     use wal_decoder::models::value::Value;
    6152              : 
    6153              :     use super::*;
    6154              :     use crate::DEFAULT_PG_VERSION;
    6155              :     use crate::keyspace::KeySpaceAccum;
    6156              :     use crate::tenant::harness::*;
    6157              :     use crate::tenant::timeline::CompactFlags;
    6158              : 
    6159              :     static TEST_KEY: Lazy<Key> =
    6160           10 :         Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
    6161              : 
    6162              :     #[cfg(feature = "testing")]
    6163              :     struct TestTimelineSpecification {
    6164              :         start_lsn: Lsn,
    6165              :         last_record_lsn: Lsn,
    6166              : 
    6167              :         in_memory_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    6168              :         delta_layers_shape: Vec<(Range<Key>, Range<Lsn>)>,
    6169              :         image_layers_shape: Vec<(Range<Key>, Lsn)>,
    6170              : 
    6171              :         gap_chance: u8,
    6172              :         will_init_chance: u8,
    6173              :     }
    6174              : 
    6175              :     #[cfg(feature = "testing")]
    6176              :     struct Storage {
    6177              :         storage: HashMap<(Key, Lsn), Value>,
    6178              :         start_lsn: Lsn,
    6179              :     }
    6180              : 
    6181              :     #[cfg(feature = "testing")]
    6182              :     impl Storage {
    6183        32000 :         fn get(&self, key: Key, lsn: Lsn) -> Bytes {
    6184              :             use bytes::BufMut;
    6185              : 
    6186        32000 :             let mut crnt_lsn = lsn;
    6187        32000 :             let mut got_base = false;
    6188              : 
    6189        32000 :             let mut acc = Vec::new();
    6190              : 
    6191      2831871 :             while crnt_lsn >= self.start_lsn {
    6192      2831871 :                 if let Some(value) = self.storage.get(&(key, crnt_lsn)) {
    6193      1421172 :                     acc.push(value.clone());
    6194              : 
    6195      1402881 :                     match value {
    6196      1402881 :                         Value::WalRecord(NeonWalRecord::Test { will_init, .. }) => {
    6197      1402881 :                             if *will_init {
    6198        13709 :                                 got_base = true;
    6199        13709 :                                 break;
    6200      1389172 :                             }
    6201              :                         }
    6202              :                         Value::Image(_) => {
    6203        18291 :                             got_base = true;
    6204        18291 :                             break;
    6205              :                         }
    6206            0 :                         _ => unreachable!(),
    6207              :                     }
    6208      1410699 :                 }
    6209              : 
    6210      2799871 :                 crnt_lsn = crnt_lsn.checked_sub(1u64).unwrap();
    6211              :             }
    6212              : 
    6213        32000 :             assert!(
    6214        32000 :                 got_base,
    6215            0 :                 "Input data was incorrect. No base image for {key}@{lsn}"
    6216              :             );
    6217              : 
    6218        32000 :             tracing::debug!("Wal redo depth for {key}@{lsn} is {}", acc.len());
    6219              : 
    6220        32000 :             let mut blob = BytesMut::new();
    6221      1421172 :             for value in acc.into_iter().rev() {
    6222      1402881 :                 match value {
    6223      1402881 :                     Value::WalRecord(NeonWalRecord::Test { append, .. }) => {
    6224      1402881 :                         blob.extend_from_slice(append.as_bytes());
    6225      1402881 :                     }
    6226        18291 :                     Value::Image(img) => {
    6227        18291 :                         blob.put(img);
    6228        18291 :                     }
    6229            0 :                     _ => unreachable!(),
    6230              :                 }
    6231              :             }
    6232              : 
    6233        32000 :             blob.into()
    6234        32000 :         }
    6235              :     }
    6236              : 
    6237              :     #[cfg(feature = "testing")]
    6238              :     #[allow(clippy::too_many_arguments)]
    6239            1 :     async fn randomize_timeline(
    6240            1 :         tenant: &Arc<TenantShard>,
    6241            1 :         new_timeline_id: TimelineId,
    6242            1 :         pg_version: PgMajorVersion,
    6243            1 :         spec: TestTimelineSpecification,
    6244            1 :         random: &mut rand::rngs::StdRng,
    6245            1 :         ctx: &RequestContext,
    6246            1 :     ) -> anyhow::Result<(Arc<Timeline>, Storage, Vec<Lsn>)> {
    6247            1 :         let mut storage: HashMap<(Key, Lsn), Value> = HashMap::default();
    6248            1 :         let mut interesting_lsns = vec![spec.last_record_lsn];
    6249              : 
    6250            2 :         for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6251            2 :             let mut lsn = lsn_range.start;
    6252          202 :             while lsn < lsn_range.end {
    6253          200 :                 let mut key = key_range.start;
    6254        21018 :                 while key < key_range.end {
    6255        20818 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6256        20818 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6257              : 
    6258        20818 :                     if gap {
    6259         1018 :                         continue;
    6260        19800 :                     }
    6261              : 
    6262        19800 :                     let record = if will_init {
    6263          191 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6264              :                     } else {
    6265        19609 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6266              :                     };
    6267              : 
    6268        19800 :                     storage.insert((key, lsn), record);
    6269              : 
    6270        19800 :                     key = key.next();
    6271              :                 }
    6272          200 :                 lsn = Lsn(lsn.0 + 1);
    6273              :             }
    6274              : 
    6275              :             // Stash some interesting LSN for future use
    6276            6 :             for offset in [0, 5, 100].iter() {
    6277            6 :                 if *offset == 0 {
    6278            2 :                     interesting_lsns.push(lsn_range.start);
    6279            2 :                 } else {
    6280            4 :                     let below = lsn_range.start.checked_sub(*offset);
    6281            4 :                     match below {
    6282            4 :                         Some(v) if v >= spec.start_lsn => {
    6283            4 :                             interesting_lsns.push(v);
    6284            4 :                         }
    6285            0 :                         _ => {}
    6286              :                     }
    6287              : 
    6288            4 :                     let above = Lsn(lsn_range.start.0 + offset);
    6289            4 :                     interesting_lsns.push(above);
    6290              :                 }
    6291              :             }
    6292              :         }
    6293              : 
    6294            3 :         for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6295            3 :             let mut lsn = lsn_range.start;
    6296          315 :             while lsn < lsn_range.end {
    6297          312 :                 let mut key = key_range.start;
    6298        11112 :                 while key < key_range.end {
    6299        10800 :                     let gap = random.gen_range(1..=100) <= spec.gap_chance;
    6300        10800 :                     let will_init = random.gen_range(1..=100) <= spec.will_init_chance;
    6301              : 
    6302        10800 :                     if gap {
    6303          504 :                         continue;
    6304        10296 :                     }
    6305              : 
    6306        10296 :                     let record = if will_init {
    6307          103 :                         Value::WalRecord(NeonWalRecord::wal_init(format!("[wil_init {key}@{lsn}]")))
    6308              :                     } else {
    6309        10193 :                         Value::WalRecord(NeonWalRecord::wal_append(format!("[delta {key}@{lsn}]")))
    6310              :                     };
    6311              : 
    6312        10296 :                     storage.insert((key, lsn), record);
    6313              : 
    6314        10296 :                     key = key.next();
    6315              :                 }
    6316          312 :                 lsn = Lsn(lsn.0 + 1);
    6317              :             }
    6318              : 
    6319              :             // Stash some interesting LSN for future use
    6320            9 :             for offset in [0, 5, 100].iter() {
    6321            9 :                 if *offset == 0 {
    6322            3 :                     interesting_lsns.push(lsn_range.start);
    6323            3 :                 } else {
    6324            6 :                     let below = lsn_range.start.checked_sub(*offset);
    6325            6 :                     match below {
    6326            6 :                         Some(v) if v >= spec.start_lsn => {
    6327            3 :                             interesting_lsns.push(v);
    6328            3 :                         }
    6329            3 :                         _ => {}
    6330              :                     }
    6331              : 
    6332            6 :                     let above = Lsn(lsn_range.start.0 + offset);
    6333            6 :                     interesting_lsns.push(above);
    6334              :                 }
    6335              :             }
    6336              :         }
    6337              : 
    6338            3 :         for (key_range, lsn) in spec.image_layers_shape.iter() {
    6339            3 :             let mut key = key_range.start;
    6340          142 :             while key < key_range.end {
    6341          139 :                 let blob = Bytes::from(format!("[image {key}@{lsn}]"));
    6342          139 :                 let record = Value::Image(blob.clone());
    6343          139 :                 storage.insert((key, *lsn), record);
    6344          139 : 
    6345          139 :                 key = key.next();
    6346          139 :             }
    6347              : 
    6348              :             // Stash some interesting LSN for future use
    6349            9 :             for offset in [0, 5, 100].iter() {
    6350            9 :                 if *offset == 0 {
    6351            3 :                     interesting_lsns.push(*lsn);
    6352            3 :                 } else {
    6353            6 :                     let below = lsn.checked_sub(*offset);
    6354            6 :                     match below {
    6355            6 :                         Some(v) if v >= spec.start_lsn => {
    6356            4 :                             interesting_lsns.push(v);
    6357            4 :                         }
    6358            2 :                         _ => {}
    6359              :                     }
    6360              : 
    6361            6 :                     let above = Lsn(lsn.0 + offset);
    6362            6 :                     interesting_lsns.push(above);
    6363              :                 }
    6364              :             }
    6365              :         }
    6366              : 
    6367            1 :         let in_memory_test_layers = {
    6368            1 :             let mut acc = Vec::new();
    6369              : 
    6370            2 :             for (key_range, lsn_range) in spec.in_memory_layers_shape.iter() {
    6371            2 :                 let mut data = Vec::new();
    6372              : 
    6373            2 :                 let mut lsn = lsn_range.start;
    6374          202 :                 while lsn < lsn_range.end {
    6375          200 :                     let mut key = key_range.start;
    6376        20000 :                     while key < key_range.end {
    6377        19800 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6378        19800 :                             data.push((key, lsn, record.clone()));
    6379        19800 :                         }
    6380              : 
    6381        19800 :                         key = key.next();
    6382              :                     }
    6383          200 :                     lsn = Lsn(lsn.0 + 1);
    6384              :                 }
    6385              : 
    6386            2 :                 acc.push(InMemoryLayerTestDesc {
    6387            2 :                     data,
    6388            2 :                     lsn_range: lsn_range.clone(),
    6389            2 :                     is_open: false,
    6390            2 :                 })
    6391              :             }
    6392              : 
    6393            1 :             acc
    6394              :         };
    6395              : 
    6396            1 :         let delta_test_layers = {
    6397            1 :             let mut acc = Vec::new();
    6398              : 
    6399            3 :             for (key_range, lsn_range) in spec.delta_layers_shape.iter() {
    6400            3 :                 let mut data = Vec::new();
    6401              : 
    6402            3 :                 let mut lsn = lsn_range.start;
    6403          315 :                 while lsn < lsn_range.end {
    6404          312 :                     let mut key = key_range.start;
    6405        10608 :                     while key < key_range.end {
    6406        10296 :                         if let Some(record) = storage.get(&(key, lsn)) {
    6407        10296 :                             data.push((key, lsn, record.clone()));
    6408        10296 :                         }
    6409              : 
    6410        10296 :                         key = key.next();
    6411              :                     }
    6412          312 :                     lsn = Lsn(lsn.0 + 1);
    6413              :                 }
    6414              : 
    6415            3 :                 acc.push(DeltaLayerTestDesc {
    6416            3 :                     data,
    6417            3 :                     lsn_range: lsn_range.clone(),
    6418            3 :                     key_range: key_range.clone(),
    6419            3 :                 })
    6420              :             }
    6421              : 
    6422            1 :             acc
    6423              :         };
    6424              : 
    6425            1 :         let image_test_layers = {
    6426            1 :             let mut acc = Vec::new();
    6427              : 
    6428            3 :             for (key_range, lsn) in spec.image_layers_shape.iter() {
    6429            3 :                 let mut data = Vec::new();
    6430              : 
    6431            3 :                 let mut key = key_range.start;
    6432          142 :                 while key < key_range.end {
    6433          139 :                     if let Some(record) = storage.get(&(key, *lsn)) {
    6434          139 :                         let blob = match record {
    6435          139 :                             Value::Image(blob) => blob.clone(),
    6436            0 :                             _ => unreachable!(),
    6437              :                         };
    6438              : 
    6439          139 :                         data.push((key, blob));
    6440            0 :                     }
    6441              : 
    6442          139 :                     key = key.next();
    6443              :                 }
    6444              : 
    6445            3 :                 acc.push((*lsn, data));
    6446              :             }
    6447              : 
    6448            1 :             acc
    6449              :         };
    6450              : 
    6451            1 :         let tline = tenant
    6452            1 :             .create_test_timeline_with_layers(
    6453            1 :                 new_timeline_id,
    6454            1 :                 spec.start_lsn,
    6455            1 :                 pg_version,
    6456            1 :                 ctx,
    6457            1 :                 in_memory_test_layers,
    6458            1 :                 delta_test_layers,
    6459            1 :                 image_test_layers,
    6460            1 :                 spec.last_record_lsn,
    6461            1 :             )
    6462            1 :             .await?;
    6463              : 
    6464            1 :         Ok((
    6465            1 :             tline,
    6466            1 :             Storage {
    6467            1 :                 storage,
    6468            1 :                 start_lsn: spec.start_lsn,
    6469            1 :             },
    6470            1 :             interesting_lsns,
    6471            1 :         ))
    6472            1 :     }
    6473              : 
    6474              :     #[tokio::test]
    6475            1 :     async fn test_basic() -> anyhow::Result<()> {
    6476            1 :         let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
    6477            1 :         let tline = tenant
    6478            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    6479            1 :             .await?;
    6480              : 
    6481            1 :         let mut writer = tline.writer().await;
    6482            1 :         writer
    6483            1 :             .put(
    6484            1 :                 *TEST_KEY,
    6485            1 :                 Lsn(0x10),
    6486            1 :                 &Value::Image(test_img("foo at 0x10")),
    6487            1 :                 &ctx,
    6488            1 :             )
    6489            1 :             .await?;
    6490            1 :         writer.finish_write(Lsn(0x10));
    6491            1 :         drop(writer);
    6492              : 
    6493            1 :         let mut writer = tline.writer().await;
    6494            1 :         writer
    6495            1 :             .put(
    6496            1 :                 *TEST_KEY,
    6497            1 :                 Lsn(0x20),
    6498            1 :                 &Value::Image(test_img("foo at 0x20")),
    6499            1 :                 &ctx,
    6500            1 :             )
    6501            1 :             .await?;
    6502            1 :         writer.finish_write(Lsn(0x20));
    6503            1 :         drop(writer);
    6504              : 
    6505            1 :         assert_eq!(
    6506            1 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    6507            1 :             test_img("foo at 0x10")
    6508              :         );
    6509            1 :         assert_eq!(
    6510            1 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    6511            1 :             test_img("foo at 0x10")
    6512              :         );
    6513            1 :         assert_eq!(
    6514            1 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    6515            1 :             test_img("foo at 0x20")
    6516              :         );
    6517              : 
    6518            2 :         Ok(())
    6519            1 :     }
    6520              : 
    6521              :     #[tokio::test]
    6522            1 :     async fn no_duplicate_timelines() -> anyhow::Result<()> {
    6523            1 :         let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
    6524            1 :             .await?
    6525            1 :             .load()
    6526            1 :             .await;
    6527            1 :         let _ = tenant
    6528            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6529            1 :             .await?;
    6530              : 
    6531            1 :         match tenant
    6532            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6533            1 :             .await
    6534            1 :         {
    6535            1 :             Ok(_) => panic!("duplicate timeline creation should fail"),
    6536            1 :             Err(e) => assert_eq!(
    6537            1 :                 e.to_string(),
    6538            1 :                 "timeline already exists with different parameters".to_string()
    6539            1 :             ),
    6540            1 :         }
    6541            1 : 
    6542            1 :         Ok(())
    6543            1 :     }
    6544              : 
    6545              :     /// Convenience function to create a page image with given string as the only content
    6546            5 :     pub fn test_value(s: &str) -> Value {
    6547            5 :         let mut buf = BytesMut::new();
    6548            5 :         buf.extend_from_slice(s.as_bytes());
    6549            5 :         Value::Image(buf.freeze())
    6550            5 :     }
    6551              : 
    6552              :     ///
    6553              :     /// Test branch creation
    6554              :     ///
    6555              :     #[tokio::test]
    6556            1 :     async fn test_branch() -> anyhow::Result<()> {
    6557              :         use std::str::from_utf8;
    6558              : 
    6559            1 :         let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
    6560            1 :         let tline = tenant
    6561            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6562            1 :             .await?;
    6563            1 :         let mut writer = tline.writer().await;
    6564              : 
    6565              :         #[allow(non_snake_case)]
    6566            1 :         let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
    6567              :         #[allow(non_snake_case)]
    6568            1 :         let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
    6569              : 
    6570              :         // Insert a value on the timeline
    6571            1 :         writer
    6572            1 :             .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
    6573            1 :             .await?;
    6574            1 :         writer
    6575            1 :             .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
    6576            1 :             .await?;
    6577            1 :         writer.finish_write(Lsn(0x20));
    6578              : 
    6579            1 :         writer
    6580            1 :             .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
    6581            1 :             .await?;
    6582            1 :         writer.finish_write(Lsn(0x30));
    6583            1 :         writer
    6584            1 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
    6585            1 :             .await?;
    6586            1 :         writer.finish_write(Lsn(0x40));
    6587              : 
    6588              :         //assert_current_logical_size(&tline, Lsn(0x40));
    6589              : 
    6590              :         // Branch the history, modify relation differently on the new timeline
    6591            1 :         tenant
    6592            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
    6593            1 :             .await?;
    6594            1 :         let newtline = tenant
    6595            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6596            1 :             .expect("Should have a local timeline");
    6597            1 :         let mut new_writer = newtline.writer().await;
    6598            1 :         new_writer
    6599            1 :             .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
    6600            1 :             .await?;
    6601            1 :         new_writer.finish_write(Lsn(0x40));
    6602              : 
    6603              :         // Check page contents on both branches
    6604            1 :         assert_eq!(
    6605            1 :             from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6606              :             "foo at 0x40"
    6607              :         );
    6608            1 :         assert_eq!(
    6609            1 :             from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
    6610              :             "bar at 0x40"
    6611              :         );
    6612            1 :         assert_eq!(
    6613            1 :             from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
    6614              :             "foobar at 0x20"
    6615              :         );
    6616              : 
    6617              :         //assert_current_logical_size(&tline, Lsn(0x40));
    6618              : 
    6619            2 :         Ok(())
    6620            1 :     }
    6621              : 
    6622           10 :     async fn make_some_layers(
    6623           10 :         tline: &Timeline,
    6624           10 :         start_lsn: Lsn,
    6625           10 :         ctx: &RequestContext,
    6626           10 :     ) -> anyhow::Result<()> {
    6627           10 :         let mut lsn = start_lsn;
    6628              :         {
    6629           10 :             let mut writer = tline.writer().await;
    6630              :             // Create a relation on the timeline
    6631           10 :             writer
    6632           10 :                 .put(
    6633           10 :                     *TEST_KEY,
    6634           10 :                     lsn,
    6635           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6636           10 :                     ctx,
    6637           10 :                 )
    6638           10 :                 .await?;
    6639           10 :             writer.finish_write(lsn);
    6640           10 :             lsn += 0x10;
    6641           10 :             writer
    6642           10 :                 .put(
    6643           10 :                     *TEST_KEY,
    6644           10 :                     lsn,
    6645           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6646           10 :                     ctx,
    6647           10 :                 )
    6648           10 :                 .await?;
    6649           10 :             writer.finish_write(lsn);
    6650           10 :             lsn += 0x10;
    6651              :         }
    6652           10 :         tline.freeze_and_flush().await?;
    6653              :         {
    6654           10 :             let mut writer = tline.writer().await;
    6655           10 :             writer
    6656           10 :                 .put(
    6657           10 :                     *TEST_KEY,
    6658           10 :                     lsn,
    6659           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6660           10 :                     ctx,
    6661           10 :                 )
    6662           10 :                 .await?;
    6663           10 :             writer.finish_write(lsn);
    6664           10 :             lsn += 0x10;
    6665           10 :             writer
    6666           10 :                 .put(
    6667           10 :                     *TEST_KEY,
    6668           10 :                     lsn,
    6669           10 :                     &Value::Image(test_img(&format!("foo at {lsn}"))),
    6670           10 :                     ctx,
    6671           10 :                 )
    6672           10 :                 .await?;
    6673           10 :             writer.finish_write(lsn);
    6674              :         }
    6675           10 :         tline.freeze_and_flush().await.map_err(|e| e.into())
    6676           10 :     }
    6677              : 
    6678              :     #[tokio::test(start_paused = true)]
    6679            1 :     async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
    6680            1 :         let (tenant, ctx) =
    6681            1 :             TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
    6682            1 :                 .await?
    6683            1 :                 .load()
    6684            1 :                 .await;
    6685              :         // Advance to the lsn lease deadline so that GC is not blocked by
    6686              :         // initial transition into AttachedSingle.
    6687            1 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    6688            1 :         tokio::time::resume();
    6689            1 :         let tline = tenant
    6690            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6691            1 :             .await?;
    6692            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6693              : 
    6694              :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6695              :         // FIXME: this doesn't actually remove any layer currently, given how the flushing
    6696              :         // and compaction works. But it does set the 'cutoff' point so that the cross check
    6697              :         // below should fail.
    6698            1 :         tenant
    6699            1 :             .gc_iteration(
    6700            1 :                 Some(TIMELINE_ID),
    6701            1 :                 0x10,
    6702            1 :                 Duration::ZERO,
    6703            1 :                 &CancellationToken::new(),
    6704            1 :                 &ctx,
    6705            1 :             )
    6706            1 :             .await?;
    6707              : 
    6708              :         // try to branch at lsn 25, should fail because we already garbage collected the data
    6709            1 :         match tenant
    6710            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6711            1 :             .await
    6712            1 :         {
    6713            1 :             Ok(_) => panic!("branching should have failed"),
    6714            1 :             Err(err) => {
    6715            1 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6716            1 :                     panic!("wrong error type")
    6717            1 :                 };
    6718            1 :                 assert!(err.to_string().contains("invalid branch start lsn"));
    6719            1 :                 assert!(
    6720            1 :                     err.source()
    6721            1 :                         .unwrap()
    6722            1 :                         .to_string()
    6723            1 :                         .contains("we might've already garbage collected needed data")
    6724            1 :                 )
    6725            1 :             }
    6726            1 :         }
    6727            1 : 
    6728            1 :         Ok(())
    6729            1 :     }
    6730              : 
    6731              :     #[tokio::test]
    6732            1 :     async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
    6733            1 :         let (tenant, ctx) =
    6734            1 :             TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
    6735            1 :                 .await?
    6736            1 :                 .load()
    6737            1 :                 .await;
    6738              : 
    6739            1 :         let tline = tenant
    6740            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
    6741            1 :             .await?;
    6742              :         // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
    6743            1 :         match tenant
    6744            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
    6745            1 :             .await
    6746            1 :         {
    6747            1 :             Ok(_) => panic!("branching should have failed"),
    6748            1 :             Err(err) => {
    6749            1 :                 let CreateTimelineError::AncestorLsn(err) = err else {
    6750            1 :                     panic!("wrong error type");
    6751            1 :                 };
    6752            1 :                 assert!(&err.to_string().contains("invalid branch start lsn"));
    6753            1 :                 assert!(
    6754            1 :                     &err.source()
    6755            1 :                         .unwrap()
    6756            1 :                         .to_string()
    6757            1 :                         .contains("is earlier than latest GC cutoff")
    6758            1 :                 );
    6759            1 :             }
    6760            1 :         }
    6761            1 : 
    6762            1 :         Ok(())
    6763            1 :     }
    6764              : 
    6765              :     /*
    6766              :     // FIXME: This currently fails to error out. Calling GC doesn't currently
    6767              :     // remove the old value, we'd need to work a little harder
    6768              :     #[tokio::test]
    6769              :     async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
    6770              :         let repo =
    6771              :             RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
    6772              :             .load();
    6773              : 
    6774              :         let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
    6775              :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6776              : 
    6777              :         repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
    6778              :         let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
    6779              :         assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
    6780              :         match tline.get(*TEST_KEY, Lsn(0x25)) {
    6781              :             Ok(_) => panic!("request for page should have failed"),
    6782              :             Err(err) => assert!(err.to_string().contains("not found at")),
    6783              :         }
    6784              :         Ok(())
    6785              :     }
    6786              :      */
    6787              : 
    6788              :     #[tokio::test]
    6789            1 :     async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
    6790            1 :         let (tenant, ctx) =
    6791            1 :             TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
    6792            1 :                 .await?
    6793            1 :                 .load()
    6794            1 :                 .await;
    6795            1 :         let tline = tenant
    6796            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6797            1 :             .await?;
    6798            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6799              : 
    6800            1 :         tenant
    6801            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6802            1 :             .await?;
    6803            1 :         let newtline = tenant
    6804            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6805            1 :             .expect("Should have a local timeline");
    6806              : 
    6807            1 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6808              : 
    6809            1 :         tline.set_broken("test".to_owned());
    6810              : 
    6811            1 :         tenant
    6812            1 :             .gc_iteration(
    6813            1 :                 Some(TIMELINE_ID),
    6814            1 :                 0x10,
    6815            1 :                 Duration::ZERO,
    6816            1 :                 &CancellationToken::new(),
    6817            1 :                 &ctx,
    6818            1 :             )
    6819            1 :             .await?;
    6820              : 
    6821              :         // The branchpoints should contain all timelines, even ones marked
    6822              :         // as Broken.
    6823              :         {
    6824            1 :             let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
    6825            1 :             assert_eq!(branchpoints.len(), 1);
    6826            1 :             assert_eq!(
    6827            1 :                 branchpoints[0],
    6828              :                 (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
    6829              :             );
    6830              :         }
    6831              : 
    6832              :         // You can read the key from the child branch even though the parent is
    6833              :         // Broken, as long as you don't need to access data from the parent.
    6834            1 :         assert_eq!(
    6835            1 :             newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
    6836            1 :             test_img(&format!("foo at {}", Lsn(0x70)))
    6837              :         );
    6838              : 
    6839              :         // This needs to traverse to the parent, and fails.
    6840            1 :         let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
    6841            1 :         assert!(
    6842            1 :             err.to_string().starts_with(&format!(
    6843            1 :                 "bad state on timeline {}: Broken",
    6844            1 :                 tline.timeline_id
    6845            1 :             )),
    6846            0 :             "{err}"
    6847              :         );
    6848              : 
    6849            2 :         Ok(())
    6850            1 :     }
    6851              : 
    6852              :     #[tokio::test]
    6853            1 :     async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
    6854            1 :         let (tenant, ctx) =
    6855            1 :             TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
    6856            1 :                 .await?
    6857            1 :                 .load()
    6858            1 :                 .await;
    6859            1 :         let tline = tenant
    6860            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6861            1 :             .await?;
    6862            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6863              : 
    6864            1 :         tenant
    6865            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6866            1 :             .await?;
    6867            1 :         let newtline = tenant
    6868            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6869            1 :             .expect("Should have a local timeline");
    6870              :         // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
    6871            1 :         tenant
    6872            1 :             .gc_iteration(
    6873            1 :                 Some(TIMELINE_ID),
    6874            1 :                 0x10,
    6875            1 :                 Duration::ZERO,
    6876            1 :                 &CancellationToken::new(),
    6877            1 :                 &ctx,
    6878            1 :             )
    6879            1 :             .await?;
    6880            1 :         assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
    6881              : 
    6882            2 :         Ok(())
    6883            1 :     }
    6884              :     #[tokio::test]
    6885            1 :     async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
    6886            1 :         let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
    6887            1 :             .await?
    6888            1 :             .load()
    6889            1 :             .await;
    6890            1 :         let tline = tenant
    6891            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6892            1 :             .await?;
    6893            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6894              : 
    6895            1 :         tenant
    6896            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6897            1 :             .await?;
    6898            1 :         let newtline = tenant
    6899            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6900            1 :             .expect("Should have a local timeline");
    6901              : 
    6902            1 :         make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6903              : 
    6904              :         // run gc on parent
    6905            1 :         tenant
    6906            1 :             .gc_iteration(
    6907            1 :                 Some(TIMELINE_ID),
    6908            1 :                 0x10,
    6909            1 :                 Duration::ZERO,
    6910            1 :                 &CancellationToken::new(),
    6911            1 :                 &ctx,
    6912            1 :             )
    6913            1 :             .await?;
    6914              : 
    6915              :         // Check that the data is still accessible on the branch.
    6916            1 :         assert_eq!(
    6917            1 :             newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
    6918            1 :             test_img(&format!("foo at {}", Lsn(0x40)))
    6919              :         );
    6920              : 
    6921            2 :         Ok(())
    6922            1 :     }
    6923              : 
    6924              :     #[tokio::test]
    6925            1 :     async fn timeline_load() -> anyhow::Result<()> {
    6926              :         const TEST_NAME: &str = "timeline_load";
    6927            1 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6928              :         {
    6929            1 :             let (tenant, ctx) = harness.load().await;
    6930            1 :             let tline = tenant
    6931            1 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
    6932            1 :                 .await?;
    6933            1 :             make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
    6934              :             // so that all uploads finish & we can call harness.load() below again
    6935            1 :             tenant
    6936            1 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6937            1 :                 .instrument(harness.span())
    6938            1 :                 .await
    6939            1 :                 .ok()
    6940            1 :                 .unwrap();
    6941              :         }
    6942              : 
    6943            1 :         let (tenant, _ctx) = harness.load().await;
    6944            1 :         tenant
    6945            1 :             .get_timeline(TIMELINE_ID, true)
    6946            1 :             .expect("cannot load timeline");
    6947              : 
    6948            2 :         Ok(())
    6949            1 :     }
    6950              : 
    6951              :     #[tokio::test]
    6952            1 :     async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
    6953              :         const TEST_NAME: &str = "timeline_load_with_ancestor";
    6954            1 :         let harness = TenantHarness::create(TEST_NAME).await?;
    6955              :         // create two timelines
    6956              :         {
    6957            1 :             let (tenant, ctx) = harness.load().await;
    6958            1 :             let tline = tenant
    6959            1 :                 .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    6960            1 :                 .await?;
    6961              : 
    6962            1 :             make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    6963              : 
    6964            1 :             let child_tline = tenant
    6965            1 :                 .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
    6966            1 :                 .await?;
    6967            1 :             child_tline.set_state(TimelineState::Active);
    6968              : 
    6969            1 :             let newtline = tenant
    6970            1 :                 .get_timeline(NEW_TIMELINE_ID, true)
    6971            1 :                 .expect("Should have a local timeline");
    6972              : 
    6973            1 :             make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
    6974              : 
    6975              :             // so that all uploads finish & we can call harness.load() below again
    6976            1 :             tenant
    6977            1 :                 .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
    6978            1 :                 .instrument(harness.span())
    6979            1 :                 .await
    6980            1 :                 .ok()
    6981            1 :                 .unwrap();
    6982              :         }
    6983              : 
    6984              :         // check that both of them are initially unloaded
    6985            1 :         let (tenant, _ctx) = harness.load().await;
    6986              : 
    6987              :         // check that both, child and ancestor are loaded
    6988            1 :         let _child_tline = tenant
    6989            1 :             .get_timeline(NEW_TIMELINE_ID, true)
    6990            1 :             .expect("cannot get child timeline loaded");
    6991              : 
    6992            1 :         let _ancestor_tline = tenant
    6993            1 :             .get_timeline(TIMELINE_ID, true)
    6994            1 :             .expect("cannot get ancestor timeline loaded");
    6995              : 
    6996            2 :         Ok(())
    6997            1 :     }
    6998              : 
    6999              :     #[tokio::test]
    7000            1 :     async fn delta_layer_dumping() -> anyhow::Result<()> {
    7001              :         use storage_layer::AsLayerDesc;
    7002            1 :         let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
    7003            1 :             .await?
    7004            1 :             .load()
    7005            1 :             .await;
    7006            1 :         let tline = tenant
    7007            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7008            1 :             .await?;
    7009            1 :         make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
    7010              : 
    7011            1 :         let layer_map = tline.layers.read(LayerManagerLockHolder::Testing).await;
    7012            1 :         let level0_deltas = layer_map
    7013            1 :             .layer_map()?
    7014            1 :             .level0_deltas()
    7015            1 :             .iter()
    7016            2 :             .map(|desc| layer_map.get_from_desc(desc))
    7017            1 :             .collect::<Vec<_>>();
    7018              : 
    7019            1 :         assert!(!level0_deltas.is_empty());
    7020              : 
    7021            3 :         for delta in level0_deltas {
    7022            1 :             // Ensure we are dumping a delta layer here
    7023            2 :             assert!(delta.layer_desc().is_delta);
    7024            2 :             delta.dump(true, &ctx).await.unwrap();
    7025            1 :         }
    7026            1 : 
    7027            1 :         Ok(())
    7028            1 :     }
    7029              : 
    7030              :     #[tokio::test]
    7031            1 :     async fn test_images() -> anyhow::Result<()> {
    7032            1 :         let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
    7033            1 :         let tline = tenant
    7034            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7035            1 :             .await?;
    7036              : 
    7037            1 :         let mut writer = tline.writer().await;
    7038            1 :         writer
    7039            1 :             .put(
    7040            1 :                 *TEST_KEY,
    7041            1 :                 Lsn(0x10),
    7042            1 :                 &Value::Image(test_img("foo at 0x10")),
    7043            1 :                 &ctx,
    7044            1 :             )
    7045            1 :             .await?;
    7046            1 :         writer.finish_write(Lsn(0x10));
    7047            1 :         drop(writer);
    7048              : 
    7049            1 :         tline.freeze_and_flush().await?;
    7050            1 :         tline
    7051            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7052            1 :             .await?;
    7053              : 
    7054            1 :         let mut writer = tline.writer().await;
    7055            1 :         writer
    7056            1 :             .put(
    7057            1 :                 *TEST_KEY,
    7058            1 :                 Lsn(0x20),
    7059            1 :                 &Value::Image(test_img("foo at 0x20")),
    7060            1 :                 &ctx,
    7061            1 :             )
    7062            1 :             .await?;
    7063            1 :         writer.finish_write(Lsn(0x20));
    7064            1 :         drop(writer);
    7065              : 
    7066            1 :         tline.freeze_and_flush().await?;
    7067            1 :         tline
    7068            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7069            1 :             .await?;
    7070              : 
    7071            1 :         let mut writer = tline.writer().await;
    7072            1 :         writer
    7073            1 :             .put(
    7074            1 :                 *TEST_KEY,
    7075            1 :                 Lsn(0x30),
    7076            1 :                 &Value::Image(test_img("foo at 0x30")),
    7077            1 :                 &ctx,
    7078            1 :             )
    7079            1 :             .await?;
    7080            1 :         writer.finish_write(Lsn(0x30));
    7081            1 :         drop(writer);
    7082              : 
    7083            1 :         tline.freeze_and_flush().await?;
    7084            1 :         tline
    7085            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7086            1 :             .await?;
    7087              : 
    7088            1 :         let mut writer = tline.writer().await;
    7089            1 :         writer
    7090            1 :             .put(
    7091            1 :                 *TEST_KEY,
    7092            1 :                 Lsn(0x40),
    7093            1 :                 &Value::Image(test_img("foo at 0x40")),
    7094            1 :                 &ctx,
    7095            1 :             )
    7096            1 :             .await?;
    7097            1 :         writer.finish_write(Lsn(0x40));
    7098            1 :         drop(writer);
    7099              : 
    7100            1 :         tline.freeze_and_flush().await?;
    7101            1 :         tline
    7102            1 :             .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
    7103            1 :             .await?;
    7104              : 
    7105            1 :         assert_eq!(
    7106            1 :             tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
    7107            1 :             test_img("foo at 0x10")
    7108              :         );
    7109            1 :         assert_eq!(
    7110            1 :             tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
    7111            1 :             test_img("foo at 0x10")
    7112              :         );
    7113            1 :         assert_eq!(
    7114            1 :             tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
    7115            1 :             test_img("foo at 0x20")
    7116              :         );
    7117            1 :         assert_eq!(
    7118            1 :             tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
    7119            1 :             test_img("foo at 0x30")
    7120              :         );
    7121            1 :         assert_eq!(
    7122            1 :             tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
    7123            1 :             test_img("foo at 0x40")
    7124              :         );
    7125              : 
    7126            2 :         Ok(())
    7127            1 :     }
    7128              : 
    7129            2 :     async fn bulk_insert_compact_gc(
    7130            2 :         tenant: &TenantShard,
    7131            2 :         timeline: &Arc<Timeline>,
    7132            2 :         ctx: &RequestContext,
    7133            2 :         lsn: Lsn,
    7134            2 :         repeat: usize,
    7135            2 :         key_count: usize,
    7136            2 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    7137            2 :         let compact = true;
    7138            2 :         bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
    7139            2 :     }
    7140              : 
    7141            4 :     async fn bulk_insert_maybe_compact_gc(
    7142            4 :         tenant: &TenantShard,
    7143            4 :         timeline: &Arc<Timeline>,
    7144            4 :         ctx: &RequestContext,
    7145            4 :         mut lsn: Lsn,
    7146            4 :         repeat: usize,
    7147            4 :         key_count: usize,
    7148            4 :         compact: bool,
    7149            4 :     ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
    7150            4 :         let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
    7151              : 
    7152            4 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7153            4 :         let mut blknum = 0;
    7154              : 
    7155              :         // Enforce that key range is monotonously increasing
    7156            4 :         let mut keyspace = KeySpaceAccum::new();
    7157              : 
    7158            4 :         let cancel = CancellationToken::new();
    7159              : 
    7160            4 :         for _ in 0..repeat {
    7161          200 :             for _ in 0..key_count {
    7162      2000000 :                 test_key.field6 = blknum;
    7163      2000000 :                 let mut writer = timeline.writer().await;
    7164      2000000 :                 writer
    7165      2000000 :                     .put(
    7166      2000000 :                         test_key,
    7167      2000000 :                         lsn,
    7168      2000000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7169      2000000 :                         ctx,
    7170      2000000 :                     )
    7171      2000000 :                     .await?;
    7172      2000000 :                 inserted.entry(test_key).or_default().insert(lsn);
    7173      2000000 :                 writer.finish_write(lsn);
    7174      2000000 :                 drop(writer);
    7175              : 
    7176      2000000 :                 keyspace.add_key(test_key);
    7177              : 
    7178      2000000 :                 lsn = Lsn(lsn.0 + 0x10);
    7179      2000000 :                 blknum += 1;
    7180              :             }
    7181              : 
    7182          200 :             timeline.freeze_and_flush().await?;
    7183          200 :             if compact {
    7184              :                 // this requires timeline to be &Arc<Timeline>
    7185          100 :                 timeline.compact(&cancel, EnumSet::default(), ctx).await?;
    7186          100 :             }
    7187              : 
    7188              :             // this doesn't really need to use the timeline_id target, but it is closer to what it
    7189              :             // originally was.
    7190          200 :             let res = tenant
    7191          200 :                 .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
    7192          200 :                 .await?;
    7193              : 
    7194          200 :             assert_eq!(res.layers_removed, 0, "this never removes anything");
    7195              :         }
    7196              : 
    7197            4 :         Ok(inserted)
    7198            4 :     }
    7199              : 
    7200              :     //
    7201              :     // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
    7202              :     // Repeat 50 times.
    7203              :     //
    7204              :     #[tokio::test]
    7205            1 :     async fn test_bulk_insert() -> anyhow::Result<()> {
    7206            1 :         let harness = TenantHarness::create("test_bulk_insert").await?;
    7207            1 :         let (tenant, ctx) = harness.load().await;
    7208            1 :         let tline = tenant
    7209            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7210            1 :             .await?;
    7211              : 
    7212            1 :         let lsn = Lsn(0x10);
    7213            1 :         bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7214              : 
    7215            2 :         Ok(())
    7216            1 :     }
    7217              : 
    7218              :     // Test the vectored get real implementation against a simple sequential implementation.
    7219              :     //
    7220              :     // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
    7221              :     // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
    7222              :     // grow to the right on the X axis.
    7223              :     //                       [Delta]
    7224              :     //                 [Delta]
    7225              :     //           [Delta]
    7226              :     //    [Delta]
    7227              :     // ------------ Image ---------------
    7228              :     //
    7229              :     // After layer generation we pick the ranges to query as follows:
    7230              :     // 1. The beginning of each delta layer
    7231              :     // 2. At the seam between two adjacent delta layers
    7232              :     //
    7233              :     // There's one major downside to this test: delta layers only contains images,
    7234              :     // so the search can stop at the first delta layer and doesn't traverse any deeper.
    7235              :     #[tokio::test]
    7236            1 :     async fn test_get_vectored() -> anyhow::Result<()> {
    7237            1 :         let harness = TenantHarness::create("test_get_vectored").await?;
    7238            1 :         let (tenant, ctx) = harness.load().await;
    7239            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7240            1 :         let tline = tenant
    7241            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    7242            1 :             .await?;
    7243              : 
    7244            1 :         let lsn = Lsn(0x10);
    7245            1 :         let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
    7246              : 
    7247            1 :         let guard = tline.layers.read(LayerManagerLockHolder::Testing).await;
    7248            1 :         let lm = guard.layer_map()?;
    7249              : 
    7250            1 :         lm.dump(true, &ctx).await?;
    7251              : 
    7252            1 :         let mut reads = Vec::new();
    7253            1 :         let mut prev = None;
    7254            6 :         lm.iter_historic_layers().for_each(|desc| {
    7255            6 :             if !desc.is_delta() {
    7256            1 :                 prev = Some(desc.clone());
    7257            1 :                 return;
    7258            5 :             }
    7259              : 
    7260            5 :             let start = desc.key_range.start;
    7261            5 :             let end = desc
    7262            5 :                 .key_range
    7263            5 :                 .start
    7264            5 :                 .add(tenant.conf.max_get_vectored_keys.get() as u32);
    7265            5 :             reads.push(KeySpace {
    7266            5 :                 ranges: vec![start..end],
    7267            5 :             });
    7268              : 
    7269            5 :             if let Some(prev) = &prev {
    7270            5 :                 if !prev.is_delta() {
    7271            5 :                     return;
    7272            0 :                 }
    7273              : 
    7274            0 :                 let first_range = Key {
    7275            0 :                     field6: prev.key_range.end.field6 - 4,
    7276            0 :                     ..prev.key_range.end
    7277            0 :                 }..prev.key_range.end;
    7278              : 
    7279            0 :                 let second_range = desc.key_range.start..Key {
    7280            0 :                     field6: desc.key_range.start.field6 + 4,
    7281            0 :                     ..desc.key_range.start
    7282            0 :                 };
    7283              : 
    7284            0 :                 reads.push(KeySpace {
    7285            0 :                     ranges: vec![first_range, second_range],
    7286            0 :                 });
    7287            0 :             };
    7288              : 
    7289            0 :             prev = Some(desc.clone());
    7290            6 :         });
    7291              : 
    7292            1 :         drop(guard);
    7293              : 
    7294              :         // Pick a big LSN such that we query over all the changes.
    7295            1 :         let reads_lsn = Lsn(u64::MAX - 1);
    7296              : 
    7297            6 :         for read in reads {
    7298            5 :             info!("Doing vectored read on {:?}", read);
    7299            1 : 
    7300            5 :             let query = VersionedKeySpaceQuery::uniform(read.clone(), reads_lsn);
    7301            1 : 
    7302            5 :             let vectored_res = tline
    7303            5 :                 .get_vectored_impl(
    7304            5 :                     query,
    7305            5 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7306            5 :                     &ctx,
    7307            5 :                 )
    7308            5 :                 .await;
    7309            1 : 
    7310            5 :             let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
    7311            5 :             let mut expect_missing = false;
    7312            5 :             let mut key = read.start().unwrap();
    7313          165 :             while key != read.end().unwrap() {
    7314          160 :                 if let Some(lsns) = inserted.get(&key) {
    7315          160 :                     let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
    7316          160 :                     match expected_lsn {
    7317          160 :                         Some(lsn) => {
    7318          160 :                             expected_lsns.insert(key, *lsn);
    7319          160 :                         }
    7320            1 :                         None => {
    7321            1 :                             expect_missing = true;
    7322            1 :                             break;
    7323            1 :                         }
    7324            1 :                     }
    7325            1 :                 } else {
    7326            1 :                     expect_missing = true;
    7327            1 :                     break;
    7328            1 :                 }
    7329            1 : 
    7330          160 :                 key = key.next();
    7331            1 :             }
    7332            1 : 
    7333            5 :             if expect_missing {
    7334            1 :                 assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
    7335            1 :             } else {
    7336          160 :                 for (key, image) in vectored_res? {
    7337          160 :                     let expected_lsn = expected_lsns.get(&key).expect("determined above");
    7338          160 :                     let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
    7339          160 :                     assert_eq!(image?, expected_image);
    7340            1 :                 }
    7341            1 :             }
    7342            1 :         }
    7343            1 : 
    7344            1 :         Ok(())
    7345            1 :     }
    7346              : 
    7347              :     #[tokio::test]
    7348            1 :     async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
    7349            1 :         let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
    7350              : 
    7351            1 :         let (tenant, ctx) = harness.load().await;
    7352            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7353            1 :         let (tline, ctx) = tenant
    7354            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    7355            1 :             .await?;
    7356            1 :         let tline = tline.raw_timeline().unwrap();
    7357              : 
    7358            1 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    7359            1 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    7360            1 :         modification.set_lsn(Lsn(0x1008))?;
    7361            1 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    7362            1 :         modification.commit(&ctx).await?;
    7363              : 
    7364            1 :         let child_timeline_id = TimelineId::generate();
    7365            1 :         tenant
    7366            1 :             .branch_timeline_test(
    7367            1 :                 tline,
    7368            1 :                 child_timeline_id,
    7369            1 :                 Some(tline.get_last_record_lsn()),
    7370            1 :                 &ctx,
    7371            1 :             )
    7372            1 :             .await?;
    7373              : 
    7374            1 :         let child_timeline = tenant
    7375            1 :             .get_timeline(child_timeline_id, true)
    7376            1 :             .expect("Should have the branched timeline");
    7377              : 
    7378            1 :         let aux_keyspace = KeySpace {
    7379            1 :             ranges: vec![NON_INHERITED_RANGE],
    7380            1 :         };
    7381            1 :         let read_lsn = child_timeline.get_last_record_lsn();
    7382              : 
    7383            1 :         let query = VersionedKeySpaceQuery::uniform(aux_keyspace.clone(), read_lsn);
    7384              : 
    7385            1 :         let vectored_res = child_timeline
    7386            1 :             .get_vectored_impl(
    7387            1 :                 query,
    7388            1 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7389            1 :                 &ctx,
    7390            1 :             )
    7391            1 :             .await;
    7392              : 
    7393            1 :         let images = vectored_res?;
    7394            1 :         assert!(images.is_empty());
    7395            2 :         Ok(())
    7396            1 :     }
    7397              : 
    7398              :     // Test that vectored get handles layer gaps correctly
    7399              :     // by advancing into the next ancestor timeline if required.
    7400              :     //
    7401              :     // The test generates timelines that look like the diagram below.
    7402              :     // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
    7403              :     // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
    7404              :     //
    7405              :     // ```
    7406              :     //-------------------------------+
    7407              :     //                          ...  |
    7408              :     //               [   L1   ]      |
    7409              :     //     [ / L1   ]                | Child Timeline
    7410              :     // ...                           |
    7411              :     // ------------------------------+
    7412              :     //     [ X L1   ]                | Parent Timeline
    7413              :     // ------------------------------+
    7414              :     // ```
    7415              :     #[tokio::test]
    7416            1 :     async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
    7417            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
    7418            1 :             // Make compaction deterministic
    7419            1 :             gc_period: Some(Duration::ZERO),
    7420            1 :             compaction_period: Some(Duration::ZERO),
    7421            1 :             // Encourage creation of L1 layers
    7422            1 :             checkpoint_distance: Some(16 * 1024),
    7423            1 :             compaction_target_size: Some(8 * 1024),
    7424            1 :             ..Default::default()
    7425            1 :         };
    7426              : 
    7427            1 :         let harness = TenantHarness::create_custom(
    7428            1 :             "test_get_vectored_key_gap",
    7429            1 :             tenant_conf,
    7430            1 :             TenantId::generate(),
    7431            1 :             ShardIdentity::unsharded(),
    7432            1 :             Generation::new(0xdeadbeef),
    7433            1 :         )
    7434            1 :         .await?;
    7435            1 :         let (tenant, ctx) = harness.load().await;
    7436            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7437              : 
    7438            1 :         let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7439            1 :         let gap_at_key = current_key.add(100);
    7440            1 :         let mut current_lsn = Lsn(0x10);
    7441              : 
    7442              :         const KEY_COUNT: usize = 10_000;
    7443              : 
    7444            1 :         let timeline_id = TimelineId::generate();
    7445            1 :         let current_timeline = tenant
    7446            1 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7447            1 :             .await?;
    7448              : 
    7449            1 :         current_lsn += 0x100;
    7450              : 
    7451            1 :         let mut writer = current_timeline.writer().await;
    7452            1 :         writer
    7453            1 :             .put(
    7454            1 :                 gap_at_key,
    7455            1 :                 current_lsn,
    7456            1 :                 &Value::Image(test_img(&format!("{gap_at_key} at {current_lsn}"))),
    7457            1 :                 &ctx,
    7458            1 :             )
    7459            1 :             .await?;
    7460            1 :         writer.finish_write(current_lsn);
    7461            1 :         drop(writer);
    7462              : 
    7463            1 :         let mut latest_lsns = HashMap::new();
    7464            1 :         latest_lsns.insert(gap_at_key, current_lsn);
    7465              : 
    7466            1 :         current_timeline.freeze_and_flush().await?;
    7467              : 
    7468            1 :         let child_timeline_id = TimelineId::generate();
    7469              : 
    7470            1 :         tenant
    7471            1 :             .branch_timeline_test(
    7472            1 :                 &current_timeline,
    7473            1 :                 child_timeline_id,
    7474            1 :                 Some(current_lsn),
    7475            1 :                 &ctx,
    7476            1 :             )
    7477            1 :             .await?;
    7478            1 :         let child_timeline = tenant
    7479            1 :             .get_timeline(child_timeline_id, true)
    7480            1 :             .expect("Should have the branched timeline");
    7481              : 
    7482        10001 :         for i in 0..KEY_COUNT {
    7483        10000 :             if current_key == gap_at_key {
    7484            1 :                 current_key = current_key.next();
    7485            1 :                 continue;
    7486         9999 :             }
    7487              : 
    7488         9999 :             current_lsn += 0x10;
    7489              : 
    7490         9999 :             let mut writer = child_timeline.writer().await;
    7491         9999 :             writer
    7492         9999 :                 .put(
    7493         9999 :                     current_key,
    7494         9999 :                     current_lsn,
    7495         9999 :                     &Value::Image(test_img(&format!("{current_key} at {current_lsn}"))),
    7496         9999 :                     &ctx,
    7497         9999 :                 )
    7498         9999 :                 .await?;
    7499         9999 :             writer.finish_write(current_lsn);
    7500         9999 :             drop(writer);
    7501              : 
    7502         9999 :             latest_lsns.insert(current_key, current_lsn);
    7503         9999 :             current_key = current_key.next();
    7504              : 
    7505              :             // Flush every now and then to encourage layer file creation.
    7506         9999 :             if i % 500 == 0 {
    7507           20 :                 child_timeline.freeze_and_flush().await?;
    7508         9979 :             }
    7509              :         }
    7510              : 
    7511            1 :         child_timeline.freeze_and_flush().await?;
    7512            1 :         let mut flags = EnumSet::new();
    7513            1 :         flags.insert(CompactFlags::ForceRepartition);
    7514            1 :         child_timeline
    7515            1 :             .compact(&CancellationToken::new(), flags, &ctx)
    7516            1 :             .await?;
    7517              : 
    7518            1 :         let key_near_end = {
    7519            1 :             let mut tmp = current_key;
    7520            1 :             tmp.field6 -= 10;
    7521            1 :             tmp
    7522              :         };
    7523              : 
    7524            1 :         let key_near_gap = {
    7525            1 :             let mut tmp = gap_at_key;
    7526            1 :             tmp.field6 -= 10;
    7527            1 :             tmp
    7528              :         };
    7529              : 
    7530            1 :         let read = KeySpace {
    7531            1 :             ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
    7532            1 :         };
    7533              : 
    7534            1 :         let query = VersionedKeySpaceQuery::uniform(read.clone(), current_lsn);
    7535              : 
    7536            1 :         let results = child_timeline
    7537            1 :             .get_vectored_impl(
    7538            1 :                 query,
    7539            1 :                 &mut ValuesReconstructState::new(io_concurrency.clone()),
    7540            1 :                 &ctx,
    7541            1 :             )
    7542            1 :             .await?;
    7543              : 
    7544           22 :         for (key, img_res) in results {
    7545           21 :             let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
    7546           21 :             assert_eq!(img_res?, expected);
    7547            1 :         }
    7548            1 : 
    7549            1 :         Ok(())
    7550            1 :     }
    7551              : 
    7552              :     // Test that vectored get descends into ancestor timelines correctly and
    7553              :     // does not return an image that's newer than requested.
    7554              :     //
    7555              :     // The diagram below ilustrates an interesting case. We have a parent timeline
    7556              :     // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
    7557              :     // from the child timeline, so the parent timeline must be visited. When advacing into
    7558              :     // the child timeline, the read path needs to remember what the requested Lsn was in
    7559              :     // order to avoid returning an image that's too new. The test below constructs such
    7560              :     // a timeline setup and does a few queries around the Lsn of each page image.
    7561              :     // ```
    7562              :     //    LSN
    7563              :     //     ^
    7564              :     //     |
    7565              :     //     |
    7566              :     // 500 | --------------------------------------> branch point
    7567              :     // 400 |        X
    7568              :     // 300 |        X
    7569              :     // 200 | --------------------------------------> requested lsn
    7570              :     // 100 |        X
    7571              :     //     |---------------------------------------> Key
    7572              :     //              |
    7573              :     //              ------> requested key
    7574              :     //
    7575              :     // Legend:
    7576              :     // * X - page images
    7577              :     // ```
    7578              :     #[tokio::test]
    7579            1 :     async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
    7580            1 :         let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
    7581            1 :         let (tenant, ctx) = harness.load().await;
    7582            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    7583              : 
    7584            1 :         let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7585            1 :         let end_key = start_key.add(1000);
    7586            1 :         let child_gap_at_key = start_key.add(500);
    7587            1 :         let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
    7588              : 
    7589            1 :         let mut current_lsn = Lsn(0x10);
    7590              : 
    7591            1 :         let timeline_id = TimelineId::generate();
    7592            1 :         let parent_timeline = tenant
    7593            1 :             .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
    7594            1 :             .await?;
    7595              : 
    7596            1 :         current_lsn += 0x100;
    7597              : 
    7598            4 :         for _ in 0..3 {
    7599            3 :             let mut key = start_key;
    7600         3003 :             while key < end_key {
    7601         3000 :                 current_lsn += 0x10;
    7602              : 
    7603         3000 :                 let image_value = format!("{child_gap_at_key} at {current_lsn}");
    7604              : 
    7605         3000 :                 let mut writer = parent_timeline.writer().await;
    7606         3000 :                 writer
    7607         3000 :                     .put(
    7608         3000 :                         key,
    7609         3000 :                         current_lsn,
    7610         3000 :                         &Value::Image(test_img(&image_value)),
    7611         3000 :                         &ctx,
    7612         3000 :                     )
    7613         3000 :                     .await?;
    7614         3000 :                 writer.finish_write(current_lsn);
    7615              : 
    7616         3000 :                 if key == child_gap_at_key {
    7617            3 :                     parent_gap_lsns.insert(current_lsn, image_value);
    7618         2997 :                 }
    7619              : 
    7620         3000 :                 key = key.next();
    7621              :             }
    7622              : 
    7623            3 :             parent_timeline.freeze_and_flush().await?;
    7624              :         }
    7625              : 
    7626            1 :         let child_timeline_id = TimelineId::generate();
    7627              : 
    7628            1 :         let child_timeline = tenant
    7629            1 :             .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
    7630            1 :             .await?;
    7631              : 
    7632            1 :         let mut key = start_key;
    7633         1001 :         while key < end_key {
    7634         1000 :             if key == child_gap_at_key {
    7635            1 :                 key = key.next();
    7636            1 :                 continue;
    7637          999 :             }
    7638              : 
    7639          999 :             current_lsn += 0x10;
    7640              : 
    7641          999 :             let mut writer = child_timeline.writer().await;
    7642          999 :             writer
    7643          999 :                 .put(
    7644          999 :                     key,
    7645          999 :                     current_lsn,
    7646          999 :                     &Value::Image(test_img(&format!("{key} at {current_lsn}"))),
    7647          999 :                     &ctx,
    7648          999 :                 )
    7649          999 :                 .await?;
    7650          999 :             writer.finish_write(current_lsn);
    7651              : 
    7652          999 :             key = key.next();
    7653              :         }
    7654              : 
    7655            1 :         child_timeline.freeze_and_flush().await?;
    7656              : 
    7657            1 :         let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
    7658            1 :         let mut query_lsns = Vec::new();
    7659            3 :         for image_lsn in parent_gap_lsns.keys().rev() {
    7660           18 :             for offset in lsn_offsets {
    7661           15 :                 query_lsns.push(Lsn(image_lsn
    7662           15 :                     .0
    7663           15 :                     .checked_add_signed(offset)
    7664           15 :                     .expect("Shouldn't overflow")));
    7665           15 :             }
    7666            1 :         }
    7667            1 : 
    7668           16 :         for query_lsn in query_lsns {
    7669           15 :             let query = VersionedKeySpaceQuery::uniform(
    7670           15 :                 KeySpace {
    7671           15 :                     ranges: vec![child_gap_at_key..child_gap_at_key.next()],
    7672           15 :                 },
    7673           15 :                 query_lsn,
    7674            1 :             );
    7675            1 : 
    7676           15 :             let results = child_timeline
    7677           15 :                 .get_vectored_impl(
    7678           15 :                     query,
    7679           15 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    7680           15 :                     &ctx,
    7681           15 :                 )
    7682           15 :                 .await;
    7683            1 : 
    7684           15 :             let expected_item = parent_gap_lsns
    7685           15 :                 .iter()
    7686           15 :                 .rev()
    7687           34 :                 .find(|(lsn, _)| **lsn <= query_lsn);
    7688            1 : 
    7689           15 :             info!(
    7690            1 :                 "Doing vectored read at LSN {}. Expecting image to be: {:?}",
    7691            1 :                 query_lsn, expected_item
    7692            1 :             );
    7693            1 : 
    7694           15 :             match expected_item {
    7695           13 :                 Some((_, img_value)) => {
    7696           13 :                     let key_results = results.expect("No vectored get error expected");
    7697           13 :                     let key_result = &key_results[&child_gap_at_key];
    7698           13 :                     let returned_img = key_result
    7699           13 :                         .as_ref()
    7700           13 :                         .expect("No page reconstruct error expected");
    7701            1 : 
    7702           13 :                     info!(
    7703            1 :                         "Vectored read at LSN {} returned image {}",
    7704            1 :                         query_lsn,
    7705            1 :                         std::str::from_utf8(returned_img)?
    7706            1 :                     );
    7707           13 :                     assert_eq!(*returned_img, test_img(img_value));
    7708            1 :                 }
    7709            1 :                 None => {
    7710            2 :                     assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
    7711            1 :                 }
    7712            1 :             }
    7713            1 :         }
    7714            1 : 
    7715            1 :         Ok(())
    7716            1 :     }
    7717              : 
    7718              :     #[tokio::test]
    7719            1 :     async fn test_random_updates() -> anyhow::Result<()> {
    7720            1 :         let names_algorithms = [
    7721            1 :             ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
    7722            1 :             ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
    7723            1 :         ];
    7724            3 :         for (name, algorithm) in names_algorithms {
    7725            2 :             test_random_updates_algorithm(name, algorithm).await?;
    7726            1 :         }
    7727            1 :         Ok(())
    7728            1 :     }
    7729              : 
    7730            2 :     async fn test_random_updates_algorithm(
    7731            2 :         name: &'static str,
    7732            2 :         compaction_algorithm: CompactionAlgorithm,
    7733            2 :     ) -> anyhow::Result<()> {
    7734            2 :         let mut harness = TenantHarness::create(name).await?;
    7735            2 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    7736            2 :             kind: compaction_algorithm,
    7737            2 :         });
    7738            2 :         let (tenant, ctx) = harness.load().await;
    7739            2 :         let tline = tenant
    7740            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7741            2 :             .await?;
    7742              : 
    7743              :         const NUM_KEYS: usize = 1000;
    7744            2 :         let cancel = CancellationToken::new();
    7745              : 
    7746            2 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7747            2 :         let mut test_key_end = test_key;
    7748            2 :         test_key_end.field6 = NUM_KEYS as u32;
    7749            2 :         tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
    7750              : 
    7751            2 :         let mut keyspace = KeySpaceAccum::new();
    7752              : 
    7753              :         // Track when each page was last modified. Used to assert that
    7754              :         // a read sees the latest page version.
    7755            2 :         let mut updated = [Lsn(0); NUM_KEYS];
    7756              : 
    7757            2 :         let mut lsn = Lsn(0x10);
    7758              :         #[allow(clippy::needless_range_loop)]
    7759         2002 :         for blknum in 0..NUM_KEYS {
    7760         2000 :             lsn = Lsn(lsn.0 + 0x10);
    7761         2000 :             test_key.field6 = blknum as u32;
    7762         2000 :             let mut writer = tline.writer().await;
    7763         2000 :             writer
    7764         2000 :                 .put(
    7765         2000 :                     test_key,
    7766         2000 :                     lsn,
    7767         2000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7768         2000 :                     &ctx,
    7769         2000 :                 )
    7770         2000 :                 .await?;
    7771         2000 :             writer.finish_write(lsn);
    7772         2000 :             updated[blknum] = lsn;
    7773         2000 :             drop(writer);
    7774              : 
    7775         2000 :             keyspace.add_key(test_key);
    7776              :         }
    7777              : 
    7778          102 :         for _ in 0..50 {
    7779       100100 :             for _ in 0..NUM_KEYS {
    7780       100000 :                 lsn = Lsn(lsn.0 + 0x10);
    7781       100000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7782       100000 :                 test_key.field6 = blknum as u32;
    7783       100000 :                 let mut writer = tline.writer().await;
    7784       100000 :                 writer
    7785       100000 :                     .put(
    7786       100000 :                         test_key,
    7787       100000 :                         lsn,
    7788       100000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7789       100000 :                         &ctx,
    7790       100000 :                     )
    7791       100000 :                     .await?;
    7792       100000 :                 writer.finish_write(lsn);
    7793       100000 :                 drop(writer);
    7794       100000 :                 updated[blknum] = lsn;
    7795              :             }
    7796              : 
    7797              :             // Read all the blocks
    7798       100000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7799       100000 :                 test_key.field6 = blknum as u32;
    7800       100000 :                 assert_eq!(
    7801       100000 :                     tline.get(test_key, lsn, &ctx).await?,
    7802       100000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    7803              :                 );
    7804              :             }
    7805              : 
    7806              :             // Perform a cycle of flush, and GC
    7807          100 :             tline.freeze_and_flush().await?;
    7808          100 :             tenant
    7809          100 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7810          100 :                 .await?;
    7811              :         }
    7812              : 
    7813            2 :         Ok(())
    7814            2 :     }
    7815              : 
    7816              :     #[tokio::test]
    7817            1 :     async fn test_traverse_branches() -> anyhow::Result<()> {
    7818            1 :         let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
    7819            1 :             .await?
    7820            1 :             .load()
    7821            1 :             .await;
    7822            1 :         let mut tline = tenant
    7823            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7824            1 :             .await?;
    7825              : 
    7826              :         const NUM_KEYS: usize = 1000;
    7827              : 
    7828            1 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7829              : 
    7830            1 :         let mut keyspace = KeySpaceAccum::new();
    7831              : 
    7832            1 :         let cancel = CancellationToken::new();
    7833              : 
    7834              :         // Track when each page was last modified. Used to assert that
    7835              :         // a read sees the latest page version.
    7836            1 :         let mut updated = [Lsn(0); NUM_KEYS];
    7837              : 
    7838            1 :         let mut lsn = Lsn(0x10);
    7839            1 :         #[allow(clippy::needless_range_loop)]
    7840         1001 :         for blknum in 0..NUM_KEYS {
    7841         1000 :             lsn = Lsn(lsn.0 + 0x10);
    7842         1000 :             test_key.field6 = blknum as u32;
    7843         1000 :             let mut writer = tline.writer().await;
    7844         1000 :             writer
    7845         1000 :                 .put(
    7846         1000 :                     test_key,
    7847         1000 :                     lsn,
    7848         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7849         1000 :                     &ctx,
    7850         1000 :                 )
    7851         1000 :                 .await?;
    7852         1000 :             writer.finish_write(lsn);
    7853         1000 :             updated[blknum] = lsn;
    7854         1000 :             drop(writer);
    7855            1 : 
    7856         1000 :             keyspace.add_key(test_key);
    7857            1 :         }
    7858            1 : 
    7859           51 :         for _ in 0..50 {
    7860           50 :             let new_tline_id = TimelineId::generate();
    7861           50 :             tenant
    7862           50 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7863           50 :                 .await?;
    7864           50 :             tline = tenant
    7865           50 :                 .get_timeline(new_tline_id, true)
    7866           50 :                 .expect("Should have the branched timeline");
    7867            1 : 
    7868        50050 :             for _ in 0..NUM_KEYS {
    7869        50000 :                 lsn = Lsn(lsn.0 + 0x10);
    7870        50000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7871        50000 :                 test_key.field6 = blknum as u32;
    7872        50000 :                 let mut writer = tline.writer().await;
    7873        50000 :                 writer
    7874        50000 :                     .put(
    7875        50000 :                         test_key,
    7876        50000 :                         lsn,
    7877        50000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    7878        50000 :                         &ctx,
    7879        50000 :                     )
    7880        50000 :                     .await?;
    7881        50000 :                 println!("updating {blknum} at {lsn}");
    7882        50000 :                 writer.finish_write(lsn);
    7883        50000 :                 drop(writer);
    7884        50000 :                 updated[blknum] = lsn;
    7885            1 :             }
    7886            1 : 
    7887            1 :             // Read all the blocks
    7888        50000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    7889        50000 :                 test_key.field6 = blknum as u32;
    7890        50000 :                 assert_eq!(
    7891        50000 :                     tline.get(test_key, lsn, &ctx).await?,
    7892        50000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    7893            1 :                 );
    7894            1 :             }
    7895            1 : 
    7896            1 :             // Perform a cycle of flush, compact, and GC
    7897           50 :             tline.freeze_and_flush().await?;
    7898           50 :             tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    7899           50 :             tenant
    7900           50 :                 .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    7901           50 :                 .await?;
    7902            1 :         }
    7903            1 : 
    7904            1 :         Ok(())
    7905            1 :     }
    7906              : 
    7907              :     #[tokio::test]
    7908            1 :     async fn test_traverse_ancestors() -> anyhow::Result<()> {
    7909            1 :         let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
    7910            1 :             .await?
    7911            1 :             .load()
    7912            1 :             .await;
    7913            1 :         let mut tline = tenant
    7914            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    7915            1 :             .await?;
    7916              : 
    7917              :         const NUM_KEYS: usize = 100;
    7918              :         const NUM_TLINES: usize = 50;
    7919              : 
    7920            1 :         let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    7921              :         // Track page mutation lsns across different timelines.
    7922            1 :         let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
    7923              : 
    7924            1 :         let mut lsn = Lsn(0x10);
    7925              : 
    7926            1 :         #[allow(clippy::needless_range_loop)]
    7927           51 :         for idx in 0..NUM_TLINES {
    7928           50 :             let new_tline_id = TimelineId::generate();
    7929           50 :             tenant
    7930           50 :                 .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
    7931           50 :                 .await?;
    7932           50 :             tline = tenant
    7933           50 :                 .get_timeline(new_tline_id, true)
    7934           50 :                 .expect("Should have the branched timeline");
    7935            1 : 
    7936         5050 :             for _ in 0..NUM_KEYS {
    7937         5000 :                 lsn = Lsn(lsn.0 + 0x10);
    7938         5000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    7939         5000 :                 test_key.field6 = blknum as u32;
    7940         5000 :                 let mut writer = tline.writer().await;
    7941         5000 :                 writer
    7942         5000 :                     .put(
    7943         5000 :                         test_key,
    7944         5000 :                         lsn,
    7945         5000 :                         &Value::Image(test_img(&format!("{idx} {blknum} at {lsn}"))),
    7946         5000 :                         &ctx,
    7947         5000 :                     )
    7948         5000 :                     .await?;
    7949         5000 :                 println!("updating [{idx}][{blknum}] at {lsn}");
    7950         5000 :                 writer.finish_write(lsn);
    7951         5000 :                 drop(writer);
    7952         5000 :                 updated[idx][blknum] = lsn;
    7953            1 :             }
    7954            1 :         }
    7955            1 : 
    7956            1 :         // Read pages from leaf timeline across all ancestors.
    7957           50 :         for (idx, lsns) in updated.iter().enumerate() {
    7958         5000 :             for (blknum, lsn) in lsns.iter().enumerate() {
    7959            1 :                 // Skip empty mutations.
    7960         5000 :                 if lsn.0 == 0 {
    7961         1877 :                     continue;
    7962         3123 :                 }
    7963         3123 :                 println!("checking [{idx}][{blknum}] at {lsn}");
    7964         3123 :                 test_key.field6 = blknum as u32;
    7965         3123 :                 assert_eq!(
    7966         3123 :                     tline.get(test_key, *lsn, &ctx).await?,
    7967         3123 :                     test_img(&format!("{idx} {blknum} at {lsn}"))
    7968            1 :                 );
    7969            1 :             }
    7970            1 :         }
    7971            1 :         Ok(())
    7972            1 :     }
    7973              : 
    7974              :     #[tokio::test]
    7975            1 :     async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
    7976            1 :         let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
    7977            1 :             .await?
    7978            1 :             .load()
    7979            1 :             .await;
    7980              : 
    7981            1 :         let initdb_lsn = Lsn(0x20);
    7982            1 :         let (utline, ctx) = tenant
    7983            1 :             .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
    7984            1 :             .await?;
    7985            1 :         let tline = utline.raw_timeline().unwrap();
    7986              : 
    7987              :         // Spawn flush loop now so that we can set the `expect_initdb_optimization`
    7988            1 :         tline.maybe_spawn_flush_loop();
    7989              : 
    7990              :         // Make sure the timeline has the minimum set of required keys for operation.
    7991              :         // The only operation you can always do on an empty timeline is to `put` new data.
    7992              :         // Except if you `put` at `initdb_lsn`.
    7993              :         // In that case, there's an optimization to directly create image layers instead of delta layers.
    7994              :         // It uses `repartition()`, which assumes some keys to be present.
    7995              :         // Let's make sure the test timeline can handle that case.
    7996              :         {
    7997            1 :             let mut state = tline.flush_loop_state.lock().unwrap();
    7998            1 :             assert_eq!(
    7999              :                 timeline::FlushLoopState::Running {
    8000              :                     expect_initdb_optimization: false,
    8001              :                     initdb_optimization_count: 0,
    8002              :                 },
    8003            1 :                 *state
    8004              :             );
    8005            1 :             *state = timeline::FlushLoopState::Running {
    8006            1 :                 expect_initdb_optimization: true,
    8007            1 :                 initdb_optimization_count: 0,
    8008            1 :             };
    8009              :         }
    8010              : 
    8011              :         // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
    8012              :         // As explained above, the optimization requires some keys to be present.
    8013              :         // As per `create_empty_timeline` documentation, use init_empty to set them.
    8014              :         // This is what `create_test_timeline` does, by the way.
    8015            1 :         let mut modification = tline.begin_modification(initdb_lsn);
    8016            1 :         modification
    8017            1 :             .init_empty_test_timeline()
    8018            1 :             .context("init_empty_test_timeline")?;
    8019            1 :         modification
    8020            1 :             .commit(&ctx)
    8021            1 :             .await
    8022            1 :             .context("commit init_empty_test_timeline modification")?;
    8023              : 
    8024              :         // Do the flush. The flush code will check the expectations that we set above.
    8025            1 :         tline.freeze_and_flush().await?;
    8026              : 
    8027              :         // assert freeze_and_flush exercised the initdb optimization
    8028            1 :         {
    8029            1 :             let state = tline.flush_loop_state.lock().unwrap();
    8030            1 :             let timeline::FlushLoopState::Running {
    8031            1 :                 expect_initdb_optimization,
    8032            1 :                 initdb_optimization_count,
    8033            1 :             } = *state
    8034            1 :             else {
    8035            1 :                 panic!("unexpected state: {:?}", *state);
    8036            1 :             };
    8037            1 :             assert!(expect_initdb_optimization);
    8038            1 :             assert!(initdb_optimization_count > 0);
    8039            1 :         }
    8040            1 :         Ok(())
    8041            1 :     }
    8042              : 
    8043              :     #[tokio::test]
    8044            1 :     async fn test_create_guard_crash() -> anyhow::Result<()> {
    8045            1 :         let name = "test_create_guard_crash";
    8046            1 :         let harness = TenantHarness::create(name).await?;
    8047              :         {
    8048            1 :             let (tenant, ctx) = harness.load().await;
    8049            1 :             let (tline, _ctx) = tenant
    8050            1 :                 .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    8051            1 :                 .await?;
    8052              :             // Leave the timeline ID in [`TenantShard::timelines_creating`] to exclude attempting to create it again
    8053            1 :             let raw_tline = tline.raw_timeline().unwrap();
    8054            1 :             raw_tline
    8055            1 :                 .shutdown(super::timeline::ShutdownMode::Hard)
    8056            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))
    8057            1 :                 .await;
    8058            1 :             std::mem::forget(tline);
    8059              :         }
    8060              : 
    8061            1 :         let (tenant, _) = harness.load().await;
    8062            1 :         match tenant.get_timeline(TIMELINE_ID, false) {
    8063            0 :             Ok(_) => panic!("timeline should've been removed during load"),
    8064            1 :             Err(e) => {
    8065            1 :                 assert_eq!(
    8066              :                     e,
    8067            1 :                     GetTimelineError::NotFound {
    8068            1 :                         tenant_id: tenant.tenant_shard_id,
    8069            1 :                         timeline_id: TIMELINE_ID,
    8070            1 :                     }
    8071              :                 )
    8072              :             }
    8073              :         }
    8074              : 
    8075            1 :         assert!(
    8076            1 :             !harness
    8077            1 :                 .conf
    8078            1 :                 .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
    8079            1 :                 .exists()
    8080              :         );
    8081              : 
    8082            2 :         Ok(())
    8083            1 :     }
    8084              : 
    8085              :     #[tokio::test]
    8086            1 :     async fn test_read_at_max_lsn() -> anyhow::Result<()> {
    8087            1 :         let names_algorithms = [
    8088            1 :             ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
    8089            1 :             ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
    8090            1 :         ];
    8091            3 :         for (name, algorithm) in names_algorithms {
    8092            2 :             test_read_at_max_lsn_algorithm(name, algorithm).await?;
    8093            1 :         }
    8094            1 :         Ok(())
    8095            1 :     }
    8096              : 
    8097            2 :     async fn test_read_at_max_lsn_algorithm(
    8098            2 :         name: &'static str,
    8099            2 :         compaction_algorithm: CompactionAlgorithm,
    8100            2 :     ) -> anyhow::Result<()> {
    8101            2 :         let mut harness = TenantHarness::create(name).await?;
    8102            2 :         harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
    8103            2 :             kind: compaction_algorithm,
    8104            2 :         });
    8105            2 :         let (tenant, ctx) = harness.load().await;
    8106            2 :         let tline = tenant
    8107            2 :             .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
    8108            2 :             .await?;
    8109              : 
    8110            2 :         let lsn = Lsn(0x10);
    8111            2 :         let compact = false;
    8112            2 :         bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
    8113              : 
    8114            2 :         let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    8115            2 :         let read_lsn = Lsn(u64::MAX - 1);
    8116              : 
    8117            2 :         let result = tline.get(test_key, read_lsn, &ctx).await;
    8118            2 :         assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
    8119              : 
    8120            2 :         Ok(())
    8121            2 :     }
    8122              : 
    8123              :     #[tokio::test]
    8124            1 :     async fn test_metadata_scan() -> anyhow::Result<()> {
    8125            1 :         let harness = TenantHarness::create("test_metadata_scan").await?;
    8126            1 :         let (tenant, ctx) = harness.load().await;
    8127            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8128            1 :         let tline = tenant
    8129            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8130            1 :             .await?;
    8131              : 
    8132              :         const NUM_KEYS: usize = 1000;
    8133              :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8134              : 
    8135            1 :         let cancel = CancellationToken::new();
    8136              : 
    8137            1 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8138            1 :         base_key.field1 = AUX_KEY_PREFIX;
    8139            1 :         let mut test_key = base_key;
    8140              : 
    8141              :         // Track when each page was last modified. Used to assert that
    8142              :         // a read sees the latest page version.
    8143            1 :         let mut updated = [Lsn(0); NUM_KEYS];
    8144              : 
    8145            1 :         let mut lsn = Lsn(0x10);
    8146              :         #[allow(clippy::needless_range_loop)]
    8147         1001 :         for blknum in 0..NUM_KEYS {
    8148         1000 :             lsn = Lsn(lsn.0 + 0x10);
    8149         1000 :             test_key.field6 = (blknum * STEP) as u32;
    8150         1000 :             let mut writer = tline.writer().await;
    8151         1000 :             writer
    8152         1000 :                 .put(
    8153         1000 :                     test_key,
    8154         1000 :                     lsn,
    8155         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8156         1000 :                     &ctx,
    8157         1000 :                 )
    8158         1000 :                 .await?;
    8159         1000 :             writer.finish_write(lsn);
    8160         1000 :             updated[blknum] = lsn;
    8161         1000 :             drop(writer);
    8162              :         }
    8163              : 
    8164            1 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8165              : 
    8166           12 :         for iter in 0..=10 {
    8167            1 :             // Read all the blocks
    8168        11000 :             for (blknum, last_lsn) in updated.iter().enumerate() {
    8169        11000 :                 test_key.field6 = (blknum * STEP) as u32;
    8170        11000 :                 assert_eq!(
    8171        11000 :                     tline.get(test_key, lsn, &ctx).await?,
    8172        11000 :                     test_img(&format!("{blknum} at {last_lsn}"))
    8173            1 :                 );
    8174            1 :             }
    8175            1 : 
    8176           11 :             let mut cnt = 0;
    8177           11 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8178            1 : 
    8179        11000 :             for (key, value) in tline
    8180           11 :                 .get_vectored_impl(
    8181           11 :                     query,
    8182           11 :                     &mut ValuesReconstructState::new(io_concurrency.clone()),
    8183           11 :                     &ctx,
    8184           11 :                 )
    8185           11 :                 .await?
    8186            1 :             {
    8187        11000 :                 let blknum = key.field6 as usize;
    8188        11000 :                 let value = value?;
    8189        11000 :                 assert!(blknum % STEP == 0);
    8190        11000 :                 let blknum = blknum / STEP;
    8191        11000 :                 assert_eq!(
    8192            1 :                     value,
    8193        11000 :                     test_img(&format!("{} at {}", blknum, updated[blknum]))
    8194            1 :                 );
    8195        11000 :                 cnt += 1;
    8196            1 :             }
    8197            1 : 
    8198           11 :             assert_eq!(cnt, NUM_KEYS);
    8199            1 : 
    8200        11011 :             for _ in 0..NUM_KEYS {
    8201        11000 :                 lsn = Lsn(lsn.0 + 0x10);
    8202        11000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8203        11000 :                 test_key.field6 = (blknum * STEP) as u32;
    8204        11000 :                 let mut writer = tline.writer().await;
    8205        11000 :                 writer
    8206        11000 :                     .put(
    8207        11000 :                         test_key,
    8208        11000 :                         lsn,
    8209        11000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8210        11000 :                         &ctx,
    8211        11000 :                     )
    8212        11000 :                     .await?;
    8213        11000 :                 writer.finish_write(lsn);
    8214        11000 :                 drop(writer);
    8215        11000 :                 updated[blknum] = lsn;
    8216            1 :             }
    8217            1 : 
    8218            1 :             // Perform two cycles of flush, compact, and GC
    8219           33 :             for round in 0..2 {
    8220           22 :                 tline.freeze_and_flush().await?;
    8221           22 :                 tline
    8222           22 :                     .compact(
    8223           22 :                         &cancel,
    8224           22 :                         if iter % 5 == 0 && round == 0 {
    8225            3 :                             let mut flags = EnumSet::new();
    8226            3 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8227            3 :                             flags.insert(CompactFlags::ForceRepartition);
    8228            3 :                             flags
    8229            1 :                         } else {
    8230           19 :                             EnumSet::empty()
    8231            1 :                         },
    8232           22 :                         &ctx,
    8233            1 :                     )
    8234           22 :                     .await?;
    8235           22 :                 tenant
    8236           22 :                     .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
    8237           22 :                     .await?;
    8238            1 :             }
    8239            1 :         }
    8240            1 : 
    8241            1 :         Ok(())
    8242            1 :     }
    8243              : 
    8244              :     #[tokio::test]
    8245            1 :     async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
    8246            1 :         let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
    8247            1 :         let (tenant, ctx) = harness.load().await;
    8248            1 :         let tline = tenant
    8249            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8250            1 :             .await?;
    8251              : 
    8252            1 :         let cancel = CancellationToken::new();
    8253              : 
    8254            1 :         let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8255            1 :         base_key.field1 = AUX_KEY_PREFIX;
    8256            1 :         let test_key = base_key;
    8257            1 :         let mut lsn = Lsn(0x10);
    8258              : 
    8259           21 :         for _ in 0..20 {
    8260           20 :             lsn = Lsn(lsn.0 + 0x10);
    8261           20 :             let mut writer = tline.writer().await;
    8262           20 :             writer
    8263           20 :                 .put(
    8264           20 :                     test_key,
    8265           20 :                     lsn,
    8266           20 :                     &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
    8267           20 :                     &ctx,
    8268           20 :                 )
    8269           20 :                 .await?;
    8270           20 :             writer.finish_write(lsn);
    8271           20 :             drop(writer);
    8272           20 :             tline.freeze_and_flush().await?; // force create a delta layer
    8273              :         }
    8274              : 
    8275            1 :         let before_num_l0_delta_files = tline
    8276            1 :             .layers
    8277            1 :             .read(LayerManagerLockHolder::Testing)
    8278            1 :             .await
    8279            1 :             .layer_map()?
    8280            1 :             .level0_deltas()
    8281            1 :             .len();
    8282              : 
    8283            1 :         tline.compact(&cancel, EnumSet::default(), &ctx).await?;
    8284              : 
    8285            1 :         let after_num_l0_delta_files = tline
    8286            1 :             .layers
    8287            1 :             .read(LayerManagerLockHolder::Testing)
    8288            1 :             .await
    8289            1 :             .layer_map()?
    8290            1 :             .level0_deltas()
    8291            1 :             .len();
    8292              : 
    8293            1 :         assert!(
    8294            1 :             after_num_l0_delta_files < before_num_l0_delta_files,
    8295            0 :             "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
    8296              :         );
    8297              : 
    8298            1 :         assert_eq!(
    8299            1 :             tline.get(test_key, lsn, &ctx).await?,
    8300            1 :             test_img(&format!("{} at {}", 0, lsn))
    8301              :         );
    8302              : 
    8303            2 :         Ok(())
    8304            1 :     }
    8305              : 
    8306              :     #[tokio::test]
    8307            1 :     async fn test_aux_file_e2e() {
    8308            1 :         let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
    8309              : 
    8310            1 :         let (tenant, ctx) = harness.load().await;
    8311            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8312              : 
    8313            1 :         let mut lsn = Lsn(0x08);
    8314              : 
    8315            1 :         let tline: Arc<Timeline> = tenant
    8316            1 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8317            1 :             .await
    8318            1 :             .unwrap();
    8319              : 
    8320              :         {
    8321            1 :             lsn += 8;
    8322            1 :             let mut modification = tline.begin_modification(lsn);
    8323            1 :             modification
    8324            1 :                 .put_file("pg_logical/mappings/test1", b"first", &ctx)
    8325            1 :                 .await
    8326            1 :                 .unwrap();
    8327            1 :             modification.commit(&ctx).await.unwrap();
    8328              :         }
    8329              : 
    8330              :         // we can read everything from the storage
    8331            1 :         let files = tline
    8332            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8333            1 :             .await
    8334            1 :             .unwrap();
    8335            1 :         assert_eq!(
    8336            1 :             files.get("pg_logical/mappings/test1"),
    8337            1 :             Some(&bytes::Bytes::from_static(b"first"))
    8338              :         );
    8339              : 
    8340              :         {
    8341            1 :             lsn += 8;
    8342            1 :             let mut modification = tline.begin_modification(lsn);
    8343            1 :             modification
    8344            1 :                 .put_file("pg_logical/mappings/test2", b"second", &ctx)
    8345            1 :                 .await
    8346            1 :                 .unwrap();
    8347            1 :             modification.commit(&ctx).await.unwrap();
    8348              :         }
    8349              : 
    8350            1 :         let files = tline
    8351            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8352            1 :             .await
    8353            1 :             .unwrap();
    8354            1 :         assert_eq!(
    8355            1 :             files.get("pg_logical/mappings/test2"),
    8356            1 :             Some(&bytes::Bytes::from_static(b"second"))
    8357              :         );
    8358              : 
    8359            1 :         let child = tenant
    8360            1 :             .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
    8361            1 :             .await
    8362            1 :             .unwrap();
    8363              : 
    8364            1 :         let files = child
    8365            1 :             .list_aux_files(lsn, &ctx, io_concurrency.clone())
    8366            1 :             .await
    8367            1 :             .unwrap();
    8368            1 :         assert_eq!(files.get("pg_logical/mappings/test1"), None);
    8369            1 :         assert_eq!(files.get("pg_logical/mappings/test2"), None);
    8370            1 :     }
    8371              : 
    8372              :     #[tokio::test]
    8373            1 :     async fn test_repl_origin_tombstones() {
    8374            1 :         let harness = TenantHarness::create("test_repl_origin_tombstones")
    8375            1 :             .await
    8376            1 :             .unwrap();
    8377              : 
    8378            1 :         let (tenant, ctx) = harness.load().await;
    8379            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8380              : 
    8381            1 :         let mut lsn = Lsn(0x08);
    8382              : 
    8383            1 :         let tline: Arc<Timeline> = tenant
    8384            1 :             .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
    8385            1 :             .await
    8386            1 :             .unwrap();
    8387              : 
    8388            1 :         let repl_lsn = Lsn(0x10);
    8389              :         {
    8390            1 :             lsn += 8;
    8391            1 :             let mut modification = tline.begin_modification(lsn);
    8392            1 :             modification.put_for_unit_test(repl_origin_key(2), Value::Image(Bytes::new()));
    8393            1 :             modification.set_replorigin(1, repl_lsn).await.unwrap();
    8394            1 :             modification.commit(&ctx).await.unwrap();
    8395              :         }
    8396              : 
    8397              :         // we can read everything from the storage
    8398            1 :         let repl_origins = tline
    8399            1 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8400            1 :             .await
    8401            1 :             .unwrap();
    8402            1 :         assert_eq!(repl_origins.len(), 1);
    8403            1 :         assert_eq!(repl_origins[&1], lsn);
    8404              : 
    8405              :         {
    8406            1 :             lsn += 8;
    8407            1 :             let mut modification = tline.begin_modification(lsn);
    8408            1 :             modification.put_for_unit_test(
    8409            1 :                 repl_origin_key(3),
    8410            1 :                 Value::Image(Bytes::copy_from_slice(b"cannot_decode_this")),
    8411              :             );
    8412            1 :             modification.commit(&ctx).await.unwrap();
    8413              :         }
    8414            1 :         let result = tline
    8415            1 :             .get_replorigins(lsn, &ctx, io_concurrency.clone())
    8416            1 :             .await;
    8417            1 :         assert!(result.is_err());
    8418            1 :     }
    8419              : 
    8420              :     #[tokio::test]
    8421            1 :     async fn test_metadata_image_creation() -> anyhow::Result<()> {
    8422            1 :         let harness = TenantHarness::create("test_metadata_image_creation").await?;
    8423            1 :         let (tenant, ctx) = harness.load().await;
    8424            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8425            1 :         let tline = tenant
    8426            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    8427            1 :             .await?;
    8428              : 
    8429              :         const NUM_KEYS: usize = 1000;
    8430              :         const STEP: usize = 10000; // random update + scan base_key + idx * STEP
    8431              : 
    8432            1 :         let cancel = CancellationToken::new();
    8433              : 
    8434            1 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8435            1 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8436            1 :         let mut test_key = base_key;
    8437            1 :         let mut lsn = Lsn(0x10);
    8438              : 
    8439            4 :         async fn scan_with_statistics(
    8440            4 :             tline: &Timeline,
    8441            4 :             keyspace: &KeySpace,
    8442            4 :             lsn: Lsn,
    8443            4 :             ctx: &RequestContext,
    8444            4 :             io_concurrency: IoConcurrency,
    8445            4 :         ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
    8446            4 :             let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8447            4 :             let query = VersionedKeySpaceQuery::uniform(keyspace.clone(), lsn);
    8448            4 :             let res = tline
    8449            4 :                 .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8450            4 :                 .await?;
    8451            4 :             Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
    8452            4 :         }
    8453              : 
    8454         1001 :         for blknum in 0..NUM_KEYS {
    8455         1000 :             lsn = Lsn(lsn.0 + 0x10);
    8456         1000 :             test_key.field6 = (blknum * STEP) as u32;
    8457         1000 :             let mut writer = tline.writer().await;
    8458         1000 :             writer
    8459         1000 :                 .put(
    8460         1000 :                     test_key,
    8461         1000 :                     lsn,
    8462         1000 :                     &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8463         1000 :                     &ctx,
    8464         1000 :                 )
    8465         1000 :                 .await?;
    8466         1000 :             writer.finish_write(lsn);
    8467         1000 :             drop(writer);
    8468              :         }
    8469              : 
    8470            1 :         let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
    8471              : 
    8472           11 :         for iter in 1..=10 {
    8473        10010 :             for _ in 0..NUM_KEYS {
    8474        10000 :                 lsn = Lsn(lsn.0 + 0x10);
    8475        10000 :                 let blknum = thread_rng().gen_range(0..NUM_KEYS);
    8476        10000 :                 test_key.field6 = (blknum * STEP) as u32;
    8477        10000 :                 let mut writer = tline.writer().await;
    8478        10000 :                 writer
    8479        10000 :                     .put(
    8480        10000 :                         test_key,
    8481        10000 :                         lsn,
    8482        10000 :                         &Value::Image(test_img(&format!("{blknum} at {lsn}"))),
    8483        10000 :                         &ctx,
    8484        10000 :                     )
    8485        10000 :                     .await?;
    8486        10000 :                 writer.finish_write(lsn);
    8487        10000 :                 drop(writer);
    8488            1 :             }
    8489            1 : 
    8490           10 :             tline.freeze_and_flush().await?;
    8491            1 :             // Force layers to L1
    8492           10 :             tline
    8493           10 :                 .compact(
    8494           10 :                     &cancel,
    8495           10 :                     {
    8496           10 :                         let mut flags = EnumSet::new();
    8497           10 :                         flags.insert(CompactFlags::ForceL0Compaction);
    8498           10 :                         flags
    8499           10 :                     },
    8500           10 :                     &ctx,
    8501           10 :                 )
    8502           10 :                 .await?;
    8503            1 : 
    8504           10 :             if iter % 5 == 0 {
    8505            2 :                 let scan_lsn = Lsn(lsn.0 + 1);
    8506            2 :                 info!("scanning at {}", scan_lsn);
    8507            2 :                 let (_, before_delta_file_accessed) =
    8508            2 :                     scan_with_statistics(&tline, &keyspace, scan_lsn, &ctx, io_concurrency.clone())
    8509            2 :                         .await?;
    8510            2 :                 tline
    8511            2 :                     .compact(
    8512            2 :                         &cancel,
    8513            2 :                         {
    8514            2 :                             let mut flags = EnumSet::new();
    8515            2 :                             flags.insert(CompactFlags::ForceImageLayerCreation);
    8516            2 :                             flags.insert(CompactFlags::ForceRepartition);
    8517            2 :                             flags.insert(CompactFlags::ForceL0Compaction);
    8518            2 :                             flags
    8519            2 :                         },
    8520            2 :                         &ctx,
    8521            2 :                     )
    8522            2 :                     .await?;
    8523            2 :                 let (_, after_delta_file_accessed) =
    8524            2 :                     scan_with_statistics(&tline, &keyspace, scan_lsn, &ctx, io_concurrency.clone())
    8525            2 :                         .await?;
    8526            2 :                 assert!(
    8527            2 :                     after_delta_file_accessed < before_delta_file_accessed,
    8528            1 :                     "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
    8529            1 :                 );
    8530            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.
    8531            2 :                 assert!(
    8532            2 :                     after_delta_file_accessed <= 2,
    8533            1 :                     "after_delta_file_accessed={after_delta_file_accessed}"
    8534            1 :                 );
    8535            8 :             }
    8536            1 :         }
    8537            1 : 
    8538            1 :         Ok(())
    8539            1 :     }
    8540              : 
    8541              :     #[tokio::test]
    8542            1 :     async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
    8543            1 :         let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
    8544            1 :         let (tenant, ctx) = harness.load().await;
    8545              : 
    8546            1 :         let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    8547            1 :         let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
    8548            1 :         let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
    8549              : 
    8550            1 :         let tline = tenant
    8551            1 :             .create_test_timeline_with_layers(
    8552            1 :                 TIMELINE_ID,
    8553            1 :                 Lsn(0x10),
    8554            1 :                 DEFAULT_PG_VERSION,
    8555            1 :                 &ctx,
    8556            1 :                 Vec::new(), // in-memory layers
    8557            1 :                 Vec::new(), // delta layers
    8558            1 :                 vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
    8559            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
    8560            1 :             )
    8561            1 :             .await?;
    8562            1 :         tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
    8563              : 
    8564            1 :         let child = tenant
    8565            1 :             .branch_timeline_test_with_layers(
    8566            1 :                 &tline,
    8567            1 :                 NEW_TIMELINE_ID,
    8568            1 :                 Some(Lsn(0x20)),
    8569            1 :                 &ctx,
    8570            1 :                 Vec::new(), // delta layers
    8571            1 :                 vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
    8572            1 :                 Lsn(0x30),
    8573            1 :             )
    8574            1 :             .await
    8575            1 :             .unwrap();
    8576              : 
    8577            1 :         let lsn = Lsn(0x30);
    8578              : 
    8579              :         // test vectored get on parent timeline
    8580            1 :         assert_eq!(
    8581            1 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8582            1 :             Some(test_img("data key 1"))
    8583              :         );
    8584            1 :         assert!(
    8585            1 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
    8586            1 :                 .await
    8587            1 :                 .unwrap_err()
    8588            1 :                 .is_missing_key_error()
    8589              :         );
    8590            1 :         assert!(
    8591            1 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
    8592            1 :                 .await
    8593            1 :                 .unwrap_err()
    8594            1 :                 .is_missing_key_error()
    8595              :         );
    8596              : 
    8597              :         // test vectored get on child timeline
    8598            1 :         assert_eq!(
    8599            1 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8600            1 :             Some(test_img("data key 1"))
    8601              :         );
    8602            1 :         assert_eq!(
    8603            1 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8604            1 :             Some(test_img("data key 2"))
    8605              :         );
    8606            1 :         assert!(
    8607            1 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
    8608            1 :                 .await
    8609            1 :                 .unwrap_err()
    8610            1 :                 .is_missing_key_error()
    8611              :         );
    8612              : 
    8613            2 :         Ok(())
    8614            1 :     }
    8615              : 
    8616              :     #[tokio::test]
    8617            1 :     async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
    8618            1 :         let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
    8619            1 :         let (tenant, ctx) = harness.load().await;
    8620            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8621              : 
    8622            1 :         let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8623            1 :         let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8624            1 :         let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8625            1 :         let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8626              : 
    8627            1 :         let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
    8628            1 :         let base_inherited_key_child =
    8629            1 :             Key::from_hex("610000000033333333444444445500000001").unwrap();
    8630            1 :         let base_inherited_key_nonexist =
    8631            1 :             Key::from_hex("610000000033333333444444445500000002").unwrap();
    8632            1 :         let base_inherited_key_overwrite =
    8633            1 :             Key::from_hex("610000000033333333444444445500000003").unwrap();
    8634              : 
    8635            1 :         assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
    8636            1 :         assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
    8637              : 
    8638            1 :         let tline = tenant
    8639            1 :             .create_test_timeline_with_layers(
    8640            1 :                 TIMELINE_ID,
    8641            1 :                 Lsn(0x10),
    8642            1 :                 DEFAULT_PG_VERSION,
    8643            1 :                 &ctx,
    8644            1 :                 Vec::new(), // in-memory layers
    8645            1 :                 Vec::new(), // delta layers
    8646            1 :                 vec![(
    8647            1 :                     Lsn(0x20),
    8648            1 :                     vec![
    8649            1 :                         (base_inherited_key, test_img("metadata inherited key 1")),
    8650            1 :                         (
    8651            1 :                             base_inherited_key_overwrite,
    8652            1 :                             test_img("metadata key overwrite 1a"),
    8653            1 :                         ),
    8654            1 :                         (base_key, test_img("metadata key 1")),
    8655            1 :                         (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8656            1 :                     ],
    8657            1 :                 )], // image layers
    8658            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
    8659            1 :             )
    8660            1 :             .await?;
    8661              : 
    8662            1 :         let child = tenant
    8663            1 :             .branch_timeline_test_with_layers(
    8664            1 :                 &tline,
    8665            1 :                 NEW_TIMELINE_ID,
    8666            1 :                 Some(Lsn(0x20)),
    8667            1 :                 &ctx,
    8668            1 :                 Vec::new(), // delta layers
    8669            1 :                 vec![(
    8670            1 :                     Lsn(0x30),
    8671            1 :                     vec![
    8672            1 :                         (
    8673            1 :                             base_inherited_key_child,
    8674            1 :                             test_img("metadata inherited key 2"),
    8675            1 :                         ),
    8676            1 :                         (
    8677            1 :                             base_inherited_key_overwrite,
    8678            1 :                             test_img("metadata key overwrite 2a"),
    8679            1 :                         ),
    8680            1 :                         (base_key_child, test_img("metadata key 2")),
    8681            1 :                         (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8682            1 :                     ],
    8683            1 :                 )], // image layers
    8684            1 :                 Lsn(0x30),
    8685            1 :             )
    8686            1 :             .await
    8687            1 :             .unwrap();
    8688              : 
    8689            1 :         let lsn = Lsn(0x30);
    8690              : 
    8691              :         // test vectored get on parent timeline
    8692            1 :         assert_eq!(
    8693            1 :             get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
    8694            1 :             Some(test_img("metadata key 1"))
    8695              :         );
    8696            1 :         assert_eq!(
    8697            1 :             get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
    8698              :             None
    8699              :         );
    8700            1 :         assert_eq!(
    8701            1 :             get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
    8702              :             None
    8703              :         );
    8704            1 :         assert_eq!(
    8705            1 :             get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
    8706            1 :             Some(test_img("metadata key overwrite 1b"))
    8707              :         );
    8708            1 :         assert_eq!(
    8709            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
    8710            1 :             Some(test_img("metadata inherited key 1"))
    8711              :         );
    8712            1 :         assert_eq!(
    8713            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
    8714              :             None
    8715              :         );
    8716            1 :         assert_eq!(
    8717            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
    8718              :             None
    8719              :         );
    8720            1 :         assert_eq!(
    8721            1 :             get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
    8722            1 :             Some(test_img("metadata key overwrite 1a"))
    8723              :         );
    8724              : 
    8725              :         // test vectored get on child timeline
    8726            1 :         assert_eq!(
    8727            1 :             get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
    8728              :             None
    8729              :         );
    8730            1 :         assert_eq!(
    8731            1 :             get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
    8732            1 :             Some(test_img("metadata key 2"))
    8733              :         );
    8734            1 :         assert_eq!(
    8735            1 :             get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
    8736              :             None
    8737              :         );
    8738            1 :         assert_eq!(
    8739            1 :             get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
    8740            1 :             Some(test_img("metadata inherited key 1"))
    8741              :         );
    8742            1 :         assert_eq!(
    8743            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
    8744            1 :             Some(test_img("metadata inherited key 2"))
    8745              :         );
    8746            1 :         assert_eq!(
    8747            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
    8748              :             None
    8749              :         );
    8750            1 :         assert_eq!(
    8751            1 :             get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
    8752            1 :             Some(test_img("metadata key overwrite 2b"))
    8753              :         );
    8754            1 :         assert_eq!(
    8755            1 :             get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
    8756            1 :             Some(test_img("metadata key overwrite 2a"))
    8757              :         );
    8758              : 
    8759              :         // test vectored scan on parent timeline
    8760            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8761            1 :         let query =
    8762            1 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8763            1 :         let res = tline
    8764            1 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8765            1 :             .await?;
    8766              : 
    8767            1 :         assert_eq!(
    8768            1 :             res.into_iter()
    8769            4 :                 .map(|(k, v)| (k, v.unwrap()))
    8770            1 :                 .collect::<Vec<_>>(),
    8771            1 :             vec![
    8772            1 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8773            1 :                 (
    8774            1 :                     base_inherited_key_overwrite,
    8775            1 :                     test_img("metadata key overwrite 1a")
    8776            1 :                 ),
    8777            1 :                 (base_key, test_img("metadata key 1")),
    8778            1 :                 (base_key_overwrite, test_img("metadata key overwrite 1b")),
    8779              :             ]
    8780              :         );
    8781              : 
    8782              :         // test vectored scan on child timeline
    8783            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    8784            1 :         let query =
    8785            1 :             VersionedKeySpaceQuery::uniform(KeySpace::single(Key::metadata_key_range()), lsn);
    8786            1 :         let res = child
    8787            1 :             .get_vectored_impl(query, &mut reconstruct_state, &ctx)
    8788            1 :             .await?;
    8789              : 
    8790            1 :         assert_eq!(
    8791            1 :             res.into_iter()
    8792            5 :                 .map(|(k, v)| (k, v.unwrap()))
    8793            1 :                 .collect::<Vec<_>>(),
    8794            1 :             vec![
    8795            1 :                 (base_inherited_key, test_img("metadata inherited key 1")),
    8796            1 :                 (
    8797            1 :                     base_inherited_key_child,
    8798            1 :                     test_img("metadata inherited key 2")
    8799            1 :                 ),
    8800            1 :                 (
    8801            1 :                     base_inherited_key_overwrite,
    8802            1 :                     test_img("metadata key overwrite 2a")
    8803            1 :                 ),
    8804            1 :                 (base_key_child, test_img("metadata key 2")),
    8805            1 :                 (base_key_overwrite, test_img("metadata key overwrite 2b")),
    8806              :             ]
    8807              :         );
    8808              : 
    8809            2 :         Ok(())
    8810            1 :     }
    8811              : 
    8812           28 :     async fn get_vectored_impl_wrapper(
    8813           28 :         tline: &Arc<Timeline>,
    8814           28 :         key: Key,
    8815           28 :         lsn: Lsn,
    8816           28 :         ctx: &RequestContext,
    8817           28 :     ) -> Result<Option<Bytes>, GetVectoredError> {
    8818           28 :         let io_concurrency = IoConcurrency::spawn_from_conf(
    8819           28 :             tline.conf.get_vectored_concurrent_io,
    8820           28 :             tline.gate.enter().unwrap(),
    8821              :         );
    8822           28 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
    8823           28 :         let query = VersionedKeySpaceQuery::uniform(KeySpace::single(key..key.next()), lsn);
    8824           28 :         let mut res = tline
    8825           28 :             .get_vectored_impl(query, &mut reconstruct_state, ctx)
    8826           28 :             .await?;
    8827           25 :         Ok(res.pop_last().map(|(k, v)| {
    8828           16 :             assert_eq!(k, key);
    8829           16 :             v.unwrap()
    8830           16 :         }))
    8831           28 :     }
    8832              : 
    8833              :     #[tokio::test]
    8834            1 :     async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
    8835            1 :         let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
    8836            1 :         let (tenant, ctx) = harness.load().await;
    8837            1 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8838            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8839            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8840            1 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8841              : 
    8842              :         // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
    8843              :         // Lsn 0x30 key0, key3, no key1+key2
    8844              :         // Lsn 0x20 key1+key2 tomestones
    8845              :         // Lsn 0x10 key1 in image, key2 in delta
    8846            1 :         let tline = tenant
    8847            1 :             .create_test_timeline_with_layers(
    8848            1 :                 TIMELINE_ID,
    8849            1 :                 Lsn(0x10),
    8850            1 :                 DEFAULT_PG_VERSION,
    8851            1 :                 &ctx,
    8852            1 :                 Vec::new(), // in-memory layers
    8853            1 :                 // delta layers
    8854            1 :                 vec![
    8855            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8856            1 :                         Lsn(0x10)..Lsn(0x20),
    8857            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8858            1 :                     ),
    8859            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8860            1 :                         Lsn(0x20)..Lsn(0x30),
    8861            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8862            1 :                     ),
    8863            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8864            1 :                         Lsn(0x20)..Lsn(0x30),
    8865            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8866            1 :                     ),
    8867            1 :                 ],
    8868            1 :                 // image layers
    8869            1 :                 vec![
    8870            1 :                     (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
    8871            1 :                     (
    8872            1 :                         Lsn(0x30),
    8873            1 :                         vec![
    8874            1 :                             (key0, test_img("metadata key 0")),
    8875            1 :                             (key3, test_img("metadata key 3")),
    8876            1 :                         ],
    8877            1 :                     ),
    8878            1 :                 ],
    8879            1 :                 Lsn(0x30),
    8880            1 :             )
    8881            1 :             .await?;
    8882              : 
    8883            1 :         let lsn = Lsn(0x30);
    8884            1 :         let old_lsn = Lsn(0x20);
    8885              : 
    8886            1 :         assert_eq!(
    8887            1 :             get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
    8888            1 :             Some(test_img("metadata key 0"))
    8889              :         );
    8890            1 :         assert_eq!(
    8891            1 :             get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
    8892              :             None,
    8893              :         );
    8894            1 :         assert_eq!(
    8895            1 :             get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
    8896              :             None,
    8897              :         );
    8898            1 :         assert_eq!(
    8899            1 :             get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
    8900            1 :             Some(Bytes::new()),
    8901              :         );
    8902            1 :         assert_eq!(
    8903            1 :             get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
    8904            1 :             Some(Bytes::new()),
    8905              :         );
    8906            1 :         assert_eq!(
    8907            1 :             get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
    8908            1 :             Some(test_img("metadata key 3"))
    8909              :         );
    8910              : 
    8911            2 :         Ok(())
    8912            1 :     }
    8913              : 
    8914              :     #[tokio::test]
    8915            1 :     async fn test_metadata_tombstone_image_creation() {
    8916            1 :         let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
    8917            1 :             .await
    8918            1 :             .unwrap();
    8919            1 :         let (tenant, ctx) = harness.load().await;
    8920            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8921              : 
    8922            1 :         let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
    8923            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    8924            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    8925            1 :         let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
    8926              : 
    8927            1 :         let tline = tenant
    8928            1 :             .create_test_timeline_with_layers(
    8929            1 :                 TIMELINE_ID,
    8930            1 :                 Lsn(0x10),
    8931            1 :                 DEFAULT_PG_VERSION,
    8932            1 :                 &ctx,
    8933            1 :                 Vec::new(), // in-memory layers
    8934            1 :                 // delta layers
    8935            1 :                 vec![
    8936            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8937            1 :                         Lsn(0x10)..Lsn(0x20),
    8938            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    8939            1 :                     ),
    8940            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8941            1 :                         Lsn(0x20)..Lsn(0x30),
    8942            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    8943            1 :                     ),
    8944            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8945            1 :                         Lsn(0x20)..Lsn(0x30),
    8946            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    8947            1 :                     ),
    8948            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    8949            1 :                         Lsn(0x30)..Lsn(0x40),
    8950            1 :                         vec![
    8951            1 :                             (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
    8952            1 :                             (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
    8953            1 :                         ],
    8954            1 :                     ),
    8955            1 :                 ],
    8956            1 :                 // image layers
    8957            1 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    8958            1 :                 Lsn(0x40),
    8959            1 :             )
    8960            1 :             .await
    8961            1 :             .unwrap();
    8962              : 
    8963            1 :         let cancel = CancellationToken::new();
    8964              : 
    8965              :         // Image layer creation happens on the disk_consistent_lsn so we need to force set it now.
    8966            1 :         tline.force_set_disk_consistent_lsn(Lsn(0x40));
    8967            1 :         tline
    8968            1 :             .compact(
    8969            1 :                 &cancel,
    8970            1 :                 {
    8971            1 :                     let mut flags = EnumSet::new();
    8972            1 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    8973            1 :                     flags.insert(CompactFlags::ForceRepartition);
    8974            1 :                     flags
    8975            1 :                 },
    8976            1 :                 &ctx,
    8977            1 :             )
    8978            1 :             .await
    8979            1 :             .unwrap();
    8980              :         // Image layers are created at repartition LSN
    8981            1 :         let images = tline
    8982            1 :             .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
    8983            1 :             .await
    8984            1 :             .unwrap()
    8985            1 :             .into_iter()
    8986            9 :             .filter(|(k, _)| k.is_metadata_key())
    8987            1 :             .collect::<Vec<_>>();
    8988            1 :         assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
    8989            1 :     }
    8990              : 
    8991              :     #[tokio::test]
    8992            1 :     async fn test_metadata_tombstone_empty_image_creation() {
    8993            1 :         let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
    8994            1 :             .await
    8995            1 :             .unwrap();
    8996            1 :         let (tenant, ctx) = harness.load().await;
    8997            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    8998              : 
    8999            1 :         let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
    9000            1 :         let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
    9001              : 
    9002            1 :         let tline = tenant
    9003            1 :             .create_test_timeline_with_layers(
    9004            1 :                 TIMELINE_ID,
    9005            1 :                 Lsn(0x10),
    9006            1 :                 DEFAULT_PG_VERSION,
    9007            1 :                 &ctx,
    9008            1 :                 Vec::new(), // in-memory layers
    9009            1 :                 // delta layers
    9010            1 :                 vec![
    9011            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9012            1 :                         Lsn(0x10)..Lsn(0x20),
    9013            1 :                         vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
    9014            1 :                     ),
    9015            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9016            1 :                         Lsn(0x20)..Lsn(0x30),
    9017            1 :                         vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
    9018            1 :                     ),
    9019            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(
    9020            1 :                         Lsn(0x20)..Lsn(0x30),
    9021            1 :                         vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
    9022            1 :                     ),
    9023            1 :                 ],
    9024            1 :                 // image layers
    9025            1 :                 vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
    9026            1 :                 Lsn(0x30),
    9027            1 :             )
    9028            1 :             .await
    9029            1 :             .unwrap();
    9030              : 
    9031            1 :         let cancel = CancellationToken::new();
    9032              : 
    9033            1 :         tline
    9034            1 :             .compact(
    9035            1 :                 &cancel,
    9036            1 :                 {
    9037            1 :                     let mut flags = EnumSet::new();
    9038            1 :                     flags.insert(CompactFlags::ForceImageLayerCreation);
    9039            1 :                     flags.insert(CompactFlags::ForceRepartition);
    9040            1 :                     flags
    9041            1 :                 },
    9042            1 :                 &ctx,
    9043            1 :             )
    9044            1 :             .await
    9045            1 :             .unwrap();
    9046              : 
    9047              :         // Image layers are created at last_record_lsn
    9048            1 :         let images = tline
    9049            1 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    9050            1 :             .await
    9051            1 :             .unwrap()
    9052            1 :             .into_iter()
    9053            7 :             .filter(|(k, _)| k.is_metadata_key())
    9054            1 :             .collect::<Vec<_>>();
    9055            1 :         assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
    9056            1 :     }
    9057              : 
    9058              :     #[tokio::test]
    9059            1 :     async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
    9060            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
    9061            1 :         let (tenant, ctx) = harness.load().await;
    9062            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    9063              : 
    9064           51 :         fn get_key(id: u32) -> Key {
    9065              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9066           51 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9067           51 :             key.field6 = id;
    9068           51 :             key
    9069           51 :         }
    9070              : 
    9071              :         // We create
    9072              :         // - one bottom-most image layer,
    9073              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9074              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9075              :         // - a delta layer D3 above the horizon.
    9076              :         //
    9077              :         //                             | D3 |
    9078              :         //  | D1 |
    9079              :         // -|    |-- gc horizon -----------------
    9080              :         //  |    |                | D2 |
    9081              :         // --------- img layer ------------------
    9082              :         //
    9083              :         // What we should expact from this compaction is:
    9084              :         //                             | D3 |
    9085              :         //  | Part of D1 |
    9086              :         // --------- img layer with D1+D2 at GC horizon------------------
    9087              : 
    9088              :         // img layer at 0x10
    9089            1 :         let img_layer = (0..10)
    9090           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9091            1 :             .collect_vec();
    9092              : 
    9093            1 :         let delta1 = vec![
    9094            1 :             (
    9095            1 :                 get_key(1),
    9096            1 :                 Lsn(0x20),
    9097            1 :                 Value::Image(Bytes::from("value 1@0x20")),
    9098            1 :             ),
    9099            1 :             (
    9100            1 :                 get_key(2),
    9101            1 :                 Lsn(0x30),
    9102            1 :                 Value::Image(Bytes::from("value 2@0x30")),
    9103            1 :             ),
    9104            1 :             (
    9105            1 :                 get_key(3),
    9106            1 :                 Lsn(0x40),
    9107            1 :                 Value::Image(Bytes::from("value 3@0x40")),
    9108            1 :             ),
    9109              :         ];
    9110            1 :         let delta2 = vec![
    9111            1 :             (
    9112            1 :                 get_key(5),
    9113            1 :                 Lsn(0x20),
    9114            1 :                 Value::Image(Bytes::from("value 5@0x20")),
    9115            1 :             ),
    9116            1 :             (
    9117            1 :                 get_key(6),
    9118            1 :                 Lsn(0x20),
    9119            1 :                 Value::Image(Bytes::from("value 6@0x20")),
    9120            1 :             ),
    9121              :         ];
    9122            1 :         let delta3 = vec![
    9123            1 :             (
    9124            1 :                 get_key(8),
    9125            1 :                 Lsn(0x48),
    9126            1 :                 Value::Image(Bytes::from("value 8@0x48")),
    9127            1 :             ),
    9128            1 :             (
    9129            1 :                 get_key(9),
    9130            1 :                 Lsn(0x48),
    9131            1 :                 Value::Image(Bytes::from("value 9@0x48")),
    9132            1 :             ),
    9133              :         ];
    9134              : 
    9135            1 :         let tline = tenant
    9136            1 :             .create_test_timeline_with_layers(
    9137            1 :                 TIMELINE_ID,
    9138            1 :                 Lsn(0x10),
    9139            1 :                 DEFAULT_PG_VERSION,
    9140            1 :                 &ctx,
    9141            1 :                 Vec::new(), // in-memory layers
    9142            1 :                 vec![
    9143            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
    9144            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
    9145            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
    9146            1 :                 ], // delta layers
    9147            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
    9148            1 :                 Lsn(0x50),
    9149            1 :             )
    9150            1 :             .await?;
    9151              :         {
    9152            1 :             tline
    9153            1 :                 .applied_gc_cutoff_lsn
    9154            1 :                 .lock_for_write()
    9155            1 :                 .store_and_unlock(Lsn(0x30))
    9156            1 :                 .wait()
    9157            1 :                 .await;
    9158              :             // Update GC info
    9159            1 :             let mut guard = tline.gc_info.write().unwrap();
    9160            1 :             guard.cutoffs.time = Some(Lsn(0x30));
    9161            1 :             guard.cutoffs.space = Lsn(0x30);
    9162              :         }
    9163              : 
    9164            1 :         let expected_result = [
    9165            1 :             Bytes::from_static(b"value 0@0x10"),
    9166            1 :             Bytes::from_static(b"value 1@0x20"),
    9167            1 :             Bytes::from_static(b"value 2@0x30"),
    9168            1 :             Bytes::from_static(b"value 3@0x40"),
    9169            1 :             Bytes::from_static(b"value 4@0x10"),
    9170            1 :             Bytes::from_static(b"value 5@0x20"),
    9171            1 :             Bytes::from_static(b"value 6@0x20"),
    9172            1 :             Bytes::from_static(b"value 7@0x10"),
    9173            1 :             Bytes::from_static(b"value 8@0x48"),
    9174            1 :             Bytes::from_static(b"value 9@0x48"),
    9175            1 :         ];
    9176              : 
    9177           10 :         for (idx, expected) in expected_result.iter().enumerate() {
    9178           10 :             assert_eq!(
    9179           10 :                 tline
    9180           10 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9181           10 :                     .await
    9182           10 :                     .unwrap(),
    9183              :                 expected
    9184              :             );
    9185              :         }
    9186              : 
    9187            1 :         let cancel = CancellationToken::new();
    9188            1 :         tline
    9189            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9190            1 :             .await
    9191            1 :             .unwrap();
    9192              : 
    9193           10 :         for (idx, expected) in expected_result.iter().enumerate() {
    9194           10 :             assert_eq!(
    9195           10 :                 tline
    9196           10 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9197           10 :                     .await
    9198           10 :                     .unwrap(),
    9199              :                 expected
    9200              :             );
    9201              :         }
    9202              : 
    9203              :         // Check if the image layer at the GC horizon contains exactly what we want
    9204            1 :         let image_at_gc_horizon = tline
    9205            1 :             .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
    9206            1 :             .await
    9207            1 :             .unwrap()
    9208            1 :             .into_iter()
    9209           17 :             .filter(|(k, _)| k.is_metadata_key())
    9210            1 :             .collect::<Vec<_>>();
    9211              : 
    9212            1 :         assert_eq!(image_at_gc_horizon.len(), 10);
    9213            1 :         let expected_result = [
    9214            1 :             Bytes::from_static(b"value 0@0x10"),
    9215            1 :             Bytes::from_static(b"value 1@0x20"),
    9216            1 :             Bytes::from_static(b"value 2@0x30"),
    9217            1 :             Bytes::from_static(b"value 3@0x10"),
    9218            1 :             Bytes::from_static(b"value 4@0x10"),
    9219            1 :             Bytes::from_static(b"value 5@0x20"),
    9220            1 :             Bytes::from_static(b"value 6@0x20"),
    9221            1 :             Bytes::from_static(b"value 7@0x10"),
    9222            1 :             Bytes::from_static(b"value 8@0x10"),
    9223            1 :             Bytes::from_static(b"value 9@0x10"),
    9224            1 :         ];
    9225           11 :         for idx in 0..10 {
    9226           10 :             assert_eq!(
    9227           10 :                 image_at_gc_horizon[idx],
    9228           10 :                 (get_key(idx as u32), expected_result[idx].clone())
    9229              :             );
    9230              :         }
    9231              : 
    9232              :         // Check if old layers are removed / new layers have the expected LSN
    9233            1 :         let all_layers = inspect_and_sort(&tline, None).await;
    9234            1 :         assert_eq!(
    9235              :             all_layers,
    9236            1 :             vec![
    9237              :                 // Image layer at GC horizon
    9238            1 :                 PersistentLayerKey {
    9239            1 :                     key_range: Key::MIN..Key::MAX,
    9240            1 :                     lsn_range: Lsn(0x30)..Lsn(0x31),
    9241            1 :                     is_delta: false
    9242            1 :                 },
    9243              :                 // The delta layer below the horizon
    9244            1 :                 PersistentLayerKey {
    9245            1 :                     key_range: get_key(3)..get_key(4),
    9246            1 :                     lsn_range: Lsn(0x30)..Lsn(0x48),
    9247            1 :                     is_delta: true
    9248            1 :                 },
    9249              :                 // The delta3 layer that should not be picked for the compaction
    9250            1 :                 PersistentLayerKey {
    9251            1 :                     key_range: get_key(8)..get_key(10),
    9252            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
    9253            1 :                     is_delta: true
    9254            1 :                 }
    9255              :             ]
    9256              :         );
    9257              : 
    9258              :         // increase GC horizon and compact again
    9259              :         {
    9260            1 :             tline
    9261            1 :                 .applied_gc_cutoff_lsn
    9262            1 :                 .lock_for_write()
    9263            1 :                 .store_and_unlock(Lsn(0x40))
    9264            1 :                 .wait()
    9265            1 :                 .await;
    9266              :             // Update GC info
    9267            1 :             let mut guard = tline.gc_info.write().unwrap();
    9268            1 :             guard.cutoffs.time = Some(Lsn(0x40));
    9269            1 :             guard.cutoffs.space = Lsn(0x40);
    9270              :         }
    9271            1 :         tline
    9272            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9273            1 :             .await
    9274            1 :             .unwrap();
    9275              : 
    9276            2 :         Ok(())
    9277            1 :     }
    9278              : 
    9279              :     #[cfg(feature = "testing")]
    9280              :     #[tokio::test]
    9281            1 :     async fn test_neon_test_record() -> anyhow::Result<()> {
    9282            1 :         let harness = TenantHarness::create("test_neon_test_record").await?;
    9283            1 :         let (tenant, ctx) = harness.load().await;
    9284              : 
    9285           17 :         fn get_key(id: u32) -> Key {
    9286              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9287           17 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9288           17 :             key.field6 = id;
    9289           17 :             key
    9290           17 :         }
    9291              : 
    9292            1 :         let delta1 = vec![
    9293            1 :             (
    9294            1 :                 get_key(1),
    9295            1 :                 Lsn(0x20),
    9296            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9297            1 :             ),
    9298            1 :             (
    9299            1 :                 get_key(1),
    9300            1 :                 Lsn(0x30),
    9301            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9302            1 :             ),
    9303            1 :             (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
    9304            1 :             (
    9305            1 :                 get_key(2),
    9306            1 :                 Lsn(0x20),
    9307            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
    9308            1 :             ),
    9309            1 :             (
    9310            1 :                 get_key(2),
    9311            1 :                 Lsn(0x30),
    9312            1 :                 Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
    9313            1 :             ),
    9314            1 :             (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
    9315            1 :             (
    9316            1 :                 get_key(3),
    9317            1 :                 Lsn(0x20),
    9318            1 :                 Value::WalRecord(NeonWalRecord::wal_clear("c")),
    9319            1 :             ),
    9320            1 :             (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
    9321            1 :             (
    9322            1 :                 get_key(4),
    9323            1 :                 Lsn(0x20),
    9324            1 :                 Value::WalRecord(NeonWalRecord::wal_init("i")),
    9325            1 :             ),
    9326            1 :             (
    9327            1 :                 get_key(4),
    9328            1 :                 Lsn(0x30),
    9329            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "i")),
    9330            1 :             ),
    9331            1 :             (
    9332            1 :                 get_key(5),
    9333            1 :                 Lsn(0x20),
    9334            1 :                 Value::WalRecord(NeonWalRecord::wal_init("1")),
    9335            1 :             ),
    9336            1 :             (
    9337            1 :                 get_key(5),
    9338            1 :                 Lsn(0x30),
    9339            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "2")),
    9340            1 :             ),
    9341              :         ];
    9342            1 :         let image1 = vec![(get_key(1), "0x10".into())];
    9343              : 
    9344            1 :         let tline = tenant
    9345            1 :             .create_test_timeline_with_layers(
    9346            1 :                 TIMELINE_ID,
    9347            1 :                 Lsn(0x10),
    9348            1 :                 DEFAULT_PG_VERSION,
    9349            1 :                 &ctx,
    9350            1 :                 Vec::new(), // in-memory layers
    9351            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
    9352            1 :                     Lsn(0x10)..Lsn(0x40),
    9353            1 :                     delta1,
    9354            1 :                 )], // delta layers
    9355            1 :                 vec![(Lsn(0x10), image1)], // image layers
    9356            1 :                 Lsn(0x50),
    9357            1 :             )
    9358            1 :             .await?;
    9359              : 
    9360            1 :         assert_eq!(
    9361            1 :             tline.get(get_key(1), Lsn(0x50), &ctx).await?,
    9362            1 :             Bytes::from_static(b"0x10,0x20,0x30")
    9363              :         );
    9364            1 :         assert_eq!(
    9365            1 :             tline.get(get_key(2), Lsn(0x50), &ctx).await?,
    9366            1 :             Bytes::from_static(b"0x10,0x20,0x30")
    9367              :         );
    9368              : 
    9369              :         // Need to remove the limit of "Neon WAL redo requires base image".
    9370              : 
    9371            1 :         assert_eq!(
    9372            1 :             tline.get(get_key(3), Lsn(0x50), &ctx).await?,
    9373            1 :             Bytes::from_static(b"c")
    9374              :         );
    9375            1 :         assert_eq!(
    9376            1 :             tline.get(get_key(4), Lsn(0x50), &ctx).await?,
    9377            1 :             Bytes::from_static(b"ij")
    9378              :         );
    9379              : 
    9380              :         // Manual testing required: currently, read errors will panic the process in debug mode. So we
    9381              :         // cannot enable this assertion in the unit test.
    9382              :         // assert!(tline.get(get_key(5), Lsn(0x50), &ctx).await.is_err());
    9383              : 
    9384            2 :         Ok(())
    9385            1 :     }
    9386              : 
    9387              :     #[tokio::test(start_paused = true)]
    9388            1 :     async fn test_lsn_lease() -> anyhow::Result<()> {
    9389            1 :         let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
    9390            1 :             .await
    9391            1 :             .unwrap()
    9392            1 :             .load()
    9393            1 :             .await;
    9394              :         // Advance to the lsn lease deadline so that GC is not blocked by
    9395              :         // initial transition into AttachedSingle.
    9396            1 :         tokio::time::advance(tenant.get_lsn_lease_length()).await;
    9397            1 :         tokio::time::resume();
    9398            1 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9399              : 
    9400            1 :         let end_lsn = Lsn(0x100);
    9401            1 :         let image_layers = (0x20..=0x90)
    9402            1 :             .step_by(0x10)
    9403            8 :             .map(|n| (Lsn(n), vec![(key, test_img(&format!("data key at {n:x}")))]))
    9404            1 :             .collect();
    9405              : 
    9406            1 :         let timeline = tenant
    9407            1 :             .create_test_timeline_with_layers(
    9408            1 :                 TIMELINE_ID,
    9409            1 :                 Lsn(0x10),
    9410            1 :                 DEFAULT_PG_VERSION,
    9411            1 :                 &ctx,
    9412            1 :                 Vec::new(), // in-memory layers
    9413            1 :                 Vec::new(),
    9414            1 :                 image_layers,
    9415            1 :                 end_lsn,
    9416            1 :             )
    9417            1 :             .await?;
    9418              : 
    9419            1 :         let leased_lsns = [0x30, 0x50, 0x70];
    9420            1 :         let mut leases = Vec::new();
    9421            3 :         leased_lsns.iter().for_each(|n| {
    9422            3 :             leases.push(
    9423            3 :                 timeline
    9424            3 :                     .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
    9425            3 :                     .expect("lease request should succeed"),
    9426              :             );
    9427            3 :         });
    9428              : 
    9429            1 :         let updated_lease_0 = timeline
    9430            1 :             .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
    9431            1 :             .expect("lease renewal should succeed");
    9432            1 :         assert_eq!(
    9433            1 :             updated_lease_0.valid_until, leases[0].valid_until,
    9434            0 :             " Renewing with shorter lease should not change the lease."
    9435              :         );
    9436              : 
    9437            1 :         let updated_lease_1 = timeline
    9438            1 :             .renew_lsn_lease(
    9439            1 :                 Lsn(leased_lsns[1]),
    9440            1 :                 timeline.get_lsn_lease_length() * 2,
    9441            1 :                 &ctx,
    9442            1 :             )
    9443            1 :             .expect("lease renewal should succeed");
    9444            1 :         assert!(
    9445            1 :             updated_lease_1.valid_until > leases[1].valid_until,
    9446            0 :             "Renewing with a long lease should renew lease with later expiration time."
    9447              :         );
    9448              : 
    9449              :         // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
    9450            1 :         info!(
    9451            0 :             "applied_gc_cutoff_lsn: {}",
    9452            0 :             *timeline.get_applied_gc_cutoff_lsn()
    9453              :         );
    9454            1 :         timeline.force_set_disk_consistent_lsn(end_lsn);
    9455              : 
    9456            1 :         let res = tenant
    9457            1 :             .gc_iteration(
    9458            1 :                 Some(TIMELINE_ID),
    9459            1 :                 0,
    9460            1 :                 Duration::ZERO,
    9461            1 :                 &CancellationToken::new(),
    9462            1 :                 &ctx,
    9463            1 :             )
    9464            1 :             .await
    9465            1 :             .unwrap();
    9466              : 
    9467              :         // Keeping everything <= Lsn(0x80) b/c leases:
    9468              :         // 0/10: initdb layer
    9469              :         // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
    9470            1 :         assert_eq!(res.layers_needed_by_leases, 7);
    9471              :         // Keeping 0/90 b/c it is the latest layer.
    9472            1 :         assert_eq!(res.layers_not_updated, 1);
    9473              :         // Removed 0/80.
    9474            1 :         assert_eq!(res.layers_removed, 1);
    9475              : 
    9476              :         // Make lease on a already GC-ed LSN.
    9477              :         // 0/80 does not have a valid lease + is below latest_gc_cutoff
    9478            1 :         assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
    9479            1 :         timeline
    9480            1 :             .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
    9481            1 :             .expect_err("lease request on GC-ed LSN should fail");
    9482              : 
    9483              :         // Should still be able to renew a currently valid lease
    9484              :         // Assumption: original lease to is still valid for 0/50.
    9485              :         // (use `Timeline::init_lsn_lease` for testing so it always does validation)
    9486            1 :         timeline
    9487            1 :             .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
    9488            1 :             .expect("lease renewal with validation should succeed");
    9489              : 
    9490            2 :         Ok(())
    9491            1 :     }
    9492              : 
    9493              :     #[tokio::test]
    9494            1 :     async fn test_failed_flush_should_not_update_disk_consistent_lsn() -> anyhow::Result<()> {
    9495              :         //
    9496              :         // Setup
    9497              :         //
    9498            1 :         let harness = TenantHarness::create_custom(
    9499            1 :             "test_failed_flush_should_not_upload_disk_consistent_lsn",
    9500            1 :             pageserver_api::models::TenantConfig::default(),
    9501            1 :             TenantId::generate(),
    9502            1 :             ShardIdentity::new(ShardNumber(0), ShardCount(4), ShardStripeSize(128)).unwrap(),
    9503            1 :             Generation::new(1),
    9504            1 :         )
    9505            1 :         .await?;
    9506            1 :         let (tenant, ctx) = harness.load().await;
    9507              : 
    9508            1 :         let timeline = tenant
    9509            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9510            1 :             .await?;
    9511            1 :         assert_eq!(timeline.get_shard_identity().count, ShardCount(4));
    9512            1 :         let mut writer = timeline.writer().await;
    9513            1 :         writer
    9514            1 :             .put(
    9515            1 :                 *TEST_KEY,
    9516            1 :                 Lsn(0x20),
    9517            1 :                 &Value::Image(test_img("foo at 0x20")),
    9518            1 :                 &ctx,
    9519            1 :             )
    9520            1 :             .await?;
    9521            1 :         writer.finish_write(Lsn(0x20));
    9522            1 :         drop(writer);
    9523            1 :         timeline.freeze_and_flush().await.unwrap();
    9524              : 
    9525            1 :         timeline.remote_client.wait_completion().await.unwrap();
    9526            1 :         let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
    9527            1 :         let remote_consistent_lsn = timeline.get_remote_consistent_lsn_projected();
    9528            1 :         assert_eq!(Some(disk_consistent_lsn), remote_consistent_lsn);
    9529              : 
    9530              :         //
    9531              :         // Test
    9532              :         //
    9533              : 
    9534            1 :         let mut writer = timeline.writer().await;
    9535            1 :         writer
    9536            1 :             .put(
    9537            1 :                 *TEST_KEY,
    9538            1 :                 Lsn(0x30),
    9539            1 :                 &Value::Image(test_img("foo at 0x30")),
    9540            1 :                 &ctx,
    9541            1 :             )
    9542            1 :             .await?;
    9543            1 :         writer.finish_write(Lsn(0x30));
    9544            1 :         drop(writer);
    9545              : 
    9546            1 :         fail::cfg(
    9547              :             "flush-layer-before-update-remote-consistent-lsn",
    9548            1 :             "return()",
    9549              :         )
    9550            1 :         .unwrap();
    9551              : 
    9552            1 :         let flush_res = timeline.freeze_and_flush().await;
    9553              :         // if flush failed, the disk/remote consistent LSN should not be updated
    9554            1 :         assert!(flush_res.is_err());
    9555            1 :         assert_eq!(disk_consistent_lsn, timeline.get_disk_consistent_lsn());
    9556            1 :         assert_eq!(
    9557              :             remote_consistent_lsn,
    9558            1 :             timeline.get_remote_consistent_lsn_projected()
    9559              :         );
    9560              : 
    9561            2 :         Ok(())
    9562            1 :     }
    9563              : 
    9564              :     #[cfg(feature = "testing")]
    9565              :     #[tokio::test]
    9566            1 :     async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
    9567            2 :         test_simple_bottom_most_compaction_deltas_helper(
    9568            2 :             "test_simple_bottom_most_compaction_deltas_1",
    9569            2 :             false,
    9570            2 :         )
    9571            2 :         .await
    9572            1 :     }
    9573              : 
    9574              :     #[cfg(feature = "testing")]
    9575              :     #[tokio::test]
    9576            1 :     async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
    9577            2 :         test_simple_bottom_most_compaction_deltas_helper(
    9578            2 :             "test_simple_bottom_most_compaction_deltas_2",
    9579            2 :             true,
    9580            2 :         )
    9581            2 :         .await
    9582            1 :     }
    9583              : 
    9584              :     #[cfg(feature = "testing")]
    9585            2 :     async fn test_simple_bottom_most_compaction_deltas_helper(
    9586            2 :         test_name: &'static str,
    9587            2 :         use_delta_bottom_layer: bool,
    9588            2 :     ) -> anyhow::Result<()> {
    9589            2 :         let harness = TenantHarness::create(test_name).await?;
    9590            2 :         let (tenant, ctx) = harness.load().await;
    9591              : 
    9592          138 :         fn get_key(id: u32) -> Key {
    9593              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
    9594          138 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
    9595          138 :             key.field6 = id;
    9596          138 :             key
    9597          138 :         }
    9598              : 
    9599              :         // We create
    9600              :         // - one bottom-most image layer,
    9601              :         // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
    9602              :         // - a delta layer D2 crossing the GC horizon with data only below the horizon,
    9603              :         // - a delta layer D3 above the horizon.
    9604              :         //
    9605              :         //                             | D3 |
    9606              :         //  | D1 |
    9607              :         // -|    |-- gc horizon -----------------
    9608              :         //  |    |                | D2 |
    9609              :         // --------- img layer ------------------
    9610              :         //
    9611              :         // What we should expact from this compaction is:
    9612              :         //                             | D3 |
    9613              :         //  | Part of D1 |
    9614              :         // --------- img layer with D1+D2 at GC horizon------------------
    9615              : 
    9616              :         // img layer at 0x10
    9617            2 :         let img_layer = (0..10)
    9618           20 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
    9619            2 :             .collect_vec();
    9620              :         // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
    9621            2 :         let delta4 = (0..10)
    9622           20 :             .map(|id| {
    9623           20 :                 (
    9624           20 :                     get_key(id),
    9625           20 :                     Lsn(0x08),
    9626           20 :                     Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
    9627           20 :                 )
    9628           20 :             })
    9629            2 :             .collect_vec();
    9630              : 
    9631            2 :         let delta1 = vec![
    9632            2 :             (
    9633            2 :                 get_key(1),
    9634            2 :                 Lsn(0x20),
    9635            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9636            2 :             ),
    9637            2 :             (
    9638            2 :                 get_key(2),
    9639            2 :                 Lsn(0x30),
    9640            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9641            2 :             ),
    9642            2 :             (
    9643            2 :                 get_key(3),
    9644            2 :                 Lsn(0x28),
    9645            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
    9646            2 :             ),
    9647            2 :             (
    9648            2 :                 get_key(3),
    9649            2 :                 Lsn(0x30),
    9650            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
    9651            2 :             ),
    9652            2 :             (
    9653            2 :                 get_key(3),
    9654            2 :                 Lsn(0x40),
    9655            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
    9656            2 :             ),
    9657              :         ];
    9658            2 :         let delta2 = vec![
    9659            2 :             (
    9660            2 :                 get_key(5),
    9661            2 :                 Lsn(0x20),
    9662            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9663            2 :             ),
    9664            2 :             (
    9665            2 :                 get_key(6),
    9666            2 :                 Lsn(0x20),
    9667            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
    9668            2 :             ),
    9669              :         ];
    9670            2 :         let delta3 = vec![
    9671            2 :             (
    9672            2 :                 get_key(8),
    9673            2 :                 Lsn(0x48),
    9674            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9675            2 :             ),
    9676            2 :             (
    9677            2 :                 get_key(9),
    9678            2 :                 Lsn(0x48),
    9679            2 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
    9680            2 :             ),
    9681              :         ];
    9682              : 
    9683            2 :         let tline = if use_delta_bottom_layer {
    9684            1 :             tenant
    9685            1 :                 .create_test_timeline_with_layers(
    9686            1 :                     TIMELINE_ID,
    9687            1 :                     Lsn(0x08),
    9688            1 :                     DEFAULT_PG_VERSION,
    9689            1 :                     &ctx,
    9690            1 :                     Vec::new(), // in-memory layers
    9691            1 :                     vec![
    9692            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9693            1 :                             Lsn(0x08)..Lsn(0x10),
    9694            1 :                             delta4,
    9695            1 :                         ),
    9696            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9697            1 :                             Lsn(0x20)..Lsn(0x48),
    9698            1 :                             delta1,
    9699            1 :                         ),
    9700            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9701            1 :                             Lsn(0x20)..Lsn(0x48),
    9702            1 :                             delta2,
    9703            1 :                         ),
    9704            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9705            1 :                             Lsn(0x48)..Lsn(0x50),
    9706            1 :                             delta3,
    9707            1 :                         ),
    9708            1 :                     ], // delta layers
    9709            1 :                     vec![],     // image layers
    9710            1 :                     Lsn(0x50),
    9711            1 :                 )
    9712            1 :                 .await?
    9713              :         } else {
    9714            1 :             tenant
    9715            1 :                 .create_test_timeline_with_layers(
    9716            1 :                     TIMELINE_ID,
    9717            1 :                     Lsn(0x10),
    9718            1 :                     DEFAULT_PG_VERSION,
    9719            1 :                     &ctx,
    9720            1 :                     Vec::new(), // in-memory layers
    9721            1 :                     vec![
    9722            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9723            1 :                             Lsn(0x10)..Lsn(0x48),
    9724            1 :                             delta1,
    9725            1 :                         ),
    9726            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9727            1 :                             Lsn(0x10)..Lsn(0x48),
    9728            1 :                             delta2,
    9729            1 :                         ),
    9730            1 :                         DeltaLayerTestDesc::new_with_inferred_key_range(
    9731            1 :                             Lsn(0x48)..Lsn(0x50),
    9732            1 :                             delta3,
    9733            1 :                         ),
    9734            1 :                     ], // delta layers
    9735            1 :                     vec![(Lsn(0x10), img_layer)], // image layers
    9736            1 :                     Lsn(0x50),
    9737            1 :                 )
    9738            1 :                 .await?
    9739              :         };
    9740              :         {
    9741            2 :             tline
    9742            2 :                 .applied_gc_cutoff_lsn
    9743            2 :                 .lock_for_write()
    9744            2 :                 .store_and_unlock(Lsn(0x30))
    9745            2 :                 .wait()
    9746            2 :                 .await;
    9747              :             // Update GC info
    9748            2 :             let mut guard = tline.gc_info.write().unwrap();
    9749            2 :             *guard = GcInfo {
    9750            2 :                 retain_lsns: vec![],
    9751            2 :                 cutoffs: GcCutoffs {
    9752            2 :                     time: Some(Lsn(0x30)),
    9753            2 :                     space: Lsn(0x30),
    9754            2 :                 },
    9755            2 :                 leases: Default::default(),
    9756            2 :                 within_ancestor_pitr: false,
    9757            2 :             };
    9758              :         }
    9759              : 
    9760            2 :         let expected_result = [
    9761            2 :             Bytes::from_static(b"value 0@0x10"),
    9762            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9763            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9764            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
    9765            2 :             Bytes::from_static(b"value 4@0x10"),
    9766            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9767            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9768            2 :             Bytes::from_static(b"value 7@0x10"),
    9769            2 :             Bytes::from_static(b"value 8@0x10@0x48"),
    9770            2 :             Bytes::from_static(b"value 9@0x10@0x48"),
    9771            2 :         ];
    9772              : 
    9773            2 :         let expected_result_at_gc_horizon = [
    9774            2 :             Bytes::from_static(b"value 0@0x10"),
    9775            2 :             Bytes::from_static(b"value 1@0x10@0x20"),
    9776            2 :             Bytes::from_static(b"value 2@0x10@0x30"),
    9777            2 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
    9778            2 :             Bytes::from_static(b"value 4@0x10"),
    9779            2 :             Bytes::from_static(b"value 5@0x10@0x20"),
    9780            2 :             Bytes::from_static(b"value 6@0x10@0x20"),
    9781            2 :             Bytes::from_static(b"value 7@0x10"),
    9782            2 :             Bytes::from_static(b"value 8@0x10"),
    9783            2 :             Bytes::from_static(b"value 9@0x10"),
    9784            2 :         ];
    9785              : 
    9786           22 :         for idx in 0..10 {
    9787           20 :             assert_eq!(
    9788           20 :                 tline
    9789           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9790           20 :                     .await
    9791           20 :                     .unwrap(),
    9792           20 :                 &expected_result[idx]
    9793              :             );
    9794           20 :             assert_eq!(
    9795           20 :                 tline
    9796           20 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9797           20 :                     .await
    9798           20 :                     .unwrap(),
    9799           20 :                 &expected_result_at_gc_horizon[idx]
    9800              :             );
    9801              :         }
    9802              : 
    9803            2 :         let cancel = CancellationToken::new();
    9804            2 :         tline
    9805            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9806            2 :             .await
    9807            2 :             .unwrap();
    9808              : 
    9809           22 :         for idx in 0..10 {
    9810           20 :             assert_eq!(
    9811           20 :                 tline
    9812           20 :                     .get(get_key(idx as u32), Lsn(0x50), &ctx)
    9813           20 :                     .await
    9814           20 :                     .unwrap(),
    9815           20 :                 &expected_result[idx]
    9816              :             );
    9817           20 :             assert_eq!(
    9818           20 :                 tline
    9819           20 :                     .get(get_key(idx as u32), Lsn(0x30), &ctx)
    9820           20 :                     .await
    9821           20 :                     .unwrap(),
    9822           20 :                 &expected_result_at_gc_horizon[idx]
    9823              :             );
    9824              :         }
    9825              : 
    9826              :         // increase GC horizon and compact again
    9827              :         {
    9828            2 :             tline
    9829            2 :                 .applied_gc_cutoff_lsn
    9830            2 :                 .lock_for_write()
    9831            2 :                 .store_and_unlock(Lsn(0x40))
    9832            2 :                 .wait()
    9833            2 :                 .await;
    9834              :             // Update GC info
    9835            2 :             let mut guard = tline.gc_info.write().unwrap();
    9836            2 :             guard.cutoffs.time = Some(Lsn(0x40));
    9837            2 :             guard.cutoffs.space = Lsn(0x40);
    9838              :         }
    9839            2 :         tline
    9840            2 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
    9841            2 :             .await
    9842            2 :             .unwrap();
    9843              : 
    9844            2 :         Ok(())
    9845            2 :     }
    9846              : 
    9847              :     #[cfg(feature = "testing")]
    9848              :     #[tokio::test]
    9849            1 :     async fn test_generate_key_retention() -> anyhow::Result<()> {
    9850            1 :         let harness = TenantHarness::create("test_generate_key_retention").await?;
    9851            1 :         let (tenant, ctx) = harness.load().await;
    9852            1 :         let tline = tenant
    9853            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    9854            1 :             .await?;
    9855            1 :         tline.force_advance_lsn(Lsn(0x70));
    9856            1 :         let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
    9857            1 :         let history = vec![
    9858            1 :             (
    9859            1 :                 key,
    9860            1 :                 Lsn(0x10),
    9861            1 :                 Value::WalRecord(NeonWalRecord::wal_init("0x10")),
    9862            1 :             ),
    9863            1 :             (
    9864            1 :                 key,
    9865            1 :                 Lsn(0x20),
    9866            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9867            1 :             ),
    9868            1 :             (
    9869            1 :                 key,
    9870            1 :                 Lsn(0x30),
    9871            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9872            1 :             ),
    9873            1 :             (
    9874            1 :                 key,
    9875            1 :                 Lsn(0x40),
    9876            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9877            1 :             ),
    9878            1 :             (
    9879            1 :                 key,
    9880            1 :                 Lsn(0x50),
    9881            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
    9882            1 :             ),
    9883            1 :             (
    9884            1 :                 key,
    9885            1 :                 Lsn(0x60),
    9886            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9887            1 :             ),
    9888            1 :             (
    9889            1 :                 key,
    9890            1 :                 Lsn(0x70),
    9891            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9892            1 :             ),
    9893            1 :             (
    9894            1 :                 key,
    9895            1 :                 Lsn(0x80),
    9896            1 :                 Value::Image(Bytes::copy_from_slice(
    9897            1 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9898            1 :                 )),
    9899            1 :             ),
    9900            1 :             (
    9901            1 :                 key,
    9902            1 :                 Lsn(0x90),
    9903            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9904            1 :             ),
    9905              :         ];
    9906            1 :         let res = tline
    9907            1 :             .generate_key_retention(
    9908            1 :                 key,
    9909            1 :                 &history,
    9910            1 :                 Lsn(0x60),
    9911            1 :                 &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
    9912            1 :                 3,
    9913            1 :                 None,
    9914            1 :                 true,
    9915            1 :             )
    9916            1 :             .await
    9917            1 :             .unwrap();
    9918            1 :         let expected_res = KeyHistoryRetention {
    9919            1 :             below_horizon: vec![
    9920            1 :                 (
    9921            1 :                     Lsn(0x20),
    9922            1 :                     KeyLogAtLsn(vec![(
    9923            1 :                         Lsn(0x20),
    9924            1 :                         Value::Image(Bytes::from_static(b"0x10;0x20")),
    9925            1 :                     )]),
    9926            1 :                 ),
    9927            1 :                 (
    9928            1 :                     Lsn(0x40),
    9929            1 :                     KeyLogAtLsn(vec![
    9930            1 :                         (
    9931            1 :                             Lsn(0x30),
    9932            1 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
    9933            1 :                         ),
    9934            1 :                         (
    9935            1 :                             Lsn(0x40),
    9936            1 :                             Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
    9937            1 :                         ),
    9938            1 :                     ]),
    9939            1 :                 ),
    9940            1 :                 (
    9941            1 :                     Lsn(0x50),
    9942            1 :                     KeyLogAtLsn(vec![(
    9943            1 :                         Lsn(0x50),
    9944            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
    9945            1 :                     )]),
    9946            1 :                 ),
    9947            1 :                 (
    9948            1 :                     Lsn(0x60),
    9949            1 :                     KeyLogAtLsn(vec![(
    9950            1 :                         Lsn(0x60),
    9951            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
    9952            1 :                     )]),
    9953            1 :                 ),
    9954            1 :             ],
    9955            1 :             above_horizon: KeyLogAtLsn(vec![
    9956            1 :                 (
    9957            1 :                     Lsn(0x70),
    9958            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
    9959            1 :                 ),
    9960            1 :                 (
    9961            1 :                     Lsn(0x80),
    9962            1 :                     Value::Image(Bytes::copy_from_slice(
    9963            1 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
    9964            1 :                     )),
    9965            1 :                 ),
    9966            1 :                 (
    9967            1 :                     Lsn(0x90),
    9968            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
    9969            1 :                 ),
    9970            1 :             ]),
    9971            1 :         };
    9972            1 :         assert_eq!(res, expected_res);
    9973              : 
    9974              :         // We expect GC-compaction to run with the original GC. This would create a situation that
    9975              :         // the original GC algorithm removes some delta layers b/c there are full image coverage,
    9976              :         // therefore causing some keys to have an incomplete history below the lowest retain LSN.
    9977              :         // For example, we have
    9978              :         // ```plain
    9979              :         // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
    9980              :         // ```
    9981              :         // Now the GC horizon moves up, and we have
    9982              :         // ```plain
    9983              :         // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
    9984              :         // ```
    9985              :         // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
    9986              :         // We will end up with
    9987              :         // ```plain
    9988              :         // delta @ 0x30, image @ 0x40 (gc_horizon)
    9989              :         // ```
    9990              :         // Now we run the GC-compaction, and this key does not have a full history.
    9991              :         // We should be able to handle this partial history and drop everything before the
    9992              :         // gc_horizon image.
    9993              : 
    9994            1 :         let history = vec![
    9995            1 :             (
    9996            1 :                 key,
    9997            1 :                 Lsn(0x20),
    9998            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
    9999            1 :             ),
   10000            1 :             (
   10001            1 :                 key,
   10002            1 :                 Lsn(0x30),
   10003            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
   10004            1 :             ),
   10005            1 :             (
   10006            1 :                 key,
   10007            1 :                 Lsn(0x40),
   10008            1 :                 Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
   10009            1 :             ),
   10010            1 :             (
   10011            1 :                 key,
   10012            1 :                 Lsn(0x50),
   10013            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
   10014            1 :             ),
   10015            1 :             (
   10016            1 :                 key,
   10017            1 :                 Lsn(0x60),
   10018            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10019            1 :             ),
   10020            1 :             (
   10021            1 :                 key,
   10022            1 :                 Lsn(0x70),
   10023            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10024            1 :             ),
   10025            1 :             (
   10026            1 :                 key,
   10027            1 :                 Lsn(0x80),
   10028            1 :                 Value::Image(Bytes::copy_from_slice(
   10029            1 :                     b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
   10030            1 :                 )),
   10031            1 :             ),
   10032            1 :             (
   10033            1 :                 key,
   10034            1 :                 Lsn(0x90),
   10035            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
   10036            1 :             ),
   10037              :         ];
   10038            1 :         let res = tline
   10039            1 :             .generate_key_retention(
   10040            1 :                 key,
   10041            1 :                 &history,
   10042            1 :                 Lsn(0x60),
   10043            1 :                 &[Lsn(0x40), Lsn(0x50)],
   10044            1 :                 3,
   10045            1 :                 None,
   10046            1 :                 true,
   10047            1 :             )
   10048            1 :             .await
   10049            1 :             .unwrap();
   10050            1 :         let expected_res = KeyHistoryRetention {
   10051            1 :             below_horizon: vec![
   10052            1 :                 (
   10053            1 :                     Lsn(0x40),
   10054            1 :                     KeyLogAtLsn(vec![(
   10055            1 :                         Lsn(0x40),
   10056            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
   10057            1 :                     )]),
   10058            1 :                 ),
   10059            1 :                 (
   10060            1 :                     Lsn(0x50),
   10061            1 :                     KeyLogAtLsn(vec![(
   10062            1 :                         Lsn(0x50),
   10063            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
   10064            1 :                     )]),
   10065            1 :                 ),
   10066            1 :                 (
   10067            1 :                     Lsn(0x60),
   10068            1 :                     KeyLogAtLsn(vec![(
   10069            1 :                         Lsn(0x60),
   10070            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10071            1 :                     )]),
   10072            1 :                 ),
   10073            1 :             ],
   10074            1 :             above_horizon: KeyLogAtLsn(vec![
   10075            1 :                 (
   10076            1 :                     Lsn(0x70),
   10077            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10078            1 :                 ),
   10079            1 :                 (
   10080            1 :                     Lsn(0x80),
   10081            1 :                     Value::Image(Bytes::copy_from_slice(
   10082            1 :                         b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
   10083            1 :                     )),
   10084            1 :                 ),
   10085            1 :                 (
   10086            1 :                     Lsn(0x90),
   10087            1 :                     Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
   10088            1 :                 ),
   10089            1 :             ]),
   10090            1 :         };
   10091            1 :         assert_eq!(res, expected_res);
   10092              : 
   10093              :         // In case of branch compaction, the branch itself does not have the full history, and we need to provide
   10094              :         // the ancestor image in the test case.
   10095              : 
   10096            1 :         let history = vec![
   10097            1 :             (
   10098            1 :                 key,
   10099            1 :                 Lsn(0x20),
   10100            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10101            1 :             ),
   10102            1 :             (
   10103            1 :                 key,
   10104            1 :                 Lsn(0x30),
   10105            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
   10106            1 :             ),
   10107            1 :             (
   10108            1 :                 key,
   10109            1 :                 Lsn(0x40),
   10110            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
   10111            1 :             ),
   10112            1 :             (
   10113            1 :                 key,
   10114            1 :                 Lsn(0x70),
   10115            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10116            1 :             ),
   10117              :         ];
   10118            1 :         let res = tline
   10119            1 :             .generate_key_retention(
   10120            1 :                 key,
   10121            1 :                 &history,
   10122            1 :                 Lsn(0x60),
   10123            1 :                 &[],
   10124            1 :                 3,
   10125            1 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
   10126            1 :                 true,
   10127            1 :             )
   10128            1 :             .await
   10129            1 :             .unwrap();
   10130            1 :         let expected_res = KeyHistoryRetention {
   10131            1 :             below_horizon: vec![(
   10132            1 :                 Lsn(0x60),
   10133            1 :                 KeyLogAtLsn(vec![(
   10134            1 :                     Lsn(0x60),
   10135            1 :                     Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
   10136            1 :                 )]),
   10137            1 :             )],
   10138            1 :             above_horizon: KeyLogAtLsn(vec![(
   10139            1 :                 Lsn(0x70),
   10140            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10141            1 :             )]),
   10142            1 :         };
   10143            1 :         assert_eq!(res, expected_res);
   10144              : 
   10145            1 :         let history = vec![
   10146            1 :             (
   10147            1 :                 key,
   10148            1 :                 Lsn(0x20),
   10149            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10150            1 :             ),
   10151            1 :             (
   10152            1 :                 key,
   10153            1 :                 Lsn(0x40),
   10154            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
   10155            1 :             ),
   10156            1 :             (
   10157            1 :                 key,
   10158            1 :                 Lsn(0x60),
   10159            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
   10160            1 :             ),
   10161            1 :             (
   10162            1 :                 key,
   10163            1 :                 Lsn(0x70),
   10164            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10165            1 :             ),
   10166              :         ];
   10167            1 :         let res = tline
   10168            1 :             .generate_key_retention(
   10169            1 :                 key,
   10170            1 :                 &history,
   10171            1 :                 Lsn(0x60),
   10172            1 :                 &[Lsn(0x30)],
   10173            1 :                 3,
   10174            1 :                 Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
   10175            1 :                 true,
   10176            1 :             )
   10177            1 :             .await
   10178            1 :             .unwrap();
   10179            1 :         let expected_res = KeyHistoryRetention {
   10180            1 :             below_horizon: vec![
   10181            1 :                 (
   10182            1 :                     Lsn(0x30),
   10183            1 :                     KeyLogAtLsn(vec![(
   10184            1 :                         Lsn(0x20),
   10185            1 :                         Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
   10186            1 :                     )]),
   10187            1 :                 ),
   10188            1 :                 (
   10189            1 :                     Lsn(0x60),
   10190            1 :                     KeyLogAtLsn(vec![(
   10191            1 :                         Lsn(0x60),
   10192            1 :                         Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
   10193            1 :                     )]),
   10194            1 :                 ),
   10195            1 :             ],
   10196            1 :             above_horizon: KeyLogAtLsn(vec![(
   10197            1 :                 Lsn(0x70),
   10198            1 :                 Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
   10199            1 :             )]),
   10200            1 :         };
   10201            1 :         assert_eq!(res, expected_res);
   10202              : 
   10203            2 :         Ok(())
   10204            1 :     }
   10205              : 
   10206              :     #[cfg(feature = "testing")]
   10207              :     #[tokio::test]
   10208            1 :     async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
   10209            1 :         let harness =
   10210            1 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
   10211            1 :         let (tenant, ctx) = harness.load().await;
   10212              : 
   10213          259 :         fn get_key(id: u32) -> Key {
   10214              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10215          259 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10216          259 :             key.field6 = id;
   10217          259 :             key
   10218          259 :         }
   10219              : 
   10220            1 :         let img_layer = (0..10)
   10221           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10222            1 :             .collect_vec();
   10223              : 
   10224            1 :         let delta1 = vec![
   10225            1 :             (
   10226            1 :                 get_key(1),
   10227            1 :                 Lsn(0x20),
   10228            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10229            1 :             ),
   10230            1 :             (
   10231            1 :                 get_key(2),
   10232            1 :                 Lsn(0x30),
   10233            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10234            1 :             ),
   10235            1 :             (
   10236            1 :                 get_key(3),
   10237            1 :                 Lsn(0x28),
   10238            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10239            1 :             ),
   10240            1 :             (
   10241            1 :                 get_key(3),
   10242            1 :                 Lsn(0x30),
   10243            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10244            1 :             ),
   10245            1 :             (
   10246            1 :                 get_key(3),
   10247            1 :                 Lsn(0x40),
   10248            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10249            1 :             ),
   10250              :         ];
   10251            1 :         let delta2 = vec![
   10252            1 :             (
   10253            1 :                 get_key(5),
   10254            1 :                 Lsn(0x20),
   10255            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10256            1 :             ),
   10257            1 :             (
   10258            1 :                 get_key(6),
   10259            1 :                 Lsn(0x20),
   10260            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10261            1 :             ),
   10262              :         ];
   10263            1 :         let delta3 = vec![
   10264            1 :             (
   10265            1 :                 get_key(8),
   10266            1 :                 Lsn(0x48),
   10267            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10268            1 :             ),
   10269            1 :             (
   10270            1 :                 get_key(9),
   10271            1 :                 Lsn(0x48),
   10272            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10273            1 :             ),
   10274              :         ];
   10275              : 
   10276            1 :         let tline = tenant
   10277            1 :             .create_test_timeline_with_layers(
   10278            1 :                 TIMELINE_ID,
   10279            1 :                 Lsn(0x10),
   10280            1 :                 DEFAULT_PG_VERSION,
   10281            1 :                 &ctx,
   10282            1 :                 Vec::new(), // in-memory layers
   10283            1 :                 vec![
   10284            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
   10285            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
   10286            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10287            1 :                 ], // delta layers
   10288            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10289            1 :                 Lsn(0x50),
   10290            1 :             )
   10291            1 :             .await?;
   10292              :         {
   10293            1 :             tline
   10294            1 :                 .applied_gc_cutoff_lsn
   10295            1 :                 .lock_for_write()
   10296            1 :                 .store_and_unlock(Lsn(0x30))
   10297            1 :                 .wait()
   10298            1 :                 .await;
   10299              :             // Update GC info
   10300            1 :             let mut guard = tline.gc_info.write().unwrap();
   10301            1 :             *guard = GcInfo {
   10302            1 :                 retain_lsns: vec![
   10303            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10304            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10305            1 :                 ],
   10306            1 :                 cutoffs: GcCutoffs {
   10307            1 :                     time: Some(Lsn(0x30)),
   10308            1 :                     space: Lsn(0x30),
   10309            1 :                 },
   10310            1 :                 leases: Default::default(),
   10311            1 :                 within_ancestor_pitr: false,
   10312            1 :             };
   10313              :         }
   10314              : 
   10315            1 :         let expected_result = [
   10316            1 :             Bytes::from_static(b"value 0@0x10"),
   10317            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10318            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10319            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10320            1 :             Bytes::from_static(b"value 4@0x10"),
   10321            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10322            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10323            1 :             Bytes::from_static(b"value 7@0x10"),
   10324            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10325            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10326            1 :         ];
   10327              : 
   10328            1 :         let expected_result_at_gc_horizon = [
   10329            1 :             Bytes::from_static(b"value 0@0x10"),
   10330            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10331            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10332            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30"),
   10333            1 :             Bytes::from_static(b"value 4@0x10"),
   10334            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10335            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10336            1 :             Bytes::from_static(b"value 7@0x10"),
   10337            1 :             Bytes::from_static(b"value 8@0x10"),
   10338            1 :             Bytes::from_static(b"value 9@0x10"),
   10339            1 :         ];
   10340              : 
   10341            1 :         let expected_result_at_lsn_20 = [
   10342            1 :             Bytes::from_static(b"value 0@0x10"),
   10343            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10344            1 :             Bytes::from_static(b"value 2@0x10"),
   10345            1 :             Bytes::from_static(b"value 3@0x10"),
   10346            1 :             Bytes::from_static(b"value 4@0x10"),
   10347            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10348            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10349            1 :             Bytes::from_static(b"value 7@0x10"),
   10350            1 :             Bytes::from_static(b"value 8@0x10"),
   10351            1 :             Bytes::from_static(b"value 9@0x10"),
   10352            1 :         ];
   10353              : 
   10354            1 :         let expected_result_at_lsn_10 = [
   10355            1 :             Bytes::from_static(b"value 0@0x10"),
   10356            1 :             Bytes::from_static(b"value 1@0x10"),
   10357            1 :             Bytes::from_static(b"value 2@0x10"),
   10358            1 :             Bytes::from_static(b"value 3@0x10"),
   10359            1 :             Bytes::from_static(b"value 4@0x10"),
   10360            1 :             Bytes::from_static(b"value 5@0x10"),
   10361            1 :             Bytes::from_static(b"value 6@0x10"),
   10362            1 :             Bytes::from_static(b"value 7@0x10"),
   10363            1 :             Bytes::from_static(b"value 8@0x10"),
   10364            1 :             Bytes::from_static(b"value 9@0x10"),
   10365            1 :         ];
   10366              : 
   10367            6 :         let verify_result = || async {
   10368            6 :             let gc_horizon = {
   10369            6 :                 let gc_info = tline.gc_info.read().unwrap();
   10370            6 :                 gc_info.cutoffs.time.unwrap_or_default()
   10371              :             };
   10372           66 :             for idx in 0..10 {
   10373           60 :                 assert_eq!(
   10374           60 :                     tline
   10375           60 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10376           60 :                         .await
   10377           60 :                         .unwrap(),
   10378           60 :                     &expected_result[idx]
   10379              :                 );
   10380           60 :                 assert_eq!(
   10381           60 :                     tline
   10382           60 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10383           60 :                         .await
   10384           60 :                         .unwrap(),
   10385           60 :                     &expected_result_at_gc_horizon[idx]
   10386              :                 );
   10387           60 :                 assert_eq!(
   10388           60 :                     tline
   10389           60 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10390           60 :                         .await
   10391           60 :                         .unwrap(),
   10392           60 :                     &expected_result_at_lsn_20[idx]
   10393              :                 );
   10394           60 :                 assert_eq!(
   10395           60 :                     tline
   10396           60 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10397           60 :                         .await
   10398           60 :                         .unwrap(),
   10399           60 :                     &expected_result_at_lsn_10[idx]
   10400              :                 );
   10401              :             }
   10402           12 :         };
   10403              : 
   10404            1 :         verify_result().await;
   10405              : 
   10406            1 :         let cancel = CancellationToken::new();
   10407            1 :         let mut dryrun_flags = EnumSet::new();
   10408            1 :         dryrun_flags.insert(CompactFlags::DryRun);
   10409              : 
   10410            1 :         tline
   10411            1 :             .compact_with_gc(
   10412            1 :                 &cancel,
   10413            1 :                 CompactOptions {
   10414            1 :                     flags: dryrun_flags,
   10415            1 :                     ..Default::default()
   10416            1 :                 },
   10417            1 :                 &ctx,
   10418            1 :             )
   10419            1 :             .await
   10420            1 :             .unwrap();
   10421              :         // 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
   10422              :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10423            1 :         verify_result().await;
   10424              : 
   10425            1 :         tline
   10426            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10427            1 :             .await
   10428            1 :             .unwrap();
   10429            1 :         verify_result().await;
   10430              : 
   10431              :         // compact again
   10432            1 :         tline
   10433            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10434            1 :             .await
   10435            1 :             .unwrap();
   10436            1 :         verify_result().await;
   10437              : 
   10438              :         // increase GC horizon and compact again
   10439              :         {
   10440            1 :             tline
   10441            1 :                 .applied_gc_cutoff_lsn
   10442            1 :                 .lock_for_write()
   10443            1 :                 .store_and_unlock(Lsn(0x38))
   10444            1 :                 .wait()
   10445            1 :                 .await;
   10446              :             // Update GC info
   10447            1 :             let mut guard = tline.gc_info.write().unwrap();
   10448            1 :             guard.cutoffs.time = Some(Lsn(0x38));
   10449            1 :             guard.cutoffs.space = Lsn(0x38);
   10450              :         }
   10451            1 :         tline
   10452            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10453            1 :             .await
   10454            1 :             .unwrap();
   10455            1 :         verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
   10456              : 
   10457              :         // not increasing the GC horizon and compact again
   10458            1 :         tline
   10459            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10460            1 :             .await
   10461            1 :             .unwrap();
   10462            1 :         verify_result().await;
   10463              : 
   10464            2 :         Ok(())
   10465            1 :     }
   10466              : 
   10467              :     #[cfg(feature = "testing")]
   10468              :     #[tokio::test]
   10469            1 :     async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
   10470            1 :     {
   10471            1 :         let harness =
   10472            1 :             TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
   10473            1 :                 .await?;
   10474            1 :         let (tenant, ctx) = harness.load().await;
   10475              : 
   10476          176 :         fn get_key(id: u32) -> Key {
   10477              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   10478          176 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   10479          176 :             key.field6 = id;
   10480          176 :             key
   10481          176 :         }
   10482              : 
   10483            1 :         let img_layer = (0..10)
   10484           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10485            1 :             .collect_vec();
   10486              : 
   10487            1 :         let delta1 = vec![
   10488            1 :             (
   10489            1 :                 get_key(1),
   10490            1 :                 Lsn(0x20),
   10491            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10492            1 :             ),
   10493            1 :             (
   10494            1 :                 get_key(1),
   10495            1 :                 Lsn(0x28),
   10496            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10497            1 :             ),
   10498              :         ];
   10499            1 :         let delta2 = vec![
   10500            1 :             (
   10501            1 :                 get_key(1),
   10502            1 :                 Lsn(0x30),
   10503            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10504            1 :             ),
   10505            1 :             (
   10506            1 :                 get_key(1),
   10507            1 :                 Lsn(0x38),
   10508            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   10509            1 :             ),
   10510              :         ];
   10511            1 :         let delta3 = vec![
   10512            1 :             (
   10513            1 :                 get_key(8),
   10514            1 :                 Lsn(0x48),
   10515            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10516            1 :             ),
   10517            1 :             (
   10518            1 :                 get_key(9),
   10519            1 :                 Lsn(0x48),
   10520            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10521            1 :             ),
   10522              :         ];
   10523              : 
   10524            1 :         let tline = tenant
   10525            1 :             .create_test_timeline_with_layers(
   10526            1 :                 TIMELINE_ID,
   10527            1 :                 Lsn(0x10),
   10528            1 :                 DEFAULT_PG_VERSION,
   10529            1 :                 &ctx,
   10530            1 :                 Vec::new(), // in-memory layers
   10531            1 :                 vec![
   10532            1 :                     // delta1 and delta 2 only contain a single key but multiple updates
   10533            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
   10534            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   10535            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
   10536            1 :                 ], // delta layers
   10537            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   10538            1 :                 Lsn(0x50),
   10539            1 :             )
   10540            1 :             .await?;
   10541              :         {
   10542            1 :             tline
   10543            1 :                 .applied_gc_cutoff_lsn
   10544            1 :                 .lock_for_write()
   10545            1 :                 .store_and_unlock(Lsn(0x30))
   10546            1 :                 .wait()
   10547            1 :                 .await;
   10548              :             // Update GC info
   10549            1 :             let mut guard = tline.gc_info.write().unwrap();
   10550            1 :             *guard = GcInfo {
   10551            1 :                 retain_lsns: vec![
   10552            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   10553            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   10554            1 :                 ],
   10555            1 :                 cutoffs: GcCutoffs {
   10556            1 :                     time: Some(Lsn(0x30)),
   10557            1 :                     space: Lsn(0x30),
   10558            1 :                 },
   10559            1 :                 leases: Default::default(),
   10560            1 :                 within_ancestor_pitr: false,
   10561            1 :             };
   10562              :         }
   10563              : 
   10564            1 :         let expected_result = [
   10565            1 :             Bytes::from_static(b"value 0@0x10"),
   10566            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   10567            1 :             Bytes::from_static(b"value 2@0x10"),
   10568            1 :             Bytes::from_static(b"value 3@0x10"),
   10569            1 :             Bytes::from_static(b"value 4@0x10"),
   10570            1 :             Bytes::from_static(b"value 5@0x10"),
   10571            1 :             Bytes::from_static(b"value 6@0x10"),
   10572            1 :             Bytes::from_static(b"value 7@0x10"),
   10573            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10574            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10575            1 :         ];
   10576              : 
   10577            1 :         let expected_result_at_gc_horizon = [
   10578            1 :             Bytes::from_static(b"value 0@0x10"),
   10579            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   10580            1 :             Bytes::from_static(b"value 2@0x10"),
   10581            1 :             Bytes::from_static(b"value 3@0x10"),
   10582            1 :             Bytes::from_static(b"value 4@0x10"),
   10583            1 :             Bytes::from_static(b"value 5@0x10"),
   10584            1 :             Bytes::from_static(b"value 6@0x10"),
   10585            1 :             Bytes::from_static(b"value 7@0x10"),
   10586            1 :             Bytes::from_static(b"value 8@0x10"),
   10587            1 :             Bytes::from_static(b"value 9@0x10"),
   10588            1 :         ];
   10589              : 
   10590            1 :         let expected_result_at_lsn_20 = [
   10591            1 :             Bytes::from_static(b"value 0@0x10"),
   10592            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10593            1 :             Bytes::from_static(b"value 2@0x10"),
   10594            1 :             Bytes::from_static(b"value 3@0x10"),
   10595            1 :             Bytes::from_static(b"value 4@0x10"),
   10596            1 :             Bytes::from_static(b"value 5@0x10"),
   10597            1 :             Bytes::from_static(b"value 6@0x10"),
   10598            1 :             Bytes::from_static(b"value 7@0x10"),
   10599            1 :             Bytes::from_static(b"value 8@0x10"),
   10600            1 :             Bytes::from_static(b"value 9@0x10"),
   10601            1 :         ];
   10602              : 
   10603            1 :         let expected_result_at_lsn_10 = [
   10604            1 :             Bytes::from_static(b"value 0@0x10"),
   10605            1 :             Bytes::from_static(b"value 1@0x10"),
   10606            1 :             Bytes::from_static(b"value 2@0x10"),
   10607            1 :             Bytes::from_static(b"value 3@0x10"),
   10608            1 :             Bytes::from_static(b"value 4@0x10"),
   10609            1 :             Bytes::from_static(b"value 5@0x10"),
   10610            1 :             Bytes::from_static(b"value 6@0x10"),
   10611            1 :             Bytes::from_static(b"value 7@0x10"),
   10612            1 :             Bytes::from_static(b"value 8@0x10"),
   10613            1 :             Bytes::from_static(b"value 9@0x10"),
   10614            1 :         ];
   10615              : 
   10616            4 :         let verify_result = || async {
   10617            4 :             let gc_horizon = {
   10618            4 :                 let gc_info = tline.gc_info.read().unwrap();
   10619            4 :                 gc_info.cutoffs.time.unwrap_or_default()
   10620              :             };
   10621           44 :             for idx in 0..10 {
   10622           40 :                 assert_eq!(
   10623           40 :                     tline
   10624           40 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10625           40 :                         .await
   10626           40 :                         .unwrap(),
   10627           40 :                     &expected_result[idx]
   10628              :                 );
   10629           40 :                 assert_eq!(
   10630           40 :                     tline
   10631           40 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   10632           40 :                         .await
   10633           40 :                         .unwrap(),
   10634           40 :                     &expected_result_at_gc_horizon[idx]
   10635              :                 );
   10636           40 :                 assert_eq!(
   10637           40 :                     tline
   10638           40 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   10639           40 :                         .await
   10640           40 :                         .unwrap(),
   10641           40 :                     &expected_result_at_lsn_20[idx]
   10642              :                 );
   10643           40 :                 assert_eq!(
   10644           40 :                     tline
   10645           40 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   10646           40 :                         .await
   10647           40 :                         .unwrap(),
   10648           40 :                     &expected_result_at_lsn_10[idx]
   10649              :                 );
   10650              :             }
   10651            8 :         };
   10652              : 
   10653            1 :         verify_result().await;
   10654              : 
   10655            1 :         let cancel = CancellationToken::new();
   10656            1 :         let mut dryrun_flags = EnumSet::new();
   10657            1 :         dryrun_flags.insert(CompactFlags::DryRun);
   10658              : 
   10659            1 :         tline
   10660            1 :             .compact_with_gc(
   10661            1 :                 &cancel,
   10662            1 :                 CompactOptions {
   10663            1 :                     flags: dryrun_flags,
   10664            1 :                     ..Default::default()
   10665            1 :                 },
   10666            1 :                 &ctx,
   10667            1 :             )
   10668            1 :             .await
   10669            1 :             .unwrap();
   10670              :         // 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
   10671              :         // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
   10672            1 :         verify_result().await;
   10673              : 
   10674            1 :         tline
   10675            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10676            1 :             .await
   10677            1 :             .unwrap();
   10678            1 :         verify_result().await;
   10679              : 
   10680              :         // compact again
   10681            1 :         tline
   10682            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10683            1 :             .await
   10684            1 :             .unwrap();
   10685            1 :         verify_result().await;
   10686              : 
   10687            2 :         Ok(())
   10688            1 :     }
   10689              : 
   10690              :     #[cfg(feature = "testing")]
   10691              :     #[tokio::test]
   10692            1 :     async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
   10693              :         use models::CompactLsnRange;
   10694              : 
   10695            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
   10696            1 :         let (tenant, ctx) = harness.load().await;
   10697              : 
   10698           83 :         fn get_key(id: u32) -> Key {
   10699           83 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
   10700           83 :             key.field6 = id;
   10701           83 :             key
   10702           83 :         }
   10703              : 
   10704            1 :         let img_layer = (0..10)
   10705           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   10706            1 :             .collect_vec();
   10707              : 
   10708            1 :         let delta1 = vec![
   10709            1 :             (
   10710            1 :                 get_key(1),
   10711            1 :                 Lsn(0x20),
   10712            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10713            1 :             ),
   10714            1 :             (
   10715            1 :                 get_key(2),
   10716            1 :                 Lsn(0x30),
   10717            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10718            1 :             ),
   10719            1 :             (
   10720            1 :                 get_key(3),
   10721            1 :                 Lsn(0x28),
   10722            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   10723            1 :             ),
   10724            1 :             (
   10725            1 :                 get_key(3),
   10726            1 :                 Lsn(0x30),
   10727            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   10728            1 :             ),
   10729            1 :             (
   10730            1 :                 get_key(3),
   10731            1 :                 Lsn(0x40),
   10732            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
   10733            1 :             ),
   10734              :         ];
   10735            1 :         let delta2 = vec![
   10736            1 :             (
   10737            1 :                 get_key(5),
   10738            1 :                 Lsn(0x20),
   10739            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10740            1 :             ),
   10741            1 :             (
   10742            1 :                 get_key(6),
   10743            1 :                 Lsn(0x20),
   10744            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   10745            1 :             ),
   10746              :         ];
   10747            1 :         let delta3 = vec![
   10748            1 :             (
   10749            1 :                 get_key(8),
   10750            1 :                 Lsn(0x48),
   10751            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10752            1 :             ),
   10753            1 :             (
   10754            1 :                 get_key(9),
   10755            1 :                 Lsn(0x48),
   10756            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   10757            1 :             ),
   10758              :         ];
   10759              : 
   10760            1 :         let parent_tline = tenant
   10761            1 :             .create_test_timeline_with_layers(
   10762            1 :                 TIMELINE_ID,
   10763            1 :                 Lsn(0x10),
   10764            1 :                 DEFAULT_PG_VERSION,
   10765            1 :                 &ctx,
   10766            1 :                 vec![],                       // in-memory layers
   10767            1 :                 vec![],                       // delta layers
   10768            1 :                 vec![(Lsn(0x18), img_layer)], // image layers
   10769            1 :                 Lsn(0x18),
   10770            1 :             )
   10771            1 :             .await?;
   10772              : 
   10773            1 :         parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10774              : 
   10775            1 :         let branch_tline = tenant
   10776            1 :             .branch_timeline_test_with_layers(
   10777            1 :                 &parent_tline,
   10778            1 :                 NEW_TIMELINE_ID,
   10779            1 :                 Some(Lsn(0x18)),
   10780            1 :                 &ctx,
   10781            1 :                 vec![
   10782            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   10783            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   10784            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   10785            1 :                 ], // delta layers
   10786            1 :                 vec![], // image layers
   10787            1 :                 Lsn(0x50),
   10788            1 :             )
   10789            1 :             .await?;
   10790              : 
   10791            1 :         branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
   10792              : 
   10793              :         {
   10794            1 :             parent_tline
   10795            1 :                 .applied_gc_cutoff_lsn
   10796            1 :                 .lock_for_write()
   10797            1 :                 .store_and_unlock(Lsn(0x10))
   10798            1 :                 .wait()
   10799            1 :                 .await;
   10800              :             // Update GC info
   10801            1 :             let mut guard = parent_tline.gc_info.write().unwrap();
   10802            1 :             *guard = GcInfo {
   10803            1 :                 retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
   10804            1 :                 cutoffs: GcCutoffs {
   10805            1 :                     time: Some(Lsn(0x10)),
   10806            1 :                     space: Lsn(0x10),
   10807            1 :                 },
   10808            1 :                 leases: Default::default(),
   10809            1 :                 within_ancestor_pitr: false,
   10810            1 :             };
   10811              :         }
   10812              : 
   10813              :         {
   10814            1 :             branch_tline
   10815            1 :                 .applied_gc_cutoff_lsn
   10816            1 :                 .lock_for_write()
   10817            1 :                 .store_and_unlock(Lsn(0x50))
   10818            1 :                 .wait()
   10819            1 :                 .await;
   10820              :             // Update GC info
   10821            1 :             let mut guard = branch_tline.gc_info.write().unwrap();
   10822            1 :             *guard = GcInfo {
   10823            1 :                 retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
   10824            1 :                 cutoffs: GcCutoffs {
   10825            1 :                     time: Some(Lsn(0x50)),
   10826            1 :                     space: Lsn(0x50),
   10827            1 :                 },
   10828            1 :                 leases: Default::default(),
   10829            1 :                 within_ancestor_pitr: false,
   10830            1 :             };
   10831              :         }
   10832              : 
   10833            1 :         let expected_result_at_gc_horizon = [
   10834            1 :             Bytes::from_static(b"value 0@0x10"),
   10835            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10836            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10837            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10838            1 :             Bytes::from_static(b"value 4@0x10"),
   10839            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10840            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10841            1 :             Bytes::from_static(b"value 7@0x10"),
   10842            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   10843            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   10844            1 :         ];
   10845              : 
   10846            1 :         let expected_result_at_lsn_40 = [
   10847            1 :             Bytes::from_static(b"value 0@0x10"),
   10848            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   10849            1 :             Bytes::from_static(b"value 2@0x10@0x30"),
   10850            1 :             Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
   10851            1 :             Bytes::from_static(b"value 4@0x10"),
   10852            1 :             Bytes::from_static(b"value 5@0x10@0x20"),
   10853            1 :             Bytes::from_static(b"value 6@0x10@0x20"),
   10854            1 :             Bytes::from_static(b"value 7@0x10"),
   10855            1 :             Bytes::from_static(b"value 8@0x10"),
   10856            1 :             Bytes::from_static(b"value 9@0x10"),
   10857            1 :         ];
   10858              : 
   10859            3 :         let verify_result = || async {
   10860           33 :             for idx in 0..10 {
   10861           30 :                 assert_eq!(
   10862           30 :                     branch_tline
   10863           30 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   10864           30 :                         .await
   10865           30 :                         .unwrap(),
   10866           30 :                     &expected_result_at_gc_horizon[idx]
   10867              :                 );
   10868           30 :                 assert_eq!(
   10869           30 :                     branch_tline
   10870           30 :                         .get(get_key(idx as u32), Lsn(0x40), &ctx)
   10871           30 :                         .await
   10872           30 :                         .unwrap(),
   10873           30 :                     &expected_result_at_lsn_40[idx]
   10874              :                 );
   10875              :             }
   10876            6 :         };
   10877              : 
   10878            1 :         verify_result().await;
   10879              : 
   10880            1 :         let cancel = CancellationToken::new();
   10881            1 :         branch_tline
   10882            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   10883            1 :             .await
   10884            1 :             .unwrap();
   10885              : 
   10886            1 :         verify_result().await;
   10887              : 
   10888              :         // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
   10889              :         // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
   10890            1 :         branch_tline
   10891            1 :             .compact_with_gc(
   10892            1 :                 &cancel,
   10893            1 :                 CompactOptions {
   10894            1 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
   10895            1 :                     ..Default::default()
   10896            1 :                 },
   10897            1 :                 &ctx,
   10898            1 :             )
   10899            1 :             .await
   10900            1 :             .unwrap();
   10901              : 
   10902            1 :         verify_result().await;
   10903              : 
   10904            2 :         Ok(())
   10905            1 :     }
   10906              : 
   10907              :     // Regression test for https://github.com/neondatabase/neon/issues/9012
   10908              :     // Create an image arrangement where we have to read at different LSN ranges
   10909              :     // from a delta layer. This is achieved by overlapping an image layer on top of
   10910              :     // a delta layer. Like so:
   10911              :     //
   10912              :     //     A      B
   10913              :     // +----------------+ -> delta_layer
   10914              :     // |                |                           ^ lsn
   10915              :     // |       =========|-> nested_image_layer      |
   10916              :     // |       C        |                           |
   10917              :     // +----------------+                           |
   10918              :     // ======== -> baseline_image_layer             +-------> key
   10919              :     //
   10920              :     //
   10921              :     // When querying the key range [A, B) we need to read at different LSN ranges
   10922              :     // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
   10923              :     #[cfg(feature = "testing")]
   10924              :     #[tokio::test]
   10925            1 :     async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
   10926            1 :         let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
   10927            1 :         let (tenant, ctx) = harness.load().await;
   10928              : 
   10929            1 :         let will_init_keys = [2, 6];
   10930           22 :         fn get_key(id: u32) -> Key {
   10931           22 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   10932           22 :             key.field6 = id;
   10933           22 :             key
   10934           22 :         }
   10935              : 
   10936            1 :         let mut expected_key_values = HashMap::new();
   10937              : 
   10938            1 :         let baseline_image_layer_lsn = Lsn(0x10);
   10939            1 :         let mut baseline_img_layer = Vec::new();
   10940            6 :         for i in 0..5 {
   10941            5 :             let key = get_key(i);
   10942            5 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   10943              : 
   10944            5 :             let removed = expected_key_values.insert(key, value.clone());
   10945            5 :             assert!(removed.is_none());
   10946              : 
   10947            5 :             baseline_img_layer.push((key, Bytes::from(value)));
   10948              :         }
   10949              : 
   10950            1 :         let nested_image_layer_lsn = Lsn(0x50);
   10951            1 :         let mut nested_img_layer = Vec::new();
   10952            6 :         for i in 5..10 {
   10953            5 :             let key = get_key(i);
   10954            5 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   10955              : 
   10956            5 :             let removed = expected_key_values.insert(key, value.clone());
   10957            5 :             assert!(removed.is_none());
   10958              : 
   10959            5 :             nested_img_layer.push((key, Bytes::from(value)));
   10960              :         }
   10961              : 
   10962            1 :         let mut delta_layer_spec = Vec::default();
   10963            1 :         let delta_layer_start_lsn = Lsn(0x20);
   10964            1 :         let mut delta_layer_end_lsn = delta_layer_start_lsn;
   10965              : 
   10966           11 :         for i in 0..10 {
   10967           10 :             let key = get_key(i);
   10968           10 :             let key_in_nested = nested_img_layer
   10969           10 :                 .iter()
   10970           40 :                 .any(|(key_with_img, _)| *key_with_img == key);
   10971           10 :             let lsn = {
   10972           10 :                 if key_in_nested {
   10973            5 :                     Lsn(nested_image_layer_lsn.0 + 0x10)
   10974              :                 } else {
   10975            5 :                     delta_layer_start_lsn
   10976              :                 }
   10977              :             };
   10978              : 
   10979           10 :             let will_init = will_init_keys.contains(&i);
   10980           10 :             if will_init {
   10981            2 :                 delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   10982            2 : 
   10983            2 :                 expected_key_values.insert(key, "".to_string());
   10984            8 :             } else {
   10985            8 :                 let delta = format!("@{lsn}");
   10986            8 :                 delta_layer_spec.push((
   10987            8 :                     key,
   10988            8 :                     lsn,
   10989            8 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   10990            8 :                 ));
   10991            8 : 
   10992            8 :                 expected_key_values
   10993            8 :                     .get_mut(&key)
   10994            8 :                     .expect("An image exists for each key")
   10995            8 :                     .push_str(delta.as_str());
   10996            8 :             }
   10997           10 :             delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
   10998              :         }
   10999              : 
   11000            1 :         delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
   11001              : 
   11002            1 :         assert!(
   11003            1 :             nested_image_layer_lsn > delta_layer_start_lsn
   11004            1 :                 && nested_image_layer_lsn < delta_layer_end_lsn
   11005              :         );
   11006              : 
   11007            1 :         let tline = tenant
   11008            1 :             .create_test_timeline_with_layers(
   11009            1 :                 TIMELINE_ID,
   11010            1 :                 baseline_image_layer_lsn,
   11011            1 :                 DEFAULT_PG_VERSION,
   11012            1 :                 &ctx,
   11013            1 :                 vec![], // in-memory layers
   11014            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   11015            1 :                     delta_layer_start_lsn..delta_layer_end_lsn,
   11016            1 :                     delta_layer_spec,
   11017            1 :                 )], // delta layers
   11018            1 :                 vec![
   11019            1 :                     (baseline_image_layer_lsn, baseline_img_layer),
   11020            1 :                     (nested_image_layer_lsn, nested_img_layer),
   11021            1 :                 ], // image layers
   11022            1 :                 delta_layer_end_lsn,
   11023            1 :             )
   11024            1 :             .await?;
   11025              : 
   11026            1 :         let query = VersionedKeySpaceQuery::uniform(
   11027            1 :             KeySpace::single(get_key(0)..get_key(10)),
   11028            1 :             delta_layer_end_lsn,
   11029              :         );
   11030              : 
   11031            1 :         let results = tline
   11032            1 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   11033            1 :             .await
   11034            1 :             .expect("No vectored errors");
   11035           11 :         for (key, res) in results {
   11036           10 :             let value = res.expect("No key errors");
   11037           10 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   11038           10 :             assert_eq!(value, Bytes::from(expected_value));
   11039            1 :         }
   11040            1 : 
   11041            1 :         Ok(())
   11042            1 :     }
   11043              : 
   11044              :     #[cfg(feature = "testing")]
   11045              :     #[tokio::test]
   11046            1 :     async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
   11047            1 :         let harness =
   11048            1 :             TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
   11049            1 :         let (tenant, ctx) = harness.load().await;
   11050              : 
   11051            1 :         let will_init_keys = [2, 6];
   11052           32 :         fn get_key(id: u32) -> Key {
   11053           32 :             let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   11054           32 :             key.field6 = id;
   11055           32 :             key
   11056           32 :         }
   11057              : 
   11058            1 :         let mut expected_key_values = HashMap::new();
   11059              : 
   11060            1 :         let baseline_image_layer_lsn = Lsn(0x10);
   11061            1 :         let mut baseline_img_layer = Vec::new();
   11062            6 :         for i in 0..5 {
   11063            5 :             let key = get_key(i);
   11064            5 :             let value = format!("value {i}@{baseline_image_layer_lsn}");
   11065              : 
   11066            5 :             let removed = expected_key_values.insert(key, value.clone());
   11067            5 :             assert!(removed.is_none());
   11068              : 
   11069            5 :             baseline_img_layer.push((key, Bytes::from(value)));
   11070              :         }
   11071              : 
   11072            1 :         let nested_image_layer_lsn = Lsn(0x50);
   11073            1 :         let mut nested_img_layer = Vec::new();
   11074            6 :         for i in 5..10 {
   11075            5 :             let key = get_key(i);
   11076            5 :             let value = format!("value {i}@{nested_image_layer_lsn}");
   11077              : 
   11078            5 :             let removed = expected_key_values.insert(key, value.clone());
   11079            5 :             assert!(removed.is_none());
   11080              : 
   11081            5 :             nested_img_layer.push((key, Bytes::from(value)));
   11082              :         }
   11083              : 
   11084            1 :         let frozen_layer = {
   11085            1 :             let lsn_range = Lsn(0x40)..Lsn(0x60);
   11086            1 :             let mut data = Vec::new();
   11087           11 :             for i in 0..10 {
   11088           10 :                 let key = get_key(i);
   11089           10 :                 let key_in_nested = nested_img_layer
   11090           10 :                     .iter()
   11091           40 :                     .any(|(key_with_img, _)| *key_with_img == key);
   11092           10 :                 let lsn = {
   11093           10 :                     if key_in_nested {
   11094            5 :                         Lsn(nested_image_layer_lsn.0 + 5)
   11095              :                     } else {
   11096            5 :                         lsn_range.start
   11097              :                     }
   11098              :                 };
   11099              : 
   11100           10 :                 let will_init = will_init_keys.contains(&i);
   11101           10 :                 if will_init {
   11102            2 :                     data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
   11103            2 : 
   11104            2 :                     expected_key_values.insert(key, "".to_string());
   11105            8 :                 } else {
   11106            8 :                     let delta = format!("@{lsn}");
   11107            8 :                     data.push((
   11108            8 :                         key,
   11109            8 :                         lsn,
   11110            8 :                         Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11111            8 :                     ));
   11112            8 : 
   11113            8 :                     expected_key_values
   11114            8 :                         .get_mut(&key)
   11115            8 :                         .expect("An image exists for each key")
   11116            8 :                         .push_str(delta.as_str());
   11117            8 :                 }
   11118              :             }
   11119              : 
   11120            1 :             InMemoryLayerTestDesc {
   11121            1 :                 lsn_range,
   11122            1 :                 is_open: false,
   11123            1 :                 data,
   11124            1 :             }
   11125              :         };
   11126              : 
   11127            1 :         let (open_layer, last_record_lsn) = {
   11128            1 :             let start_lsn = Lsn(0x70);
   11129            1 :             let mut data = Vec::new();
   11130            1 :             let mut end_lsn = Lsn(0);
   11131           11 :             for i in 0..10 {
   11132           10 :                 let key = get_key(i);
   11133           10 :                 let lsn = Lsn(start_lsn.0 + i as u64);
   11134           10 :                 let delta = format!("@{lsn}");
   11135           10 :                 data.push((
   11136           10 :                     key,
   11137           10 :                     lsn,
   11138           10 :                     Value::WalRecord(NeonWalRecord::wal_append(&delta)),
   11139           10 :                 ));
   11140           10 : 
   11141           10 :                 expected_key_values
   11142           10 :                     .get_mut(&key)
   11143           10 :                     .expect("An image exists for each key")
   11144           10 :                     .push_str(delta.as_str());
   11145           10 : 
   11146           10 :                 end_lsn = std::cmp::max(end_lsn, lsn);
   11147           10 :             }
   11148              : 
   11149            1 :             (
   11150            1 :                 InMemoryLayerTestDesc {
   11151            1 :                     lsn_range: start_lsn..Lsn::MAX,
   11152            1 :                     is_open: true,
   11153            1 :                     data,
   11154            1 :                 },
   11155            1 :                 end_lsn,
   11156            1 :             )
   11157              :         };
   11158              : 
   11159            1 :         assert!(
   11160            1 :             nested_image_layer_lsn > frozen_layer.lsn_range.start
   11161            1 :                 && nested_image_layer_lsn < frozen_layer.lsn_range.end
   11162              :         );
   11163              : 
   11164            1 :         let tline = tenant
   11165            1 :             .create_test_timeline_with_layers(
   11166            1 :                 TIMELINE_ID,
   11167            1 :                 baseline_image_layer_lsn,
   11168            1 :                 DEFAULT_PG_VERSION,
   11169            1 :                 &ctx,
   11170            1 :                 vec![open_layer, frozen_layer], // in-memory layers
   11171            1 :                 Vec::new(),                     // delta layers
   11172            1 :                 vec![
   11173            1 :                     (baseline_image_layer_lsn, baseline_img_layer),
   11174            1 :                     (nested_image_layer_lsn, nested_img_layer),
   11175            1 :                 ], // image layers
   11176            1 :                 last_record_lsn,
   11177            1 :             )
   11178            1 :             .await?;
   11179              : 
   11180            1 :         let query = VersionedKeySpaceQuery::uniform(
   11181            1 :             KeySpace::single(get_key(0)..get_key(10)),
   11182            1 :             last_record_lsn,
   11183              :         );
   11184              : 
   11185            1 :         let results = tline
   11186            1 :             .get_vectored(query, IoConcurrency::sequential(), &ctx)
   11187            1 :             .await
   11188            1 :             .expect("No vectored errors");
   11189           11 :         for (key, res) in results {
   11190           10 :             let value = res.expect("No key errors");
   11191           10 :             let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
   11192           10 :             assert_eq!(value, Bytes::from(expected_value.clone()));
   11193            1 : 
   11194           10 :             tracing::info!("key={key} value={expected_value}");
   11195            1 :         }
   11196            1 : 
   11197            1 :         Ok(())
   11198            1 :     }
   11199              : 
   11200              :     // A randomized read path test. Generates a layer map according to a deterministic
   11201              :     // specification. Fills the (key, LSN) space in random manner and then performs
   11202              :     // random scattered queries validating the results against in-memory storage.
   11203              :     //
   11204              :     // See this internal Notion page for a diagram of the layer map:
   11205              :     // https://www.notion.so/neondatabase/Read-Path-Unit-Testing-Fuzzing-1d1f189e0047806c8e5cd37781b0a350?pvs=4
   11206              :     //
   11207              :     // A fuzzing mode is also supported. In this mode, the test will use a random
   11208              :     // seed instead of a hardcoded one. Use it in conjunction with `cargo stress`
   11209              :     // to run multiple instances in parallel:
   11210              :     //
   11211              :     // $ RUST_BACKTRACE=1 RUST_LOG=INFO \
   11212              :     //   cargo stress --package=pageserver --features=testing,fuzz-read-path --release -- test_read_path
   11213              :     #[cfg(feature = "testing")]
   11214              :     #[tokio::test]
   11215            1 :     async fn test_read_path() -> anyhow::Result<()> {
   11216              :         use rand::seq::SliceRandom;
   11217              : 
   11218            1 :         let seed = if cfg!(feature = "fuzz-read-path") {
   11219            0 :             let seed: u64 = thread_rng().r#gen();
   11220            0 :             seed
   11221              :         } else {
   11222              :             // Use a hard-coded seed when not in fuzzing mode.
   11223              :             // Note that with the current approach results are not reproducible
   11224              :             // accross platforms and Rust releases.
   11225              :             const SEED: u64 = 0;
   11226            1 :             SEED
   11227              :         };
   11228              : 
   11229            1 :         let mut random = StdRng::seed_from_u64(seed);
   11230              : 
   11231            1 :         let (queries, will_init_chance, gap_chance) = if cfg!(feature = "fuzz-read-path") {
   11232              :             const QUERIES: u64 = 5000;
   11233            0 :             let will_init_chance: u8 = random.gen_range(0..=10);
   11234            0 :             let gap_chance: u8 = random.gen_range(0..=50);
   11235              : 
   11236            0 :             (QUERIES, will_init_chance, gap_chance)
   11237              :         } else {
   11238              :             const QUERIES: u64 = 1000;
   11239              :             const WILL_INIT_CHANCE: u8 = 1;
   11240              :             const GAP_CHANCE: u8 = 5;
   11241              : 
   11242            1 :             (QUERIES, WILL_INIT_CHANCE, GAP_CHANCE)
   11243              :         };
   11244              : 
   11245            1 :         let harness = TenantHarness::create("test_read_path").await?;
   11246            1 :         let (tenant, ctx) = harness.load().await;
   11247              : 
   11248            1 :         tracing::info!("Using random seed: {seed}");
   11249            1 :         tracing::info!(%will_init_chance, %gap_chance, "Fill params");
   11250              : 
   11251              :         // Define the layer map shape. Note that this part is not randomized.
   11252              : 
   11253              :         const KEY_DIMENSION_SIZE: u32 = 99;
   11254            1 :         let start_key = Key::from_hex("110000000033333333444444445500000000").unwrap();
   11255            1 :         let end_key = start_key.add(KEY_DIMENSION_SIZE);
   11256            1 :         let total_key_range = start_key..end_key;
   11257            1 :         let total_key_range_size = end_key.to_i128() - start_key.to_i128();
   11258            1 :         let total_start_lsn = Lsn(104);
   11259            1 :         let last_record_lsn = Lsn(504);
   11260              : 
   11261            1 :         assert!(total_key_range_size % 3 == 0);
   11262              : 
   11263            1 :         let in_memory_layers_shape = vec![
   11264            1 :             (total_key_range.clone(), Lsn(304)..Lsn(400)),
   11265            1 :             (total_key_range.clone(), Lsn(400)..last_record_lsn),
   11266              :         ];
   11267              : 
   11268            1 :         let delta_layers_shape = vec![
   11269            1 :             (
   11270            1 :                 start_key..(start_key.add((total_key_range_size / 3) as u32)),
   11271            1 :                 Lsn(200)..Lsn(304),
   11272            1 :             ),
   11273            1 :             (
   11274            1 :                 (start_key.add((total_key_range_size / 3) as u32))
   11275            1 :                     ..(start_key.add((total_key_range_size * 2 / 3) as u32)),
   11276            1 :                 Lsn(200)..Lsn(304),
   11277            1 :             ),
   11278            1 :             (
   11279            1 :                 (start_key.add((total_key_range_size * 2 / 3) as u32))
   11280            1 :                     ..(start_key.add(total_key_range_size as u32)),
   11281            1 :                 Lsn(200)..Lsn(304),
   11282            1 :             ),
   11283              :         ];
   11284              : 
   11285            1 :         let image_layers_shape = vec![
   11286            1 :             (
   11287            1 :                 start_key.add((total_key_range_size * 2 / 3 - 10) as u32)
   11288            1 :                     ..start_key.add((total_key_range_size * 2 / 3 + 10) as u32),
   11289            1 :                 Lsn(456),
   11290            1 :             ),
   11291            1 :             (
   11292            1 :                 start_key.add((total_key_range_size / 3 - 10) as u32)
   11293            1 :                     ..start_key.add((total_key_range_size / 3 + 10) as u32),
   11294            1 :                 Lsn(256),
   11295            1 :             ),
   11296            1 :             (total_key_range.clone(), total_start_lsn),
   11297              :         ];
   11298              : 
   11299            1 :         let specification = TestTimelineSpecification {
   11300            1 :             start_lsn: total_start_lsn,
   11301            1 :             last_record_lsn,
   11302            1 :             in_memory_layers_shape,
   11303            1 :             delta_layers_shape,
   11304            1 :             image_layers_shape,
   11305            1 :             gap_chance,
   11306            1 :             will_init_chance,
   11307            1 :         };
   11308              : 
   11309              :         // Create and randomly fill in the layers according to the specification
   11310            1 :         let (tline, storage, interesting_lsns) = randomize_timeline(
   11311            1 :             &tenant,
   11312            1 :             TIMELINE_ID,
   11313            1 :             DEFAULT_PG_VERSION,
   11314            1 :             specification,
   11315            1 :             &mut random,
   11316            1 :             &ctx,
   11317            1 :         )
   11318            1 :         .await?;
   11319              : 
   11320              :         // Now generate queries based on the interesting lsns that we've collected.
   11321              :         //
   11322              :         // While there's still room in the query, pick and interesting LSN and a random
   11323              :         // key. Then roll the dice to see if the next key should also be included in
   11324              :         // the query. When the roll fails, break the "batch" and pick another point in the
   11325              :         // (key, LSN) space.
   11326              : 
   11327              :         const PICK_NEXT_CHANCE: u8 = 50;
   11328            1 :         for _ in 0..queries {
   11329         1000 :             let query = {
   11330         1000 :                 let mut keyspaces_at_lsn: HashMap<Lsn, KeySpaceRandomAccum> = HashMap::default();
   11331         1000 :                 let mut used_keys: HashSet<Key> = HashSet::default();
   11332            1 : 
   11333        22536 :                 while used_keys.len() < tenant.conf.max_get_vectored_keys.get() {
   11334        21536 :                     let selected_lsn = interesting_lsns.choose(&mut random).expect("not empty");
   11335        21536 :                     let mut selected_key = start_key.add(random.gen_range(0..KEY_DIMENSION_SIZE));
   11336            1 : 
   11337        37614 :                     while used_keys.len() < tenant.conf.max_get_vectored_keys.get() {
   11338        37093 :                         if used_keys.contains(&selected_key)
   11339        32154 :                             || selected_key >= start_key.add(KEY_DIMENSION_SIZE)
   11340            1 :                         {
   11341         5093 :                             break;
   11342        32000 :                         }
   11343            1 : 
   11344        32000 :                         keyspaces_at_lsn
   11345        32000 :                             .entry(*selected_lsn)
   11346        32000 :                             .or_default()
   11347        32000 :                             .add_key(selected_key);
   11348        32000 :                         used_keys.insert(selected_key);
   11349            1 : 
   11350        32000 :                         let pick_next = random.gen_range(0..=100) <= PICK_NEXT_CHANCE;
   11351        32000 :                         if pick_next {
   11352        16078 :                             selected_key = selected_key.next();
   11353        16078 :                         } else {
   11354        15922 :                             break;
   11355            1 :                         }
   11356            1 :                     }
   11357            1 :                 }
   11358            1 : 
   11359         1000 :                 VersionedKeySpaceQuery::scattered(
   11360         1000 :                     keyspaces_at_lsn
   11361         1000 :                         .into_iter()
   11362        11917 :                         .map(|(lsn, acc)| (lsn, acc.to_keyspace()))
   11363         1000 :                         .collect(),
   11364            1 :                 )
   11365            1 :             };
   11366            1 : 
   11367            1 :             // Run the query and validate the results
   11368            1 : 
   11369         1000 :             let results = tline
   11370         1000 :                 .get_vectored(query.clone(), IoConcurrency::Sequential, &ctx)
   11371         1000 :                 .await;
   11372            1 : 
   11373         1000 :             let blobs = match results {
   11374         1000 :                 Ok(ok) => ok,
   11375            1 :                 Err(err) => {
   11376            1 :                     panic!("seed={seed} Error returned for query {query}: {err}");
   11377            1 :                 }
   11378            1 :             };
   11379            1 : 
   11380        32000 :             for (key, key_res) in blobs.into_iter() {
   11381        32000 :                 match key_res {
   11382        32000 :                     Ok(blob) => {
   11383        32000 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11384        32000 :                         let expected = storage.get(key, requested_at_lsn);
   11385            1 : 
   11386        32000 :                         if blob != expected {
   11387            1 :                             tracing::error!(
   11388            1 :                                 "seed={seed} Mismatch for {key}@{requested_at_lsn} from query: {query}"
   11389            1 :                             );
   11390        32000 :                         }
   11391            1 : 
   11392        32000 :                         assert_eq!(blob, expected);
   11393            1 :                     }
   11394            1 :                     Err(err) => {
   11395            1 :                         let requested_at_lsn = query.map_key_to_lsn(&key);
   11396            1 : 
   11397            1 :                         panic!(
   11398            1 :                             "seed={seed} Error returned for {key}@{requested_at_lsn} from query {query}: {err}"
   11399            1 :                         );
   11400            1 :                     }
   11401            1 :                 }
   11402            1 :             }
   11403            1 :         }
   11404            1 : 
   11405            1 :         Ok(())
   11406            1 :     }
   11407              : 
   11408          107 :     fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
   11409          107 :         (
   11410          107 :             k1.is_delta,
   11411          107 :             k1.key_range.start,
   11412          107 :             k1.key_range.end,
   11413          107 :             k1.lsn_range.start,
   11414          107 :             k1.lsn_range.end,
   11415          107 :         )
   11416          107 :             .cmp(&(
   11417          107 :                 k2.is_delta,
   11418          107 :                 k2.key_range.start,
   11419          107 :                 k2.key_range.end,
   11420          107 :                 k2.lsn_range.start,
   11421          107 :                 k2.lsn_range.end,
   11422          107 :             ))
   11423          107 :     }
   11424              : 
   11425           12 :     async fn inspect_and_sort(
   11426           12 :         tline: &Arc<Timeline>,
   11427           12 :         filter: Option<std::ops::Range<Key>>,
   11428           12 :     ) -> Vec<PersistentLayerKey> {
   11429           12 :         let mut all_layers = tline.inspect_historic_layers().await.unwrap();
   11430           12 :         if let Some(filter) = filter {
   11431           54 :             all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
   11432            1 :         }
   11433           12 :         all_layers.sort_by(sort_layer_key);
   11434           12 :         all_layers
   11435           12 :     }
   11436              : 
   11437              :     #[cfg(feature = "testing")]
   11438           11 :     fn check_layer_map_key_eq(
   11439           11 :         mut left: Vec<PersistentLayerKey>,
   11440           11 :         mut right: Vec<PersistentLayerKey>,
   11441           11 :     ) {
   11442           11 :         left.sort_by(sort_layer_key);
   11443           11 :         right.sort_by(sort_layer_key);
   11444           11 :         if left != right {
   11445            0 :             eprintln!("---LEFT---");
   11446            0 :             for left in left.iter() {
   11447            0 :                 eprintln!("{left}");
   11448            0 :             }
   11449            0 :             eprintln!("---RIGHT---");
   11450            0 :             for right in right.iter() {
   11451            0 :                 eprintln!("{right}");
   11452            0 :             }
   11453            0 :             assert_eq!(left, right);
   11454           11 :         }
   11455           11 :     }
   11456              : 
   11457              :     #[cfg(feature = "testing")]
   11458              :     #[tokio::test]
   11459            1 :     async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
   11460            1 :         let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
   11461            1 :         let (tenant, ctx) = harness.load().await;
   11462              : 
   11463           91 :         fn get_key(id: u32) -> Key {
   11464              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11465           91 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11466           91 :             key.field6 = id;
   11467           91 :             key
   11468           91 :         }
   11469              : 
   11470              :         // img layer at 0x10
   11471            1 :         let img_layer = (0..10)
   11472           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11473            1 :             .collect_vec();
   11474              : 
   11475            1 :         let delta1 = vec![
   11476            1 :             (
   11477            1 :                 get_key(1),
   11478            1 :                 Lsn(0x20),
   11479            1 :                 Value::Image(Bytes::from("value 1@0x20")),
   11480            1 :             ),
   11481            1 :             (
   11482            1 :                 get_key(2),
   11483            1 :                 Lsn(0x30),
   11484            1 :                 Value::Image(Bytes::from("value 2@0x30")),
   11485            1 :             ),
   11486            1 :             (
   11487            1 :                 get_key(3),
   11488            1 :                 Lsn(0x40),
   11489            1 :                 Value::Image(Bytes::from("value 3@0x40")),
   11490            1 :             ),
   11491              :         ];
   11492            1 :         let delta2 = vec![
   11493            1 :             (
   11494            1 :                 get_key(5),
   11495            1 :                 Lsn(0x20),
   11496            1 :                 Value::Image(Bytes::from("value 5@0x20")),
   11497            1 :             ),
   11498            1 :             (
   11499            1 :                 get_key(6),
   11500            1 :                 Lsn(0x20),
   11501            1 :                 Value::Image(Bytes::from("value 6@0x20")),
   11502            1 :             ),
   11503              :         ];
   11504            1 :         let delta3 = vec![
   11505            1 :             (
   11506            1 :                 get_key(8),
   11507            1 :                 Lsn(0x48),
   11508            1 :                 Value::Image(Bytes::from("value 8@0x48")),
   11509            1 :             ),
   11510            1 :             (
   11511            1 :                 get_key(9),
   11512            1 :                 Lsn(0x48),
   11513            1 :                 Value::Image(Bytes::from("value 9@0x48")),
   11514            1 :             ),
   11515              :         ];
   11516              : 
   11517            1 :         let tline = tenant
   11518            1 :             .create_test_timeline_with_layers(
   11519            1 :                 TIMELINE_ID,
   11520            1 :                 Lsn(0x10),
   11521            1 :                 DEFAULT_PG_VERSION,
   11522            1 :                 &ctx,
   11523            1 :                 vec![], // in-memory layers
   11524            1 :                 vec![
   11525            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
   11526            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
   11527            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
   11528            1 :                 ], // delta layers
   11529            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11530            1 :                 Lsn(0x50),
   11531            1 :             )
   11532            1 :             .await?;
   11533              : 
   11534              :         {
   11535            1 :             tline
   11536            1 :                 .applied_gc_cutoff_lsn
   11537            1 :                 .lock_for_write()
   11538            1 :                 .store_and_unlock(Lsn(0x30))
   11539            1 :                 .wait()
   11540            1 :                 .await;
   11541              :             // Update GC info
   11542            1 :             let mut guard = tline.gc_info.write().unwrap();
   11543            1 :             *guard = GcInfo {
   11544            1 :                 retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
   11545            1 :                 cutoffs: GcCutoffs {
   11546            1 :                     time: Some(Lsn(0x30)),
   11547            1 :                     space: Lsn(0x30),
   11548            1 :                 },
   11549            1 :                 leases: Default::default(),
   11550            1 :                 within_ancestor_pitr: false,
   11551            1 :             };
   11552              :         }
   11553              : 
   11554            1 :         let cancel = CancellationToken::new();
   11555              : 
   11556              :         // Do a partial compaction on key range 0..2
   11557            1 :         tline
   11558            1 :             .compact_with_gc(
   11559            1 :                 &cancel,
   11560            1 :                 CompactOptions {
   11561            1 :                     flags: EnumSet::new(),
   11562            1 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   11563            1 :                     ..Default::default()
   11564            1 :                 },
   11565            1 :                 &ctx,
   11566            1 :             )
   11567            1 :             .await
   11568            1 :             .unwrap();
   11569            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11570            1 :         check_layer_map_key_eq(
   11571            1 :             all_layers,
   11572            1 :             vec![
   11573              :                 // newly-generated image layer for the partial compaction range 0-2
   11574            1 :                 PersistentLayerKey {
   11575            1 :                     key_range: get_key(0)..get_key(2),
   11576            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11577            1 :                     is_delta: false,
   11578            1 :                 },
   11579            1 :                 PersistentLayerKey {
   11580            1 :                     key_range: get_key(0)..get_key(10),
   11581            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11582            1 :                     is_delta: false,
   11583            1 :                 },
   11584              :                 // delta1 is split and the second part is rewritten
   11585            1 :                 PersistentLayerKey {
   11586            1 :                     key_range: get_key(2)..get_key(4),
   11587            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11588            1 :                     is_delta: true,
   11589            1 :                 },
   11590            1 :                 PersistentLayerKey {
   11591            1 :                     key_range: get_key(5)..get_key(7),
   11592            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11593            1 :                     is_delta: true,
   11594            1 :                 },
   11595            1 :                 PersistentLayerKey {
   11596            1 :                     key_range: get_key(8)..get_key(10),
   11597            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11598            1 :                     is_delta: true,
   11599            1 :                 },
   11600              :             ],
   11601              :         );
   11602              : 
   11603              :         // Do a partial compaction on key range 2..4
   11604            1 :         tline
   11605            1 :             .compact_with_gc(
   11606            1 :                 &cancel,
   11607            1 :                 CompactOptions {
   11608            1 :                     flags: EnumSet::new(),
   11609            1 :                     compact_key_range: Some((get_key(2)..get_key(4)).into()),
   11610            1 :                     ..Default::default()
   11611            1 :                 },
   11612            1 :                 &ctx,
   11613            1 :             )
   11614            1 :             .await
   11615            1 :             .unwrap();
   11616            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11617            1 :         check_layer_map_key_eq(
   11618            1 :             all_layers,
   11619            1 :             vec![
   11620            1 :                 PersistentLayerKey {
   11621            1 :                     key_range: get_key(0)..get_key(2),
   11622            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11623            1 :                     is_delta: false,
   11624            1 :                 },
   11625            1 :                 PersistentLayerKey {
   11626            1 :                     key_range: get_key(0)..get_key(10),
   11627            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11628            1 :                     is_delta: false,
   11629            1 :                 },
   11630              :                 // image layer generated for the compaction range 2-4
   11631            1 :                 PersistentLayerKey {
   11632            1 :                     key_range: get_key(2)..get_key(4),
   11633            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11634            1 :                     is_delta: false,
   11635            1 :                 },
   11636              :                 // we have key2/key3 above the retain_lsn, so we still need this delta layer
   11637            1 :                 PersistentLayerKey {
   11638            1 :                     key_range: get_key(2)..get_key(4),
   11639            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11640            1 :                     is_delta: true,
   11641            1 :                 },
   11642            1 :                 PersistentLayerKey {
   11643            1 :                     key_range: get_key(5)..get_key(7),
   11644            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11645            1 :                     is_delta: true,
   11646            1 :                 },
   11647            1 :                 PersistentLayerKey {
   11648            1 :                     key_range: get_key(8)..get_key(10),
   11649            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11650            1 :                     is_delta: true,
   11651            1 :                 },
   11652              :             ],
   11653              :         );
   11654              : 
   11655              :         // Do a partial compaction on key range 4..9
   11656            1 :         tline
   11657            1 :             .compact_with_gc(
   11658            1 :                 &cancel,
   11659            1 :                 CompactOptions {
   11660            1 :                     flags: EnumSet::new(),
   11661            1 :                     compact_key_range: Some((get_key(4)..get_key(9)).into()),
   11662            1 :                     ..Default::default()
   11663            1 :                 },
   11664            1 :                 &ctx,
   11665            1 :             )
   11666            1 :             .await
   11667            1 :             .unwrap();
   11668            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11669            1 :         check_layer_map_key_eq(
   11670            1 :             all_layers,
   11671            1 :             vec![
   11672            1 :                 PersistentLayerKey {
   11673            1 :                     key_range: get_key(0)..get_key(2),
   11674            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11675            1 :                     is_delta: false,
   11676            1 :                 },
   11677            1 :                 PersistentLayerKey {
   11678            1 :                     key_range: get_key(0)..get_key(10),
   11679            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11680            1 :                     is_delta: false,
   11681            1 :                 },
   11682            1 :                 PersistentLayerKey {
   11683            1 :                     key_range: get_key(2)..get_key(4),
   11684            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11685            1 :                     is_delta: false,
   11686            1 :                 },
   11687            1 :                 PersistentLayerKey {
   11688            1 :                     key_range: get_key(2)..get_key(4),
   11689            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11690            1 :                     is_delta: true,
   11691            1 :                 },
   11692              :                 // image layer generated for this compaction range
   11693            1 :                 PersistentLayerKey {
   11694            1 :                     key_range: get_key(4)..get_key(9),
   11695            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11696            1 :                     is_delta: false,
   11697            1 :                 },
   11698            1 :                 PersistentLayerKey {
   11699            1 :                     key_range: get_key(8)..get_key(10),
   11700            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11701            1 :                     is_delta: true,
   11702            1 :                 },
   11703              :             ],
   11704              :         );
   11705              : 
   11706              :         // Do a partial compaction on key range 9..10
   11707            1 :         tline
   11708            1 :             .compact_with_gc(
   11709            1 :                 &cancel,
   11710            1 :                 CompactOptions {
   11711            1 :                     flags: EnumSet::new(),
   11712            1 :                     compact_key_range: Some((get_key(9)..get_key(10)).into()),
   11713            1 :                     ..Default::default()
   11714            1 :                 },
   11715            1 :                 &ctx,
   11716            1 :             )
   11717            1 :             .await
   11718            1 :             .unwrap();
   11719            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11720            1 :         check_layer_map_key_eq(
   11721            1 :             all_layers,
   11722            1 :             vec![
   11723            1 :                 PersistentLayerKey {
   11724            1 :                     key_range: get_key(0)..get_key(2),
   11725            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11726            1 :                     is_delta: false,
   11727            1 :                 },
   11728            1 :                 PersistentLayerKey {
   11729            1 :                     key_range: get_key(0)..get_key(10),
   11730            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   11731            1 :                     is_delta: false,
   11732            1 :                 },
   11733            1 :                 PersistentLayerKey {
   11734            1 :                     key_range: get_key(2)..get_key(4),
   11735            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11736            1 :                     is_delta: false,
   11737            1 :                 },
   11738            1 :                 PersistentLayerKey {
   11739            1 :                     key_range: get_key(2)..get_key(4),
   11740            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11741            1 :                     is_delta: true,
   11742            1 :                 },
   11743            1 :                 PersistentLayerKey {
   11744            1 :                     key_range: get_key(4)..get_key(9),
   11745            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11746            1 :                     is_delta: false,
   11747            1 :                 },
   11748              :                 // image layer generated for the compaction range
   11749            1 :                 PersistentLayerKey {
   11750            1 :                     key_range: get_key(9)..get_key(10),
   11751            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11752            1 :                     is_delta: false,
   11753            1 :                 },
   11754            1 :                 PersistentLayerKey {
   11755            1 :                     key_range: get_key(8)..get_key(10),
   11756            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11757            1 :                     is_delta: true,
   11758            1 :                 },
   11759              :             ],
   11760              :         );
   11761              : 
   11762              :         // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
   11763            1 :         tline
   11764            1 :             .compact_with_gc(
   11765            1 :                 &cancel,
   11766            1 :                 CompactOptions {
   11767            1 :                     flags: EnumSet::new(),
   11768            1 :                     compact_key_range: Some((get_key(0)..get_key(10)).into()),
   11769            1 :                     ..Default::default()
   11770            1 :                 },
   11771            1 :                 &ctx,
   11772            1 :             )
   11773            1 :             .await
   11774            1 :             .unwrap();
   11775            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   11776            1 :         check_layer_map_key_eq(
   11777            1 :             all_layers,
   11778            1 :             vec![
   11779              :                 // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
   11780            1 :                 PersistentLayerKey {
   11781            1 :                     key_range: get_key(0)..get_key(10),
   11782            1 :                     lsn_range: Lsn(0x20)..Lsn(0x21),
   11783            1 :                     is_delta: false,
   11784            1 :                 },
   11785            1 :                 PersistentLayerKey {
   11786            1 :                     key_range: get_key(2)..get_key(4),
   11787            1 :                     lsn_range: Lsn(0x20)..Lsn(0x48),
   11788            1 :                     is_delta: true,
   11789            1 :                 },
   11790            1 :                 PersistentLayerKey {
   11791            1 :                     key_range: get_key(8)..get_key(10),
   11792            1 :                     lsn_range: Lsn(0x48)..Lsn(0x50),
   11793            1 :                     is_delta: true,
   11794            1 :                 },
   11795              :             ],
   11796              :         );
   11797            2 :         Ok(())
   11798            1 :     }
   11799              : 
   11800              :     #[cfg(feature = "testing")]
   11801              :     #[tokio::test]
   11802            1 :     async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
   11803            1 :         let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
   11804            1 :             .await
   11805            1 :             .unwrap();
   11806            1 :         let (tenant, ctx) = harness.load().await;
   11807            1 :         let tline_parent = tenant
   11808            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
   11809            1 :             .await
   11810            1 :             .unwrap();
   11811            1 :         let tline_child = tenant
   11812            1 :             .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
   11813            1 :             .await
   11814            1 :             .unwrap();
   11815              :         {
   11816            1 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11817            1 :             assert_eq!(
   11818            1 :                 gc_info_parent.retain_lsns,
   11819            1 :                 vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
   11820              :             );
   11821              :         }
   11822              :         // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
   11823            1 :         tline_child
   11824            1 :             .remote_client
   11825            1 :             .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
   11826            1 :             .unwrap();
   11827            1 :         tline_child.remote_client.wait_completion().await.unwrap();
   11828            1 :         offload_timeline(&tenant, &tline_child)
   11829            1 :             .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
   11830            1 :             .await.unwrap();
   11831            1 :         let child_timeline_id = tline_child.timeline_id;
   11832            1 :         Arc::try_unwrap(tline_child).unwrap();
   11833              : 
   11834              :         {
   11835            1 :             let gc_info_parent = tline_parent.gc_info.read().unwrap();
   11836            1 :             assert_eq!(
   11837            1 :                 gc_info_parent.retain_lsns,
   11838            1 :                 vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
   11839              :             );
   11840              :         }
   11841              : 
   11842            1 :         tenant
   11843            1 :             .get_offloaded_timeline(child_timeline_id)
   11844            1 :             .unwrap()
   11845            1 :             .defuse_for_tenant_drop();
   11846              : 
   11847            2 :         Ok(())
   11848            1 :     }
   11849              : 
   11850              :     #[cfg(feature = "testing")]
   11851              :     #[tokio::test]
   11852            1 :     async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
   11853            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
   11854            1 :         let (tenant, ctx) = harness.load().await;
   11855              : 
   11856          148 :         fn get_key(id: u32) -> Key {
   11857              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   11858          148 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   11859          148 :             key.field6 = id;
   11860          148 :             key
   11861          148 :         }
   11862              : 
   11863            1 :         let img_layer = (0..10)
   11864           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   11865            1 :             .collect_vec();
   11866              : 
   11867            1 :         let delta1 = vec![(
   11868            1 :             get_key(1),
   11869            1 :             Lsn(0x20),
   11870            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   11871            1 :         )];
   11872            1 :         let delta4 = vec![(
   11873            1 :             get_key(1),
   11874            1 :             Lsn(0x28),
   11875            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   11876            1 :         )];
   11877            1 :         let delta2 = vec![
   11878            1 :             (
   11879            1 :                 get_key(1),
   11880            1 :                 Lsn(0x30),
   11881            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   11882            1 :             ),
   11883            1 :             (
   11884            1 :                 get_key(1),
   11885            1 :                 Lsn(0x38),
   11886            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   11887            1 :             ),
   11888              :         ];
   11889            1 :         let delta3 = vec![
   11890            1 :             (
   11891            1 :                 get_key(8),
   11892            1 :                 Lsn(0x48),
   11893            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11894            1 :             ),
   11895            1 :             (
   11896            1 :                 get_key(9),
   11897            1 :                 Lsn(0x48),
   11898            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   11899            1 :             ),
   11900              :         ];
   11901              : 
   11902            1 :         let tline = tenant
   11903            1 :             .create_test_timeline_with_layers(
   11904            1 :                 TIMELINE_ID,
   11905            1 :                 Lsn(0x10),
   11906            1 :                 DEFAULT_PG_VERSION,
   11907            1 :                 &ctx,
   11908            1 :                 vec![], // in-memory layers
   11909            1 :                 vec![
   11910            1 :                     // delta1/2/4 only contain a single key but multiple updates
   11911            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   11912            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   11913            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   11914            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   11915            1 :                 ], // delta layers
   11916            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   11917            1 :                 Lsn(0x50),
   11918            1 :             )
   11919            1 :             .await?;
   11920              :         {
   11921            1 :             tline
   11922            1 :                 .applied_gc_cutoff_lsn
   11923            1 :                 .lock_for_write()
   11924            1 :                 .store_and_unlock(Lsn(0x30))
   11925            1 :                 .wait()
   11926            1 :                 .await;
   11927              :             // Update GC info
   11928            1 :             let mut guard = tline.gc_info.write().unwrap();
   11929            1 :             *guard = GcInfo {
   11930            1 :                 retain_lsns: vec![
   11931            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   11932            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   11933            1 :                 ],
   11934            1 :                 cutoffs: GcCutoffs {
   11935            1 :                     time: Some(Lsn(0x30)),
   11936            1 :                     space: Lsn(0x30),
   11937            1 :                 },
   11938            1 :                 leases: Default::default(),
   11939            1 :                 within_ancestor_pitr: false,
   11940            1 :             };
   11941              :         }
   11942              : 
   11943            1 :         let expected_result = [
   11944            1 :             Bytes::from_static(b"value 0@0x10"),
   11945            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   11946            1 :             Bytes::from_static(b"value 2@0x10"),
   11947            1 :             Bytes::from_static(b"value 3@0x10"),
   11948            1 :             Bytes::from_static(b"value 4@0x10"),
   11949            1 :             Bytes::from_static(b"value 5@0x10"),
   11950            1 :             Bytes::from_static(b"value 6@0x10"),
   11951            1 :             Bytes::from_static(b"value 7@0x10"),
   11952            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   11953            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   11954            1 :         ];
   11955              : 
   11956            1 :         let expected_result_at_gc_horizon = [
   11957            1 :             Bytes::from_static(b"value 0@0x10"),
   11958            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   11959            1 :             Bytes::from_static(b"value 2@0x10"),
   11960            1 :             Bytes::from_static(b"value 3@0x10"),
   11961            1 :             Bytes::from_static(b"value 4@0x10"),
   11962            1 :             Bytes::from_static(b"value 5@0x10"),
   11963            1 :             Bytes::from_static(b"value 6@0x10"),
   11964            1 :             Bytes::from_static(b"value 7@0x10"),
   11965            1 :             Bytes::from_static(b"value 8@0x10"),
   11966            1 :             Bytes::from_static(b"value 9@0x10"),
   11967            1 :         ];
   11968              : 
   11969            1 :         let expected_result_at_lsn_20 = [
   11970            1 :             Bytes::from_static(b"value 0@0x10"),
   11971            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   11972            1 :             Bytes::from_static(b"value 2@0x10"),
   11973            1 :             Bytes::from_static(b"value 3@0x10"),
   11974            1 :             Bytes::from_static(b"value 4@0x10"),
   11975            1 :             Bytes::from_static(b"value 5@0x10"),
   11976            1 :             Bytes::from_static(b"value 6@0x10"),
   11977            1 :             Bytes::from_static(b"value 7@0x10"),
   11978            1 :             Bytes::from_static(b"value 8@0x10"),
   11979            1 :             Bytes::from_static(b"value 9@0x10"),
   11980            1 :         ];
   11981              : 
   11982            1 :         let expected_result_at_lsn_10 = [
   11983            1 :             Bytes::from_static(b"value 0@0x10"),
   11984            1 :             Bytes::from_static(b"value 1@0x10"),
   11985            1 :             Bytes::from_static(b"value 2@0x10"),
   11986            1 :             Bytes::from_static(b"value 3@0x10"),
   11987            1 :             Bytes::from_static(b"value 4@0x10"),
   11988            1 :             Bytes::from_static(b"value 5@0x10"),
   11989            1 :             Bytes::from_static(b"value 6@0x10"),
   11990            1 :             Bytes::from_static(b"value 7@0x10"),
   11991            1 :             Bytes::from_static(b"value 8@0x10"),
   11992            1 :             Bytes::from_static(b"value 9@0x10"),
   11993            1 :         ];
   11994              : 
   11995            3 :         let verify_result = || async {
   11996            3 :             let gc_horizon = {
   11997            3 :                 let gc_info = tline.gc_info.read().unwrap();
   11998            3 :                 gc_info.cutoffs.time.unwrap_or_default()
   11999              :             };
   12000           33 :             for idx in 0..10 {
   12001           30 :                 assert_eq!(
   12002           30 :                     tline
   12003           30 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   12004           30 :                         .await
   12005           30 :                         .unwrap(),
   12006           30 :                     &expected_result[idx]
   12007              :                 );
   12008           30 :                 assert_eq!(
   12009           30 :                     tline
   12010           30 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   12011           30 :                         .await
   12012           30 :                         .unwrap(),
   12013           30 :                     &expected_result_at_gc_horizon[idx]
   12014              :                 );
   12015           30 :                 assert_eq!(
   12016           30 :                     tline
   12017           30 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   12018           30 :                         .await
   12019           30 :                         .unwrap(),
   12020           30 :                     &expected_result_at_lsn_20[idx]
   12021              :                 );
   12022           30 :                 assert_eq!(
   12023           30 :                     tline
   12024           30 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   12025           30 :                         .await
   12026           30 :                         .unwrap(),
   12027           30 :                     &expected_result_at_lsn_10[idx]
   12028              :                 );
   12029              :             }
   12030            6 :         };
   12031              : 
   12032            1 :         verify_result().await;
   12033              : 
   12034            1 :         let cancel = CancellationToken::new();
   12035            1 :         tline
   12036            1 :             .compact_with_gc(
   12037            1 :                 &cancel,
   12038            1 :                 CompactOptions {
   12039            1 :                     compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
   12040            1 :                     ..Default::default()
   12041            1 :                 },
   12042            1 :                 &ctx,
   12043            1 :             )
   12044            1 :             .await
   12045            1 :             .unwrap();
   12046            1 :         verify_result().await;
   12047              : 
   12048            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12049            1 :         check_layer_map_key_eq(
   12050            1 :             all_layers,
   12051            1 :             vec![
   12052              :                 // The original image layer, not compacted
   12053            1 :                 PersistentLayerKey {
   12054            1 :                     key_range: get_key(0)..get_key(10),
   12055            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12056            1 :                     is_delta: false,
   12057            1 :                 },
   12058              :                 // Delta layer below the specified above_lsn not compacted
   12059            1 :                 PersistentLayerKey {
   12060            1 :                     key_range: get_key(1)..get_key(2),
   12061            1 :                     lsn_range: Lsn(0x20)..Lsn(0x28),
   12062            1 :                     is_delta: true,
   12063            1 :                 },
   12064              :                 // Delta layer compacted above the LSN
   12065            1 :                 PersistentLayerKey {
   12066            1 :                     key_range: get_key(1)..get_key(10),
   12067            1 :                     lsn_range: Lsn(0x28)..Lsn(0x50),
   12068            1 :                     is_delta: true,
   12069            1 :                 },
   12070              :             ],
   12071              :         );
   12072              : 
   12073              :         // compact again
   12074            1 :         tline
   12075            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   12076            1 :             .await
   12077            1 :             .unwrap();
   12078            1 :         verify_result().await;
   12079              : 
   12080            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12081            1 :         check_layer_map_key_eq(
   12082            1 :             all_layers,
   12083            1 :             vec![
   12084              :                 // The compacted image layer (full key range)
   12085            1 :                 PersistentLayerKey {
   12086            1 :                     key_range: Key::MIN..Key::MAX,
   12087            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12088            1 :                     is_delta: false,
   12089            1 :                 },
   12090              :                 // All other data in the delta layer
   12091            1 :                 PersistentLayerKey {
   12092            1 :                     key_range: get_key(1)..get_key(10),
   12093            1 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12094            1 :                     is_delta: true,
   12095            1 :                 },
   12096              :             ],
   12097              :         );
   12098              : 
   12099            2 :         Ok(())
   12100            1 :     }
   12101              : 
   12102              :     #[cfg(feature = "testing")]
   12103              :     #[tokio::test]
   12104            1 :     async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
   12105            1 :         let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
   12106            1 :         let (tenant, ctx) = harness.load().await;
   12107              : 
   12108          254 :         fn get_key(id: u32) -> Key {
   12109              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12110          254 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12111          254 :             key.field6 = id;
   12112          254 :             key
   12113          254 :         }
   12114              : 
   12115            1 :         let img_layer = (0..10)
   12116           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12117            1 :             .collect_vec();
   12118              : 
   12119            1 :         let delta1 = vec![(
   12120            1 :             get_key(1),
   12121            1 :             Lsn(0x20),
   12122            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12123            1 :         )];
   12124            1 :         let delta4 = vec![(
   12125            1 :             get_key(1),
   12126            1 :             Lsn(0x28),
   12127            1 :             Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
   12128            1 :         )];
   12129            1 :         let delta2 = vec![
   12130            1 :             (
   12131            1 :                 get_key(1),
   12132            1 :                 Lsn(0x30),
   12133            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
   12134            1 :             ),
   12135            1 :             (
   12136            1 :                 get_key(1),
   12137            1 :                 Lsn(0x38),
   12138            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
   12139            1 :             ),
   12140              :         ];
   12141            1 :         let delta3 = vec![
   12142            1 :             (
   12143            1 :                 get_key(8),
   12144            1 :                 Lsn(0x48),
   12145            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   12146            1 :             ),
   12147            1 :             (
   12148            1 :                 get_key(9),
   12149            1 :                 Lsn(0x48),
   12150            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
   12151            1 :             ),
   12152              :         ];
   12153              : 
   12154            1 :         let tline = tenant
   12155            1 :             .create_test_timeline_with_layers(
   12156            1 :                 TIMELINE_ID,
   12157            1 :                 Lsn(0x10),
   12158            1 :                 DEFAULT_PG_VERSION,
   12159            1 :                 &ctx,
   12160            1 :                 vec![], // in-memory layers
   12161            1 :                 vec![
   12162            1 :                     // delta1/2/4 only contain a single key but multiple updates
   12163            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
   12164            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
   12165            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
   12166            1 :                     DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
   12167            1 :                 ], // delta layers
   12168            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12169            1 :                 Lsn(0x50),
   12170            1 :             )
   12171            1 :             .await?;
   12172              :         {
   12173            1 :             tline
   12174            1 :                 .applied_gc_cutoff_lsn
   12175            1 :                 .lock_for_write()
   12176            1 :                 .store_and_unlock(Lsn(0x30))
   12177            1 :                 .wait()
   12178            1 :                 .await;
   12179              :             // Update GC info
   12180            1 :             let mut guard = tline.gc_info.write().unwrap();
   12181            1 :             *guard = GcInfo {
   12182            1 :                 retain_lsns: vec![
   12183            1 :                     (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
   12184            1 :                     (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
   12185            1 :                 ],
   12186            1 :                 cutoffs: GcCutoffs {
   12187            1 :                     time: Some(Lsn(0x30)),
   12188            1 :                     space: Lsn(0x30),
   12189            1 :                 },
   12190            1 :                 leases: Default::default(),
   12191            1 :                 within_ancestor_pitr: false,
   12192            1 :             };
   12193              :         }
   12194              : 
   12195            1 :         let expected_result = [
   12196            1 :             Bytes::from_static(b"value 0@0x10"),
   12197            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
   12198            1 :             Bytes::from_static(b"value 2@0x10"),
   12199            1 :             Bytes::from_static(b"value 3@0x10"),
   12200            1 :             Bytes::from_static(b"value 4@0x10"),
   12201            1 :             Bytes::from_static(b"value 5@0x10"),
   12202            1 :             Bytes::from_static(b"value 6@0x10"),
   12203            1 :             Bytes::from_static(b"value 7@0x10"),
   12204            1 :             Bytes::from_static(b"value 8@0x10@0x48"),
   12205            1 :             Bytes::from_static(b"value 9@0x10@0x48"),
   12206            1 :         ];
   12207              : 
   12208            1 :         let expected_result_at_gc_horizon = [
   12209            1 :             Bytes::from_static(b"value 0@0x10"),
   12210            1 :             Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
   12211            1 :             Bytes::from_static(b"value 2@0x10"),
   12212            1 :             Bytes::from_static(b"value 3@0x10"),
   12213            1 :             Bytes::from_static(b"value 4@0x10"),
   12214            1 :             Bytes::from_static(b"value 5@0x10"),
   12215            1 :             Bytes::from_static(b"value 6@0x10"),
   12216            1 :             Bytes::from_static(b"value 7@0x10"),
   12217            1 :             Bytes::from_static(b"value 8@0x10"),
   12218            1 :             Bytes::from_static(b"value 9@0x10"),
   12219            1 :         ];
   12220              : 
   12221            1 :         let expected_result_at_lsn_20 = [
   12222            1 :             Bytes::from_static(b"value 0@0x10"),
   12223            1 :             Bytes::from_static(b"value 1@0x10@0x20"),
   12224            1 :             Bytes::from_static(b"value 2@0x10"),
   12225            1 :             Bytes::from_static(b"value 3@0x10"),
   12226            1 :             Bytes::from_static(b"value 4@0x10"),
   12227            1 :             Bytes::from_static(b"value 5@0x10"),
   12228            1 :             Bytes::from_static(b"value 6@0x10"),
   12229            1 :             Bytes::from_static(b"value 7@0x10"),
   12230            1 :             Bytes::from_static(b"value 8@0x10"),
   12231            1 :             Bytes::from_static(b"value 9@0x10"),
   12232            1 :         ];
   12233              : 
   12234            1 :         let expected_result_at_lsn_10 = [
   12235            1 :             Bytes::from_static(b"value 0@0x10"),
   12236            1 :             Bytes::from_static(b"value 1@0x10"),
   12237            1 :             Bytes::from_static(b"value 2@0x10"),
   12238            1 :             Bytes::from_static(b"value 3@0x10"),
   12239            1 :             Bytes::from_static(b"value 4@0x10"),
   12240            1 :             Bytes::from_static(b"value 5@0x10"),
   12241            1 :             Bytes::from_static(b"value 6@0x10"),
   12242            1 :             Bytes::from_static(b"value 7@0x10"),
   12243            1 :             Bytes::from_static(b"value 8@0x10"),
   12244            1 :             Bytes::from_static(b"value 9@0x10"),
   12245            1 :         ];
   12246              : 
   12247            5 :         let verify_result = || async {
   12248            5 :             let gc_horizon = {
   12249            5 :                 let gc_info = tline.gc_info.read().unwrap();
   12250            5 :                 gc_info.cutoffs.time.unwrap_or_default()
   12251              :             };
   12252           55 :             for idx in 0..10 {
   12253           50 :                 assert_eq!(
   12254           50 :                     tline
   12255           50 :                         .get(get_key(idx as u32), Lsn(0x50), &ctx)
   12256           50 :                         .await
   12257           50 :                         .unwrap(),
   12258           50 :                     &expected_result[idx]
   12259              :                 );
   12260           50 :                 assert_eq!(
   12261           50 :                     tline
   12262           50 :                         .get(get_key(idx as u32), gc_horizon, &ctx)
   12263           50 :                         .await
   12264           50 :                         .unwrap(),
   12265           50 :                     &expected_result_at_gc_horizon[idx]
   12266              :                 );
   12267           50 :                 assert_eq!(
   12268           50 :                     tline
   12269           50 :                         .get(get_key(idx as u32), Lsn(0x20), &ctx)
   12270           50 :                         .await
   12271           50 :                         .unwrap(),
   12272           50 :                     &expected_result_at_lsn_20[idx]
   12273              :                 );
   12274           50 :                 assert_eq!(
   12275           50 :                     tline
   12276           50 :                         .get(get_key(idx as u32), Lsn(0x10), &ctx)
   12277           50 :                         .await
   12278           50 :                         .unwrap(),
   12279           50 :                     &expected_result_at_lsn_10[idx]
   12280              :                 );
   12281              :             }
   12282           10 :         };
   12283              : 
   12284            1 :         verify_result().await;
   12285              : 
   12286            1 :         let cancel = CancellationToken::new();
   12287              : 
   12288            1 :         tline
   12289            1 :             .compact_with_gc(
   12290            1 :                 &cancel,
   12291            1 :                 CompactOptions {
   12292            1 :                     compact_key_range: Some((get_key(0)..get_key(2)).into()),
   12293            1 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
   12294            1 :                     ..Default::default()
   12295            1 :                 },
   12296            1 :                 &ctx,
   12297            1 :             )
   12298            1 :             .await
   12299            1 :             .unwrap();
   12300            1 :         verify_result().await;
   12301              : 
   12302            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12303            1 :         check_layer_map_key_eq(
   12304            1 :             all_layers,
   12305            1 :             vec![
   12306              :                 // The original image layer, not compacted
   12307            1 :                 PersistentLayerKey {
   12308            1 :                     key_range: get_key(0)..get_key(10),
   12309            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12310            1 :                     is_delta: false,
   12311            1 :                 },
   12312              :                 // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
   12313              :                 // the layer 0x28-0x30 into one.
   12314            1 :                 PersistentLayerKey {
   12315            1 :                     key_range: get_key(1)..get_key(2),
   12316            1 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12317            1 :                     is_delta: true,
   12318            1 :                 },
   12319              :                 // Above the upper bound and untouched
   12320            1 :                 PersistentLayerKey {
   12321            1 :                     key_range: get_key(1)..get_key(2),
   12322            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12323            1 :                     is_delta: true,
   12324            1 :                 },
   12325              :                 // This layer is untouched
   12326            1 :                 PersistentLayerKey {
   12327            1 :                     key_range: get_key(8)..get_key(10),
   12328            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12329            1 :                     is_delta: true,
   12330            1 :                 },
   12331              :             ],
   12332              :         );
   12333              : 
   12334            1 :         tline
   12335            1 :             .compact_with_gc(
   12336            1 :                 &cancel,
   12337            1 :                 CompactOptions {
   12338            1 :                     compact_key_range: Some((get_key(3)..get_key(8)).into()),
   12339            1 :                     compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
   12340            1 :                     ..Default::default()
   12341            1 :                 },
   12342            1 :                 &ctx,
   12343            1 :             )
   12344            1 :             .await
   12345            1 :             .unwrap();
   12346            1 :         verify_result().await;
   12347              : 
   12348            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12349            1 :         check_layer_map_key_eq(
   12350            1 :             all_layers,
   12351            1 :             vec![
   12352              :                 // The original image layer, not compacted
   12353            1 :                 PersistentLayerKey {
   12354            1 :                     key_range: get_key(0)..get_key(10),
   12355            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12356            1 :                     is_delta: false,
   12357            1 :                 },
   12358              :                 // Not in the compaction key range, uncompacted
   12359            1 :                 PersistentLayerKey {
   12360            1 :                     key_range: get_key(1)..get_key(2),
   12361            1 :                     lsn_range: Lsn(0x20)..Lsn(0x30),
   12362            1 :                     is_delta: true,
   12363            1 :                 },
   12364              :                 // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
   12365            1 :                 PersistentLayerKey {
   12366            1 :                     key_range: get_key(1)..get_key(2),
   12367            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12368            1 :                     is_delta: true,
   12369            1 :                 },
   12370              :                 // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
   12371              :                 // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
   12372              :                 // becomes 0x50.
   12373            1 :                 PersistentLayerKey {
   12374            1 :                     key_range: get_key(8)..get_key(10),
   12375            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12376            1 :                     is_delta: true,
   12377            1 :                 },
   12378              :             ],
   12379              :         );
   12380              : 
   12381              :         // compact again
   12382            1 :         tline
   12383            1 :             .compact_with_gc(
   12384            1 :                 &cancel,
   12385            1 :                 CompactOptions {
   12386            1 :                     compact_key_range: Some((get_key(0)..get_key(5)).into()),
   12387            1 :                     compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
   12388            1 :                     ..Default::default()
   12389            1 :                 },
   12390            1 :                 &ctx,
   12391            1 :             )
   12392            1 :             .await
   12393            1 :             .unwrap();
   12394            1 :         verify_result().await;
   12395              : 
   12396            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12397            1 :         check_layer_map_key_eq(
   12398            1 :             all_layers,
   12399            1 :             vec![
   12400              :                 // The original image layer, not compacted
   12401            1 :                 PersistentLayerKey {
   12402            1 :                     key_range: get_key(0)..get_key(10),
   12403            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12404            1 :                     is_delta: false,
   12405            1 :                 },
   12406              :                 // The range gets compacted
   12407            1 :                 PersistentLayerKey {
   12408            1 :                     key_range: get_key(1)..get_key(2),
   12409            1 :                     lsn_range: Lsn(0x20)..Lsn(0x50),
   12410            1 :                     is_delta: true,
   12411            1 :                 },
   12412              :                 // Not touched during this iteration of compaction
   12413            1 :                 PersistentLayerKey {
   12414            1 :                     key_range: get_key(8)..get_key(10),
   12415            1 :                     lsn_range: Lsn(0x30)..Lsn(0x50),
   12416            1 :                     is_delta: true,
   12417            1 :                 },
   12418              :             ],
   12419              :         );
   12420              : 
   12421              :         // final full compaction
   12422            1 :         tline
   12423            1 :             .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
   12424            1 :             .await
   12425            1 :             .unwrap();
   12426            1 :         verify_result().await;
   12427              : 
   12428            1 :         let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
   12429            1 :         check_layer_map_key_eq(
   12430            1 :             all_layers,
   12431            1 :             vec![
   12432              :                 // The compacted image layer (full key range)
   12433            1 :                 PersistentLayerKey {
   12434            1 :                     key_range: Key::MIN..Key::MAX,
   12435            1 :                     lsn_range: Lsn(0x10)..Lsn(0x11),
   12436            1 :                     is_delta: false,
   12437            1 :                 },
   12438              :                 // All other data in the delta layer
   12439            1 :                 PersistentLayerKey {
   12440            1 :                     key_range: get_key(1)..get_key(10),
   12441            1 :                     lsn_range: Lsn(0x10)..Lsn(0x50),
   12442            1 :                     is_delta: true,
   12443            1 :                 },
   12444              :             ],
   12445              :         );
   12446              : 
   12447            2 :         Ok(())
   12448            1 :     }
   12449              : 
   12450              :     #[cfg(feature = "testing")]
   12451              :     #[tokio::test]
   12452            1 :     async fn test_bottom_most_compation_redo_failure() -> anyhow::Result<()> {
   12453            1 :         let harness = TenantHarness::create("test_bottom_most_compation_redo_failure").await?;
   12454            1 :         let (tenant, ctx) = harness.load().await;
   12455              : 
   12456           13 :         fn get_key(id: u32) -> Key {
   12457              :             // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
   12458           13 :             let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
   12459           13 :             key.field6 = id;
   12460           13 :             key
   12461           13 :         }
   12462              : 
   12463            1 :         let img_layer = (0..10)
   12464           10 :             .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
   12465            1 :             .collect_vec();
   12466              : 
   12467            1 :         let delta1 = vec![
   12468            1 :             (
   12469            1 :                 get_key(1),
   12470            1 :                 Lsn(0x20),
   12471            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
   12472            1 :             ),
   12473            1 :             (
   12474            1 :                 get_key(1),
   12475            1 :                 Lsn(0x24),
   12476            1 :                 Value::WalRecord(NeonWalRecord::wal_append("@0x24")),
   12477            1 :             ),
   12478            1 :             (
   12479            1 :                 get_key(1),
   12480            1 :                 Lsn(0x28),
   12481            1 :                 // This record will fail to redo
   12482            1 :                 Value::WalRecord(NeonWalRecord::wal_append_conditional("@0x28", "???")),
   12483            1 :             ),
   12484              :         ];
   12485              : 
   12486            1 :         let tline = tenant
   12487            1 :             .create_test_timeline_with_layers(
   12488            1 :                 TIMELINE_ID,
   12489            1 :                 Lsn(0x10),
   12490            1 :                 DEFAULT_PG_VERSION,
   12491            1 :                 &ctx,
   12492            1 :                 vec![], // in-memory layers
   12493            1 :                 vec![DeltaLayerTestDesc::new_with_inferred_key_range(
   12494            1 :                     Lsn(0x20)..Lsn(0x30),
   12495            1 :                     delta1,
   12496            1 :                 )], // delta layers
   12497            1 :                 vec![(Lsn(0x10), img_layer)], // image layers
   12498            1 :                 Lsn(0x50),
   12499            1 :             )
   12500            1 :             .await?;
   12501              :         {
   12502            1 :             tline
   12503            1 :                 .applied_gc_cutoff_lsn
   12504            1 :                 .lock_for_write()
   12505            1 :                 .store_and_unlock(Lsn(0x30))
   12506            1 :                 .wait()
   12507            1 :                 .await;
   12508              :             // Update GC info
   12509            1 :             let mut guard = tline.gc_info.write().unwrap();
   12510            1 :             *guard = GcInfo {
   12511            1 :                 retain_lsns: vec![],
   12512            1 :                 cutoffs: GcCutoffs {
   12513            1 :                     time: Some(Lsn(0x30)),
   12514            1 :                     space: Lsn(0x30),
   12515            1 :                 },
   12516            1 :                 leases: Default::default(),
   12517            1 :                 within_ancestor_pitr: false,
   12518            1 :             };
   12519              :         }
   12520              : 
   12521            1 :         let cancel = CancellationToken::new();
   12522              : 
   12523              :         // Compaction will fail, but should not fire any critical error.
   12524              :         // Gc-compaction currently cannot figure out what keys are not in the keyspace during the compaction
   12525              :         // process. It will always try to redo the logs it reads and if it doesn't work, fail the entire
   12526              :         // compaction job. Tracked in <https://github.com/neondatabase/neon/issues/10395>.
   12527            1 :         let res = tline
   12528            1 :             .compact_with_gc(
   12529            1 :                 &cancel,
   12530            1 :                 CompactOptions {
   12531            1 :                     compact_key_range: None,
   12532            1 :                     compact_lsn_range: None,
   12533            1 :                     ..Default::default()
   12534            1 :                 },
   12535            1 :                 &ctx,
   12536            1 :             )
   12537            1 :             .await;
   12538            1 :         assert!(res.is_err());
   12539              : 
   12540            2 :         Ok(())
   12541            1 :     }
   12542              : 
   12543              :     #[cfg(feature = "testing")]
   12544              :     #[tokio::test]
   12545            1 :     async fn test_synthetic_size_calculation_with_invisible_branches() -> anyhow::Result<()> {
   12546              :         use pageserver_api::models::TimelineVisibilityState;
   12547              : 
   12548              :         use crate::tenant::size::gather_inputs;
   12549              : 
   12550            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
   12551            1 :             // Ensure that we don't compute gc_cutoffs (which needs reading the layer files)
   12552            1 :             pitr_interval: Some(Duration::ZERO),
   12553            1 :             ..Default::default()
   12554            1 :         };
   12555            1 :         let harness = TenantHarness::create_custom(
   12556            1 :             "test_synthetic_size_calculation_with_invisible_branches",
   12557            1 :             tenant_conf,
   12558            1 :             TenantId::generate(),
   12559            1 :             ShardIdentity::unsharded(),
   12560            1 :             Generation::new(0xdeadbeef),
   12561            1 :         )
   12562            1 :         .await?;
   12563            1 :         let (tenant, ctx) = harness.load().await;
   12564            1 :         let main_tline = tenant
   12565            1 :             .create_test_timeline_with_layers(
   12566            1 :                 TIMELINE_ID,
   12567            1 :                 Lsn(0x10),
   12568            1 :                 DEFAULT_PG_VERSION,
   12569            1 :                 &ctx,
   12570            1 :                 vec![],
   12571            1 :                 vec![],
   12572            1 :                 vec![],
   12573            1 :                 Lsn(0x100),
   12574            1 :             )
   12575            1 :             .await?;
   12576              : 
   12577            1 :         let snapshot1 = TimelineId::from_array(hex!("11223344556677881122334455667790"));
   12578            1 :         tenant
   12579            1 :             .branch_timeline_test_with_layers(
   12580            1 :                 &main_tline,
   12581            1 :                 snapshot1,
   12582            1 :                 Some(Lsn(0x20)),
   12583            1 :                 &ctx,
   12584            1 :                 vec![],
   12585            1 :                 vec![],
   12586            1 :                 Lsn(0x50),
   12587            1 :             )
   12588            1 :             .await?;
   12589            1 :         let snapshot2 = TimelineId::from_array(hex!("11223344556677881122334455667791"));
   12590            1 :         tenant
   12591            1 :             .branch_timeline_test_with_layers(
   12592            1 :                 &main_tline,
   12593            1 :                 snapshot2,
   12594            1 :                 Some(Lsn(0x30)),
   12595            1 :                 &ctx,
   12596            1 :                 vec![],
   12597            1 :                 vec![],
   12598            1 :                 Lsn(0x50),
   12599            1 :             )
   12600            1 :             .await?;
   12601            1 :         let snapshot3 = TimelineId::from_array(hex!("11223344556677881122334455667792"));
   12602            1 :         tenant
   12603            1 :             .branch_timeline_test_with_layers(
   12604            1 :                 &main_tline,
   12605            1 :                 snapshot3,
   12606            1 :                 Some(Lsn(0x40)),
   12607            1 :                 &ctx,
   12608            1 :                 vec![],
   12609            1 :                 vec![],
   12610            1 :                 Lsn(0x50),
   12611            1 :             )
   12612            1 :             .await?;
   12613            1 :         let limit = Arc::new(Semaphore::new(1));
   12614            1 :         let max_retention_period = None;
   12615            1 :         let mut logical_size_cache = HashMap::new();
   12616            1 :         let cause = LogicalSizeCalculationCause::EvictionTaskImitation;
   12617            1 :         let cancel = CancellationToken::new();
   12618              : 
   12619            1 :         let inputs = gather_inputs(
   12620            1 :             &tenant,
   12621            1 :             &limit,
   12622            1 :             max_retention_period,
   12623            1 :             &mut logical_size_cache,
   12624            1 :             cause,
   12625            1 :             &cancel,
   12626            1 :             &ctx,
   12627              :         )
   12628            1 :         .instrument(info_span!(
   12629              :             "gather_inputs",
   12630              :             tenant_id = "unknown",
   12631              :             shard_id = "unknown",
   12632              :         ))
   12633            1 :         .await?;
   12634              :         use crate::tenant::size::{LsnKind, ModelInputs, SegmentMeta};
   12635              :         use LsnKind::*;
   12636              :         use tenant_size_model::Segment;
   12637            1 :         let ModelInputs { mut segments, .. } = inputs;
   12638           15 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12639            6 :         for segment in segments.iter_mut() {
   12640            6 :             segment.segment.parent = None; // We don't care about the parent for the test
   12641            6 :             segment.segment.size = None; // We don't care about the size for the test
   12642            6 :         }
   12643            1 :         assert_eq!(
   12644              :             segments,
   12645              :             [
   12646              :                 SegmentMeta {
   12647              :                     segment: Segment {
   12648              :                         parent: None,
   12649              :                         lsn: 0x10,
   12650              :                         size: None,
   12651              :                         needed: false,
   12652              :                     },
   12653              :                     timeline_id: TIMELINE_ID,
   12654              :                     kind: BranchStart,
   12655              :                 },
   12656              :                 SegmentMeta {
   12657              :                     segment: Segment {
   12658              :                         parent: None,
   12659              :                         lsn: 0x20,
   12660              :                         size: None,
   12661              :                         needed: false,
   12662              :                     },
   12663              :                     timeline_id: TIMELINE_ID,
   12664              :                     kind: BranchPoint,
   12665              :                 },
   12666              :                 SegmentMeta {
   12667              :                     segment: Segment {
   12668              :                         parent: None,
   12669              :                         lsn: 0x30,
   12670              :                         size: None,
   12671              :                         needed: false,
   12672              :                     },
   12673              :                     timeline_id: TIMELINE_ID,
   12674              :                     kind: BranchPoint,
   12675              :                 },
   12676              :                 SegmentMeta {
   12677              :                     segment: Segment {
   12678              :                         parent: None,
   12679              :                         lsn: 0x40,
   12680              :                         size: None,
   12681              :                         needed: false,
   12682              :                     },
   12683              :                     timeline_id: TIMELINE_ID,
   12684              :                     kind: BranchPoint,
   12685              :                 },
   12686              :                 SegmentMeta {
   12687              :                     segment: Segment {
   12688              :                         parent: None,
   12689              :                         lsn: 0x100,
   12690              :                         size: None,
   12691              :                         needed: false,
   12692              :                     },
   12693              :                     timeline_id: TIMELINE_ID,
   12694              :                     kind: GcCutOff,
   12695              :                 }, // we need to retain everything above the last branch point
   12696              :                 SegmentMeta {
   12697              :                     segment: Segment {
   12698              :                         parent: None,
   12699              :                         lsn: 0x100,
   12700              :                         size: None,
   12701              :                         needed: true,
   12702              :                     },
   12703              :                     timeline_id: TIMELINE_ID,
   12704              :                     kind: BranchEnd,
   12705              :                 },
   12706              :             ]
   12707              :         );
   12708              : 
   12709            1 :         main_tline
   12710            1 :             .remote_client
   12711            1 :             .schedule_index_upload_for_timeline_invisible_state(
   12712            1 :                 TimelineVisibilityState::Invisible,
   12713            0 :             )?;
   12714            1 :         main_tline.remote_client.wait_completion().await?;
   12715            1 :         let inputs = gather_inputs(
   12716            1 :             &tenant,
   12717            1 :             &limit,
   12718            1 :             max_retention_period,
   12719            1 :             &mut logical_size_cache,
   12720            1 :             cause,
   12721            1 :             &cancel,
   12722            1 :             &ctx,
   12723              :         )
   12724            1 :         .instrument(info_span!(
   12725              :             "gather_inputs",
   12726              :             tenant_id = "unknown",
   12727              :             shard_id = "unknown",
   12728              :         ))
   12729            1 :         .await?;
   12730            1 :         let ModelInputs { mut segments, .. } = inputs;
   12731           14 :         segments.retain(|s| s.timeline_id == TIMELINE_ID);
   12732            5 :         for segment in segments.iter_mut() {
   12733            5 :             segment.segment.parent = None; // We don't care about the parent for the test
   12734            5 :             segment.segment.size = None; // We don't care about the size for the test
   12735            5 :         }
   12736            1 :         assert_eq!(
   12737              :             segments,
   12738              :             [
   12739              :                 SegmentMeta {
   12740              :                     segment: Segment {
   12741              :                         parent: None,
   12742              :                         lsn: 0x10,
   12743              :                         size: None,
   12744              :                         needed: false,
   12745              :                     },
   12746              :                     timeline_id: TIMELINE_ID,
   12747              :                     kind: BranchStart,
   12748              :                 },
   12749              :                 SegmentMeta {
   12750              :                     segment: Segment {
   12751              :                         parent: None,
   12752              :                         lsn: 0x20,
   12753              :                         size: None,
   12754              :                         needed: false,
   12755              :                     },
   12756              :                     timeline_id: TIMELINE_ID,
   12757              :                     kind: BranchPoint,
   12758              :                 },
   12759              :                 SegmentMeta {
   12760              :                     segment: Segment {
   12761              :                         parent: None,
   12762              :                         lsn: 0x30,
   12763              :                         size: None,
   12764              :                         needed: false,
   12765              :                     },
   12766              :                     timeline_id: TIMELINE_ID,
   12767              :                     kind: BranchPoint,
   12768              :                 },
   12769              :                 SegmentMeta {
   12770              :                     segment: Segment {
   12771              :                         parent: None,
   12772              :                         lsn: 0x40,
   12773              :                         size: None,
   12774              :                         needed: false,
   12775              :                     },
   12776              :                     timeline_id: TIMELINE_ID,
   12777              :                     kind: BranchPoint,
   12778              :                 },
   12779              :                 SegmentMeta {
   12780              :                     segment: Segment {
   12781              :                         parent: None,
   12782              :                         lsn: 0x40, // Branch end LSN == last branch point LSN
   12783              :                         size: None,
   12784              :                         needed: true,
   12785              :                     },
   12786              :                     timeline_id: TIMELINE_ID,
   12787              :                     kind: BranchEnd,
   12788              :                 },
   12789              :             ]
   12790              :         );
   12791            2 :         Ok(())
   12792            1 :     }
   12793              : }
        

Generated by: LCOV version 2.1-beta