LCOV - code coverage report
Current view: top level - pageserver/src - walingest.rs (source / functions) Coverage Total Hit
Test: 15f04989d2faf4ce76cecb56042184aca56ebae6.info Lines: 55.8 % 1598 892
Test Date: 2025-07-14 11:50:36 Functions: 56.5 % 92 52

            Line data    Source code
       1              : //!
       2              : //! Parse PostgreSQL WAL records and store them in a neon Timeline.
       3              : //!
       4              : //! The pipeline for ingesting WAL looks like this:
       5              : //!
       6              : //! WAL receiver  -> [`wal_decoder`] ->  WalIngest  ->   Repository
       7              : //!
       8              : //! The WAL receiver receives a stream of WAL from the WAL safekeepers.
       9              : //! Records get decoded and interpreted in the [`wal_decoder`] module
      10              : //! and then stored to the Repository by WalIngest.
      11              : //!
      12              : //! The neon Repository can store page versions in two formats: as
      13              : //! page images, or a WAL records. [`wal_decoder::models::InterpretedWalRecord::from_bytes_filtered`]
      14              : //! extracts page images out of some WAL records, but mostly it's WAL
      15              : //! records. If a WAL record modifies multiple pages, WalIngest
      16              : //! will call Repository::put_rel_wal_record or put_rel_page_image functions
      17              : //! separately for each modified page.
      18              : //!
      19              : //! To reconstruct a page using a WAL record, the Repository calls the
      20              : //! code in walredo.rs. walredo.rs passes most WAL records to the WAL
      21              : //! redo Postgres process, but some records it can handle directly with
      22              : //! bespoken Rust code.
      23              : 
      24              : use std::backtrace::Backtrace;
      25              : use std::collections::HashMap;
      26              : use std::sync::{Arc, OnceLock};
      27              : use std::time::{Duration, Instant, SystemTime};
      28              : 
      29              : use bytes::{Buf, Bytes};
      30              : use pageserver_api::key::{Key, rel_block_to_key};
      31              : use pageserver_api::reltag::{BlockNumber, RelTag, SlruKind};
      32              : use pageserver_api::shard::ShardIdentity;
      33              : use postgres_ffi::walrecord::*;
      34              : use postgres_ffi::{
      35              :     PgMajorVersion, TimestampTz, TransactionId, dispatch_pgversion, enum_pgversion,
      36              :     enum_pgversion_dispatch, fsm_logical_to_physical, pg_constants,
      37              : };
      38              : use postgres_ffi_types::forknum::{FSM_FORKNUM, INIT_FORKNUM, MAIN_FORKNUM, VISIBILITYMAP_FORKNUM};
      39              : use tracing::*;
      40              : use utils::bin_ser::{DeserializeError, SerializeError};
      41              : use utils::lsn::Lsn;
      42              : use utils::rate_limit::RateLimit;
      43              : use utils::{critical_timeline, failpoint_support};
      44              : use wal_decoder::models::record::NeonWalRecord;
      45              : use wal_decoder::models::*;
      46              : 
      47              : use crate::ZERO_PAGE;
      48              : use crate::context::RequestContext;
      49              : use crate::metrics::WAL_INGEST;
      50              : use crate::pgdatadir_mapping::{DatadirModification, Version};
      51              : use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
      52              : use crate::tenant::{PageReconstructError, Timeline};
      53              : 
      54              : enum_pgversion! {CheckPoint, pgv::CheckPoint}
      55              : 
      56              : impl CheckPoint {
      57            3 :     fn encode(&self) -> Result<Bytes, SerializeError> {
      58            3 :         enum_pgversion_dispatch!(self, CheckPoint, cp, { cp.encode() })
      59            3 :     }
      60              : 
      61        72917 :     fn update_next_xid(&mut self, xid: u32) -> bool {
      62        72917 :         enum_pgversion_dispatch!(self, CheckPoint, cp, { cp.update_next_xid(xid) })
      63        72917 :     }
      64              : 
      65            0 :     pub fn update_next_multixid(&mut self, multi_xid: u32, multi_offset: u32) -> bool {
      66            0 :         enum_pgversion_dispatch!(self, CheckPoint, cp, {
      67            0 :             cp.update_next_multixid(multi_xid, multi_offset)
      68              :         })
      69            0 :     }
      70              : }
      71              : 
      72              : /// Temporary limitation of WAL lag warnings after attach
      73              : ///
      74              : /// After tenant attach, we want to limit WAL lag warnings because
      75              : /// we don't look at the WAL until the attach is complete, which
      76              : /// might take a while.
      77              : pub struct WalLagCooldown {
      78              :     /// Until when should this limitation apply at all
      79              :     active_until: std::time::Instant,
      80              :     /// The maximum lag to suppress. Lags above this limit get reported anyways.
      81              :     max_lag: Duration,
      82              : }
      83              : 
      84              : impl WalLagCooldown {
      85            0 :     pub fn new(attach_start: Instant, attach_duration: Duration) -> Self {
      86            0 :         Self {
      87            0 :             active_until: attach_start + attach_duration * 3 + Duration::from_secs(120),
      88            0 :             max_lag: attach_duration * 2 + Duration::from_secs(60),
      89            0 :         }
      90            0 :     }
      91              : }
      92              : 
      93              : pub struct WalIngest {
      94              :     attach_wal_lag_cooldown: Arc<OnceLock<WalLagCooldown>>,
      95              :     shard: ShardIdentity,
      96              :     checkpoint: CheckPoint,
      97              :     checkpoint_modified: bool,
      98              :     warn_ingest_lag: WarnIngestLag,
      99              : }
     100              : 
     101              : struct WarnIngestLag {
     102              :     lag_msg_ratelimit: RateLimit,
     103              :     future_lsn_msg_ratelimit: RateLimit,
     104              :     timestamp_invalid_msg_ratelimit: RateLimit,
     105              : }
     106              : 
     107              : pub struct WalIngestError {
     108              :     pub backtrace: std::backtrace::Backtrace,
     109              :     pub kind: WalIngestErrorKind,
     110              : }
     111              : 
     112              : #[derive(thiserror::Error, Debug)]
     113              : pub enum WalIngestErrorKind {
     114              :     #[error(transparent)]
     115              :     #[allow(private_interfaces)]
     116              :     PageReconstructError(#[from] PageReconstructError),
     117              :     #[error(transparent)]
     118              :     DeserializationFailure(#[from] DeserializeError),
     119              :     #[error(transparent)]
     120              :     SerializationFailure(#[from] SerializeError),
     121              :     #[error("the request contains data not supported by pageserver: {0} @ {1}")]
     122              :     InvalidKey(Key, Lsn),
     123              :     #[error("twophase file for xid {0} already exists")]
     124              :     FileAlreadyExists(u64),
     125              :     #[error("slru segment {0:?}/{1} already exists")]
     126              :     SlruAlreadyExists(SlruKind, u32),
     127              :     #[error("relation already exists")]
     128              :     RelationAlreadyExists(RelTag),
     129              :     #[error("invalid reldir key {0}")]
     130              :     InvalidRelDirKey(Key),
     131              : 
     132              :     #[error(transparent)]
     133              :     LogicalError(anyhow::Error),
     134              :     #[error(transparent)]
     135              :     EncodeAuxFileError(anyhow::Error),
     136              :     #[error(transparent)]
     137              :     MaybeRelSizeV2Error(anyhow::Error),
     138              : 
     139              :     #[error("timeline shutting down")]
     140              :     Cancelled,
     141              : }
     142              : 
     143              : impl<T> From<T> for WalIngestError
     144              : where
     145              :     WalIngestErrorKind: From<T>,
     146              : {
     147            0 :     fn from(value: T) -> Self {
     148            0 :         WalIngestError {
     149            0 :             backtrace: Backtrace::capture(),
     150            0 :             kind: WalIngestErrorKind::from(value),
     151            0 :         }
     152            0 :     }
     153              : }
     154              : 
     155              : impl std::error::Error for WalIngestError {
     156            0 :     fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
     157            0 :         self.kind.source()
     158            0 :     }
     159              : }
     160              : 
     161              : impl core::fmt::Display for WalIngestError {
     162            0 :     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
     163            0 :         self.kind.fmt(f)
     164            0 :     }
     165              : }
     166              : 
     167              : impl core::fmt::Debug for WalIngestError {
     168            0 :     fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
     169            0 :         if f.alternate() {
     170            0 :             f.debug_map()
     171            0 :                 .key(&"backtrace")
     172            0 :                 .value(&self.backtrace)
     173            0 :                 .key(&"kind")
     174            0 :                 .value(&self.kind)
     175            0 :                 .finish()
     176              :         } else {
     177            0 :             writeln!(f, "Error: {:?}", self.kind)?;
     178            0 :             if self.backtrace.status() == std::backtrace::BacktraceStatus::Captured {
     179            0 :                 writeln!(f, "Stack backtrace: {:?}", self.backtrace)?;
     180            0 :             }
     181            0 :             Ok(())
     182              :         }
     183            0 :     }
     184              : }
     185              : 
     186              : #[macro_export]
     187              : macro_rules! ensure_walingest {
     188              :     ($($t:tt)*) => {
     189       354701 :         _ = || -> Result<(), anyhow::Error> {
     190       354701 :             anyhow::ensure!($($t)*);
     191       354701 :             Ok(())
     192       354701 :         }().map_err(WalIngestErrorKind::LogicalError)?;
     193              :     };
     194              : }
     195              : 
     196              : impl WalIngest {
     197            6 :     pub async fn new(
     198            6 :         timeline: &Timeline,
     199            6 :         startpoint: Lsn,
     200            6 :         ctx: &RequestContext,
     201            6 :     ) -> Result<WalIngest, WalIngestError> {
     202              :         // Fetch the latest checkpoint into memory, so that we can compare with it
     203              :         // quickly in `ingest_record` and update it when it changes.
     204            6 :         let checkpoint_bytes = timeline.get_checkpoint(startpoint, ctx).await?;
     205            6 :         let pgversion = timeline.pg_version;
     206              : 
     207            6 :         let checkpoint = dispatch_pgversion!(pgversion, {
     208            0 :             let checkpoint = pgv::CheckPoint::decode(&checkpoint_bytes)?;
     209            4 :             trace!("CheckPoint.nextXid = {}", checkpoint.nextXid.value);
     210            0 :             <pgv::CheckPoint as Into<CheckPoint>>::into(checkpoint)
     211              :         });
     212              : 
     213            6 :         Ok(WalIngest {
     214            6 :             shard: *timeline.get_shard_identity(),
     215            6 :             checkpoint,
     216            6 :             checkpoint_modified: false,
     217            6 :             attach_wal_lag_cooldown: timeline.attach_wal_lag_cooldown.clone(),
     218            6 :             warn_ingest_lag: WarnIngestLag {
     219            6 :                 lag_msg_ratelimit: RateLimit::new(std::time::Duration::from_secs(10)),
     220            6 :                 future_lsn_msg_ratelimit: RateLimit::new(std::time::Duration::from_secs(10)),
     221            6 :                 timestamp_invalid_msg_ratelimit: RateLimit::new(std::time::Duration::from_secs(10)),
     222            6 :             },
     223            6 :         })
     224            6 :     }
     225              : 
     226              :     /// Ingest an interpreted PostgreSQL WAL record by doing writes to the underlying key value
     227              :     /// storage of a given timeline.
     228              :     ///
     229              :     /// This function updates `lsn` field of `DatadirModification`
     230              :     ///
     231              :     /// This function returns `true` if the record was ingested, and `false` if it was filtered out
     232        72926 :     pub async fn ingest_record(
     233        72926 :         &mut self,
     234        72926 :         interpreted: InterpretedWalRecord,
     235        72926 :         modification: &mut DatadirModification<'_>,
     236        72926 :         ctx: &RequestContext,
     237        72926 :     ) -> Result<bool, WalIngestError> {
     238        72926 :         WAL_INGEST.records_received.inc();
     239        72926 :         let prev_len = modification.len();
     240              : 
     241        72926 :         modification.set_lsn(interpreted.next_record_lsn)?;
     242              : 
     243        72926 :         if matches!(interpreted.flush_uncommitted, FlushUncommittedRecords::Yes) {
     244              :             // Records of this type should always be preceded by a commit(), as they
     245              :             // rely on reading data pages back from the Timeline.
     246            0 :             assert!(!modification.has_dirty_data());
     247        72926 :         }
     248              : 
     249        72926 :         assert!(!self.checkpoint_modified);
     250        72926 :         if interpreted.xid != pg_constants::INVALID_TRANSACTION_ID
     251        72917 :             && self.checkpoint.update_next_xid(interpreted.xid)
     252            1 :         {
     253            1 :             self.checkpoint_modified = true;
     254        72925 :         }
     255              : 
     256        72926 :         failpoint_support::sleep_millis_async!("wal-ingest-record-sleep");
     257              : 
     258           33 :         match interpreted.metadata_record {
     259            6 :             Some(MetadataRecord::Heapam(rec)) => match rec {
     260            6 :                 HeapamRecord::ClearVmBits(clear_vm_bits) => {
     261            6 :                     self.ingest_clear_vm_bits(clear_vm_bits, modification, ctx)
     262            6 :                         .await?;
     263              :                 }
     264              :             },
     265            0 :             Some(MetadataRecord::Neonrmgr(rec)) => match rec {
     266            0 :                 NeonrmgrRecord::ClearVmBits(clear_vm_bits) => {
     267            0 :                     self.ingest_clear_vm_bits(clear_vm_bits, modification, ctx)
     268            0 :                         .await?;
     269              :                 }
     270              :             },
     271            8 :             Some(MetadataRecord::Smgr(rec)) => match rec {
     272            8 :                 SmgrRecord::Create(create) => {
     273            8 :                     self.ingest_xlog_smgr_create(create, modification, ctx)
     274            8 :                         .await?;
     275              :                 }
     276            0 :                 SmgrRecord::Truncate(truncate) => {
     277            0 :                     self.ingest_xlog_smgr_truncate(truncate, modification, ctx)
     278            0 :                         .await?;
     279              :                 }
     280              :             },
     281            0 :             Some(MetadataRecord::Dbase(rec)) => match rec {
     282            0 :                 DbaseRecord::Create(create) => {
     283            0 :                     self.ingest_xlog_dbase_create(create, modification, ctx)
     284            0 :                         .await?;
     285              :                 }
     286            0 :                 DbaseRecord::Drop(drop) => {
     287            0 :                     self.ingest_xlog_dbase_drop(drop, modification, ctx).await?;
     288              :                 }
     289              :             },
     290            0 :             Some(MetadataRecord::Clog(rec)) => match rec {
     291            0 :                 ClogRecord::ZeroPage(zero_page) => {
     292            0 :                     self.ingest_clog_zero_page(zero_page, modification, ctx)
     293            0 :                         .await?;
     294              :                 }
     295            0 :                 ClogRecord::Truncate(truncate) => {
     296            0 :                     self.ingest_clog_truncate(truncate, modification, ctx)
     297            0 :                         .await?;
     298              :                 }
     299              :             },
     300            4 :             Some(MetadataRecord::Xact(rec)) => {
     301            4 :                 self.ingest_xact_record(rec, modification, ctx).await?;
     302              :             }
     303            0 :             Some(MetadataRecord::MultiXact(rec)) => match rec {
     304            0 :                 MultiXactRecord::ZeroPage(zero_page) => {
     305            0 :                     self.ingest_multixact_zero_page(zero_page, modification, ctx)
     306            0 :                         .await?;
     307              :                 }
     308            0 :                 MultiXactRecord::Create(create) => {
     309            0 :                     self.ingest_multixact_create(modification, &create)?;
     310              :                 }
     311            0 :                 MultiXactRecord::Truncate(truncate) => {
     312            0 :                     self.ingest_multixact_truncate(modification, &truncate, ctx)
     313            0 :                         .await?;
     314              :                 }
     315              :             },
     316            0 :             Some(MetadataRecord::Relmap(rec)) => match rec {
     317            0 :                 RelmapRecord::Update(update) => {
     318            0 :                     self.ingest_relmap_update(update, modification, ctx).await?;
     319              :                 }
     320              :             },
     321           15 :             Some(MetadataRecord::Xlog(rec)) => match rec {
     322           15 :                 XlogRecord::Raw(raw) => {
     323           15 :                     self.ingest_raw_xlog_record(raw, modification, ctx).await?;
     324              :                 }
     325              :             },
     326            0 :             Some(MetadataRecord::LogicalMessage(rec)) => match rec {
     327            0 :                 LogicalMessageRecord::Put(put) => {
     328            0 :                     self.ingest_logical_message_put(put, modification, ctx)
     329            0 :                         .await?;
     330              :                 }
     331              :                 #[cfg(feature = "testing")]
     332              :                 LogicalMessageRecord::Failpoint => {
     333              :                     // This is a convenient way to make the WAL ingestion pause at
     334              :                     // particular point in the WAL. For more fine-grained control,
     335              :                     // we could peek into the message and only pause if it contains
     336              :                     // a particular string, for example, but this is enough for now.
     337            0 :                     failpoint_support::sleep_millis_async!(
     338              :                         "pageserver-wal-ingest-logical-message-sleep"
     339              :                     );
     340              :                 }
     341              :             },
     342            0 :             Some(MetadataRecord::Standby(rec)) => {
     343            0 :                 self.ingest_standby_record(rec).unwrap();
     344            0 :             }
     345            0 :             Some(MetadataRecord::Replorigin(rec)) => {
     346            0 :                 self.ingest_replorigin_record(rec, modification).await?;
     347              :             }
     348        72893 :             None => {
     349        72893 :                 // There are two cases through which we end up here:
     350        72893 :                 // 1. The resource manager for the original PG WAL record
     351        72893 :                 //    is [`pg_constants::RM_TBLSPC_ID`]. This is not a supported
     352        72893 :                 //    record type within Neon.
     353        72893 :                 // 2. The resource manager id was unknown to
     354        72893 :                 //    [`wal_decoder::decoder::MetadataRecord::from_decoded`].
     355        72893 :                 // TODO(vlad): Tighten this up more once we build confidence
     356        72893 :                 // that case (2) does not happen in the field.
     357        72893 :             }
     358              :         }
     359              : 
     360        72926 :         modification
     361        72926 :             .ingest_batch(interpreted.batch, &self.shard, ctx)
     362        72926 :             .await?;
     363              : 
     364              :         // If checkpoint data was updated, store the new version in the repository
     365        72926 :         if self.checkpoint_modified {
     366            3 :             let new_checkpoint_bytes = self.checkpoint.encode()?;
     367              : 
     368            3 :             modification.put_checkpoint(new_checkpoint_bytes)?;
     369            3 :             self.checkpoint_modified = false;
     370        72923 :         }
     371              : 
     372              :         // Note that at this point this record is only cached in the modification
     373              :         // until commit() is called to flush the data into the repository and update
     374              :         // the latest LSN.
     375              : 
     376        72926 :         Ok(modification.len() > prev_len)
     377        72926 :     }
     378              : 
     379              :     /// This is the same as AdjustToFullTransactionId(xid) in PostgreSQL
     380            0 :     fn adjust_to_full_transaction_id(&self, xid: TransactionId) -> Result<u64, WalIngestError> {
     381            0 :         let next_full_xid =
     382            0 :             enum_pgversion_dispatch!(&self.checkpoint, CheckPoint, cp, { cp.nextXid.value });
     383              : 
     384            0 :         let next_xid = (next_full_xid) as u32;
     385            0 :         let mut epoch = (next_full_xid >> 32) as u32;
     386              : 
     387            0 :         if xid > next_xid {
     388              :             // Wraparound occurred, must be from a prev epoch.
     389            0 :             if epoch == 0 {
     390            0 :                 Err(WalIngestErrorKind::LogicalError(anyhow::anyhow!(
     391            0 :                     "apparent XID wraparound with prepared transaction XID {xid}, nextXid is {next_full_xid}"
     392            0 :                 )))?;
     393            0 :             }
     394            0 :             epoch -= 1;
     395            0 :         }
     396              : 
     397            0 :         Ok(((epoch as u64) << 32) | xid as u64)
     398            0 :     }
     399              : 
     400            6 :     async fn ingest_clear_vm_bits(
     401            6 :         &mut self,
     402            6 :         clear_vm_bits: ClearVmBits,
     403            6 :         modification: &mut DatadirModification<'_>,
     404            6 :         ctx: &RequestContext,
     405            6 :     ) -> Result<(), WalIngestError> {
     406              :         let ClearVmBits {
     407            6 :             new_heap_blkno,
     408            6 :             old_heap_blkno,
     409            6 :             flags,
     410            6 :             vm_rel,
     411            6 :         } = clear_vm_bits;
     412              :         // Clear the VM bits if required.
     413            6 :         let mut new_vm_blk = new_heap_blkno.map(pg_constants::HEAPBLK_TO_MAPBLOCK);
     414            6 :         let mut old_vm_blk = old_heap_blkno.map(pg_constants::HEAPBLK_TO_MAPBLOCK);
     415              : 
     416              :         // VM bits can only be cleared on the shard(s) owning the VM relation, and must be within
     417              :         // its view of the VM relation size. Out of caution, error instead of failing WAL ingestion,
     418              :         // as there has historically been cases where PostgreSQL has cleared spurious VM pages. See:
     419              :         // https://github.com/neondatabase/neon/pull/10634.
     420            6 :         let Some(vm_size) = get_relsize(modification, vm_rel, ctx).await? else {
     421            0 :             critical_timeline!(
     422            0 :                 modification.tline.tenant_shard_id,
     423            0 :                 modification.tline.timeline_id,
     424            0 :                 "clear_vm_bits for unknown VM relation {vm_rel}"
     425              :             );
     426            0 :             return Ok(());
     427              :         };
     428            6 :         if let Some(blknum) = new_vm_blk {
     429            6 :             if blknum >= vm_size {
     430            0 :                 critical_timeline!(
     431            0 :                     modification.tline.tenant_shard_id,
     432            0 :                     modification.tline.timeline_id,
     433            0 :                     "new_vm_blk {blknum} not in {vm_rel} of size {vm_size}"
     434              :                 );
     435            0 :                 new_vm_blk = None;
     436            6 :             }
     437            0 :         }
     438            6 :         if let Some(blknum) = old_vm_blk {
     439            0 :             if blknum >= vm_size {
     440            0 :                 critical_timeline!(
     441            0 :                     modification.tline.tenant_shard_id,
     442            0 :                     modification.tline.timeline_id,
     443            0 :                     "old_vm_blk {blknum} not in {vm_rel} of size {vm_size}"
     444              :                 );
     445            0 :                 old_vm_blk = None;
     446            0 :             }
     447            6 :         }
     448              : 
     449            6 :         if new_vm_blk.is_none() && old_vm_blk.is_none() {
     450            0 :             return Ok(());
     451            6 :         } else if new_vm_blk == old_vm_blk {
     452              :             // An UPDATE record that needs to clear the bits for both old and the new page, both of
     453              :             // which reside on the same VM page.
     454            0 :             self.put_rel_wal_record(
     455            0 :                 modification,
     456            0 :                 vm_rel,
     457            0 :                 new_vm_blk.unwrap(),
     458            0 :                 NeonWalRecord::ClearVisibilityMapFlags {
     459            0 :                     new_heap_blkno,
     460            0 :                     old_heap_blkno,
     461            0 :                     flags,
     462            0 :                 },
     463            0 :                 ctx,
     464            0 :             )
     465            0 :             .await?;
     466              :         } else {
     467              :             // Clear VM bits for one heap page, or for two pages that reside on different VM pages.
     468            6 :             if let Some(new_vm_blk) = new_vm_blk {
     469            6 :                 self.put_rel_wal_record(
     470            6 :                     modification,
     471            6 :                     vm_rel,
     472            6 :                     new_vm_blk,
     473            6 :                     NeonWalRecord::ClearVisibilityMapFlags {
     474            6 :                         new_heap_blkno,
     475            6 :                         old_heap_blkno: None,
     476            6 :                         flags,
     477            6 :                     },
     478            6 :                     ctx,
     479            6 :                 )
     480            6 :                 .await?;
     481            0 :             }
     482            6 :             if let Some(old_vm_blk) = old_vm_blk {
     483            0 :                 self.put_rel_wal_record(
     484            0 :                     modification,
     485            0 :                     vm_rel,
     486            0 :                     old_vm_blk,
     487            0 :                     NeonWalRecord::ClearVisibilityMapFlags {
     488            0 :                         new_heap_blkno: None,
     489            0 :                         old_heap_blkno,
     490            0 :                         flags,
     491            0 :                     },
     492            0 :                     ctx,
     493            0 :                 )
     494            0 :                 .await?;
     495            6 :             }
     496              :         }
     497            6 :         Ok(())
     498            6 :     }
     499              : 
     500              :     /// Subroutine of ingest_record(), to handle an XLOG_DBASE_CREATE record.
     501            0 :     async fn ingest_xlog_dbase_create(
     502            0 :         &mut self,
     503            0 :         create: DbaseCreate,
     504            0 :         modification: &mut DatadirModification<'_>,
     505            0 :         ctx: &RequestContext,
     506            0 :     ) -> Result<(), WalIngestError> {
     507              :         let DbaseCreate {
     508            0 :             db_id,
     509            0 :             tablespace_id,
     510            0 :             src_db_id,
     511            0 :             src_tablespace_id,
     512            0 :         } = create;
     513              : 
     514            0 :         let rels = modification
     515            0 :             .tline
     516            0 :             .list_rels(
     517            0 :                 src_tablespace_id,
     518            0 :                 src_db_id,
     519            0 :                 Version::Modified(modification),
     520            0 :                 ctx,
     521            0 :             )
     522            0 :             .await?;
     523              : 
     524            0 :         debug!("ingest_xlog_dbase_create: {} rels", rels.len());
     525              : 
     526              :         // Copy relfilemap
     527            0 :         let filemap = modification
     528            0 :             .tline
     529            0 :             .get_relmap_file(
     530            0 :                 src_tablespace_id,
     531            0 :                 src_db_id,
     532            0 :                 Version::Modified(modification),
     533            0 :                 ctx,
     534            0 :             )
     535            0 :             .await?;
     536            0 :         modification
     537            0 :             .put_relmap_file(tablespace_id, db_id, filemap, ctx)
     538            0 :             .await?;
     539              : 
     540            0 :         let mut num_rels_copied = 0;
     541            0 :         let mut num_blocks_copied = 0;
     542            0 :         for src_rel in rels {
     543            0 :             assert_eq!(src_rel.spcnode, src_tablespace_id);
     544            0 :             assert_eq!(src_rel.dbnode, src_db_id);
     545              : 
     546            0 :             let nblocks = modification
     547            0 :                 .tline
     548            0 :                 .get_rel_size(src_rel, Version::Modified(modification), ctx)
     549            0 :                 .await?;
     550            0 :             let dst_rel = RelTag {
     551            0 :                 spcnode: tablespace_id,
     552            0 :                 dbnode: db_id,
     553            0 :                 relnode: src_rel.relnode,
     554            0 :                 forknum: src_rel.forknum,
     555            0 :             };
     556              : 
     557            0 :             modification.put_rel_creation(dst_rel, nblocks, ctx).await?;
     558              : 
     559              :             // Copy content
     560            0 :             debug!("copying rel {} to {}, {} blocks", src_rel, dst_rel, nblocks);
     561            0 :             for blknum in 0..nblocks {
     562              :                 // Sharding:
     563              :                 //  - src and dst are always on the same shard, because they differ only by dbNode, and
     564              :                 //    dbNode is not included in the hash inputs for sharding.
     565              :                 //  - This WAL command is replayed on all shards, but each shard only copies the blocks
     566              :                 //    that belong to it.
     567            0 :                 let src_key = rel_block_to_key(src_rel, blknum);
     568            0 :                 if !self.shard.is_key_local(&src_key) {
     569            0 :                     debug!(
     570            0 :                         "Skipping non-local key {} during XLOG_DBASE_CREATE",
     571              :                         src_key
     572              :                     );
     573            0 :                     continue;
     574            0 :                 }
     575            0 :                 debug!(
     576            0 :                     "copying block {} from {} ({}) to {}",
     577              :                     blknum, src_rel, src_key, dst_rel
     578              :                 );
     579              : 
     580            0 :                 let content = modification
     581            0 :                     .tline
     582            0 :                     .get_rel_page_at_lsn(
     583            0 :                         src_rel,
     584            0 :                         blknum,
     585            0 :                         Version::Modified(modification),
     586            0 :                         ctx,
     587            0 :                         crate::tenant::storage_layer::IoConcurrency::sequential(),
     588            0 :                     )
     589            0 :                     .await?;
     590            0 :                 modification.put_rel_page_image(dst_rel, blknum, content)?;
     591            0 :                 num_blocks_copied += 1;
     592              :             }
     593              : 
     594            0 :             num_rels_copied += 1;
     595              :         }
     596              : 
     597            0 :         info!(
     598            0 :             "Created database {}/{}, copied {} blocks in {} rels",
     599              :             tablespace_id, db_id, num_blocks_copied, num_rels_copied
     600              :         );
     601            0 :         Ok(())
     602            0 :     }
     603              : 
     604            0 :     async fn ingest_xlog_dbase_drop(
     605            0 :         &mut self,
     606            0 :         dbase_drop: DbaseDrop,
     607            0 :         modification: &mut DatadirModification<'_>,
     608            0 :         ctx: &RequestContext,
     609            0 :     ) -> Result<(), WalIngestError> {
     610              :         let DbaseDrop {
     611            0 :             db_id,
     612            0 :             tablespace_ids,
     613            0 :         } = dbase_drop;
     614            0 :         for tablespace_id in tablespace_ids {
     615            0 :             trace!("Drop db {}, {}", tablespace_id, db_id);
     616            0 :             modification.drop_dbdir(tablespace_id, db_id, ctx).await?;
     617              :         }
     618              : 
     619            0 :         Ok(())
     620            0 :     }
     621              : 
     622            8 :     async fn ingest_xlog_smgr_create(
     623            8 :         &mut self,
     624            8 :         create: SmgrCreate,
     625            8 :         modification: &mut DatadirModification<'_>,
     626            8 :         ctx: &RequestContext,
     627            8 :     ) -> Result<(), WalIngestError> {
     628            8 :         let SmgrCreate { rel } = create;
     629            8 :         self.put_rel_creation(modification, rel, ctx).await?;
     630            8 :         Ok(())
     631            8 :     }
     632              : 
     633              :     /// Subroutine of ingest_record(), to handle an XLOG_SMGR_TRUNCATE record.
     634              :     ///
     635              :     /// This is the same logic as in PostgreSQL's smgr_redo() function.
     636            0 :     async fn ingest_xlog_smgr_truncate(
     637            0 :         &mut self,
     638            0 :         truncate: XlSmgrTruncate,
     639            0 :         modification: &mut DatadirModification<'_>,
     640            0 :         ctx: &RequestContext,
     641            0 :     ) -> Result<(), WalIngestError> {
     642              :         let XlSmgrTruncate {
     643            0 :             blkno,
     644            0 :             rnode,
     645            0 :             flags,
     646            0 :         } = truncate;
     647              : 
     648            0 :         let spcnode = rnode.spcnode;
     649            0 :         let dbnode = rnode.dbnode;
     650            0 :         let relnode = rnode.relnode;
     651              : 
     652            0 :         if flags & pg_constants::SMGR_TRUNCATE_HEAP != 0 {
     653            0 :             let rel = RelTag {
     654            0 :                 spcnode,
     655            0 :                 dbnode,
     656            0 :                 relnode,
     657            0 :                 forknum: MAIN_FORKNUM,
     658            0 :             };
     659              : 
     660            0 :             self.put_rel_truncation(modification, rel, blkno, ctx)
     661            0 :                 .await?;
     662            0 :         }
     663            0 :         if flags & pg_constants::SMGR_TRUNCATE_FSM != 0 {
     664            0 :             let rel = RelTag {
     665            0 :                 spcnode,
     666            0 :                 dbnode,
     667            0 :                 relnode,
     668            0 :                 forknum: FSM_FORKNUM,
     669            0 :             };
     670              : 
     671              :             // Zero out the last remaining FSM page, if this shard owns it. We are not precise here,
     672              :             // and instead of digging in the FSM bitmap format we just clear the whole page.
     673            0 :             let fsm_logical_page_no = blkno / pg_constants::SLOTS_PER_FSM_PAGE;
     674            0 :             let mut fsm_physical_page_no = fsm_logical_to_physical(fsm_logical_page_no);
     675            0 :             if blkno % pg_constants::SLOTS_PER_FSM_PAGE != 0
     676            0 :                 && self
     677            0 :                     .shard
     678            0 :                     .is_key_local(&rel_block_to_key(rel, fsm_physical_page_no))
     679              :             {
     680            0 :                 modification.put_rel_page_image_zero(rel, fsm_physical_page_no)?;
     681            0 :                 fsm_physical_page_no += 1;
     682            0 :             }
     683              :             // Truncate this shard's view of the FSM relation size, if it even has one.
     684            0 :             let nblocks = get_relsize(modification, rel, ctx).await?.unwrap_or(0);
     685            0 :             if nblocks > fsm_physical_page_no {
     686            0 :                 self.put_rel_truncation(modification, rel, fsm_physical_page_no, ctx)
     687            0 :                     .await?;
     688            0 :             }
     689            0 :         }
     690            0 :         if flags & pg_constants::SMGR_TRUNCATE_VM != 0 {
     691            0 :             let rel = RelTag {
     692            0 :                 spcnode,
     693            0 :                 dbnode,
     694            0 :                 relnode,
     695            0 :                 forknum: VISIBILITYMAP_FORKNUM,
     696            0 :             };
     697              : 
     698              :             // last remaining block, byte, and bit
     699            0 :             let mut vm_page_no = blkno / (pg_constants::VM_HEAPBLOCKS_PER_PAGE as u32);
     700            0 :             let trunc_byte = blkno as usize % pg_constants::VM_HEAPBLOCKS_PER_PAGE
     701            0 :                 / pg_constants::VM_HEAPBLOCKS_PER_BYTE;
     702            0 :             let trunc_offs = blkno as usize % pg_constants::VM_HEAPBLOCKS_PER_BYTE
     703            0 :                 * pg_constants::VM_BITS_PER_HEAPBLOCK;
     704              : 
     705              :             // Unless the new size is exactly at a visibility map page boundary, the
     706              :             // tail bits in the last remaining map page, representing truncated heap
     707              :             // blocks, need to be cleared. This is not only tidy, but also necessary
     708              :             // because we don't get a chance to clear the bits if the heap is extended
     709              :             // again. Only do this on the shard that owns the page.
     710            0 :             if (trunc_byte != 0 || trunc_offs != 0)
     711            0 :                 && self.shard.is_key_local(&rel_block_to_key(rel, vm_page_no))
     712              :             {
     713            0 :                 modification.put_rel_wal_record(
     714            0 :                     rel,
     715            0 :                     vm_page_no,
     716            0 :                     NeonWalRecord::TruncateVisibilityMap {
     717            0 :                         trunc_byte,
     718            0 :                         trunc_offs,
     719            0 :                     },
     720            0 :                 )?;
     721            0 :                 vm_page_no += 1;
     722            0 :             }
     723              :             // Truncate this shard's view of the VM relation size, if it even has one.
     724            0 :             let nblocks = get_relsize(modification, rel, ctx).await?.unwrap_or(0);
     725            0 :             if nblocks > vm_page_no {
     726            0 :                 self.put_rel_truncation(modification, rel, vm_page_no, ctx)
     727            0 :                     .await?;
     728            0 :             }
     729            0 :         }
     730            0 :         Ok(())
     731            0 :     }
     732              : 
     733            4 :     fn warn_on_ingest_lag(
     734            4 :         &mut self,
     735            4 :         conf: &crate::config::PageServerConf,
     736            4 :         wal_timestamp: TimestampTz,
     737            4 :     ) {
     738            4 :         debug_assert_current_span_has_tenant_and_timeline_id();
     739            4 :         let now = SystemTime::now();
     740            4 :         let rate_limits = &mut self.warn_ingest_lag;
     741              : 
     742            4 :         let ts = enum_pgversion_dispatch!(&self.checkpoint, CheckPoint, _cp, {
     743            0 :             pgv::xlog_utils::try_from_pg_timestamp(wal_timestamp)
     744              :         });
     745              : 
     746            4 :         match ts {
     747            4 :             Ok(ts) => {
     748            4 :                 match now.duration_since(ts) {
     749            4 :                     Ok(lag) => {
     750            4 :                         if lag > conf.wait_lsn_timeout {
     751            4 :                             rate_limits.lag_msg_ratelimit.call2(|rate_limit_stats| {
     752            1 :                                 if let Some(cooldown) = self.attach_wal_lag_cooldown.get() {
     753            0 :                                     if std::time::Instant::now() < cooldown.active_until && lag <= cooldown.max_lag {
     754            0 :                                         return;
     755            0 :                                     }
     756            1 :                                 } else {
     757            1 :                                     // Still loading? We shouldn't be here
     758            1 :                                 }
     759            1 :                                 let lag = humantime::format_duration(lag);
     760            1 :                                 warn!(%rate_limit_stats, %lag, "ingesting record with timestamp lagging more than wait_lsn_timeout");
     761            1 :                             })
     762            0 :                         }
     763              :                     }
     764            0 :                     Err(e) => {
     765            0 :                         let delta_t = e.duration();
     766              :                         // determined by prod victoriametrics query: 1000 * (timestamp(node_time_seconds{neon_service="pageserver"}) - node_time_seconds)
     767              :                         // => https://www.robustperception.io/time-metric-from-the-node-exporter/
     768              :                         const IGNORED_DRIFT: Duration = Duration::from_millis(100);
     769            0 :                         if delta_t > IGNORED_DRIFT {
     770            0 :                             let delta_t = humantime::format_duration(delta_t);
     771            0 :                             rate_limits.future_lsn_msg_ratelimit.call2(|rate_limit_stats| {
     772            0 :                                 warn!(%rate_limit_stats, %delta_t, "ingesting record with timestamp from future");
     773            0 :                             })
     774            0 :                         }
     775              :                     }
     776              :                 };
     777              :             }
     778            0 :             Err(error) => {
     779            0 :                 rate_limits.timestamp_invalid_msg_ratelimit.call2(|rate_limit_stats| {
     780            0 :                     warn!(%rate_limit_stats, %error, "ingesting record with invalid timestamp, cannot calculate lag and will fail find-lsn-for-timestamp type queries");
     781            0 :                 })
     782              :             }
     783              :         }
     784            4 :     }
     785              : 
     786              :     /// Subroutine of ingest_record(), to handle an XLOG_XACT_* records.
     787              :     ///
     788            4 :     async fn ingest_xact_record(
     789            4 :         &mut self,
     790            4 :         record: XactRecord,
     791            4 :         modification: &mut DatadirModification<'_>,
     792            4 :         ctx: &RequestContext,
     793            4 :     ) -> Result<(), WalIngestError> {
     794            4 :         let (xact_common, is_commit, is_prepared) = match record {
     795            0 :             XactRecord::Prepare(XactPrepare { xl_xid, data }) => {
     796            0 :                 let xid: u64 = if modification.tline.pg_version >= PgMajorVersion::PG17 {
     797            0 :                     self.adjust_to_full_transaction_id(xl_xid)?
     798              :                 } else {
     799            0 :                     xl_xid as u64
     800              :                 };
     801            0 :                 return modification.put_twophase_file(xid, data, ctx).await;
     802              :             }
     803            4 :             XactRecord::Commit(common) => (common, true, false),
     804            0 :             XactRecord::Abort(common) => (common, false, false),
     805            0 :             XactRecord::CommitPrepared(common) => (common, true, true),
     806            0 :             XactRecord::AbortPrepared(common) => (common, false, true),
     807              :         };
     808              : 
     809              :         let XactCommon {
     810            4 :             parsed,
     811            4 :             origin_id,
     812            4 :             xl_xid,
     813            4 :             lsn,
     814            4 :         } = xact_common;
     815              : 
     816              :         // Record update of CLOG pages
     817            4 :         let mut pageno = parsed.xid / pg_constants::CLOG_XACTS_PER_PAGE;
     818            4 :         let mut segno = pageno / pg_constants::SLRU_PAGES_PER_SEGMENT;
     819            4 :         let mut rpageno = pageno % pg_constants::SLRU_PAGES_PER_SEGMENT;
     820            4 :         let mut page_xids: Vec<TransactionId> = vec![parsed.xid];
     821              : 
     822            4 :         self.warn_on_ingest_lag(modification.tline.conf, parsed.xact_time);
     823              : 
     824            4 :         for subxact in &parsed.subxacts {
     825            0 :             let subxact_pageno = subxact / pg_constants::CLOG_XACTS_PER_PAGE;
     826            0 :             if subxact_pageno != pageno {
     827              :                 // This subxact goes to different page. Write the record
     828              :                 // for all the XIDs on the previous page, and continue
     829              :                 // accumulating XIDs on this new page.
     830            0 :                 modification.put_slru_wal_record(
     831            0 :                     SlruKind::Clog,
     832            0 :                     segno,
     833            0 :                     rpageno,
     834            0 :                     if is_commit {
     835            0 :                         NeonWalRecord::ClogSetCommitted {
     836            0 :                             xids: page_xids,
     837            0 :                             timestamp: parsed.xact_time,
     838            0 :                         }
     839              :                     } else {
     840            0 :                         NeonWalRecord::ClogSetAborted { xids: page_xids }
     841              :                     },
     842            0 :                 )?;
     843            0 :                 page_xids = Vec::new();
     844            0 :             }
     845            0 :             pageno = subxact_pageno;
     846            0 :             segno = pageno / pg_constants::SLRU_PAGES_PER_SEGMENT;
     847            0 :             rpageno = pageno % pg_constants::SLRU_PAGES_PER_SEGMENT;
     848            0 :             page_xids.push(*subxact);
     849              :         }
     850            4 :         modification.put_slru_wal_record(
     851            4 :             SlruKind::Clog,
     852            4 :             segno,
     853            4 :             rpageno,
     854            4 :             if is_commit {
     855            4 :                 NeonWalRecord::ClogSetCommitted {
     856            4 :                     xids: page_xids,
     857            4 :                     timestamp: parsed.xact_time,
     858            4 :                 }
     859              :             } else {
     860            0 :                 NeonWalRecord::ClogSetAborted { xids: page_xids }
     861              :             },
     862            0 :         )?;
     863              : 
     864              :         // Group relations to drop by dbNode.  This map will contain all relations that _might_
     865              :         // exist, we will reduce it to which ones really exist later.  This map can be huge if
     866              :         // the transaction touches a huge number of relations (there is no bound on this in
     867              :         // postgres).
     868            4 :         let mut drop_relations: HashMap<(u32, u32), Vec<RelTag>> = HashMap::new();
     869              : 
     870            4 :         for xnode in &parsed.xnodes {
     871            0 :             for forknum in MAIN_FORKNUM..=INIT_FORKNUM {
     872            0 :                 let rel = RelTag {
     873            0 :                     forknum,
     874            0 :                     spcnode: xnode.spcnode,
     875            0 :                     dbnode: xnode.dbnode,
     876            0 :                     relnode: xnode.relnode,
     877            0 :                 };
     878            0 :                 drop_relations
     879            0 :                     .entry((xnode.spcnode, xnode.dbnode))
     880            0 :                     .or_default()
     881            0 :                     .push(rel);
     882            0 :             }
     883              :         }
     884              : 
     885              :         // Execute relation drops in a batch: the number may be huge, so deleting individually is prohibitively expensive
     886            4 :         modification.put_rel_drops(drop_relations, ctx).await?;
     887              : 
     888            4 :         if origin_id != 0 {
     889            0 :             modification
     890            0 :                 .set_replorigin(origin_id, parsed.origin_lsn)
     891            0 :                 .await?;
     892            4 :         }
     893              : 
     894            4 :         if is_prepared {
     895              :             // Remove twophase file. see RemoveTwoPhaseFile() in postgres code
     896            0 :             trace!(
     897            0 :                 "Drop twophaseFile for xid {} parsed_xact.xid {} here at {}",
     898              :                 xl_xid, parsed.xid, lsn,
     899              :             );
     900              : 
     901            0 :             let xid: u64 = if modification.tline.pg_version >= PgMajorVersion::PG17 {
     902            0 :                 self.adjust_to_full_transaction_id(parsed.xid)?
     903              :             } else {
     904            0 :                 parsed.xid as u64
     905              :             };
     906            0 :             modification.drop_twophase_file(xid, ctx).await?;
     907            4 :         }
     908              : 
     909            4 :         Ok(())
     910            4 :     }
     911              : 
     912            0 :     async fn ingest_clog_truncate(
     913            0 :         &mut self,
     914            0 :         truncate: ClogTruncate,
     915            0 :         modification: &mut DatadirModification<'_>,
     916            0 :         ctx: &RequestContext,
     917            0 :     ) -> Result<(), WalIngestError> {
     918              :         let ClogTruncate {
     919            0 :             pageno,
     920            0 :             oldest_xid,
     921            0 :             oldest_xid_db,
     922            0 :         } = truncate;
     923              : 
     924            0 :         info!(
     925            0 :             "RM_CLOG_ID truncate pageno {} oldestXid {} oldestXidDB {}",
     926              :             pageno, oldest_xid, oldest_xid_db
     927              :         );
     928              : 
     929              :         // In Postgres, oldestXid and oldestXidDB are updated in memory when the CLOG is
     930              :         // truncated, but a checkpoint record with the updated values isn't written until
     931              :         // later. In Neon, a server can start at any LSN, not just on a checkpoint record,
     932              :         // so we keep the oldestXid and oldestXidDB up-to-date.
     933            0 :         enum_pgversion_dispatch!(&mut self.checkpoint, CheckPoint, cp, {
     934            0 :             cp.oldestXid = oldest_xid;
     935            0 :             cp.oldestXidDB = oldest_xid_db;
     936            0 :         });
     937            0 :         self.checkpoint_modified = true;
     938              : 
     939              :         // TODO Treat AdvanceOldestClogXid() or write a comment why we don't need it
     940              : 
     941            0 :         let latest_page_number =
     942            0 :             enum_pgversion_dispatch!(self.checkpoint, CheckPoint, cp, { cp.nextXid.value }) as u32
     943              :                 / pg_constants::CLOG_XACTS_PER_PAGE;
     944              : 
     945              :         // Now delete all segments containing pages between xlrec.pageno
     946              :         // and latest_page_number.
     947              : 
     948              :         // First, make an important safety check:
     949              :         // the current endpoint page must not be eligible for removal.
     950              :         // See SimpleLruTruncate() in slru.c
     951            0 :         if dispatch_pgversion!(modification.tline.pg_version, {
     952            0 :             pgv::nonrelfile_utils::clogpage_precedes(latest_page_number, pageno)
     953              :         }) {
     954            0 :             info!("could not truncate directory pg_xact apparent wraparound");
     955            0 :             return Ok(());
     956            0 :         }
     957              : 
     958              :         // Iterate via SLRU CLOG segments and drop segments that we're ready to truncate
     959              :         //
     960              :         // We cannot pass 'lsn' to the Timeline.list_nonrels(), or it
     961              :         // will block waiting for the last valid LSN to advance up to
     962              :         // it. So we use the previous record's LSN in the get calls
     963              :         // instead.
     964            0 :         if modification.tline.get_shard_identity().is_shard_zero() {
     965            0 :             for segno in modification
     966            0 :                 .tline
     967            0 :                 .list_slru_segments(SlruKind::Clog, Version::Modified(modification), ctx)
     968            0 :                 .await?
     969              :             {
     970            0 :                 let segpage = segno * pg_constants::SLRU_PAGES_PER_SEGMENT;
     971              : 
     972            0 :                 let may_delete = dispatch_pgversion!(modification.tline.pg_version, {
     973            0 :                     pgv::nonrelfile_utils::slru_may_delete_clogsegment(segpage, pageno)
     974              :                 });
     975              : 
     976            0 :                 if may_delete {
     977            0 :                     modification
     978            0 :                         .drop_slru_segment(SlruKind::Clog, segno, ctx)
     979            0 :                         .await?;
     980            0 :                     trace!("Drop CLOG segment {:>04X}", segno);
     981            0 :                 }
     982              :             }
     983            0 :         }
     984              : 
     985            0 :         Ok(())
     986            0 :     }
     987              : 
     988            0 :     async fn ingest_clog_zero_page(
     989            0 :         &mut self,
     990            0 :         zero_page: ClogZeroPage,
     991            0 :         modification: &mut DatadirModification<'_>,
     992            0 :         ctx: &RequestContext,
     993            0 :     ) -> Result<(), WalIngestError> {
     994            0 :         let ClogZeroPage { segno, rpageno } = zero_page;
     995              : 
     996            0 :         self.put_slru_page_image(
     997            0 :             modification,
     998            0 :             SlruKind::Clog,
     999            0 :             segno,
    1000            0 :             rpageno,
    1001            0 :             ZERO_PAGE.clone(),
    1002            0 :             ctx,
    1003            0 :         )
    1004            0 :         .await
    1005            0 :     }
    1006              : 
    1007            0 :     fn ingest_multixact_create(
    1008            0 :         &mut self,
    1009            0 :         modification: &mut DatadirModification,
    1010            0 :         xlrec: &XlMultiXactCreate,
    1011            0 :     ) -> Result<(), WalIngestError> {
    1012              :         // Create WAL record for updating the multixact-offsets page
    1013            0 :         let pageno = xlrec.mid / pg_constants::MULTIXACT_OFFSETS_PER_PAGE as u32;
    1014            0 :         let segno = pageno / pg_constants::SLRU_PAGES_PER_SEGMENT;
    1015            0 :         let rpageno = pageno % pg_constants::SLRU_PAGES_PER_SEGMENT;
    1016              : 
    1017            0 :         modification.put_slru_wal_record(
    1018            0 :             SlruKind::MultiXactOffsets,
    1019            0 :             segno,
    1020            0 :             rpageno,
    1021            0 :             NeonWalRecord::MultixactOffsetCreate {
    1022            0 :                 mid: xlrec.mid,
    1023            0 :                 moff: xlrec.moff,
    1024            0 :             },
    1025            0 :         )?;
    1026              : 
    1027              :         // Create WAL records for the update of each affected multixact-members page
    1028            0 :         let mut members = xlrec.members.iter();
    1029            0 :         let mut offset = xlrec.moff;
    1030              :         loop {
    1031            0 :             let pageno = offset / pg_constants::MULTIXACT_MEMBERS_PER_PAGE as u32;
    1032              : 
    1033              :             // How many members fit on this page?
    1034            0 :             let page_remain = pg_constants::MULTIXACT_MEMBERS_PER_PAGE as u32
    1035            0 :                 - offset % pg_constants::MULTIXACT_MEMBERS_PER_PAGE as u32;
    1036              : 
    1037            0 :             let mut this_page_members: Vec<MultiXactMember> = Vec::new();
    1038            0 :             for _ in 0..page_remain {
    1039            0 :                 if let Some(m) = members.next() {
    1040            0 :                     this_page_members.push(m.clone());
    1041            0 :                 } else {
    1042            0 :                     break;
    1043              :                 }
    1044              :             }
    1045            0 :             if this_page_members.is_empty() {
    1046              :                 // all done
    1047            0 :                 break;
    1048            0 :             }
    1049            0 :             let n_this_page = this_page_members.len();
    1050              : 
    1051            0 :             modification.put_slru_wal_record(
    1052            0 :                 SlruKind::MultiXactMembers,
    1053            0 :                 pageno / pg_constants::SLRU_PAGES_PER_SEGMENT,
    1054            0 :                 pageno % pg_constants::SLRU_PAGES_PER_SEGMENT,
    1055            0 :                 NeonWalRecord::MultixactMembersCreate {
    1056            0 :                     moff: offset,
    1057            0 :                     members: this_page_members,
    1058            0 :                 },
    1059            0 :             )?;
    1060              : 
    1061              :             // Note: The multixact members can wrap around, even within one WAL record.
    1062            0 :             offset = offset.wrapping_add(n_this_page as u32);
    1063              :         }
    1064            0 :         let next_offset = offset;
    1065            0 :         assert!(xlrec.moff.wrapping_add(xlrec.nmembers) == next_offset);
    1066              : 
    1067              :         // Update next-multi-xid and next-offset
    1068              :         //
    1069              :         // NB: In PostgreSQL, the next-multi-xid stored in the control file is allowed to
    1070              :         // go to 0, and it's fixed up by skipping to FirstMultiXactId in functions that
    1071              :         // read it, like GetNewMultiXactId(). This is different from how nextXid is
    1072              :         // incremented! nextXid skips over < FirstNormalTransactionId when the the value
    1073              :         // is stored, so it's never 0 in a checkpoint.
    1074              :         //
    1075              :         // I don't know why it's done that way, it seems less error-prone to skip over 0
    1076              :         // when the value is stored rather than when it's read. But let's do it the same
    1077              :         // way here.
    1078            0 :         let next_multi_xid = xlrec.mid.wrapping_add(1);
    1079              : 
    1080            0 :         if self
    1081            0 :             .checkpoint
    1082            0 :             .update_next_multixid(next_multi_xid, next_offset)
    1083            0 :         {
    1084            0 :             self.checkpoint_modified = true;
    1085            0 :         }
    1086              : 
    1087              :         // Also update the next-xid with the highest member. According to the comments in
    1088              :         // multixact_redo(), this shouldn't be necessary, but let's do the same here.
    1089            0 :         let max_mbr_xid = xlrec.members.iter().fold(None, |acc, mbr| {
    1090            0 :             if let Some(max_xid) = acc {
    1091            0 :                 if mbr.xid.wrapping_sub(max_xid) as i32 > 0 {
    1092            0 :                     Some(mbr.xid)
    1093              :                 } else {
    1094            0 :                     acc
    1095              :                 }
    1096              :             } else {
    1097            0 :                 Some(mbr.xid)
    1098              :             }
    1099            0 :         });
    1100              : 
    1101            0 :         if let Some(max_xid) = max_mbr_xid {
    1102            0 :             if self.checkpoint.update_next_xid(max_xid) {
    1103            0 :                 self.checkpoint_modified = true;
    1104            0 :             }
    1105            0 :         }
    1106            0 :         Ok(())
    1107            0 :     }
    1108              : 
    1109            0 :     async fn ingest_multixact_truncate(
    1110            0 :         &mut self,
    1111            0 :         modification: &mut DatadirModification<'_>,
    1112            0 :         xlrec: &XlMultiXactTruncate,
    1113            0 :         ctx: &RequestContext,
    1114            0 :     ) -> Result<(), WalIngestError> {
    1115            0 :         let (maxsegment, startsegment, endsegment) =
    1116            0 :             enum_pgversion_dispatch!(&mut self.checkpoint, CheckPoint, cp, {
    1117            0 :                 cp.oldestMulti = xlrec.end_trunc_off;
    1118            0 :                 cp.oldestMultiDB = xlrec.oldest_multi_db;
    1119            0 :                 let maxsegment: i32 = pgv::nonrelfile_utils::mx_offset_to_member_segment(
    1120              :                     pg_constants::MAX_MULTIXACT_OFFSET,
    1121              :                 );
    1122            0 :                 let startsegment: i32 =
    1123            0 :                     pgv::nonrelfile_utils::mx_offset_to_member_segment(xlrec.start_trunc_memb);
    1124            0 :                 let endsegment: i32 =
    1125            0 :                     pgv::nonrelfile_utils::mx_offset_to_member_segment(xlrec.end_trunc_memb);
    1126            0 :                 (maxsegment, startsegment, endsegment)
    1127              :             });
    1128              : 
    1129            0 :         self.checkpoint_modified = true;
    1130              : 
    1131              :         // PerformMembersTruncation
    1132            0 :         let mut segment: i32 = startsegment;
    1133              : 
    1134              :         // Delete all the segments except the last one. The last segment can still
    1135              :         // contain, possibly partially, valid data.
    1136            0 :         if modification.tline.get_shard_identity().is_shard_zero() {
    1137            0 :             while segment != endsegment {
    1138            0 :                 modification
    1139            0 :                     .drop_slru_segment(SlruKind::MultiXactMembers, segment as u32, ctx)
    1140            0 :                     .await?;
    1141              : 
    1142              :                 /* move to next segment, handling wraparound correctly */
    1143            0 :                 if segment == maxsegment {
    1144            0 :                     segment = 0;
    1145            0 :                 } else {
    1146            0 :                     segment += 1;
    1147            0 :                 }
    1148              :             }
    1149            0 :         }
    1150              : 
    1151              :         // Truncate offsets
    1152              :         // FIXME: this did not handle wraparound correctly
    1153              : 
    1154            0 :         Ok(())
    1155            0 :     }
    1156              : 
    1157            0 :     async fn ingest_multixact_zero_page(
    1158            0 :         &mut self,
    1159            0 :         zero_page: MultiXactZeroPage,
    1160            0 :         modification: &mut DatadirModification<'_>,
    1161            0 :         ctx: &RequestContext,
    1162            0 :     ) -> Result<(), WalIngestError> {
    1163              :         let MultiXactZeroPage {
    1164            0 :             slru_kind,
    1165            0 :             segno,
    1166            0 :             rpageno,
    1167            0 :         } = zero_page;
    1168            0 :         self.put_slru_page_image(
    1169            0 :             modification,
    1170            0 :             slru_kind,
    1171            0 :             segno,
    1172            0 :             rpageno,
    1173            0 :             ZERO_PAGE.clone(),
    1174            0 :             ctx,
    1175            0 :         )
    1176            0 :         .await
    1177            0 :     }
    1178              : 
    1179            0 :     async fn ingest_relmap_update(
    1180            0 :         &mut self,
    1181            0 :         update: RelmapUpdate,
    1182            0 :         modification: &mut DatadirModification<'_>,
    1183            0 :         ctx: &RequestContext,
    1184            0 :     ) -> Result<(), WalIngestError> {
    1185            0 :         let RelmapUpdate { update, buf } = update;
    1186              : 
    1187            0 :         modification
    1188            0 :             .put_relmap_file(update.tsid, update.dbid, buf, ctx)
    1189            0 :             .await
    1190            0 :     }
    1191              : 
    1192           15 :     async fn ingest_raw_xlog_record(
    1193           15 :         &mut self,
    1194           15 :         raw_record: RawXlogRecord,
    1195           15 :         modification: &mut DatadirModification<'_>,
    1196           15 :         ctx: &RequestContext,
    1197           15 :     ) -> Result<(), WalIngestError> {
    1198           15 :         let RawXlogRecord { info, lsn, mut buf } = raw_record;
    1199           15 :         let pg_version = modification.tline.pg_version;
    1200              : 
    1201           15 :         if info == pg_constants::XLOG_PARAMETER_CHANGE {
    1202            1 :             if let CheckPoint::V17(cp) = &mut self.checkpoint {
    1203            0 :                 let rec = v17::XlParameterChange::decode(&mut buf);
    1204            0 :                 cp.wal_level = rec.wal_level;
    1205            0 :                 self.checkpoint_modified = true;
    1206            1 :             }
    1207           14 :         } else if info == pg_constants::XLOG_END_OF_RECOVERY {
    1208            0 :             if let CheckPoint::V17(cp) = &mut self.checkpoint {
    1209            0 :                 let rec = v17::XlEndOfRecovery::decode(&mut buf);
    1210            0 :                 cp.wal_level = rec.wal_level;
    1211            0 :                 self.checkpoint_modified = true;
    1212            0 :             }
    1213           14 :         }
    1214              : 
    1215           15 :         enum_pgversion_dispatch!(&mut self.checkpoint, CheckPoint, cp, {
    1216            0 :             if info == pg_constants::XLOG_NEXTOID {
    1217            0 :                 let next_oid = buf.get_u32_le();
    1218            0 :                 if cp.nextOid != next_oid {
    1219            0 :                     cp.nextOid = next_oid;
    1220            0 :                     self.checkpoint_modified = true;
    1221            0 :                 }
    1222            0 :             } else if info == pg_constants::XLOG_CHECKPOINT_ONLINE
    1223            0 :                 || info == pg_constants::XLOG_CHECKPOINT_SHUTDOWN
    1224              :             {
    1225            0 :                 let mut checkpoint_bytes = [0u8; pgv::xlog_utils::SIZEOF_CHECKPOINT];
    1226            0 :                 buf.copy_to_slice(&mut checkpoint_bytes);
    1227            0 :                 let xlog_checkpoint = pgv::CheckPoint::decode(&checkpoint_bytes)?;
    1228            0 :                 trace!(
    1229            0 :                     "xlog_checkpoint.oldestXid={}, checkpoint.oldestXid={}",
    1230              :                     xlog_checkpoint.oldestXid, cp.oldestXid
    1231              :                 );
    1232            0 :                 if (cp.oldestXid.wrapping_sub(xlog_checkpoint.oldestXid) as i32) < 0 {
    1233            0 :                     cp.oldestXid = xlog_checkpoint.oldestXid;
    1234            0 :                 }
    1235            0 :                 trace!(
    1236            0 :                     "xlog_checkpoint.oldestActiveXid={}, checkpoint.oldestActiveXid={}",
    1237              :                     xlog_checkpoint.oldestActiveXid, cp.oldestActiveXid
    1238              :                 );
    1239              : 
    1240              :                 // A shutdown checkpoint has `oldestActiveXid == InvalidTransactionid`,
    1241              :                 // because at shutdown, all in-progress transactions will implicitly
    1242              :                 // end. Postgres startup code knows that, and allows hot standby to start
    1243              :                 // immediately from a shutdown checkpoint.
    1244              :                 //
    1245              :                 // In Neon, Postgres hot standby startup always behaves as if starting from
    1246              :                 // an online checkpoint. It needs a valid `oldestActiveXid` value, so
    1247              :                 // instead of overwriting self.checkpoint.oldestActiveXid with
    1248              :                 // InvalidTransactionid from the checkpoint WAL record, update it to a
    1249              :                 // proper value, knowing that there are no in-progress transactions at this
    1250              :                 // point, except for prepared transactions.
    1251              :                 //
    1252              :                 // See also the neon code changes in the InitWalRecovery() function.
    1253            0 :                 if xlog_checkpoint.oldestActiveXid == pg_constants::INVALID_TRANSACTION_ID
    1254            0 :                     && info == pg_constants::XLOG_CHECKPOINT_SHUTDOWN
    1255              :                 {
    1256            0 :                     let oldest_active_xid = if pg_version >= PgMajorVersion::PG17 {
    1257            0 :                         let mut oldest_active_full_xid = cp.nextXid.value;
    1258            0 :                         for xid in modification.tline.list_twophase_files(lsn, ctx).await? {
    1259            0 :                             if xid < oldest_active_full_xid {
    1260            0 :                                 oldest_active_full_xid = xid;
    1261            0 :                             }
    1262              :                         }
    1263            0 :                         oldest_active_full_xid as u32
    1264              :                     } else {
    1265            0 :                         let mut oldest_active_xid = cp.nextXid.value as u32;
    1266            0 :                         for xid in modification.tline.list_twophase_files(lsn, ctx).await? {
    1267            0 :                             let narrow_xid = xid as u32;
    1268            0 :                             if (narrow_xid.wrapping_sub(oldest_active_xid) as i32) < 0 {
    1269            0 :                                 oldest_active_xid = narrow_xid;
    1270            0 :                             }
    1271              :                         }
    1272            0 :                         oldest_active_xid
    1273              :                     };
    1274            0 :                     cp.oldestActiveXid = oldest_active_xid;
    1275            0 :                 } else {
    1276            0 :                     cp.oldestActiveXid = xlog_checkpoint.oldestActiveXid;
    1277            0 :                 }
    1278              :                 // NB: We abuse the Checkpoint.redo field:
    1279              :                 //
    1280              :                 // - In PostgreSQL, the Checkpoint struct doesn't store the information
    1281              :                 //   of whether this is an online checkpoint or a shutdown checkpoint. It's
    1282              :                 //   stored in the XLOG info field of the WAL record, shutdown checkpoints
    1283              :                 //   use record type XLOG_CHECKPOINT_SHUTDOWN and online checkpoints use
    1284              :                 //   XLOG_CHECKPOINT_ONLINE. We don't store the original WAL record headers
    1285              :                 //   in the pageserver, however.
    1286              :                 //
    1287              :                 // - In PostgreSQL, the Checkpoint.redo field stores the *start* of the
    1288              :                 //   checkpoint record, if it's a shutdown checkpoint. But when we are
    1289              :                 //   starting from a shutdown checkpoint, the basebackup LSN is the *end*
    1290              :                 //   of the shutdown checkpoint WAL record. That makes it difficult to
    1291              :                 //   correctly detect whether we're starting from a shutdown record or
    1292              :                 //   not.
    1293              :                 //
    1294              :                 // To address both of those issues, we store 0 in the redo field if it's
    1295              :                 // an online checkpoint record, and the record's *end* LSN if it's a
    1296              :                 // shutdown checkpoint. We don't need the original redo pointer in neon,
    1297              :                 // because we don't perform WAL replay at startup anyway, so we can get
    1298              :                 // away with abusing the redo field like this.
    1299              :                 //
    1300              :                 // XXX: Ideally, we would persist the extra information in a more
    1301              :                 // explicit format, rather than repurpose the fields of the Postgres
    1302              :                 // struct like this. However, we already have persisted data like this,
    1303              :                 // so we need to maintain backwards compatibility.
    1304              :                 //
    1305              :                 // NB: We didn't originally have this convention, so there are still old
    1306              :                 // persisted records that didn't do this. Before, we didn't update the
    1307              :                 // persisted redo field at all. That means that old records have a bogus
    1308              :                 // redo pointer that points to some old value, from the checkpoint record
    1309              :                 // that was originally imported from the data directory. If it was a
    1310              :                 // project created in Neon, that means it points to the first checkpoint
    1311              :                 // after initdb. That's OK for our purposes: all such old checkpoints are
    1312              :                 // treated as old online checkpoints when the basebackup is created.
    1313            0 :                 cp.redo = if info == pg_constants::XLOG_CHECKPOINT_SHUTDOWN {
    1314              :                     // Store the *end* LSN of the checkpoint record. Or to be precise,
    1315              :                     // the start LSN of the *next* record, i.e. if the record ends
    1316              :                     // exactly at page boundary, the redo LSN points to just after the
    1317              :                     // page header on the next page.
    1318            0 :                     lsn.into()
    1319              :                 } else {
    1320            0 :                     Lsn::INVALID.into()
    1321              :                 };
    1322              : 
    1323              :                 // Write a new checkpoint key-value pair on every checkpoint record, even
    1324              :                 // if nothing really changed. Not strictly required, but it seems nice to
    1325              :                 // have some trace of the checkpoint records in the layer files at the same
    1326              :                 // LSNs.
    1327            0 :                 self.checkpoint_modified = true;
    1328            0 :             }
    1329              :         });
    1330              : 
    1331           15 :         if info == pg_constants::XLOG_CHECKPOINT_SHUTDOWN {
    1332            1 :             modification.tline.prepare_basebackup(lsn);
    1333           14 :         }
    1334              : 
    1335           15 :         Ok(())
    1336           15 :     }
    1337              : 
    1338            0 :     async fn ingest_logical_message_put(
    1339            0 :         &mut self,
    1340            0 :         put: PutLogicalMessage,
    1341            0 :         modification: &mut DatadirModification<'_>,
    1342            0 :         ctx: &RequestContext,
    1343            0 :     ) -> Result<(), WalIngestError> {
    1344            0 :         let PutLogicalMessage { path, buf } = put;
    1345            0 :         modification.put_file(path.as_str(), &buf, ctx).await
    1346            0 :     }
    1347              : 
    1348            0 :     fn ingest_standby_record(&mut self, record: StandbyRecord) -> Result<(), WalIngestError> {
    1349            0 :         match record {
    1350            0 :             StandbyRecord::RunningXacts(running_xacts) => {
    1351            0 :                 enum_pgversion_dispatch!(&mut self.checkpoint, CheckPoint, cp, {
    1352            0 :                     cp.oldestActiveXid = running_xacts.oldest_running_xid;
    1353            0 :                 });
    1354              : 
    1355            0 :                 self.checkpoint_modified = true;
    1356              :             }
    1357              :         }
    1358              : 
    1359            0 :         Ok(())
    1360            0 :     }
    1361              : 
    1362            0 :     async fn ingest_replorigin_record(
    1363            0 :         &mut self,
    1364            0 :         record: ReploriginRecord,
    1365            0 :         modification: &mut DatadirModification<'_>,
    1366            0 :     ) -> Result<(), WalIngestError> {
    1367            0 :         match record {
    1368            0 :             ReploriginRecord::Set(set) => {
    1369            0 :                 modification
    1370            0 :                     .set_replorigin(set.node_id, set.remote_lsn)
    1371            0 :                     .await?;
    1372              :             }
    1373            0 :             ReploriginRecord::Drop(drop) => {
    1374            0 :                 modification.drop_replorigin(drop.node_id).await?;
    1375              :             }
    1376              :         }
    1377              : 
    1378            0 :         Ok(())
    1379            0 :     }
    1380              : 
    1381            9 :     async fn put_rel_creation(
    1382            9 :         &mut self,
    1383            9 :         modification: &mut DatadirModification<'_>,
    1384            9 :         rel: RelTag,
    1385            9 :         ctx: &RequestContext,
    1386            9 :     ) -> Result<(), WalIngestError> {
    1387            9 :         modification.put_rel_creation(rel, 0, ctx).await?;
    1388            9 :         Ok(())
    1389            9 :     }
    1390              : 
    1391              :     #[cfg(test)]
    1392       136201 :     async fn put_rel_page_image(
    1393       136201 :         &mut self,
    1394       136201 :         modification: &mut DatadirModification<'_>,
    1395       136201 :         rel: RelTag,
    1396       136201 :         blknum: BlockNumber,
    1397       136201 :         img: Bytes,
    1398       136201 :         ctx: &RequestContext,
    1399       136201 :     ) -> Result<(), WalIngestError> {
    1400       136201 :         self.handle_rel_extend(modification, rel, blknum, ctx)
    1401       136201 :             .await?;
    1402       136201 :         modification.put_rel_page_image(rel, blknum, img)?;
    1403       136201 :         Ok(())
    1404       136201 :     }
    1405              : 
    1406            6 :     async fn put_rel_wal_record(
    1407            6 :         &mut self,
    1408            6 :         modification: &mut DatadirModification<'_>,
    1409            6 :         rel: RelTag,
    1410            6 :         blknum: BlockNumber,
    1411            6 :         rec: NeonWalRecord,
    1412            6 :         ctx: &RequestContext,
    1413            6 :     ) -> Result<(), WalIngestError> {
    1414            6 :         self.handle_rel_extend(modification, rel, blknum, ctx)
    1415            6 :             .await?;
    1416            6 :         modification.put_rel_wal_record(rel, blknum, rec)?;
    1417            6 :         Ok(())
    1418            6 :     }
    1419              : 
    1420         3006 :     async fn put_rel_truncation(
    1421         3006 :         &mut self,
    1422         3006 :         modification: &mut DatadirModification<'_>,
    1423         3006 :         rel: RelTag,
    1424         3006 :         nblocks: BlockNumber,
    1425         3006 :         ctx: &RequestContext,
    1426         3006 :     ) -> Result<(), WalIngestError> {
    1427         3006 :         modification.put_rel_truncation(rel, nblocks, ctx).await?;
    1428         3006 :         Ok(())
    1429         3006 :     }
    1430              : 
    1431       136207 :     async fn handle_rel_extend(
    1432       136207 :         &mut self,
    1433       136207 :         modification: &mut DatadirModification<'_>,
    1434       136207 :         rel: RelTag,
    1435       136207 :         blknum: BlockNumber,
    1436       136207 :         ctx: &RequestContext,
    1437       136207 :     ) -> Result<(), WalIngestError> {
    1438       136207 :         let new_nblocks = blknum + 1;
    1439              :         // Check if the relation exists. We implicitly create relations on first
    1440              :         // record.
    1441       136207 :         let old_nblocks = modification.create_relation_if_required(rel, ctx).await?;
    1442              : 
    1443       136207 :         if new_nblocks > old_nblocks {
    1444              :             //info!("extending {} {} to {}", rel, old_nblocks, new_nblocks);
    1445       136199 :             modification.put_rel_extend(rel, new_nblocks, ctx).await?;
    1446              : 
    1447       136199 :             let mut key = rel_block_to_key(rel, blknum);
    1448              : 
    1449              :             // fill the gap with zeros
    1450       136199 :             let mut gap_blocks_filled: u64 = 0;
    1451       136199 :             for gap_blknum in old_nblocks..blknum {
    1452         1499 :                 key.field6 = gap_blknum;
    1453              : 
    1454         1499 :                 if self.shard.get_shard_number(&key) != self.shard.number {
    1455            0 :                     continue;
    1456         1499 :                 }
    1457              : 
    1458         1499 :                 modification.put_rel_page_image_zero(rel, gap_blknum)?;
    1459         1499 :                 gap_blocks_filled += 1;
    1460              :             }
    1461              : 
    1462       136199 :             WAL_INGEST
    1463       136199 :                 .gap_blocks_zeroed_on_rel_extend
    1464       136199 :                 .inc_by(gap_blocks_filled);
    1465              : 
    1466              :             // Log something when relation extends cause use to fill gaps
    1467              :             // with zero pages. Logging is rate limited per pg version to
    1468              :             // avoid skewing.
    1469       136199 :             if gap_blocks_filled > 0 {
    1470              :                 use std::sync::Mutex;
    1471              : 
    1472              :                 use once_cell::sync::Lazy;
    1473              :                 use utils::rate_limit::RateLimit;
    1474              : 
    1475              :                 struct RateLimitPerPgVersion {
    1476              :                     rate_limiters: [Lazy<Mutex<RateLimit>>; 4],
    1477              :                 }
    1478              : 
    1479              :                 impl RateLimitPerPgVersion {
    1480            0 :                     const fn new() -> Self {
    1481              :                         Self {
    1482              :                             rate_limiters: [const {
    1483            1 :                                 Lazy::new(|| Mutex::new(RateLimit::new(Duration::from_secs(30))))
    1484              :                             }; 4],
    1485              :                         }
    1486            0 :                     }
    1487              : 
    1488            2 :                     const fn rate_limiter(
    1489            2 :                         &self,
    1490            2 :                         pg_version: PgMajorVersion,
    1491            2 :                     ) -> Option<&Lazy<Mutex<RateLimit>>> {
    1492              :                         const MIN_PG_VERSION: u32 = PgMajorVersion::PG14.major_version_num();
    1493              :                         const MAX_PG_VERSION: u32 = PgMajorVersion::PG17.major_version_num();
    1494            2 :                         let pg_version = pg_version.major_version_num();
    1495              : 
    1496            2 :                         if pg_version < MIN_PG_VERSION || pg_version > MAX_PG_VERSION {
    1497            0 :                             return None;
    1498            2 :                         }
    1499              : 
    1500            2 :                         Some(&self.rate_limiters[(pg_version - MIN_PG_VERSION) as usize])
    1501            2 :                     }
    1502              :                 }
    1503              : 
    1504              :                 static LOGGED: RateLimitPerPgVersion = RateLimitPerPgVersion::new();
    1505            2 :                 if let Some(rate_limiter) = LOGGED.rate_limiter(modification.tline.pg_version) {
    1506            2 :                     if let Ok(mut locked) = rate_limiter.try_lock() {
    1507            2 :                         locked.call(|| {
    1508            1 :                             info!(
    1509            0 :                                 lsn=%modification.get_lsn(),
    1510              :                                 pg_version=%modification.tline.pg_version,
    1511              :                                 rel=%rel,
    1512            0 :                                 "Filled {} gap blocks on rel extend to {} from {}",
    1513              :                                 gap_blocks_filled,
    1514              :                                 new_nblocks,
    1515              :                                 old_nblocks);
    1516            1 :                         });
    1517            0 :                     }
    1518            0 :                 }
    1519       136197 :             }
    1520            8 :         }
    1521       136207 :         Ok(())
    1522       136207 :     }
    1523              : 
    1524            0 :     async fn put_slru_page_image(
    1525            0 :         &mut self,
    1526            0 :         modification: &mut DatadirModification<'_>,
    1527            0 :         kind: SlruKind,
    1528            0 :         segno: u32,
    1529            0 :         blknum: BlockNumber,
    1530            0 :         img: Bytes,
    1531            0 :         ctx: &RequestContext,
    1532            0 :     ) -> Result<(), WalIngestError> {
    1533            0 :         if !self.shard.is_shard_zero() {
    1534            0 :             return Ok(());
    1535            0 :         }
    1536              : 
    1537            0 :         self.handle_slru_extend(modification, kind, segno, blknum, ctx)
    1538            0 :             .await?;
    1539            0 :         modification.put_slru_page_image(kind, segno, blknum, img)?;
    1540            0 :         Ok(())
    1541            0 :     }
    1542              : 
    1543            0 :     async fn handle_slru_extend(
    1544            0 :         &mut self,
    1545            0 :         modification: &mut DatadirModification<'_>,
    1546            0 :         kind: SlruKind,
    1547            0 :         segno: u32,
    1548            0 :         blknum: BlockNumber,
    1549            0 :         ctx: &RequestContext,
    1550            0 :     ) -> Result<(), WalIngestError> {
    1551              :         // we don't use a cache for this like we do for relations. SLRUS are explcitly
    1552              :         // extended with ZEROPAGE records, not with commit records, so it happens
    1553              :         // a lot less frequently.
    1554              : 
    1555            0 :         let new_nblocks = blknum + 1;
    1556              :         // Check if the relation exists. We implicitly create relations on first
    1557              :         // record.
    1558              :         // TODO: would be nice if to be more explicit about it
    1559            0 :         let old_nblocks = if !modification
    1560            0 :             .tline
    1561            0 :             .get_slru_segment_exists(kind, segno, Version::Modified(modification), ctx)
    1562            0 :             .await?
    1563              :         {
    1564              :             // create it with 0 size initially, the logic below will extend it
    1565            0 :             modification
    1566            0 :                 .put_slru_segment_creation(kind, segno, 0, ctx)
    1567            0 :                 .await?;
    1568            0 :             0
    1569              :         } else {
    1570            0 :             modification
    1571            0 :                 .tline
    1572            0 :                 .get_slru_segment_size(kind, segno, Version::Modified(modification), ctx)
    1573            0 :                 .await?
    1574              :         };
    1575              : 
    1576            0 :         if new_nblocks > old_nblocks {
    1577            0 :             trace!(
    1578            0 :                 "extending SLRU {:?} seg {} from {} to {} blocks",
    1579              :                 kind, segno, old_nblocks, new_nblocks
    1580              :             );
    1581            0 :             modification.put_slru_extend(kind, segno, new_nblocks)?;
    1582              : 
    1583              :             // fill the gap with zeros
    1584            0 :             for gap_blknum in old_nblocks..blknum {
    1585            0 :                 modification.put_slru_page_image_zero(kind, segno, gap_blknum)?;
    1586              :             }
    1587            0 :         }
    1588            0 :         Ok(())
    1589            0 :     }
    1590              : }
    1591              : 
    1592              : /// Returns the size of the relation as of this modification, or None if the relation doesn't exist.
    1593              : ///
    1594              : /// This is only accurate on shard 0. On other shards, it will return the size up to the highest
    1595              : /// page number stored in the shard, or None if the shard does not have any pages for it.
    1596            6 : async fn get_relsize(
    1597            6 :     modification: &DatadirModification<'_>,
    1598            6 :     rel: RelTag,
    1599            6 :     ctx: &RequestContext,
    1600            6 : ) -> Result<Option<BlockNumber>, PageReconstructError> {
    1601            6 :     if !modification
    1602            6 :         .tline
    1603            6 :         .get_rel_exists(rel, Version::Modified(modification), ctx)
    1604            6 :         .await?
    1605              :     {
    1606            0 :         return Ok(None);
    1607            6 :     }
    1608            6 :     modification
    1609            6 :         .tline
    1610            6 :         .get_rel_size(rel, Version::Modified(modification), ctx)
    1611            6 :         .await
    1612            6 :         .map(Some)
    1613            6 : }
    1614              : 
    1615              : #[allow(clippy::bool_assert_comparison)]
    1616              : #[cfg(test)]
    1617              : mod tests {
    1618              :     use anyhow::Result;
    1619              :     use postgres_ffi::PgMajorVersion;
    1620              :     use postgres_ffi::RELSEG_SIZE;
    1621              : 
    1622              :     use super::*;
    1623              :     use crate::DEFAULT_PG_VERSION;
    1624              :     use crate::tenant::harness::*;
    1625              :     use crate::tenant::remote_timeline_client::{INITDB_PATH, remote_initdb_archive_path};
    1626              :     use crate::tenant::storage_layer::IoConcurrency;
    1627              : 
    1628              :     /// Arbitrary relation tag, for testing.
    1629              :     const TESTREL_A: RelTag = RelTag {
    1630              :         spcnode: 0,
    1631              :         dbnode: 111,
    1632              :         relnode: 1000,
    1633              :         forknum: 0,
    1634              :     };
    1635              : 
    1636            6 :     fn assert_current_logical_size(_timeline: &Timeline, _lsn: Lsn) {
    1637              :         // TODO
    1638            6 :     }
    1639              : 
    1640              :     #[tokio::test]
    1641            1 :     async fn test_zeroed_checkpoint_decodes_correctly() -> Result<(), anyhow::Error> {
    1642            5 :         for i in PgMajorVersion::ALL {
    1643            4 :             dispatch_pgversion!(i, {
    1644            1 :                 pgv::CheckPoint::decode(&pgv::ZERO_CHECKPOINT)?;
    1645            1 :             });
    1646            1 :         }
    1647            1 : 
    1648            1 :         Ok(())
    1649            1 :     }
    1650              : 
    1651            4 :     async fn init_walingest_test(tline: &Timeline, ctx: &RequestContext) -> Result<WalIngest> {
    1652            4 :         let mut m = tline.begin_modification(Lsn(0x10));
    1653            4 :         m.put_checkpoint(dispatch_pgversion!(
    1654            4 :             tline.pg_version,
    1655            0 :             pgv::ZERO_CHECKPOINT.clone()
    1656            0 :         ))?;
    1657            4 :         m.put_relmap_file(0, 111, Bytes::from(""), ctx).await?; // dummy relmapper file
    1658            4 :         m.commit(ctx).await?;
    1659            4 :         let walingest = WalIngest::new(tline, Lsn(0x10), ctx).await?;
    1660              : 
    1661            4 :         Ok(walingest)
    1662            4 :     }
    1663              : 
    1664              :     #[tokio::test]
    1665            1 :     async fn test_relsize() -> Result<()> {
    1666            1 :         let (tenant, ctx) = TenantHarness::create("test_relsize").await?.load().await;
    1667            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    1668            1 :         let tline = tenant
    1669            1 :             .create_test_timeline(TIMELINE_ID, Lsn(8), DEFAULT_PG_VERSION, &ctx)
    1670            1 :             .await?;
    1671            1 :         let mut walingest = init_walingest_test(&tline, &ctx).await?;
    1672              : 
    1673            1 :         let mut m = tline.begin_modification(Lsn(0x20));
    1674            1 :         walingest.put_rel_creation(&mut m, TESTREL_A, &ctx).await?;
    1675            1 :         walingest
    1676            1 :             .put_rel_page_image(&mut m, TESTREL_A, 0, test_img("foo blk 0 at 2"), &ctx)
    1677            1 :             .await?;
    1678            1 :         m.commit(&ctx).await?;
    1679            1 :         let mut m = tline.begin_modification(Lsn(0x30));
    1680            1 :         walingest
    1681            1 :             .put_rel_page_image(&mut m, TESTREL_A, 0, test_img("foo blk 0 at 3"), &ctx)
    1682            1 :             .await?;
    1683            1 :         m.commit(&ctx).await?;
    1684            1 :         let mut m = tline.begin_modification(Lsn(0x40));
    1685            1 :         walingest
    1686            1 :             .put_rel_page_image(&mut m, TESTREL_A, 1, test_img("foo blk 1 at 4"), &ctx)
    1687            1 :             .await?;
    1688            1 :         m.commit(&ctx).await?;
    1689            1 :         let mut m = tline.begin_modification(Lsn(0x50));
    1690            1 :         walingest
    1691            1 :             .put_rel_page_image(&mut m, TESTREL_A, 2, test_img("foo blk 2 at 5"), &ctx)
    1692            1 :             .await?;
    1693            1 :         m.commit(&ctx).await?;
    1694              : 
    1695            1 :         assert_current_logical_size(&tline, Lsn(0x50));
    1696              : 
    1697            1 :         let test_span = tracing::info_span!(parent: None, "test",
    1698            0 :                                             tenant_id=%tline.tenant_shard_id.tenant_id,
    1699            0 :                                             shard_id=%tline.tenant_shard_id.shard_slug(),
    1700            0 :                                             timeline_id=%tline.timeline_id);
    1701              : 
    1702              :         // The relation was created at LSN 2, not visible at LSN 1 yet.
    1703            1 :         assert_eq!(
    1704            1 :             tline
    1705            1 :                 .get_rel_exists(TESTREL_A, Version::at(Lsn(0x10)), &ctx)
    1706            1 :                 .await?,
    1707              :             false
    1708              :         );
    1709            1 :         assert!(
    1710            1 :             tline
    1711            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x10)), &ctx)
    1712            1 :                 .await
    1713            1 :                 .is_err()
    1714              :         );
    1715            1 :         assert_eq!(
    1716            1 :             tline
    1717            1 :                 .get_rel_exists(TESTREL_A, Version::at(Lsn(0x20)), &ctx)
    1718            1 :                 .await?,
    1719              :             true
    1720              :         );
    1721            1 :         assert_eq!(
    1722            1 :             tline
    1723            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x20)), &ctx)
    1724            1 :                 .await?,
    1725              :             1
    1726              :         );
    1727            1 :         assert_eq!(
    1728            1 :             tline
    1729            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x50)), &ctx)
    1730            1 :                 .await?,
    1731              :             3
    1732              :         );
    1733              : 
    1734              :         // Check page contents at each LSN
    1735            1 :         assert_eq!(
    1736            1 :             tline
    1737            1 :                 .get_rel_page_at_lsn(
    1738            1 :                     TESTREL_A,
    1739            1 :                     0,
    1740            1 :                     Version::at(Lsn(0x20)),
    1741            1 :                     &ctx,
    1742            1 :                     io_concurrency.clone()
    1743            1 :                 )
    1744            1 :                 .instrument(test_span.clone())
    1745            1 :                 .await?,
    1746            1 :             test_img("foo blk 0 at 2")
    1747              :         );
    1748              : 
    1749            1 :         assert_eq!(
    1750            1 :             tline
    1751            1 :                 .get_rel_page_at_lsn(
    1752            1 :                     TESTREL_A,
    1753            1 :                     0,
    1754            1 :                     Version::at(Lsn(0x30)),
    1755            1 :                     &ctx,
    1756            1 :                     io_concurrency.clone()
    1757            1 :                 )
    1758            1 :                 .instrument(test_span.clone())
    1759            1 :                 .await?,
    1760            1 :             test_img("foo blk 0 at 3")
    1761              :         );
    1762              : 
    1763            1 :         assert_eq!(
    1764            1 :             tline
    1765            1 :                 .get_rel_page_at_lsn(
    1766            1 :                     TESTREL_A,
    1767            1 :                     0,
    1768            1 :                     Version::at(Lsn(0x40)),
    1769            1 :                     &ctx,
    1770            1 :                     io_concurrency.clone()
    1771            1 :                 )
    1772            1 :                 .instrument(test_span.clone())
    1773            1 :                 .await?,
    1774            1 :             test_img("foo blk 0 at 3")
    1775              :         );
    1776            1 :         assert_eq!(
    1777            1 :             tline
    1778            1 :                 .get_rel_page_at_lsn(
    1779            1 :                     TESTREL_A,
    1780            1 :                     1,
    1781            1 :                     Version::at(Lsn(0x40)),
    1782            1 :                     &ctx,
    1783            1 :                     io_concurrency.clone()
    1784            1 :                 )
    1785            1 :                 .instrument(test_span.clone())
    1786            1 :                 .await?,
    1787            1 :             test_img("foo blk 1 at 4")
    1788              :         );
    1789              : 
    1790            1 :         assert_eq!(
    1791            1 :             tline
    1792            1 :                 .get_rel_page_at_lsn(
    1793            1 :                     TESTREL_A,
    1794            1 :                     0,
    1795            1 :                     Version::at(Lsn(0x50)),
    1796            1 :                     &ctx,
    1797            1 :                     io_concurrency.clone()
    1798            1 :                 )
    1799            1 :                 .instrument(test_span.clone())
    1800            1 :                 .await?,
    1801            1 :             test_img("foo blk 0 at 3")
    1802              :         );
    1803            1 :         assert_eq!(
    1804            1 :             tline
    1805            1 :                 .get_rel_page_at_lsn(
    1806            1 :                     TESTREL_A,
    1807            1 :                     1,
    1808            1 :                     Version::at(Lsn(0x50)),
    1809            1 :                     &ctx,
    1810            1 :                     io_concurrency.clone()
    1811            1 :                 )
    1812            1 :                 .instrument(test_span.clone())
    1813            1 :                 .await?,
    1814            1 :             test_img("foo blk 1 at 4")
    1815              :         );
    1816            1 :         assert_eq!(
    1817            1 :             tline
    1818            1 :                 .get_rel_page_at_lsn(
    1819            1 :                     TESTREL_A,
    1820            1 :                     2,
    1821            1 :                     Version::at(Lsn(0x50)),
    1822            1 :                     &ctx,
    1823            1 :                     io_concurrency.clone()
    1824            1 :                 )
    1825            1 :                 .instrument(test_span.clone())
    1826            1 :                 .await?,
    1827            1 :             test_img("foo blk 2 at 5")
    1828              :         );
    1829              : 
    1830              :         // Truncate last block
    1831            1 :         let mut m = tline.begin_modification(Lsn(0x60));
    1832            1 :         walingest
    1833            1 :             .put_rel_truncation(&mut m, TESTREL_A, 2, &ctx)
    1834            1 :             .await?;
    1835            1 :         m.commit(&ctx).await?;
    1836            1 :         assert_current_logical_size(&tline, Lsn(0x60));
    1837              : 
    1838              :         // Check reported size and contents after truncation
    1839            1 :         assert_eq!(
    1840            1 :             tline
    1841            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x60)), &ctx)
    1842            1 :                 .await?,
    1843              :             2
    1844              :         );
    1845            1 :         assert_eq!(
    1846            1 :             tline
    1847            1 :                 .get_rel_page_at_lsn(
    1848            1 :                     TESTREL_A,
    1849            1 :                     0,
    1850            1 :                     Version::at(Lsn(0x60)),
    1851            1 :                     &ctx,
    1852            1 :                     io_concurrency.clone()
    1853            1 :                 )
    1854            1 :                 .instrument(test_span.clone())
    1855            1 :                 .await?,
    1856            1 :             test_img("foo blk 0 at 3")
    1857              :         );
    1858            1 :         assert_eq!(
    1859            1 :             tline
    1860            1 :                 .get_rel_page_at_lsn(
    1861            1 :                     TESTREL_A,
    1862            1 :                     1,
    1863            1 :                     Version::at(Lsn(0x60)),
    1864            1 :                     &ctx,
    1865            1 :                     io_concurrency.clone()
    1866            1 :                 )
    1867            1 :                 .instrument(test_span.clone())
    1868            1 :                 .await?,
    1869            1 :             test_img("foo blk 1 at 4")
    1870              :         );
    1871              : 
    1872              :         // should still see the truncated block with older LSN
    1873            1 :         assert_eq!(
    1874            1 :             tline
    1875            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x50)), &ctx)
    1876            1 :                 .await?,
    1877              :             3
    1878              :         );
    1879            1 :         assert_eq!(
    1880            1 :             tline
    1881            1 :                 .get_rel_page_at_lsn(
    1882            1 :                     TESTREL_A,
    1883            1 :                     2,
    1884            1 :                     Version::at(Lsn(0x50)),
    1885            1 :                     &ctx,
    1886            1 :                     io_concurrency.clone()
    1887            1 :                 )
    1888            1 :                 .instrument(test_span.clone())
    1889            1 :                 .await?,
    1890            1 :             test_img("foo blk 2 at 5")
    1891              :         );
    1892              : 
    1893              :         // Truncate to zero length
    1894            1 :         let mut m = tline.begin_modification(Lsn(0x68));
    1895            1 :         walingest
    1896            1 :             .put_rel_truncation(&mut m, TESTREL_A, 0, &ctx)
    1897            1 :             .await?;
    1898            1 :         m.commit(&ctx).await?;
    1899            1 :         assert_eq!(
    1900            1 :             tline
    1901            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x68)), &ctx)
    1902            1 :                 .await?,
    1903              :             0
    1904              :         );
    1905              : 
    1906              :         // Extend from 0 to 2 blocks, leaving a gap
    1907            1 :         let mut m = tline.begin_modification(Lsn(0x70));
    1908            1 :         walingest
    1909            1 :             .put_rel_page_image(&mut m, TESTREL_A, 1, test_img("foo blk 1"), &ctx)
    1910            1 :             .await?;
    1911            1 :         m.commit(&ctx).await?;
    1912            1 :         assert_eq!(
    1913            1 :             tline
    1914            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x70)), &ctx)
    1915            1 :                 .await?,
    1916              :             2
    1917              :         );
    1918            1 :         assert_eq!(
    1919            1 :             tline
    1920            1 :                 .get_rel_page_at_lsn(
    1921            1 :                     TESTREL_A,
    1922            1 :                     0,
    1923            1 :                     Version::at(Lsn(0x70)),
    1924            1 :                     &ctx,
    1925            1 :                     io_concurrency.clone()
    1926            1 :                 )
    1927            1 :                 .instrument(test_span.clone())
    1928            1 :                 .await?,
    1929            1 :             ZERO_PAGE
    1930              :         );
    1931            1 :         assert_eq!(
    1932            1 :             tline
    1933            1 :                 .get_rel_page_at_lsn(
    1934            1 :                     TESTREL_A,
    1935            1 :                     1,
    1936            1 :                     Version::at(Lsn(0x70)),
    1937            1 :                     &ctx,
    1938            1 :                     io_concurrency.clone()
    1939            1 :                 )
    1940            1 :                 .instrument(test_span.clone())
    1941            1 :                 .await?,
    1942            1 :             test_img("foo blk 1")
    1943              :         );
    1944              : 
    1945              :         // Extend a lot more, leaving a big gap that spans across segments
    1946            1 :         let mut m = tline.begin_modification(Lsn(0x80));
    1947            1 :         walingest
    1948            1 :             .put_rel_page_image(&mut m, TESTREL_A, 1500, test_img("foo blk 1500"), &ctx)
    1949            1 :             .await?;
    1950            1 :         m.commit(&ctx).await?;
    1951            1 :         assert_eq!(
    1952            1 :             tline
    1953            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x80)), &ctx)
    1954            1 :                 .await?,
    1955              :             1501
    1956              :         );
    1957         1499 :         for blk in 2..1500 {
    1958         1498 :             assert_eq!(
    1959         1498 :                 tline
    1960         1498 :                     .get_rel_page_at_lsn(
    1961         1498 :                         TESTREL_A,
    1962         1498 :                         blk,
    1963         1498 :                         Version::at(Lsn(0x80)),
    1964         1498 :                         &ctx,
    1965         1498 :                         io_concurrency.clone()
    1966         1498 :                     )
    1967         1498 :                     .instrument(test_span.clone())
    1968         1498 :                     .await?,
    1969         1498 :                 ZERO_PAGE
    1970              :             );
    1971              :         }
    1972            1 :         assert_eq!(
    1973            1 :             tline
    1974            1 :                 .get_rel_page_at_lsn(
    1975            1 :                     TESTREL_A,
    1976            1 :                     1500,
    1977            1 :                     Version::at(Lsn(0x80)),
    1978            1 :                     &ctx,
    1979            1 :                     io_concurrency.clone()
    1980            1 :                 )
    1981            1 :                 .instrument(test_span.clone())
    1982            1 :                 .await?,
    1983            1 :             test_img("foo blk 1500")
    1984              :         );
    1985              : 
    1986            2 :         Ok(())
    1987            1 :     }
    1988              : 
    1989              :     // Test what happens if we dropped a relation
    1990              :     // and then created it again within the same layer.
    1991              :     #[tokio::test]
    1992            1 :     async fn test_drop_extend() -> Result<()> {
    1993            1 :         let (tenant, ctx) = TenantHarness::create("test_drop_extend")
    1994            1 :             .await?
    1995            1 :             .load()
    1996            1 :             .await;
    1997            1 :         let tline = tenant
    1998            1 :             .create_test_timeline(TIMELINE_ID, Lsn(8), DEFAULT_PG_VERSION, &ctx)
    1999            1 :             .await?;
    2000            1 :         let mut walingest = init_walingest_test(&tline, &ctx).await?;
    2001              : 
    2002            1 :         let mut m = tline.begin_modification(Lsn(0x20));
    2003            1 :         walingest
    2004            1 :             .put_rel_page_image(&mut m, TESTREL_A, 0, test_img("foo blk 0 at 2"), &ctx)
    2005            1 :             .await?;
    2006            1 :         m.commit(&ctx).await?;
    2007              : 
    2008              :         // Check that rel exists and size is correct
    2009            1 :         assert_eq!(
    2010            1 :             tline
    2011            1 :                 .get_rel_exists(TESTREL_A, Version::at(Lsn(0x20)), &ctx)
    2012            1 :                 .await?,
    2013              :             true
    2014              :         );
    2015            1 :         assert_eq!(
    2016            1 :             tline
    2017            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x20)), &ctx)
    2018            1 :                 .await?,
    2019              :             1
    2020              :         );
    2021              : 
    2022              :         // Drop rel
    2023            1 :         let mut m = tline.begin_modification(Lsn(0x30));
    2024            1 :         let mut rel_drops = HashMap::new();
    2025            1 :         rel_drops.insert((TESTREL_A.spcnode, TESTREL_A.dbnode), vec![TESTREL_A]);
    2026            1 :         m.put_rel_drops(rel_drops, &ctx).await?;
    2027            1 :         m.commit(&ctx).await?;
    2028              : 
    2029              :         // Check that rel is not visible anymore
    2030            1 :         assert_eq!(
    2031            1 :             tline
    2032            1 :                 .get_rel_exists(TESTREL_A, Version::at(Lsn(0x30)), &ctx)
    2033            1 :                 .await?,
    2034              :             false
    2035              :         );
    2036              : 
    2037              :         // FIXME: should fail
    2038              :         //assert!(tline.get_rel_size(TESTREL_A, Lsn(0x30), false)?.is_none());
    2039              : 
    2040              :         // Re-create it
    2041            1 :         let mut m = tline.begin_modification(Lsn(0x40));
    2042            1 :         walingest
    2043            1 :             .put_rel_page_image(&mut m, TESTREL_A, 0, test_img("foo blk 0 at 4"), &ctx)
    2044            1 :             .await?;
    2045            1 :         m.commit(&ctx).await?;
    2046              : 
    2047              :         // Check that rel exists and size is correct
    2048            1 :         assert_eq!(
    2049            1 :             tline
    2050            1 :                 .get_rel_exists(TESTREL_A, Version::at(Lsn(0x40)), &ctx)
    2051            1 :                 .await?,
    2052              :             true
    2053              :         );
    2054            1 :         assert_eq!(
    2055            1 :             tline
    2056            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x40)), &ctx)
    2057            1 :                 .await?,
    2058              :             1
    2059              :         );
    2060              : 
    2061            2 :         Ok(())
    2062            1 :     }
    2063              : 
    2064              :     // Test what happens if we truncated a relation
    2065              :     // so that one of its segments was dropped
    2066              :     // and then extended it again within the same layer.
    2067              :     #[tokio::test]
    2068            1 :     async fn test_truncate_extend() -> Result<()> {
    2069            1 :         let (tenant, ctx) = TenantHarness::create("test_truncate_extend")
    2070            1 :             .await?
    2071            1 :             .load()
    2072            1 :             .await;
    2073            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    2074            1 :         let tline = tenant
    2075            1 :             .create_test_timeline(TIMELINE_ID, Lsn(8), DEFAULT_PG_VERSION, &ctx)
    2076            1 :             .await?;
    2077            1 :         let mut walingest = init_walingest_test(&tline, &ctx).await?;
    2078              : 
    2079              :         // Create a 20 MB relation (the size is arbitrary)
    2080            1 :         let relsize = 20 * 1024 * 1024 / 8192;
    2081            1 :         let mut m = tline.begin_modification(Lsn(0x20));
    2082         2560 :         for blkno in 0..relsize {
    2083         2560 :             let data = format!("foo blk {} at {}", blkno, Lsn(0x20));
    2084         2560 :             walingest
    2085         2560 :                 .put_rel_page_image(&mut m, TESTREL_A, blkno, test_img(&data), &ctx)
    2086         2560 :                 .await?;
    2087              :         }
    2088            1 :         m.commit(&ctx).await?;
    2089              : 
    2090            1 :         let test_span = tracing::info_span!(parent: None, "test",
    2091            0 :                                             tenant_id=%tline.tenant_shard_id.tenant_id,
    2092            0 :                                             shard_id=%tline.tenant_shard_id.shard_slug(),
    2093            0 :                                             timeline_id=%tline.timeline_id);
    2094              : 
    2095              :         // The relation was created at LSN 20, not visible at LSN 1 yet.
    2096            1 :         assert_eq!(
    2097            1 :             tline
    2098            1 :                 .get_rel_exists(TESTREL_A, Version::at(Lsn(0x10)), &ctx)
    2099            1 :                 .await?,
    2100              :             false
    2101              :         );
    2102            1 :         assert!(
    2103            1 :             tline
    2104            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x10)), &ctx)
    2105            1 :                 .await
    2106            1 :                 .is_err()
    2107              :         );
    2108              : 
    2109            1 :         assert_eq!(
    2110            1 :             tline
    2111            1 :                 .get_rel_exists(TESTREL_A, Version::at(Lsn(0x20)), &ctx)
    2112            1 :                 .await?,
    2113              :             true
    2114              :         );
    2115            1 :         assert_eq!(
    2116            1 :             tline
    2117            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x20)), &ctx)
    2118            1 :                 .await?,
    2119              :             relsize
    2120              :         );
    2121              : 
    2122              :         // Check relation content
    2123         2560 :         for blkno in 0..relsize {
    2124         2560 :             let lsn = Lsn(0x20);
    2125         2560 :             let data = format!("foo blk {blkno} at {lsn}");
    2126         2560 :             assert_eq!(
    2127         2560 :                 tline
    2128         2560 :                     .get_rel_page_at_lsn(
    2129         2560 :                         TESTREL_A,
    2130         2560 :                         blkno,
    2131         2560 :                         Version::at(lsn),
    2132         2560 :                         &ctx,
    2133         2560 :                         io_concurrency.clone()
    2134         2560 :                     )
    2135         2560 :                     .instrument(test_span.clone())
    2136         2560 :                     .await?,
    2137         2560 :                 test_img(&data)
    2138              :             );
    2139              :         }
    2140              : 
    2141              :         // Truncate relation so that second segment was dropped
    2142              :         // - only leave one page
    2143            1 :         let mut m = tline.begin_modification(Lsn(0x60));
    2144            1 :         walingest
    2145            1 :             .put_rel_truncation(&mut m, TESTREL_A, 1, &ctx)
    2146            1 :             .await?;
    2147            1 :         m.commit(&ctx).await?;
    2148              : 
    2149              :         // Check reported size and contents after truncation
    2150            1 :         assert_eq!(
    2151            1 :             tline
    2152            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x60)), &ctx)
    2153            1 :                 .await?,
    2154              :             1
    2155              :         );
    2156              : 
    2157            2 :         for blkno in 0..1 {
    2158            1 :             let lsn = Lsn(0x20);
    2159            1 :             let data = format!("foo blk {blkno} at {lsn}");
    2160            1 :             assert_eq!(
    2161            1 :                 tline
    2162            1 :                     .get_rel_page_at_lsn(
    2163            1 :                         TESTREL_A,
    2164            1 :                         blkno,
    2165            1 :                         Version::at(Lsn(0x60)),
    2166            1 :                         &ctx,
    2167            1 :                         io_concurrency.clone()
    2168            1 :                     )
    2169            1 :                     .instrument(test_span.clone())
    2170            1 :                     .await?,
    2171            1 :                 test_img(&data)
    2172              :             );
    2173              :         }
    2174              : 
    2175              :         // should still see all blocks with older LSN
    2176            1 :         assert_eq!(
    2177            1 :             tline
    2178            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x50)), &ctx)
    2179            1 :                 .await?,
    2180              :             relsize
    2181              :         );
    2182         2560 :         for blkno in 0..relsize {
    2183         2560 :             let lsn = Lsn(0x20);
    2184         2560 :             let data = format!("foo blk {blkno} at {lsn}");
    2185         2560 :             assert_eq!(
    2186         2560 :                 tline
    2187         2560 :                     .get_rel_page_at_lsn(
    2188         2560 :                         TESTREL_A,
    2189         2560 :                         blkno,
    2190         2560 :                         Version::at(Lsn(0x50)),
    2191         2560 :                         &ctx,
    2192         2560 :                         io_concurrency.clone()
    2193         2560 :                     )
    2194         2560 :                     .instrument(test_span.clone())
    2195         2560 :                     .await?,
    2196         2560 :                 test_img(&data)
    2197              :             );
    2198              :         }
    2199              : 
    2200              :         // Extend relation again.
    2201              :         // Add enough blocks to create second segment
    2202            1 :         let lsn = Lsn(0x80);
    2203            1 :         let mut m = tline.begin_modification(lsn);
    2204         2560 :         for blkno in 0..relsize {
    2205         2560 :             let data = format!("foo blk {blkno} at {lsn}");
    2206         2560 :             walingest
    2207         2560 :                 .put_rel_page_image(&mut m, TESTREL_A, blkno, test_img(&data), &ctx)
    2208         2560 :                 .await?;
    2209              :         }
    2210            1 :         m.commit(&ctx).await?;
    2211              : 
    2212            1 :         assert_eq!(
    2213            1 :             tline
    2214            1 :                 .get_rel_exists(TESTREL_A, Version::at(Lsn(0x80)), &ctx)
    2215            1 :                 .await?,
    2216              :             true
    2217              :         );
    2218            1 :         assert_eq!(
    2219            1 :             tline
    2220            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(0x80)), &ctx)
    2221            1 :                 .await?,
    2222              :             relsize
    2223              :         );
    2224              :         // Check relation content
    2225         2560 :         for blkno in 0..relsize {
    2226         2560 :             let lsn = Lsn(0x80);
    2227         2560 :             let data = format!("foo blk {blkno} at {lsn}");
    2228         2560 :             assert_eq!(
    2229         2560 :                 tline
    2230         2560 :                     .get_rel_page_at_lsn(
    2231         2560 :                         TESTREL_A,
    2232         2560 :                         blkno,
    2233         2560 :                         Version::at(Lsn(0x80)),
    2234         2560 :                         &ctx,
    2235         2560 :                         io_concurrency.clone()
    2236         2560 :                     )
    2237         2560 :                     .instrument(test_span.clone())
    2238         2560 :                     .await?,
    2239         2560 :                 test_img(&data)
    2240            1 :             );
    2241            1 :         }
    2242            1 : 
    2243            1 :         Ok(())
    2244            1 :     }
    2245              : 
    2246              :     /// Test get_relsize() and truncation with a file larger than 1 GB, so that it's
    2247              :     /// split into multiple 1 GB segments in Postgres.
    2248              :     #[tokio::test]
    2249            1 :     async fn test_large_rel() -> Result<()> {
    2250            1 :         let (tenant, ctx) = TenantHarness::create("test_large_rel").await?.load().await;
    2251            1 :         let tline = tenant
    2252            1 :             .create_test_timeline(TIMELINE_ID, Lsn(8), DEFAULT_PG_VERSION, &ctx)
    2253            1 :             .await?;
    2254            1 :         let mut walingest = init_walingest_test(&tline, &ctx).await?;
    2255              : 
    2256            1 :         let mut lsn = 0x10;
    2257       131073 :         for blknum in 0..RELSEG_SIZE + 1 {
    2258       131073 :             lsn += 0x10;
    2259       131073 :             let mut m = tline.begin_modification(Lsn(lsn));
    2260       131073 :             let img = test_img(&format!("foo blk {} at {}", blknum, Lsn(lsn)));
    2261       131073 :             walingest
    2262       131073 :                 .put_rel_page_image(&mut m, TESTREL_A, blknum as BlockNumber, img, &ctx)
    2263       131073 :                 .await?;
    2264       131073 :             m.commit(&ctx).await?;
    2265              :         }
    2266              : 
    2267            1 :         assert_current_logical_size(&tline, Lsn(lsn));
    2268              : 
    2269            1 :         assert_eq!(
    2270            1 :             tline
    2271            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(lsn)), &ctx)
    2272            1 :                 .await?,
    2273            1 :             RELSEG_SIZE + 1
    2274              :         );
    2275              : 
    2276              :         // Truncate one block
    2277            1 :         lsn += 0x10;
    2278            1 :         let mut m = tline.begin_modification(Lsn(lsn));
    2279            1 :         walingest
    2280            1 :             .put_rel_truncation(&mut m, TESTREL_A, RELSEG_SIZE, &ctx)
    2281            1 :             .await?;
    2282            1 :         m.commit(&ctx).await?;
    2283            1 :         assert_eq!(
    2284            1 :             tline
    2285            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(lsn)), &ctx)
    2286            1 :                 .await?,
    2287              :             RELSEG_SIZE
    2288              :         );
    2289            1 :         assert_current_logical_size(&tline, Lsn(lsn));
    2290              : 
    2291              :         // Truncate another block
    2292            1 :         lsn += 0x10;
    2293            1 :         let mut m = tline.begin_modification(Lsn(lsn));
    2294            1 :         walingest
    2295            1 :             .put_rel_truncation(&mut m, TESTREL_A, RELSEG_SIZE - 1, &ctx)
    2296            1 :             .await?;
    2297            1 :         m.commit(&ctx).await?;
    2298            1 :         assert_eq!(
    2299            1 :             tline
    2300            1 :                 .get_rel_size(TESTREL_A, Version::at(Lsn(lsn)), &ctx)
    2301            1 :                 .await?,
    2302            1 :             RELSEG_SIZE - 1
    2303              :         );
    2304            1 :         assert_current_logical_size(&tline, Lsn(lsn));
    2305              : 
    2306              :         // Truncate to 1500, and then truncate all the way down to 0, one block at a time
    2307              :         // This tests the behavior at segment boundaries
    2308            1 :         let mut size: i32 = 3000;
    2309         3002 :         while size >= 0 {
    2310         3001 :             lsn += 0x10;
    2311         3001 :             let mut m = tline.begin_modification(Lsn(lsn));
    2312         3001 :             walingest
    2313         3001 :                 .put_rel_truncation(&mut m, TESTREL_A, size as BlockNumber, &ctx)
    2314         3001 :                 .await?;
    2315         3001 :             m.commit(&ctx).await?;
    2316         3001 :             assert_eq!(
    2317         3001 :                 tline
    2318         3001 :                     .get_rel_size(TESTREL_A, Version::at(Lsn(lsn)), &ctx)
    2319         3001 :                     .await?,
    2320         3001 :                 size as BlockNumber
    2321              :             );
    2322              : 
    2323         3001 :             size -= 1;
    2324              :         }
    2325            1 :         assert_current_logical_size(&tline, Lsn(lsn));
    2326              : 
    2327            2 :         Ok(())
    2328            1 :     }
    2329              : 
    2330              :     /// Replay a wal segment file taken directly from safekeepers.
    2331              :     ///
    2332              :     /// This test is useful for benchmarking since it allows us to profile only
    2333              :     /// the walingest code in a single-threaded executor, and iterate more quickly
    2334              :     /// without waiting for unrelated steps.
    2335              :     #[tokio::test]
    2336            1 :     async fn test_ingest_real_wal() {
    2337              :         use postgres_ffi::WAL_SEGMENT_SIZE;
    2338              :         use postgres_ffi::waldecoder::WalStreamDecoder;
    2339              : 
    2340              :         use crate::tenant::harness::*;
    2341              : 
    2342              :         // Define test data path and constants.
    2343              :         //
    2344              :         // Steps to reconstruct the data, if needed:
    2345              :         // 1. Run the pgbench python test
    2346              :         // 2. Take the first wal segment file from safekeeper
    2347              :         // 3. Compress it using `zstd --long input_file`
    2348              :         // 4. Copy initdb.tar.zst from local_fs_remote_storage
    2349              :         // 5. Grep sk logs for "restart decoder" to get startpoint
    2350              :         // 6. Run just the decoder from this test to get the endpoint.
    2351              :         //    It's the last LSN the decoder will output.
    2352            1 :         let pg_version = PgMajorVersion::PG15; // The test data was generated by pg15
    2353            1 :         let path = "test_data/sk_wal_segment_from_pgbench";
    2354            1 :         let wal_segment_path = format!("{path}/000000010000000000000001.zst");
    2355            1 :         let source_initdb_path = format!("{path}/{INITDB_PATH}");
    2356            1 :         let startpoint = Lsn::from_hex("14AEC08").unwrap();
    2357            1 :         let _endpoint = Lsn::from_hex("1FFFF98").unwrap();
    2358              : 
    2359            1 :         let harness = TenantHarness::create("test_ingest_real_wal").await.unwrap();
    2360            1 :         let span = harness
    2361            1 :             .span()
    2362            1 :             .in_scope(|| info_span!("timeline_span", timeline_id=%TIMELINE_ID));
    2363            1 :         let (tenant, ctx) = harness.load().await;
    2364              : 
    2365            1 :         let remote_initdb_path =
    2366            1 :             remote_initdb_archive_path(&tenant.tenant_shard_id().tenant_id, &TIMELINE_ID);
    2367            1 :         let initdb_path = harness.remote_fs_dir.join(remote_initdb_path.get_path());
    2368              : 
    2369            1 :         std::fs::create_dir_all(initdb_path.parent().unwrap())
    2370            1 :             .expect("creating test dir should work");
    2371            1 :         std::fs::copy(source_initdb_path, initdb_path).expect("copying the initdb.tar.zst works");
    2372              : 
    2373              :         // Bootstrap a real timeline. We can't use create_test_timeline because
    2374              :         // it doesn't create a real checkpoint, and Walingest::new tries to parse
    2375              :         // the garbage data.
    2376            1 :         let tline = tenant
    2377            1 :             .bootstrap_timeline_test(TIMELINE_ID, pg_version, Some(TIMELINE_ID), &ctx)
    2378            1 :             .await
    2379            1 :             .unwrap();
    2380              : 
    2381              :         // We fully read and decompress this into memory before decoding
    2382              :         // to get a more accurate perf profile of the decoder.
    2383            1 :         let bytes = {
    2384              :             use async_compression::tokio::bufread::ZstdDecoder;
    2385            1 :             let file = tokio::fs::File::open(wal_segment_path).await.unwrap();
    2386            1 :             let reader = tokio::io::BufReader::new(file);
    2387            1 :             let decoder = ZstdDecoder::new(reader);
    2388            1 :             let mut reader = tokio::io::BufReader::new(decoder);
    2389            1 :             let mut buffer = Vec::new();
    2390            1 :             tokio::io::copy_buf(&mut reader, &mut buffer).await.unwrap();
    2391            1 :             buffer
    2392              :         };
    2393              : 
    2394              :         // TODO start a profiler too
    2395            1 :         let started_at = std::time::Instant::now();
    2396              : 
    2397              :         // Initialize walingest
    2398            1 :         let xlogoff: usize = startpoint.segment_offset(WAL_SEGMENT_SIZE);
    2399            1 :         let mut decoder = WalStreamDecoder::new(startpoint, pg_version);
    2400            1 :         let mut walingest = WalIngest::new(tline.as_ref(), startpoint, &ctx)
    2401            1 :             .await
    2402            1 :             .unwrap();
    2403            1 :         let mut modification = tline.begin_modification(startpoint);
    2404            1 :         println!("decoding {} bytes", bytes.len() - xlogoff);
    2405              : 
    2406              :         // Decode and ingest wal. We process the wal in chunks because
    2407              :         // that's what happens when we get bytes from safekeepers.
    2408       237343 :         for chunk in bytes[xlogoff..].chunks(50) {
    2409       237343 :             decoder.feed_bytes(chunk);
    2410       310268 :             while let Some((lsn, recdata)) = decoder.poll_decode().unwrap() {
    2411        72925 :                 let interpreted = InterpretedWalRecord::from_bytes_filtered(
    2412        72925 :                     recdata,
    2413        72925 :                     &[*modification.tline.get_shard_identity()],
    2414        72925 :                     lsn,
    2415        72925 :                     modification.tline.pg_version,
    2416        72925 :                 )
    2417        72925 :                 .unwrap()
    2418        72925 :                 .remove(modification.tline.get_shard_identity())
    2419        72925 :                 .unwrap();
    2420              : 
    2421        72925 :                 walingest
    2422        72925 :                     .ingest_record(interpreted, &mut modification, &ctx)
    2423        72925 :                     .instrument(span.clone())
    2424        72925 :                     .await
    2425        72925 :                     .unwrap();
    2426              :             }
    2427       237343 :             modification.commit(&ctx).await.unwrap();
    2428              :         }
    2429              : 
    2430            1 :         let duration = started_at.elapsed();
    2431            1 :         println!("done in {duration:?}");
    2432            1 :     }
    2433              : }
        

Generated by: LCOV version 2.1-beta