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