LCOV - code coverage report
Current view: top level - pageserver/src - pgdatadir_mapping.rs (source / functions) Coverage Total Hit
Test: fabb29a6339542ee130cd1d32b534fafdc0be240.info Lines: 55.7 % 1335 743
Test Date: 2024-06-25 13:20:00 Functions: 38.6 % 184 71

            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 super::tenant::{PageReconstructError, Timeline};
      10              : use crate::context::RequestContext;
      11              : use crate::keyspace::{KeySpace, KeySpaceAccum};
      12              : use crate::span::debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id;
      13              : use crate::walrecord::NeonWalRecord;
      14              : use crate::{aux_file, repository::*};
      15              : use anyhow::{ensure, Context};
      16              : use bytes::{Buf, Bytes, BytesMut};
      17              : use enum_map::Enum;
      18              : use itertools::Itertools;
      19              : use pageserver_api::key::{
      20              :     dbdir_key_range, rel_block_to_key, rel_dir_to_key, rel_key_range, rel_size_to_key,
      21              :     relmap_file_key, 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              :     AUX_FILES_KEY, CHECKPOINT_KEY, CONTROLFILE_KEY, DBDIR_KEY, TWOPHASEDIR_KEY,
      24              : };
      25              : use pageserver_api::keyspace::SparseKeySpace;
      26              : use pageserver_api::models::AuxFilePolicy;
      27              : use pageserver_api::reltag::{BlockNumber, RelTag, SlruKind};
      28              : use postgres_ffi::relfile_utils::{FSM_FORKNUM, VISIBILITYMAP_FORKNUM};
      29              : use postgres_ffi::BLCKSZ;
      30              : use postgres_ffi::{Oid, RepOriginId, TimestampTz, TransactionId};
      31              : use serde::{Deserialize, Serialize};
      32              : use std::collections::{hash_map, HashMap, HashSet};
      33              : use std::ops::ControlFlow;
      34              : use std::ops::Range;
      35              : use strum::IntoEnumIterator;
      36              : use tokio_util::sync::CancellationToken;
      37              : use tracing::{debug, info, trace, warn};
      38              : use utils::bin_ser::DeserializeError;
      39              : use utils::pausable_failpoint;
      40              : use utils::vec_map::{VecMap, VecMapOrdering};
      41              : use utils::{bin_ser::BeSer, lsn::Lsn};
      42              : 
      43              : /// 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.
      44              : pub const MAX_AUX_FILE_DELTAS: usize = 1024;
      45              : 
      46              : /// Max number of aux-file-related delta layers. The compaction will create a new image layer once this threshold is reached.
      47              : pub const MAX_AUX_FILE_V2_DELTAS: usize = 64;
      48              : 
      49              : #[derive(Debug)]
      50              : pub enum LsnForTimestamp {
      51              :     /// Found commits both before and after the given timestamp
      52              :     Present(Lsn),
      53              : 
      54              :     /// Found no commits after the given timestamp, this means
      55              :     /// that the newest data in the branch is older than the given
      56              :     /// timestamp.
      57              :     ///
      58              :     /// All commits <= LSN happened before the given timestamp
      59              :     Future(Lsn),
      60              : 
      61              :     /// The queried timestamp is past our horizon we look back at (PITR)
      62              :     ///
      63              :     /// All commits > LSN happened after the given timestamp,
      64              :     /// but any commits < LSN might have happened before or after
      65              :     /// the given timestamp. We don't know because no data before
      66              :     /// the given lsn is available.
      67              :     Past(Lsn),
      68              : 
      69              :     /// We have found no commit with a timestamp,
      70              :     /// so we can't return anything meaningful.
      71              :     ///
      72              :     /// The associated LSN is the lower bound value we can safely
      73              :     /// create branches on, but no statement is made if it is
      74              :     /// older or newer than the timestamp.
      75              :     ///
      76              :     /// This variant can e.g. be returned right after a
      77              :     /// cluster import.
      78              :     NoData(Lsn),
      79              : }
      80              : 
      81            0 : #[derive(Debug, thiserror::Error)]
      82              : pub(crate) enum CalculateLogicalSizeError {
      83              :     #[error("cancelled")]
      84              :     Cancelled,
      85              : 
      86              :     /// Something went wrong while reading the metadata we use to calculate logical size
      87              :     /// Note that cancellation variants of `PageReconstructError` are transformed to [`Self::Cancelled`]
      88              :     /// in the `From` implementation for this variant.
      89              :     #[error(transparent)]
      90              :     PageRead(PageReconstructError),
      91              : 
      92              :     /// Something went wrong deserializing metadata that we read to calculate logical size
      93              :     #[error("decode error: {0}")]
      94              :     Decode(#[from] DeserializeError),
      95              : }
      96              : 
      97            0 : #[derive(Debug, thiserror::Error)]
      98              : pub(crate) enum CollectKeySpaceError {
      99              :     #[error(transparent)]
     100              :     Decode(#[from] DeserializeError),
     101              :     #[error(transparent)]
     102              :     PageRead(PageReconstructError),
     103              :     #[error("cancelled")]
     104              :     Cancelled,
     105              : }
     106              : 
     107              : impl From<PageReconstructError> for CollectKeySpaceError {
     108            0 :     fn from(err: PageReconstructError) -> Self {
     109            0 :         match err {
     110            0 :             PageReconstructError::Cancelled => Self::Cancelled,
     111            0 :             err => Self::PageRead(err),
     112              :         }
     113            0 :     }
     114              : }
     115              : 
     116              : impl From<PageReconstructError> for CalculateLogicalSizeError {
     117            0 :     fn from(pre: PageReconstructError) -> Self {
     118            0 :         match pre {
     119            0 :             PageReconstructError::Cancelled => Self::Cancelled,
     120            0 :             _ => Self::PageRead(pre),
     121              :         }
     122            0 :     }
     123              : }
     124              : 
     125            0 : #[derive(Debug, thiserror::Error)]
     126              : pub enum RelationError {
     127              :     #[error("Relation Already Exists")]
     128              :     AlreadyExists,
     129              :     #[error("invalid relnode")]
     130              :     InvalidRelnode,
     131              :     #[error(transparent)]
     132              :     Other(#[from] anyhow::Error),
     133              : }
     134              : 
     135              : ///
     136              : /// This impl provides all the functionality to store PostgreSQL relations, SLRUs,
     137              : /// and other special kinds of files, in a versioned key-value store. The
     138              : /// Timeline struct provides the key-value store.
     139              : ///
     140              : /// This is a separate impl, so that we can easily include all these functions in a Timeline
     141              : /// implementation, and might be moved into a separate struct later.
     142              : impl Timeline {
     143              :     /// Start ingesting a WAL record, or other atomic modification of
     144              :     /// the timeline.
     145              :     ///
     146              :     /// This provides a transaction-like interface to perform a bunch
     147              :     /// of modifications atomically.
     148              :     ///
     149              :     /// To ingest a WAL record, call begin_modification(lsn) to get a
     150              :     /// DatadirModification object. Use the functions in the object to
     151              :     /// modify the repository state, updating all the pages and metadata
     152              :     /// that the WAL record affects. When you're done, call commit() to
     153              :     /// commit the changes.
     154              :     ///
     155              :     /// Lsn stored in modification is advanced by `ingest_record` and
     156              :     /// is used by `commit()` to update `last_record_lsn`.
     157              :     ///
     158              :     /// Calling commit() will flush all the changes and reset the state,
     159              :     /// so the `DatadirModification` struct can be reused to perform the next modification.
     160              :     ///
     161              :     /// Note that any pending modifications you make through the
     162              :     /// modification object won't be visible to calls to the 'get' and list
     163              :     /// functions of the timeline until you finish! And if you update the
     164              :     /// same page twice, the last update wins.
     165              :     ///
     166       268363 :     pub fn begin_modification(&self, lsn: Lsn) -> DatadirModification
     167       268363 :     where
     168       268363 :         Self: Sized,
     169       268363 :     {
     170       268363 :         DatadirModification {
     171       268363 :             tline: self,
     172       268363 :             pending_lsns: Vec::new(),
     173       268363 :             pending_updates: HashMap::new(),
     174       268363 :             pending_deletions: Vec::new(),
     175       268363 :             pending_nblocks: 0,
     176       268363 :             pending_directory_entries: Vec::new(),
     177       268363 :             lsn,
     178       268363 :         }
     179       268363 :     }
     180              : 
     181              :     //------------------------------------------------------------------------------
     182              :     // Public GET functions
     183              :     //------------------------------------------------------------------------------
     184              : 
     185              :     /// Look up given page version.
     186        18384 :     pub(crate) async fn get_rel_page_at_lsn(
     187        18384 :         &self,
     188        18384 :         tag: RelTag,
     189        18384 :         blknum: BlockNumber,
     190        18384 :         version: Version<'_>,
     191        18384 :         ctx: &RequestContext,
     192        18384 :     ) -> Result<Bytes, PageReconstructError> {
     193        18384 :         if tag.relnode == 0 {
     194            0 :             return Err(PageReconstructError::Other(
     195            0 :                 RelationError::InvalidRelnode.into(),
     196            0 :             ));
     197        18384 :         }
     198              : 
     199        18384 :         let nblocks = self.get_rel_size(tag, version, ctx).await?;
     200        18384 :         if blknum >= nblocks {
     201            0 :             debug!(
     202            0 :                 "read beyond EOF at {} blk {} at {}, size is {}: returning all-zeros page",
     203            0 :                 tag,
     204            0 :                 blknum,
     205            0 :                 version.get_lsn(),
     206              :                 nblocks
     207              :             );
     208            0 :             return Ok(ZERO_PAGE.clone());
     209        18384 :         }
     210        18384 : 
     211        18384 :         let key = rel_block_to_key(tag, blknum);
     212        18384 :         version.get(self, key, ctx).await
     213        18384 :     }
     214              : 
     215              :     // Get size of a database in blocks
     216            0 :     pub(crate) async fn get_db_size(
     217            0 :         &self,
     218            0 :         spcnode: Oid,
     219            0 :         dbnode: Oid,
     220            0 :         version: Version<'_>,
     221            0 :         ctx: &RequestContext,
     222            0 :     ) -> Result<usize, PageReconstructError> {
     223            0 :         let mut total_blocks = 0;
     224              : 
     225            0 :         let rels = self.list_rels(spcnode, dbnode, version, ctx).await?;
     226              : 
     227            0 :         for rel in rels {
     228            0 :             let n_blocks = self.get_rel_size(rel, version, ctx).await?;
     229            0 :             total_blocks += n_blocks as usize;
     230              :         }
     231            0 :         Ok(total_blocks)
     232            0 :     }
     233              : 
     234              :     /// Get size of a relation file
     235        24434 :     pub(crate) async fn get_rel_size(
     236        24434 :         &self,
     237        24434 :         tag: RelTag,
     238        24434 :         version: Version<'_>,
     239        24434 :         ctx: &RequestContext,
     240        24434 :     ) -> Result<BlockNumber, PageReconstructError> {
     241        24434 :         if tag.relnode == 0 {
     242            0 :             return Err(PageReconstructError::Other(
     243            0 :                 RelationError::InvalidRelnode.into(),
     244            0 :             ));
     245        24434 :         }
     246              : 
     247        24434 :         if let Some(nblocks) = self.get_cached_rel_size(&tag, version.get_lsn()) {
     248        19294 :             return Ok(nblocks);
     249         5140 :         }
     250         5140 : 
     251         5140 :         if (tag.forknum == FSM_FORKNUM || tag.forknum == VISIBILITYMAP_FORKNUM)
     252            0 :             && !self.get_rel_exists(tag, version, ctx).await?
     253              :         {
     254              :             // FIXME: Postgres sometimes calls smgrcreate() to create
     255              :             // FSM, and smgrnblocks() on it immediately afterwards,
     256              :             // without extending it.  Tolerate that by claiming that
     257              :             // any non-existent FSM fork has size 0.
     258            0 :             return Ok(0);
     259         5140 :         }
     260         5140 : 
     261         5140 :         let key = rel_size_to_key(tag);
     262         5140 :         let mut buf = version.get(self, key, ctx).await?;
     263         5136 :         let nblocks = buf.get_u32_le();
     264         5136 : 
     265         5136 :         self.update_cached_rel_size(tag, version.get_lsn(), nblocks);
     266         5136 : 
     267         5136 :         Ok(nblocks)
     268        24434 :     }
     269              : 
     270              :     /// Does relation exist?
     271         6050 :     pub(crate) async fn get_rel_exists(
     272         6050 :         &self,
     273         6050 :         tag: RelTag,
     274         6050 :         version: Version<'_>,
     275         6050 :         ctx: &RequestContext,
     276         6050 :     ) -> Result<bool, PageReconstructError> {
     277         6050 :         if tag.relnode == 0 {
     278            0 :             return Err(PageReconstructError::Other(
     279            0 :                 RelationError::InvalidRelnode.into(),
     280            0 :             ));
     281         6050 :         }
     282              : 
     283              :         // first try to lookup relation in cache
     284         6050 :         if let Some(_nblocks) = self.get_cached_rel_size(&tag, version.get_lsn()) {
     285         6032 :             return Ok(true);
     286           18 :         }
     287           18 :         // fetch directory listing
     288           18 :         let key = rel_dir_to_key(tag.spcnode, tag.dbnode);
     289           18 :         let buf = version.get(self, key, ctx).await?;
     290              : 
     291           18 :         match RelDirectory::des(&buf).context("deserialization failure") {
     292           18 :             Ok(dir) => {
     293           18 :                 let exists = dir.rels.contains(&(tag.relnode, tag.forknum));
     294           18 :                 Ok(exists)
     295              :             }
     296            0 :             Err(e) => Err(PageReconstructError::from(e)),
     297              :         }
     298         6050 :     }
     299              : 
     300              :     /// Get a list of all existing relations in given tablespace and database.
     301              :     ///
     302              :     /// # Cancel-Safety
     303              :     ///
     304              :     /// This method is cancellation-safe.
     305            0 :     pub(crate) async fn list_rels(
     306            0 :         &self,
     307            0 :         spcnode: Oid,
     308            0 :         dbnode: Oid,
     309            0 :         version: Version<'_>,
     310            0 :         ctx: &RequestContext,
     311            0 :     ) -> Result<HashSet<RelTag>, PageReconstructError> {
     312            0 :         // fetch directory listing
     313            0 :         let key = rel_dir_to_key(spcnode, dbnode);
     314            0 :         let buf = version.get(self, key, ctx).await?;
     315              : 
     316            0 :         match RelDirectory::des(&buf).context("deserialization failure") {
     317            0 :             Ok(dir) => {
     318            0 :                 let rels: HashSet<RelTag> =
     319            0 :                     HashSet::from_iter(dir.rels.iter().map(|(relnode, forknum)| RelTag {
     320            0 :                         spcnode,
     321            0 :                         dbnode,
     322            0 :                         relnode: *relnode,
     323            0 :                         forknum: *forknum,
     324            0 :                     }));
     325            0 : 
     326            0 :                 Ok(rels)
     327              :             }
     328            0 :             Err(e) => Err(PageReconstructError::from(e)),
     329              :         }
     330            0 :     }
     331              : 
     332              :     /// Get the whole SLRU segment
     333            0 :     pub(crate) async fn get_slru_segment(
     334            0 :         &self,
     335            0 :         kind: SlruKind,
     336            0 :         segno: u32,
     337            0 :         lsn: Lsn,
     338            0 :         ctx: &RequestContext,
     339            0 :     ) -> Result<Bytes, PageReconstructError> {
     340            0 :         let n_blocks = self
     341            0 :             .get_slru_segment_size(kind, segno, Version::Lsn(lsn), ctx)
     342            0 :             .await?;
     343            0 :         let mut segment = BytesMut::with_capacity(n_blocks as usize * BLCKSZ as usize);
     344            0 :         for blkno in 0..n_blocks {
     345            0 :             let block = self
     346            0 :                 .get_slru_page_at_lsn(kind, segno, blkno, lsn, ctx)
     347            0 :                 .await?;
     348            0 :             segment.extend_from_slice(&block[..BLCKSZ as usize]);
     349              :         }
     350            0 :         Ok(segment.freeze())
     351            0 :     }
     352              : 
     353              :     /// Look up given SLRU page version.
     354            0 :     pub(crate) async fn get_slru_page_at_lsn(
     355            0 :         &self,
     356            0 :         kind: SlruKind,
     357            0 :         segno: u32,
     358            0 :         blknum: BlockNumber,
     359            0 :         lsn: Lsn,
     360            0 :         ctx: &RequestContext,
     361            0 :     ) -> Result<Bytes, PageReconstructError> {
     362            0 :         let key = slru_block_to_key(kind, segno, blknum);
     363            0 :         self.get(key, lsn, ctx).await
     364            0 :     }
     365              : 
     366              :     /// Get size of an SLRU segment
     367            0 :     pub(crate) async fn get_slru_segment_size(
     368            0 :         &self,
     369            0 :         kind: SlruKind,
     370            0 :         segno: u32,
     371            0 :         version: Version<'_>,
     372            0 :         ctx: &RequestContext,
     373            0 :     ) -> Result<BlockNumber, PageReconstructError> {
     374            0 :         let key = slru_segment_size_to_key(kind, segno);
     375            0 :         let mut buf = version.get(self, key, ctx).await?;
     376            0 :         Ok(buf.get_u32_le())
     377            0 :     }
     378              : 
     379              :     /// Get size of an SLRU segment
     380            0 :     pub(crate) async fn get_slru_segment_exists(
     381            0 :         &self,
     382            0 :         kind: SlruKind,
     383            0 :         segno: u32,
     384            0 :         version: Version<'_>,
     385            0 :         ctx: &RequestContext,
     386            0 :     ) -> Result<bool, PageReconstructError> {
     387            0 :         // fetch directory listing
     388            0 :         let key = slru_dir_to_key(kind);
     389            0 :         let buf = version.get(self, key, ctx).await?;
     390              : 
     391            0 :         match SlruSegmentDirectory::des(&buf).context("deserialization failure") {
     392            0 :             Ok(dir) => {
     393            0 :                 let exists = dir.segments.contains(&segno);
     394            0 :                 Ok(exists)
     395              :             }
     396            0 :             Err(e) => Err(PageReconstructError::from(e)),
     397              :         }
     398            0 :     }
     399              : 
     400              :     /// Locate LSN, such that all transactions that committed before
     401              :     /// 'search_timestamp' are visible, but nothing newer is.
     402              :     ///
     403              :     /// This is not exact. Commit timestamps are not guaranteed to be ordered,
     404              :     /// so it's not well defined which LSN you get if there were multiple commits
     405              :     /// "in flight" at that point in time.
     406              :     ///
     407            0 :     pub(crate) async fn find_lsn_for_timestamp(
     408            0 :         &self,
     409            0 :         search_timestamp: TimestampTz,
     410            0 :         cancel: &CancellationToken,
     411            0 :         ctx: &RequestContext,
     412            0 :     ) -> Result<LsnForTimestamp, PageReconstructError> {
     413              :         pausable_failpoint!("find-lsn-for-timestamp-pausable");
     414              : 
     415            0 :         let gc_cutoff_lsn_guard = self.get_latest_gc_cutoff_lsn();
     416            0 :         // We use this method to figure out the branching LSN for the new branch, but the
     417            0 :         // GC cutoff could be before the branching point and we cannot create a new branch
     418            0 :         // with LSN < `ancestor_lsn`. Thus, pick the maximum of these two to be
     419            0 :         // on the safe side.
     420            0 :         let min_lsn = std::cmp::max(*gc_cutoff_lsn_guard, self.get_ancestor_lsn());
     421            0 :         let max_lsn = self.get_last_record_lsn();
     422            0 : 
     423            0 :         // LSNs are always 8-byte aligned. low/mid/high represent the
     424            0 :         // LSN divided by 8.
     425            0 :         let mut low = min_lsn.0 / 8;
     426            0 :         let mut high = max_lsn.0 / 8 + 1;
     427            0 : 
     428            0 :         let mut found_smaller = false;
     429            0 :         let mut found_larger = false;
     430              : 
     431            0 :         while low < high {
     432            0 :             if cancel.is_cancelled() {
     433            0 :                 return Err(PageReconstructError::Cancelled);
     434            0 :             }
     435            0 :             // cannot overflow, high and low are both smaller than u64::MAX / 2
     436            0 :             let mid = (high + low) / 2;
     437              : 
     438            0 :             let cmp = self
     439            0 :                 .is_latest_commit_timestamp_ge_than(
     440            0 :                     search_timestamp,
     441            0 :                     Lsn(mid * 8),
     442            0 :                     &mut found_smaller,
     443            0 :                     &mut found_larger,
     444            0 :                     ctx,
     445            0 :                 )
     446            0 :                 .await?;
     447              : 
     448            0 :             if cmp {
     449            0 :                 high = mid;
     450            0 :             } else {
     451            0 :                 low = mid + 1;
     452            0 :             }
     453              :         }
     454              :         // If `found_smaller == true`, `low = t + 1` where `t` is the target LSN,
     455              :         // so the LSN of the last commit record before or at `search_timestamp`.
     456              :         // Remove one from `low` to get `t`.
     457              :         //
     458              :         // FIXME: it would be better to get the LSN of the previous commit.
     459              :         // Otherwise, if you restore to the returned LSN, the database will
     460              :         // include physical changes from later commits that will be marked
     461              :         // as aborted, and will need to be vacuumed away.
     462            0 :         let commit_lsn = Lsn((low - 1) * 8);
     463            0 :         match (found_smaller, found_larger) {
     464              :             (false, false) => {
     465              :                 // This can happen if no commit records have been processed yet, e.g.
     466              :                 // just after importing a cluster.
     467            0 :                 Ok(LsnForTimestamp::NoData(min_lsn))
     468              :             }
     469              :             (false, true) => {
     470              :                 // Didn't find any commit timestamps smaller than the request
     471            0 :                 Ok(LsnForTimestamp::Past(min_lsn))
     472              :             }
     473            0 :             (true, _) if commit_lsn < min_lsn => {
     474            0 :                 // the search above did set found_smaller to true but it never increased the lsn.
     475            0 :                 // Then, low is still the old min_lsn, and the subtraction above gave a value
     476            0 :                 // below the min_lsn. We should never do that.
     477            0 :                 Ok(LsnForTimestamp::Past(min_lsn))
     478              :             }
     479              :             (true, false) => {
     480              :                 // Only found commits with timestamps smaller than the request.
     481              :                 // It's still a valid case for branch creation, return it.
     482              :                 // And `update_gc_info()` ignores LSN for a `LsnForTimestamp::Future`
     483              :                 // case, anyway.
     484            0 :                 Ok(LsnForTimestamp::Future(commit_lsn))
     485              :             }
     486            0 :             (true, true) => Ok(LsnForTimestamp::Present(commit_lsn)),
     487              :         }
     488            0 :     }
     489              : 
     490              :     /// Subroutine of find_lsn_for_timestamp(). Returns true, if there are any
     491              :     /// commits that committed after 'search_timestamp', at LSN 'probe_lsn'.
     492              :     ///
     493              :     /// Additionally, sets 'found_smaller'/'found_Larger, if encounters any commits
     494              :     /// with a smaller/larger timestamp.
     495              :     ///
     496            0 :     pub(crate) async fn is_latest_commit_timestamp_ge_than(
     497            0 :         &self,
     498            0 :         search_timestamp: TimestampTz,
     499            0 :         probe_lsn: Lsn,
     500            0 :         found_smaller: &mut bool,
     501            0 :         found_larger: &mut bool,
     502            0 :         ctx: &RequestContext,
     503            0 :     ) -> Result<bool, PageReconstructError> {
     504            0 :         self.map_all_timestamps(probe_lsn, ctx, |timestamp| {
     505            0 :             if timestamp >= search_timestamp {
     506            0 :                 *found_larger = true;
     507            0 :                 return ControlFlow::Break(true);
     508            0 :             } else {
     509            0 :                 *found_smaller = true;
     510            0 :             }
     511            0 :             ControlFlow::Continue(())
     512            0 :         })
     513            0 :         .await
     514            0 :     }
     515              : 
     516              :     /// Obtain the possible timestamp range for the given lsn.
     517              :     ///
     518              :     /// If the lsn has no timestamps, returns None. returns `(min, max, median)` if it has timestamps.
     519            0 :     pub(crate) async fn get_timestamp_for_lsn(
     520            0 :         &self,
     521            0 :         probe_lsn: Lsn,
     522            0 :         ctx: &RequestContext,
     523            0 :     ) -> Result<Option<TimestampTz>, PageReconstructError> {
     524            0 :         let mut max: Option<TimestampTz> = None;
     525            0 :         self.map_all_timestamps(probe_lsn, ctx, |timestamp| {
     526            0 :             if let Some(max_prev) = max {
     527            0 :                 max = Some(max_prev.max(timestamp));
     528            0 :             } else {
     529            0 :                 max = Some(timestamp);
     530            0 :             }
     531            0 :             ControlFlow::Continue(())
     532            0 :         })
     533            0 :         .await?;
     534              : 
     535            0 :         Ok(max)
     536            0 :     }
     537              : 
     538              :     /// Runs the given function on all the timestamps for a given lsn
     539              :     ///
     540              :     /// The return value is either given by the closure, or set to the `Default`
     541              :     /// impl's output.
     542            0 :     async fn map_all_timestamps<T: Default>(
     543            0 :         &self,
     544            0 :         probe_lsn: Lsn,
     545            0 :         ctx: &RequestContext,
     546            0 :         mut f: impl FnMut(TimestampTz) -> ControlFlow<T>,
     547            0 :     ) -> Result<T, PageReconstructError> {
     548            0 :         for segno in self
     549            0 :             .list_slru_segments(SlruKind::Clog, Version::Lsn(probe_lsn), ctx)
     550            0 :             .await?
     551              :         {
     552            0 :             let nblocks = self
     553            0 :                 .get_slru_segment_size(SlruKind::Clog, segno, Version::Lsn(probe_lsn), ctx)
     554            0 :                 .await?;
     555            0 :             for blknum in (0..nblocks).rev() {
     556            0 :                 let clog_page = self
     557            0 :                     .get_slru_page_at_lsn(SlruKind::Clog, segno, blknum, probe_lsn, ctx)
     558            0 :                     .await?;
     559              : 
     560            0 :                 if clog_page.len() == BLCKSZ as usize + 8 {
     561            0 :                     let mut timestamp_bytes = [0u8; 8];
     562            0 :                     timestamp_bytes.copy_from_slice(&clog_page[BLCKSZ as usize..]);
     563            0 :                     let timestamp = TimestampTz::from_be_bytes(timestamp_bytes);
     564            0 : 
     565            0 :                     match f(timestamp) {
     566            0 :                         ControlFlow::Break(b) => return Ok(b),
     567            0 :                         ControlFlow::Continue(()) => (),
     568              :                     }
     569            0 :                 }
     570              :             }
     571              :         }
     572            0 :         Ok(Default::default())
     573            0 :     }
     574              : 
     575            0 :     pub(crate) async fn get_slru_keyspace(
     576            0 :         &self,
     577            0 :         version: Version<'_>,
     578            0 :         ctx: &RequestContext,
     579            0 :     ) -> Result<KeySpace, PageReconstructError> {
     580            0 :         let mut accum = KeySpaceAccum::new();
     581              : 
     582            0 :         for kind in SlruKind::iter() {
     583            0 :             let mut segments: Vec<u32> = self
     584            0 :                 .list_slru_segments(kind, version, ctx)
     585            0 :                 .await?
     586            0 :                 .into_iter()
     587            0 :                 .collect();
     588            0 :             segments.sort_unstable();
     589              : 
     590            0 :             for seg in segments {
     591            0 :                 let block_count = self.get_slru_segment_size(kind, seg, version, ctx).await?;
     592              : 
     593            0 :                 accum.add_range(
     594            0 :                     slru_block_to_key(kind, seg, 0)..slru_block_to_key(kind, seg, block_count),
     595            0 :                 );
     596              :             }
     597              :         }
     598              : 
     599            0 :         Ok(accum.to_keyspace())
     600            0 :     }
     601              : 
     602              :     /// Get a list of SLRU segments
     603            0 :     pub(crate) async fn list_slru_segments(
     604            0 :         &self,
     605            0 :         kind: SlruKind,
     606            0 :         version: Version<'_>,
     607            0 :         ctx: &RequestContext,
     608            0 :     ) -> Result<HashSet<u32>, PageReconstructError> {
     609            0 :         // fetch directory entry
     610            0 :         let key = slru_dir_to_key(kind);
     611              : 
     612            0 :         let buf = version.get(self, key, ctx).await?;
     613            0 :         match SlruSegmentDirectory::des(&buf).context("deserialization failure") {
     614            0 :             Ok(dir) => Ok(dir.segments),
     615            0 :             Err(e) => Err(PageReconstructError::from(e)),
     616              :         }
     617            0 :     }
     618              : 
     619            0 :     pub(crate) async fn get_relmap_file(
     620            0 :         &self,
     621            0 :         spcnode: Oid,
     622            0 :         dbnode: Oid,
     623            0 :         version: Version<'_>,
     624            0 :         ctx: &RequestContext,
     625            0 :     ) -> Result<Bytes, PageReconstructError> {
     626            0 :         let key = relmap_file_key(spcnode, dbnode);
     627              : 
     628            0 :         let buf = version.get(self, key, ctx).await?;
     629            0 :         Ok(buf)
     630            0 :     }
     631              : 
     632            0 :     pub(crate) async fn list_dbdirs(
     633            0 :         &self,
     634            0 :         lsn: Lsn,
     635            0 :         ctx: &RequestContext,
     636            0 :     ) -> Result<HashMap<(Oid, Oid), bool>, PageReconstructError> {
     637              :         // fetch directory entry
     638            0 :         let buf = self.get(DBDIR_KEY, lsn, ctx).await?;
     639              : 
     640            0 :         match DbDirectory::des(&buf).context("deserialization failure") {
     641            0 :             Ok(dir) => Ok(dir.dbdirs),
     642            0 :             Err(e) => Err(PageReconstructError::from(e)),
     643              :         }
     644            0 :     }
     645              : 
     646            0 :     pub(crate) async fn get_twophase_file(
     647            0 :         &self,
     648            0 :         xid: TransactionId,
     649            0 :         lsn: Lsn,
     650            0 :         ctx: &RequestContext,
     651            0 :     ) -> Result<Bytes, PageReconstructError> {
     652            0 :         let key = twophase_file_key(xid);
     653            0 :         let buf = self.get(key, lsn, ctx).await?;
     654            0 :         Ok(buf)
     655            0 :     }
     656              : 
     657            0 :     pub(crate) async fn list_twophase_files(
     658            0 :         &self,
     659            0 :         lsn: Lsn,
     660            0 :         ctx: &RequestContext,
     661            0 :     ) -> Result<HashSet<TransactionId>, PageReconstructError> {
     662              :         // fetch directory entry
     663            0 :         let buf = self.get(TWOPHASEDIR_KEY, lsn, ctx).await?;
     664              : 
     665            0 :         match TwoPhaseDirectory::des(&buf).context("deserialization failure") {
     666            0 :             Ok(dir) => Ok(dir.xids),
     667            0 :             Err(e) => Err(PageReconstructError::from(e)),
     668              :         }
     669            0 :     }
     670              : 
     671            0 :     pub(crate) async fn get_control_file(
     672            0 :         &self,
     673            0 :         lsn: Lsn,
     674            0 :         ctx: &RequestContext,
     675            0 :     ) -> Result<Bytes, PageReconstructError> {
     676            0 :         self.get(CONTROLFILE_KEY, lsn, ctx).await
     677            0 :     }
     678              : 
     679           12 :     pub(crate) async fn get_checkpoint(
     680           12 :         &self,
     681           12 :         lsn: Lsn,
     682           12 :         ctx: &RequestContext,
     683           12 :     ) -> Result<Bytes, PageReconstructError> {
     684           12 :         self.get(CHECKPOINT_KEY, lsn, ctx).await
     685           12 :     }
     686              : 
     687           28 :     async fn list_aux_files_v1(
     688           28 :         &self,
     689           28 :         lsn: Lsn,
     690           28 :         ctx: &RequestContext,
     691           28 :     ) -> Result<HashMap<String, Bytes>, PageReconstructError> {
     692           28 :         match self.get(AUX_FILES_KEY, lsn, ctx).await {
     693           22 :             Ok(buf) => match AuxFilesDirectory::des(&buf).context("deserialization failure") {
     694           22 :                 Ok(dir) => Ok(dir.files),
     695            0 :                 Err(e) => Err(PageReconstructError::from(e)),
     696              :             },
     697            6 :             Err(e) => {
     698            6 :                 // This is expected: historical databases do not have the key.
     699            6 :                 debug!("Failed to get info about AUX files: {}", e);
     700            6 :                 Ok(HashMap::new())
     701              :             }
     702              :         }
     703           28 :     }
     704              : 
     705           12 :     async fn list_aux_files_v2(
     706           12 :         &self,
     707           12 :         lsn: Lsn,
     708           12 :         ctx: &RequestContext,
     709           12 :     ) -> Result<HashMap<String, Bytes>, PageReconstructError> {
     710           12 :         let kv = self
     711           12 :             .scan(KeySpace::single(Key::metadata_aux_key_range()), lsn, ctx)
     712            0 :             .await
     713           12 :             .context("scan")?;
     714           12 :         let mut result = HashMap::new();
     715           12 :         let mut sz = 0;
     716           30 :         for (_, v) in kv {
     717           18 :             let v = v.context("get value")?;
     718           18 :             let v = aux_file::decode_file_value_bytes(&v).context("value decode")?;
     719           36 :             for (fname, content) in v {
     720           18 :                 sz += fname.len();
     721           18 :                 sz += content.len();
     722           18 :                 result.insert(fname, content);
     723           18 :             }
     724              :         }
     725           12 :         self.aux_file_size_estimator.on_initial(sz);
     726           12 :         Ok(result)
     727           12 :     }
     728              : 
     729            0 :     pub(crate) async fn trigger_aux_file_size_computation(
     730            0 :         &self,
     731            0 :         lsn: Lsn,
     732            0 :         ctx: &RequestContext,
     733            0 :     ) -> Result<(), PageReconstructError> {
     734            0 :         let current_policy = self.last_aux_file_policy.load();
     735            0 :         if let Some(AuxFilePolicy::V2) | Some(AuxFilePolicy::CrossValidation) = current_policy {
     736            0 :             self.list_aux_files_v2(lsn, ctx).await?;
     737            0 :         }
     738            0 :         Ok(())
     739            0 :     }
     740              : 
     741           26 :     pub(crate) async fn list_aux_files(
     742           26 :         &self,
     743           26 :         lsn: Lsn,
     744           26 :         ctx: &RequestContext,
     745           26 :     ) -> Result<HashMap<String, Bytes>, PageReconstructError> {
     746           26 :         let current_policy = self.last_aux_file_policy.load();
     747           26 :         match current_policy {
     748           14 :             Some(AuxFilePolicy::V1) | None => self.list_aux_files_v1(lsn, ctx).await,
     749           10 :             Some(AuxFilePolicy::V2) => self.list_aux_files_v2(lsn, ctx).await,
     750              :             Some(AuxFilePolicy::CrossValidation) => {
     751            2 :                 let v1_result = self.list_aux_files_v1(lsn, ctx).await;
     752            2 :                 let v2_result = self.list_aux_files_v2(lsn, ctx).await;
     753            2 :                 match (v1_result, v2_result) {
     754            2 :                     (Ok(v1), Ok(v2)) => {
     755            2 :                         if v1 != v2 {
     756            0 :                             tracing::error!(
     757            0 :                                 "unmatched aux file v1 v2 result:\nv1 {v1:?}\nv2 {v2:?}"
     758              :                             );
     759            0 :                             return Err(PageReconstructError::Other(anyhow::anyhow!(
     760            0 :                                 "unmatched aux file v1 v2 result"
     761            0 :                             )));
     762            2 :                         }
     763            2 :                         Ok(v1)
     764              :                     }
     765            0 :                     (Ok(_), Err(v2)) => {
     766            0 :                         tracing::error!("aux file v1 returns Ok while aux file v2 returns an err");
     767            0 :                         Err(v2)
     768              :                     }
     769            0 :                     (Err(v1), Ok(_)) => {
     770            0 :                         tracing::error!("aux file v2 returns Ok while aux file v1 returns an err");
     771            0 :                         Err(v1)
     772              :                     }
     773            0 :                     (Err(_), Err(v2)) => Err(v2),
     774              :                 }
     775              :             }
     776              :         }
     777           26 :     }
     778              : 
     779            0 :     pub(crate) async fn get_replorigins(
     780            0 :         &self,
     781            0 :         lsn: Lsn,
     782            0 :         ctx: &RequestContext,
     783            0 :     ) -> Result<HashMap<RepOriginId, Lsn>, PageReconstructError> {
     784            0 :         let kv = self
     785            0 :             .scan(KeySpace::single(repl_origin_key_range()), lsn, ctx)
     786            0 :             .await
     787            0 :             .context("scan")?;
     788            0 :         let mut result = HashMap::new();
     789            0 :         for (k, v) in kv {
     790            0 :             let v = v.context("get value")?;
     791            0 :             let origin_id = k.field6 as RepOriginId;
     792            0 :             let origin_lsn = Lsn::des(&v).unwrap();
     793            0 :             if origin_lsn != Lsn::INVALID {
     794            0 :                 result.insert(origin_id, origin_lsn);
     795            0 :             }
     796              :         }
     797            0 :         Ok(result)
     798            0 :     }
     799              : 
     800              :     /// Does the same as get_current_logical_size but counted on demand.
     801              :     /// Used to initialize the logical size tracking on startup.
     802              :     ///
     803              :     /// Only relation blocks are counted currently. That excludes metadata,
     804              :     /// SLRUs, twophase files etc.
     805              :     ///
     806              :     /// # Cancel-Safety
     807              :     ///
     808              :     /// This method is cancellation-safe.
     809            0 :     pub(crate) async fn get_current_logical_size_non_incremental(
     810            0 :         &self,
     811            0 :         lsn: Lsn,
     812            0 :         ctx: &RequestContext,
     813            0 :     ) -> Result<u64, CalculateLogicalSizeError> {
     814            0 :         debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
     815              : 
     816              :         // Fetch list of database dirs and iterate them
     817            0 :         let buf = self.get(DBDIR_KEY, lsn, ctx).await?;
     818            0 :         let dbdir = DbDirectory::des(&buf)?;
     819              : 
     820            0 :         let mut total_size: u64 = 0;
     821            0 :         for (spcnode, dbnode) in dbdir.dbdirs.keys() {
     822            0 :             for rel in self
     823            0 :                 .list_rels(*spcnode, *dbnode, Version::Lsn(lsn), ctx)
     824            0 :                 .await?
     825              :             {
     826            0 :                 if self.cancel.is_cancelled() {
     827            0 :                     return Err(CalculateLogicalSizeError::Cancelled);
     828            0 :                 }
     829            0 :                 let relsize_key = rel_size_to_key(rel);
     830            0 :                 let mut buf = self.get(relsize_key, lsn, ctx).await?;
     831            0 :                 let relsize = buf.get_u32_le();
     832            0 : 
     833            0 :                 total_size += relsize as u64;
     834              :             }
     835              :         }
     836            0 :         Ok(total_size * BLCKSZ as u64)
     837            0 :     }
     838              : 
     839              :     ///
     840              :     /// Get a KeySpace that covers all the Keys that are in use at the given LSN.
     841              :     /// Anything that's not listed maybe removed from the underlying storage (from
     842              :     /// that LSN forwards).
     843              :     ///
     844              :     /// The return value is (dense keyspace, sparse keyspace).
     845          259 :     pub(crate) async fn collect_keyspace(
     846          259 :         &self,
     847          259 :         lsn: Lsn,
     848          259 :         ctx: &RequestContext,
     849          259 :     ) -> Result<(KeySpace, SparseKeySpace), CollectKeySpaceError> {
     850          259 :         // Iterate through key ranges, greedily packing them into partitions
     851          259 :         let mut result = KeySpaceAccum::new();
     852          259 : 
     853          259 :         // The dbdir metadata always exists
     854          259 :         result.add_key(DBDIR_KEY);
     855              : 
     856              :         // Fetch list of database dirs and iterate them
     857         2440 :         let buf = self.get(DBDIR_KEY, lsn, ctx).await?;
     858          259 :         let dbdir = DbDirectory::des(&buf)?;
     859              : 
     860          259 :         let mut dbs: Vec<(Oid, Oid)> = dbdir.dbdirs.keys().cloned().collect();
     861          259 :         dbs.sort_unstable();
     862          259 :         for (spcnode, dbnode) in dbs {
     863            0 :             result.add_key(relmap_file_key(spcnode, dbnode));
     864            0 :             result.add_key(rel_dir_to_key(spcnode, dbnode));
     865              : 
     866            0 :             let mut rels: Vec<RelTag> = self
     867            0 :                 .list_rels(spcnode, dbnode, Version::Lsn(lsn), ctx)
     868            0 :                 .await?
     869            0 :                 .into_iter()
     870            0 :                 .collect();
     871            0 :             rels.sort_unstable();
     872            0 :             for rel in rels {
     873            0 :                 let relsize_key = rel_size_to_key(rel);
     874            0 :                 let mut buf = self.get(relsize_key, lsn, ctx).await?;
     875            0 :                 let relsize = buf.get_u32_le();
     876            0 : 
     877            0 :                 result.add_range(rel_block_to_key(rel, 0)..rel_block_to_key(rel, relsize));
     878            0 :                 result.add_key(relsize_key);
     879              :             }
     880              :         }
     881              : 
     882              :         // Iterate SLRUs next
     883          777 :         for kind in [
     884          259 :             SlruKind::Clog,
     885          259 :             SlruKind::MultiXactMembers,
     886          259 :             SlruKind::MultiXactOffsets,
     887              :         ] {
     888          777 :             let slrudir_key = slru_dir_to_key(kind);
     889          777 :             result.add_key(slrudir_key);
     890         8384 :             let buf = self.get(slrudir_key, lsn, ctx).await?;
     891          777 :             let dir = SlruSegmentDirectory::des(&buf)?;
     892          777 :             let mut segments: Vec<u32> = dir.segments.iter().cloned().collect();
     893          777 :             segments.sort_unstable();
     894          777 :             for segno in segments {
     895            0 :                 let segsize_key = slru_segment_size_to_key(kind, segno);
     896            0 :                 let mut buf = self.get(segsize_key, lsn, ctx).await?;
     897            0 :                 let segsize = buf.get_u32_le();
     898            0 : 
     899            0 :                 result.add_range(
     900            0 :                     slru_block_to_key(kind, segno, 0)..slru_block_to_key(kind, segno, segsize),
     901            0 :                 );
     902            0 :                 result.add_key(segsize_key);
     903              :             }
     904              :         }
     905              : 
     906              :         // Then pg_twophase
     907          259 :         result.add_key(TWOPHASEDIR_KEY);
     908         3135 :         let buf = self.get(TWOPHASEDIR_KEY, lsn, ctx).await?;
     909          259 :         let twophase_dir = TwoPhaseDirectory::des(&buf)?;
     910          259 :         let mut xids: Vec<TransactionId> = twophase_dir.xids.iter().cloned().collect();
     911          259 :         xids.sort_unstable();
     912          259 :         for xid in xids {
     913            0 :             result.add_key(twophase_file_key(xid));
     914            0 :         }
     915              : 
     916          259 :         result.add_key(CONTROLFILE_KEY);
     917          259 :         result.add_key(CHECKPOINT_KEY);
     918          259 :         if self.get(AUX_FILES_KEY, lsn, ctx).await.is_ok() {
     919          155 :             result.add_key(AUX_FILES_KEY);
     920          155 :         }
     921              : 
     922              :         #[cfg(test)]
     923              :         {
     924          259 :             let guard = self.extra_test_dense_keyspace.load();
     925          259 :             for kr in &guard.ranges {
     926            0 :                 result.add_range(kr.clone());
     927            0 :             }
     928              :         }
     929              : 
     930          259 :         Ok((
     931          259 :             result.to_keyspace(),
     932          259 :             /* AUX sparse key space */
     933          259 :             SparseKeySpace(KeySpace {
     934          259 :                 ranges: vec![repl_origin_key_range(), Key::metadata_aux_key_range()],
     935          259 :             }),
     936          259 :         ))
     937          259 :     }
     938              : 
     939              :     /// Get cached size of relation if it not updated after specified LSN
     940       448540 :     pub fn get_cached_rel_size(&self, tag: &RelTag, lsn: Lsn) -> Option<BlockNumber> {
     941       448540 :         let rel_size_cache = self.rel_size_cache.read().unwrap();
     942       448540 :         if let Some((cached_lsn, nblocks)) = rel_size_cache.map.get(tag) {
     943       448518 :             if lsn >= *cached_lsn {
     944       443372 :                 return Some(*nblocks);
     945         5146 :             }
     946           22 :         }
     947         5168 :         None
     948       448540 :     }
     949              : 
     950              :     /// Update cached relation size if there is no more recent update
     951         5136 :     pub fn update_cached_rel_size(&self, tag: RelTag, lsn: Lsn, nblocks: BlockNumber) {
     952         5136 :         let mut rel_size_cache = self.rel_size_cache.write().unwrap();
     953         5136 : 
     954         5136 :         if lsn < rel_size_cache.complete_as_of {
     955              :             // Do not cache old values. It's safe to cache the size on read, as long as
     956              :             // the read was at an LSN since we started the WAL ingestion. Reasoning: we
     957              :             // never evict values from the cache, so if the relation size changed after
     958              :             // 'lsn', the new value is already in the cache.
     959            0 :             return;
     960         5136 :         }
     961         5136 : 
     962         5136 :         match rel_size_cache.map.entry(tag) {
     963         5136 :             hash_map::Entry::Occupied(mut entry) => {
     964         5136 :                 let cached_lsn = entry.get_mut();
     965         5136 :                 if lsn >= cached_lsn.0 {
     966            0 :                     *cached_lsn = (lsn, nblocks);
     967         5136 :                 }
     968              :             }
     969            0 :             hash_map::Entry::Vacant(entry) => {
     970            0 :                 entry.insert((lsn, nblocks));
     971            0 :             }
     972              :         }
     973         5136 :     }
     974              : 
     975              :     /// Store cached relation size
     976       288732 :     pub fn set_cached_rel_size(&self, tag: RelTag, lsn: Lsn, nblocks: BlockNumber) {
     977       288732 :         let mut rel_size_cache = self.rel_size_cache.write().unwrap();
     978       288732 :         rel_size_cache.map.insert(tag, (lsn, nblocks));
     979       288732 :     }
     980              : 
     981              :     /// Remove cached relation size
     982            2 :     pub fn remove_cached_rel_size(&self, tag: &RelTag) {
     983            2 :         let mut rel_size_cache = self.rel_size_cache.write().unwrap();
     984            2 :         rel_size_cache.map.remove(tag);
     985            2 :     }
     986              : }
     987              : 
     988              : /// DatadirModification represents an operation to ingest an atomic set of
     989              : /// updates to the repository. It is created by the 'begin_record'
     990              : /// function. It is called for each WAL record, so that all the modifications
     991              : /// by a one WAL record appear atomic.
     992              : pub struct DatadirModification<'a> {
     993              :     /// The timeline this modification applies to. You can access this to
     994              :     /// read the state, but note that any pending updates are *not* reflected
     995              :     /// in the state in 'tline' yet.
     996              :     pub tline: &'a Timeline,
     997              : 
     998              :     /// Current LSN of the modification
     999              :     lsn: Lsn,
    1000              : 
    1001              :     // The modifications are not applied directly to the underlying key-value store.
    1002              :     // The put-functions add the modifications here, and they are flushed to the
    1003              :     // underlying key-value store by the 'finish' function.
    1004              :     pending_lsns: Vec<Lsn>,
    1005              :     pending_updates: HashMap<Key, Vec<(Lsn, Value)>>,
    1006              :     pending_deletions: Vec<(Range<Key>, Lsn)>,
    1007              :     pending_nblocks: i64,
    1008              : 
    1009              :     /// For special "directory" keys that store key-value maps, track the size of the map
    1010              :     /// if it was updated in this modification.
    1011              :     pending_directory_entries: Vec<(DirectoryKind, usize)>,
    1012              : }
    1013              : 
    1014              : impl<'a> DatadirModification<'a> {
    1015              :     /// Get the current lsn
    1016       418056 :     pub(crate) fn get_lsn(&self) -> Lsn {
    1017       418056 :         self.lsn
    1018       418056 :     }
    1019              : 
    1020              :     /// Set the current lsn
    1021       145858 :     pub(crate) fn set_lsn(&mut self, lsn: Lsn) -> anyhow::Result<()> {
    1022       145858 :         ensure!(
    1023       145858 :             lsn >= self.lsn,
    1024            0 :             "setting an older lsn {} than {} is not allowed",
    1025              :             lsn,
    1026              :             self.lsn
    1027              :         );
    1028       145858 :         if lsn > self.lsn {
    1029       145858 :             self.pending_lsns.push(self.lsn);
    1030       145858 :             self.lsn = lsn;
    1031       145858 :         }
    1032       145858 :         Ok(())
    1033       145858 :     }
    1034              : 
    1035              :     /// Initialize a completely new repository.
    1036              :     ///
    1037              :     /// This inserts the directory metadata entries that are assumed to
    1038              :     /// always exist.
    1039          145 :     pub fn init_empty(&mut self) -> anyhow::Result<()> {
    1040          145 :         let buf = DbDirectory::ser(&DbDirectory {
    1041          145 :             dbdirs: HashMap::new(),
    1042          145 :         })?;
    1043          145 :         self.pending_directory_entries.push((DirectoryKind::Db, 0));
    1044          145 :         self.put(DBDIR_KEY, Value::Image(buf.into()));
    1045          145 : 
    1046          145 :         // Create AuxFilesDirectory
    1047          145 :         self.init_aux_dir()?;
    1048              : 
    1049          145 :         let buf = TwoPhaseDirectory::ser(&TwoPhaseDirectory {
    1050          145 :             xids: HashSet::new(),
    1051          145 :         })?;
    1052          145 :         self.pending_directory_entries
    1053          145 :             .push((DirectoryKind::TwoPhase, 0));
    1054          145 :         self.put(TWOPHASEDIR_KEY, Value::Image(buf.into()));
    1055              : 
    1056          145 :         let buf: Bytes = SlruSegmentDirectory::ser(&SlruSegmentDirectory::default())?.into();
    1057          145 :         let empty_dir = Value::Image(buf);
    1058          145 :         self.put(slru_dir_to_key(SlruKind::Clog), empty_dir.clone());
    1059          145 :         self.pending_directory_entries
    1060          145 :             .push((DirectoryKind::SlruSegment(SlruKind::Clog), 0));
    1061          145 :         self.put(
    1062          145 :             slru_dir_to_key(SlruKind::MultiXactMembers),
    1063          145 :             empty_dir.clone(),
    1064          145 :         );
    1065          145 :         self.pending_directory_entries
    1066          145 :             .push((DirectoryKind::SlruSegment(SlruKind::Clog), 0));
    1067          145 :         self.put(slru_dir_to_key(SlruKind::MultiXactOffsets), empty_dir);
    1068          145 :         self.pending_directory_entries
    1069          145 :             .push((DirectoryKind::SlruSegment(SlruKind::MultiXactOffsets), 0));
    1070          145 : 
    1071          145 :         Ok(())
    1072          145 :     }
    1073              : 
    1074              :     #[cfg(test)]
    1075          143 :     pub fn init_empty_test_timeline(&mut self) -> anyhow::Result<()> {
    1076          143 :         self.init_empty()?;
    1077          143 :         self.put_control_file(bytes::Bytes::from_static(
    1078          143 :             b"control_file contents do not matter",
    1079          143 :         ))
    1080          143 :         .context("put_control_file")?;
    1081          143 :         self.put_checkpoint(bytes::Bytes::from_static(
    1082          143 :             b"checkpoint_file contents do not matter",
    1083          143 :         ))
    1084          143 :         .context("put_checkpoint_file")?;
    1085          143 :         Ok(())
    1086          143 :     }
    1087              : 
    1088              :     /// Put a new page version that can be constructed from a WAL record
    1089              :     ///
    1090              :     /// NOTE: this will *not* implicitly extend the relation, if the page is beyond the
    1091              :     /// current end-of-file. It's up to the caller to check that the relation size
    1092              :     /// matches the blocks inserted!
    1093       145630 :     pub fn put_rel_wal_record(
    1094       145630 :         &mut self,
    1095       145630 :         rel: RelTag,
    1096       145630 :         blknum: BlockNumber,
    1097       145630 :         rec: NeonWalRecord,
    1098       145630 :     ) -> anyhow::Result<()> {
    1099       145630 :         anyhow::ensure!(rel.relnode != 0, RelationError::InvalidRelnode);
    1100       145630 :         self.put(rel_block_to_key(rel, blknum), Value::WalRecord(rec));
    1101       145630 :         Ok(())
    1102       145630 :     }
    1103              : 
    1104              :     // Same, but for an SLRU.
    1105            8 :     pub fn put_slru_wal_record(
    1106            8 :         &mut self,
    1107            8 :         kind: SlruKind,
    1108            8 :         segno: u32,
    1109            8 :         blknum: BlockNumber,
    1110            8 :         rec: NeonWalRecord,
    1111            8 :     ) -> anyhow::Result<()> {
    1112            8 :         self.put(
    1113            8 :             slru_block_to_key(kind, segno, blknum),
    1114            8 :             Value::WalRecord(rec),
    1115            8 :         );
    1116            8 :         Ok(())
    1117            8 :     }
    1118              : 
    1119              :     /// Like put_wal_record, but with ready-made image of the page.
    1120       280864 :     pub fn put_rel_page_image(
    1121       280864 :         &mut self,
    1122       280864 :         rel: RelTag,
    1123       280864 :         blknum: BlockNumber,
    1124       280864 :         img: Bytes,
    1125       280864 :     ) -> anyhow::Result<()> {
    1126       280864 :         anyhow::ensure!(rel.relnode != 0, RelationError::InvalidRelnode);
    1127       280864 :         self.put(rel_block_to_key(rel, blknum), Value::Image(img));
    1128       280864 :         Ok(())
    1129       280864 :     }
    1130              : 
    1131            6 :     pub fn put_slru_page_image(
    1132            6 :         &mut self,
    1133            6 :         kind: SlruKind,
    1134            6 :         segno: u32,
    1135            6 :         blknum: BlockNumber,
    1136            6 :         img: Bytes,
    1137            6 :     ) -> anyhow::Result<()> {
    1138            6 :         self.put(slru_block_to_key(kind, segno, blknum), Value::Image(img));
    1139            6 :         Ok(())
    1140            6 :     }
    1141              : 
    1142              :     /// Store a relmapper file (pg_filenode.map) in the repository
    1143           16 :     pub async fn put_relmap_file(
    1144           16 :         &mut self,
    1145           16 :         spcnode: Oid,
    1146           16 :         dbnode: Oid,
    1147           16 :         img: Bytes,
    1148           16 :         ctx: &RequestContext,
    1149           16 :     ) -> anyhow::Result<()> {
    1150              :         // Add it to the directory (if it doesn't exist already)
    1151           16 :         let buf = self.get(DBDIR_KEY, ctx).await?;
    1152           16 :         let mut dbdir = DbDirectory::des(&buf)?;
    1153              : 
    1154           16 :         let r = dbdir.dbdirs.insert((spcnode, dbnode), true);
    1155           16 :         if r.is_none() || r == Some(false) {
    1156              :             // The dbdir entry didn't exist, or it contained a
    1157              :             // 'false'. The 'insert' call already updated it with
    1158              :             // 'true', now write the updated 'dbdirs' map back.
    1159           16 :             let buf = DbDirectory::ser(&dbdir)?;
    1160           16 :             self.put(DBDIR_KEY, Value::Image(buf.into()));
    1161           16 : 
    1162           16 :             // Create AuxFilesDirectory as well
    1163           16 :             self.init_aux_dir()?;
    1164            0 :         }
    1165           16 :         if r.is_none() {
    1166            8 :             // Create RelDirectory
    1167            8 :             let buf = RelDirectory::ser(&RelDirectory {
    1168            8 :                 rels: HashSet::new(),
    1169            8 :             })?;
    1170            8 :             self.pending_directory_entries.push((DirectoryKind::Rel, 0));
    1171            8 :             self.put(
    1172            8 :                 rel_dir_to_key(spcnode, dbnode),
    1173            8 :                 Value::Image(Bytes::from(buf)),
    1174            8 :             );
    1175            8 :         }
    1176              : 
    1177           16 :         self.put(relmap_file_key(spcnode, dbnode), Value::Image(img));
    1178           16 :         Ok(())
    1179           16 :     }
    1180              : 
    1181            0 :     pub async fn put_twophase_file(
    1182            0 :         &mut self,
    1183            0 :         xid: TransactionId,
    1184            0 :         img: Bytes,
    1185            0 :         ctx: &RequestContext,
    1186            0 :     ) -> anyhow::Result<()> {
    1187              :         // Add it to the directory entry
    1188            0 :         let buf = self.get(TWOPHASEDIR_KEY, ctx).await?;
    1189            0 :         let mut dir = TwoPhaseDirectory::des(&buf)?;
    1190            0 :         if !dir.xids.insert(xid) {
    1191            0 :             anyhow::bail!("twophase file for xid {} already exists", xid);
    1192            0 :         }
    1193            0 :         self.pending_directory_entries
    1194            0 :             .push((DirectoryKind::TwoPhase, dir.xids.len()));
    1195            0 :         self.put(
    1196            0 :             TWOPHASEDIR_KEY,
    1197            0 :             Value::Image(Bytes::from(TwoPhaseDirectory::ser(&dir)?)),
    1198              :         );
    1199              : 
    1200            0 :         self.put(twophase_file_key(xid), Value::Image(img));
    1201            0 :         Ok(())
    1202            0 :     }
    1203              : 
    1204            0 :     pub async fn set_replorigin(
    1205            0 :         &mut self,
    1206            0 :         origin_id: RepOriginId,
    1207            0 :         origin_lsn: Lsn,
    1208            0 :     ) -> anyhow::Result<()> {
    1209            0 :         let key = repl_origin_key(origin_id);
    1210            0 :         self.put(key, Value::Image(origin_lsn.ser().unwrap().into()));
    1211            0 :         Ok(())
    1212            0 :     }
    1213              : 
    1214            0 :     pub async fn drop_replorigin(&mut self, origin_id: RepOriginId) -> anyhow::Result<()> {
    1215            0 :         self.set_replorigin(origin_id, Lsn::INVALID).await
    1216            0 :     }
    1217              : 
    1218          145 :     pub fn put_control_file(&mut self, img: Bytes) -> anyhow::Result<()> {
    1219          145 :         self.put(CONTROLFILE_KEY, Value::Image(img));
    1220          145 :         Ok(())
    1221          145 :     }
    1222              : 
    1223          159 :     pub fn put_checkpoint(&mut self, img: Bytes) -> anyhow::Result<()> {
    1224          159 :         self.put(CHECKPOINT_KEY, Value::Image(img));
    1225          159 :         Ok(())
    1226          159 :     }
    1227              : 
    1228            0 :     pub async fn drop_dbdir(
    1229            0 :         &mut self,
    1230            0 :         spcnode: Oid,
    1231            0 :         dbnode: Oid,
    1232            0 :         ctx: &RequestContext,
    1233            0 :     ) -> anyhow::Result<()> {
    1234            0 :         let total_blocks = self
    1235            0 :             .tline
    1236            0 :             .get_db_size(spcnode, dbnode, Version::Modified(self), ctx)
    1237            0 :             .await?;
    1238              : 
    1239              :         // Remove entry from dbdir
    1240            0 :         let buf = self.get(DBDIR_KEY, ctx).await?;
    1241            0 :         let mut dir = DbDirectory::des(&buf)?;
    1242            0 :         if dir.dbdirs.remove(&(spcnode, dbnode)).is_some() {
    1243            0 :             let buf = DbDirectory::ser(&dir)?;
    1244            0 :             self.pending_directory_entries
    1245            0 :                 .push((DirectoryKind::Db, dir.dbdirs.len()));
    1246            0 :             self.put(DBDIR_KEY, Value::Image(buf.into()));
    1247              :         } else {
    1248            0 :             warn!(
    1249            0 :                 "dropped dbdir for spcnode {} dbnode {} did not exist in db directory",
    1250              :                 spcnode, dbnode
    1251              :             );
    1252              :         }
    1253              : 
    1254              :         // Update logical database size.
    1255            0 :         self.pending_nblocks -= total_blocks as i64;
    1256            0 : 
    1257            0 :         // Delete all relations and metadata files for the spcnode/dnode
    1258            0 :         self.delete(dbdir_key_range(spcnode, dbnode));
    1259            0 :         Ok(())
    1260            0 :     }
    1261              : 
    1262              :     /// Create a relation fork.
    1263              :     ///
    1264              :     /// 'nblocks' is the initial size.
    1265         1920 :     pub async fn put_rel_creation(
    1266         1920 :         &mut self,
    1267         1920 :         rel: RelTag,
    1268         1920 :         nblocks: BlockNumber,
    1269         1920 :         ctx: &RequestContext,
    1270         1920 :     ) -> Result<(), RelationError> {
    1271         1920 :         if rel.relnode == 0 {
    1272            0 :             return Err(RelationError::InvalidRelnode);
    1273         1920 :         }
    1274              :         // It's possible that this is the first rel for this db in this
    1275              :         // tablespace.  Create the reldir entry for it if so.
    1276         1920 :         let mut dbdir = DbDirectory::des(&self.get(DBDIR_KEY, ctx).await.context("read db")?)
    1277         1920 :             .context("deserialize db")?;
    1278         1920 :         let rel_dir_key = rel_dir_to_key(rel.spcnode, rel.dbnode);
    1279         1920 :         let mut rel_dir =
    1280         1920 :             if let hash_map::Entry::Vacant(e) = dbdir.dbdirs.entry((rel.spcnode, rel.dbnode)) {
    1281              :                 // Didn't exist. Update dbdir
    1282            8 :                 e.insert(false);
    1283            8 :                 let buf = DbDirectory::ser(&dbdir).context("serialize db")?;
    1284            8 :                 self.pending_directory_entries
    1285            8 :                     .push((DirectoryKind::Db, dbdir.dbdirs.len()));
    1286            8 :                 self.put(DBDIR_KEY, Value::Image(buf.into()));
    1287            8 : 
    1288            8 :                 // and create the RelDirectory
    1289            8 :                 RelDirectory::default()
    1290              :             } else {
    1291              :                 // reldir already exists, fetch it
    1292         1912 :                 RelDirectory::des(&self.get(rel_dir_key, ctx).await.context("read db")?)
    1293         1912 :                     .context("deserialize db")?
    1294              :             };
    1295              : 
    1296              :         // Add the new relation to the rel directory entry, and write it back
    1297         1920 :         if !rel_dir.rels.insert((rel.relnode, rel.forknum)) {
    1298            0 :             return Err(RelationError::AlreadyExists);
    1299         1920 :         }
    1300         1920 : 
    1301         1920 :         self.pending_directory_entries
    1302         1920 :             .push((DirectoryKind::Rel, rel_dir.rels.len()));
    1303         1920 : 
    1304         1920 :         self.put(
    1305         1920 :             rel_dir_key,
    1306         1920 :             Value::Image(Bytes::from(
    1307         1920 :                 RelDirectory::ser(&rel_dir).context("serialize")?,
    1308              :             )),
    1309              :         );
    1310              : 
    1311              :         // Put size
    1312         1920 :         let size_key = rel_size_to_key(rel);
    1313         1920 :         let buf = nblocks.to_le_bytes();
    1314         1920 :         self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
    1315         1920 : 
    1316         1920 :         self.pending_nblocks += nblocks as i64;
    1317         1920 : 
    1318         1920 :         // Update relation size cache
    1319         1920 :         self.tline.set_cached_rel_size(rel, self.lsn, nblocks);
    1320         1920 : 
    1321         1920 :         // Even if nblocks > 0, we don't insert any actual blocks here. That's up to the
    1322         1920 :         // caller.
    1323         1920 :         Ok(())
    1324         1920 :     }
    1325              : 
    1326              :     /// Truncate relation
    1327         6012 :     pub async fn put_rel_truncation(
    1328         6012 :         &mut self,
    1329         6012 :         rel: RelTag,
    1330         6012 :         nblocks: BlockNumber,
    1331         6012 :         ctx: &RequestContext,
    1332         6012 :     ) -> anyhow::Result<()> {
    1333         6012 :         anyhow::ensure!(rel.relnode != 0, RelationError::InvalidRelnode);
    1334         6012 :         if self
    1335         6012 :             .tline
    1336         6012 :             .get_rel_exists(rel, Version::Modified(self), ctx)
    1337            0 :             .await?
    1338              :         {
    1339         6012 :             let size_key = rel_size_to_key(rel);
    1340              :             // Fetch the old size first
    1341         6012 :             let old_size = self.get(size_key, ctx).await?.get_u32_le();
    1342         6012 : 
    1343         6012 :             // Update the entry with the new size.
    1344         6012 :             let buf = nblocks.to_le_bytes();
    1345         6012 :             self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
    1346         6012 : 
    1347         6012 :             // Update relation size cache
    1348         6012 :             self.tline.set_cached_rel_size(rel, self.lsn, nblocks);
    1349         6012 : 
    1350         6012 :             // Update relation size cache
    1351         6012 :             self.tline.set_cached_rel_size(rel, self.lsn, nblocks);
    1352         6012 : 
    1353         6012 :             // Update logical database size.
    1354         6012 :             self.pending_nblocks -= old_size as i64 - nblocks as i64;
    1355            0 :         }
    1356         6012 :         Ok(())
    1357         6012 :     }
    1358              : 
    1359              :     /// Extend relation
    1360              :     /// If new size is smaller, do nothing.
    1361       276680 :     pub async fn put_rel_extend(
    1362       276680 :         &mut self,
    1363       276680 :         rel: RelTag,
    1364       276680 :         nblocks: BlockNumber,
    1365       276680 :         ctx: &RequestContext,
    1366       276680 :     ) -> anyhow::Result<()> {
    1367       276680 :         anyhow::ensure!(rel.relnode != 0, RelationError::InvalidRelnode);
    1368              : 
    1369              :         // Put size
    1370       276680 :         let size_key = rel_size_to_key(rel);
    1371       276680 :         let old_size = self.get(size_key, ctx).await?.get_u32_le();
    1372       276680 : 
    1373       276680 :         // only extend relation here. never decrease the size
    1374       276680 :         if nblocks > old_size {
    1375       274788 :             let buf = nblocks.to_le_bytes();
    1376       274788 :             self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
    1377       274788 : 
    1378       274788 :             // Update relation size cache
    1379       274788 :             self.tline.set_cached_rel_size(rel, self.lsn, nblocks);
    1380       274788 : 
    1381       274788 :             self.pending_nblocks += nblocks as i64 - old_size as i64;
    1382       274788 :         }
    1383       276680 :         Ok(())
    1384       276680 :     }
    1385              : 
    1386              :     /// Drop a relation.
    1387            2 :     pub async fn put_rel_drop(&mut self, rel: RelTag, ctx: &RequestContext) -> anyhow::Result<()> {
    1388            2 :         anyhow::ensure!(rel.relnode != 0, RelationError::InvalidRelnode);
    1389              : 
    1390              :         // Remove it from the directory entry
    1391            2 :         let dir_key = rel_dir_to_key(rel.spcnode, rel.dbnode);
    1392            2 :         let buf = self.get(dir_key, ctx).await?;
    1393            2 :         let mut dir = RelDirectory::des(&buf)?;
    1394              : 
    1395            2 :         self.pending_directory_entries
    1396            2 :             .push((DirectoryKind::Rel, dir.rels.len()));
    1397            2 : 
    1398            2 :         if dir.rels.remove(&(rel.relnode, rel.forknum)) {
    1399            2 :             self.put(dir_key, Value::Image(Bytes::from(RelDirectory::ser(&dir)?)));
    1400              :         } else {
    1401            0 :             warn!("dropped rel {} did not exist in rel directory", rel);
    1402              :         }
    1403              : 
    1404              :         // update logical size
    1405            2 :         let size_key = rel_size_to_key(rel);
    1406            2 :         let old_size = self.get(size_key, ctx).await?.get_u32_le();
    1407            2 :         self.pending_nblocks -= old_size as i64;
    1408            2 : 
    1409            2 :         // Remove enty from relation size cache
    1410            2 :         self.tline.remove_cached_rel_size(&rel);
    1411            2 : 
    1412            2 :         // Delete size entry, as well as all blocks
    1413            2 :         self.delete(rel_key_range(rel));
    1414            2 : 
    1415            2 :         Ok(())
    1416            2 :     }
    1417              : 
    1418            6 :     pub async fn put_slru_segment_creation(
    1419            6 :         &mut self,
    1420            6 :         kind: SlruKind,
    1421            6 :         segno: u32,
    1422            6 :         nblocks: BlockNumber,
    1423            6 :         ctx: &RequestContext,
    1424            6 :     ) -> anyhow::Result<()> {
    1425            6 :         // Add it to the directory entry
    1426            6 :         let dir_key = slru_dir_to_key(kind);
    1427            6 :         let buf = self.get(dir_key, ctx).await?;
    1428            6 :         let mut dir = SlruSegmentDirectory::des(&buf)?;
    1429              : 
    1430            6 :         if !dir.segments.insert(segno) {
    1431            0 :             anyhow::bail!("slru segment {kind:?}/{segno} already exists");
    1432            6 :         }
    1433            6 :         self.pending_directory_entries
    1434            6 :             .push((DirectoryKind::SlruSegment(kind), dir.segments.len()));
    1435            6 :         self.put(
    1436            6 :             dir_key,
    1437            6 :             Value::Image(Bytes::from(SlruSegmentDirectory::ser(&dir)?)),
    1438              :         );
    1439              : 
    1440              :         // Put size
    1441            6 :         let size_key = slru_segment_size_to_key(kind, segno);
    1442            6 :         let buf = nblocks.to_le_bytes();
    1443            6 :         self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
    1444            6 : 
    1445            6 :         // even if nblocks > 0, we don't insert any actual blocks here
    1446            6 : 
    1447            6 :         Ok(())
    1448            6 :     }
    1449              : 
    1450              :     /// Extend SLRU segment
    1451            0 :     pub fn put_slru_extend(
    1452            0 :         &mut self,
    1453            0 :         kind: SlruKind,
    1454            0 :         segno: u32,
    1455            0 :         nblocks: BlockNumber,
    1456            0 :     ) -> anyhow::Result<()> {
    1457            0 :         // Put size
    1458            0 :         let size_key = slru_segment_size_to_key(kind, segno);
    1459            0 :         let buf = nblocks.to_le_bytes();
    1460            0 :         self.put(size_key, Value::Image(Bytes::from(buf.to_vec())));
    1461            0 :         Ok(())
    1462            0 :     }
    1463              : 
    1464              :     /// This method is used for marking truncated SLRU files
    1465            0 :     pub async fn drop_slru_segment(
    1466            0 :         &mut self,
    1467            0 :         kind: SlruKind,
    1468            0 :         segno: u32,
    1469            0 :         ctx: &RequestContext,
    1470            0 :     ) -> anyhow::Result<()> {
    1471            0 :         // Remove it from the directory entry
    1472            0 :         let dir_key = slru_dir_to_key(kind);
    1473            0 :         let buf = self.get(dir_key, ctx).await?;
    1474            0 :         let mut dir = SlruSegmentDirectory::des(&buf)?;
    1475              : 
    1476            0 :         if !dir.segments.remove(&segno) {
    1477            0 :             warn!("slru segment {:?}/{} does not exist", kind, segno);
    1478            0 :         }
    1479            0 :         self.pending_directory_entries
    1480            0 :             .push((DirectoryKind::SlruSegment(kind), dir.segments.len()));
    1481            0 :         self.put(
    1482            0 :             dir_key,
    1483            0 :             Value::Image(Bytes::from(SlruSegmentDirectory::ser(&dir)?)),
    1484              :         );
    1485              : 
    1486              :         // Delete size entry, as well as all blocks
    1487            0 :         self.delete(slru_segment_key_range(kind, segno));
    1488            0 : 
    1489            0 :         Ok(())
    1490            0 :     }
    1491              : 
    1492              :     /// Drop a relmapper file (pg_filenode.map)
    1493            0 :     pub fn drop_relmap_file(&mut self, _spcnode: Oid, _dbnode: Oid) -> anyhow::Result<()> {
    1494            0 :         // TODO
    1495            0 :         Ok(())
    1496            0 :     }
    1497              : 
    1498              :     /// This method is used for marking truncated SLRU files
    1499            0 :     pub async fn drop_twophase_file(
    1500            0 :         &mut self,
    1501            0 :         xid: TransactionId,
    1502            0 :         ctx: &RequestContext,
    1503            0 :     ) -> anyhow::Result<()> {
    1504              :         // Remove it from the directory entry
    1505            0 :         let buf = self.get(TWOPHASEDIR_KEY, ctx).await?;
    1506            0 :         let mut dir = TwoPhaseDirectory::des(&buf)?;
    1507              : 
    1508            0 :         if !dir.xids.remove(&xid) {
    1509            0 :             warn!("twophase file for xid {} does not exist", xid);
    1510            0 :         }
    1511            0 :         self.pending_directory_entries
    1512            0 :             .push((DirectoryKind::TwoPhase, dir.xids.len()));
    1513            0 :         self.put(
    1514            0 :             TWOPHASEDIR_KEY,
    1515            0 :             Value::Image(Bytes::from(TwoPhaseDirectory::ser(&dir)?)),
    1516              :         );
    1517              : 
    1518              :         // Delete it
    1519            0 :         self.delete(twophase_key_range(xid));
    1520            0 : 
    1521            0 :         Ok(())
    1522            0 :     }
    1523              : 
    1524          161 :     pub fn init_aux_dir(&mut self) -> anyhow::Result<()> {
    1525          161 :         if let AuxFilePolicy::V2 = self.tline.get_switch_aux_file_policy() {
    1526            2 :             return Ok(());
    1527          159 :         }
    1528          159 :         let buf = AuxFilesDirectory::ser(&AuxFilesDirectory {
    1529          159 :             files: HashMap::new(),
    1530          159 :         })?;
    1531          159 :         self.pending_directory_entries
    1532          159 :             .push((DirectoryKind::AuxFiles, 0));
    1533          159 :         self.put(AUX_FILES_KEY, Value::Image(Bytes::from(buf)));
    1534          159 :         Ok(())
    1535          161 :     }
    1536              : 
    1537           30 :     pub async fn put_file(
    1538           30 :         &mut self,
    1539           30 :         path: &str,
    1540           30 :         content: &[u8],
    1541           30 :         ctx: &RequestContext,
    1542           30 :     ) -> anyhow::Result<()> {
    1543           30 :         let switch_policy = self.tline.get_switch_aux_file_policy();
    1544              : 
    1545           30 :         let policy = {
    1546           30 :             let current_policy = self.tline.last_aux_file_policy.load();
    1547              :             // Allowed switch path:
    1548              :             // * no aux files -> v1/v2/cross-validation
    1549              :             // * cross-validation->v2
    1550              : 
    1551           30 :             let current_policy = if current_policy.is_none() {
    1552              :                 // This path will only be hit once per tenant: we will decide the final policy in this code block.
    1553              :                 // The next call to `put_file` will always have `last_aux_file_policy != None`.
    1554           12 :                 let lsn = Lsn::max(self.tline.get_last_record_lsn(), self.lsn);
    1555           12 :                 let aux_files_key_v1 = self.tline.list_aux_files_v1(lsn, ctx).await?;
    1556           12 :                 if aux_files_key_v1.is_empty() {
    1557           10 :                     None
    1558              :                 } else {
    1559            2 :                     self.tline.do_switch_aux_policy(AuxFilePolicy::V1)?;
    1560            2 :                     Some(AuxFilePolicy::V1)
    1561              :                 }
    1562              :             } else {
    1563           18 :                 current_policy
    1564              :             };
    1565              : 
    1566           30 :             if AuxFilePolicy::is_valid_migration_path(current_policy, switch_policy) {
    1567           12 :                 self.tline.do_switch_aux_policy(switch_policy)?;
    1568           12 :                 info!(current=?current_policy, next=?switch_policy, "switching aux file policy");
    1569           12 :                 switch_policy
    1570              :             } else {
    1571              :                 // This branch handles non-valid migration path, and the case that switch_policy == current_policy.
    1572              :                 // And actually, because the migration path always allow unspecified -> *, this unwrap_or will never be hit.
    1573           18 :                 current_policy.unwrap_or(AuxFilePolicy::default_tenant_config())
    1574              :             }
    1575              :         };
    1576              : 
    1577           30 :         if let AuxFilePolicy::V2 | AuxFilePolicy::CrossValidation = policy {
    1578           10 :             let key = aux_file::encode_aux_file_key(path);
    1579              :             // retrieve the key from the engine
    1580           10 :             let old_val = match self.get(key, ctx).await {
    1581            2 :                 Ok(val) => Some(val),
    1582            8 :                 Err(PageReconstructError::MissingKey(_)) => None,
    1583            0 :                 Err(e) => return Err(e.into()),
    1584              :             };
    1585           10 :             let files: Vec<(&str, &[u8])> = if let Some(ref old_val) = old_val {
    1586            2 :                 aux_file::decode_file_value(old_val)?
    1587              :             } else {
    1588            8 :                 Vec::new()
    1589              :             };
    1590           10 :             let mut other_files = Vec::with_capacity(files.len());
    1591           10 :             let mut modifying_file = None;
    1592           12 :             for file @ (p, content) in files {
    1593            2 :                 if path == p {
    1594            2 :                     assert!(
    1595            2 :                         modifying_file.is_none(),
    1596            0 :                         "duplicated entries found for {}",
    1597              :                         path
    1598              :                     );
    1599            2 :                     modifying_file = Some(content);
    1600            0 :                 } else {
    1601            0 :                     other_files.push(file);
    1602            0 :                 }
    1603              :             }
    1604           10 :             let mut new_files = other_files;
    1605           10 :             match (modifying_file, content.is_empty()) {
    1606            2 :                 (Some(old_content), false) => {
    1607            2 :                     self.tline
    1608            2 :                         .aux_file_size_estimator
    1609            2 :                         .on_update(old_content.len(), content.len());
    1610            2 :                     new_files.push((path, content));
    1611            2 :                 }
    1612            0 :                 (Some(old_content), true) => {
    1613            0 :                     self.tline
    1614            0 :                         .aux_file_size_estimator
    1615            0 :                         .on_remove(old_content.len());
    1616            0 :                     // not adding the file key to the final `new_files` vec.
    1617            0 :                 }
    1618            8 :                 (None, false) => {
    1619            8 :                     self.tline.aux_file_size_estimator.on_add(content.len());
    1620            8 :                     new_files.push((path, content));
    1621            8 :                 }
    1622            0 :                 (None, true) => warn!("removing non-existing aux file: {}", path),
    1623              :             }
    1624           10 :             let new_val = aux_file::encode_file_value(&new_files)?;
    1625           10 :             self.put(key, Value::Image(new_val.into()));
    1626           20 :         }
    1627              : 
    1628           30 :         if let AuxFilePolicy::V1 | AuxFilePolicy::CrossValidation = policy {
    1629           22 :             let file_path = path.to_string();
    1630           22 :             let content = if content.is_empty() {
    1631            2 :                 None
    1632              :             } else {
    1633           20 :                 Some(Bytes::copy_from_slice(content))
    1634              :             };
    1635              : 
    1636              :             let n_files;
    1637           22 :             let mut aux_files = self.tline.aux_files.lock().await;
    1638           22 :             if let Some(mut dir) = aux_files.dir.take() {
    1639              :                 // We already updated aux files in `self`: emit a delta and update our latest value.
    1640           10 :                 dir.upsert(file_path.clone(), content.clone());
    1641           10 :                 n_files = dir.files.len();
    1642           10 :                 if aux_files.n_deltas == MAX_AUX_FILE_DELTAS {
    1643            0 :                     self.put(
    1644            0 :                         AUX_FILES_KEY,
    1645            0 :                         Value::Image(Bytes::from(
    1646            0 :                             AuxFilesDirectory::ser(&dir).context("serialize")?,
    1647              :                         )),
    1648              :                     );
    1649            0 :                     aux_files.n_deltas = 0;
    1650           10 :                 } else {
    1651           10 :                     self.put(
    1652           10 :                         AUX_FILES_KEY,
    1653           10 :                         Value::WalRecord(NeonWalRecord::AuxFile { file_path, content }),
    1654           10 :                     );
    1655           10 :                     aux_files.n_deltas += 1;
    1656           10 :                 }
    1657           10 :                 aux_files.dir = Some(dir);
    1658              :             } else {
    1659              :                 // Check if the AUX_FILES_KEY is initialized
    1660           12 :                 match self.get(AUX_FILES_KEY, ctx).await {
    1661            8 :                     Ok(dir_bytes) => {
    1662            8 :                         let mut dir = AuxFilesDirectory::des(&dir_bytes)?;
    1663              :                         // Key is already set, we may append a delta
    1664            8 :                         self.put(
    1665            8 :                             AUX_FILES_KEY,
    1666            8 :                             Value::WalRecord(NeonWalRecord::AuxFile {
    1667            8 :                                 file_path: file_path.clone(),
    1668            8 :                                 content: content.clone(),
    1669            8 :                             }),
    1670            8 :                         );
    1671            8 :                         dir.upsert(file_path, content);
    1672            8 :                         n_files = dir.files.len();
    1673            8 :                         aux_files.dir = Some(dir);
    1674              :                     }
    1675              :                     Err(
    1676            0 :                         e @ (PageReconstructError::Cancelled
    1677            0 :                         | PageReconstructError::AncestorLsnTimeout(_)),
    1678            0 :                     ) => {
    1679            0 :                         // Important that we do not interpret a shutdown error as "not found" and thereby
    1680            0 :                         // reset the map.
    1681            0 :                         return Err(e.into());
    1682              :                     }
    1683              :                     // Note: we added missing key error variant in https://github.com/neondatabase/neon/pull/7393 but
    1684              :                     // the original code assumes all other errors are missing keys. Therefore, we keep the code path
    1685              :                     // the same for now, though in theory, we should only match the `MissingKey` variant.
    1686              :                     Err(
    1687              :                         PageReconstructError::Other(_)
    1688              :                         | PageReconstructError::WalRedo(_)
    1689              :                         | PageReconstructError::MissingKey { .. },
    1690              :                     ) => {
    1691              :                         // Key is missing, we must insert an image as the basis for subsequent deltas.
    1692              : 
    1693            4 :                         let mut dir = AuxFilesDirectory {
    1694            4 :                             files: HashMap::new(),
    1695            4 :                         };
    1696            4 :                         dir.upsert(file_path, content);
    1697            4 :                         self.put(
    1698            4 :                             AUX_FILES_KEY,
    1699            4 :                             Value::Image(Bytes::from(
    1700            4 :                                 AuxFilesDirectory::ser(&dir).context("serialize")?,
    1701              :                             )),
    1702              :                         );
    1703            4 :                         n_files = 1;
    1704            4 :                         aux_files.dir = Some(dir);
    1705              :                     }
    1706              :                 }
    1707              :             }
    1708              : 
    1709           22 :             self.pending_directory_entries
    1710           22 :                 .push((DirectoryKind::AuxFiles, n_files));
    1711            8 :         }
    1712              : 
    1713           30 :         Ok(())
    1714           30 :     }
    1715              : 
    1716              :     ///
    1717              :     /// Flush changes accumulated so far to the underlying repository.
    1718              :     ///
    1719              :     /// Usually, changes made in DatadirModification are atomic, but this allows
    1720              :     /// you to flush them to the underlying repository before the final `commit`.
    1721              :     /// That allows to free up the memory used to hold the pending changes.
    1722              :     ///
    1723              :     /// Currently only used during bulk import of a data directory. In that
    1724              :     /// context, breaking the atomicity is OK. If the import is interrupted, the
    1725              :     /// whole import fails and the timeline will be deleted anyway.
    1726              :     /// (Or to be precise, it will be left behind for debugging purposes and
    1727              :     /// ignored, see <https://github.com/neondatabase/neon/pull/1809>)
    1728              :     ///
    1729              :     /// Note: A consequence of flushing the pending operations is that they
    1730              :     /// won't be visible to subsequent operations until `commit`. The function
    1731              :     /// retains all the metadata, but data pages are flushed. That's again OK
    1732              :     /// for bulk import, where you are just loading data pages and won't try to
    1733              :     /// modify the same pages twice.
    1734         1930 :     pub async fn flush(&mut self, ctx: &RequestContext) -> anyhow::Result<()> {
    1735         1930 :         // Unless we have accumulated a decent amount of changes, it's not worth it
    1736         1930 :         // to scan through the pending_updates list.
    1737         1930 :         let pending_nblocks = self.pending_nblocks;
    1738         1930 :         if pending_nblocks < 10000 {
    1739         1930 :             return Ok(());
    1740            0 :         }
    1741              : 
    1742            0 :         let mut writer = self.tline.writer().await;
    1743              : 
    1744              :         // Flush relation and  SLRU data blocks, keep metadata.
    1745            0 :         let mut retained_pending_updates = HashMap::<_, Vec<_>>::new();
    1746            0 :         for (key, values) in self.pending_updates.drain() {
    1747            0 :             for (lsn, value) in values {
    1748            0 :                 if key.is_rel_block_key() || key.is_slru_block_key() {
    1749              :                     // This bails out on first error without modifying pending_updates.
    1750              :                     // That's Ok, cf this function's doc comment.
    1751            0 :                     writer.put(key, lsn, &value, ctx).await?;
    1752            0 :                 } else {
    1753            0 :                     retained_pending_updates
    1754            0 :                         .entry(key)
    1755            0 :                         .or_default()
    1756            0 :                         .push((lsn, value));
    1757            0 :                 }
    1758              :             }
    1759              :         }
    1760              : 
    1761            0 :         self.pending_updates = retained_pending_updates;
    1762            0 : 
    1763            0 :         if pending_nblocks != 0 {
    1764            0 :             writer.update_current_logical_size(pending_nblocks * i64::from(BLCKSZ));
    1765            0 :             self.pending_nblocks = 0;
    1766            0 :         }
    1767              : 
    1768            0 :         for (kind, count) in std::mem::take(&mut self.pending_directory_entries) {
    1769            0 :             writer.update_directory_entries_count(kind, count as u64);
    1770            0 :         }
    1771              : 
    1772            0 :         Ok(())
    1773         1930 :     }
    1774              : 
    1775              :     ///
    1776              :     /// Finish this atomic update, writing all the updated keys to the
    1777              :     /// underlying timeline.
    1778              :     /// All the modifications in this atomic update are stamped by the specified LSN.
    1779              :     ///
    1780       743047 :     pub async fn commit(&mut self, ctx: &RequestContext) -> anyhow::Result<()> {
    1781       743047 :         let mut writer = self.tline.writer().await;
    1782              : 
    1783       743047 :         let pending_nblocks = self.pending_nblocks;
    1784       743047 :         self.pending_nblocks = 0;
    1785       743047 : 
    1786       743047 :         if !self.pending_updates.is_empty() {
    1787              :             // The put_batch call below expects expects the inputs to be sorted by Lsn,
    1788              :             // so we do that first.
    1789       414031 :             let lsn_ordered_batch: VecMap<Lsn, (Key, Value)> = VecMap::from_iter(
    1790       414031 :                 self.pending_updates
    1791       414031 :                     .drain()
    1792       700272 :                     .map(|(key, vals)| vals.into_iter().map(move |(lsn, val)| (lsn, (key, val))))
    1793       414031 :                     .kmerge_by(|lhs, rhs| lhs.0 < rhs.0),
    1794       414031 :                 VecMapOrdering::GreaterOrEqual,
    1795       414031 :             );
    1796       414031 : 
    1797       414031 :             writer.put_batch(lsn_ordered_batch, ctx).await?;
    1798       329016 :         }
    1799              : 
    1800       743047 :         if !self.pending_deletions.is_empty() {
    1801            2 :             writer.delete_batch(&self.pending_deletions, ctx).await?;
    1802            2 :             self.pending_deletions.clear();
    1803       743045 :         }
    1804              : 
    1805       743047 :         self.pending_lsns.push(self.lsn);
    1806       888905 :         for pending_lsn in self.pending_lsns.drain(..) {
    1807       888905 :             // Ideally, we should be able to call writer.finish_write() only once
    1808       888905 :             // with the highest LSN. However, the last_record_lsn variable in the
    1809       888905 :             // timeline keeps track of the latest LSN and the immediate previous LSN
    1810       888905 :             // so we need to record every LSN to not leave a gap between them.
    1811       888905 :             writer.finish_write(pending_lsn);
    1812       888905 :         }
    1813              : 
    1814       743047 :         if pending_nblocks != 0 {
    1815       270570 :             writer.update_current_logical_size(pending_nblocks * i64::from(BLCKSZ));
    1816       472477 :         }
    1817              : 
    1818       743047 :         for (kind, count) in std::mem::take(&mut self.pending_directory_entries) {
    1819         2850 :             writer.update_directory_entries_count(kind, count as u64);
    1820         2850 :         }
    1821              : 
    1822       743047 :         Ok(())
    1823       743047 :     }
    1824              : 
    1825       291704 :     pub(crate) fn len(&self) -> usize {
    1826       291704 :         self.pending_updates.len() + self.pending_deletions.len()
    1827       291704 :     }
    1828              : 
    1829              :     // Internal helper functions to batch the modifications
    1830              : 
    1831       286582 :     async fn get(&self, key: Key, ctx: &RequestContext) -> Result<Bytes, PageReconstructError> {
    1832              :         // Have we already updated the same key? Read the latest pending updated
    1833              :         // version in that case.
    1834              :         //
    1835              :         // Note: we don't check pending_deletions. It is an error to request a
    1836              :         // value that has been removed, deletion only avoids leaking storage.
    1837       286582 :         if let Some(values) = self.pending_updates.get(&key) {
    1838        15928 :             if let Some((_, value)) = values.last() {
    1839        15928 :                 return if let Value::Image(img) = value {
    1840        15928 :                     Ok(img.clone())
    1841              :                 } else {
    1842              :                     // Currently, we never need to read back a WAL record that we
    1843              :                     // inserted in the same "transaction". All the metadata updates
    1844              :                     // work directly with Images, and we never need to read actual
    1845              :                     // data pages. We could handle this if we had to, by calling
    1846              :                     // the walredo manager, but let's keep it simple for now.
    1847            0 :                     Err(PageReconstructError::from(anyhow::anyhow!(
    1848            0 :                         "unexpected pending WAL record"
    1849            0 :                     )))
    1850              :                 };
    1851            0 :             }
    1852       270654 :         }
    1853       270654 :         let lsn = Lsn::max(self.tline.get_last_record_lsn(), self.lsn);
    1854       270654 :         self.tline.get(key, lsn, ctx).await
    1855       286582 :     }
    1856              : 
    1857              :     /// Only used during unit tests, force putting a key into the modification.
    1858              :     #[cfg(test)]
    1859            2 :     pub(crate) fn put_for_test(&mut self, key: Key, val: Value) {
    1860            2 :         self.put(key, val);
    1861            2 :     }
    1862              : 
    1863       712432 :     fn put(&mut self, key: Key, val: Value) {
    1864       712432 :         let values = self.pending_updates.entry(key).or_default();
    1865              :         // Replace the previous value if it exists at the same lsn
    1866       712432 :         if let Some((last_lsn, last_value)) = values.last_mut() {
    1867        12166 :             if *last_lsn == self.lsn {
    1868        12160 :                 *last_value = val;
    1869        12160 :                 return;
    1870            6 :             }
    1871       700266 :         }
    1872       700272 :         values.push((self.lsn, val));
    1873       712432 :     }
    1874              : 
    1875            2 :     fn delete(&mut self, key_range: Range<Key>) {
    1876            2 :         trace!("DELETE {}-{}", key_range.start, key_range.end);
    1877            2 :         self.pending_deletions.push((key_range, self.lsn));
    1878            2 :     }
    1879              : }
    1880              : 
    1881              : /// This struct facilitates accessing either a committed key from the timeline at a
    1882              : /// specific LSN, or the latest uncommitted key from a pending modification.
    1883              : /// During WAL ingestion, the records from multiple LSNs may be batched in the same
    1884              : /// modification before being flushed to the timeline. Hence, the routines in WalIngest
    1885              : /// need to look up the keys in the modification first before looking them up in the
    1886              : /// timeline to not miss the latest updates.
    1887              : #[derive(Clone, Copy)]
    1888              : pub enum Version<'a> {
    1889              :     Lsn(Lsn),
    1890              :     Modified(&'a DatadirModification<'a>),
    1891              : }
    1892              : 
    1893              : impl<'a> Version<'a> {
    1894        23542 :     async fn get(
    1895        23542 :         &self,
    1896        23542 :         timeline: &Timeline,
    1897        23542 :         key: Key,
    1898        23542 :         ctx: &RequestContext,
    1899        23542 :     ) -> Result<Bytes, PageReconstructError> {
    1900        23542 :         match self {
    1901        23532 :             Version::Lsn(lsn) => timeline.get(key, *lsn, ctx).await,
    1902           10 :             Version::Modified(modification) => modification.get(key, ctx).await,
    1903              :         }
    1904        23542 :     }
    1905              : 
    1906        35620 :     fn get_lsn(&self) -> Lsn {
    1907        35620 :         match self {
    1908        29574 :             Version::Lsn(lsn) => *lsn,
    1909         6046 :             Version::Modified(modification) => modification.lsn,
    1910              :         }
    1911        35620 :     }
    1912              : }
    1913              : 
    1914              : //--- Metadata structs stored in key-value pairs in the repository.
    1915              : 
    1916         2195 : #[derive(Debug, Serialize, Deserialize)]
    1917              : struct DbDirectory {
    1918              :     // (spcnode, dbnode) -> (do relmapper and PG_VERSION files exist)
    1919              :     dbdirs: HashMap<(Oid, Oid), bool>,
    1920              : }
    1921              : 
    1922          259 : #[derive(Debug, Serialize, Deserialize)]
    1923              : struct TwoPhaseDirectory {
    1924              :     xids: HashSet<TransactionId>,
    1925              : }
    1926              : 
    1927         1932 : #[derive(Debug, Serialize, Deserialize, Default)]
    1928              : struct RelDirectory {
    1929              :     // Set of relations that exist. (relfilenode, forknum)
    1930              :     //
    1931              :     // TODO: Store it as a btree or radix tree or something else that spans multiple
    1932              :     // key-value pairs, if you have a lot of relations
    1933              :     rels: HashSet<(Oid, u8)>,
    1934              : }
    1935              : 
    1936           58 : #[derive(Debug, Serialize, Deserialize, Default, PartialEq)]
    1937              : pub(crate) struct AuxFilesDirectory {
    1938              :     pub(crate) files: HashMap<String, Bytes>,
    1939              : }
    1940              : 
    1941              : impl AuxFilesDirectory {
    1942           48 :     pub(crate) fn upsert(&mut self, key: String, value: Option<Bytes>) {
    1943           48 :         if let Some(value) = value {
    1944           42 :             self.files.insert(key, value);
    1945           42 :         } else {
    1946            6 :             self.files.remove(&key);
    1947            6 :         }
    1948           48 :     }
    1949              : }
    1950              : 
    1951            0 : #[derive(Debug, Serialize, Deserialize)]
    1952              : struct RelSizeEntry {
    1953              :     nblocks: u32,
    1954              : }
    1955              : 
    1956          783 : #[derive(Debug, Serialize, Deserialize, Default)]
    1957              : struct SlruSegmentDirectory {
    1958              :     // Set of SLRU segments that exist.
    1959              :     segments: HashSet<u32>,
    1960              : }
    1961              : 
    1962              : #[derive(Copy, Clone, PartialEq, Eq, Debug, enum_map::Enum)]
    1963              : #[repr(u8)]
    1964              : pub(crate) enum DirectoryKind {
    1965              :     Db,
    1966              :     TwoPhase,
    1967              :     Rel,
    1968              :     AuxFiles,
    1969              :     SlruSegment(SlruKind),
    1970              : }
    1971              : 
    1972              : impl DirectoryKind {
    1973              :     pub(crate) const KINDS_NUM: usize = <DirectoryKind as Enum>::LENGTH;
    1974         5700 :     pub(crate) fn offset(&self) -> usize {
    1975         5700 :         self.into_usize()
    1976         5700 :     }
    1977              : }
    1978              : 
    1979              : static ZERO_PAGE: Bytes = Bytes::from_static(&[0u8; BLCKSZ as usize]);
    1980              : 
    1981              : #[allow(clippy::bool_assert_comparison)]
    1982              : #[cfg(test)]
    1983              : mod tests {
    1984              :     use hex_literal::hex;
    1985              :     use utils::id::TimelineId;
    1986              : 
    1987              :     use super::*;
    1988              : 
    1989              :     use crate::{tenant::harness::TenantHarness, DEFAULT_PG_VERSION};
    1990              : 
    1991              :     /// Test a round trip of aux file updates, from DatadirModification to reading back from the Timeline
    1992              :     #[tokio::test]
    1993            2 :     async fn aux_files_round_trip() -> anyhow::Result<()> {
    1994            2 :         let name = "aux_files_round_trip";
    1995            2 :         let harness = TenantHarness::create(name)?;
    1996            2 : 
    1997            2 :         pub const TIMELINE_ID: TimelineId =
    1998            2 :             TimelineId::from_array(hex!("11223344556677881122334455667788"));
    1999            2 : 
    2000            8 :         let (tenant, ctx) = harness.load().await;
    2001            2 :         let tline = tenant
    2002            2 :             .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
    2003            2 :             .await?;
    2004            2 :         let tline = tline.raw_timeline().unwrap();
    2005            2 : 
    2006            2 :         // First modification: insert two keys
    2007            2 :         let mut modification = tline.begin_modification(Lsn(0x1000));
    2008            2 :         modification.put_file("foo/bar1", b"content1", &ctx).await?;
    2009            2 :         modification.set_lsn(Lsn(0x1008))?;
    2010            2 :         modification.put_file("foo/bar2", b"content2", &ctx).await?;
    2011            2 :         modification.commit(&ctx).await?;
    2012            2 :         let expect_1008 = HashMap::from([
    2013            2 :             ("foo/bar1".to_string(), Bytes::from_static(b"content1")),
    2014            2 :             ("foo/bar2".to_string(), Bytes::from_static(b"content2")),
    2015            2 :         ]);
    2016            2 : 
    2017            2 :         let readback = tline.list_aux_files(Lsn(0x1008), &ctx).await?;
    2018            2 :         assert_eq!(readback, expect_1008);
    2019            2 : 
    2020            2 :         // Second modification: update one key, remove the other
    2021            2 :         let mut modification = tline.begin_modification(Lsn(0x2000));
    2022            2 :         modification.put_file("foo/bar1", b"content3", &ctx).await?;
    2023            2 :         modification.set_lsn(Lsn(0x2008))?;
    2024            2 :         modification.put_file("foo/bar2", b"", &ctx).await?;
    2025            2 :         modification.commit(&ctx).await?;
    2026            2 :         let expect_2008 =
    2027            2 :             HashMap::from([("foo/bar1".to_string(), Bytes::from_static(b"content3"))]);
    2028            2 : 
    2029            2 :         let readback = tline.list_aux_files(Lsn(0x2008), &ctx).await?;
    2030            2 :         assert_eq!(readback, expect_2008);
    2031            2 : 
    2032            2 :         // Reading back in time works
    2033            2 :         let readback = tline.list_aux_files(Lsn(0x1008), &ctx).await?;
    2034            2 :         assert_eq!(readback, expect_1008);
    2035            2 : 
    2036            2 :         Ok(())
    2037            2 :     }
    2038              : 
    2039              :     /*
    2040              :         fn assert_current_logical_size<R: Repository>(timeline: &DatadirTimeline<R>, lsn: Lsn) {
    2041              :             let incremental = timeline.get_current_logical_size();
    2042              :             let non_incremental = timeline
    2043              :                 .get_current_logical_size_non_incremental(lsn)
    2044              :                 .unwrap();
    2045              :             assert_eq!(incremental, non_incremental);
    2046              :         }
    2047              :     */
    2048              : 
    2049              :     /*
    2050              :     ///
    2051              :     /// Test list_rels() function, with branches and dropped relations
    2052              :     ///
    2053              :     #[test]
    2054              :     fn test_list_rels_drop() -> Result<()> {
    2055              :         let repo = RepoHarness::create("test_list_rels_drop")?.load();
    2056              :         let tline = create_empty_timeline(repo, TIMELINE_ID)?;
    2057              :         const TESTDB: u32 = 111;
    2058              : 
    2059              :         // Import initial dummy checkpoint record, otherwise the get_timeline() call
    2060              :         // after branching fails below
    2061              :         let mut writer = tline.begin_record(Lsn(0x10));
    2062              :         writer.put_checkpoint(ZERO_CHECKPOINT.clone())?;
    2063              :         writer.finish()?;
    2064              : 
    2065              :         // Create a relation on the timeline
    2066              :         let mut writer = tline.begin_record(Lsn(0x20));
    2067              :         writer.put_rel_page_image(TESTREL_A, 0, TEST_IMG("foo blk 0 at 2"))?;
    2068              :         writer.finish()?;
    2069              : 
    2070              :         let writer = tline.begin_record(Lsn(0x00));
    2071              :         writer.finish()?;
    2072              : 
    2073              :         // Check that list_rels() lists it after LSN 2, but no before it
    2074              :         assert!(!tline.list_rels(0, TESTDB, Lsn(0x10))?.contains(&TESTREL_A));
    2075              :         assert!(tline.list_rels(0, TESTDB, Lsn(0x20))?.contains(&TESTREL_A));
    2076              :         assert!(tline.list_rels(0, TESTDB, Lsn(0x30))?.contains(&TESTREL_A));
    2077              : 
    2078              :         // Create a branch, check that the relation is visible there
    2079              :         repo.branch_timeline(&tline, NEW_TIMELINE_ID, Lsn(0x30))?;
    2080              :         let newtline = match repo.get_timeline(NEW_TIMELINE_ID)?.local_timeline() {
    2081              :             Some(timeline) => timeline,
    2082              :             None => panic!("Should have a local timeline"),
    2083              :         };
    2084              :         let newtline = DatadirTimelineImpl::new(newtline);
    2085              :         assert!(newtline
    2086              :             .list_rels(0, TESTDB, Lsn(0x30))?
    2087              :             .contains(&TESTREL_A));
    2088              : 
    2089              :         // Drop it on the branch
    2090              :         let mut new_writer = newtline.begin_record(Lsn(0x40));
    2091              :         new_writer.drop_relation(TESTREL_A)?;
    2092              :         new_writer.finish()?;
    2093              : 
    2094              :         // Check that it's no longer listed on the branch after the point where it was dropped
    2095              :         assert!(newtline
    2096              :             .list_rels(0, TESTDB, Lsn(0x30))?
    2097              :             .contains(&TESTREL_A));
    2098              :         assert!(!newtline
    2099              :             .list_rels(0, TESTDB, Lsn(0x40))?
    2100              :             .contains(&TESTREL_A));
    2101              : 
    2102              :         // Run checkpoint and garbage collection and check that it's still not visible
    2103              :         newtline.checkpoint(CheckpointConfig::Forced)?;
    2104              :         repo.gc_iteration(Some(NEW_TIMELINE_ID), 0, true)?;
    2105              : 
    2106              :         assert!(!newtline
    2107              :             .list_rels(0, TESTDB, Lsn(0x40))?
    2108              :             .contains(&TESTREL_A));
    2109              : 
    2110              :         Ok(())
    2111              :     }
    2112              :      */
    2113              : 
    2114              :     /*
    2115              :     #[test]
    2116              :     fn test_read_beyond_eof() -> Result<()> {
    2117              :         let repo = RepoHarness::create("test_read_beyond_eof")?.load();
    2118              :         let tline = create_test_timeline(repo, TIMELINE_ID)?;
    2119              : 
    2120              :         make_some_layers(&tline, Lsn(0x20))?;
    2121              :         let mut writer = tline.begin_record(Lsn(0x60));
    2122              :         walingest.put_rel_page_image(
    2123              :             &mut writer,
    2124              :             TESTREL_A,
    2125              :             0,
    2126              :             TEST_IMG(&format!("foo blk 0 at {}", Lsn(0x60))),
    2127              :         )?;
    2128              :         writer.finish()?;
    2129              : 
    2130              :         // Test read before rel creation. Should error out.
    2131              :         assert!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x10), false).is_err());
    2132              : 
    2133              :         // Read block beyond end of relation at different points in time.
    2134              :         // These reads should fall into different delta, image, and in-memory layers.
    2135              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x20), false)?, ZERO_PAGE);
    2136              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x25), false)?, ZERO_PAGE);
    2137              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x30), false)?, ZERO_PAGE);
    2138              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x35), false)?, ZERO_PAGE);
    2139              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x40), false)?, ZERO_PAGE);
    2140              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x45), false)?, ZERO_PAGE);
    2141              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x50), false)?, ZERO_PAGE);
    2142              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x55), false)?, ZERO_PAGE);
    2143              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_A, 1, Lsn(0x60), false)?, ZERO_PAGE);
    2144              : 
    2145              :         // Test on an in-memory layer with no preceding layer
    2146              :         let mut writer = tline.begin_record(Lsn(0x70));
    2147              :         walingest.put_rel_page_image(
    2148              :             &mut writer,
    2149              :             TESTREL_B,
    2150              :             0,
    2151              :             TEST_IMG(&format!("foo blk 0 at {}", Lsn(0x70))),
    2152              :         )?;
    2153              :         writer.finish()?;
    2154              : 
    2155              :         assert_eq!(tline.get_rel_page_at_lsn(TESTREL_B, 1, Lsn(0x70), false)?6, ZERO_PAGE);
    2156              : 
    2157              :         Ok(())
    2158              :     }
    2159              :      */
    2160              : }
        

Generated by: LCOV version 2.1-beta