LCOV - code coverage report
Current view: top level - pageserver/src - pgdatadir_mapping.rs (source / functions) Coverage Total Hit
Test: 1e20c4f2b28aa592527961bb32170ebbd2c9172f.info Lines: 56.5 % 1864 1054
Test Date: 2025-07-16 12:29:03 Functions: 50.8 % 197 100

            Line data    Source code
       1              : //!
       2              : //! This provides an abstraction to store PostgreSQL relations and other files
       3              : //! in the key-value store that implements the Repository interface.
       4              : //!
       5              : //! (TODO: The line between PUT-functions here and walingest.rs is a bit blurry, as
       6              : //! walingest.rs handles a few things like implicit relation creation and extension.
       7              : //! Clarify that)
       8              : //!
       9              : use std::collections::{HashMap, HashSet, hash_map};
      10              : use std::ops::{ControlFlow, Range};
      11              : 
      12              : use crate::walingest::{WalIngestError, WalIngestErrorKind};
      13              : use crate::{PERF_TRACE_TARGET, ensure_walingest};
      14              : use anyhow::Context;
      15              : use bytes::{Buf, Bytes, BytesMut};
      16              : use enum_map::Enum;
      17              : use pageserver_api::key::{
      18              :     AUX_FILES_KEY, CHECKPOINT_KEY, CONTROLFILE_KEY, CompactKey, DBDIR_KEY, Key, RelDirExists,
      19              :     TWOPHASEDIR_KEY, dbdir_key_range, rel_block_to_key, rel_dir_to_key, rel_key_range,
      20              :     rel_size_to_key, rel_tag_sparse_key, rel_tag_sparse_key_range, relmap_file_key,
      21              :     repl_origin_key, repl_origin_key_range, slru_block_to_key, slru_dir_to_key,
      22              :     slru_segment_key_range, slru_segment_size_to_key, twophase_file_key, twophase_key_range,
      23              : };
      24              : use pageserver_api::keyspace::{KeySpaceRandomAccum, SparseKeySpace};
      25              : use pageserver_api::models::RelSizeMigration;
      26              : use pageserver_api::reltag::{BlockNumber, RelTag, SlruKind};
      27              : use pageserver_api::shard::ShardIdentity;
      28              : use postgres_ffi::{BLCKSZ, PgMajorVersion, TransactionId};
      29              : use postgres_ffi_types::forknum::{FSM_FORKNUM, VISIBILITYMAP_FORKNUM};
      30              : use postgres_ffi_types::{Oid, RepOriginId, TimestampTz};
      31              : use serde::{Deserialize, Serialize};
      32              : use strum::IntoEnumIterator;
      33              : use tokio_util::sync::CancellationToken;
      34              : use tracing::{debug, info, info_span, trace, warn};
      35              : use utils::bin_ser::{BeSer, DeserializeError};
      36              : use utils::lsn::Lsn;
      37              : use utils::pausable_failpoint;
      38              : use wal_decoder::models::record::NeonWalRecord;
      39              : use wal_decoder::models::value::Value;
      40              : use wal_decoder::serialized_batch::{SerializedValueBatch, ValueMeta};
      41              : 
      42              : use super::tenant::{PageReconstructError, Timeline};
      43              : use crate::aux_file;
      44              : use crate::context::{PerfInstrumentFutureExt, RequestContext, RequestContextBuilder};
      45              : use crate::keyspace::{KeySpace, KeySpaceAccum};
      46              : use crate::metrics::{
      47              :     RELSIZE_CACHE_MISSES_OLD, RELSIZE_LATEST_CACHE_ENTRIES, RELSIZE_LATEST_CACHE_HITS,
      48              :     RELSIZE_LATEST_CACHE_MISSES, RELSIZE_SNAPSHOT_CACHE_ENTRIES, RELSIZE_SNAPSHOT_CACHE_HITS,
      49              :     RELSIZE_SNAPSHOT_CACHE_MISSES,
      50              : };
      51              : use crate::span::{
      52              :     debug_assert_current_span_has_tenant_and_timeline_id,
      53              :     debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id,
      54              : };
      55              : use crate::tenant::storage_layer::IoConcurrency;
      56              : use crate::tenant::timeline::{GetVectoredError, VersionedKeySpaceQuery};
      57              : 
      58              : /// Max delta records appended to the AUX_FILES_KEY (for aux v1). The write path will write a full image once this threshold is reached.
      59              : pub const MAX_AUX_FILE_DELTAS: usize = 1024;
      60              : 
      61              : /// Max number of aux-file-related delta layers. The compaction will create a new image layer once this threshold is reached.
      62              : pub const MAX_AUX_FILE_V2_DELTAS: usize = 16;
      63              : 
      64              : #[derive(Debug)]
      65              : pub enum LsnForTimestamp {
      66              :     /// Found commits both before and after the given timestamp
      67              :     Present(Lsn),
      68              : 
      69              :     /// Found no commits after the given timestamp, this means
      70              :     /// that the newest data in the branch is older than the given
      71              :     /// timestamp.
      72              :     ///
      73              :     /// All commits <= LSN happened before the given timestamp
      74              :     Future(Lsn),
      75              : 
      76              :     /// The queried timestamp is past our horizon we look back at (PITR)
      77              :     ///
      78              :     /// All commits > LSN happened after the given timestamp,
      79              :     /// but any commits < LSN might have happened before or after
      80              :     /// the given timestamp. We don't know because no data before
      81              :     /// the given lsn is available.
      82              :     Past(Lsn),
      83              : 
      84              :     /// We have found no commit with a timestamp,
      85              :     /// so we can't return anything meaningful.
      86              :     ///
      87              :     /// The associated LSN is the lower bound value we can safely
      88              :     /// create branches on, but no statement is made if it is
      89              :     /// older or newer than the timestamp.
      90              :     ///
      91              :     /// This variant can e.g. be returned right after a
      92              :     /// cluster import.
      93              :     NoData(Lsn),
      94              : }
      95              : 
      96              : /// Each request to page server contains LSN range: `not_modified_since..request_lsn`.
      97              : /// See comments libs/pageserver_api/src/models.rs.
      98              : /// Based on this range and `last_record_lsn` PS calculates `effective_lsn`.
      99              : /// But to distinguish requests from primary and replicas we need also to pass `request_lsn`.
     100              : #[derive(Debug, Clone, Copy, Default)]
     101              : pub struct LsnRange {
     102              :     pub effective_lsn: Lsn,
     103              :     pub request_lsn: Lsn,
     104              : }
     105              : 
     106              : impl LsnRange {
     107            0 :     pub fn at(lsn: Lsn) -> LsnRange {
     108            0 :         LsnRange {
     109            0 :             effective_lsn: lsn,
     110            0 :             request_lsn: lsn,
     111            0 :         }
     112            0 :     }
     113           16 :     pub fn is_latest(&self) -> bool {
     114           16 :         self.request_lsn == Lsn::MAX
     115           16 :     }
     116              : }
     117              : 
     118              : #[derive(Debug, thiserror::Error)]
     119              : pub(crate) enum CalculateLogicalSizeError {
     120              :     #[error("cancelled")]
     121              :     Cancelled,
     122              : 
     123              :     /// Something went wrong while reading the metadata we use to calculate logical size
     124              :     /// Note that cancellation variants of `PageReconstructError` are transformed to [`Self::Cancelled`]
     125              :     /// in the `From` implementation for this variant.
     126              :     #[error(transparent)]
     127              :     PageRead(PageReconstructError),
     128              : 
     129              :     /// Something went wrong deserializing metadata that we read to calculate logical size
     130              :     #[error("decode error: {0}")]
     131              :     Decode(#[from] DeserializeError),
     132              : }
     133              : 
     134              : #[derive(Debug, thiserror::Error)]
     135              : pub(crate) enum CollectKeySpaceError {
     136              :     #[error(transparent)]
     137              :     Decode(#[from] DeserializeError),
     138              :     #[error(transparent)]
     139              :     PageRead(PageReconstructError),
     140              :     #[error("cancelled")]
     141              :     Cancelled,
     142              : }
     143              : 
     144              : impl CollectKeySpaceError {
     145            0 :     pub(crate) fn is_cancel(&self) -> bool {
     146            0 :         match self {
     147            0 :             CollectKeySpaceError::Decode(_) => false,
     148            0 :             CollectKeySpaceError::PageRead(e) => e.is_cancel(),
     149            0 :             CollectKeySpaceError::Cancelled => true,
     150              :         }
     151            0 :     }
     152            0 :     pub(crate) fn into_anyhow(self) -> anyhow::Error {
     153            0 :         match self {
     154            0 :             CollectKeySpaceError::Decode(e) => anyhow::Error::new(e),
     155            0 :             CollectKeySpaceError::PageRead(e) => anyhow::Error::new(e),
     156            0 :             CollectKeySpaceError::Cancelled => anyhow::Error::new(self),
     157              :         }
     158            0 :     }
     159              : }
     160              : 
     161              : impl From<PageReconstructError> for CollectKeySpaceError {
     162            0 :     fn from(err: PageReconstructError) -> Self {
     163            0 :         match err {
     164            0 :             PageReconstructError::Cancelled => Self::Cancelled,
     165            0 :             err => Self::PageRead(err),
     166              :         }
     167            0 :     }
     168              : }
     169              : 
     170              : impl From<PageReconstructError> for CalculateLogicalSizeError {
     171            0 :     fn from(pre: PageReconstructError) -> Self {
     172            0 :         match pre {
     173            0 :             PageReconstructError::Cancelled => Self::Cancelled,
     174            0 :             _ => Self::PageRead(pre),
     175              :         }
     176            0 :     }
     177              : }
     178              : 
     179              : #[derive(Debug, thiserror::Error)]
     180              : pub enum RelationError {
     181              :     #[error("invalid relnode")]
     182              :     InvalidRelnode,
     183              : }
     184              : 
     185              : ///
     186              : /// This impl provides all the functionality to store PostgreSQL relations, SLRUs,
     187              : /// and other special kinds of files, in a versioned key-value store. The
     188              : /// Timeline struct provides the key-value store.
     189              : ///
     190              : /// This is a separate impl, so that we can easily include all these functions in a Timeline
     191              : /// implementation, and might be moved into a separate struct later.
     192              : impl Timeline {
     193              :     /// Start ingesting a WAL record, or other atomic modification of
     194              :     /// the timeline.
     195              :     ///
     196              :     /// This provides a transaction-like interface to perform a bunch
     197              :     /// of modifications atomically.
     198              :     ///
     199              :     /// To ingest a WAL record, call begin_modification(lsn) to get a
     200              :     /// DatadirModification object. Use the functions in the object to
     201              :     /// modify the repository state, updating all the pages and metadata
     202              :     /// that the WAL record affects. When you're done, call commit() to
     203              :     /// commit the changes.
     204              :     ///
     205              :     /// Lsn stored in modification is advanced by `ingest_record` and
     206              :     /// is used by `commit()` to update `last_record_lsn`.
     207              :     ///
     208              :     /// Calling commit() will flush all the changes and reset the state,
     209              :     /// so the `DatadirModification` struct can be reused to perform the next modification.
     210              :     ///
     211              :     /// Note that any pending modifications you make through the
     212              :     /// modification object won't be visible to calls to the 'get' and list
     213              :     /// functions of the timeline until you finish! And if you update the
     214              :     /// same page twice, the last update wins.
     215              :     ///
     216       134215 :     pub fn begin_modification(&self, lsn: Lsn) -> DatadirModification
     217       134215 :     where
     218       134215 :         Self: Sized,
     219              :     {
     220       134215 :         DatadirModification {
     221       134215 :             tline: self,
     222       134215 :             pending_lsns: Vec::new(),
     223       134215 :             pending_metadata_pages: HashMap::new(),
     224       134215 :             pending_data_batch: None,
     225       134215 :             pending_deletions: Vec::new(),
     226       134215 :             pending_nblocks: 0,
     227       134215 :             pending_directory_entries: Vec::new(),
     228       134215 :             pending_metadata_bytes: 0,
     229       134215 :             lsn,
     230       134215 :         }
     231       134215 :     }
     232              : 
     233              :     //------------------------------------------------------------------------------
     234              :     // Public GET functions
     235              :     //------------------------------------------------------------------------------
     236              : 
     237              :     /// Look up given page version.
     238         9192 :     pub(crate) async fn get_rel_page_at_lsn(
     239         9192 :         &self,
     240         9192 :         tag: RelTag,
     241         9192 :         blknum: BlockNumber,
     242         9192 :         version: Version<'_>,
     243         9192 :         ctx: &RequestContext,
     244         9192 :         io_concurrency: IoConcurrency,
     245         9192 :     ) -> Result<Bytes, PageReconstructError> {
     246         9192 :         match version {
     247         9192 :             Version::LsnRange(lsns) => {
     248         9192 :                 let pages: smallvec::SmallVec<[_; 1]> = smallvec::smallvec![(tag, blknum)];
     249         9192 :                 let res = self
     250         9192 :                     .get_rel_page_at_lsn_batched(
     251         9192 :                         pages
     252         9192 :                             .iter()
     253         9192 :                             .map(|(tag, blknum)| (tag, blknum, lsns, ctx.attached_child())),
     254         9192 :                         io_concurrency.clone(),
     255         9192 :                         ctx,
     256              :                     )
     257         9192 :                     .await;
     258         9192 :                 assert_eq!(res.len(), 1);
     259         9192 :                 res.into_iter().next().unwrap()
     260              :             }
     261            0 :             Version::Modified(modification) => {
     262            0 :                 if tag.relnode == 0 {
     263            0 :                     return Err(PageReconstructError::Other(
     264            0 :                         RelationError::InvalidRelnode.into(),
     265            0 :                     ));
     266            0 :                 }
     267              : 
     268            0 :                 let nblocks = self.get_rel_size(tag, version, ctx).await?;
     269            0 :                 if blknum >= nblocks {
     270            0 :                     debug!(
     271            0 :                         "read beyond EOF at {} blk {} at {}, size is {}: returning all-zeros page",
     272              :                         tag,
     273              :                         blknum,
     274            0 :                         version.get_lsn(),
     275              :                         nblocks
     276              :                     );
     277            0 :                     return Ok(ZERO_PAGE.clone());
     278            0 :                 }
     279              : 
     280            0 :                 let key = rel_block_to_key(tag, blknum);
     281            0 :                 modification.get(key, ctx).await
     282              :             }
     283              :         }
     284         9192 :     }
     285              : 
     286              :     /// Like [`Self::get_rel_page_at_lsn`], but returns a batch of pages.
     287              :     ///
     288              :     /// The ordering of the returned vec corresponds to the ordering of `pages`.
     289         9192 :     pub(crate) async fn get_rel_page_at_lsn_batched(
     290         9192 :         &self,
     291         9192 :         pages: impl ExactSizeIterator<Item = (&RelTag, &BlockNumber, LsnRange, RequestContext)>,
     292         9192 :         io_concurrency: IoConcurrency,
     293         9192 :         ctx: &RequestContext,
     294         9192 :     ) -> Vec<Result<Bytes, PageReconstructError>> {
     295         9192 :         debug_assert_current_span_has_tenant_and_timeline_id();
     296              : 
     297         9192 :         let mut slots_filled = 0;
     298         9192 :         let page_count = pages.len();
     299              : 
     300              :         // Would be nice to use smallvec here but it doesn't provide the spare_capacity_mut() API.
     301         9192 :         let mut result = Vec::with_capacity(pages.len());
     302         9192 :         let result_slots = result.spare_capacity_mut();
     303              : 
     304         9192 :         let mut keys_slots: HashMap<Key, smallvec::SmallVec<[(usize, RequestContext); 1]>> =
     305         9192 :             HashMap::with_capacity(pages.len());
     306              : 
     307         9192 :         let mut req_keyspaces: HashMap<Lsn, KeySpaceRandomAccum> =
     308         9192 :             HashMap::with_capacity(pages.len());
     309              : 
     310         9192 :         for (response_slot_idx, (tag, blknum, lsns, ctx)) in pages.enumerate() {
     311         9192 :             if tag.relnode == 0 {
     312            0 :                 result_slots[response_slot_idx].write(Err(PageReconstructError::Other(
     313            0 :                     RelationError::InvalidRelnode.into(),
     314            0 :                 )));
     315              : 
     316            0 :                 slots_filled += 1;
     317            0 :                 continue;
     318         9192 :             }
     319         9192 :             let lsn = lsns.effective_lsn;
     320         9192 :             let nblocks = {
     321         9192 :                 let ctx = RequestContextBuilder::from(&ctx)
     322         9192 :                     .perf_span(|crnt_perf_span| {
     323            0 :                         info_span!(
     324              :                             target: PERF_TRACE_TARGET,
     325            0 :                             parent: crnt_perf_span,
     326              :                             "GET_REL_SIZE",
     327              :                             reltag=%tag,
     328              :                             lsn=%lsn,
     329              :                         )
     330            0 :                     })
     331         9192 :                     .attached_child();
     332              : 
     333         9192 :                 match self
     334         9192 :                     .get_rel_size(*tag, Version::LsnRange(lsns), &ctx)
     335         9192 :                     .maybe_perf_instrument(&ctx, |crnt_perf_span| crnt_perf_span.clone())
     336         9192 :                     .await
     337              :                 {
     338         9192 :                     Ok(nblocks) => nblocks,
     339            0 :                     Err(err) => {
     340            0 :                         result_slots[response_slot_idx].write(Err(err));
     341            0 :                         slots_filled += 1;
     342            0 :                         continue;
     343              :                     }
     344              :                 }
     345              :             };
     346              : 
     347         9192 :             if *blknum >= nblocks {
     348            0 :                 debug!(
     349            0 :                     "read beyond EOF at {} blk {} at {}, size is {}: returning all-zeros page",
     350              :                     tag, blknum, lsn, nblocks
     351              :                 );
     352            0 :                 result_slots[response_slot_idx].write(Ok(ZERO_PAGE.clone()));
     353            0 :                 slots_filled += 1;
     354            0 :                 continue;
     355         9192 :             }
     356              : 
     357         9192 :             let key = rel_block_to_key(*tag, *blknum);
     358              : 
     359         9192 :             let ctx = RequestContextBuilder::from(&ctx)
     360         9192 :                 .perf_span(|crnt_perf_span| {
     361            0 :                     info_span!(
     362              :                         target: PERF_TRACE_TARGET,
     363            0 :                         parent: crnt_perf_span,
     364              :                         "GET_BATCH",
     365              :                         batch_size = %page_count,
     366              :                     )
     367            0 :                 })
     368         9192 :                 .attached_child();
     369              : 
     370         9192 :             let key_slots = keys_slots.entry(key).or_default();
     371         9192 :             key_slots.push((response_slot_idx, ctx));
     372              : 
     373         9192 :             let acc = req_keyspaces.entry(lsn).or_default();
     374         9192 :             acc.add_key(key);
     375              :         }
     376              : 
     377         9192 :         let query: Vec<(Lsn, KeySpace)> = req_keyspaces
     378         9192 :             .into_iter()
     379         9192 :             .map(|(lsn, acc)| (lsn, acc.to_keyspace()))
     380         9192 :             .collect();
     381              : 
     382         9192 :         let query = VersionedKeySpaceQuery::scattered(query);
     383         9192 :         let res = self
     384         9192 :             .get_vectored(query, io_concurrency, ctx)
     385         9192 :             .maybe_perf_instrument(ctx, |current_perf_span| current_perf_span.clone())
     386         9192 :             .await;
     387              : 
     388         9192 :         match res {
     389         9192 :             Ok(results) => {
     390        18384 :                 for (key, res) in results {
     391         9192 :                     let mut key_slots = keys_slots.remove(&key).unwrap().into_iter();
     392         9192 :                     let (first_slot, first_req_ctx) = key_slots.next().unwrap();
     393              : 
     394         9192 :                     for (slot, req_ctx) in key_slots {
     395            0 :                         let clone = match &res {
     396            0 :                             Ok(buf) => Ok(buf.clone()),
     397            0 :                             Err(err) => Err(match err {
     398            0 :                                 PageReconstructError::Cancelled => PageReconstructError::Cancelled,
     399              : 
     400            0 :                                 x @ PageReconstructError::Other(_)
     401            0 :                                 | x @ PageReconstructError::AncestorLsnTimeout(_)
     402            0 :                                 | x @ PageReconstructError::WalRedo(_)
     403            0 :                                 | x @ PageReconstructError::MissingKey(_) => {
     404            0 :                                     PageReconstructError::Other(anyhow::anyhow!(
     405            0 :                                         "there was more than one request for this key in the batch, error logged once: {x:?}"
     406            0 :                                     ))
     407              :                                 }
     408              :                             }),
     409              :                         };
     410              : 
     411            0 :                         result_slots[slot].write(clone);
     412              :                         // There is no standardized way to express that the batched span followed from N request spans.
     413              :                         // So, abuse the system and mark the request contexts as follows_from the batch span, so we get
     414              :                         // some linkage in our trace viewer. It allows us to answer: which GET_VECTORED did this GET_PAGE wait for.
     415            0 :                         req_ctx.perf_follows_from(ctx);
     416            0 :                         slots_filled += 1;
     417              :                     }
     418              : 
     419         9192 :                     result_slots[first_slot].write(res);
     420         9192 :                     first_req_ctx.perf_follows_from(ctx);
     421         9192 :                     slots_filled += 1;
     422              :                 }
     423              :             }
     424            0 :             Err(err) => {
     425              :                 // this cannot really happen because get_vectored only errors globally on invalid LSN or too large batch size
     426              :                 // (We enforce the max batch size outside of this function, in the code that constructs the batch request.)
     427            0 :                 for (slot, req_ctx) in keys_slots.values().flatten() {
     428              :                     // this whole `match` is a lot like `From<GetVectoredError> for PageReconstructError`
     429              :                     // but without taking ownership of the GetVectoredError
     430            0 :                     let err = match &err {
     431            0 :                         GetVectoredError::Cancelled => Err(PageReconstructError::Cancelled),
     432              :                         // TODO: restructure get_vectored API to make this error per-key
     433            0 :                         GetVectoredError::MissingKey(err) => {
     434            0 :                             Err(PageReconstructError::Other(anyhow::anyhow!(
     435            0 :                                 "whole vectored get request failed because one or more of the requested keys were missing: {err:?}"
     436            0 :                             )))
     437              :                         }
     438              :                         // TODO: restructure get_vectored API to make this error per-key
     439            0 :                         GetVectoredError::GetReadyAncestorError(err) => {
     440            0 :                             Err(PageReconstructError::Other(anyhow::anyhow!(
     441            0 :                                 "whole vectored get request failed because one or more key required ancestor that wasn't ready: {err:?}"
     442            0 :                             )))
     443              :                         }
     444              :                         // TODO: restructure get_vectored API to make this error per-key
     445            0 :                         GetVectoredError::Other(err) => Err(PageReconstructError::Other(
     446            0 :                             anyhow::anyhow!("whole vectored get request failed: {err:?}"),
     447            0 :                         )),
     448              :                         // TODO: we can prevent this error class by moving this check into the type system
     449            0 :                         GetVectoredError::InvalidLsn(e) => {
     450            0 :                             Err(anyhow::anyhow!("invalid LSN: {e:?}").into())
     451              :                         }
     452              :                         // NB: this should never happen in practice because we limit batch size to be smaller than max_get_vectored_keys
     453              :                         // TODO: we can prevent this error class by moving this check into the type system
     454            0 :                         GetVectoredError::Oversized(err, max) => {
     455            0 :                             Err(anyhow::anyhow!("batching oversized: {err} > {max}").into())
     456              :                         }
     457              :                     };
     458              : 
     459            0 :                     req_ctx.perf_follows_from(ctx);
     460            0 :                     result_slots[*slot].write(err);
     461              :                 }
     462              : 
     463            0 :                 slots_filled += keys_slots.values().map(|slots| slots.len()).sum::<usize>();
     464              :             }
     465              :         };
     466              : 
     467         9192 :         assert_eq!(slots_filled, page_count);
     468              :         // SAFETY:
     469              :         // 1. `result` and any of its uninint members are not read from until this point
     470              :         // 2. The length below is tracked at run-time and matches the number of requested pages.
     471         9192 :         unsafe {
     472         9192 :             result.set_len(page_count);
     473         9192 :         }
     474              : 
     475         9192 :         result
     476         9192 :     }
     477              : 
     478              :     /// Get size of a database in blocks. This is only accurate on shard 0. It will undercount on
     479              :     /// other shards, by only accounting for relations the shard has pages for, and only accounting
     480              :     /// for pages up to the highest page number it has stored.
     481            0 :     pub(crate) async fn get_db_size(
     482            0 :         &self,
     483            0 :         spcnode: Oid,
     484            0 :         dbnode: Oid,
     485            0 :         version: Version<'_>,
     486            0 :         ctx: &RequestContext,
     487            0 :     ) -> Result<usize, PageReconstructError> {
     488            0 :         let mut total_blocks = 0;
     489              : 
     490            0 :         let rels = self.list_rels(spcnode, dbnode, version, ctx).await?;
     491              : 
     492            0 :         if rels.is_empty() {
     493            0 :             return Ok(0);
     494            0 :         }
     495              : 
     496              :         // Pre-deserialize the rel directory to avoid duplicated work in `get_relsize_cached`.
     497            0 :         let reldir_key = rel_dir_to_key(spcnode, dbnode);
     498            0 :         let buf = version.get(self, reldir_key, ctx).await?;
     499            0 :         let reldir = RelDirectory::des(&buf)?;
     500              : 
     501            0 :         for rel in rels {
     502            0 :             let n_blocks = self
     503            0 :                 .get_rel_size_in_reldir(rel, version, Some((reldir_key, &reldir)), ctx)
     504            0 :                 .await?;
     505            0 :             total_blocks += n_blocks as usize;
     506              :         }
     507            0 :         Ok(total_blocks)
     508            0 :     }
     509              : 
     510              :     /// Get size of a relation file. The relation must exist, otherwise an error is returned.
     511              :     ///
     512              :     /// This is only accurate on shard 0. On other shards, it will return the size up to the highest
     513              :     /// page number stored in the shard.
     514        12217 :     pub(crate) async fn get_rel_size(
     515        12217 :         &self,
     516        12217 :         tag: RelTag,
     517        12217 :         version: Version<'_>,
     518        12217 :         ctx: &RequestContext,
     519        12217 :     ) -> Result<BlockNumber, PageReconstructError> {
     520        12217 :         self.get_rel_size_in_reldir(tag, version, None, ctx).await
     521        12217 :     }
     522              : 
     523              :     /// Get size of a relation file. The relation must exist, otherwise an error is returned.
     524              :     ///
     525              :     /// See [`Self::get_rel_exists_in_reldir`] on why we need `deserialized_reldir_v1`.
     526        12217 :     pub(crate) async fn get_rel_size_in_reldir(
     527        12217 :         &self,
     528        12217 :         tag: RelTag,
     529        12217 :         version: Version<'_>,
     530        12217 :         deserialized_reldir_v1: Option<(Key, &RelDirectory)>,
     531        12217 :         ctx: &RequestContext,
     532        12217 :     ) -> Result<BlockNumber, PageReconstructError> {
     533        12217 :         if tag.relnode == 0 {
     534            0 :             return Err(PageReconstructError::Other(
     535            0 :                 RelationError::InvalidRelnode.into(),
     536            0 :             ));
     537        12217 :         }
     538              : 
     539        12217 :         if let Some(nblocks) = self.get_cached_rel_size(&tag, version) {
     540        12210 :             return Ok(nblocks);
     541            7 :         }
     542              : 
     543            7 :         if (tag.forknum == FSM_FORKNUM || tag.forknum == VISIBILITYMAP_FORKNUM)
     544            0 :             && !self
     545            0 :                 .get_rel_exists_in_reldir(tag, version, deserialized_reldir_v1, ctx)
     546            0 :                 .await?
     547              :         {
     548              :             // FIXME: Postgres sometimes calls smgrcreate() to create
     549              :             // FSM, and smgrnblocks() on it immediately afterwards,
     550              :             // without extending it.  Tolerate that by claiming that
     551              :             // any non-existent FSM fork has size 0.
     552            0 :             return Ok(0);
     553            7 :         }
     554              : 
     555            7 :         let key = rel_size_to_key(tag);
     556            7 :         let mut buf = version.get(self, key, ctx).await?;
     557            5 :         let nblocks = buf.get_u32_le();
     558              : 
     559            5 :         self.update_cached_rel_size(tag, version, nblocks);
     560              : 
     561            5 :         Ok(nblocks)
     562        12217 :     }
     563              : 
     564              :     /// Does the relation exist?
     565              :     ///
     566              :     /// Only shard 0 has a full view of the relations. Other shards only know about relations that
     567              :     /// the shard stores pages for.
     568              :     ///
     569         3025 :     pub(crate) async fn get_rel_exists(
     570         3025 :         &self,
     571         3025 :         tag: RelTag,
     572         3025 :         version: Version<'_>,
     573         3025 :         ctx: &RequestContext,
     574         3025 :     ) -> Result<bool, PageReconstructError> {
     575         3025 :         self.get_rel_exists_in_reldir(tag, version, None, ctx).await
     576         3025 :     }
     577              : 
     578              :     /// Does the relation exist? With a cached deserialized `RelDirectory`.
     579              :     ///
     580              :     /// There are some cases where the caller loops across all relations. In that specific case,
     581              :     /// the caller should obtain the deserialized `RelDirectory` first and then call this function
     582              :     /// to avoid duplicated work of deserliazation. This is a hack and should be removed by introducing
     583              :     /// a new API (e.g., `get_rel_exists_batched`).
     584         3025 :     pub(crate) async fn get_rel_exists_in_reldir(
     585         3025 :         &self,
     586         3025 :         tag: RelTag,
     587         3025 :         version: Version<'_>,
     588         3025 :         deserialized_reldir_v1: Option<(Key, &RelDirectory)>,
     589         3025 :         ctx: &RequestContext,
     590         3025 :     ) -> Result<bool, PageReconstructError> {
     591         3025 :         if tag.relnode == 0 {
     592            0 :             return Err(PageReconstructError::Other(
     593            0 :                 RelationError::InvalidRelnode.into(),
     594            0 :             ));
     595         3025 :         }
     596              : 
     597              :         // first try to lookup relation in cache
     598         3025 :         if let Some(_nblocks) = self.get_cached_rel_size(&tag, version) {
     599         3016 :             return Ok(true);
     600            9 :         }
     601              :         // then check if the database was already initialized.
     602              :         // get_rel_exists can be called before dbdir is created.
     603            9 :         let buf = version.get(self, DBDIR_KEY, ctx).await?;
     604            9 :         let dbdirs = DbDirectory::des(&buf)?.dbdirs;
     605            9 :         if !dbdirs.contains_key(&(tag.spcnode, tag.dbnode)) {
     606            0 :             return Ok(false);
     607            9 :         }
     608              : 
     609              :         // Read path: first read the new reldir keyspace. Early return if the relation exists.
     610              :         // Otherwise, read the old reldir keyspace.
     611              :         // TODO: if IndexPart::rel_size_migration is `Migrated`, we only need to read from v2.
     612              : 
     613              :         if let RelSizeMigration::Migrated | RelSizeMigration::Migrating =
     614            9 :             self.get_rel_size_v2_status()
     615              :         {
     616              :             // fetch directory listing (new)
     617            0 :             let key = rel_tag_sparse_key(tag.spcnode, tag.dbnode, tag.relnode, tag.forknum);
     618            0 :             let buf = RelDirExists::decode_option(version.sparse_get(self, key, ctx).await?)
     619            0 :                 .map_err(|_| PageReconstructError::Other(anyhow::anyhow!("invalid reldir key")))?;
     620            0 :             let exists_v2 = buf == RelDirExists::Exists;
     621              :             // Fast path: if the relation exists in the new format, return true.
     622              :             // TODO: we should have a verification mode that checks both keyspaces
     623              :             // to ensure the relation only exists in one of them.
     624            0 :             if exists_v2 {
     625            0 :                 return Ok(true);
     626            0 :             }
     627            9 :         }
     628              : 
     629              :         // fetch directory listing (old)
     630              : 
     631            9 :         let key = rel_dir_to_key(tag.spcnode, tag.dbnode);
     632              : 
     633            9 :         if let Some((cached_key, dir)) = deserialized_reldir_v1 {
     634            0 :             if cached_key == key {
     635            0 :                 return Ok(dir.rels.contains(&(tag.relnode, tag.forknum)));
     636            0 :             } else if cfg!(test) || cfg!(feature = "testing") {
     637            0 :                 panic!("cached reldir key mismatch: {cached_key} != {key}");
     638              :             } else {
     639            0 :                 warn!("cached reldir key mismatch: {cached_key} != {key}");
     640              :             }
     641              :             // Fallback to reading the directory from the datadir.
     642            9 :         }
     643            9 :         let buf = version.get(self, key, ctx).await?;
     644              : 
     645            9 :         let dir = RelDirectory::des(&buf)?;
     646            9 :         let exists_v1 = dir.rels.contains(&(tag.relnode, tag.forknum));
     647            9 :         Ok(exists_v1)
     648         3025 :     }
     649              : 
     650              :     /// Get a list of all existing relations in given tablespace and database.
     651              :     ///
     652              :     /// Only shard 0 has a full view of the relations. Other shards only know about relations that
     653              :     /// the shard stores pages for.
     654              :     ///
     655              :     /// # Cancel-Safety
     656              :     ///
     657              :     /// This method is cancellation-safe.
     658            0 :     pub(crate) async fn list_rels(
     659            0 :         &self,
     660            0 :         spcnode: Oid,
     661            0 :         dbnode: Oid,
     662            0 :         version: Version<'_>,
     663            0 :         ctx: &RequestContext,
     664            0 :     ) -> Result<HashSet<RelTag>, PageReconstructError> {
     665              :         // fetch directory listing (old)
     666            0 :         let key = rel_dir_to_key(spcnode, dbnode);
     667            0 :         let buf = version.get(self, key, ctx).await?;
     668              : 
     669            0 :         let dir = RelDirectory::des(&buf)?;
     670            0 :         let rels_v1: HashSet<RelTag> =
     671            0 :             HashSet::from_iter(dir.rels.iter().map(|(relnode, forknum)| RelTag {
     672            0 :                 spcnode,
     673            0 :                 dbnode,
     674            0 :                 relnode: *relnode,
     675            0 :                 forknum: *forknum,
     676            0 :             }));
     677              : 
     678            0 :         if let RelSizeMigration::Legacy = self.get_rel_size_v2_status() {
     679            0 :             return Ok(rels_v1);
     680            0 :         }
     681              : 
     682              :         // scan directory listing (new), merge with the old results
     683            0 :         let key_range = rel_tag_sparse_key_range(spcnode, dbnode);
     684            0 :         let io_concurrency = IoConcurrency::spawn_from_conf(
     685            0 :             self.conf.get_vectored_concurrent_io,
     686            0 :             self.gate
     687            0 :                 .enter()
     688            0 :                 .map_err(|_| PageReconstructError::Cancelled)?,
     689              :         );
     690            0 :         let results = self
     691            0 :             .scan(
     692            0 :                 KeySpace::single(key_range),
     693            0 :                 version.get_lsn(),
     694            0 :                 ctx,
     695            0 :                 io_concurrency,
     696            0 :             )
     697            0 :             .await?;
     698            0 :         let mut rels = rels_v1;
     699            0 :         for (key, val) in results {
     700            0 :             let val = RelDirExists::decode(&val?)
     701            0 :                 .map_err(|_| PageReconstructError::Other(anyhow::anyhow!("invalid reldir key")))?;
     702            0 :             assert_eq!(key.field6, 1);
     703            0 :             assert_eq!(key.field2, spcnode);
     704            0 :             assert_eq!(key.field3, dbnode);
     705            0 :             let tag = RelTag {
     706            0 :                 spcnode,
     707            0 :                 dbnode,
     708            0 :                 relnode: key.field4,
     709            0 :                 forknum: key.field5,
     710            0 :             };
     711            0 :             if val == RelDirExists::Removed {
     712            0 :                 debug_assert!(!rels.contains(&tag), "removed reltag in v2");
     713            0 :                 continue;
     714            0 :             }
     715            0 :             let did_not_contain = rels.insert(tag);
     716            0 :             debug_assert!(did_not_contain, "duplicate reltag in v2");
     717              :         }
     718            0 :         Ok(rels)
     719            0 :     }
     720              : 
     721              :     /// Get the whole SLRU segment
     722            0 :     pub(crate) async fn get_slru_segment(
     723            0 :         &self,
     724            0 :         kind: SlruKind,
     725            0 :         segno: u32,
     726            0 :         lsn: Lsn,
     727            0 :         ctx: &RequestContext,
     728            0 :     ) -> Result<Bytes, PageReconstructError> {
     729            0 :         assert!(self.tenant_shard_id.is_shard_zero());
     730            0 :         let n_blocks = self
     731            0 :             .get_slru_segment_size(kind, segno, Version::at(lsn), ctx)
     732            0 :             .await?;
     733              : 
     734            0 :         let keyspace = KeySpace::single(
     735            0 :             slru_block_to_key(kind, segno, 0)..slru_block_to_key(kind, segno, n_blocks),
     736              :         );
     737              : 
     738            0 :         let batches = keyspace.partition(
     739            0 :             self.get_shard_identity(),
     740            0 :             self.conf.max_get_vectored_keys.get() as u64 * BLCKSZ as u64,
     741            0 :             BLCKSZ as u64,
     742              :         );
     743              : 
     744            0 :         let io_concurrency = IoConcurrency::spawn_from_conf(
     745            0 :             self.conf.get_vectored_concurrent_io,
     746            0 :             self.gate
     747            0 :                 .enter()
     748            0 :                 .map_err(|_| PageReconstructError::Cancelled)?,
     749              :         );
     750              : 
     751            0 :         let mut segment = BytesMut::with_capacity(n_blocks as usize * BLCKSZ as usize);
     752            0 :         for batch in batches.parts {
     753            0 :             let query = VersionedKeySpaceQuery::uniform(batch, lsn);
     754            0 :             let blocks = self
     755            0 :                 .get_vectored(query, io_concurrency.clone(), ctx)
     756            0 :                 .await?;
     757              : 
     758            0 :             for (_key, block) in blocks {
     759            0 :                 let block = block?;
     760            0 :                 segment.extend_from_slice(&block[..BLCKSZ as usize]);
     761              :             }
     762              :         }
     763              : 
     764            0 :         Ok(segment.freeze())
     765            0 :     }
     766              : 
     767              :     /// Get size of an SLRU segment
     768            0 :     pub(crate) async fn get_slru_segment_size(
     769            0 :         &self,
     770            0 :         kind: SlruKind,
     771            0 :         segno: u32,
     772            0 :         version: Version<'_>,
     773            0 :         ctx: &RequestContext,
     774            0 :     ) -> Result<BlockNumber, PageReconstructError> {
     775            0 :         assert!(self.tenant_shard_id.is_shard_zero());
     776            0 :         let key = slru_segment_size_to_key(kind, segno);
     777            0 :         let mut buf = version.get(self, key, ctx).await?;
     778            0 :         Ok(buf.get_u32_le())
     779            0 :     }
     780              : 
     781              :     /// Does the slru segment exist?
     782            0 :     pub(crate) async fn get_slru_segment_exists(
     783            0 :         &self,
     784            0 :         kind: SlruKind,
     785            0 :         segno: u32,
     786            0 :         version: Version<'_>,
     787            0 :         ctx: &RequestContext,
     788            0 :     ) -> Result<bool, PageReconstructError> {
     789            0 :         assert!(self.tenant_shard_id.is_shard_zero());
     790              :         // fetch directory listing
     791            0 :         let key = slru_dir_to_key(kind);
     792            0 :         let buf = version.get(self, key, ctx).await?;
     793              : 
     794            0 :         let dir = SlruSegmentDirectory::des(&buf)?;
     795            0 :         Ok(dir.segments.contains(&segno))
     796            0 :     }
     797              : 
     798              :     /// Locate LSN, such that all transactions that committed before
     799              :     /// 'search_timestamp' are visible, but nothing newer is.
     800              :     ///
     801              :     /// This is not exact. Commit timestamps are not guaranteed to be ordered,
     802              :     /// so it's not well defined which LSN you get if there were multiple commits
     803              :     /// "in flight" at that point in time.
     804              :     ///
     805            0 :     pub(crate) async fn find_lsn_for_timestamp(
     806            0 :         &self,
     807            0 :         search_timestamp: TimestampTz,
     808            0 :         cancel: &CancellationToken,
     809            0 :         ctx: &RequestContext,
     810            0 :     ) -> Result<LsnForTimestamp, PageReconstructError> {
     811            0 :         pausable_failpoint!("find-lsn-for-timestamp-pausable");
     812              : 
     813            0 :         let gc_cutoff_lsn_guard = self.get_applied_gc_cutoff_lsn();
     814            0 :         let gc_cutoff_planned = {
     815            0 :             let gc_info = self.gc_info.read().unwrap();
     816            0 :             gc_info.min_cutoff()
     817              :         };
     818              :         // Usually the planned cutoff is newer than the cutoff of the last gc run,
     819              :         // but let's be defensive.
     820            0 :         let gc_cutoff = gc_cutoff_planned.max(*gc_cutoff_lsn_guard);
     821              :         // We use this method to figure out the branching LSN for the new branch, but the
     822              :         // GC cutoff could be before the branching point and we cannot create a new branch
     823              :         // with LSN < `ancestor_lsn`. Thus, pick the maximum of these two to be
     824              :         // on the safe side.
     825            0 :         let min_lsn = std::cmp::max(gc_cutoff, self.get_ancestor_lsn());
     826            0 :         let max_lsn = self.get_last_record_lsn();
     827              : 
     828              :         // LSNs are always 8-byte aligned. low/mid/high represent the
     829              :         // LSN divided by 8.
     830            0 :         let mut low = min_lsn.0 / 8;
     831            0 :         let mut high = max_lsn.0 / 8 + 1;
     832              : 
     833            0 :         let mut found_smaller = false;
     834            0 :         let mut found_larger = false;
     835              : 
     836            0 :         while low < high {
     837            0 :             if cancel.is_cancelled() {
     838            0 :                 return Err(PageReconstructError::Cancelled);
     839            0 :             }
     840              :             // cannot overflow, high and low are both smaller than u64::MAX / 2
     841            0 :             let mid = (high + low) / 2;
     842              : 
     843            0 :             let cmp = match self
     844            0 :                 .is_latest_commit_timestamp_ge_than(
     845            0 :                     search_timestamp,
     846            0 :                     Lsn(mid * 8),
     847            0 :                     &mut found_smaller,
     848            0 :                     &mut found_larger,
     849            0 :                     ctx,
     850              :                 )
     851            0 :                 .await
     852              :             {
     853            0 :                 Ok(res) => res,
     854            0 :                 Err(PageReconstructError::MissingKey(e)) => {
     855            0 :                     warn!(
     856            0 :                         "Missing key while find_lsn_for_timestamp. Either we might have already garbage-collected that data or the key is really missing. Last error: {:#}",
     857              :                         e
     858              :                     );
     859              :                     // Return that we didn't find any requests smaller than the LSN, and logging the error.
     860            0 :                     return Ok(LsnForTimestamp::Past(min_lsn));
     861              :                 }
     862            0 :                 Err(e) => return Err(e),
     863              :             };
     864              : 
     865            0 :             if cmp {
     866            0 :                 high = mid;
     867            0 :             } else {
     868            0 :                 low = mid + 1;
     869            0 :             }
     870              :         }
     871              : 
     872              :         // If `found_smaller == true`, `low = t + 1` where `t` is the target LSN,
     873              :         // so the LSN of the last commit record before or at `search_timestamp`.
     874              :         // Remove one from `low` to get `t`.
     875              :         //
     876              :         // FIXME: it would be better to get the LSN of the previous commit.
     877              :         // Otherwise, if you restore to the returned LSN, the database will
     878              :         // include physical changes from later commits that will be marked
     879              :         // as aborted, and will need to be vacuumed away.
     880            0 :         let commit_lsn = Lsn((low - 1) * 8);
     881            0 :         match (found_smaller, found_larger) {
     882              :             (false, false) => {
     883              :                 // This can happen if no commit records have been processed yet, e.g.
     884              :                 // just after importing a cluster.
     885            0 :                 Ok(LsnForTimestamp::NoData(min_lsn))
     886              :             }
     887              :             (false, true) => {
     888              :                 // Didn't find any commit timestamps smaller than the request
     889            0 :                 Ok(LsnForTimestamp::Past(min_lsn))
     890              :             }
     891            0 :             (true, _) if commit_lsn < min_lsn => {
     892              :                 // the search above did set found_smaller to true but it never increased the lsn.
     893              :                 // Then, low is still the old min_lsn, and the subtraction above gave a value
     894              :                 // below the min_lsn. We should never do that.
     895            0 :                 Ok(LsnForTimestamp::Past(min_lsn))
     896              :             }
     897              :             (true, false) => {
     898              :                 // Only found commits with timestamps smaller than the request.
     899              :                 // It's still a valid case for branch creation, return it.
     900              :                 // And `update_gc_info()` ignores LSN for a `LsnForTimestamp::Future`
     901              :                 // case, anyway.
     902            0 :                 Ok(LsnForTimestamp::Future(commit_lsn))
     903              :             }
     904            0 :             (true, true) => Ok(LsnForTimestamp::Present(commit_lsn)),
     905              :         }
     906            0 :     }
     907              : 
     908              :     /// Subroutine of find_lsn_for_timestamp(). Returns true, if there are any
     909              :     /// commits that committed after 'search_timestamp', at LSN 'probe_lsn'.
     910              :     ///
     911              :     /// Additionally, sets 'found_smaller'/'found_Larger, if encounters any commits
     912              :     /// with a smaller/larger timestamp.
     913              :     ///
     914            0 :     pub(crate) async fn is_latest_commit_timestamp_ge_than(
     915            0 :         &self,
     916            0 :         search_timestamp: TimestampTz,
     917            0 :         probe_lsn: Lsn,
     918            0 :         found_smaller: &mut bool,
     919            0 :         found_larger: &mut bool,
     920            0 :         ctx: &RequestContext,
     921            0 :     ) -> Result<bool, PageReconstructError> {
     922            0 :         self.map_all_timestamps(probe_lsn, ctx, |timestamp| {
     923            0 :             if timestamp >= search_timestamp {
     924            0 :                 *found_larger = true;
     925            0 :                 return ControlFlow::Break(true);
     926            0 :             } else {
     927            0 :                 *found_smaller = true;
     928            0 :             }
     929            0 :             ControlFlow::Continue(())
     930            0 :         })
     931            0 :         .await
     932            0 :     }
     933              : 
     934              :     /// Obtain the timestamp for the given lsn.
     935              :     ///
     936              :     /// If the lsn has no timestamps (e.g. no commits), returns None.
     937            0 :     pub(crate) async fn get_timestamp_for_lsn(
     938            0 :         &self,
     939            0 :         probe_lsn: Lsn,
     940            0 :         ctx: &RequestContext,
     941            0 :     ) -> Result<Option<TimestampTz>, PageReconstructError> {
     942            0 :         let mut max: Option<TimestampTz> = None;
     943            0 :         self.map_all_timestamps::<()>(probe_lsn, ctx, |timestamp| {
     944            0 :             if let Some(max_prev) = max {
     945            0 :                 max = Some(max_prev.max(timestamp));
     946            0 :             } else {
     947            0 :                 max = Some(timestamp);
     948            0 :             }
     949            0 :             ControlFlow::Continue(())
     950            0 :         })
     951            0 :         .await?;
     952              : 
     953            0 :         Ok(max)
     954            0 :     }
     955              : 
     956              :     /// Runs the given function on all the timestamps for a given lsn
     957              :     ///
     958              :     /// The return value is either given by the closure, or set to the `Default`
     959              :     /// impl's output.
     960            0 :     async fn map_all_timestamps<T: Default>(
     961            0 :         &self,
     962            0 :         probe_lsn: Lsn,
     963            0 :         ctx: &RequestContext,
     964            0 :         mut f: impl FnMut(TimestampTz) -> ControlFlow<T>,
     965            0 :     ) -> Result<T, PageReconstructError> {
     966            0 :         for segno in self
     967            0 :             .list_slru_segments(SlruKind::Clog, Version::at(probe_lsn), ctx)
     968            0 :             .await?
     969              :         {
     970            0 :             let nblocks = self
     971            0 :                 .get_slru_segment_size(SlruKind::Clog, segno, Version::at(probe_lsn), ctx)
     972            0 :                 .await?;
     973              : 
     974            0 :             let keyspace = KeySpace::single(
     975            0 :                 slru_block_to_key(SlruKind::Clog, segno, 0)
     976            0 :                     ..slru_block_to_key(SlruKind::Clog, segno, nblocks),
     977              :             );
     978              : 
     979            0 :             let batches = keyspace.partition(
     980            0 :                 self.get_shard_identity(),
     981            0 :                 self.conf.max_get_vectored_keys.get() as u64 * BLCKSZ as u64,
     982            0 :                 BLCKSZ as u64,
     983              :             );
     984              : 
     985            0 :             let io_concurrency = IoConcurrency::spawn_from_conf(
     986            0 :                 self.conf.get_vectored_concurrent_io,
     987            0 :                 self.gate
     988            0 :                     .enter()
     989            0 :                     .map_err(|_| PageReconstructError::Cancelled)?,
     990              :             );
     991              : 
     992            0 :             for batch in batches.parts.into_iter().rev() {
     993            0 :                 let query = VersionedKeySpaceQuery::uniform(batch, probe_lsn);
     994            0 :                 let blocks = self
     995            0 :                     .get_vectored(query, io_concurrency.clone(), ctx)
     996            0 :                     .await?;
     997              : 
     998            0 :                 for (_key, clog_page) in blocks.into_iter().rev() {
     999            0 :                     let clog_page = clog_page?;
    1000              : 
    1001            0 :                     if clog_page.len() == BLCKSZ as usize + 8 {
    1002            0 :                         let mut timestamp_bytes = [0u8; 8];
    1003            0 :                         timestamp_bytes.copy_from_slice(&clog_page[BLCKSZ as usize..]);
    1004            0 :                         let timestamp = TimestampTz::from_be_bytes(timestamp_bytes);
    1005              : 
    1006            0 :                         match f(timestamp) {
    1007            0 :                             ControlFlow::Break(b) => return Ok(b),
    1008            0 :                             ControlFlow::Continue(()) => (),
    1009              :                         }
    1010            0 :                     }
    1011              :                 }
    1012              :             }
    1013              :         }
    1014            0 :         Ok(Default::default())
    1015            0 :     }
    1016              : 
    1017            0 :     pub(crate) async fn get_slru_keyspace(
    1018            0 :         &self,
    1019            0 :         version: Version<'_>,
    1020            0 :         ctx: &RequestContext,
    1021            0 :     ) -> Result<KeySpace, PageReconstructError> {
    1022            0 :         let mut accum = KeySpaceAccum::new();
    1023              : 
    1024            0 :         for kind in SlruKind::iter() {
    1025            0 :             let mut segments: Vec<u32> = self
    1026            0 :                 .list_slru_segments(kind, version, ctx)
    1027            0 :                 .await?
    1028            0 :                 .into_iter()
    1029            0 :                 .collect();
    1030            0 :             segments.sort_unstable();
    1031              : 
    1032            0 :             for seg in segments {
    1033            0 :                 let block_count = self.get_slru_segment_size(kind, seg, version, ctx).await?;
    1034              : 
    1035            0 :                 accum.add_range(
    1036            0 :                     slru_block_to_key(kind, seg, 0)..slru_block_to_key(kind, seg, block_count),
    1037              :                 );
    1038              :             }
    1039              :         }
    1040              : 
    1041            0 :         Ok(accum.to_keyspace())
    1042            0 :     }
    1043              : 
    1044              :     /// Get a list of SLRU segments
    1045            0 :     pub(crate) async fn list_slru_segments(
    1046            0 :         &self,
    1047            0 :         kind: SlruKind,
    1048            0 :         version: Version<'_>,
    1049            0 :         ctx: &RequestContext,
    1050            0 :     ) -> Result<HashSet<u32>, PageReconstructError> {
    1051              :         // fetch directory entry
    1052            0 :         let key = slru_dir_to_key(kind);
    1053              : 
    1054            0 :         let buf = version.get(self, key, ctx).await?;
    1055            0 :         Ok(SlruSegmentDirectory::des(&buf)?.segments)
    1056            0 :     }
    1057              : 
    1058            0 :     pub(crate) async fn get_relmap_file(
    1059            0 :         &self,
    1060            0 :         spcnode: Oid,
    1061            0 :         dbnode: Oid,
    1062            0 :         version: Version<'_>,
    1063            0 :         ctx: &RequestContext,
    1064            0 :     ) -> Result<Bytes, PageReconstructError> {
    1065            0 :         let key = relmap_file_key(spcnode, dbnode);
    1066              : 
    1067            0 :         let buf = version.get(self, key, ctx).await?;
    1068            0 :         Ok(buf)
    1069            0 :     }
    1070              : 
    1071          169 :     pub(crate) async fn list_dbdirs(
    1072          169 :         &self,
    1073          169 :         lsn: Lsn,
    1074          169 :         ctx: &RequestContext,
    1075          169 :     ) -> Result<HashMap<(Oid, Oid), bool>, PageReconstructError> {
    1076              :         // fetch directory entry
    1077          169 :         let buf = self.get(DBDIR_KEY, lsn, ctx).await?;
    1078              : 
    1079          169 :         Ok(DbDirectory::des(&buf)?.dbdirs)
    1080          169 :     }
    1081              : 
    1082            0 :     pub(crate) async fn get_twophase_file(
    1083            0 :         &self,
    1084            0 :         xid: u64,
    1085            0 :         lsn: Lsn,
    1086            0 :         ctx: &RequestContext,
    1087            0 :     ) -> Result<Bytes, PageReconstructError> {
    1088            0 :         let key = twophase_file_key(xid);
    1089            0 :         let buf = self.get(key, lsn, ctx).await?;
    1090            0 :         Ok(buf)
    1091            0 :     }
    1092              : 
    1093          170 :     pub(crate) async fn list_twophase_files(
    1094          170 :         &self,
    1095          170 :         lsn: Lsn,
    1096          170 :         ctx: &RequestContext,
    1097          170 :     ) -> Result<HashSet<u64>, PageReconstructError> {
    1098              :         // fetch directory entry
    1099          170 :         let buf = self.get(TWOPHASEDIR_KEY, lsn, ctx).await?;
    1100              : 
    1101          170 :         if self.pg_version >= PgMajorVersion::PG17 {
    1102          157 :             Ok(TwoPhaseDirectoryV17::des(&buf)?.xids)
    1103              :         } else {
    1104           13 :             Ok(TwoPhaseDirectory::des(&buf)?
    1105              :                 .xids
    1106           13 :                 .iter()
    1107           13 :                 .map(|x| u64::from(*x))
    1108           13 :                 .collect())
    1109              :         }
    1110          170 :     }
    1111              : 
    1112            0 :     pub(crate) async fn get_control_file(
    1113            0 :         &self,
    1114            0 :         lsn: Lsn,
    1115            0 :         ctx: &RequestContext,
    1116            0 :     ) -> Result<Bytes, PageReconstructError> {
    1117            0 :         self.get(CONTROLFILE_KEY, lsn, ctx).await
    1118            0 :     }
    1119              : 
    1120            6 :     pub(crate) async fn get_checkpoint(
    1121            6 :         &self,
    1122            6 :         lsn: Lsn,
    1123            6 :         ctx: &RequestContext,
    1124            6 :     ) -> Result<Bytes, PageReconstructError> {
    1125            6 :         self.get(CHECKPOINT_KEY, lsn, ctx).await
    1126            6 :     }
    1127              : 
    1128            6 :     async fn list_aux_files_v2(
    1129            6 :         &self,
    1130            6 :         lsn: Lsn,
    1131            6 :         ctx: &RequestContext,
    1132            6 :         io_concurrency: IoConcurrency,
    1133            6 :     ) -> Result<HashMap<String, Bytes>, PageReconstructError> {
    1134            6 :         let kv = self
    1135            6 :             .scan(
    1136            6 :                 KeySpace::single(Key::metadata_aux_key_range()),
    1137            6 :                 lsn,
    1138            6 :                 ctx,
    1139            6 :                 io_concurrency,
    1140            6 :             )
    1141            6 :             .await?;
    1142            6 :         let mut result = HashMap::new();
    1143            6 :         let mut sz = 0;
    1144           15 :         for (_, v) in kv {
    1145            9 :             let v = v?;
    1146            9 :             let v = aux_file::decode_file_value_bytes(&v)
    1147            9 :                 .context("value decode")
    1148            9 :                 .map_err(PageReconstructError::Other)?;
    1149           17 :             for (fname, content) in v {
    1150            8 :                 sz += fname.len();
    1151            8 :                 sz += content.len();
    1152            8 :                 result.insert(fname, content);
    1153            8 :             }
    1154              :         }
    1155            6 :         self.aux_file_size_estimator.on_initial(sz);
    1156            6 :         Ok(result)
    1157            6 :     }
    1158              : 
    1159            0 :     pub(crate) async fn trigger_aux_file_size_computation(
    1160            0 :         &self,
    1161            0 :         lsn: Lsn,
    1162            0 :         ctx: &RequestContext,
    1163            0 :         io_concurrency: IoConcurrency,
    1164            0 :     ) -> Result<(), PageReconstructError> {
    1165            0 :         self.list_aux_files_v2(lsn, ctx, io_concurrency).await?;
    1166            0 :         Ok(())
    1167            0 :     }
    1168              : 
    1169            6 :     pub(crate) async fn list_aux_files(
    1170            6 :         &self,
    1171            6 :         lsn: Lsn,
    1172            6 :         ctx: &RequestContext,
    1173            6 :         io_concurrency: IoConcurrency,
    1174            6 :     ) -> Result<HashMap<String, Bytes>, PageReconstructError> {
    1175            6 :         self.list_aux_files_v2(lsn, ctx, io_concurrency).await
    1176            6 :     }
    1177              : 
    1178            2 :     pub(crate) async fn get_replorigins(
    1179            2 :         &self,
    1180            2 :         lsn: Lsn,
    1181            2 :         ctx: &RequestContext,
    1182            2 :         io_concurrency: IoConcurrency,
    1183            2 :     ) -> Result<HashMap<RepOriginId, Lsn>, PageReconstructError> {
    1184            2 :         let kv = self
    1185            2 :             .scan(
    1186            2 :                 KeySpace::single(repl_origin_key_range()),
    1187            2 :                 lsn,
    1188            2 :                 ctx,
    1189            2 :                 io_concurrency,
    1190            2 :             )
    1191            2 :             .await?;
    1192            2 :         let mut result = HashMap::new();
    1193            6 :         for (k, v) in kv {
    1194            5 :             let v = v?;
    1195            5 :             if v.is_empty() {
    1196              :                 // This is a tombstone -- we can skip it.
    1197              :                 // Originally, the replorigin code uses `Lsn::INVALID` to represent a tombstone. However, as it part of
    1198              :                 // the sparse keyspace and the sparse keyspace uses an empty image to universally represent a tombstone,
    1199              :                 // we also need to consider that. Such tombstones might be written on the detach ancestor code path to
    1200              :                 // avoid the value going into the child branch. (See [`crate::tenant::timeline::detach_ancestor::generate_tombstone_image_layer`] for more details.)
    1201            2 :                 continue;
    1202            3 :             }
    1203            3 :             let origin_id = k.field6 as RepOriginId;
    1204            3 :             let origin_lsn = Lsn::des(&v)
    1205            3 :                 .with_context(|| format!("decode replorigin value for {origin_id}: {v:?}"))?;
    1206            2 :             if origin_lsn != Lsn::INVALID {
    1207            2 :                 result.insert(origin_id, origin_lsn);
    1208            2 :             }
    1209              :         }
    1210            1 :         Ok(result)
    1211            2 :     }
    1212              : 
    1213              :     /// Does the same as get_current_logical_size but counted on demand.
    1214              :     /// Used to initialize the logical size tracking on startup.
    1215              :     ///
    1216              :     /// Only relation blocks are counted currently. That excludes metadata,
    1217              :     /// SLRUs, twophase files etc.
    1218              :     ///
    1219              :     /// # Cancel-Safety
    1220              :     ///
    1221              :     /// This method is cancellation-safe.
    1222            7 :     pub(crate) async fn get_current_logical_size_non_incremental(
    1223            7 :         &self,
    1224            7 :         lsn: Lsn,
    1225            7 :         ctx: &RequestContext,
    1226            7 :     ) -> Result<u64, CalculateLogicalSizeError> {
    1227            7 :         debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
    1228              : 
    1229            7 :         fail::fail_point!("skip-logical-size-calculation", |_| { Ok(0) });
    1230              : 
    1231              :         // Fetch list of database dirs and iterate them
    1232            7 :         let buf = self.get(DBDIR_KEY, lsn, ctx).await?;
    1233            7 :         let dbdir = DbDirectory::des(&buf)?;
    1234              : 
    1235            7 :         let mut total_size: u64 = 0;
    1236            7 :         for (spcnode, dbnode) in dbdir.dbdirs.keys() {
    1237            0 :             for rel in self
    1238            0 :                 .list_rels(*spcnode, *dbnode, Version::at(lsn), ctx)
    1239            0 :                 .await?
    1240              :             {
    1241            0 :                 if self.cancel.is_cancelled() {
    1242            0 :                     return Err(CalculateLogicalSizeError::Cancelled);
    1243            0 :                 }
    1244            0 :                 let relsize_key = rel_size_to_key(rel);
    1245            0 :                 let mut buf = self.get(relsize_key, lsn, ctx).await?;
    1246            0 :                 let relsize = buf.get_u32_le();
    1247              : 
    1248            0 :                 total_size += relsize as u64;
    1249              :             }
    1250              :         }
    1251            7 :         Ok(total_size * BLCKSZ as u64)
    1252            7 :     }
    1253              : 
    1254              :     /// Get a KeySpace that covers all the Keys that are in use at AND below the given LSN. This is only used
    1255              :     /// for gc-compaction.
    1256              :     ///
    1257              :     /// gc-compaction cannot use the same `collect_keyspace` function as the legacy compaction because it
    1258              :     /// processes data at multiple LSNs and needs to be aware of the fact that some key ranges might need to
    1259              :     /// be kept only for a specific range of LSN.
    1260              :     ///
    1261              :     /// Consider the case that the user created branches at LSN 10 and 20, where the user created a table A at
    1262              :     /// LSN 10 and dropped that table at LSN 20. `collect_keyspace` at LSN 10 will return the key range
    1263              :     /// corresponding to that table, while LSN 20 won't. The keyspace info at a single LSN is not enough to
    1264              :     /// determine which keys to retain/drop for gc-compaction.
    1265              :     ///
    1266              :     /// For now, it only drops AUX-v1 keys. But in the future, the function will be extended to return the keyspace
    1267              :     /// to be retained for each of the branch LSN.
    1268              :     ///
    1269              :     /// The return value is (dense keyspace, sparse keyspace).
    1270           27 :     pub(crate) async fn collect_gc_compaction_keyspace(
    1271           27 :         &self,
    1272           27 :     ) -> Result<(KeySpace, SparseKeySpace), CollectKeySpaceError> {
    1273           27 :         let metadata_key_begin = Key::metadata_key_range().start;
    1274           27 :         let aux_v1_key = AUX_FILES_KEY;
    1275           27 :         let dense_keyspace = KeySpace {
    1276           27 :             ranges: vec![Key::MIN..aux_v1_key, aux_v1_key.next()..metadata_key_begin],
    1277           27 :         };
    1278           27 :         Ok((
    1279           27 :             dense_keyspace,
    1280           27 :             SparseKeySpace(KeySpace::single(Key::metadata_key_range())),
    1281           27 :         ))
    1282           27 :     }
    1283              : 
    1284              :     ///
    1285              :     /// Get a KeySpace that covers all the Keys that are in use at the given LSN.
    1286              :     /// Anything that's not listed maybe removed from the underlying storage (from
    1287              :     /// that LSN forwards).
    1288              :     ///
    1289              :     /// The return value is (dense keyspace, sparse keyspace).
    1290          169 :     pub(crate) async fn collect_keyspace(
    1291          169 :         &self,
    1292          169 :         lsn: Lsn,
    1293          169 :         ctx: &RequestContext,
    1294          169 :     ) -> Result<(KeySpace, SparseKeySpace), CollectKeySpaceError> {
    1295              :         // Iterate through key ranges, greedily packing them into partitions
    1296          169 :         let mut result = KeySpaceAccum::new();
    1297              : 
    1298              :         // The dbdir metadata always exists
    1299          169 :         result.add_key(DBDIR_KEY);
    1300              : 
    1301              :         // Fetch list of database dirs and iterate them
    1302          169 :         let dbdir = self.list_dbdirs(lsn, ctx).await?;
    1303          169 :         let mut dbs: Vec<((Oid, Oid), bool)> = dbdir.into_iter().collect();
    1304              : 
    1305          169 :         dbs.sort_unstable_by(|(k_a, _), (k_b, _)| k_a.cmp(k_b));
    1306          169 :         for ((spcnode, dbnode), has_relmap_file) in dbs {
    1307            0 :             if has_relmap_file {
    1308            0 :                 result.add_key(relmap_file_key(spcnode, dbnode));
    1309            0 :             }
    1310            0 :             result.add_key(rel_dir_to_key(spcnode, dbnode));
    1311              : 
    1312            0 :             let mut rels: Vec<RelTag> = self
    1313            0 :                 .list_rels(spcnode, dbnode, Version::at(lsn), ctx)
    1314            0 :                 .await?
    1315            0 :                 .into_iter()
    1316            0 :                 .collect();
    1317            0 :             rels.sort_unstable();
    1318            0 :             for rel in rels {
    1319            0 :                 let relsize_key = rel_size_to_key(rel);
    1320            0 :                 let mut buf = self.get(relsize_key, lsn, ctx).await?;
    1321            0 :                 let relsize = buf.get_u32_le();
    1322              : 
    1323            0 :                 result.add_range(rel_block_to_key(rel, 0)..rel_block_to_key(rel, relsize));
    1324            0 :                 result.add_key(relsize_key);
    1325              :             }
    1326              :         }
    1327              : 
    1328              :         // Iterate SLRUs next
    1329          169 :         if self.tenant_shard_id.is_shard_zero() {
    1330          498 :             for kind in [
    1331          166 :                 SlruKind::Clog,
    1332          166 :                 SlruKind::MultiXactMembers,
    1333          166 :                 SlruKind::MultiXactOffsets,
    1334              :             ] {
    1335          498 :                 let slrudir_key = slru_dir_to_key(kind);
    1336          498 :                 result.add_key(slrudir_key);
    1337          498 :                 let buf = self.get(slrudir_key, lsn, ctx).await?;
    1338          498 :                 let dir = SlruSegmentDirectory::des(&buf)?;
    1339          498 :                 let mut segments: Vec<u32> = dir.segments.iter().cloned().collect();
    1340          498 :                 segments.sort_unstable();
    1341          498 :                 for segno in segments {
    1342            0 :                     let segsize_key = slru_segment_size_to_key(kind, segno);
    1343            0 :                     let mut buf = self.get(segsize_key, lsn, ctx).await?;
    1344            0 :                     let segsize = buf.get_u32_le();
    1345              : 
    1346            0 :                     result.add_range(
    1347            0 :                         slru_block_to_key(kind, segno, 0)..slru_block_to_key(kind, segno, segsize),
    1348              :                     );
    1349            0 :                     result.add_key(segsize_key);
    1350              :                 }
    1351              :             }
    1352            3 :         }
    1353              : 
    1354              :         // Then pg_twophase
    1355          169 :         result.add_key(TWOPHASEDIR_KEY);
    1356              : 
    1357          169 :         let mut xids: Vec<u64> = self
    1358          169 :             .list_twophase_files(lsn, ctx)
    1359          169 :             .await?
    1360          169 :             .iter()
    1361          169 :             .cloned()
    1362          169 :             .collect();
    1363          169 :         xids.sort_unstable();
    1364          169 :         for xid in xids {
    1365            0 :             result.add_key(twophase_file_key(xid));
    1366            0 :         }
    1367              : 
    1368          169 :         result.add_key(CONTROLFILE_KEY);
    1369          169 :         result.add_key(CHECKPOINT_KEY);
    1370              : 
    1371              :         // Add extra keyspaces in the test cases. Some test cases write keys into the storage without
    1372              :         // creating directory keys. These test cases will add such keyspaces into `extra_test_dense_keyspace`
    1373              :         // and the keys will not be garbage-colllected.
    1374              :         #[cfg(test)]
    1375              :         {
    1376          169 :             let guard = self.extra_test_dense_keyspace.load();
    1377          169 :             for kr in &guard.ranges {
    1378            0 :                 result.add_range(kr.clone());
    1379            0 :             }
    1380              :         }
    1381              : 
    1382          169 :         let dense_keyspace = result.to_keyspace();
    1383          169 :         let sparse_keyspace = SparseKeySpace(KeySpace {
    1384          169 :             ranges: vec![
    1385          169 :                 Key::metadata_aux_key_range(),
    1386          169 :                 repl_origin_key_range(),
    1387          169 :                 Key::rel_dir_sparse_key_range(),
    1388          169 :             ],
    1389          169 :         });
    1390              : 
    1391          169 :         if cfg!(debug_assertions) {
    1392              :             // Verify if the sparse keyspaces are ordered and non-overlapping.
    1393              : 
    1394              :             // We do not use KeySpaceAccum for sparse_keyspace because we want to ensure each
    1395              :             // category of sparse keys are split into their own image/delta files. If there
    1396              :             // are overlapping keyspaces, they will be automatically merged by keyspace accum,
    1397              :             // and we want the developer to keep the keyspaces separated.
    1398              : 
    1399          169 :             let ranges = &sparse_keyspace.0.ranges;
    1400              : 
    1401              :             // TODO: use a single overlaps_with across the codebase
    1402          507 :             fn overlaps_with<T: Ord>(a: &Range<T>, b: &Range<T>) -> bool {
    1403          507 :                 !(a.end <= b.start || b.end <= a.start)
    1404          507 :             }
    1405          507 :             for i in 0..ranges.len() {
    1406          507 :                 for j in 0..i {
    1407          507 :                     if overlaps_with(&ranges[i], &ranges[j]) {
    1408            0 :                         panic!(
    1409            0 :                             "overlapping sparse keyspace: {}..{} and {}..{}",
    1410            0 :                             ranges[i].start, ranges[i].end, ranges[j].start, ranges[j].end
    1411              :                         );
    1412          507 :                     }
    1413              :                 }
    1414              :             }
    1415          338 :             for i in 1..ranges.len() {
    1416          338 :                 assert!(
    1417          338 :                     ranges[i - 1].end <= ranges[i].start,
    1418            0 :                     "unordered sparse keyspace: {}..{} and {}..{}",
    1419            0 :                     ranges[i - 1].start,
    1420            0 :                     ranges[i - 1].end,
    1421            0 :                     ranges[i].start,
    1422            0 :                     ranges[i].end
    1423              :                 );
    1424              :             }
    1425            0 :         }
    1426              : 
    1427          169 :         Ok((dense_keyspace, sparse_keyspace))
    1428          169 :     }
    1429              : 
    1430              :     /// Get cached size of relation. There are two caches: one for primary updates, it captures the latest state of
    1431              :     /// of the timeline and snapshot cache, which key includes LSN and so can be used by replicas to get relation size
    1432              :     /// at the particular LSN (snapshot).
    1433       224270 :     pub fn get_cached_rel_size(&self, tag: &RelTag, version: Version<'_>) -> Option<BlockNumber> {
    1434       224270 :         let lsn = version.get_lsn();
    1435              :         {
    1436       224270 :             let rel_size_cache = self.rel_size_latest_cache.read().unwrap();
    1437       224270 :             if let Some((cached_lsn, nblocks)) = rel_size_cache.get(tag) {
    1438       224259 :                 if lsn >= *cached_lsn {
    1439       221686 :                     RELSIZE_LATEST_CACHE_HITS.inc();
    1440       221686 :                     return Some(*nblocks);
    1441         2573 :                 }
    1442         2573 :                 RELSIZE_CACHE_MISSES_OLD.inc();
    1443           11 :             }
    1444              :         }
    1445              :         {
    1446         2584 :             let mut rel_size_cache = self.rel_size_snapshot_cache.lock().unwrap();
    1447         2584 :             if let Some(nblock) = rel_size_cache.get(&(lsn, *tag)) {
    1448         2563 :                 RELSIZE_SNAPSHOT_CACHE_HITS.inc();
    1449         2563 :                 return Some(*nblock);
    1450           21 :             }
    1451              :         }
    1452           21 :         if version.is_latest() {
    1453           10 :             RELSIZE_LATEST_CACHE_MISSES.inc();
    1454           11 :         } else {
    1455           11 :             RELSIZE_SNAPSHOT_CACHE_MISSES.inc();
    1456           11 :         }
    1457           21 :         None
    1458       224270 :     }
    1459              : 
    1460              :     /// Update cached relation size if there is no more recent update
    1461            5 :     pub fn update_cached_rel_size(&self, tag: RelTag, version: Version<'_>, nblocks: BlockNumber) {
    1462            5 :         let lsn = version.get_lsn();
    1463            5 :         if version.is_latest() {
    1464            0 :             let mut rel_size_cache = self.rel_size_latest_cache.write().unwrap();
    1465            0 :             match rel_size_cache.entry(tag) {
    1466            0 :                 hash_map::Entry::Occupied(mut entry) => {
    1467            0 :                     let cached_lsn = entry.get_mut();
    1468            0 :                     if lsn >= cached_lsn.0 {
    1469            0 :                         *cached_lsn = (lsn, nblocks);
    1470            0 :                     }
    1471              :                 }
    1472            0 :                 hash_map::Entry::Vacant(entry) => {
    1473            0 :                     entry.insert((lsn, nblocks));
    1474            0 :                     RELSIZE_LATEST_CACHE_ENTRIES.inc();
    1475            0 :                 }
    1476              :             }
    1477              :         } else {
    1478            5 :             let mut rel_size_cache = self.rel_size_snapshot_cache.lock().unwrap();
    1479            5 :             if rel_size_cache.capacity() != 0 {
    1480            5 :                 rel_size_cache.insert((lsn, tag), nblocks);
    1481            5 :                 RELSIZE_SNAPSHOT_CACHE_ENTRIES.set(rel_size_cache.len() as u64);
    1482            5 :             }
    1483              :         }
    1484            5 :     }
    1485              : 
    1486              :     /// Store cached relation size
    1487       141360 :     pub fn set_cached_rel_size(&self, tag: RelTag, lsn: Lsn, nblocks: BlockNumber) {
    1488       141360 :         let mut rel_size_cache = self.rel_size_latest_cache.write().unwrap();
    1489       141360 :         if rel_size_cache.insert(tag, (lsn, nblocks)).is_none() {
    1490          960 :             RELSIZE_LATEST_CACHE_ENTRIES.inc();
    1491       140400 :         }
    1492       141360 :     }
    1493              : 
    1494              :     /// Remove cached relation size
    1495            1 :     pub fn remove_cached_rel_size(&self, tag: &RelTag) {
    1496            1 :         let mut rel_size_cache = self.rel_size_latest_cache.write().unwrap();
    1497            1 :         if rel_size_cache.remove(tag).is_some() {
    1498            1 :             RELSIZE_LATEST_CACHE_ENTRIES.dec();
    1499            1 :         }
    1500            1 :     }
    1501              : }
    1502              : 
    1503              : /// DatadirModification represents an operation to ingest an atomic set of
    1504              : /// updates to the repository.
    1505              : ///
    1506              : /// It is created by the 'begin_record' function. It is called for each WAL
    1507              : /// record, so that all the modifications by a one WAL record appear atomic.
    1508              : pub struct DatadirModification<'a> {
    1509              :     /// The timeline this modification applies to. You can access this to
    1510              :     /// read the state, but note that any pending updates are *not* reflected
    1511              :     /// in the state in 'tline' yet.
    1512              :     pub tline: &'a Timeline,
    1513              : 
    1514              :     /// Current LSN of the modification
    1515              :     lsn: Lsn,
    1516              : 
    1517              :     // The modifications are not applied directly to the underlying key-value store.
    1518              :     // The put-functions add the modifications here, and they are flushed to the
    1519              :     // underlying key-value store by the 'finish' function.
    1520              :     pending_lsns: Vec<Lsn>,
    1521              :     pending_deletions: Vec<(Range<Key>, Lsn)>,
    1522              :     pending_nblocks: i64,
    1523              : 
    1524              :     /// Metadata writes, indexed by key so that they can be read from not-yet-committed modifications
    1525              :     /// while ingesting subsequent records. See [`Self::is_data_key`] for the definition of 'metadata'.
    1526              :     pending_metadata_pages: HashMap<CompactKey, Vec<(Lsn, usize, Value)>>,
    1527              : 
    1528              :     /// Data writes, ready to be flushed into an ephemeral layer. See [`Self::is_data_key`] for
    1529              :     /// which keys are stored here.
    1530              :     pending_data_batch: Option<SerializedValueBatch>,
    1531              : 
    1532              :     /// For special "directory" keys that store key-value maps, track the size of the map
    1533              :     /// if it was updated in this modification.
    1534              :     pending_directory_entries: Vec<(DirectoryKind, MetricsUpdate)>,
    1535              : 
    1536              :     /// An **approximation** of how many metadata bytes will be written to the EphemeralFile.
    1537              :     pending_metadata_bytes: usize,
    1538              : }
    1539              : 
    1540              : #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    1541              : pub enum MetricsUpdate {
    1542              :     /// Set the metrics to this value
    1543              :     Set(u64),
    1544              :     /// Increment the metrics by this value
    1545              :     Add(u64),
    1546              :     /// Decrement the metrics by this value
    1547              :     Sub(u64),
    1548              : }
    1549              : 
    1550              : impl DatadirModification<'_> {
    1551              :     // When a DatadirModification is committed, we do a monolithic serialization of all its contents.  WAL records can
    1552              :     // contain multiple pages, so the pageserver's record-based batch size isn't sufficient to bound this allocation: we
    1553              :     // additionally specify a limit on how much payload a DatadirModification may contain before it should be committed.
    1554              :     pub(crate) const MAX_PENDING_BYTES: usize = 8 * 1024 * 1024;
    1555              : 
    1556              :     /// Get the current lsn
    1557            1 :     pub(crate) fn get_lsn(&self) -> Lsn {
    1558            1 :         self.lsn
    1559            1 :     }
    1560              : 
    1561            0 :     pub(crate) fn approx_pending_bytes(&self) -> usize {
    1562            0 :         self.pending_data_batch
    1563            0 :             .as_ref()
    1564            0 :             .map_or(0, |b| b.buffer_size())
    1565            0 :             + self.pending_metadata_bytes
    1566            0 :     }
    1567              : 
    1568            0 :     pub(crate) fn has_dirty_data(&self) -> bool {
    1569            0 :         self.pending_data_batch
    1570            0 :             .as_ref()
    1571            0 :             .is_some_and(|b| b.has_data())
    1572            0 :     }
    1573              : 
    1574              :     /// Returns statistics about the currently pending modifications.
    1575            0 :     pub(crate) fn stats(&self) -> DatadirModificationStats {
    1576            0 :         let mut stats = DatadirModificationStats::default();
    1577            0 :         for (_, _, value) in self.pending_metadata_pages.values().flatten() {
    1578            0 :             match value {
    1579            0 :                 Value::Image(_) => stats.metadata_images += 1,
    1580            0 :                 Value::WalRecord(r) if r.will_init() => stats.metadata_images += 1,
    1581            0 :                 Value::WalRecord(_) => stats.metadata_deltas += 1,
    1582              :             }
    1583              :         }
    1584            0 :         for valuemeta in self.pending_data_batch.iter().flat_map(|b| &b.metadata) {
    1585            0 :             match valuemeta {
    1586            0 :                 ValueMeta::Serialized(s) if s.will_init => stats.data_images += 1,
    1587            0 :                 ValueMeta::Serialized(_) => stats.data_deltas += 1,
    1588            0 :                 ValueMeta::Observed(_) => {}
    1589              :             }
    1590              :         }
    1591            0 :         stats
    1592            0 :     }
    1593              : 
    1594              :     /// Set the current lsn
    1595        72929 :     pub(crate) fn set_lsn(&mut self, lsn: Lsn) -> Result<(), WalIngestError> {
    1596        72929 :         ensure_walingest!(
    1597              :             lsn >= self.lsn,
    1598              :             "setting an older lsn {} than {} is not allowed",
    1599              :             lsn,
    1600              :             self.lsn
    1601              :         );
    1602              : 
    1603        72929 :         if lsn > self.lsn {
    1604        72929 :             self.pending_lsns.push(self.lsn);
    1605        72929 :             self.lsn = lsn;
    1606        72929 :         }
    1607        72929 :         Ok(())
    1608        72929 :     }
    1609              : 
    1610              :     /// In this context, 'metadata' means keys that are only read by the pageserver internally, and 'data' means
    1611              :     /// keys that represent literal blocks that postgres can read.  So data includes relation blocks and
    1612              :     /// SLRU blocks, which are read directly by postgres, and everything else is considered metadata.
    1613              :     ///
    1614              :     /// The distinction is important because data keys are handled on a fast path where dirty writes are
    1615              :     /// not readable until this modification is committed, whereas metadata keys are visible for read
    1616              :     /// via [`Self::get`] as soon as their record has been ingested.
    1617       425371 :     fn is_data_key(key: &Key) -> bool {
    1618       425371 :         key.is_rel_block_key() || key.is_slru_block_key()
    1619       425371 :     }
    1620              : 
    1621              :     /// Initialize a completely new repository.
    1622              :     ///
    1623              :     /// This inserts the directory metadata entries that are assumed to
    1624              :     /// always exist.
    1625          112 :     pub fn init_empty(&mut self) -> anyhow::Result<()> {
    1626          112 :         let buf = DbDirectory::ser(&DbDirectory {
    1627          112 :             dbdirs: HashMap::new(),
    1628          112 :         })?;
    1629          112 :         self.pending_directory_entries
    1630          112 :             .push((DirectoryKind::Db, MetricsUpdate::Set(0)));
    1631          112 :         self.put(DBDIR_KEY, Value::Image(buf.into()));
    1632              : 
    1633          112 :         let buf = if self.tline.pg_version >= PgMajorVersion::PG17 {
    1634           99 :             TwoPhaseDirectoryV17::ser(&TwoPhaseDirectoryV17 {
    1635           99 :                 xids: HashSet::new(),
    1636           99 :             })
    1637              :         } else {
    1638           13 :             TwoPhaseDirectory::ser(&TwoPhaseDirectory {
    1639           13 :                 xids: HashSet::new(),
    1640           13 :             })
    1641            0 :         }?;
    1642          112 :         self.pending_directory_entries
    1643          112 :             .push((DirectoryKind::TwoPhase, MetricsUpdate::Set(0)));
    1644          112 :         self.put(TWOPHASEDIR_KEY, Value::Image(buf.into()));
    1645              : 
    1646          112 :         let buf: Bytes = SlruSegmentDirectory::ser(&SlruSegmentDirectory::default())?.into();
    1647          112 :         let empty_dir = Value::Image(buf);
    1648              : 
    1649              :         // Initialize SLRUs on shard 0 only: creating these on other shards would be
    1650              :         // harmless but they'd just be dropped on later compaction.
    1651          112 :         if self.tline.tenant_shard_id.is_shard_zero() {
    1652          109 :             self.put(slru_dir_to_key(SlruKind::Clog), empty_dir.clone());
    1653          109 :             self.pending_directory_entries.push((
    1654          109 :                 DirectoryKind::SlruSegment(SlruKind::Clog),
    1655          109 :                 MetricsUpdate::Set(0),
    1656          109 :             ));
    1657          109 :             self.put(
    1658          109 :                 slru_dir_to_key(SlruKind::MultiXactMembers),
    1659          109 :                 empty_dir.clone(),
    1660          109 :             );
    1661          109 :             self.pending_directory_entries.push((
    1662          109 :                 DirectoryKind::SlruSegment(SlruKind::Clog),
    1663          109 :                 MetricsUpdate::Set(0),
    1664          109 :             ));
    1665          109 :             self.put(slru_dir_to_key(SlruKind::MultiXactOffsets), empty_dir);
    1666          109 :             self.pending_directory_entries.push((
    1667          109 :                 DirectoryKind::SlruSegment(SlruKind::MultiXactOffsets),
    1668          109 :                 MetricsUpdate::Set(0),
    1669          109 :             ));
    1670          109 :         }
    1671              : 
    1672          112 :         Ok(())
    1673          112 :     }
    1674              : 
    1675              :     #[cfg(test)]
    1676          111 :     pub fn init_empty_test_timeline(&mut self) -> anyhow::Result<()> {
    1677          111 :         self.init_empty()?;
    1678          111 :         self.put_control_file(bytes::Bytes::from_static(
    1679          111 :             b"control_file contents do not matter",
    1680              :         ))
    1681          111 :         .context("put_control_file")?;
    1682          111 :         self.put_checkpoint(bytes::Bytes::from_static(
    1683          111 :             b"checkpoint_file contents do not matter",
    1684              :         ))
    1685          111 :         .context("put_checkpoint_file")?;
    1686          111 :         Ok(())
    1687          111 :     }
    1688              : 
    1689              :     /// Creates a relation if it is not already present.
    1690              :     /// Returns the current size of the relation
    1691       209028 :     pub(crate) async fn create_relation_if_required(
    1692       209028 :         &mut self,
    1693       209028 :         rel: RelTag,
    1694       209028 :         ctx: &RequestContext,
    1695       209028 :     ) -> Result<u32, WalIngestError> {
    1696              :         // Get current size and put rel creation if rel doesn't exist
    1697              :         //
    1698              :         // NOTE: we check the cache first even though get_rel_exists and get_rel_size would
    1699              :         //       check the cache too. This is because eagerly checking the cache results in
    1700              :         //       less work overall and 10% better performance. It's more work on cache miss
    1701              :         //       but cache miss is rare.
    1702       209028 :         if let Some(nblocks) = self
    1703       209028 :             .tline
    1704       209028 :             .get_cached_rel_size(&rel, Version::Modified(self))
    1705              :         {
    1706       209023 :             Ok(nblocks)
    1707            5 :         } else if !self
    1708            5 :             .tline
    1709            5 :             .get_rel_exists(rel, Version::Modified(self), ctx)
    1710            5 :             .await?
    1711              :         {
    1712              :             // create it with 0 size initially, the logic below will extend it
    1713            5 :             self.put_rel_creation(rel, 0, ctx).await?;
    1714            5 :             Ok(0)
    1715              :         } else {
    1716            0 :             Ok(self
    1717            0 :                 .tline
    1718            0 :                 .get_rel_size(rel, Version::Modified(self), ctx)
    1719            0 :                 .await?)
    1720              :         }
    1721       209028 :     }
    1722              : 
    1723              :     /// Given a block number for a relation (which represents a newly written block),
    1724              :     /// the previous block count of the relation, and the shard info, find the gaps
    1725              :     /// that were created by the newly written block if any.
    1726        72835 :     fn find_gaps(
    1727        72835 :         rel: RelTag,
    1728        72835 :         blkno: u32,
    1729        72835 :         previous_nblocks: u32,
    1730        72835 :         shard: &ShardIdentity,
    1731        72835 :     ) -> Option<KeySpace> {
    1732        72835 :         let mut key = rel_block_to_key(rel, blkno);
    1733        72835 :         let mut gap_accum = None;
    1734              : 
    1735        72835 :         for gap_blkno in previous_nblocks..blkno {
    1736           16 :             key.field6 = gap_blkno;
    1737              : 
    1738           16 :             if shard.get_shard_number(&key) != shard.number {
    1739            4 :                 continue;
    1740           12 :             }
    1741              : 
    1742           12 :             gap_accum
    1743           12 :                 .get_or_insert_with(KeySpaceAccum::new)
    1744           12 :                 .add_key(key);
    1745              :         }
    1746              : 
    1747        72835 :         gap_accum.map(|accum| accum.to_keyspace())
    1748        72835 :     }
    1749              : 
    1750        72926 :     pub async fn ingest_batch(
    1751        72926 :         &mut self,
    1752        72926 :         mut batch: SerializedValueBatch,
    1753        72926 :         // TODO(vlad): remove this argument and replace the shard check with is_key_local
    1754        72926 :         shard: &ShardIdentity,
    1755        72926 :         ctx: &RequestContext,
    1756        72926 :     ) -> Result<(), WalIngestError> {
    1757        72926 :         let mut gaps_at_lsns = Vec::default();
    1758              : 
    1759        72926 :         for meta in batch.metadata.iter() {
    1760        72821 :             let key = Key::from_compact(meta.key());
    1761        72821 :             let (rel, blkno) = key
    1762        72821 :                 .to_rel_block()
    1763        72821 :                 .map_err(|_| WalIngestErrorKind::InvalidKey(key, meta.lsn()))?;
    1764        72821 :             let new_nblocks = blkno + 1;
    1765              : 
    1766        72821 :             let old_nblocks = self.create_relation_if_required(rel, ctx).await?;
    1767        72821 :             if new_nblocks > old_nblocks {
    1768         1195 :                 self.put_rel_extend(rel, new_nblocks, ctx).await?;
    1769        71626 :             }
    1770              : 
    1771        72821 :             if let Some(gaps) = Self::find_gaps(rel, blkno, old_nblocks, shard) {
    1772            0 :                 gaps_at_lsns.push((gaps, meta.lsn()));
    1773        72821 :             }
    1774              :         }
    1775              : 
    1776        72926 :         if !gaps_at_lsns.is_empty() {
    1777            0 :             batch.zero_gaps(gaps_at_lsns);
    1778        72926 :         }
    1779              : 
    1780        72926 :         match self.pending_data_batch.as_mut() {
    1781           10 :             Some(pending_batch) => {
    1782           10 :                 pending_batch.extend(batch);
    1783           10 :             }
    1784        72916 :             None if batch.has_data() => {
    1785        72815 :                 self.pending_data_batch = Some(batch);
    1786        72815 :             }
    1787          101 :             None => {
    1788          101 :                 // Nothing to initialize the batch with
    1789          101 :             }
    1790              :         }
    1791              : 
    1792        72926 :         Ok(())
    1793        72926 :     }
    1794              : 
    1795              :     /// Put a new page version that can be constructed from a WAL record
    1796              :     ///
    1797              :     /// NOTE: this will *not* implicitly extend the relation, if the page is beyond the
    1798              :     /// current end-of-file. It's up to the caller to check that the relation size
    1799              :     /// matches the blocks inserted!
    1800            6 :     pub fn put_rel_wal_record(
    1801            6 :         &mut self,
    1802            6 :         rel: RelTag,
    1803            6 :         blknum: BlockNumber,
    1804            6 :         rec: NeonWalRecord,
    1805            6 :     ) -> Result<(), WalIngestError> {
    1806            6 :         ensure_walingest!(rel.relnode != 0, RelationError::InvalidRelnode);
    1807            6 :         self.put(rel_block_to_key(rel, blknum), Value::WalRecord(rec));
    1808            6 :         Ok(())
    1809            6 :     }
    1810              : 
    1811              :     // Same, but for an SLRU.
    1812            4 :     pub fn put_slru_wal_record(
    1813            4 :         &mut self,
    1814            4 :         kind: SlruKind,
    1815            4 :         segno: u32,
    1816            4 :         blknum: BlockNumber,
    1817            4 :         rec: NeonWalRecord,
    1818            4 :     ) -> Result<(), WalIngestError> {
    1819            4 :         if !self.tline.tenant_shard_id.is_shard_zero() {
    1820            0 :             return Ok(());
    1821            4 :         }
    1822              : 
    1823            4 :         self.put(
    1824            4 :             slru_block_to_key(kind, segno, blknum),
    1825            4 :             Value::WalRecord(rec),
    1826              :         );
    1827            4 :         Ok(())
    1828            4 :     }
    1829              : 
    1830              :     /// Like put_wal_record, but with ready-made image of the page.
    1831       138921 :     pub fn put_rel_page_image(
    1832       138921 :         &mut self,
    1833       138921 :         rel: RelTag,
    1834       138921 :         blknum: BlockNumber,
    1835       138921 :         img: Bytes,
    1836       138921 :     ) -> Result<(), WalIngestError> {
    1837       138921 :         ensure_walingest!(rel.relnode != 0, RelationError::InvalidRelnode);
    1838       138921 :         let key = rel_block_to_key(rel, blknum);
    1839       138921 :         if !key.is_valid_key_on_write_path() {
    1840            0 :             Err(WalIngestErrorKind::InvalidKey(key, self.lsn))?;
    1841       138921 :         }
    1842       138921 :         self.put(rel_block_to_key(rel, blknum), Value::Image(img));
    1843       138921 :         Ok(())
    1844       138921 :     }
    1845              : 
    1846            3 :     pub fn put_slru_page_image(
    1847            3 :         &mut self,
    1848            3 :         kind: SlruKind,
    1849            3 :         segno: u32,
    1850            3 :         blknum: BlockNumber,
    1851            3 :         img: Bytes,
    1852            3 :     ) -> Result<(), WalIngestError> {
    1853            3 :         assert!(self.tline.tenant_shard_id.is_shard_zero());
    1854              : 
    1855            3 :         let key = slru_block_to_key(kind, segno, blknum);
    1856            3 :         if !key.is_valid_key_on_write_path() {
    1857            0 :             Err(WalIngestErrorKind::InvalidKey(key, self.lsn))?;
    1858            3 :         }
    1859            3 :         self.put(key, Value::Image(img));
    1860            3 :         Ok(())
    1861            3 :     }
    1862              : 
    1863         1499 :     pub(crate) fn put_rel_page_image_zero(
    1864         1499 :         &mut self,
    1865         1499 :         rel: RelTag,
    1866         1499 :         blknum: BlockNumber,
    1867         1499 :     ) -> Result<(), WalIngestError> {
    1868         1499 :         ensure_walingest!(rel.relnode != 0, RelationError::InvalidRelnode);
    1869         1499 :         let key = rel_block_to_key(rel, blknum);
    1870         1499 :         if !key.is_valid_key_on_write_path() {
    1871            0 :             Err(WalIngestErrorKind::InvalidKey(key, self.lsn))?;
    1872         1499 :         }
    1873              : 
    1874         1499 :         let batch = self
    1875         1499 :             .pending_data_batch
    1876         1499 :             .get_or_insert_with(SerializedValueBatch::default);
    1877              : 
    1878         1499 :         batch.put(key.to_compact(), Value::Image(ZERO_PAGE.clone()), self.lsn);
    1879              : 
    1880         1499 :         Ok(())
    1881         1499 :     }
    1882              : 
    1883            0 :     pub(crate) fn put_slru_page_image_zero(
    1884            0 :         &mut self,
    1885            0 :         kind: SlruKind,
    1886            0 :         segno: u32,
    1887            0 :         blknum: BlockNumber,
    1888            0 :     ) -> Result<(), WalIngestError> {
    1889            0 :         assert!(self.tline.tenant_shard_id.is_shard_zero());
    1890            0 :         let key = slru_block_to_key(kind, segno, blknum);
    1891            0 :         if !key.is_valid_key_on_write_path() {
    1892            0 :             Err(WalIngestErrorKind::InvalidKey(key, self.lsn))?;
    1893            0 :         }
    1894              : 
    1895            0 :         let batch = self
    1896            0 :             .pending_data_batch
    1897            0 :             .get_or_insert_with(SerializedValueBatch::default);
    1898              : 
    1899            0 :         batch.put(key.to_compact(), Value::Image(ZERO_PAGE.clone()), self.lsn);
    1900              : 
    1901            0 :         Ok(())
    1902            0 :     }
    1903              : 
    1904              :     /// Returns `true` if the rel_size_v2 write path is enabled. If it is the first time that
    1905              :     /// we enable it, we also need to persist it in `index_part.json`.
    1906          973 :     pub fn maybe_enable_rel_size_v2(&mut self) -> anyhow::Result<bool> {
    1907          973 :         let status = self.tline.get_rel_size_v2_status();
    1908          973 :         let config = self.tline.get_rel_size_v2_enabled();
    1909          973 :         match (config, status) {
    1910              :             (false, RelSizeMigration::Legacy) => {
    1911              :                 // tenant config didn't enable it and we didn't write any reldir_v2 key yet
    1912          973 :                 Ok(false)
    1913              :             }
    1914              :             (false, RelSizeMigration::Migrating | RelSizeMigration::Migrated) => {
    1915              :                 // index_part already persisted that the timeline has enabled rel_size_v2
    1916            0 :                 Ok(true)
    1917              :             }
    1918              :             (true, RelSizeMigration::Legacy) => {
    1919              :                 // The first time we enable it, we need to persist it in `index_part.json`
    1920            0 :                 self.tline
    1921            0 :                     .update_rel_size_v2_status(RelSizeMigration::Migrating)?;
    1922            0 :                 tracing::info!("enabled rel_size_v2");
    1923            0 :                 Ok(true)
    1924              :             }
    1925              :             (true, RelSizeMigration::Migrating | RelSizeMigration::Migrated) => {
    1926              :                 // index_part already persisted that the timeline has enabled rel_size_v2
    1927              :                 // and we don't need to do anything
    1928            0 :                 Ok(true)
    1929              :             }
    1930              :         }
    1931          973 :     }
    1932              : 
    1933              :     /// Store a relmapper file (pg_filenode.map) in the repository
    1934            8 :     pub async fn put_relmap_file(
    1935            8 :         &mut self,
    1936            8 :         spcnode: Oid,
    1937            8 :         dbnode: Oid,
    1938            8 :         img: Bytes,
    1939            8 :         ctx: &RequestContext,
    1940            8 :     ) -> Result<(), WalIngestError> {
    1941            8 :         let v2_enabled = self
    1942            8 :             .maybe_enable_rel_size_v2()
    1943            8 :             .map_err(WalIngestErrorKind::MaybeRelSizeV2Error)?;
    1944              : 
    1945              :         // Add it to the directory (if it doesn't exist already)
    1946            8 :         let buf = self.get(DBDIR_KEY, ctx).await?;
    1947            8 :         let mut dbdir = DbDirectory::des(&buf)?;
    1948              : 
    1949            8 :         let r = dbdir.dbdirs.insert((spcnode, dbnode), true);
    1950            8 :         if r.is_none() || r == Some(false) {
    1951              :             // The dbdir entry didn't exist, or it contained a
    1952              :             // 'false'. The 'insert' call already updated it with
    1953              :             // 'true', now write the updated 'dbdirs' map back.
    1954            8 :             let buf = DbDirectory::ser(&dbdir)?;
    1955            8 :             self.put(DBDIR_KEY, Value::Image(buf.into()));
    1956            0 :         }
    1957            8 :         if r.is_none() {
    1958              :             // Create RelDirectory
    1959              :             // TODO: if we have fully migrated to v2, no need to create this directory
    1960            4 :             let buf = RelDirectory::ser(&RelDirectory {
    1961            4 :                 rels: HashSet::new(),
    1962            4 :             })?;
    1963            4 :             self.pending_directory_entries
    1964            4 :                 .push((DirectoryKind::Rel, MetricsUpdate::Set(0)));
    1965            4 :             if v2_enabled {
    1966            0 :                 self.pending_directory_entries
    1967            0 :                     .push((DirectoryKind::RelV2, MetricsUpdate::Set(0)));
    1968            4 :             }
    1969            4 :             self.put(
    1970            4 :                 rel_dir_to_key(spcnode, dbnode),
    1971            4 :                 Value::Image(Bytes::from(buf)),
    1972              :             );
    1973            4 :         }
    1974              : 
    1975            8 :         self.put(relmap_file_key(spcnode, dbnode), Value::Image(img));
    1976            8 :         Ok(())
    1977            8 :     }
    1978              : 
    1979            0 :     pub async fn put_twophase_file(
    1980            0 :         &mut self,
    1981            0 :         xid: u64,
    1982            0 :         img: Bytes,
    1983            0 :         ctx: &RequestContext,
    1984            0 :     ) -> Result<(), WalIngestError> {
    1985              :         // Add it to the directory entry
    1986            0 :         let dirbuf = self.get(TWOPHASEDIR_KEY, ctx).await?;
    1987            0 :         let newdirbuf = if self.tline.pg_version >= PgMajorVersion::PG17 {
    1988            0 :             let mut dir = TwoPhaseDirectoryV17::des(&dirbuf)?;
    1989            0 :             if !dir.xids.insert(xid) {
    1990            0 :                 Err(WalIngestErrorKind::FileAlreadyExists(xid))?;
    1991            0 :             }
    1992            0 :             self.pending_directory_entries.push((
    1993            0 :                 DirectoryKind::TwoPhase,
    1994            0 :                 MetricsUpdate::Set(dir.xids.len() as u64),
    1995            0 :             ));
    1996            0 :             Bytes::from(TwoPhaseDirectoryV17::ser(&dir)?)
    1997              :         } else {
    1998            0 :             let xid = xid as u32;
    1999            0 :             let mut dir = TwoPhaseDirectory::des(&dirbuf)?;
    2000            0 :             if !dir.xids.insert(xid) {
    2001            0 :                 Err(WalIngestErrorKind::FileAlreadyExists(xid.into()))?;
    2002            0 :             }
    2003            0 :             self.pending_directory_entries.push((
    2004            0 :                 DirectoryKind::TwoPhase,
    2005            0 :                 MetricsUpdate::Set(dir.xids.len() as u64),
    2006            0 :             ));
    2007            0 :             Bytes::from(TwoPhaseDirectory::ser(&dir)?)
    2008              :         };
    2009            0 :         self.put(TWOPHASEDIR_KEY, Value::Image(newdirbuf));
    2010              : 
    2011            0 :         self.put(twophase_file_key(xid), Value::Image(img));
    2012            0 :         Ok(())
    2013            0 :     }
    2014              : 
    2015            1 :     pub async fn set_replorigin(
    2016            1 :         &mut self,
    2017            1 :         origin_id: RepOriginId,
    2018            1 :         origin_lsn: Lsn,
    2019            1 :     ) -> Result<(), WalIngestError> {
    2020            1 :         let key = repl_origin_key(origin_id);
    2021            1 :         self.put(key, Value::Image(origin_lsn.ser().unwrap().into()));
    2022            1 :         Ok(())
    2023            1 :     }
    2024              : 
    2025            0 :     pub async fn drop_replorigin(&mut self, origin_id: RepOriginId) -> Result<(), WalIngestError> {
    2026            0 :         self.set_replorigin(origin_id, Lsn::INVALID).await
    2027            0 :     }
    2028              : 
    2029          112 :     pub fn put_control_file(&mut self, img: Bytes) -> Result<(), WalIngestError> {
    2030          112 :         self.put(CONTROLFILE_KEY, Value::Image(img));
    2031          112 :         Ok(())
    2032          112 :     }
    2033              : 
    2034          119 :     pub fn put_checkpoint(&mut self, img: Bytes) -> Result<(), WalIngestError> {
    2035          119 :         self.put(CHECKPOINT_KEY, Value::Image(img));
    2036          119 :         Ok(())
    2037          119 :     }
    2038              : 
    2039            0 :     pub async fn drop_dbdir(
    2040            0 :         &mut self,
    2041            0 :         spcnode: Oid,
    2042            0 :         dbnode: Oid,
    2043            0 :         ctx: &RequestContext,
    2044            0 :     ) -> Result<(), WalIngestError> {
    2045            0 :         let total_blocks = self
    2046            0 :             .tline
    2047            0 :             .get_db_size(spcnode, dbnode, Version::Modified(self), ctx)
    2048            0 :             .await?;
    2049              : 
    2050              :         // Remove entry from dbdir
    2051            0 :         let buf = self.get(DBDIR_KEY, ctx).await?;
    2052            0 :         let mut dir = DbDirectory::des(&buf)?;
    2053            0 :         if dir.dbdirs.remove(&(spcnode, dbnode)).is_some() {
    2054            0 :             let buf = DbDirectory::ser(&dir)?;
    2055            0 :             self.pending_directory_entries.push((
    2056            0 :                 DirectoryKind::Db,
    2057            0 :                 MetricsUpdate::Set(dir.dbdirs.len() as u64),
    2058            0 :             ));
    2059            0 :             self.put(DBDIR_KEY, Value::Image(buf.into()));
    2060              :         } else {
    2061            0 :             warn!(
    2062            0 :                 "dropped dbdir for spcnode {} dbnode {} did not exist in db directory",
    2063              :                 spcnode, dbnode
    2064              :             );
    2065              :         }
    2066              : 
    2067              :         // Update logical database size.
    2068            0 :         self.pending_nblocks -= total_blocks as i64;
    2069              : 
    2070              :         // Delete all relations and metadata files for the spcnode/dnode
    2071            0 :         self.delete(dbdir_key_range(spcnode, dbnode));
    2072            0 :         Ok(())
    2073            0 :     }
    2074              : 
    2075              :     /// Create a relation fork.
    2076              :     ///
    2077              :     /// 'nblocks' is the initial size.
    2078          960 :     pub async fn put_rel_creation(
    2079          960 :         &mut self,
    2080          960 :         rel: RelTag,
    2081          960 :         nblocks: BlockNumber,
    2082          960 :         ctx: &RequestContext,
    2083          960 :     ) -> Result<(), WalIngestError> {
    2084          960 :         if rel.relnode == 0 {
    2085            0 :             Err(WalIngestErrorKind::LogicalError(anyhow::anyhow!(
    2086            0 :                 "invalid relnode"
    2087            0 :             )))?;
    2088          960 :         }
    2089              :         // It's possible that this is the first rel for this db in this
    2090              :         // tablespace.  Create the reldir entry for it if so.
    2091          960 :         let mut dbdir = DbDirectory::des(&self.get(DBDIR_KEY, ctx).await?)?;
    2092              : 
    2093          960 :         let dbdir_exists =
    2094          960 :             if let hash_map::Entry::Vacant(e) = dbdir.dbdirs.entry((rel.spcnode, rel.dbnode)) {
    2095              :                 // Didn't exist. Update dbdir
    2096            4 :                 e.insert(false);
    2097            4 :                 let buf = DbDirectory::ser(&dbdir)?;
    2098            4 :                 self.pending_directory_entries.push((
    2099            4 :                     DirectoryKind::Db,
    2100            4 :                     MetricsUpdate::Set(dbdir.dbdirs.len() as u64),
    2101            4 :                 ));
    2102            4 :                 self.put(DBDIR_KEY, Value::Image(buf.into()));
    2103            4 :                 false
    2104              :             } else {
    2105          956 :                 true
    2106              :             };
    2107              : 
    2108          960 :         let rel_dir_key = rel_dir_to_key(rel.spcnode, rel.dbnode);
    2109          960 :         let mut rel_dir = if !dbdir_exists {
    2110              :             // Create the RelDirectory
    2111            4 :             RelDirectory::default()
    2112              :         } else {
    2113              :             // reldir already exists, fetch it
    2114          956 :             RelDirectory::des(&self.get(rel_dir_key, ctx).await?)?
    2115              :         };
    2116              : 
    2117          960 :         let v2_enabled = self
    2118          960 :             .maybe_enable_rel_size_v2()
    2119          960 :             .map_err(WalIngestErrorKind::MaybeRelSizeV2Error)?;
    2120              : 
    2121          960 :         if v2_enabled {
    2122            0 :             if rel_dir.rels.contains(&(rel.relnode, rel.forknum)) {
    2123            0 :                 Err(WalIngestErrorKind::RelationAlreadyExists(rel))?;
    2124            0 :             }
    2125            0 :             let sparse_rel_dir_key =
    2126            0 :                 rel_tag_sparse_key(rel.spcnode, rel.dbnode, rel.relnode, rel.forknum);
    2127              :             // check if the rel_dir_key exists in v2
    2128            0 :             let val = self.sparse_get(sparse_rel_dir_key, ctx).await?;
    2129            0 :             let val = RelDirExists::decode_option(val)
    2130            0 :                 .map_err(|_| WalIngestErrorKind::InvalidRelDirKey(sparse_rel_dir_key))?;
    2131            0 :             if val == RelDirExists::Exists {
    2132            0 :                 Err(WalIngestErrorKind::RelationAlreadyExists(rel))?;
    2133            0 :             }
    2134            0 :             self.put(
    2135            0 :                 sparse_rel_dir_key,
    2136            0 :                 Value::Image(RelDirExists::Exists.encode()),
    2137              :             );
    2138            0 :             if !dbdir_exists {
    2139            0 :                 self.pending_directory_entries
    2140            0 :                     .push((DirectoryKind::Rel, MetricsUpdate::Set(0)));
    2141            0 :                 self.pending_directory_entries
    2142            0 :                     .push((DirectoryKind::RelV2, MetricsUpdate::Set(0)));
    2143              :                 // We don't write `rel_dir_key -> rel_dir.rels` back to the storage in the v2 path unless it's the initial creation.
    2144              :                 // TODO: if we have fully migrated to v2, no need to create this directory. Otherwise, there
    2145              :                 // will be key not found errors if we don't create an empty one for rel_size_v2.
    2146            0 :                 self.put(
    2147            0 :                     rel_dir_key,
    2148            0 :                     Value::Image(Bytes::from(RelDirectory::ser(&RelDirectory::default())?)),
    2149              :                 );
    2150            0 :             }
    2151            0 :             self.pending_directory_entries
    2152            0 :                 .push((DirectoryKind::RelV2, MetricsUpdate::Add(1)));
    2153              :         } else {
    2154              :             // Add the new relation to the rel directory entry, and write it back
    2155          960 :             if !rel_dir.rels.insert((rel.relnode, rel.forknum)) {
    2156            0 :                 Err(WalIngestErrorKind::RelationAlreadyExists(rel))?;
    2157          960 :             }
    2158          960 :             if !dbdir_exists {
    2159            4 :                 self.pending_directory_entries
    2160            4 :                     .push((DirectoryKind::Rel, MetricsUpdate::Set(0)))
    2161          956 :             }
    2162          960 :             self.pending_directory_entries
    2163          960 :                 .push((DirectoryKind::Rel, MetricsUpdate::Add(1)));
    2164          960 :             self.put(
    2165          960 :                 rel_dir_key,
    2166          960 :                 Value::Image(Bytes::from(RelDirectory::ser(&rel_dir)?)),
    2167              :             );
    2168              :         }
    2169              : 
    2170              :         // Put size
    2171          960 :         let size_key = rel_size_to_key(rel);
    2172          960 :         let buf = nblocks.to_le_bytes();
    2173          960 :         self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
    2174              : 
    2175          960 :         self.pending_nblocks += nblocks as i64;
    2176              : 
    2177              :         // Update relation size cache
    2178          960 :         self.tline.set_cached_rel_size(rel, self.lsn, nblocks);
    2179              : 
    2180              :         // Even if nblocks > 0, we don't insert any actual blocks here. That's up to the
    2181              :         // caller.
    2182          960 :         Ok(())
    2183          960 :     }
    2184              : 
    2185              :     /// Truncate relation
    2186         3006 :     pub async fn put_rel_truncation(
    2187         3006 :         &mut self,
    2188         3006 :         rel: RelTag,
    2189         3006 :         nblocks: BlockNumber,
    2190         3006 :         ctx: &RequestContext,
    2191         3006 :     ) -> Result<(), WalIngestError> {
    2192         3006 :         ensure_walingest!(rel.relnode != 0, RelationError::InvalidRelnode);
    2193         3006 :         if self
    2194         3006 :             .tline
    2195         3006 :             .get_rel_exists(rel, Version::Modified(self), ctx)
    2196         3006 :             .await?
    2197              :         {
    2198         3006 :             let size_key = rel_size_to_key(rel);
    2199              :             // Fetch the old size first
    2200         3006 :             let old_size = self.get(size_key, ctx).await?.get_u32_le();
    2201              : 
    2202              :             // Update the entry with the new size.
    2203         3006 :             let buf = nblocks.to_le_bytes();
    2204         3006 :             self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
    2205              : 
    2206              :             // Update relation size cache
    2207         3006 :             self.tline.set_cached_rel_size(rel, self.lsn, nblocks);
    2208              : 
    2209              :             // Update logical database size.
    2210         3006 :             self.pending_nblocks -= old_size as i64 - nblocks as i64;
    2211            0 :         }
    2212         3006 :         Ok(())
    2213         3006 :     }
    2214              : 
    2215              :     /// Extend relation
    2216              :     /// If new size is smaller, do nothing.
    2217       138340 :     pub async fn put_rel_extend(
    2218       138340 :         &mut self,
    2219       138340 :         rel: RelTag,
    2220       138340 :         nblocks: BlockNumber,
    2221       138340 :         ctx: &RequestContext,
    2222       138340 :     ) -> Result<(), WalIngestError> {
    2223       138340 :         ensure_walingest!(rel.relnode != 0, RelationError::InvalidRelnode);
    2224              : 
    2225              :         // Put size
    2226       138340 :         let size_key = rel_size_to_key(rel);
    2227       138340 :         let old_size = self.get(size_key, ctx).await?.get_u32_le();
    2228              : 
    2229              :         // only extend relation here. never decrease the size
    2230       138340 :         if nblocks > old_size {
    2231       137394 :             let buf = nblocks.to_le_bytes();
    2232       137394 :             self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
    2233       137394 : 
    2234       137394 :             // Update relation size cache
    2235       137394 :             self.tline.set_cached_rel_size(rel, self.lsn, nblocks);
    2236       137394 : 
    2237       137394 :             self.pending_nblocks += nblocks as i64 - old_size as i64;
    2238       137394 :         }
    2239       138340 :         Ok(())
    2240       138340 :     }
    2241              : 
    2242              :     /// Drop some relations
    2243            5 :     pub(crate) async fn put_rel_drops(
    2244            5 :         &mut self,
    2245            5 :         drop_relations: HashMap<(u32, u32), Vec<RelTag>>,
    2246            5 :         ctx: &RequestContext,
    2247            5 :     ) -> Result<(), WalIngestError> {
    2248            5 :         let v2_enabled = self
    2249            5 :             .maybe_enable_rel_size_v2()
    2250            5 :             .map_err(WalIngestErrorKind::MaybeRelSizeV2Error)?;
    2251            6 :         for ((spc_node, db_node), rel_tags) in drop_relations {
    2252            1 :             let dir_key = rel_dir_to_key(spc_node, db_node);
    2253            1 :             let buf = self.get(dir_key, ctx).await?;
    2254            1 :             let mut dir = RelDirectory::des(&buf)?;
    2255              : 
    2256            1 :             let mut dirty = false;
    2257            2 :             for rel_tag in rel_tags {
    2258            1 :                 let found = if dir.rels.remove(&(rel_tag.relnode, rel_tag.forknum)) {
    2259            1 :                     self.pending_directory_entries
    2260            1 :                         .push((DirectoryKind::Rel, MetricsUpdate::Sub(1)));
    2261            1 :                     dirty = true;
    2262            1 :                     true
    2263            0 :                 } else if v2_enabled {
    2264              :                     // The rel is not found in the old reldir key, so we need to check the new sparse keyspace.
    2265              :                     // Note that a relation can only exist in one of the two keyspaces (guaranteed by the ingestion
    2266              :                     // logic).
    2267            0 :                     let key =
    2268            0 :                         rel_tag_sparse_key(spc_node, db_node, rel_tag.relnode, rel_tag.forknum);
    2269            0 :                     let val = RelDirExists::decode_option(self.sparse_get(key, ctx).await?)
    2270            0 :                         .map_err(|_| WalIngestErrorKind::InvalidKey(key, self.lsn))?;
    2271            0 :                     if val == RelDirExists::Exists {
    2272            0 :                         self.pending_directory_entries
    2273            0 :                             .push((DirectoryKind::RelV2, MetricsUpdate::Sub(1)));
    2274              :                         // put tombstone
    2275            0 :                         self.put(key, Value::Image(RelDirExists::Removed.encode()));
    2276              :                         // no need to set dirty to true
    2277            0 :                         true
    2278              :                     } else {
    2279            0 :                         false
    2280              :                     }
    2281              :                 } else {
    2282            0 :                     false
    2283              :                 };
    2284              : 
    2285            1 :                 if found {
    2286              :                     // update logical size
    2287            1 :                     let size_key = rel_size_to_key(rel_tag);
    2288            1 :                     let old_size = self.get(size_key, ctx).await?.get_u32_le();
    2289            1 :                     self.pending_nblocks -= old_size as i64;
    2290              : 
    2291              :                     // Remove entry from relation size cache
    2292            1 :                     self.tline.remove_cached_rel_size(&rel_tag);
    2293              : 
    2294              :                     // Delete size entry, as well as all blocks; this is currently a no-op because we haven't implemented tombstones in storage.
    2295            1 :                     self.delete(rel_key_range(rel_tag));
    2296            0 :                 }
    2297              :             }
    2298              : 
    2299            1 :             if dirty {
    2300            1 :                 self.put(dir_key, Value::Image(Bytes::from(RelDirectory::ser(&dir)?)));
    2301            0 :             }
    2302              :         }
    2303              : 
    2304            5 :         Ok(())
    2305            5 :     }
    2306              : 
    2307            3 :     pub async fn put_slru_segment_creation(
    2308            3 :         &mut self,
    2309            3 :         kind: SlruKind,
    2310            3 :         segno: u32,
    2311            3 :         nblocks: BlockNumber,
    2312            3 :         ctx: &RequestContext,
    2313            3 :     ) -> Result<(), WalIngestError> {
    2314            3 :         assert!(self.tline.tenant_shard_id.is_shard_zero());
    2315              : 
    2316              :         // Add it to the directory entry
    2317            3 :         let dir_key = slru_dir_to_key(kind);
    2318            3 :         let buf = self.get(dir_key, ctx).await?;
    2319            3 :         let mut dir = SlruSegmentDirectory::des(&buf)?;
    2320              : 
    2321            3 :         if !dir.segments.insert(segno) {
    2322            0 :             Err(WalIngestErrorKind::SlruAlreadyExists(kind, segno))?;
    2323            3 :         }
    2324            3 :         self.pending_directory_entries.push((
    2325            3 :             DirectoryKind::SlruSegment(kind),
    2326            3 :             MetricsUpdate::Set(dir.segments.len() as u64),
    2327            3 :         ));
    2328            3 :         self.put(
    2329            3 :             dir_key,
    2330            3 :             Value::Image(Bytes::from(SlruSegmentDirectory::ser(&dir)?)),
    2331              :         );
    2332              : 
    2333              :         // Put size
    2334            3 :         let size_key = slru_segment_size_to_key(kind, segno);
    2335            3 :         let buf = nblocks.to_le_bytes();
    2336            3 :         self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
    2337              : 
    2338              :         // even if nblocks > 0, we don't insert any actual blocks here
    2339              : 
    2340            3 :         Ok(())
    2341            3 :     }
    2342              : 
    2343              :     /// Extend SLRU segment
    2344            0 :     pub fn put_slru_extend(
    2345            0 :         &mut self,
    2346            0 :         kind: SlruKind,
    2347            0 :         segno: u32,
    2348            0 :         nblocks: BlockNumber,
    2349            0 :     ) -> Result<(), WalIngestError> {
    2350            0 :         assert!(self.tline.tenant_shard_id.is_shard_zero());
    2351              : 
    2352              :         // Put size
    2353            0 :         let size_key = slru_segment_size_to_key(kind, segno);
    2354            0 :         let buf = nblocks.to_le_bytes();
    2355            0 :         self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
    2356            0 :         Ok(())
    2357            0 :     }
    2358              : 
    2359              :     /// This method is used for marking truncated SLRU files
    2360            0 :     pub async fn drop_slru_segment(
    2361            0 :         &mut self,
    2362            0 :         kind: SlruKind,
    2363            0 :         segno: u32,
    2364            0 :         ctx: &RequestContext,
    2365            0 :     ) -> Result<(), WalIngestError> {
    2366              :         // Remove it from the directory entry
    2367            0 :         let dir_key = slru_dir_to_key(kind);
    2368            0 :         let buf = self.get(dir_key, ctx).await?;
    2369            0 :         let mut dir = SlruSegmentDirectory::des(&buf)?;
    2370              : 
    2371            0 :         if !dir.segments.remove(&segno) {
    2372            0 :             warn!("slru segment {:?}/{} does not exist", kind, segno);
    2373            0 :         }
    2374            0 :         self.pending_directory_entries.push((
    2375            0 :             DirectoryKind::SlruSegment(kind),
    2376            0 :             MetricsUpdate::Set(dir.segments.len() as u64),
    2377            0 :         ));
    2378            0 :         self.put(
    2379            0 :             dir_key,
    2380            0 :             Value::Image(Bytes::from(SlruSegmentDirectory::ser(&dir)?)),
    2381              :         );
    2382              : 
    2383              :         // Delete size entry, as well as all blocks
    2384            0 :         self.delete(slru_segment_key_range(kind, segno));
    2385              : 
    2386            0 :         Ok(())
    2387            0 :     }
    2388              : 
    2389              :     /// Drop a relmapper file (pg_filenode.map)
    2390            0 :     pub fn drop_relmap_file(&mut self, _spcnode: Oid, _dbnode: Oid) -> Result<(), WalIngestError> {
    2391              :         // TODO
    2392            0 :         Ok(())
    2393            0 :     }
    2394              : 
    2395              :     /// This method is used for marking truncated SLRU files
    2396            0 :     pub async fn drop_twophase_file(
    2397            0 :         &mut self,
    2398            0 :         xid: u64,
    2399            0 :         ctx: &RequestContext,
    2400            0 :     ) -> Result<(), WalIngestError> {
    2401              :         // Remove it from the directory entry
    2402            0 :         let buf = self.get(TWOPHASEDIR_KEY, ctx).await?;
    2403            0 :         let newdirbuf = if self.tline.pg_version >= PgMajorVersion::PG17 {
    2404            0 :             let mut dir = TwoPhaseDirectoryV17::des(&buf)?;
    2405              : 
    2406            0 :             if !dir.xids.remove(&xid) {
    2407            0 :                 warn!("twophase file for xid {} does not exist", xid);
    2408            0 :             }
    2409            0 :             self.pending_directory_entries.push((
    2410            0 :                 DirectoryKind::TwoPhase,
    2411            0 :                 MetricsUpdate::Set(dir.xids.len() as u64),
    2412            0 :             ));
    2413            0 :             Bytes::from(TwoPhaseDirectoryV17::ser(&dir)?)
    2414              :         } else {
    2415            0 :             let xid: u32 = u32::try_from(xid)
    2416            0 :                 .map_err(|e| WalIngestErrorKind::LogicalError(anyhow::Error::from(e)))?;
    2417            0 :             let mut dir = TwoPhaseDirectory::des(&buf)?;
    2418              : 
    2419            0 :             if !dir.xids.remove(&xid) {
    2420            0 :                 warn!("twophase file for xid {} does not exist", xid);
    2421            0 :             }
    2422            0 :             self.pending_directory_entries.push((
    2423            0 :                 DirectoryKind::TwoPhase,
    2424            0 :                 MetricsUpdate::Set(dir.xids.len() as u64),
    2425            0 :             ));
    2426            0 :             Bytes::from(TwoPhaseDirectory::ser(&dir)?)
    2427              :         };
    2428            0 :         self.put(TWOPHASEDIR_KEY, Value::Image(newdirbuf));
    2429              : 
    2430              :         // Delete it
    2431            0 :         self.delete(twophase_key_range(xid));
    2432              : 
    2433            0 :         Ok(())
    2434            0 :     }
    2435              : 
    2436            8 :     pub async fn put_file(
    2437            8 :         &mut self,
    2438            8 :         path: &str,
    2439            8 :         content: &[u8],
    2440            8 :         ctx: &RequestContext,
    2441            8 :     ) -> Result<(), WalIngestError> {
    2442            8 :         let key = aux_file::encode_aux_file_key(path);
    2443              :         // retrieve the key from the engine
    2444            8 :         let old_val = match self.get(key, ctx).await {
    2445            2 :             Ok(val) => Some(val),
    2446            6 :             Err(PageReconstructError::MissingKey(_)) => None,
    2447            0 :             Err(e) => return Err(e.into()),
    2448              :         };
    2449            8 :         let files: Vec<(&str, &[u8])> = if let Some(ref old_val) = old_val {
    2450            2 :             aux_file::decode_file_value(old_val).map_err(WalIngestErrorKind::EncodeAuxFileError)?
    2451              :         } else {
    2452            6 :             Vec::new()
    2453              :         };
    2454            8 :         let mut other_files = Vec::with_capacity(files.len());
    2455            8 :         let mut modifying_file = None;
    2456           10 :         for file @ (p, content) in files {
    2457            2 :             if path == p {
    2458            2 :                 assert!(
    2459            2 :                     modifying_file.is_none(),
    2460            0 :                     "duplicated entries found for {path}"
    2461              :                 );
    2462            2 :                 modifying_file = Some(content);
    2463            0 :             } else {
    2464            0 :                 other_files.push(file);
    2465            0 :             }
    2466              :         }
    2467            8 :         let mut new_files = other_files;
    2468            8 :         match (modifying_file, content.is_empty()) {
    2469            1 :             (Some(old_content), false) => {
    2470            1 :                 self.tline
    2471            1 :                     .aux_file_size_estimator
    2472            1 :                     .on_update(old_content.len(), content.len());
    2473            1 :                 new_files.push((path, content));
    2474            1 :             }
    2475            1 :             (Some(old_content), true) => {
    2476            1 :                 self.tline
    2477            1 :                     .aux_file_size_estimator
    2478            1 :                     .on_remove(old_content.len());
    2479            1 :                 // not adding the file key to the final `new_files` vec.
    2480            1 :             }
    2481            6 :             (None, false) => {
    2482            6 :                 self.tline.aux_file_size_estimator.on_add(content.len());
    2483            6 :                 new_files.push((path, content));
    2484            6 :             }
    2485              :             // Compute may request delete of old version of pgstat AUX file if new one exceeds size limit.
    2486              :             // Compute doesn't know if previous version of this file exists or not, so
    2487              :             // attempt to delete non-existing file can cause this message.
    2488              :             // To avoid false alarms, log it as info rather than warning.
    2489            0 :             (None, true) if path.starts_with("pg_stat/") => {
    2490            0 :                 info!("removing non-existing pg_stat file: {}", path)
    2491              :             }
    2492            0 :             (None, true) => warn!("removing non-existing aux file: {}", path),
    2493              :         }
    2494            8 :         let new_val = aux_file::encode_file_value(&new_files)
    2495            8 :             .map_err(WalIngestErrorKind::EncodeAuxFileError)?;
    2496            8 :         self.put(key, Value::Image(new_val.into()));
    2497              : 
    2498            8 :         Ok(())
    2499            8 :     }
    2500              : 
    2501              :     ///
    2502              :     /// Flush changes accumulated so far to the underlying repository.
    2503              :     ///
    2504              :     /// Usually, changes made in DatadirModification are atomic, but this allows
    2505              :     /// you to flush them to the underlying repository before the final `commit`.
    2506              :     /// That allows to free up the memory used to hold the pending changes.
    2507              :     ///
    2508              :     /// Currently only used during bulk import of a data directory. In that
    2509              :     /// context, breaking the atomicity is OK. If the import is interrupted, the
    2510              :     /// whole import fails and the timeline will be deleted anyway.
    2511              :     /// (Or to be precise, it will be left behind for debugging purposes and
    2512              :     /// ignored, see <https://github.com/neondatabase/neon/pull/1809>)
    2513              :     ///
    2514              :     /// Note: A consequence of flushing the pending operations is that they
    2515              :     /// won't be visible to subsequent operations until `commit`. The function
    2516              :     /// retains all the metadata, but data pages are flushed. That's again OK
    2517              :     /// for bulk import, where you are just loading data pages and won't try to
    2518              :     /// modify the same pages twice.
    2519          965 :     pub(crate) async fn flush(&mut self, ctx: &RequestContext) -> anyhow::Result<()> {
    2520              :         // Unless we have accumulated a decent amount of changes, it's not worth it
    2521              :         // to scan through the pending_updates list.
    2522          965 :         let pending_nblocks = self.pending_nblocks;
    2523          965 :         if pending_nblocks < 10000 {
    2524          965 :             return Ok(());
    2525            0 :         }
    2526              : 
    2527            0 :         let mut writer = self.tline.writer().await;
    2528              : 
    2529              :         // Flush relation and  SLRU data blocks, keep metadata.
    2530            0 :         if let Some(batch) = self.pending_data_batch.take() {
    2531            0 :             tracing::debug!(
    2532            0 :                 "Flushing batch with max_lsn={}. Last record LSN is {}",
    2533              :                 batch.max_lsn,
    2534            0 :                 self.tline.get_last_record_lsn()
    2535              :             );
    2536              : 
    2537              :             // This bails out on first error without modifying pending_updates.
    2538              :             // That's Ok, cf this function's doc comment.
    2539            0 :             writer.put_batch(batch, ctx).await?;
    2540            0 :         }
    2541              : 
    2542            0 :         if pending_nblocks != 0 {
    2543            0 :             writer.update_current_logical_size(pending_nblocks * i64::from(BLCKSZ));
    2544            0 :             self.pending_nblocks = 0;
    2545            0 :         }
    2546              : 
    2547            0 :         for (kind, count) in std::mem::take(&mut self.pending_directory_entries) {
    2548            0 :             writer.update_directory_entries_count(kind, count);
    2549            0 :         }
    2550              : 
    2551            0 :         Ok(())
    2552          965 :     }
    2553              : 
    2554              :     ///
    2555              :     /// Finish this atomic update, writing all the updated keys to the
    2556              :     /// underlying timeline.
    2557              :     /// All the modifications in this atomic update are stamped by the specified LSN.
    2558              :     ///
    2559       371557 :     pub async fn commit(&mut self, ctx: &RequestContext) -> anyhow::Result<()> {
    2560       371557 :         let mut writer = self.tline.writer().await;
    2561              : 
    2562       371557 :         let pending_nblocks = self.pending_nblocks;
    2563       371557 :         self.pending_nblocks = 0;
    2564              : 
    2565              :         // Ordering: the items in this batch do not need to be in any global order, but values for
    2566              :         // a particular Key must be in Lsn order relative to one another.  InMemoryLayer relies on
    2567              :         // this to do efficient updates to its index.  See [`wal_decoder::serialized_batch`] for
    2568              :         // more details.
    2569              : 
    2570       371557 :         let metadata_batch = {
    2571       371557 :             let pending_meta = self
    2572       371557 :                 .pending_metadata_pages
    2573       371557 :                 .drain()
    2574       371557 :                 .flat_map(|(key, values)| {
    2575       137068 :                     values
    2576       137068 :                         .into_iter()
    2577       137068 :                         .map(move |(lsn, value_size, value)| (key, lsn, value_size, value))
    2578       137068 :                 })
    2579       371557 :                 .collect::<Vec<_>>();
    2580              : 
    2581       371557 :             if pending_meta.is_empty() {
    2582       236139 :                 None
    2583              :             } else {
    2584       135418 :                 Some(SerializedValueBatch::from_values(pending_meta))
    2585              :             }
    2586              :         };
    2587              : 
    2588       371557 :         let data_batch = self.pending_data_batch.take();
    2589              : 
    2590       371557 :         let maybe_batch = match (data_batch, metadata_batch) {
    2591       132278 :             (Some(mut data), Some(metadata)) => {
    2592       132278 :                 data.extend(metadata);
    2593       132278 :                 Some(data)
    2594              :             }
    2595        71631 :             (Some(data), None) => Some(data),
    2596         3140 :             (None, Some(metadata)) => Some(metadata),
    2597       164508 :             (None, None) => None,
    2598              :         };
    2599              : 
    2600       371557 :         if let Some(batch) = maybe_batch {
    2601       207049 :             tracing::debug!(
    2602            0 :                 "Flushing batch with max_lsn={}. Last record LSN is {}",
    2603              :                 batch.max_lsn,
    2604            0 :                 self.tline.get_last_record_lsn()
    2605              :             );
    2606              : 
    2607              :             // This bails out on first error without modifying pending_updates.
    2608              :             // That's Ok, cf this function's doc comment.
    2609       207049 :             writer.put_batch(batch, ctx).await?;
    2610       164508 :         }
    2611              : 
    2612       371557 :         if !self.pending_deletions.is_empty() {
    2613            1 :             writer.delete_batch(&self.pending_deletions, ctx).await?;
    2614            1 :             self.pending_deletions.clear();
    2615       371556 :         }
    2616              : 
    2617       371557 :         self.pending_lsns.push(self.lsn);
    2618       444486 :         for pending_lsn in self.pending_lsns.drain(..) {
    2619       444486 :             // TODO(vlad): pretty sure the comment below is not valid anymore
    2620       444486 :             // and we can call finish write with the latest LSN
    2621       444486 :             //
    2622       444486 :             // Ideally, we should be able to call writer.finish_write() only once
    2623       444486 :             // with the highest LSN. However, the last_record_lsn variable in the
    2624       444486 :             // timeline keeps track of the latest LSN and the immediate previous LSN
    2625       444486 :             // so we need to record every LSN to not leave a gap between them.
    2626       444486 :             writer.finish_write(pending_lsn);
    2627       444486 :         }
    2628              : 
    2629       371557 :         if pending_nblocks != 0 {
    2630       135285 :             writer.update_current_logical_size(pending_nblocks * i64::from(BLCKSZ));
    2631       236272 :         }
    2632              : 
    2633       371557 :         for (kind, count) in std::mem::take(&mut self.pending_directory_entries) {
    2634         1527 :             writer.update_directory_entries_count(kind, count);
    2635         1527 :         }
    2636              : 
    2637       371557 :         self.pending_metadata_bytes = 0;
    2638              : 
    2639       371557 :         Ok(())
    2640       371557 :     }
    2641              : 
    2642       145852 :     pub(crate) fn len(&self) -> usize {
    2643       145852 :         self.pending_metadata_pages.len()
    2644       145852 :             + self.pending_data_batch.as_ref().map_or(0, |b| b.len())
    2645       145852 :             + self.pending_deletions.len()
    2646       145852 :     }
    2647              : 
    2648              :     /// Read a page from the Timeline we are writing to.  For metadata pages, this passes through
    2649              :     /// a cache in Self, which makes writes earlier in this modification visible to WAL records later
    2650              :     /// in the modification.
    2651              :     ///
    2652              :     /// For data pages, reads pass directly to the owning Timeline: any ingest code which reads a data
    2653              :     /// page must ensure that the pages they read are already committed in Timeline, for example
    2654              :     /// DB create operations are always preceded by a call to commit().  This is special cased because
    2655              :     /// it's rare: all the 'normal' WAL operations will only read metadata pages such as relation sizes,
    2656              :     /// and not data pages.
    2657       143293 :     async fn get(&self, key: Key, ctx: &RequestContext) -> Result<Bytes, PageReconstructError> {
    2658       143293 :         if !Self::is_data_key(&key) {
    2659              :             // Have we already updated the same key? Read the latest pending updated
    2660              :             // version in that case.
    2661              :             //
    2662              :             // Note: we don't check pending_deletions. It is an error to request a
    2663              :             // value that has been removed, deletion only avoids leaking storage.
    2664       143293 :             if let Some(values) = self.pending_metadata_pages.get(&key.to_compact()) {
    2665         7964 :                 if let Some((_, _, value)) = values.last() {
    2666         7964 :                     return if let Value::Image(img) = value {
    2667         7964 :                         Ok(img.clone())
    2668              :                     } else {
    2669              :                         // Currently, we never need to read back a WAL record that we
    2670              :                         // inserted in the same "transaction". All the metadata updates
    2671              :                         // work directly with Images, and we never need to read actual
    2672              :                         // data pages. We could handle this if we had to, by calling
    2673              :                         // the walredo manager, but let's keep it simple for now.
    2674            0 :                         Err(PageReconstructError::Other(anyhow::anyhow!(
    2675            0 :                             "unexpected pending WAL record"
    2676            0 :                         )))
    2677              :                     };
    2678            0 :                 }
    2679       135329 :             }
    2680              :         } else {
    2681              :             // This is an expensive check, so we only do it in debug mode. If reading a data key,
    2682              :             // this key should never be present in pending_data_pages. We ensure this by committing
    2683              :             // modifications before ingesting DB create operations, which are the only kind that reads
    2684              :             // data pages during ingest.
    2685            0 :             if cfg!(debug_assertions) {
    2686            0 :                 assert!(
    2687            0 :                     !self
    2688            0 :                         .pending_data_batch
    2689            0 :                         .as_ref()
    2690            0 :                         .is_some_and(|b| b.updates_key(&key))
    2691              :                 );
    2692            0 :             }
    2693              :         }
    2694              : 
    2695              :         // Metadata page cache miss, or we're reading a data page.
    2696       135329 :         let lsn = Lsn::max(self.tline.get_last_record_lsn(), self.lsn);
    2697       135329 :         self.tline.get(key, lsn, ctx).await
    2698       143293 :     }
    2699              : 
    2700              :     /// Get a key from the sparse keyspace. Automatically converts the missing key error
    2701              :     /// and the empty value into None.
    2702            0 :     async fn sparse_get(
    2703            0 :         &self,
    2704            0 :         key: Key,
    2705            0 :         ctx: &RequestContext,
    2706            0 :     ) -> Result<Option<Bytes>, PageReconstructError> {
    2707            0 :         let val = self.get(key, ctx).await;
    2708            0 :         match val {
    2709            0 :             Ok(val) if val.is_empty() => Ok(None),
    2710            0 :             Ok(val) => Ok(Some(val)),
    2711            0 :             Err(PageReconstructError::MissingKey(_)) => Ok(None),
    2712            0 :             Err(e) => Err(e),
    2713              :         }
    2714            0 :     }
    2715              : 
    2716              :     #[cfg(test)]
    2717            2 :     pub fn put_for_unit_test(&mut self, key: Key, val: Value) {
    2718            2 :         self.put(key, val);
    2719            2 :     }
    2720              : 
    2721       282078 :     fn put(&mut self, key: Key, val: Value) {
    2722       282078 :         if Self::is_data_key(&key) {
    2723       138934 :             self.put_data(key.to_compact(), val)
    2724              :         } else {
    2725       143144 :             self.put_metadata(key.to_compact(), val)
    2726              :         }
    2727       282078 :     }
    2728              : 
    2729       138934 :     fn put_data(&mut self, key: CompactKey, val: Value) {
    2730       138934 :         let batch = self
    2731       138934 :             .pending_data_batch
    2732       138934 :             .get_or_insert_with(SerializedValueBatch::default);
    2733       138934 :         batch.put(key, val, self.lsn);
    2734       138934 :     }
    2735              : 
    2736       143144 :     fn put_metadata(&mut self, key: CompactKey, val: Value) {
    2737       143144 :         let values = self.pending_metadata_pages.entry(key).or_default();
    2738              :         // Replace the previous value if it exists at the same lsn
    2739       143144 :         if let Some((last_lsn, last_value_ser_size, last_value)) = values.last_mut() {
    2740         6076 :             if *last_lsn == self.lsn {
    2741              :                 // Update the pending_metadata_bytes contribution from this entry, and update the serialized size in place
    2742         6076 :                 self.pending_metadata_bytes -= *last_value_ser_size;
    2743         6076 :                 *last_value_ser_size = val.serialized_size().unwrap() as usize;
    2744         6076 :                 self.pending_metadata_bytes += *last_value_ser_size;
    2745              : 
    2746              :                 // Use the latest value, this replaces any earlier write to the same (key,lsn), such as much
    2747              :                 // have been generated by synthesized zero page writes prior to the first real write to a page.
    2748         6076 :                 *last_value = val;
    2749         6076 :                 return;
    2750            0 :             }
    2751       137068 :         }
    2752              : 
    2753       137068 :         let val_serialized_size = val.serialized_size().unwrap() as usize;
    2754       137068 :         self.pending_metadata_bytes += val_serialized_size;
    2755       137068 :         values.push((self.lsn, val_serialized_size, val));
    2756              : 
    2757       137068 :         if key == CHECKPOINT_KEY.to_compact() {
    2758          119 :             tracing::debug!("Checkpoint key added to pending with size {val_serialized_size}");
    2759       136949 :         }
    2760       143144 :     }
    2761              : 
    2762            1 :     fn delete(&mut self, key_range: Range<Key>) {
    2763            1 :         trace!("DELETE {}-{}", key_range.start, key_range.end);
    2764            1 :         self.pending_deletions.push((key_range, self.lsn));
    2765            1 :     }
    2766              : }
    2767              : 
    2768              : /// Statistics for a DatadirModification.
    2769              : #[derive(Default)]
    2770              : pub struct DatadirModificationStats {
    2771              :     pub metadata_images: u64,
    2772              :     pub metadata_deltas: u64,
    2773              :     pub data_images: u64,
    2774              :     pub data_deltas: u64,
    2775              : }
    2776              : 
    2777              : /// This struct facilitates accessing either a committed key from the timeline at a
    2778              : /// specific LSN, or the latest uncommitted key from a pending modification.
    2779              : ///
    2780              : /// During WAL ingestion, the records from multiple LSNs may be batched in the same
    2781              : /// modification before being flushed to the timeline. Hence, the routines in WalIngest
    2782              : /// need to look up the keys in the modification first before looking them up in the
    2783              : /// timeline to not miss the latest updates.
    2784              : #[derive(Clone, Copy)]
    2785              : pub enum Version<'a> {
    2786              :     LsnRange(LsnRange),
    2787              :     Modified(&'a DatadirModification<'a>),
    2788              : }
    2789              : 
    2790              : impl Version<'_> {
    2791           25 :     async fn get(
    2792           25 :         &self,
    2793           25 :         timeline: &Timeline,
    2794           25 :         key: Key,
    2795           25 :         ctx: &RequestContext,
    2796           25 :     ) -> Result<Bytes, PageReconstructError> {
    2797           25 :         match self {
    2798           15 :             Version::LsnRange(lsns) => timeline.get(key, lsns.effective_lsn, ctx).await,
    2799           10 :             Version::Modified(modification) => modification.get(key, ctx).await,
    2800              :         }
    2801           25 :     }
    2802              : 
    2803              :     /// Get a key from the sparse keyspace. Automatically converts the missing key error
    2804              :     /// and the empty value into None.
    2805            0 :     async fn sparse_get(
    2806            0 :         &self,
    2807            0 :         timeline: &Timeline,
    2808            0 :         key: Key,
    2809            0 :         ctx: &RequestContext,
    2810            0 :     ) -> Result<Option<Bytes>, PageReconstructError> {
    2811            0 :         let val = self.get(timeline, key, ctx).await;
    2812            0 :         match val {
    2813            0 :             Ok(val) if val.is_empty() => Ok(None),
    2814            0 :             Ok(val) => Ok(Some(val)),
    2815            0 :             Err(PageReconstructError::MissingKey(_)) => Ok(None),
    2816            0 :             Err(e) => Err(e),
    2817              :         }
    2818            0 :     }
    2819              : 
    2820           26 :     pub fn is_latest(&self) -> bool {
    2821           26 :         match self {
    2822           16 :             Version::LsnRange(lsns) => lsns.is_latest(),
    2823           10 :             Version::Modified(_) => true,
    2824              :         }
    2825           26 :     }
    2826              : 
    2827       224275 :     pub fn get_lsn(&self) -> Lsn {
    2828       224275 :         match self {
    2829        12224 :             Version::LsnRange(lsns) => lsns.effective_lsn,
    2830       212051 :             Version::Modified(modification) => modification.lsn,
    2831              :         }
    2832       224275 :     }
    2833              : 
    2834        12219 :     pub fn at(lsn: Lsn) -> Self {
    2835        12219 :         Version::LsnRange(LsnRange {
    2836        12219 :             effective_lsn: lsn,
    2837        12219 :             request_lsn: lsn,
    2838        12219 :         })
    2839        12219 :     }
    2840              : }
    2841              : 
    2842              : //--- Metadata structs stored in key-value pairs in the repository.
    2843              : 
    2844            0 : #[derive(Debug, Serialize, Deserialize)]
    2845              : pub(crate) struct DbDirectory {
    2846              :     // (spcnode, dbnode) -> (do relmapper and PG_VERSION files exist)
    2847              :     pub(crate) dbdirs: HashMap<(Oid, Oid), bool>,
    2848              : }
    2849              : 
    2850              : // The format of TwoPhaseDirectory changed in PostgreSQL v17, because the filenames of
    2851              : // pg_twophase files was expanded from 32-bit XIDs to 64-bit XIDs.  Previously, the files
    2852              : // were named like "pg_twophase/000002E5", now they're like
    2853              : // "pg_twophsae/0000000A000002E4".
    2854              : 
    2855            0 : #[derive(Debug, Serialize, Deserialize)]
    2856              : pub(crate) struct TwoPhaseDirectory {
    2857              :     pub(crate) xids: HashSet<TransactionId>,
    2858              : }
    2859              : 
    2860            0 : #[derive(Debug, Serialize, Deserialize)]
    2861              : struct TwoPhaseDirectoryV17 {
    2862              :     xids: HashSet<u64>,
    2863              : }
    2864              : 
    2865            0 : #[derive(Debug, Serialize, Deserialize, Default)]
    2866              : pub(crate) struct RelDirectory {
    2867              :     // Set of relations that exist. (relfilenode, forknum)
    2868              :     //
    2869              :     // TODO: Store it as a btree or radix tree or something else that spans multiple
    2870              :     // key-value pairs, if you have a lot of relations
    2871              :     pub(crate) rels: HashSet<(Oid, u8)>,
    2872              : }
    2873              : 
    2874            0 : #[derive(Debug, Serialize, Deserialize)]
    2875              : struct RelSizeEntry {
    2876              :     nblocks: u32,
    2877              : }
    2878              : 
    2879            0 : #[derive(Debug, Serialize, Deserialize, Default)]
    2880              : pub(crate) struct SlruSegmentDirectory {
    2881              :     // Set of SLRU segments that exist.
    2882              :     pub(crate) segments: HashSet<u32>,
    2883              : }
    2884              : 
    2885              : #[derive(Copy, Clone, PartialEq, Eq, Debug, enum_map::Enum)]
    2886              : #[repr(u8)]
    2887              : pub(crate) enum DirectoryKind {
    2888              :     Db,
    2889              :     TwoPhase,
    2890              :     Rel,
    2891              :     AuxFiles,
    2892              :     SlruSegment(SlruKind),
    2893              :     RelV2,
    2894              : }
    2895              : 
    2896              : impl DirectoryKind {
    2897              :     pub(crate) const KINDS_NUM: usize = <DirectoryKind as Enum>::LENGTH;
    2898         4582 :     pub(crate) fn offset(&self) -> usize {
    2899         4582 :         self.into_usize()
    2900         4582 :     }
    2901              : }
    2902              : 
    2903              : static ZERO_PAGE: Bytes = Bytes::from_static(&[0u8; BLCKSZ as usize]);
    2904              : 
    2905              : #[allow(clippy::bool_assert_comparison)]
    2906              : #[cfg(test)]
    2907              : mod tests {
    2908              :     use hex_literal::hex;
    2909              :     use pageserver_api::models::ShardParameters;
    2910              :     use pageserver_api::shard::ShardStripeSize;
    2911              :     use utils::id::TimelineId;
    2912              :     use utils::shard::{ShardCount, ShardNumber};
    2913              : 
    2914              :     use super::*;
    2915              :     use crate::DEFAULT_PG_VERSION;
    2916              :     use crate::tenant::harness::TenantHarness;
    2917              : 
    2918              :     /// Test a round trip of aux file updates, from DatadirModification to reading back from the Timeline
    2919              :     #[tokio::test]
    2920            1 :     async fn aux_files_round_trip() -> anyhow::Result<()> {
    2921            1 :         let name = "aux_files_round_trip";
    2922            1 :         let harness = TenantHarness::create(name).await?;
    2923              : 
    2924              :         pub const TIMELINE_ID: TimelineId =
    2925              :             TimelineId::from_array(hex!("11223344556677881122334455667788"));
    2926              : 
    2927            1 :         let (tenant, ctx) = harness.load().await;
    2928            1 :         let (tline, ctx) = tenant
    2929            1 :             .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    2930            1 :             .await?;
    2931            1 :         let tline = tline.raw_timeline().unwrap();
    2932              : 
    2933              :         // First modification: insert two keys
    2934            1 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    2935            1 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    2936            1 :         modification.set_lsn(Lsn(0x1008))?;
    2937            1 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    2938            1 :         modification.commit(&ctx).await?;
    2939            1 :         let expect_1008 = HashMap::from([
    2940            1 :             ("foo/bar1".to_string(), Bytes::from_static(b"content1")),
    2941            1 :             ("foo/bar2".to_string(), Bytes::from_static(b"content2")),
    2942            1 :         ]);
    2943              : 
    2944            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    2945              : 
    2946            1 :         let readback = tline
    2947            1 :             .list_aux_files(Lsn(0x1008), &ctx, io_concurrency.clone())
    2948            1 :             .await?;
    2949            1 :         assert_eq!(readback, expect_1008);
    2950              : 
    2951              :         // Second modification: update one key, remove the other
    2952            1 :         let mut modification = tline.begin_modification(Lsn(0x2000));
    2953            1 :         modification.put_file("foo/bar1", b"content3", &ctx).await?;
    2954            1 :         modification.set_lsn(Lsn(0x2008))?;
    2955            1 :         modification.put_file("foo/bar2", b"", &ctx).await?;
    2956            1 :         modification.commit(&ctx).await?;
    2957            1 :         let expect_2008 =
    2958            1 :             HashMap::from([("foo/bar1".to_string(), Bytes::from_static(b"content3"))]);
    2959              : 
    2960            1 :         let readback = tline
    2961            1 :             .list_aux_files(Lsn(0x2008), &ctx, io_concurrency.clone())
    2962            1 :             .await?;
    2963            1 :         assert_eq!(readback, expect_2008);
    2964              : 
    2965              :         // Reading back in time works
    2966            1 :         let readback = tline
    2967            1 :             .list_aux_files(Lsn(0x1008), &ctx, io_concurrency.clone())
    2968            1 :             .await?;
    2969            1 :         assert_eq!(readback, expect_1008);
    2970              : 
    2971            2 :         Ok(())
    2972            1 :     }
    2973              : 
    2974              :     #[test]
    2975            1 :     fn gap_finding() {
    2976            1 :         let rel = RelTag {
    2977            1 :             spcnode: 1663,
    2978            1 :             dbnode: 208101,
    2979            1 :             relnode: 2620,
    2980            1 :             forknum: 0,
    2981            1 :         };
    2982            1 :         let base_blkno = 1;
    2983              : 
    2984            1 :         let base_key = rel_block_to_key(rel, base_blkno);
    2985            1 :         let before_base_key = rel_block_to_key(rel, base_blkno - 1);
    2986              : 
    2987            1 :         let shard = ShardIdentity::unsharded();
    2988              : 
    2989            1 :         let mut previous_nblocks = 0;
    2990           11 :         for i in 0..10 {
    2991           10 :             let crnt_blkno = base_blkno + i;
    2992           10 :             let gaps = DatadirModification::find_gaps(rel, crnt_blkno, previous_nblocks, &shard);
    2993              : 
    2994           10 :             previous_nblocks = crnt_blkno + 1;
    2995              : 
    2996           10 :             if i == 0 {
    2997              :                 // The first block we write is 1, so we should find the gap.
    2998            1 :                 assert_eq!(gaps.unwrap(), KeySpace::single(before_base_key..base_key));
    2999              :             } else {
    3000            9 :                 assert!(gaps.is_none());
    3001              :             }
    3002              :         }
    3003              : 
    3004              :         // This is an update to an already existing block. No gaps here.
    3005            1 :         let update_blkno = 5;
    3006            1 :         let gaps = DatadirModification::find_gaps(rel, update_blkno, previous_nblocks, &shard);
    3007            1 :         assert!(gaps.is_none());
    3008              : 
    3009              :         // This is an update past the current end block.
    3010            1 :         let after_gap_blkno = 20;
    3011            1 :         let gaps = DatadirModification::find_gaps(rel, after_gap_blkno, previous_nblocks, &shard);
    3012              : 
    3013            1 :         let gap_start_key = rel_block_to_key(rel, previous_nblocks);
    3014            1 :         let after_gap_key = rel_block_to_key(rel, after_gap_blkno);
    3015            1 :         assert_eq!(
    3016            1 :             gaps.unwrap(),
    3017            1 :             KeySpace::single(gap_start_key..after_gap_key)
    3018              :         );
    3019            1 :     }
    3020              : 
    3021              :     #[test]
    3022            1 :     fn sharded_gap_finding() {
    3023            1 :         let rel = RelTag {
    3024            1 :             spcnode: 1663,
    3025            1 :             dbnode: 208101,
    3026            1 :             relnode: 2620,
    3027            1 :             forknum: 0,
    3028            1 :         };
    3029              : 
    3030            1 :         let first_blkno = 6;
    3031              : 
    3032              :         // This shard will get the even blocks
    3033            1 :         let shard = ShardIdentity::from_params(
    3034            1 :             ShardNumber(0),
    3035            1 :             ShardParameters {
    3036            1 :                 count: ShardCount(2),
    3037            1 :                 stripe_size: ShardStripeSize(1),
    3038            1 :             },
    3039              :         );
    3040              : 
    3041              :         // Only keys belonging to this shard are considered as gaps.
    3042            1 :         let mut previous_nblocks = 0;
    3043            1 :         let gaps =
    3044            1 :             DatadirModification::find_gaps(rel, first_blkno, previous_nblocks, &shard).unwrap();
    3045            1 :         assert!(!gaps.ranges.is_empty());
    3046            3 :         for gap_range in gaps.ranges {
    3047            2 :             let mut k = gap_range.start;
    3048            4 :             while k != gap_range.end {
    3049            2 :                 assert_eq!(shard.get_shard_number(&k), shard.number);
    3050            2 :                 k = k.next();
    3051              :             }
    3052              :         }
    3053              : 
    3054            1 :         previous_nblocks = first_blkno;
    3055              : 
    3056            1 :         let update_blkno = 2;
    3057            1 :         let gaps = DatadirModification::find_gaps(rel, update_blkno, previous_nblocks, &shard);
    3058            1 :         assert!(gaps.is_none());
    3059            1 :     }
    3060              : 
    3061              :     /*
    3062              :         fn assert_current_logical_size<R: Repository>(timeline: &DatadirTimeline<R>, lsn: Lsn) {
    3063              :             let incremental = timeline.get_current_logical_size();
    3064              :             let non_incremental = timeline
    3065              :                 .get_current_logical_size_non_incremental(lsn)
    3066              :                 .unwrap();
    3067              :             assert_eq!(incremental, non_incremental);
    3068              :         }
    3069              :     */
    3070              : 
    3071              :     /*
    3072              :     ///
    3073              :     /// Test list_rels() function, with branches and dropped relations
    3074              :     ///
    3075              :     #[test]
    3076              :     fn test_list_rels_drop() -> Result<()> {
    3077              :         let repo = RepoHarness::create("test_list_rels_drop")?.load();
    3078              :         let tline = create_empty_timeline(repo, TIMELINE_ID)?;
    3079              :         const TESTDB: u32 = 111;
    3080              : 
    3081              :         // Import initial dummy checkpoint record, otherwise the get_timeline() call
    3082              :         // after branching fails below
    3083              :         let mut writer = tline.begin_record(Lsn(0x10));
    3084              :         writer.put_checkpoint(ZERO_CHECKPOINT.clone())?;
    3085              :         writer.finish()?;
    3086              : 
    3087              :         // Create a relation on the timeline
    3088              :         let mut writer = tline.begin_record(Lsn(0x20));
    3089              :         writer.put_rel_page_image(TESTREL_A, 0, TEST_IMG("foo blk 0 at 2"))?;
    3090              :         writer.finish()?;
    3091              : 
    3092              :         let writer = tline.begin_record(Lsn(0x00));
    3093              :         writer.finish()?;
    3094              : 
    3095              :         // Check that list_rels() lists it after LSN 2, but no before it
    3096              :         assert!(!tline.list_rels(0, TESTDB, Lsn(0x10))?.contains(&TESTREL_A));
    3097              :         assert!(tline.list_rels(0, TESTDB, Lsn(0x20))?.contains(&TESTREL_A));
    3098              :         assert!(tline.list_rels(0, TESTDB, Lsn(0x30))?.contains(&TESTREL_A));
    3099              : 
    3100              :         // Create a branch, check that the relation is visible there
    3101              :         repo.branch_timeline(&tline, NEW_TIMELINE_ID, Lsn(0x30))?;
    3102              :         let newtline = match repo.get_timeline(NEW_TIMELINE_ID)?.local_timeline() {
    3103              :             Some(timeline) => timeline,
    3104              :             None => panic!("Should have a local timeline"),
    3105              :         };
    3106              :         let newtline = DatadirTimelineImpl::new(newtline);
    3107              :         assert!(newtline
    3108              :             .list_rels(0, TESTDB, Lsn(0x30))?
    3109              :             .contains(&TESTREL_A));
    3110              : 
    3111              :         // Drop it on the branch
    3112              :         let mut new_writer = newtline.begin_record(Lsn(0x40));
    3113              :         new_writer.drop_relation(TESTREL_A)?;
    3114              :         new_writer.finish()?;
    3115              : 
    3116              :         // Check that it's no longer listed on the branch after the point where it was dropped
    3117              :         assert!(newtline
    3118              :             .list_rels(0, TESTDB, Lsn(0x30))?
    3119              :             .contains(&TESTREL_A));
    3120              :         assert!(!newtline
    3121              :             .list_rels(0, TESTDB, Lsn(0x40))?
    3122              :             .contains(&TESTREL_A));
    3123              : 
    3124              :         // Run checkpoint and garbage collection and check that it's still not visible
    3125              :         newtline.checkpoint(CheckpointConfig::Forced)?;
    3126              :         repo.gc_iteration(Some(NEW_TIMELINE_ID), 0, true)?;
    3127              : 
    3128              :         assert!(!newtline
    3129              :             .list_rels(0, TESTDB, Lsn(0x40))?
    3130              :             .contains(&TESTREL_A));
    3131              : 
    3132              :         Ok(())
    3133              :     }
    3134              :      */
    3135              : 
    3136              :     /*
    3137              :     #[test]
    3138              :     fn test_read_beyond_eof() -> Result<()> {
    3139              :         let repo = RepoHarness::create("test_read_beyond_eof")?.load();
    3140              :         let tline = create_test_timeline(repo, TIMELINE_ID)?;
    3141              : 
    3142              :         make_some_layers(&tline, Lsn(0x20))?;
    3143              :         let mut writer = tline.begin_record(Lsn(0x60));
    3144              :         walingest.put_rel_page_image(
    3145              :             &mut writer,
    3146              :             TESTREL_A,
    3147              :             0,
    3148              :             TEST_IMG(&format!("foo blk 0 at {}", Lsn(0x60))),
    3149              :         )?;
    3150              :         writer.finish()?;
    3151              : 
    3152              :         // Test read before rel creation. Should error out.
    3153              :         assert!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x10), false).is_err());
    3154              : 
    3155              :         // Read block beyond end of relation at different points in time.
    3156              :         // These reads should fall into different delta, image, and in-memory layers.
    3157              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x20), false)?, ZERO_PAGE);
    3158              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x25), false)?, ZERO_PAGE);
    3159              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x30), false)?, ZERO_PAGE);
    3160              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x35), false)?, ZERO_PAGE);
    3161              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x40), false)?, ZERO_PAGE);
    3162              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x45), false)?, ZERO_PAGE);
    3163              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x50), false)?, ZERO_PAGE);
    3164              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x55), false)?, ZERO_PAGE);
    3165              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x60), false)?, ZERO_PAGE);
    3166              : 
    3167              :         // Test on an in-memory layer with no preceding layer
    3168              :         let mut writer = tline.begin_record(Lsn(0x70));
    3169              :         walingest.put_rel_page_image(
    3170              :             &mut writer,
    3171              :             TESTREL_B,
    3172              :             0,
    3173              :             TEST_IMG(&format!("foo blk 0 at {}", Lsn(0x70))),
    3174              :         )?;
    3175              :         writer.finish()?;
    3176              : 
    3177              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_B, 1, Lsn(0x70), false)?6, ZERO_PAGE);
    3178              : 
    3179              :         Ok(())
    3180              :     }
    3181              :      */
    3182              : }
        

Generated by: LCOV version 2.1-beta