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