Line data Source code
1 : //! Timeline repository implementation that keeps old data in layer files, and
2 : //! the recent changes in ephemeral files.
3 : //!
4 : //! See tenant/*_layer.rs files. The functions here are responsible for locating
5 : //! the correct layer for the get/put call, walking back the timeline branching
6 : //! history as needed.
7 : //!
8 : //! The files are stored in the .neon/tenants/<tenant_id>/timelines/<timeline_id>
9 : //! directory. See docs/pageserver-storage.md for how the files are managed.
10 : //! In addition to the layer files, there is a metadata file in the same
11 : //! directory that contains information about the timeline, in particular its
12 : //! parent timeline, and the last LSN that has been written to disk.
13 : //!
14 :
15 : use anyhow::{bail, Context};
16 : use arc_swap::ArcSwap;
17 : use camino::Utf8Path;
18 : use camino::Utf8PathBuf;
19 : use enumset::EnumSet;
20 : use futures::stream::FuturesUnordered;
21 : use futures::FutureExt;
22 : use futures::StreamExt;
23 : use pageserver_api::models;
24 : use pageserver_api::models::AuxFilePolicy;
25 : use pageserver_api::models::TimelineArchivalState;
26 : use pageserver_api::models::TimelineState;
27 : use pageserver_api::models::TopTenantShardItem;
28 : use pageserver_api::models::WalRedoManagerStatus;
29 : use pageserver_api::shard::ShardIdentity;
30 : use pageserver_api::shard::ShardStripeSize;
31 : use pageserver_api::shard::TenantShardId;
32 : use remote_storage::DownloadError;
33 : use remote_storage::GenericRemoteStorage;
34 : use remote_storage::TimeoutOrCancel;
35 : use std::collections::BTreeMap;
36 : use std::fmt;
37 : use std::sync::Weak;
38 : use std::time::SystemTime;
39 : use storage_broker::BrokerClientChannel;
40 : use tokio::io::BufReader;
41 : use tokio::sync::watch;
42 : use tokio::task::JoinSet;
43 : use tokio_util::sync::CancellationToken;
44 : use tracing::*;
45 : use upload_queue::NotInitialized;
46 : use utils::backoff;
47 : use utils::circuit_breaker::CircuitBreaker;
48 : use utils::completion;
49 : use utils::crashsafe::path_with_suffix_extension;
50 : use utils::failpoint_support;
51 : use utils::fs_ext;
52 : use utils::pausable_failpoint;
53 : use utils::sync::gate::Gate;
54 : use utils::sync::gate::GateGuard;
55 : use utils::timeout::timeout_cancellable;
56 : use utils::timeout::TimeoutCancellableError;
57 : use utils::zstd::create_zst_tarball;
58 : use utils::zstd::extract_zst_tarball;
59 :
60 : use self::config::AttachedLocationConfig;
61 : use self::config::AttachmentMode;
62 : use self::config::LocationConf;
63 : use self::config::TenantConf;
64 : use self::metadata::TimelineMetadata;
65 : use self::mgr::GetActiveTenantError;
66 : use self::mgr::GetTenantError;
67 : use self::remote_timeline_client::upload::upload_index_part;
68 : use self::remote_timeline_client::RemoteTimelineClient;
69 : use self::timeline::uninit::TimelineCreateGuard;
70 : use self::timeline::uninit::TimelineExclusionError;
71 : use self::timeline::uninit::UninitializedTimeline;
72 : use self::timeline::EvictionTaskTenantState;
73 : use self::timeline::GcCutoffs;
74 : use self::timeline::TimelineResources;
75 : use self::timeline::WaitLsnError;
76 : use crate::config::PageServerConf;
77 : use crate::context::{DownloadBehavior, RequestContext};
78 : use crate::deletion_queue::DeletionQueueClient;
79 : use crate::deletion_queue::DeletionQueueError;
80 : use crate::import_datadir;
81 : use crate::is_uninit_mark;
82 : use crate::l0_flush::L0FlushGlobalState;
83 : use crate::metrics::TENANT;
84 : use crate::metrics::{
85 : remove_tenant_metrics, BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN,
86 : TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC,
87 : };
88 : use crate::repository::GcResult;
89 : use crate::task_mgr;
90 : use crate::task_mgr::TaskKind;
91 : use crate::tenant::config::LocationMode;
92 : use crate::tenant::config::TenantConfOpt;
93 : pub use crate::tenant::remote_timeline_client::index::IndexPart;
94 : use crate::tenant::remote_timeline_client::remote_initdb_archive_path;
95 : use crate::tenant::remote_timeline_client::MaybeDeletedIndexPart;
96 : use crate::tenant::remote_timeline_client::INITDB_PATH;
97 : use crate::tenant::storage_layer::DeltaLayer;
98 : use crate::tenant::storage_layer::ImageLayer;
99 : use crate::walredo;
100 : use crate::InitializationOrder;
101 : use std::collections::hash_map::Entry;
102 : use std::collections::HashMap;
103 : use std::collections::HashSet;
104 : use std::fmt::Debug;
105 : use std::fmt::Display;
106 : use std::fs;
107 : use std::fs::File;
108 : use std::sync::atomic::{AtomicU64, Ordering};
109 : use std::sync::Arc;
110 : use std::sync::Mutex;
111 : use std::time::{Duration, Instant};
112 :
113 : use crate::span;
114 : use crate::tenant::timeline::delete::DeleteTimelineFlow;
115 : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
116 : use crate::virtual_file::VirtualFile;
117 : use crate::walredo::PostgresRedoManager;
118 : use crate::TEMP_FILE_SUFFIX;
119 : use once_cell::sync::Lazy;
120 : pub use pageserver_api::models::TenantState;
121 : use tokio::sync::Semaphore;
122 :
123 0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
124 : use utils::{
125 : crashsafe,
126 : generation::Generation,
127 : id::TimelineId,
128 : lsn::{Lsn, RecordLsn},
129 : };
130 :
131 : pub mod blob_io;
132 : pub mod block_io;
133 : pub mod vectored_blob_io;
134 :
135 : pub mod disk_btree;
136 : pub(crate) mod ephemeral_file;
137 : pub mod layer_map;
138 :
139 : pub mod metadata;
140 : pub mod remote_timeline_client;
141 : pub mod storage_layer;
142 :
143 : pub mod config;
144 : pub mod mgr;
145 : pub mod secondary;
146 : pub mod tasks;
147 : pub mod upload_queue;
148 :
149 : pub(crate) mod timeline;
150 :
151 : pub mod size;
152 :
153 : mod gc_block;
154 : pub(crate) mod throttle;
155 :
156 : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
157 : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
158 :
159 : // re-export for use in walreceiver
160 : pub use crate::tenant::timeline::WalReceiverInfo;
161 :
162 : /// The "tenants" part of `tenants/<tenant>/timelines...`
163 : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
164 :
165 : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
166 : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
167 :
168 : /// References to shared objects that are passed into each tenant, such
169 : /// as the shared remote storage client and process initialization state.
170 : #[derive(Clone)]
171 : pub struct TenantSharedResources {
172 : pub broker_client: storage_broker::BrokerClientChannel,
173 : pub remote_storage: GenericRemoteStorage,
174 : pub deletion_queue_client: DeletionQueueClient,
175 : pub l0_flush_global_state: L0FlushGlobalState,
176 : }
177 :
178 : /// A [`Tenant`] is really an _attached_ tenant. The configuration
179 : /// for an attached tenant is a subset of the [`LocationConf`], represented
180 : /// in this struct.
181 : pub(super) struct AttachedTenantConf {
182 : tenant_conf: TenantConfOpt,
183 : location: AttachedLocationConfig,
184 : }
185 :
186 : impl AttachedTenantConf {
187 0 : fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
188 0 : Self {
189 0 : tenant_conf,
190 0 : location,
191 0 : }
192 0 : }
193 :
194 588 : fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
195 588 : match &location_conf.mode {
196 588 : LocationMode::Attached(attach_conf) => Ok(Self {
197 588 : tenant_conf: location_conf.tenant_conf,
198 588 : location: *attach_conf,
199 588 : }),
200 : LocationMode::Secondary(_) => {
201 0 : anyhow::bail!("Attempted to construct AttachedTenantConf from a LocationConf in secondary mode")
202 : }
203 : }
204 588 : }
205 : }
206 : struct TimelinePreload {
207 : timeline_id: TimelineId,
208 : client: RemoteTimelineClient,
209 : index_part: Result<MaybeDeletedIndexPart, DownloadError>,
210 : }
211 :
212 : pub(crate) struct TenantPreload {
213 : timelines: HashMap<TimelineId, TimelinePreload>,
214 : }
215 :
216 : /// When we spawn a tenant, there is a special mode for tenant creation that
217 : /// avoids trying to read anything from remote storage.
218 : pub(crate) enum SpawnMode {
219 : /// Activate as soon as possible
220 : Eager,
221 : /// Lazy activation in the background, with the option to skip the queue if the need comes up
222 : Lazy,
223 : }
224 :
225 : ///
226 : /// Tenant consists of multiple timelines. Keep them in a hash table.
227 : ///
228 : pub struct Tenant {
229 : // Global pageserver config parameters
230 : pub conf: &'static PageServerConf,
231 :
232 : /// The value creation timestamp, used to measure activation delay, see:
233 : /// <https://github.com/neondatabase/neon/issues/4025>
234 : constructed_at: Instant,
235 :
236 : state: watch::Sender<TenantState>,
237 :
238 : // Overridden tenant-specific config parameters.
239 : // We keep TenantConfOpt sturct here to preserve the information
240 : // about parameters that are not set.
241 : // This is necessary to allow global config updates.
242 : tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
243 :
244 : tenant_shard_id: TenantShardId,
245 :
246 : // The detailed sharding information, beyond the number/count in tenant_shard_id
247 : shard_identity: ShardIdentity,
248 :
249 : /// The remote storage generation, used to protect S3 objects from split-brain.
250 : /// Does not change over the lifetime of the [`Tenant`] object.
251 : ///
252 : /// This duplicates the generation stored in LocationConf, but that structure is mutable:
253 : /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
254 : generation: Generation,
255 :
256 : timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
257 :
258 : /// During timeline creation, we first insert the TimelineId to the
259 : /// creating map, then `timelines`, then remove it from the creating map.
260 : /// **Lock order**: if acquring both, acquire`timelines` before `timelines_creating`
261 : timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
262 :
263 : // This mutex prevents creation of new timelines during GC.
264 : // Adding yet another mutex (in addition to `timelines`) is needed because holding
265 : // `timelines` mutex during all GC iteration
266 : // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
267 : // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
268 : // timeout...
269 : gc_cs: tokio::sync::Mutex<()>,
270 : walredo_mgr: Option<Arc<WalRedoManager>>,
271 :
272 : // provides access to timeline data sitting in the remote storage
273 : pub(crate) remote_storage: GenericRemoteStorage,
274 :
275 : // Access to global deletion queue for when this tenant wants to schedule a deletion
276 : deletion_queue_client: DeletionQueueClient,
277 :
278 : /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
279 : cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
280 : cached_synthetic_tenant_size: Arc<AtomicU64>,
281 :
282 : eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
283 :
284 : /// Track repeated failures to compact, so that we can back off.
285 : /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
286 : compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
287 :
288 : /// If the tenant is in Activating state, notify this to encourage it
289 : /// to proceed to Active as soon as possible, rather than waiting for lazy
290 : /// background warmup.
291 : pub(crate) activate_now_sem: tokio::sync::Semaphore,
292 :
293 : // Cancellation token fires when we have entered shutdown(). This is a parent of
294 : // Timelines' cancellation token.
295 : pub(crate) cancel: CancellationToken,
296 :
297 : // Users of the Tenant such as the page service must take this Gate to avoid
298 : // trying to use a Tenant which is shutting down.
299 : pub(crate) gate: Gate,
300 :
301 : /// Throttle applied at the top of [`Timeline::get`].
302 : /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
303 : pub(crate) timeline_get_throttle:
304 : Arc<throttle::Throttle<&'static crate::metrics::tenant_throttling::TimelineGet>>,
305 :
306 : /// An ongoing timeline detach concurrency limiter.
307 : ///
308 : /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
309 : /// to have two running at the same time. A different one can be started if an earlier one
310 : /// has failed for whatever reason.
311 : ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
312 :
313 : /// `index_part.json` based gc blocking reason tracking.
314 : ///
315 : /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
316 : /// proceeding.
317 : pub(crate) gc_block: gc_block::GcBlock,
318 :
319 : l0_flush_global_state: L0FlushGlobalState,
320 : }
321 :
322 : impl std::fmt::Debug for Tenant {
323 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324 0 : write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
325 0 : }
326 : }
327 :
328 : pub(crate) enum WalRedoManager {
329 : Prod(WalredoManagerId, PostgresRedoManager),
330 : #[cfg(test)]
331 : Test(harness::TestRedoManager),
332 : }
333 :
334 0 : #[derive(thiserror::Error, Debug)]
335 : #[error("pageserver is shutting down")]
336 : pub(crate) struct GlobalShutDown;
337 :
338 : impl WalRedoManager {
339 0 : pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
340 0 : let id = WalredoManagerId::next();
341 0 : let arc = Arc::new(Self::Prod(id, mgr));
342 0 : let mut guard = WALREDO_MANAGERS.lock().unwrap();
343 0 : match &mut *guard {
344 0 : Some(map) => {
345 0 : map.insert(id, Arc::downgrade(&arc));
346 0 : Ok(arc)
347 : }
348 0 : None => Err(GlobalShutDown),
349 : }
350 0 : }
351 : }
352 :
353 : impl Drop for WalRedoManager {
354 30 : fn drop(&mut self) {
355 30 : match self {
356 0 : Self::Prod(id, _) => {
357 0 : let mut guard = WALREDO_MANAGERS.lock().unwrap();
358 0 : if let Some(map) = &mut *guard {
359 0 : map.remove(id).expect("new() registers, drop() unregisters");
360 0 : }
361 : }
362 : #[cfg(test)]
363 30 : Self::Test(_) => {
364 30 : // Not applicable to test redo manager
365 30 : }
366 : }
367 30 : }
368 : }
369 :
370 : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
371 : /// the walredo processes outside of the regular order.
372 : ///
373 : /// This is necessary to work around a systemd bug where it freezes if there are
374 : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
375 : #[allow(clippy::type_complexity)]
376 : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
377 : Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
378 0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
379 : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
380 : pub(crate) struct WalredoManagerId(u64);
381 : impl WalredoManagerId {
382 0 : pub fn next() -> Self {
383 : static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
384 0 : let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
385 0 : if id == 0 {
386 0 : panic!("WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique");
387 0 : }
388 0 : Self(id)
389 0 : }
390 : }
391 :
392 : #[cfg(test)]
393 : impl From<harness::TestRedoManager> for WalRedoManager {
394 564 : fn from(mgr: harness::TestRedoManager) -> Self {
395 564 : Self::Test(mgr)
396 564 : }
397 : }
398 :
399 : impl WalRedoManager {
400 18 : pub(crate) async fn shutdown(&self) -> bool {
401 18 : match self {
402 0 : Self::Prod(_, mgr) => mgr.shutdown().await,
403 : #[cfg(test)]
404 : Self::Test(_) => {
405 : // Not applicable to test redo manager
406 18 : true
407 : }
408 : }
409 18 : }
410 :
411 0 : pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
412 0 : match self {
413 0 : Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
414 0 : #[cfg(test)]
415 0 : Self::Test(_) => {
416 0 : // Not applicable to test redo manager
417 0 : }
418 0 : }
419 0 : }
420 :
421 : /// # Cancel-Safety
422 : ///
423 : /// This method is cancellation-safe.
424 978 : pub async fn request_redo(
425 978 : &self,
426 978 : key: crate::repository::Key,
427 978 : lsn: Lsn,
428 978 : base_img: Option<(Lsn, bytes::Bytes)>,
429 978 : records: Vec<(Lsn, crate::walrecord::NeonWalRecord)>,
430 978 : pg_version: u32,
431 978 : ) -> Result<bytes::Bytes, walredo::Error> {
432 978 : match self {
433 0 : Self::Prod(_, mgr) => {
434 0 : mgr.request_redo(key, lsn, base_img, records, pg_version)
435 0 : .await
436 : }
437 : #[cfg(test)]
438 978 : Self::Test(mgr) => {
439 978 : mgr.request_redo(key, lsn, base_img, records, pg_version)
440 0 : .await
441 : }
442 : }
443 978 : }
444 :
445 0 : pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
446 0 : match self {
447 0 : WalRedoManager::Prod(_, m) => Some(m.status()),
448 0 : #[cfg(test)]
449 0 : WalRedoManager::Test(_) => None,
450 0 : }
451 0 : }
452 : }
453 :
454 0 : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
455 : pub enum GetTimelineError {
456 : #[error("Timeline is shutting down")]
457 : ShuttingDown,
458 : #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
459 : NotActive {
460 : tenant_id: TenantShardId,
461 : timeline_id: TimelineId,
462 : state: TimelineState,
463 : },
464 : #[error("Timeline {tenant_id}/{timeline_id} was not found")]
465 : NotFound {
466 : tenant_id: TenantShardId,
467 : timeline_id: TimelineId,
468 : },
469 : }
470 :
471 0 : #[derive(Debug, thiserror::Error)]
472 : pub enum LoadLocalTimelineError {
473 : #[error("FailedToLoad")]
474 : Load(#[source] anyhow::Error),
475 : #[error("FailedToResumeDeletion")]
476 : ResumeDeletion(#[source] anyhow::Error),
477 : }
478 :
479 0 : #[derive(thiserror::Error)]
480 : pub enum DeleteTimelineError {
481 : #[error("NotFound")]
482 : NotFound,
483 :
484 : #[error("HasChildren")]
485 : HasChildren(Vec<TimelineId>),
486 :
487 : #[error("Timeline deletion is already in progress")]
488 : AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
489 :
490 : #[error(transparent)]
491 : Other(#[from] anyhow::Error),
492 : }
493 :
494 : impl Debug for DeleteTimelineError {
495 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
496 0 : match self {
497 0 : Self::NotFound => write!(f, "NotFound"),
498 0 : Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
499 0 : Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
500 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
501 : }
502 0 : }
503 : }
504 :
505 0 : #[derive(thiserror::Error)]
506 : pub enum TimelineArchivalError {
507 : #[error("NotFound")]
508 : NotFound,
509 :
510 : #[error("Timeout")]
511 : Timeout,
512 :
513 : #[error("ancestor is archived: {}", .0)]
514 : HasArchivedParent(TimelineId),
515 :
516 : #[error("HasUnarchivedChildren")]
517 : HasUnarchivedChildren(Vec<TimelineId>),
518 :
519 : #[error("Timeline archival is already in progress")]
520 : AlreadyInProgress,
521 :
522 : #[error(transparent)]
523 : Other(#[from] anyhow::Error),
524 : }
525 :
526 : impl Debug for TimelineArchivalError {
527 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
528 0 : match self {
529 0 : Self::NotFound => write!(f, "NotFound"),
530 0 : Self::Timeout => write!(f, "Timeout"),
531 0 : Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
532 0 : Self::HasUnarchivedChildren(c) => {
533 0 : f.debug_tuple("HasUnarchivedChildren").field(c).finish()
534 : }
535 0 : Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
536 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
537 : }
538 0 : }
539 : }
540 :
541 : pub enum SetStoppingError {
542 : AlreadyStopping(completion::Barrier),
543 : Broken,
544 : }
545 :
546 : impl Debug for SetStoppingError {
547 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
548 0 : match self {
549 0 : Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
550 0 : Self::Broken => write!(f, "Broken"),
551 : }
552 0 : }
553 : }
554 :
555 0 : #[derive(thiserror::Error, Debug)]
556 : pub enum CreateTimelineError {
557 : #[error("creation of timeline with the given ID is in progress")]
558 : AlreadyCreating,
559 : #[error("timeline already exists with different parameters")]
560 : Conflict,
561 : #[error(transparent)]
562 : AncestorLsn(anyhow::Error),
563 : #[error("ancestor timeline is not active")]
564 : AncestorNotActive,
565 : #[error("tenant shutting down")]
566 : ShuttingDown,
567 : #[error(transparent)]
568 : Other(#[from] anyhow::Error),
569 : }
570 :
571 : #[derive(thiserror::Error, Debug)]
572 : enum InitdbError {
573 : Other(anyhow::Error),
574 : Cancelled,
575 : Spawn(std::io::Result<()>),
576 : Failed(std::process::ExitStatus, Vec<u8>),
577 : }
578 :
579 : impl fmt::Display for InitdbError {
580 0 : fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
581 0 : match self {
582 0 : InitdbError::Cancelled => write!(f, "Operation was cancelled"),
583 0 : InitdbError::Spawn(e) => write!(f, "Spawn error: {:?}", e),
584 0 : InitdbError::Failed(status, stderr) => write!(
585 0 : f,
586 0 : "Command failed with status {:?}: {}",
587 0 : status,
588 0 : String::from_utf8_lossy(stderr)
589 0 : ),
590 0 : InitdbError::Other(e) => write!(f, "Error: {:?}", e),
591 : }
592 0 : }
593 : }
594 :
595 : impl From<std::io::Error> for InitdbError {
596 0 : fn from(error: std::io::Error) -> Self {
597 0 : InitdbError::Spawn(Err(error))
598 0 : }
599 : }
600 :
601 : enum CreateTimelineCause {
602 : Load,
603 : Delete,
604 : }
605 :
606 0 : #[derive(thiserror::Error, Debug)]
607 : pub(crate) enum GcError {
608 : // The tenant is shutting down
609 : #[error("tenant shutting down")]
610 : TenantCancelled,
611 :
612 : // The tenant is shutting down
613 : #[error("timeline shutting down")]
614 : TimelineCancelled,
615 :
616 : // The tenant is in a state inelegible to run GC
617 : #[error("not active")]
618 : NotActive,
619 :
620 : // A requested GC cutoff LSN was invalid, for example it tried to move backwards
621 : #[error("not active")]
622 : BadLsn { why: String },
623 :
624 : // A remote storage error while scheduling updates after compaction
625 : #[error(transparent)]
626 : Remote(anyhow::Error),
627 :
628 : // An error reading while calculating GC cutoffs
629 : #[error(transparent)]
630 : GcCutoffs(PageReconstructError),
631 :
632 : // If GC was invoked for a particular timeline, this error means it didn't exist
633 : #[error("timeline not found")]
634 : TimelineNotFound,
635 : }
636 :
637 : impl From<PageReconstructError> for GcError {
638 0 : fn from(value: PageReconstructError) -> Self {
639 0 : match value {
640 0 : PageReconstructError::Cancelled => Self::TimelineCancelled,
641 0 : other => Self::GcCutoffs(other),
642 : }
643 0 : }
644 : }
645 :
646 : impl From<NotInitialized> for GcError {
647 0 : fn from(value: NotInitialized) -> Self {
648 0 : match value {
649 0 : NotInitialized::Uninitialized => GcError::Remote(value.into()),
650 0 : NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
651 : }
652 0 : }
653 : }
654 :
655 : impl From<timeline::layer_manager::Shutdown> for GcError {
656 0 : fn from(_: timeline::layer_manager::Shutdown) -> Self {
657 0 : GcError::TimelineCancelled
658 0 : }
659 : }
660 :
661 0 : #[derive(thiserror::Error, Debug)]
662 : pub(crate) enum LoadConfigError {
663 : #[error("TOML deserialization error: '{0}'")]
664 : DeserializeToml(#[from] toml_edit::de::Error),
665 :
666 : #[error("Config not found at {0}")]
667 : NotFound(Utf8PathBuf),
668 : }
669 :
670 : impl Tenant {
671 : /// Yet another helper for timeline initialization.
672 : ///
673 : /// - Initializes the Timeline struct and inserts it into the tenant's hash map
674 : /// - Scans the local timeline directory for layer files and builds the layer map
675 : /// - Downloads remote index file and adds remote files to the layer map
676 : /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
677 : ///
678 : /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
679 : /// it is marked as Active.
680 : #[allow(clippy::too_many_arguments)]
681 18 : async fn timeline_init_and_sync(
682 18 : &self,
683 18 : timeline_id: TimelineId,
684 18 : resources: TimelineResources,
685 18 : index_part: Option<IndexPart>,
686 18 : metadata: TimelineMetadata,
687 18 : ancestor: Option<Arc<Timeline>>,
688 18 : last_aux_file_policy: Option<AuxFilePolicy>,
689 18 : _ctx: &RequestContext,
690 18 : ) -> anyhow::Result<()> {
691 18 : let tenant_id = self.tenant_shard_id;
692 :
693 18 : let timeline = self.create_timeline_struct(
694 18 : timeline_id,
695 18 : &metadata,
696 18 : ancestor.clone(),
697 18 : resources,
698 18 : CreateTimelineCause::Load,
699 18 : // This could be derived from ancestor branch + index part. Though the only caller of `timeline_init_and_sync` is `load_remote_timeline`,
700 18 : // there will potentially be other caller of this function in the future, and we don't know whether `index_part` or `ancestor` takes precedence.
701 18 : // Therefore, we pass this field explicitly for now, and remove it once we fully migrate to aux file v2.
702 18 : last_aux_file_policy,
703 18 : )?;
704 18 : let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
705 18 : anyhow::ensure!(
706 18 : disk_consistent_lsn.is_valid(),
707 0 : "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
708 : );
709 18 : assert_eq!(
710 18 : disk_consistent_lsn,
711 18 : metadata.disk_consistent_lsn(),
712 0 : "these are used interchangeably"
713 : );
714 :
715 18 : if let Some(index_part) = index_part.as_ref() {
716 18 : timeline.remote_client.init_upload_queue(index_part)?;
717 :
718 18 : timeline
719 18 : .last_aux_file_policy
720 18 : .store(index_part.last_aux_file_policy());
721 : } else {
722 : // No data on the remote storage, but we have local metadata file. We can end up
723 : // here with timeline_create being interrupted before finishing index part upload.
724 : // By doing what we do here, the index part upload is retried.
725 : // If control plane retries timeline creation in the meantime, the mgmt API handler
726 : // for timeline creation will coalesce on the upload we queue here.
727 :
728 : // FIXME: this branch should be dead code as we no longer write local metadata.
729 :
730 0 : timeline
731 0 : .remote_client
732 0 : .init_upload_queue_for_empty_remote(&metadata)?;
733 0 : timeline
734 0 : .remote_client
735 0 : .schedule_index_upload_for_full_metadata_update(&metadata)?;
736 : }
737 :
738 18 : timeline
739 18 : .load_layer_map(disk_consistent_lsn, index_part)
740 16 : .await
741 18 : .with_context(|| {
742 0 : format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
743 18 : })?;
744 :
745 : {
746 : // avoiding holding it across awaits
747 18 : let mut timelines_accessor = self.timelines.lock().unwrap();
748 18 : match timelines_accessor.entry(timeline_id) {
749 : // We should never try and load the same timeline twice during startup
750 : Entry::Occupied(_) => {
751 0 : unreachable!(
752 0 : "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
753 0 : );
754 : }
755 18 : Entry::Vacant(v) => {
756 18 : v.insert(Arc::clone(&timeline));
757 18 : timeline.maybe_spawn_flush_loop();
758 18 : }
759 18 : }
760 18 : };
761 18 :
762 18 : // Sanity check: a timeline should have some content.
763 18 : anyhow::ensure!(
764 18 : ancestor.is_some()
765 12 : || timeline
766 12 : .layers
767 12 : .read()
768 0 : .await
769 12 : .layer_map()
770 12 : .expect("currently loading, layer manager cannot be shutdown already")
771 12 : .iter_historic_layers()
772 12 : .next()
773 12 : .is_some(),
774 0 : "Timeline has no ancestor and no layer files"
775 : );
776 :
777 18 : Ok(())
778 18 : }
779 :
780 : /// Attach a tenant that's available in cloud storage.
781 : ///
782 : /// This returns quickly, after just creating the in-memory object
783 : /// Tenant struct and launching a background task to download
784 : /// the remote index files. On return, the tenant is most likely still in
785 : /// Attaching state, and it will become Active once the background task
786 : /// finishes. You can use wait_until_active() to wait for the task to
787 : /// complete.
788 : ///
789 : #[allow(clippy::too_many_arguments)]
790 0 : pub(crate) fn spawn(
791 0 : conf: &'static PageServerConf,
792 0 : tenant_shard_id: TenantShardId,
793 0 : resources: TenantSharedResources,
794 0 : attached_conf: AttachedTenantConf,
795 0 : shard_identity: ShardIdentity,
796 0 : init_order: Option<InitializationOrder>,
797 0 : mode: SpawnMode,
798 0 : ctx: &RequestContext,
799 0 : ) -> Result<Arc<Tenant>, GlobalShutDown> {
800 0 : let wal_redo_manager =
801 0 : WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
802 :
803 : let TenantSharedResources {
804 0 : broker_client,
805 0 : remote_storage,
806 0 : deletion_queue_client,
807 0 : l0_flush_global_state,
808 0 : } = resources;
809 0 :
810 0 : let attach_mode = attached_conf.location.attach_mode;
811 0 : let generation = attached_conf.location.generation;
812 0 :
813 0 : let tenant = Arc::new(Tenant::new(
814 0 : TenantState::Attaching,
815 0 : conf,
816 0 : attached_conf,
817 0 : shard_identity,
818 0 : Some(wal_redo_manager),
819 0 : tenant_shard_id,
820 0 : remote_storage.clone(),
821 0 : deletion_queue_client,
822 0 : l0_flush_global_state,
823 0 : ));
824 0 :
825 0 : // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
826 0 : // we shut down while attaching.
827 0 : let attach_gate_guard = tenant
828 0 : .gate
829 0 : .enter()
830 0 : .expect("We just created the Tenant: nothing else can have shut it down yet");
831 0 :
832 0 : // Do all the hard work in the background
833 0 : let tenant_clone = Arc::clone(&tenant);
834 0 : let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
835 0 : task_mgr::spawn(
836 0 : &tokio::runtime::Handle::current(),
837 0 : TaskKind::Attach,
838 0 : tenant_shard_id,
839 0 : None,
840 0 : "attach tenant",
841 0 : async move {
842 0 :
843 0 : info!(
844 : ?attach_mode,
845 0 : "Attaching tenant"
846 : );
847 :
848 0 : let _gate_guard = attach_gate_guard;
849 0 :
850 0 : // Is this tenant being spawned as part of process startup?
851 0 : let starting_up = init_order.is_some();
852 0 : scopeguard::defer! {
853 0 : if starting_up {
854 0 : TENANT.startup_complete.inc();
855 0 : }
856 0 : }
857 :
858 : // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
859 : enum BrokenVerbosity {
860 : Error,
861 : Info
862 : }
863 0 : let make_broken =
864 0 : |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
865 0 : match verbosity {
866 : BrokenVerbosity::Info => {
867 0 : info!("attach cancelled, setting tenant state to Broken: {err}");
868 : },
869 : BrokenVerbosity::Error => {
870 0 : error!("attach failed, setting tenant state to Broken: {err:?}");
871 : }
872 : }
873 0 : t.state.send_modify(|state| {
874 0 : // The Stopping case is for when we have passed control on to DeleteTenantFlow:
875 0 : // if it errors, we will call make_broken when tenant is already in Stopping.
876 0 : assert!(
877 0 : matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
878 0 : "the attach task owns the tenant state until activation is complete"
879 : );
880 :
881 0 : *state = TenantState::broken_from_reason(err.to_string());
882 0 : });
883 0 : };
884 :
885 : // TODO: should also be rejecting tenant conf changes that violate this check.
886 0 : if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
887 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
888 0 : return Ok(());
889 0 : }
890 0 :
891 0 : let mut init_order = init_order;
892 0 : // take the completion because initial tenant loading will complete when all of
893 0 : // these tasks complete.
894 0 : let _completion = init_order
895 0 : .as_mut()
896 0 : .and_then(|x| x.initial_tenant_load.take());
897 0 : let remote_load_completion = init_order
898 0 : .as_mut()
899 0 : .and_then(|x| x.initial_tenant_load_remote.take());
900 :
901 : enum AttachType<'a> {
902 : /// We are attaching this tenant lazily in the background.
903 : Warmup {
904 : _permit: tokio::sync::SemaphorePermit<'a>,
905 : during_startup: bool
906 : },
907 : /// We are attaching this tenant as soon as we can, because for example an
908 : /// endpoint tried to access it.
909 : OnDemand,
910 : /// During normal operations after startup, we are attaching a tenant, and
911 : /// eager attach was requested.
912 : Normal,
913 : }
914 :
915 0 : let attach_type = if matches!(mode, SpawnMode::Lazy) {
916 : // Before doing any I/O, wait for at least one of:
917 : // - A client attempting to access to this tenant (on-demand loading)
918 : // - A permit becoming available in the warmup semaphore (background warmup)
919 :
920 0 : tokio::select!(
921 0 : permit = tenant_clone.activate_now_sem.acquire() => {
922 0 : let _ = permit.expect("activate_now_sem is never closed");
923 0 : tracing::info!("Activating tenant (on-demand)");
924 0 : AttachType::OnDemand
925 : },
926 0 : permit = conf.concurrent_tenant_warmup.inner().acquire() => {
927 0 : let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
928 0 : tracing::info!("Activating tenant (warmup)");
929 0 : AttachType::Warmup {
930 0 : _permit,
931 0 : during_startup: init_order.is_some()
932 0 : }
933 : }
934 0 : _ = tenant_clone.cancel.cancelled() => {
935 : // This is safe, but should be pretty rare: it is interesting if a tenant
936 : // stayed in Activating for such a long time that shutdown found it in
937 : // that state.
938 0 : tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
939 : // Make the tenant broken so that set_stopping will not hang waiting for it to leave
940 : // the Attaching state. This is an over-reaction (nothing really broke, the tenant is
941 : // just shutting down), but ensures progress.
942 0 : make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
943 0 : return Ok(());
944 : },
945 : )
946 : } else {
947 : // SpawnMode::{Create,Eager} always cause jumping ahead of the
948 : // concurrent_tenant_warmup queue
949 0 : AttachType::Normal
950 : };
951 :
952 0 : let preload = match &mode {
953 : SpawnMode::Eager | SpawnMode::Lazy => {
954 0 : let _preload_timer = TENANT.preload.start_timer();
955 0 : let res = tenant_clone
956 0 : .preload(&remote_storage, task_mgr::shutdown_token())
957 0 : .await;
958 0 : match res {
959 0 : Ok(p) => Some(p),
960 0 : Err(e) => {
961 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
962 0 : return Ok(());
963 : }
964 : }
965 : }
966 :
967 : };
968 :
969 : // Remote preload is complete.
970 0 : drop(remote_load_completion);
971 :
972 : // We will time the duration of the attach phase unless this is a creation (attach will do no work)
973 0 : let attached = {
974 0 : let _attach_timer = Some(TENANT.attach.start_timer());
975 0 : tenant_clone.attach(preload, &ctx).await
976 : };
977 :
978 0 : match attached {
979 : Ok(()) => {
980 0 : info!("attach finished, activating");
981 0 : tenant_clone.activate(broker_client, None, &ctx);
982 : }
983 0 : Err(e) => {
984 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
985 0 : }
986 : }
987 :
988 : // If we are doing an opportunistic warmup attachment at startup, initialize
989 : // logical size at the same time. This is better than starting a bunch of idle tenants
990 : // with cold caches and then coming back later to initialize their logical sizes.
991 : //
992 : // It also prevents the warmup proccess competing with the concurrency limit on
993 : // logical size calculations: if logical size calculation semaphore is saturated,
994 : // then warmup will wait for that before proceeding to the next tenant.
995 0 : if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
996 0 : let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
997 0 : tracing::info!("Waiting for initial logical sizes while warming up...");
998 0 : while futs.next().await.is_some() {}
999 0 : tracing::info!("Warm-up complete");
1000 0 : }
1001 :
1002 0 : Ok(())
1003 0 : }
1004 0 : .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
1005 : );
1006 0 : Ok(tenant)
1007 0 : }
1008 :
1009 564 : #[instrument(skip_all)]
1010 : pub(crate) async fn preload(
1011 : self: &Arc<Self>,
1012 : remote_storage: &GenericRemoteStorage,
1013 : cancel: CancellationToken,
1014 : ) -> anyhow::Result<TenantPreload> {
1015 : span::debug_assert_current_span_has_tenant_id();
1016 : // Get list of remote timelines
1017 : // download index files for every tenant timeline
1018 : info!("listing remote timelines");
1019 : let (remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
1020 : remote_storage,
1021 : self.tenant_shard_id,
1022 : cancel.clone(),
1023 : )
1024 : .await?;
1025 :
1026 : info!("found {} timelines", remote_timeline_ids.len(),);
1027 :
1028 : for k in other_keys {
1029 : warn!("Unexpected non timeline key {k}");
1030 : }
1031 :
1032 : Ok(TenantPreload {
1033 : timelines: Self::load_timeline_metadata(
1034 : self,
1035 : remote_timeline_ids,
1036 : remote_storage,
1037 : cancel,
1038 : )
1039 : .await?,
1040 : })
1041 : }
1042 :
1043 : ///
1044 : /// Background task that downloads all data for a tenant and brings it to Active state.
1045 : ///
1046 : /// No background tasks are started as part of this routine.
1047 : ///
1048 564 : async fn attach(
1049 564 : self: &Arc<Tenant>,
1050 564 : preload: Option<TenantPreload>,
1051 564 : ctx: &RequestContext,
1052 564 : ) -> anyhow::Result<()> {
1053 564 : span::debug_assert_current_span_has_tenant_id();
1054 564 :
1055 564 : failpoint_support::sleep_millis_async!("before-attaching-tenant");
1056 :
1057 564 : let Some(preload) = preload else {
1058 0 : anyhow::bail!("local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624");
1059 : };
1060 :
1061 564 : let mut timelines_to_resume_deletions = vec![];
1062 564 :
1063 564 : let mut remote_index_and_client = HashMap::new();
1064 564 : let mut timeline_ancestors = HashMap::new();
1065 564 : let mut existent_timelines = HashSet::new();
1066 582 : for (timeline_id, preload) in preload.timelines {
1067 18 : let index_part = match preload.index_part {
1068 18 : Ok(i) => {
1069 18 : debug!("remote index part exists for timeline {timeline_id}");
1070 : // We found index_part on the remote, this is the standard case.
1071 18 : existent_timelines.insert(timeline_id);
1072 18 : i
1073 : }
1074 : Err(DownloadError::NotFound) => {
1075 : // There is no index_part on the remote. We only get here
1076 : // if there is some prefix for the timeline in the remote storage.
1077 : // This can e.g. be the initdb.tar.zst archive, maybe a
1078 : // remnant from a prior incomplete creation or deletion attempt.
1079 : // Delete the local directory as the deciding criterion for a
1080 : // timeline's existence is presence of index_part.
1081 0 : info!(%timeline_id, "index_part not found on remote");
1082 0 : continue;
1083 : }
1084 0 : Err(e) => {
1085 0 : // Some (possibly ephemeral) error happened during index_part download.
1086 0 : // Pretend the timeline exists to not delete the timeline directory,
1087 0 : // as it might be a temporary issue and we don't want to re-download
1088 0 : // everything after it resolves.
1089 0 : warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
1090 :
1091 0 : existent_timelines.insert(timeline_id);
1092 0 : continue;
1093 : }
1094 : };
1095 18 : match index_part {
1096 18 : MaybeDeletedIndexPart::IndexPart(index_part) => {
1097 18 : timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
1098 18 : remote_index_and_client.insert(timeline_id, (index_part, preload.client));
1099 18 : }
1100 0 : MaybeDeletedIndexPart::Deleted(index_part) => {
1101 0 : info!(
1102 0 : "timeline {} is deleted, picking to resume deletion",
1103 : timeline_id
1104 : );
1105 0 : timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
1106 : }
1107 : }
1108 : }
1109 :
1110 564 : let mut gc_blocks = HashMap::new();
1111 :
1112 : // For every timeline, download the metadata file, scan the local directory,
1113 : // and build a layer map that contains an entry for each remote and local
1114 : // layer file.
1115 564 : let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
1116 582 : for (timeline_id, remote_metadata) in sorted_timelines {
1117 18 : let (index_part, remote_client) = remote_index_and_client
1118 18 : .remove(&timeline_id)
1119 18 : .expect("just put it in above");
1120 :
1121 18 : if let Some(blocking) = index_part.gc_blocking.as_ref() {
1122 : // could just filter these away, but it helps while testing
1123 0 : anyhow::ensure!(
1124 0 : !blocking.reasons.is_empty(),
1125 0 : "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
1126 : );
1127 0 : let prev = gc_blocks.insert(timeline_id, blocking.reasons);
1128 0 : assert!(prev.is_none());
1129 18 : }
1130 :
1131 : // TODO again handle early failure
1132 18 : self.load_remote_timeline(
1133 18 : timeline_id,
1134 18 : index_part,
1135 18 : remote_metadata,
1136 18 : TimelineResources {
1137 18 : remote_client,
1138 18 : timeline_get_throttle: self.timeline_get_throttle.clone(),
1139 18 : l0_flush_global_state: self.l0_flush_global_state.clone(),
1140 18 : },
1141 18 : ctx,
1142 18 : )
1143 31 : .await
1144 18 : .with_context(|| {
1145 0 : format!(
1146 0 : "failed to load remote timeline {} for tenant {}",
1147 0 : timeline_id, self.tenant_shard_id
1148 0 : )
1149 18 : })?;
1150 : }
1151 :
1152 : // Walk through deleted timelines, resume deletion
1153 564 : for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
1154 0 : remote_timeline_client
1155 0 : .init_upload_queue_stopped_to_continue_deletion(&index_part)
1156 0 : .context("init queue stopped")
1157 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1158 :
1159 0 : DeleteTimelineFlow::resume_deletion(
1160 0 : Arc::clone(self),
1161 0 : timeline_id,
1162 0 : &index_part.metadata,
1163 0 : remote_timeline_client,
1164 0 : )
1165 0 : .instrument(tracing::info_span!("timeline_delete", %timeline_id))
1166 0 : .await
1167 0 : .context("resume_deletion")
1168 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1169 : }
1170 :
1171 : // The local filesystem contents are a cache of what's in the remote IndexPart;
1172 : // IndexPart is the source of truth.
1173 564 : self.clean_up_timelines(&existent_timelines)?;
1174 :
1175 564 : self.gc_block.set_scanned(gc_blocks);
1176 564 :
1177 564 : fail::fail_point!("attach-before-activate", |_| {
1178 0 : anyhow::bail!("attach-before-activate");
1179 564 : });
1180 564 : failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
1181 :
1182 564 : info!("Done");
1183 :
1184 564 : Ok(())
1185 564 : }
1186 :
1187 : /// Check for any local timeline directories that are temporary, or do not correspond to a
1188 : /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
1189 : /// if a timeline was deleted while the tenant was attached to a different pageserver.
1190 564 : fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
1191 564 : let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
1192 :
1193 564 : let entries = match timelines_dir.read_dir_utf8() {
1194 564 : Ok(d) => d,
1195 0 : Err(e) => {
1196 0 : if e.kind() == std::io::ErrorKind::NotFound {
1197 0 : return Ok(());
1198 : } else {
1199 0 : return Err(e).context("list timelines directory for tenant");
1200 : }
1201 : }
1202 : };
1203 :
1204 588 : for entry in entries {
1205 24 : let entry = entry.context("read timeline dir entry")?;
1206 24 : let entry_path = entry.path();
1207 :
1208 24 : let purge = if crate::is_temporary(entry_path)
1209 : // TODO: remove uninit mark code (https://github.com/neondatabase/neon/issues/5718)
1210 24 : || is_uninit_mark(entry_path)
1211 24 : || crate::is_delete_mark(entry_path)
1212 : {
1213 0 : true
1214 : } else {
1215 24 : match TimelineId::try_from(entry_path.file_name()) {
1216 24 : Ok(i) => {
1217 24 : // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
1218 24 : !existent_timelines.contains(&i)
1219 : }
1220 0 : Err(e) => {
1221 0 : tracing::warn!(
1222 0 : "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
1223 : );
1224 : // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
1225 0 : false
1226 : }
1227 : }
1228 : };
1229 :
1230 24 : if purge {
1231 6 : tracing::info!("Purging stale timeline dentry {entry_path}");
1232 6 : if let Err(e) = match entry.file_type() {
1233 6 : Ok(t) => if t.is_dir() {
1234 6 : std::fs::remove_dir_all(entry_path)
1235 : } else {
1236 0 : std::fs::remove_file(entry_path)
1237 : }
1238 6 : .or_else(fs_ext::ignore_not_found),
1239 0 : Err(e) => Err(e),
1240 : } {
1241 0 : tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
1242 6 : }
1243 18 : }
1244 : }
1245 :
1246 564 : Ok(())
1247 564 : }
1248 :
1249 : /// Get sum of all remote timelines sizes
1250 : ///
1251 : /// This function relies on the index_part instead of listing the remote storage
1252 0 : pub fn remote_size(&self) -> u64 {
1253 0 : let mut size = 0;
1254 :
1255 0 : for timeline in self.list_timelines() {
1256 0 : size += timeline.remote_client.get_remote_physical_size();
1257 0 : }
1258 :
1259 0 : size
1260 0 : }
1261 :
1262 18 : #[instrument(skip_all, fields(timeline_id=%timeline_id))]
1263 : async fn load_remote_timeline(
1264 : &self,
1265 : timeline_id: TimelineId,
1266 : index_part: IndexPart,
1267 : remote_metadata: TimelineMetadata,
1268 : resources: TimelineResources,
1269 : ctx: &RequestContext,
1270 : ) -> anyhow::Result<()> {
1271 : span::debug_assert_current_span_has_tenant_id();
1272 :
1273 : info!("downloading index file for timeline {}", timeline_id);
1274 : tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
1275 : .await
1276 : .context("Failed to create new timeline directory")?;
1277 :
1278 : let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
1279 : let timelines = self.timelines.lock().unwrap();
1280 : Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
1281 0 : || {
1282 0 : anyhow::anyhow!(
1283 0 : "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
1284 0 : )
1285 0 : },
1286 : )?))
1287 : } else {
1288 : None
1289 : };
1290 :
1291 : let last_aux_file_policy = index_part.last_aux_file_policy();
1292 :
1293 : self.timeline_init_and_sync(
1294 : timeline_id,
1295 : resources,
1296 : Some(index_part),
1297 : remote_metadata,
1298 : ancestor,
1299 : last_aux_file_policy,
1300 : ctx,
1301 : )
1302 : .await
1303 : }
1304 :
1305 564 : async fn load_timeline_metadata(
1306 564 : self: &Arc<Tenant>,
1307 564 : timeline_ids: HashSet<TimelineId>,
1308 564 : remote_storage: &GenericRemoteStorage,
1309 564 : cancel: CancellationToken,
1310 564 : ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
1311 564 : let mut part_downloads = JoinSet::new();
1312 582 : for timeline_id in timeline_ids {
1313 18 : let client = RemoteTimelineClient::new(
1314 18 : remote_storage.clone(),
1315 18 : self.deletion_queue_client.clone(),
1316 18 : self.conf,
1317 18 : self.tenant_shard_id,
1318 18 : timeline_id,
1319 18 : self.generation,
1320 18 : );
1321 18 : let cancel_clone = cancel.clone();
1322 18 : part_downloads.spawn(
1323 18 : async move {
1324 18 : debug!("starting index part download");
1325 :
1326 69 : let index_part = client.download_index_file(&cancel_clone).await;
1327 :
1328 18 : debug!("finished index part download");
1329 :
1330 18 : Result::<_, anyhow::Error>::Ok(TimelinePreload {
1331 18 : client,
1332 18 : timeline_id,
1333 18 : index_part,
1334 18 : })
1335 18 : }
1336 18 : .map(move |res| {
1337 18 : res.with_context(|| format!("download index part for timeline {timeline_id}"))
1338 18 : })
1339 18 : .instrument(info_span!("download_index_part", %timeline_id)),
1340 : );
1341 : }
1342 :
1343 564 : let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
1344 :
1345 : loop {
1346 582 : tokio::select!(
1347 582 : next = part_downloads.join_next() => {
1348 582 : match next {
1349 18 : Some(result) => {
1350 18 : let preload_result = result.context("join preload task")?;
1351 18 : let preload = preload_result?;
1352 18 : timeline_preloads.insert(preload.timeline_id, preload);
1353 : },
1354 : None => {
1355 564 : break;
1356 : }
1357 : }
1358 : },
1359 582 : _ = cancel.cancelled() => {
1360 0 : anyhow::bail!("Cancelled while waiting for remote index download")
1361 : }
1362 : )
1363 : }
1364 :
1365 564 : Ok(timeline_preloads)
1366 564 : }
1367 :
1368 0 : pub(crate) async fn apply_timeline_archival_config(
1369 0 : &self,
1370 0 : timeline_id: TimelineId,
1371 0 : state: TimelineArchivalState,
1372 0 : ) -> Result<(), TimelineArchivalError> {
1373 0 : info!("setting timeline archival config");
1374 0 : let timeline = {
1375 0 : let timelines = self.timelines.lock().unwrap();
1376 :
1377 0 : let Some(timeline) = timelines.get(&timeline_id) else {
1378 0 : return Err(TimelineArchivalError::NotFound);
1379 : };
1380 :
1381 0 : if state == TimelineArchivalState::Unarchived {
1382 0 : if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
1383 0 : if ancestor_timeline.is_archived() == Some(true) {
1384 0 : return Err(TimelineArchivalError::HasArchivedParent(
1385 0 : ancestor_timeline.timeline_id,
1386 0 : ));
1387 0 : }
1388 0 : }
1389 0 : }
1390 :
1391 : // Ensure that there are no non-archived child timelines
1392 0 : let children: Vec<TimelineId> = timelines
1393 0 : .iter()
1394 0 : .filter_map(|(id, entry)| {
1395 0 : if entry.get_ancestor_timeline_id() != Some(timeline_id) {
1396 0 : return None;
1397 0 : }
1398 0 : if entry.is_archived() == Some(true) {
1399 0 : return None;
1400 0 : }
1401 0 : Some(*id)
1402 0 : })
1403 0 : .collect();
1404 0 :
1405 0 : if !children.is_empty() && state == TimelineArchivalState::Archived {
1406 0 : return Err(TimelineArchivalError::HasUnarchivedChildren(children));
1407 0 : }
1408 0 : Arc::clone(timeline)
1409 : };
1410 :
1411 0 : let upload_needed = timeline
1412 0 : .remote_client
1413 0 : .schedule_index_upload_for_timeline_archival_state(state)?;
1414 :
1415 0 : if upload_needed {
1416 0 : info!("Uploading new state");
1417 : const MAX_WAIT: Duration = Duration::from_secs(10);
1418 0 : let Ok(v) =
1419 0 : tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
1420 : else {
1421 0 : tracing::warn!("reached timeout for waiting on upload queue");
1422 0 : return Err(TimelineArchivalError::Timeout);
1423 : };
1424 0 : v.map_err(|e| TimelineArchivalError::Other(anyhow::anyhow!(e)))?;
1425 0 : }
1426 0 : Ok(())
1427 0 : }
1428 :
1429 12 : pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
1430 12 : self.tenant_shard_id
1431 12 : }
1432 :
1433 : /// Get Timeline handle for given Neon timeline ID.
1434 : /// This function is idempotent. It doesn't change internal state in any way.
1435 666 : pub fn get_timeline(
1436 666 : &self,
1437 666 : timeline_id: TimelineId,
1438 666 : active_only: bool,
1439 666 : ) -> Result<Arc<Timeline>, GetTimelineError> {
1440 666 : let timelines_accessor = self.timelines.lock().unwrap();
1441 666 : let timeline = timelines_accessor
1442 666 : .get(&timeline_id)
1443 666 : .ok_or(GetTimelineError::NotFound {
1444 666 : tenant_id: self.tenant_shard_id,
1445 666 : timeline_id,
1446 666 : })?;
1447 :
1448 660 : if active_only && !timeline.is_active() {
1449 0 : Err(GetTimelineError::NotActive {
1450 0 : tenant_id: self.tenant_shard_id,
1451 0 : timeline_id,
1452 0 : state: timeline.current_state(),
1453 0 : })
1454 : } else {
1455 660 : Ok(Arc::clone(timeline))
1456 : }
1457 666 : }
1458 :
1459 : /// Lists timelines the tenant contains.
1460 : /// Up to tenant's implementation to omit certain timelines that ar not considered ready for use.
1461 24 : pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
1462 24 : self.timelines
1463 24 : .lock()
1464 24 : .unwrap()
1465 24 : .values()
1466 24 : .map(Arc::clone)
1467 24 : .collect()
1468 24 : }
1469 :
1470 0 : pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
1471 0 : self.timelines.lock().unwrap().keys().cloned().collect()
1472 0 : }
1473 :
1474 : /// This is used to create the initial 'main' timeline during bootstrapping,
1475 : /// or when importing a new base backup. The caller is expected to load an
1476 : /// initial image of the datadir to the new timeline after this.
1477 : ///
1478 : /// Until that happens, the on-disk state is invalid (disk_consistent_lsn=Lsn(0))
1479 : /// and the timeline will fail to load at a restart.
1480 : ///
1481 : /// For tests, use `DatadirModification::init_empty_test_timeline` + `commit` to setup the
1482 : /// minimum amount of keys required to get a writable timeline.
1483 : /// (Without it, `put` might fail due to `repartition` failing.)
1484 540 : pub(crate) async fn create_empty_timeline(
1485 540 : &self,
1486 540 : new_timeline_id: TimelineId,
1487 540 : initdb_lsn: Lsn,
1488 540 : pg_version: u32,
1489 540 : _ctx: &RequestContext,
1490 540 : ) -> anyhow::Result<UninitializedTimeline> {
1491 540 : anyhow::ensure!(
1492 540 : self.is_active(),
1493 0 : "Cannot create empty timelines on inactive tenant"
1494 : );
1495 :
1496 : // Protect against concurrent attempts to use this TimelineId
1497 540 : let create_guard = self.create_timeline_create_guard(new_timeline_id)?;
1498 :
1499 534 : let new_metadata = TimelineMetadata::new(
1500 534 : // Initialize disk_consistent LSN to 0, The caller must import some data to
1501 534 : // make it valid, before calling finish_creation()
1502 534 : Lsn(0),
1503 534 : None,
1504 534 : None,
1505 534 : Lsn(0),
1506 534 : initdb_lsn,
1507 534 : initdb_lsn,
1508 534 : pg_version,
1509 534 : );
1510 534 : self.prepare_new_timeline(
1511 534 : new_timeline_id,
1512 534 : &new_metadata,
1513 534 : create_guard,
1514 534 : initdb_lsn,
1515 534 : None,
1516 534 : None,
1517 534 : )
1518 0 : .await
1519 540 : }
1520 :
1521 : /// Helper for unit tests to create an empty timeline.
1522 : ///
1523 : /// The timeline is has state value `Active` but its background loops are not running.
1524 : // This makes the various functions which anyhow::ensure! for Active state work in tests.
1525 : // Our current tests don't need the background loops.
1526 : #[cfg(test)]
1527 510 : pub async fn create_test_timeline(
1528 510 : &self,
1529 510 : new_timeline_id: TimelineId,
1530 510 : initdb_lsn: Lsn,
1531 510 : pg_version: u32,
1532 510 : ctx: &RequestContext,
1533 510 : ) -> anyhow::Result<Arc<Timeline>> {
1534 510 : let uninit_tl = self
1535 510 : .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
1536 0 : .await?;
1537 510 : let tline = uninit_tl.raw_timeline().expect("we just created it");
1538 510 : assert_eq!(tline.get_last_record_lsn(), Lsn(0));
1539 :
1540 : // Setup minimum keys required for the timeline to be usable.
1541 510 : let mut modification = tline.begin_modification(initdb_lsn);
1542 510 : modification
1543 510 : .init_empty_test_timeline()
1544 510 : .context("init_empty_test_timeline")?;
1545 510 : modification
1546 510 : .commit(ctx)
1547 492 : .await
1548 510 : .context("commit init_empty_test_timeline modification")?;
1549 :
1550 : // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
1551 510 : tline.maybe_spawn_flush_loop();
1552 510 : tline.freeze_and_flush().await.context("freeze_and_flush")?;
1553 :
1554 : // Make sure the freeze_and_flush reaches remote storage.
1555 510 : tline.remote_client.wait_completion().await.unwrap();
1556 :
1557 510 : let tl = uninit_tl.finish_creation()?;
1558 : // The non-test code would call tl.activate() here.
1559 510 : tl.set_state(TimelineState::Active);
1560 510 : Ok(tl)
1561 510 : }
1562 :
1563 : /// Helper for unit tests to create a timeline with some pre-loaded states.
1564 : #[cfg(test)]
1565 : #[allow(clippy::too_many_arguments)]
1566 78 : pub async fn create_test_timeline_with_layers(
1567 78 : &self,
1568 78 : new_timeline_id: TimelineId,
1569 78 : initdb_lsn: Lsn,
1570 78 : pg_version: u32,
1571 78 : ctx: &RequestContext,
1572 78 : delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
1573 78 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
1574 78 : end_lsn: Lsn,
1575 78 : ) -> anyhow::Result<Arc<Timeline>> {
1576 78 : let tline = self
1577 78 : .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
1578 156 : .await?;
1579 78 : tline.force_advance_lsn(end_lsn);
1580 234 : for deltas in delta_layer_desc {
1581 156 : tline
1582 156 : .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
1583 468 : .await?;
1584 : }
1585 204 : for (lsn, images) in image_layer_desc {
1586 126 : tline
1587 126 : .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
1588 717 : .await?;
1589 : }
1590 78 : Ok(tline)
1591 78 : }
1592 :
1593 : /// Create a new timeline.
1594 : ///
1595 : /// Returns the new timeline ID and reference to its Timeline object.
1596 : ///
1597 : /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
1598 : /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
1599 : #[allow(clippy::too_many_arguments)]
1600 0 : pub(crate) async fn create_timeline(
1601 0 : self: &Arc<Tenant>,
1602 0 : new_timeline_id: TimelineId,
1603 0 : ancestor_timeline_id: Option<TimelineId>,
1604 0 : mut ancestor_start_lsn: Option<Lsn>,
1605 0 : pg_version: u32,
1606 0 : load_existing_initdb: Option<TimelineId>,
1607 0 : broker_client: storage_broker::BrokerClientChannel,
1608 0 : ctx: &RequestContext,
1609 0 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
1610 0 : if !self.is_active() {
1611 0 : if matches!(self.current_state(), TenantState::Stopping { .. }) {
1612 0 : return Err(CreateTimelineError::ShuttingDown);
1613 : } else {
1614 0 : return Err(CreateTimelineError::Other(anyhow::anyhow!(
1615 0 : "Cannot create timelines on inactive tenant"
1616 0 : )));
1617 : }
1618 0 : }
1619 :
1620 0 : let _gate = self
1621 0 : .gate
1622 0 : .enter()
1623 0 : .map_err(|_| CreateTimelineError::ShuttingDown)?;
1624 :
1625 : // Get exclusive access to the timeline ID: this ensures that it does not already exist,
1626 : // and that no other creation attempts will be allowed in while we are working.
1627 0 : let create_guard = match self.create_timeline_create_guard(new_timeline_id) {
1628 0 : Ok(m) => m,
1629 : Err(TimelineExclusionError::AlreadyCreating) => {
1630 : // Creation is in progress, we cannot create it again, and we cannot
1631 : // check if this request matches the existing one, so caller must try
1632 : // again later.
1633 0 : return Err(CreateTimelineError::AlreadyCreating);
1634 : }
1635 0 : Err(TimelineExclusionError::Other(e)) => {
1636 0 : return Err(CreateTimelineError::Other(e));
1637 : }
1638 0 : Err(TimelineExclusionError::AlreadyExists(existing)) => {
1639 0 : debug!("timeline {new_timeline_id} already exists");
1640 :
1641 : // Idempotency: creating the same timeline twice is not an error, unless
1642 : // the second creation has different parameters.
1643 0 : if existing.get_ancestor_timeline_id() != ancestor_timeline_id
1644 0 : || existing.pg_version != pg_version
1645 0 : || (ancestor_start_lsn.is_some()
1646 0 : && ancestor_start_lsn != Some(existing.get_ancestor_lsn()))
1647 : {
1648 0 : return Err(CreateTimelineError::Conflict);
1649 0 : }
1650 0 :
1651 0 : // Wait for uploads to complete, so that when we return Ok, the timeline
1652 0 : // is known to be durable on remote storage. Just like we do at the end of
1653 0 : // this function, after we have created the timeline ourselves.
1654 0 : //
1655 0 : // We only really care that the initial version of `index_part.json` has
1656 0 : // been uploaded. That's enough to remember that the timeline
1657 0 : // exists. However, there is no function to wait specifically for that so
1658 0 : // we just wait for all in-progress uploads to finish.
1659 0 : existing
1660 0 : .remote_client
1661 0 : .wait_completion()
1662 0 : .await
1663 0 : .context("wait for timeline uploads to complete")?;
1664 :
1665 0 : return Ok(existing);
1666 : }
1667 : };
1668 :
1669 0 : pausable_failpoint!("timeline-creation-after-uninit");
1670 :
1671 0 : let loaded_timeline = match ancestor_timeline_id {
1672 0 : Some(ancestor_timeline_id) => {
1673 0 : let ancestor_timeline = self
1674 0 : .get_timeline(ancestor_timeline_id, false)
1675 0 : .context("Cannot branch off the timeline that's not present in pageserver")?;
1676 :
1677 : // instead of waiting around, just deny the request because ancestor is not yet
1678 : // ready for other purposes either.
1679 0 : if !ancestor_timeline.is_active() {
1680 0 : return Err(CreateTimelineError::AncestorNotActive);
1681 0 : }
1682 :
1683 0 : if let Some(lsn) = ancestor_start_lsn.as_mut() {
1684 0 : *lsn = lsn.align();
1685 0 :
1686 0 : let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
1687 0 : if ancestor_ancestor_lsn > *lsn {
1688 : // can we safely just branch from the ancestor instead?
1689 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
1690 0 : "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
1691 0 : lsn,
1692 0 : ancestor_timeline_id,
1693 0 : ancestor_ancestor_lsn,
1694 0 : )));
1695 0 : }
1696 0 :
1697 0 : // Wait for the WAL to arrive and be processed on the parent branch up
1698 0 : // to the requested branch point. The repository code itself doesn't
1699 0 : // require it, but if we start to receive WAL on the new timeline,
1700 0 : // decoding the new WAL might need to look up previous pages, relation
1701 0 : // sizes etc. and that would get confused if the previous page versions
1702 0 : // are not in the repository yet.
1703 0 : ancestor_timeline
1704 0 : .wait_lsn(*lsn, timeline::WaitLsnWaiter::Tenant, ctx)
1705 0 : .await
1706 0 : .map_err(|e| match e {
1707 0 : e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
1708 0 : CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
1709 : }
1710 0 : WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
1711 0 : })?;
1712 0 : }
1713 :
1714 0 : self.branch_timeline(
1715 0 : &ancestor_timeline,
1716 0 : new_timeline_id,
1717 0 : ancestor_start_lsn,
1718 0 : create_guard,
1719 0 : ctx,
1720 0 : )
1721 0 : .await?
1722 : }
1723 : None => {
1724 0 : self.bootstrap_timeline(
1725 0 : new_timeline_id,
1726 0 : pg_version,
1727 0 : load_existing_initdb,
1728 0 : create_guard,
1729 0 : ctx,
1730 0 : )
1731 0 : .await?
1732 : }
1733 : };
1734 :
1735 : // At this point we have dropped our guard on [`Self::timelines_creating`], and
1736 : // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet. We must
1737 : // not send a success to the caller until it is. The same applies to handling retries,
1738 : // see the handling of [`TimelineExclusionError::AlreadyExists`] above.
1739 0 : let kind = ancestor_timeline_id
1740 0 : .map(|_| "branched")
1741 0 : .unwrap_or("bootstrapped");
1742 0 : loaded_timeline
1743 0 : .remote_client
1744 0 : .wait_completion()
1745 0 : .await
1746 0 : .with_context(|| format!("wait for {} timeline initial uploads to complete", kind))?;
1747 :
1748 0 : loaded_timeline.activate(self.clone(), broker_client, None, ctx);
1749 0 :
1750 0 : Ok(loaded_timeline)
1751 0 : }
1752 :
1753 0 : pub(crate) async fn delete_timeline(
1754 0 : self: Arc<Self>,
1755 0 : timeline_id: TimelineId,
1756 0 : ) -> Result<(), DeleteTimelineError> {
1757 0 : DeleteTimelineFlow::run(&self, timeline_id).await?;
1758 :
1759 0 : Ok(())
1760 0 : }
1761 :
1762 : /// perform one garbage collection iteration, removing old data files from disk.
1763 : /// this function is periodically called by gc task.
1764 : /// also it can be explicitly requested through page server api 'do_gc' command.
1765 : ///
1766 : /// `target_timeline_id` specifies the timeline to GC, or None for all.
1767 : ///
1768 : /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
1769 : /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
1770 : /// the amount of history, as LSN difference from current latest LSN on each timeline.
1771 : /// `pitr` specifies the same as a time difference from the current time. The effective
1772 : /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
1773 : /// requires more history to be retained.
1774 : //
1775 2262 : pub(crate) async fn gc_iteration(
1776 2262 : &self,
1777 2262 : target_timeline_id: Option<TimelineId>,
1778 2262 : horizon: u64,
1779 2262 : pitr: Duration,
1780 2262 : cancel: &CancellationToken,
1781 2262 : ctx: &RequestContext,
1782 2262 : ) -> Result<GcResult, GcError> {
1783 2262 : // Don't start doing work during shutdown
1784 2262 : if let TenantState::Stopping { .. } = self.current_state() {
1785 0 : return Ok(GcResult::default());
1786 2262 : }
1787 2262 :
1788 2262 : // there is a global allowed_error for this
1789 2262 : if !self.is_active() {
1790 0 : return Err(GcError::NotActive);
1791 2262 : }
1792 2262 :
1793 2262 : {
1794 2262 : let conf = self.tenant_conf.load();
1795 2262 :
1796 2262 : if !conf.location.may_delete_layers_hint() {
1797 0 : info!("Skipping GC in location state {:?}", conf.location);
1798 0 : return Ok(GcResult::default());
1799 2262 : }
1800 : }
1801 :
1802 2262 : let _guard = match self.gc_block.start().await {
1803 2262 : Ok(guard) => guard,
1804 0 : Err(reasons) => {
1805 0 : info!("Skipping GC: {reasons}");
1806 0 : return Ok(GcResult::default());
1807 : }
1808 : };
1809 :
1810 2262 : self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
1811 2235 : .await
1812 2262 : }
1813 :
1814 : /// Perform one compaction iteration.
1815 : /// This function is periodically called by compactor task.
1816 : /// Also it can be explicitly requested per timeline through page server
1817 : /// api's 'compact' command.
1818 : ///
1819 : /// Returns whether we have pending compaction task.
1820 0 : async fn compaction_iteration(
1821 0 : &self,
1822 0 : cancel: &CancellationToken,
1823 0 : ctx: &RequestContext,
1824 0 : ) -> Result<bool, timeline::CompactionError> {
1825 0 : // Don't start doing work during shutdown, or when broken, we do not need those in the logs
1826 0 : if !self.is_active() {
1827 0 : return Ok(false);
1828 0 : }
1829 0 :
1830 0 : {
1831 0 : let conf = self.tenant_conf.load();
1832 0 : if !conf.location.may_delete_layers_hint() || !conf.location.may_upload_layers_hint() {
1833 0 : info!("Skipping compaction in location state {:?}", conf.location);
1834 0 : return Ok(false);
1835 0 : }
1836 0 : }
1837 0 :
1838 0 : // Scan through the hashmap and collect a list of all the timelines,
1839 0 : // while holding the lock. Then drop the lock and actually perform the
1840 0 : // compactions. We don't want to block everything else while the
1841 0 : // compaction runs.
1842 0 : let timelines_to_compact = {
1843 0 : let timelines = self.timelines.lock().unwrap();
1844 0 : let timelines_to_compact = timelines
1845 0 : .iter()
1846 0 : .filter_map(|(timeline_id, timeline)| {
1847 0 : if timeline.is_active() {
1848 0 : Some((*timeline_id, timeline.clone()))
1849 : } else {
1850 0 : None
1851 : }
1852 0 : })
1853 0 : .collect::<Vec<_>>();
1854 0 : drop(timelines);
1855 0 : timelines_to_compact
1856 0 : };
1857 0 :
1858 0 : // Before doing any I/O work, check our circuit breaker
1859 0 : if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
1860 0 : info!("Skipping compaction due to previous failures");
1861 0 : return Ok(false);
1862 0 : }
1863 0 :
1864 0 : let mut has_pending_task = false;
1865 :
1866 0 : for (timeline_id, timeline) in &timelines_to_compact {
1867 0 : has_pending_task |= timeline
1868 0 : .compact(cancel, EnumSet::empty(), ctx)
1869 0 : .instrument(info_span!("compact_timeline", %timeline_id))
1870 0 : .await
1871 0 : .inspect_err(|e| match e {
1872 0 : timeline::CompactionError::ShuttingDown => (),
1873 0 : timeline::CompactionError::Other(e) => {
1874 0 : self.compaction_circuit_breaker
1875 0 : .lock()
1876 0 : .unwrap()
1877 0 : .fail(&CIRCUIT_BREAKERS_BROKEN, e);
1878 0 : }
1879 0 : })?;
1880 : }
1881 :
1882 0 : self.compaction_circuit_breaker
1883 0 : .lock()
1884 0 : .unwrap()
1885 0 : .success(&CIRCUIT_BREAKERS_UNBROKEN);
1886 0 :
1887 0 : Ok(has_pending_task)
1888 0 : }
1889 :
1890 : // Call through to all timelines to freeze ephemeral layers if needed. Usually
1891 : // this happens during ingest: this background housekeeping is for freezing layers
1892 : // that are open but haven't been written to for some time.
1893 0 : async fn ingest_housekeeping(&self) {
1894 0 : // Scan through the hashmap and collect a list of all the timelines,
1895 0 : // while holding the lock. Then drop the lock and actually perform the
1896 0 : // compactions. We don't want to block everything else while the
1897 0 : // compaction runs.
1898 0 : let timelines = {
1899 0 : self.timelines
1900 0 : .lock()
1901 0 : .unwrap()
1902 0 : .values()
1903 0 : .filter_map(|timeline| {
1904 0 : if timeline.is_active() {
1905 0 : Some(timeline.clone())
1906 : } else {
1907 0 : None
1908 : }
1909 0 : })
1910 0 : .collect::<Vec<_>>()
1911 : };
1912 :
1913 0 : for timeline in &timelines {
1914 0 : timeline.maybe_freeze_ephemeral_layer().await;
1915 : }
1916 0 : }
1917 :
1918 7344 : pub fn current_state(&self) -> TenantState {
1919 7344 : self.state.borrow().clone()
1920 7344 : }
1921 :
1922 5064 : pub fn is_active(&self) -> bool {
1923 5064 : self.current_state() == TenantState::Active
1924 5064 : }
1925 :
1926 0 : pub fn generation(&self) -> Generation {
1927 0 : self.generation
1928 0 : }
1929 :
1930 0 : pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
1931 0 : self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
1932 0 : }
1933 :
1934 : /// Changes tenant status to active, unless shutdown was already requested.
1935 : ///
1936 : /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
1937 : /// to delay background jobs. Background jobs can be started right away when None is given.
1938 0 : fn activate(
1939 0 : self: &Arc<Self>,
1940 0 : broker_client: BrokerClientChannel,
1941 0 : background_jobs_can_start: Option<&completion::Barrier>,
1942 0 : ctx: &RequestContext,
1943 0 : ) {
1944 0 : span::debug_assert_current_span_has_tenant_id();
1945 0 :
1946 0 : let mut activating = false;
1947 0 : self.state.send_modify(|current_state| {
1948 : use pageserver_api::models::ActivatingFrom;
1949 0 : match &*current_state {
1950 : TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
1951 0 : panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
1952 : }
1953 0 : TenantState::Loading => {
1954 0 : *current_state = TenantState::Activating(ActivatingFrom::Loading);
1955 0 : }
1956 0 : TenantState::Attaching => {
1957 0 : *current_state = TenantState::Activating(ActivatingFrom::Attaching);
1958 0 : }
1959 : }
1960 0 : debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
1961 0 : activating = true;
1962 0 : // Continue outside the closure. We need to grab timelines.lock()
1963 0 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
1964 0 : });
1965 0 :
1966 0 : if activating {
1967 0 : let timelines_accessor = self.timelines.lock().unwrap();
1968 0 : let timelines_to_activate = timelines_accessor
1969 0 : .values()
1970 0 : .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
1971 0 :
1972 0 : // Before activation, populate each Timeline's GcInfo with information about its children
1973 0 : self.initialize_gc_info(&timelines_accessor);
1974 0 :
1975 0 : // Spawn gc and compaction loops. The loops will shut themselves
1976 0 : // down when they notice that the tenant is inactive.
1977 0 : tasks::start_background_loops(self, background_jobs_can_start);
1978 0 :
1979 0 : let mut activated_timelines = 0;
1980 :
1981 0 : for timeline in timelines_to_activate {
1982 0 : timeline.activate(
1983 0 : self.clone(),
1984 0 : broker_client.clone(),
1985 0 : background_jobs_can_start,
1986 0 : ctx,
1987 0 : );
1988 0 : activated_timelines += 1;
1989 0 : }
1990 :
1991 0 : self.state.send_modify(move |current_state| {
1992 0 : assert!(
1993 0 : matches!(current_state, TenantState::Activating(_)),
1994 0 : "set_stopping and set_broken wait for us to leave Activating state",
1995 : );
1996 0 : *current_state = TenantState::Active;
1997 0 :
1998 0 : let elapsed = self.constructed_at.elapsed();
1999 0 : let total_timelines = timelines_accessor.len();
2000 0 :
2001 0 : // log a lot of stuff, because some tenants sometimes suffer from user-visible
2002 0 : // times to activate. see https://github.com/neondatabase/neon/issues/4025
2003 0 : info!(
2004 0 : since_creation_millis = elapsed.as_millis(),
2005 0 : tenant_id = %self.tenant_shard_id.tenant_id,
2006 0 : shard_id = %self.tenant_shard_id.shard_slug(),
2007 0 : activated_timelines,
2008 0 : total_timelines,
2009 0 : post_state = <&'static str>::from(&*current_state),
2010 0 : "activation attempt finished"
2011 : );
2012 :
2013 0 : TENANT.activation.observe(elapsed.as_secs_f64());
2014 0 : });
2015 0 : }
2016 0 : }
2017 :
2018 : /// Shutdown the tenant and join all of the spawned tasks.
2019 : ///
2020 : /// The method caters for all use-cases:
2021 : /// - pageserver shutdown (freeze_and_flush == true)
2022 : /// - detach + ignore (freeze_and_flush == false)
2023 : ///
2024 : /// This will attempt to shutdown even if tenant is broken.
2025 : ///
2026 : /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
2027 : /// If the tenant is already shutting down, we return a clone of the first shutdown call's
2028 : /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
2029 : /// the ongoing shutdown.
2030 18 : async fn shutdown(
2031 18 : &self,
2032 18 : shutdown_progress: completion::Barrier,
2033 18 : shutdown_mode: timeline::ShutdownMode,
2034 18 : ) -> Result<(), completion::Barrier> {
2035 18 : span::debug_assert_current_span_has_tenant_id();
2036 :
2037 : // Set tenant (and its timlines) to Stoppping state.
2038 : //
2039 : // Since we can only transition into Stopping state after activation is complete,
2040 : // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
2041 : //
2042 : // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
2043 : // 1. Lock out any new requests to the tenants.
2044 : // 2. Signal cancellation to WAL receivers (we wait on it below).
2045 : // 3. Signal cancellation for other tenant background loops.
2046 : // 4. ???
2047 : //
2048 : // The waiting for the cancellation is not done uniformly.
2049 : // We certainly wait for WAL receivers to shut down.
2050 : // That is necessary so that no new data comes in before the freeze_and_flush.
2051 : // But the tenant background loops are joined-on in our caller.
2052 : // It's mesed up.
2053 : // we just ignore the failure to stop
2054 :
2055 : // If we're still attaching, fire the cancellation token early to drop out: this
2056 : // will prevent us flushing, but ensures timely shutdown if some I/O during attach
2057 : // is very slow.
2058 18 : let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
2059 0 : self.cancel.cancel();
2060 0 :
2061 0 : // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
2062 0 : // are children of ours, so their flush loops will have shut down already
2063 0 : timeline::ShutdownMode::Hard
2064 : } else {
2065 18 : shutdown_mode
2066 : };
2067 :
2068 18 : match self.set_stopping(shutdown_progress, false, false).await {
2069 18 : Ok(()) => {}
2070 0 : Err(SetStoppingError::Broken) => {
2071 0 : // assume that this is acceptable
2072 0 : }
2073 0 : Err(SetStoppingError::AlreadyStopping(other)) => {
2074 0 : // give caller the option to wait for this this shutdown
2075 0 : info!("Tenant::shutdown: AlreadyStopping");
2076 0 : return Err(other);
2077 : }
2078 : };
2079 :
2080 18 : let mut js = tokio::task::JoinSet::new();
2081 18 : {
2082 18 : let timelines = self.timelines.lock().unwrap();
2083 18 : timelines.values().for_each(|timeline| {
2084 18 : let timeline = Arc::clone(timeline);
2085 18 : let timeline_id = timeline.timeline_id;
2086 18 : let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
2087 36 : js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
2088 18 : })
2089 18 : };
2090 18 : // test_long_timeline_create_then_tenant_delete is leaning on this message
2091 18 : tracing::info!("Waiting for timelines...");
2092 36 : while let Some(res) = js.join_next().await {
2093 0 : match res {
2094 18 : Ok(()) => {}
2095 0 : Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
2096 0 : Err(je) if je.is_panic() => { /* logged already */ }
2097 0 : Err(je) => warn!("unexpected JoinError: {je:?}"),
2098 : }
2099 : }
2100 :
2101 : // We cancel the Tenant's cancellation token _after_ the timelines have all shut down. This permits
2102 : // them to continue to do work during their shutdown methods, e.g. flushing data.
2103 18 : tracing::debug!("Cancelling CancellationToken");
2104 18 : self.cancel.cancel();
2105 18 :
2106 18 : // shutdown all tenant and timeline tasks: gc, compaction, page service
2107 18 : // No new tasks will be started for this tenant because it's in `Stopping` state.
2108 18 : //
2109 18 : // this will additionally shutdown and await all timeline tasks.
2110 18 : tracing::debug!("Waiting for tasks...");
2111 18 : task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
2112 :
2113 18 : if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
2114 18 : walredo_mgr.shutdown().await;
2115 0 : }
2116 :
2117 : // Wait for any in-flight operations to complete
2118 18 : self.gate.close().await;
2119 :
2120 18 : remove_tenant_metrics(&self.tenant_shard_id);
2121 18 :
2122 18 : Ok(())
2123 18 : }
2124 :
2125 : /// Change tenant status to Stopping, to mark that it is being shut down.
2126 : ///
2127 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
2128 : ///
2129 : /// This function is not cancel-safe!
2130 : ///
2131 : /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
2132 : /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
2133 18 : async fn set_stopping(
2134 18 : &self,
2135 18 : progress: completion::Barrier,
2136 18 : allow_transition_from_loading: bool,
2137 18 : allow_transition_from_attaching: bool,
2138 18 : ) -> Result<(), SetStoppingError> {
2139 18 : let mut rx = self.state.subscribe();
2140 18 :
2141 18 : // cannot stop before we're done activating, so wait out until we're done activating
2142 18 : rx.wait_for(|state| match state {
2143 0 : TenantState::Attaching if allow_transition_from_attaching => true,
2144 : TenantState::Activating(_) | TenantState::Attaching => {
2145 0 : info!(
2146 0 : "waiting for {} to turn Active|Broken|Stopping",
2147 0 : <&'static str>::from(state)
2148 : );
2149 0 : false
2150 : }
2151 0 : TenantState::Loading => allow_transition_from_loading,
2152 18 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
2153 18 : })
2154 0 : .await
2155 18 : .expect("cannot drop self.state while on a &self method");
2156 18 :
2157 18 : // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
2158 18 : let mut err = None;
2159 18 : let stopping = self.state.send_if_modified(|current_state| match current_state {
2160 : TenantState::Activating(_) => {
2161 0 : unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
2162 : }
2163 : TenantState::Attaching => {
2164 0 : if !allow_transition_from_attaching {
2165 0 : unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
2166 0 : };
2167 0 : *current_state = TenantState::Stopping { progress };
2168 0 : true
2169 : }
2170 : TenantState::Loading => {
2171 0 : if !allow_transition_from_loading {
2172 0 : unreachable!("3we ensured above that we're done with activation, and, there is no re-activation")
2173 0 : };
2174 0 : *current_state = TenantState::Stopping { progress };
2175 0 : true
2176 : }
2177 : TenantState::Active => {
2178 : // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
2179 : // are created after the transition to Stopping. That's harmless, as the Timelines
2180 : // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
2181 18 : *current_state = TenantState::Stopping { progress };
2182 18 : // Continue stopping outside the closure. We need to grab timelines.lock()
2183 18 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
2184 18 : true
2185 : }
2186 0 : TenantState::Broken { reason, .. } => {
2187 0 : info!(
2188 0 : "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
2189 : );
2190 0 : err = Some(SetStoppingError::Broken);
2191 0 : false
2192 : }
2193 0 : TenantState::Stopping { progress } => {
2194 0 : info!("Tenant is already in Stopping state");
2195 0 : err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
2196 0 : false
2197 : }
2198 18 : });
2199 18 : match (stopping, err) {
2200 18 : (true, None) => {} // continue
2201 0 : (false, Some(err)) => return Err(err),
2202 0 : (true, Some(_)) => unreachable!(
2203 0 : "send_if_modified closure must error out if not transitioning to Stopping"
2204 0 : ),
2205 0 : (false, None) => unreachable!(
2206 0 : "send_if_modified closure must return true if transitioning to Stopping"
2207 0 : ),
2208 : }
2209 :
2210 18 : let timelines_accessor = self.timelines.lock().unwrap();
2211 18 : let not_broken_timelines = timelines_accessor
2212 18 : .values()
2213 18 : .filter(|timeline| !timeline.is_broken());
2214 36 : for timeline in not_broken_timelines {
2215 18 : timeline.set_state(TimelineState::Stopping);
2216 18 : }
2217 18 : Ok(())
2218 18 : }
2219 :
2220 : /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
2221 : /// `remove_tenant_from_memory`
2222 : ///
2223 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
2224 : ///
2225 : /// In tests, we also use this to set tenants to Broken state on purpose.
2226 0 : pub(crate) async fn set_broken(&self, reason: String) {
2227 0 : let mut rx = self.state.subscribe();
2228 0 :
2229 0 : // The load & attach routines own the tenant state until it has reached `Active`.
2230 0 : // So, wait until it's done.
2231 0 : rx.wait_for(|state| match state {
2232 : TenantState::Activating(_) | TenantState::Loading | TenantState::Attaching => {
2233 0 : info!(
2234 0 : "waiting for {} to turn Active|Broken|Stopping",
2235 0 : <&'static str>::from(state)
2236 : );
2237 0 : false
2238 : }
2239 0 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
2240 0 : })
2241 0 : .await
2242 0 : .expect("cannot drop self.state while on a &self method");
2243 0 :
2244 0 : // we now know we're done activating, let's see whether this task is the winner to transition into Broken
2245 0 : self.set_broken_no_wait(reason)
2246 0 : }
2247 :
2248 0 : pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
2249 0 : let reason = reason.to_string();
2250 0 : self.state.send_modify(|current_state| {
2251 0 : match *current_state {
2252 : TenantState::Activating(_) | TenantState::Loading | TenantState::Attaching => {
2253 0 : unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
2254 : }
2255 : TenantState::Active => {
2256 0 : if cfg!(feature = "testing") {
2257 0 : warn!("Changing Active tenant to Broken state, reason: {}", reason);
2258 0 : *current_state = TenantState::broken_from_reason(reason);
2259 : } else {
2260 0 : unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
2261 : }
2262 : }
2263 : TenantState::Broken { .. } => {
2264 0 : warn!("Tenant is already in Broken state");
2265 : }
2266 : // This is the only "expected" path, any other path is a bug.
2267 : TenantState::Stopping { .. } => {
2268 0 : warn!(
2269 0 : "Marking Stopping tenant as Broken state, reason: {}",
2270 : reason
2271 : );
2272 0 : *current_state = TenantState::broken_from_reason(reason);
2273 : }
2274 : }
2275 0 : });
2276 0 : }
2277 :
2278 0 : pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
2279 0 : self.state.subscribe()
2280 0 : }
2281 :
2282 : /// The activate_now semaphore is initialized with zero units. As soon as
2283 : /// we add a unit, waiters will be able to acquire a unit and proceed.
2284 0 : pub(crate) fn activate_now(&self) {
2285 0 : self.activate_now_sem.add_permits(1);
2286 0 : }
2287 :
2288 0 : pub(crate) async fn wait_to_become_active(
2289 0 : &self,
2290 0 : timeout: Duration,
2291 0 : ) -> Result<(), GetActiveTenantError> {
2292 0 : let mut receiver = self.state.subscribe();
2293 : loop {
2294 0 : let current_state = receiver.borrow_and_update().clone();
2295 0 : match current_state {
2296 : TenantState::Loading | TenantState::Attaching | TenantState::Activating(_) => {
2297 : // in these states, there's a chance that we can reach ::Active
2298 0 : self.activate_now();
2299 0 : match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
2300 0 : Ok(r) => {
2301 0 : r.map_err(
2302 0 : |_e: tokio::sync::watch::error::RecvError|
2303 : // Tenant existed but was dropped: report it as non-existent
2304 0 : GetActiveTenantError::NotFound(GetTenantError::NotFound(self.tenant_shard_id.tenant_id))
2305 0 : )?
2306 : }
2307 : Err(TimeoutCancellableError::Cancelled) => {
2308 0 : return Err(GetActiveTenantError::Cancelled);
2309 : }
2310 : Err(TimeoutCancellableError::Timeout) => {
2311 0 : return Err(GetActiveTenantError::WaitForActiveTimeout {
2312 0 : latest_state: Some(self.current_state()),
2313 0 : wait_time: timeout,
2314 0 : });
2315 : }
2316 : }
2317 : }
2318 : TenantState::Active { .. } => {
2319 0 : return Ok(());
2320 : }
2321 0 : TenantState::Broken { reason, .. } => {
2322 0 : // This is fatal, and reported distinctly from the general case of "will never be active" because
2323 0 : // it's logically a 500 to external API users (broken is always a bug).
2324 0 : return Err(GetActiveTenantError::Broken(reason));
2325 : }
2326 : TenantState::Stopping { .. } => {
2327 : // There's no chance the tenant can transition back into ::Active
2328 0 : return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
2329 : }
2330 : }
2331 : }
2332 0 : }
2333 :
2334 0 : pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
2335 0 : self.tenant_conf.load().location.attach_mode
2336 0 : }
2337 :
2338 : /// For API access: generate a LocationConfig equivalent to the one that would be used to
2339 : /// create a Tenant in the same state. Do not use this in hot paths: it's for relatively
2340 : /// rare external API calls, like a reconciliation at startup.
2341 0 : pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
2342 0 : let conf = self.tenant_conf.load();
2343 :
2344 0 : let location_config_mode = match conf.location.attach_mode {
2345 0 : AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
2346 0 : AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
2347 0 : AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
2348 : };
2349 :
2350 : // We have a pageserver TenantConf, we need the API-facing TenantConfig.
2351 0 : let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
2352 0 :
2353 0 : models::LocationConfig {
2354 0 : mode: location_config_mode,
2355 0 : generation: self.generation.into(),
2356 0 : secondary_conf: None,
2357 0 : shard_number: self.shard_identity.number.0,
2358 0 : shard_count: self.shard_identity.count.literal(),
2359 0 : shard_stripe_size: self.shard_identity.stripe_size.0,
2360 0 : tenant_conf: tenant_config,
2361 0 : }
2362 0 : }
2363 :
2364 0 : pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
2365 0 : &self.tenant_shard_id
2366 0 : }
2367 :
2368 0 : pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
2369 0 : self.shard_identity.stripe_size
2370 0 : }
2371 :
2372 0 : pub(crate) fn get_generation(&self) -> Generation {
2373 0 : self.generation
2374 0 : }
2375 :
2376 : /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
2377 : /// and can leave the tenant in a bad state if it fails. The caller is responsible for
2378 : /// resetting this tenant to a valid state if we fail.
2379 0 : pub(crate) async fn split_prepare(
2380 0 : &self,
2381 0 : child_shards: &Vec<TenantShardId>,
2382 0 : ) -> anyhow::Result<()> {
2383 0 : let timelines = self.timelines.lock().unwrap().clone();
2384 0 : for timeline in timelines.values() {
2385 : // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
2386 : // to ensure that they do not start a split if currently in the process of doing these.
2387 :
2388 : // Upload an index from the parent: this is partly to provide freshness for the
2389 : // child tenants that will copy it, and partly for general ease-of-debugging: there will
2390 : // always be a parent shard index in the same generation as we wrote the child shard index.
2391 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Uploading index");
2392 0 : timeline
2393 0 : .remote_client
2394 0 : .schedule_index_upload_for_file_changes()?;
2395 0 : timeline.remote_client.wait_completion().await?;
2396 :
2397 : // Shut down the timeline's remote client: this means that the indices we write
2398 : // for child shards will not be invalidated by the parent shard deleting layers.
2399 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Shutting down remote storage client");
2400 0 : timeline.remote_client.shutdown().await;
2401 :
2402 : // Download methods can still be used after shutdown, as they don't flow through the remote client's
2403 : // queue. In principal the RemoteTimelineClient could provide this without downloading it, but this
2404 : // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
2405 : // we use here really is the remotely persistent one).
2406 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Downloading index_part from parent");
2407 0 : let result = timeline.remote_client
2408 0 : .download_index_file(&self.cancel)
2409 0 : .instrument(info_span!("download_index_file", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%timeline.timeline_id))
2410 0 : .await?;
2411 0 : let index_part = match result {
2412 : MaybeDeletedIndexPart::Deleted(_) => {
2413 0 : anyhow::bail!("Timeline deletion happened concurrently with split")
2414 : }
2415 0 : MaybeDeletedIndexPart::IndexPart(p) => p,
2416 : };
2417 :
2418 0 : for child_shard in child_shards {
2419 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Uploading index_part for child {}", child_shard.to_index());
2420 0 : upload_index_part(
2421 0 : &self.remote_storage,
2422 0 : child_shard,
2423 0 : &timeline.timeline_id,
2424 0 : self.generation,
2425 0 : &index_part,
2426 0 : &self.cancel,
2427 0 : )
2428 0 : .await?;
2429 : }
2430 : }
2431 :
2432 0 : Ok(())
2433 0 : }
2434 :
2435 0 : pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
2436 0 : let mut result = TopTenantShardItem {
2437 0 : id: self.tenant_shard_id,
2438 0 : resident_size: 0,
2439 0 : physical_size: 0,
2440 0 : max_logical_size: 0,
2441 0 : };
2442 :
2443 0 : for timeline in self.timelines.lock().unwrap().values() {
2444 0 : result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
2445 0 :
2446 0 : result.physical_size += timeline
2447 0 : .remote_client
2448 0 : .metrics
2449 0 : .remote_physical_size_gauge
2450 0 : .get();
2451 0 : result.max_logical_size = std::cmp::max(
2452 0 : result.max_logical_size,
2453 0 : timeline.metrics.current_logical_size_gauge.get(),
2454 0 : );
2455 0 : }
2456 :
2457 0 : result
2458 0 : }
2459 : }
2460 :
2461 : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
2462 : /// perform a topological sort, so that the parent of each timeline comes
2463 : /// before the children.
2464 : /// E extracts the ancestor from T
2465 : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
2466 564 : fn tree_sort_timelines<T, E>(
2467 564 : timelines: HashMap<TimelineId, T>,
2468 564 : extractor: E,
2469 564 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
2470 564 : where
2471 564 : E: Fn(&T) -> Option<TimelineId>,
2472 564 : {
2473 564 : let mut result = Vec::with_capacity(timelines.len());
2474 564 :
2475 564 : let mut now = Vec::with_capacity(timelines.len());
2476 564 : // (ancestor, children)
2477 564 : let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
2478 564 : HashMap::with_capacity(timelines.len());
2479 :
2480 582 : for (timeline_id, value) in timelines {
2481 18 : if let Some(ancestor_id) = extractor(&value) {
2482 6 : let children = later.entry(ancestor_id).or_default();
2483 6 : children.push((timeline_id, value));
2484 12 : } else {
2485 12 : now.push((timeline_id, value));
2486 12 : }
2487 : }
2488 :
2489 582 : while let Some((timeline_id, metadata)) = now.pop() {
2490 18 : result.push((timeline_id, metadata));
2491 : // All children of this can be loaded now
2492 18 : if let Some(mut children) = later.remove(&timeline_id) {
2493 6 : now.append(&mut children);
2494 12 : }
2495 : }
2496 :
2497 : // All timelines should be visited now. Unless there were timelines with missing ancestors.
2498 564 : if !later.is_empty() {
2499 0 : for (missing_id, orphan_ids) in later {
2500 0 : for (orphan_id, _) in orphan_ids {
2501 0 : error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
2502 : }
2503 : }
2504 0 : bail!("could not load tenant because some timelines are missing ancestors");
2505 564 : }
2506 564 :
2507 564 : Ok(result)
2508 564 : }
2509 :
2510 : impl Tenant {
2511 0 : pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
2512 0 : self.tenant_conf.load().tenant_conf.clone()
2513 0 : }
2514 :
2515 0 : pub fn effective_config(&self) -> TenantConf {
2516 0 : self.tenant_specific_overrides()
2517 0 : .merge(self.conf.default_tenant_conf.clone())
2518 0 : }
2519 :
2520 0 : pub fn get_checkpoint_distance(&self) -> u64 {
2521 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2522 0 : tenant_conf
2523 0 : .checkpoint_distance
2524 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
2525 0 : }
2526 :
2527 0 : pub fn get_checkpoint_timeout(&self) -> Duration {
2528 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2529 0 : tenant_conf
2530 0 : .checkpoint_timeout
2531 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
2532 0 : }
2533 :
2534 0 : pub fn get_compaction_target_size(&self) -> u64 {
2535 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2536 0 : tenant_conf
2537 0 : .compaction_target_size
2538 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
2539 0 : }
2540 :
2541 0 : pub fn get_compaction_period(&self) -> Duration {
2542 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2543 0 : tenant_conf
2544 0 : .compaction_period
2545 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_period)
2546 0 : }
2547 :
2548 0 : pub fn get_compaction_threshold(&self) -> usize {
2549 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2550 0 : tenant_conf
2551 0 : .compaction_threshold
2552 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
2553 0 : }
2554 :
2555 0 : pub fn get_gc_horizon(&self) -> u64 {
2556 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2557 0 : tenant_conf
2558 0 : .gc_horizon
2559 0 : .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
2560 0 : }
2561 :
2562 0 : pub fn get_gc_period(&self) -> Duration {
2563 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2564 0 : tenant_conf
2565 0 : .gc_period
2566 0 : .unwrap_or(self.conf.default_tenant_conf.gc_period)
2567 0 : }
2568 :
2569 0 : pub fn get_image_creation_threshold(&self) -> usize {
2570 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2571 0 : tenant_conf
2572 0 : .image_creation_threshold
2573 0 : .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
2574 0 : }
2575 :
2576 0 : pub fn get_pitr_interval(&self) -> Duration {
2577 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2578 0 : tenant_conf
2579 0 : .pitr_interval
2580 0 : .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
2581 0 : }
2582 :
2583 0 : pub fn get_min_resident_size_override(&self) -> Option<u64> {
2584 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2585 0 : tenant_conf
2586 0 : .min_resident_size_override
2587 0 : .or(self.conf.default_tenant_conf.min_resident_size_override)
2588 0 : }
2589 :
2590 0 : pub fn get_heatmap_period(&self) -> Option<Duration> {
2591 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2592 0 : let heatmap_period = tenant_conf
2593 0 : .heatmap_period
2594 0 : .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
2595 0 : if heatmap_period.is_zero() {
2596 0 : None
2597 : } else {
2598 0 : Some(heatmap_period)
2599 : }
2600 0 : }
2601 :
2602 0 : pub fn get_lsn_lease_length(&self) -> Duration {
2603 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
2604 0 : tenant_conf
2605 0 : .lsn_lease_length
2606 0 : .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
2607 0 : }
2608 :
2609 0 : pub fn set_new_tenant_config(&self, new_tenant_conf: TenantConfOpt) {
2610 0 : // Use read-copy-update in order to avoid overwriting the location config
2611 0 : // state if this races with [`Tenant::set_new_location_config`]. Note that
2612 0 : // this race is not possible if both request types come from the storage
2613 0 : // controller (as they should!) because an exclusive op lock is required
2614 0 : // on the storage controller side.
2615 0 : self.tenant_conf.rcu(|inner| {
2616 0 : Arc::new(AttachedTenantConf {
2617 0 : tenant_conf: new_tenant_conf.clone(),
2618 0 : location: inner.location,
2619 0 : })
2620 0 : });
2621 0 :
2622 0 : self.tenant_conf_updated(&new_tenant_conf);
2623 0 : // Don't hold self.timelines.lock() during the notifies.
2624 0 : // There's no risk of deadlock right now, but there could be if we consolidate
2625 0 : // mutexes in struct Timeline in the future.
2626 0 : let timelines = self.list_timelines();
2627 0 : for timeline in timelines {
2628 0 : timeline.tenant_conf_updated(&new_tenant_conf);
2629 0 : }
2630 0 : }
2631 :
2632 24 : pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
2633 24 : let new_tenant_conf = new_conf.tenant_conf.clone();
2634 24 :
2635 24 : self.tenant_conf.store(Arc::new(new_conf));
2636 24 :
2637 24 : self.tenant_conf_updated(&new_tenant_conf);
2638 24 : // Don't hold self.timelines.lock() during the notifies.
2639 24 : // There's no risk of deadlock right now, but there could be if we consolidate
2640 24 : // mutexes in struct Timeline in the future.
2641 24 : let timelines = self.list_timelines();
2642 48 : for timeline in timelines {
2643 24 : timeline.tenant_conf_updated(&new_tenant_conf);
2644 24 : }
2645 24 : }
2646 :
2647 588 : fn get_timeline_get_throttle_config(
2648 588 : psconf: &'static PageServerConf,
2649 588 : overrides: &TenantConfOpt,
2650 588 : ) -> throttle::Config {
2651 588 : overrides
2652 588 : .timeline_get_throttle
2653 588 : .clone()
2654 588 : .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
2655 588 : }
2656 :
2657 24 : pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
2658 24 : let conf = Self::get_timeline_get_throttle_config(self.conf, new_conf);
2659 24 : self.timeline_get_throttle.reconfigure(conf)
2660 24 : }
2661 :
2662 : /// Helper function to create a new Timeline struct.
2663 : ///
2664 : /// The returned Timeline is in Loading state. The caller is responsible for
2665 : /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
2666 : /// map.
2667 : ///
2668 : /// `validate_ancestor == false` is used when a timeline is created for deletion
2669 : /// and we might not have the ancestor present anymore which is fine for to be
2670 : /// deleted timelines.
2671 1236 : fn create_timeline_struct(
2672 1236 : &self,
2673 1236 : new_timeline_id: TimelineId,
2674 1236 : new_metadata: &TimelineMetadata,
2675 1236 : ancestor: Option<Arc<Timeline>>,
2676 1236 : resources: TimelineResources,
2677 1236 : cause: CreateTimelineCause,
2678 1236 : last_aux_file_policy: Option<AuxFilePolicy>,
2679 1236 : ) -> anyhow::Result<Arc<Timeline>> {
2680 1236 : let state = match cause {
2681 : CreateTimelineCause::Load => {
2682 1236 : let ancestor_id = new_metadata.ancestor_timeline();
2683 1236 : anyhow::ensure!(
2684 1236 : ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
2685 0 : "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
2686 : );
2687 1236 : TimelineState::Loading
2688 : }
2689 0 : CreateTimelineCause::Delete => TimelineState::Stopping,
2690 : };
2691 :
2692 1236 : let pg_version = new_metadata.pg_version();
2693 1236 :
2694 1236 : let timeline = Timeline::new(
2695 1236 : self.conf,
2696 1236 : Arc::clone(&self.tenant_conf),
2697 1236 : new_metadata,
2698 1236 : ancestor,
2699 1236 : new_timeline_id,
2700 1236 : self.tenant_shard_id,
2701 1236 : self.generation,
2702 1236 : self.shard_identity,
2703 1236 : self.walredo_mgr.clone(),
2704 1236 : resources,
2705 1236 : pg_version,
2706 1236 : state,
2707 1236 : last_aux_file_policy,
2708 1236 : self.cancel.child_token(),
2709 1236 : );
2710 1236 :
2711 1236 : Ok(timeline)
2712 1236 : }
2713 :
2714 : // Allow too_many_arguments because a constructor's argument list naturally grows with the
2715 : // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
2716 : #[allow(clippy::too_many_arguments)]
2717 564 : fn new(
2718 564 : state: TenantState,
2719 564 : conf: &'static PageServerConf,
2720 564 : attached_conf: AttachedTenantConf,
2721 564 : shard_identity: ShardIdentity,
2722 564 : walredo_mgr: Option<Arc<WalRedoManager>>,
2723 564 : tenant_shard_id: TenantShardId,
2724 564 : remote_storage: GenericRemoteStorage,
2725 564 : deletion_queue_client: DeletionQueueClient,
2726 564 : l0_flush_global_state: L0FlushGlobalState,
2727 564 : ) -> Tenant {
2728 564 : debug_assert!(
2729 564 : !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
2730 : );
2731 :
2732 564 : let (state, mut rx) = watch::channel(state);
2733 564 :
2734 564 : tokio::spawn(async move {
2735 564 : // reflect tenant state in metrics:
2736 564 : // - global per tenant state: TENANT_STATE_METRIC
2737 564 : // - "set" of broken tenants: BROKEN_TENANTS_SET
2738 564 : //
2739 564 : // set of broken tenants should not have zero counts so that it remains accessible for
2740 564 : // alerting.
2741 564 :
2742 564 : let tid = tenant_shard_id.to_string();
2743 564 : let shard_id = tenant_shard_id.shard_slug().to_string();
2744 564 : let set_key = &[tid.as_str(), shard_id.as_str()][..];
2745 :
2746 1122 : fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
2747 1122 : ([state.into()], matches!(state, TenantState::Broken { .. }))
2748 1122 : }
2749 :
2750 564 : let mut tuple = inspect_state(&rx.borrow_and_update());
2751 564 :
2752 564 : let is_broken = tuple.1;
2753 564 : let mut counted_broken = if is_broken {
2754 : // add the id to the set right away, there should not be any updates on the channel
2755 : // after before tenant is removed, if ever
2756 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
2757 0 : true
2758 : } else {
2759 564 : false
2760 : };
2761 :
2762 : loop {
2763 1122 : let labels = &tuple.0;
2764 1122 : let current = TENANT_STATE_METRIC.with_label_values(labels);
2765 1122 : current.inc();
2766 1122 :
2767 1122 : if rx.changed().await.is_err() {
2768 : // tenant has been dropped
2769 48 : current.dec();
2770 48 : drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
2771 48 : break;
2772 558 : }
2773 558 :
2774 558 : current.dec();
2775 558 : tuple = inspect_state(&rx.borrow_and_update());
2776 558 :
2777 558 : let is_broken = tuple.1;
2778 558 : if is_broken && !counted_broken {
2779 0 : counted_broken = true;
2780 0 : // insert the tenant_id (back) into the set while avoiding needless counter
2781 0 : // access
2782 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
2783 558 : }
2784 : }
2785 564 : });
2786 564 :
2787 564 : Tenant {
2788 564 : tenant_shard_id,
2789 564 : shard_identity,
2790 564 : generation: attached_conf.location.generation,
2791 564 : conf,
2792 564 : // using now here is good enough approximation to catch tenants with really long
2793 564 : // activation times.
2794 564 : constructed_at: Instant::now(),
2795 564 : timelines: Mutex::new(HashMap::new()),
2796 564 : timelines_creating: Mutex::new(HashSet::new()),
2797 564 : gc_cs: tokio::sync::Mutex::new(()),
2798 564 : walredo_mgr,
2799 564 : remote_storage,
2800 564 : deletion_queue_client,
2801 564 : state,
2802 564 : cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
2803 564 : cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
2804 564 : eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
2805 564 : compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
2806 564 : format!("compaction-{tenant_shard_id}"),
2807 564 : 5,
2808 564 : // Compaction can be a very expensive operation, and might leak disk space. It also ought
2809 564 : // to be infallible, as long as remote storage is available. So if it repeatedly fails,
2810 564 : // use an extremely long backoff.
2811 564 : Some(Duration::from_secs(3600 * 24)),
2812 564 : )),
2813 564 : activate_now_sem: tokio::sync::Semaphore::new(0),
2814 564 : cancel: CancellationToken::default(),
2815 564 : gate: Gate::default(),
2816 564 : timeline_get_throttle: Arc::new(throttle::Throttle::new(
2817 564 : Tenant::get_timeline_get_throttle_config(conf, &attached_conf.tenant_conf),
2818 564 : &crate::metrics::tenant_throttling::TIMELINE_GET,
2819 564 : )),
2820 564 : tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
2821 564 : ongoing_timeline_detach: std::sync::Mutex::default(),
2822 564 : gc_block: Default::default(),
2823 564 : l0_flush_global_state,
2824 564 : }
2825 564 : }
2826 :
2827 : /// Locate and load config
2828 0 : pub(super) fn load_tenant_config(
2829 0 : conf: &'static PageServerConf,
2830 0 : tenant_shard_id: &TenantShardId,
2831 0 : ) -> Result<LocationConf, LoadConfigError> {
2832 0 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
2833 0 :
2834 0 : info!("loading tenant configuration from {config_path}");
2835 :
2836 : // load and parse file
2837 0 : let config = fs::read_to_string(&config_path).map_err(|e| {
2838 0 : match e.kind() {
2839 : std::io::ErrorKind::NotFound => {
2840 : // The config should almost always exist for a tenant directory:
2841 : // - When attaching a tenant, the config is the first thing we write
2842 : // - When detaching a tenant, we atomically move the directory to a tmp location
2843 : // before deleting contents.
2844 : //
2845 : // The very rare edge case that can result in a missing config is if we crash during attach
2846 : // between creating directory and writing config. Callers should handle that as if the
2847 : // directory didn't exist.
2848 :
2849 0 : LoadConfigError::NotFound(config_path)
2850 : }
2851 : _ => {
2852 : // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
2853 : // that we cannot cleanly recover
2854 0 : crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
2855 : }
2856 : }
2857 0 : })?;
2858 :
2859 0 : Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
2860 0 : }
2861 :
2862 0 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
2863 : pub(super) async fn persist_tenant_config(
2864 : conf: &'static PageServerConf,
2865 : tenant_shard_id: &TenantShardId,
2866 : location_conf: &LocationConf,
2867 : ) -> std::io::Result<()> {
2868 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
2869 :
2870 : Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
2871 : }
2872 :
2873 0 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
2874 : pub(super) async fn persist_tenant_config_at(
2875 : tenant_shard_id: &TenantShardId,
2876 : config_path: &Utf8Path,
2877 : location_conf: &LocationConf,
2878 : ) -> std::io::Result<()> {
2879 : debug!("persisting tenantconf to {config_path}");
2880 :
2881 : let mut conf_content = r#"# This file contains a specific per-tenant's config.
2882 : # It is read in case of pageserver restart.
2883 : "#
2884 : .to_string();
2885 :
2886 0 : fail::fail_point!("tenant-config-before-write", |_| {
2887 0 : Err(std::io::Error::new(
2888 0 : std::io::ErrorKind::Other,
2889 0 : "tenant-config-before-write",
2890 0 : ))
2891 0 : });
2892 :
2893 : // Convert the config to a toml file.
2894 : conf_content +=
2895 : &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
2896 :
2897 : let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
2898 :
2899 : let conf_content = conf_content.into_bytes();
2900 : VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
2901 : }
2902 :
2903 : //
2904 : // How garbage collection works:
2905 : //
2906 : // +--bar------------->
2907 : // /
2908 : // +----+-----foo---------------->
2909 : // /
2910 : // ----main--+-------------------------->
2911 : // \
2912 : // +-----baz-------->
2913 : //
2914 : //
2915 : // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
2916 : // `gc_infos` are being refreshed
2917 : // 2. Scan collected timelines, and on each timeline, make note of the
2918 : // all the points where other timelines have been branched off.
2919 : // We will refrain from removing page versions at those LSNs.
2920 : // 3. For each timeline, scan all layer files on the timeline.
2921 : // Remove all files for which a newer file exists and which
2922 : // don't cover any branch point LSNs.
2923 : //
2924 : // TODO:
2925 : // - if a relation has a non-incremental persistent layer on a child branch, then we
2926 : // don't need to keep that in the parent anymore. But currently
2927 : // we do.
2928 2262 : async fn gc_iteration_internal(
2929 2262 : &self,
2930 2262 : target_timeline_id: Option<TimelineId>,
2931 2262 : horizon: u64,
2932 2262 : pitr: Duration,
2933 2262 : cancel: &CancellationToken,
2934 2262 : ctx: &RequestContext,
2935 2262 : ) -> Result<GcResult, GcError> {
2936 2262 : let mut totals: GcResult = Default::default();
2937 2262 : let now = Instant::now();
2938 :
2939 2262 : let gc_timelines = self
2940 2262 : .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
2941 2235 : .await?;
2942 :
2943 2262 : failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
2944 :
2945 : // If there is nothing to GC, we don't want any messages in the INFO log.
2946 2262 : if !gc_timelines.is_empty() {
2947 2262 : info!("{} timelines need GC", gc_timelines.len());
2948 : } else {
2949 0 : debug!("{} timelines need GC", gc_timelines.len());
2950 : }
2951 :
2952 : // Perform GC for each timeline.
2953 : //
2954 : // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
2955 : // branch creation task, which requires the GC lock. A GC iteration can run concurrently
2956 : // with branch creation.
2957 : //
2958 : // See comments in [`Tenant::branch_timeline`] for more information about why branch
2959 : // creation task can run concurrently with timeline's GC iteration.
2960 4524 : for timeline in gc_timelines {
2961 2262 : if cancel.is_cancelled() {
2962 : // We were requested to shut down. Stop and return with the progress we
2963 : // made.
2964 0 : break;
2965 2262 : }
2966 2262 : let result = match timeline.gc().await {
2967 : Err(GcError::TimelineCancelled) => {
2968 0 : if target_timeline_id.is_some() {
2969 : // If we were targetting this specific timeline, surface cancellation to caller
2970 0 : return Err(GcError::TimelineCancelled);
2971 : } else {
2972 : // A timeline may be shutting down independently of the tenant's lifecycle: we should
2973 : // skip past this and proceed to try GC on other timelines.
2974 0 : continue;
2975 : }
2976 : }
2977 2262 : r => r?,
2978 : };
2979 2262 : totals += result;
2980 : }
2981 :
2982 2262 : totals.elapsed = now.elapsed();
2983 2262 : Ok(totals)
2984 2262 : }
2985 :
2986 : /// Refreshes the Timeline::gc_info for all timelines, returning the
2987 : /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
2988 : /// [`Tenant::get_gc_horizon`].
2989 : ///
2990 : /// This is usually executed as part of periodic gc, but can now be triggered more often.
2991 0 : pub(crate) async fn refresh_gc_info(
2992 0 : &self,
2993 0 : cancel: &CancellationToken,
2994 0 : ctx: &RequestContext,
2995 0 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
2996 0 : // since this method can now be called at different rates than the configured gc loop, it
2997 0 : // might be that these configuration values get applied faster than what it was previously,
2998 0 : // since these were only read from the gc task.
2999 0 : let horizon = self.get_gc_horizon();
3000 0 : let pitr = self.get_pitr_interval();
3001 0 :
3002 0 : // refresh all timelines
3003 0 : let target_timeline_id = None;
3004 0 :
3005 0 : self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
3006 0 : .await
3007 0 : }
3008 :
3009 : /// Populate all Timelines' `GcInfo` with information about their children. We do not set the
3010 : /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
3011 : ///
3012 : /// Subsequently, parent-child relationships are updated incrementally during timeline creation/deletion.
3013 0 : fn initialize_gc_info(
3014 0 : &self,
3015 0 : timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
3016 0 : ) {
3017 0 : // This function must be called before activation: after activation timeline create/delete operations
3018 0 : // might happen, and this function is not safe to run concurrently with those.
3019 0 : assert!(!self.is_active());
3020 :
3021 : // Scan all timelines. For each timeline, remember the timeline ID and
3022 : // the branch point where it was created.
3023 0 : let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId)>> = BTreeMap::new();
3024 0 : timelines.iter().for_each(|(timeline_id, timeline_entry)| {
3025 0 : if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
3026 0 : let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
3027 0 : ancestor_children.push((timeline_entry.get_ancestor_lsn(), *timeline_id));
3028 0 : }
3029 0 : });
3030 0 :
3031 0 : // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
3032 0 : let horizon = self.get_gc_horizon();
3033 :
3034 : // Populate each timeline's GcInfo with information about its child branches
3035 0 : for timeline in timelines.values() {
3036 0 : let mut branchpoints: Vec<(Lsn, TimelineId)> = all_branchpoints
3037 0 : .remove(&timeline.timeline_id)
3038 0 : .unwrap_or_default();
3039 0 :
3040 0 : branchpoints.sort_by_key(|b| b.0);
3041 0 :
3042 0 : let mut target = timeline.gc_info.write().unwrap();
3043 0 :
3044 0 : target.retain_lsns = branchpoints;
3045 0 :
3046 0 : let space_cutoff = timeline
3047 0 : .get_last_record_lsn()
3048 0 : .checked_sub(horizon)
3049 0 : .unwrap_or(Lsn(0));
3050 0 :
3051 0 : target.cutoffs = GcCutoffs {
3052 0 : space: space_cutoff,
3053 0 : time: Lsn::INVALID,
3054 0 : };
3055 0 : }
3056 0 : }
3057 :
3058 2262 : async fn refresh_gc_info_internal(
3059 2262 : &self,
3060 2262 : target_timeline_id: Option<TimelineId>,
3061 2262 : horizon: u64,
3062 2262 : pitr: Duration,
3063 2262 : cancel: &CancellationToken,
3064 2262 : ctx: &RequestContext,
3065 2262 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
3066 2262 : // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
3067 2262 : // currently visible timelines.
3068 2262 : let timelines = self
3069 2262 : .timelines
3070 2262 : .lock()
3071 2262 : .unwrap()
3072 2262 : .values()
3073 9930 : .filter(|tl| match target_timeline_id.as_ref() {
3074 9930 : Some(target) => &tl.timeline_id == target,
3075 0 : None => true,
3076 9930 : })
3077 2262 : .cloned()
3078 2262 : .collect::<Vec<_>>();
3079 2262 :
3080 2262 : if target_timeline_id.is_some() && timelines.is_empty() {
3081 : // We were to act on a particular timeline and it wasn't found
3082 0 : return Err(GcError::TimelineNotFound);
3083 2262 : }
3084 2262 :
3085 2262 : let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
3086 2262 : HashMap::with_capacity(timelines.len());
3087 :
3088 2262 : for timeline in timelines.iter() {
3089 2262 : let cutoff = timeline
3090 2262 : .get_last_record_lsn()
3091 2262 : .checked_sub(horizon)
3092 2262 : .unwrap_or(Lsn(0));
3093 :
3094 2262 : let cutoffs = timeline.find_gc_cutoffs(cutoff, pitr, cancel, ctx).await?;
3095 2262 : let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
3096 2262 : assert!(old.is_none());
3097 : }
3098 :
3099 2262 : if !self.is_active() || self.cancel.is_cancelled() {
3100 0 : return Err(GcError::TenantCancelled);
3101 2262 : }
3102 :
3103 : // grab mutex to prevent new timelines from being created here; avoid doing long operations
3104 : // because that will stall branch creation.
3105 2262 : let gc_cs = self.gc_cs.lock().await;
3106 :
3107 : // Ok, we now know all the branch points.
3108 : // Update the GC information for each timeline.
3109 2262 : let mut gc_timelines = Vec::with_capacity(timelines.len());
3110 4524 : for timeline in timelines {
3111 : // We filtered the timeline list above
3112 2262 : if let Some(target_timeline_id) = target_timeline_id {
3113 2262 : assert_eq!(target_timeline_id, timeline.timeline_id);
3114 0 : }
3115 :
3116 : {
3117 2262 : let mut target = timeline.gc_info.write().unwrap();
3118 2262 :
3119 2262 : // Cull any expired leases
3120 2262 : let now = SystemTime::now();
3121 2262 : target.leases.retain(|_, lease| !lease.is_expired(&now));
3122 2262 :
3123 2262 : timeline
3124 2262 : .metrics
3125 2262 : .valid_lsn_lease_count_gauge
3126 2262 : .set(target.leases.len() as u64);
3127 :
3128 : // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
3129 2262 : if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
3130 300 : if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
3131 0 : target.within_ancestor_pitr =
3132 0 : timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
3133 300 : }
3134 1962 : }
3135 :
3136 : // Update metrics that depend on GC state
3137 2262 : timeline
3138 2262 : .metrics
3139 2262 : .archival_size
3140 2262 : .set(if target.within_ancestor_pitr {
3141 0 : timeline.metrics.current_logical_size_gauge.get()
3142 : } else {
3143 2262 : 0
3144 : });
3145 2262 : timeline.metrics.pitr_history_size.set(
3146 2262 : timeline
3147 2262 : .get_last_record_lsn()
3148 2262 : .checked_sub(target.cutoffs.time)
3149 2262 : .unwrap_or(Lsn(0))
3150 2262 : .0,
3151 2262 : );
3152 :
3153 : // Apply the cutoffs we found to the Timeline's GcInfo. Why might we _not_ have cutoffs for a timeline?
3154 : // - this timeline was created while we were finding cutoffs
3155 : // - lsn for timestamp search fails for this timeline repeatedly
3156 2262 : if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
3157 2262 : target.cutoffs = cutoffs.clone();
3158 2262 : }
3159 : }
3160 :
3161 2262 : gc_timelines.push(timeline);
3162 : }
3163 2262 : drop(gc_cs);
3164 2262 : Ok(gc_timelines)
3165 2262 : }
3166 :
3167 : /// A substitute for `branch_timeline` for use in unit tests.
3168 : /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
3169 : /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
3170 : /// timeline background tasks are launched, except the flush loop.
3171 : #[cfg(test)]
3172 690 : async fn branch_timeline_test(
3173 690 : &self,
3174 690 : src_timeline: &Arc<Timeline>,
3175 690 : dst_id: TimelineId,
3176 690 : ancestor_lsn: Option<Lsn>,
3177 690 : ctx: &RequestContext,
3178 690 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
3179 690 : let create_guard = self.create_timeline_create_guard(dst_id).unwrap();
3180 690 : let tl = self
3181 690 : .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, create_guard, ctx)
3182 12 : .await?;
3183 678 : tl.set_state(TimelineState::Active);
3184 678 : Ok(tl)
3185 690 : }
3186 :
3187 : /// Helper for unit tests to branch a timeline with some pre-loaded states.
3188 : #[cfg(test)]
3189 : #[allow(clippy::too_many_arguments)]
3190 18 : pub async fn branch_timeline_test_with_layers(
3191 18 : &self,
3192 18 : src_timeline: &Arc<Timeline>,
3193 18 : dst_id: TimelineId,
3194 18 : ancestor_lsn: Option<Lsn>,
3195 18 : ctx: &RequestContext,
3196 18 : delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
3197 18 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
3198 18 : end_lsn: Lsn,
3199 18 : ) -> anyhow::Result<Arc<Timeline>> {
3200 18 : let tline = self
3201 18 : .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
3202 0 : .await?;
3203 18 : let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
3204 18 : ancestor_lsn
3205 : } else {
3206 0 : tline.get_last_record_lsn()
3207 : };
3208 18 : assert!(end_lsn >= ancestor_lsn);
3209 18 : tline.force_advance_lsn(end_lsn);
3210 36 : for deltas in delta_layer_desc {
3211 18 : tline
3212 18 : .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
3213 54 : .await?;
3214 : }
3215 30 : for (lsn, images) in image_layer_desc {
3216 12 : tline
3217 12 : .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
3218 42 : .await?;
3219 : }
3220 18 : Ok(tline)
3221 18 : }
3222 :
3223 : /// Branch an existing timeline.
3224 : ///
3225 : /// The caller is responsible for activating the returned timeline.
3226 0 : async fn branch_timeline(
3227 0 : &self,
3228 0 : src_timeline: &Arc<Timeline>,
3229 0 : dst_id: TimelineId,
3230 0 : start_lsn: Option<Lsn>,
3231 0 : timeline_create_guard: TimelineCreateGuard<'_>,
3232 0 : ctx: &RequestContext,
3233 0 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
3234 0 : self.branch_timeline_impl(src_timeline, dst_id, start_lsn, timeline_create_guard, ctx)
3235 0 : .await
3236 0 : }
3237 :
3238 690 : async fn branch_timeline_impl(
3239 690 : &self,
3240 690 : src_timeline: &Arc<Timeline>,
3241 690 : dst_id: TimelineId,
3242 690 : start_lsn: Option<Lsn>,
3243 690 : timeline_create_guard: TimelineCreateGuard<'_>,
3244 690 : _ctx: &RequestContext,
3245 690 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
3246 690 : let src_id = src_timeline.timeline_id;
3247 :
3248 : // We will validate our ancestor LSN in this function. Acquire the GC lock so that
3249 : // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
3250 : // valid while we are creating the branch.
3251 690 : let _gc_cs = self.gc_cs.lock().await;
3252 :
3253 : // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
3254 690 : let start_lsn = start_lsn.unwrap_or_else(|| {
3255 6 : let lsn = src_timeline.get_last_record_lsn();
3256 6 : info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
3257 6 : lsn
3258 690 : });
3259 690 :
3260 690 : // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
3261 690 : // horizon on the source timeline
3262 690 : //
3263 690 : // We check it against both the planned GC cutoff stored in 'gc_info',
3264 690 : // and the 'latest_gc_cutoff' of the last GC that was performed. The
3265 690 : // planned GC cutoff in 'gc_info' is normally larger than
3266 690 : // 'latest_gc_cutoff_lsn', but beware of corner cases like if you just
3267 690 : // changed the GC settings for the tenant to make the PITR window
3268 690 : // larger, but some of the data was already removed by an earlier GC
3269 690 : // iteration.
3270 690 :
3271 690 : // check against last actual 'latest_gc_cutoff' first
3272 690 : let latest_gc_cutoff_lsn = src_timeline.get_latest_gc_cutoff_lsn();
3273 690 : src_timeline
3274 690 : .check_lsn_is_in_scope(start_lsn, &latest_gc_cutoff_lsn)
3275 690 : .context(format!(
3276 690 : "invalid branch start lsn: less than latest GC cutoff {}",
3277 690 : *latest_gc_cutoff_lsn,
3278 690 : ))
3279 690 : .map_err(CreateTimelineError::AncestorLsn)?;
3280 :
3281 : // and then the planned GC cutoff
3282 : {
3283 678 : let gc_info = src_timeline.gc_info.read().unwrap();
3284 678 : let cutoff = gc_info.min_cutoff();
3285 678 : if start_lsn < cutoff {
3286 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
3287 0 : "invalid branch start lsn: less than planned GC cutoff {cutoff}"
3288 0 : )));
3289 678 : }
3290 678 : }
3291 678 :
3292 678 : //
3293 678 : // The branch point is valid, and we are still holding the 'gc_cs' lock
3294 678 : // so that GC cannot advance the GC cutoff until we are finished.
3295 678 : // Proceed with the branch creation.
3296 678 : //
3297 678 :
3298 678 : // Determine prev-LSN for the new timeline. We can only determine it if
3299 678 : // the timeline was branched at the current end of the source timeline.
3300 678 : let RecordLsn {
3301 678 : last: src_last,
3302 678 : prev: src_prev,
3303 678 : } = src_timeline.get_last_record_rlsn();
3304 678 : let dst_prev = if src_last == start_lsn {
3305 648 : Some(src_prev)
3306 : } else {
3307 30 : None
3308 : };
3309 :
3310 : // Create the metadata file, noting the ancestor of the new timeline.
3311 : // There is initially no data in it, but all the read-calls know to look
3312 : // into the ancestor.
3313 678 : let metadata = TimelineMetadata::new(
3314 678 : start_lsn,
3315 678 : dst_prev,
3316 678 : Some(src_id),
3317 678 : start_lsn,
3318 678 : *src_timeline.latest_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
3319 678 : src_timeline.initdb_lsn,
3320 678 : src_timeline.pg_version,
3321 678 : );
3322 :
3323 678 : let uninitialized_timeline = self
3324 678 : .prepare_new_timeline(
3325 678 : dst_id,
3326 678 : &metadata,
3327 678 : timeline_create_guard,
3328 678 : start_lsn + 1,
3329 678 : Some(Arc::clone(src_timeline)),
3330 678 : src_timeline.last_aux_file_policy.load(),
3331 678 : )
3332 0 : .await?;
3333 :
3334 678 : let new_timeline = uninitialized_timeline.finish_creation()?;
3335 :
3336 : // Root timeline gets its layers during creation and uploads them along with the metadata.
3337 : // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
3338 : // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
3339 : // could get incorrect information and remove more layers, than needed.
3340 : // See also https://github.com/neondatabase/neon/issues/3865
3341 678 : new_timeline
3342 678 : .remote_client
3343 678 : .schedule_index_upload_for_full_metadata_update(&metadata)
3344 678 : .context("branch initial metadata upload")?;
3345 :
3346 678 : Ok(new_timeline)
3347 690 : }
3348 :
3349 : /// For unit tests, make this visible so that other modules can directly create timelines
3350 : #[cfg(test)]
3351 6 : #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
3352 : pub(crate) async fn bootstrap_timeline_test(
3353 : &self,
3354 : timeline_id: TimelineId,
3355 : pg_version: u32,
3356 : load_existing_initdb: Option<TimelineId>,
3357 : ctx: &RequestContext,
3358 : ) -> anyhow::Result<Arc<Timeline>> {
3359 : let create_guard = self.create_timeline_create_guard(timeline_id).unwrap();
3360 : self.bootstrap_timeline(
3361 : timeline_id,
3362 : pg_version,
3363 : load_existing_initdb,
3364 : create_guard,
3365 : ctx,
3366 : )
3367 : .await
3368 : }
3369 :
3370 0 : async fn upload_initdb(
3371 0 : &self,
3372 0 : timelines_path: &Utf8PathBuf,
3373 0 : pgdata_path: &Utf8PathBuf,
3374 0 : timeline_id: &TimelineId,
3375 0 : ) -> anyhow::Result<()> {
3376 0 : let temp_path = timelines_path.join(format!(
3377 0 : "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
3378 0 : ));
3379 0 :
3380 0 : scopeguard::defer! {
3381 0 : if let Err(e) = fs::remove_file(&temp_path) {
3382 0 : error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
3383 0 : }
3384 0 : }
3385 :
3386 0 : let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
3387 : const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
3388 0 : if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
3389 0 : warn!(
3390 0 : "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
3391 : );
3392 0 : }
3393 :
3394 0 : pausable_failpoint!("before-initdb-upload");
3395 :
3396 0 : backoff::retry(
3397 0 : || async {
3398 0 : self::remote_timeline_client::upload_initdb_dir(
3399 0 : &self.remote_storage,
3400 0 : &self.tenant_shard_id.tenant_id,
3401 0 : timeline_id,
3402 0 : pgdata_zstd.try_clone().await?,
3403 0 : tar_zst_size,
3404 0 : &self.cancel,
3405 : )
3406 0 : .await
3407 0 : },
3408 0 : |_| false,
3409 0 : 3,
3410 0 : u32::MAX,
3411 0 : "persist_initdb_tar_zst",
3412 0 : &self.cancel,
3413 0 : )
3414 0 : .await
3415 0 : .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
3416 0 : .and_then(|x| x)
3417 0 : }
3418 :
3419 : /// - run initdb to init temporary instance and get bootstrap data
3420 : /// - after initialization completes, tar up the temp dir and upload it to S3.
3421 : ///
3422 : /// The caller is responsible for activating the returned timeline.
3423 6 : async fn bootstrap_timeline(
3424 6 : &self,
3425 6 : timeline_id: TimelineId,
3426 6 : pg_version: u32,
3427 6 : load_existing_initdb: Option<TimelineId>,
3428 6 : timeline_create_guard: TimelineCreateGuard<'_>,
3429 6 : ctx: &RequestContext,
3430 6 : ) -> anyhow::Result<Arc<Timeline>> {
3431 6 : // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
3432 6 : // temporary directory for basebackup files for the given timeline.
3433 6 :
3434 6 : let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
3435 6 : let pgdata_path = path_with_suffix_extension(
3436 6 : timelines_path.join(format!("basebackup-{timeline_id}")),
3437 6 : TEMP_FILE_SUFFIX,
3438 6 : );
3439 6 :
3440 6 : // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
3441 6 : // we won't race with other creations or existent timelines with the same path.
3442 6 : if pgdata_path.exists() {
3443 0 : fs::remove_dir_all(&pgdata_path).with_context(|| {
3444 0 : format!("Failed to remove already existing initdb directory: {pgdata_path}")
3445 0 : })?;
3446 6 : }
3447 :
3448 : // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
3449 6 : scopeguard::defer! {
3450 6 : if let Err(e) = fs::remove_dir_all(&pgdata_path) {
3451 6 : // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
3452 6 : error!("Failed to remove temporary initdb directory '{pgdata_path}': {e}");
3453 6 : }
3454 6 : }
3455 6 : if let Some(existing_initdb_timeline_id) = load_existing_initdb {
3456 6 : if existing_initdb_timeline_id != timeline_id {
3457 0 : let source_path = &remote_initdb_archive_path(
3458 0 : &self.tenant_shard_id.tenant_id,
3459 0 : &existing_initdb_timeline_id,
3460 0 : );
3461 0 : let dest_path =
3462 0 : &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
3463 0 :
3464 0 : // if this fails, it will get retried by retried control plane requests
3465 0 : self.remote_storage
3466 0 : .copy_object(source_path, dest_path, &self.cancel)
3467 0 : .await
3468 0 : .context("copy initdb tar")?;
3469 6 : }
3470 6 : let (initdb_tar_zst_path, initdb_tar_zst) =
3471 6 : self::remote_timeline_client::download_initdb_tar_zst(
3472 6 : self.conf,
3473 6 : &self.remote_storage,
3474 6 : &self.tenant_shard_id,
3475 6 : &existing_initdb_timeline_id,
3476 6 : &self.cancel,
3477 6 : )
3478 2022 : .await
3479 6 : .context("download initdb tar")?;
3480 :
3481 6 : scopeguard::defer! {
3482 6 : if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
3483 6 : error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
3484 6 : }
3485 6 : }
3486 6 :
3487 6 : let buf_read =
3488 6 : BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
3489 6 : extract_zst_tarball(&pgdata_path, buf_read)
3490 30017 : .await
3491 6 : .context("extract initdb tar")?;
3492 : } else {
3493 : // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
3494 0 : run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel).await?;
3495 :
3496 : // Upload the created data dir to S3
3497 0 : if self.tenant_shard_id().is_shard_zero() {
3498 0 : self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
3499 0 : .await?;
3500 0 : }
3501 : }
3502 6 : let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
3503 6 :
3504 6 : // Import the contents of the data directory at the initial checkpoint
3505 6 : // LSN, and any WAL after that.
3506 6 : // Initdb lsn will be equal to last_record_lsn which will be set after import.
3507 6 : // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
3508 6 : let new_metadata = TimelineMetadata::new(
3509 6 : Lsn(0),
3510 6 : None,
3511 6 : None,
3512 6 : Lsn(0),
3513 6 : pgdata_lsn,
3514 6 : pgdata_lsn,
3515 6 : pg_version,
3516 6 : );
3517 6 : let raw_timeline = self
3518 6 : .prepare_new_timeline(
3519 6 : timeline_id,
3520 6 : &new_metadata,
3521 6 : timeline_create_guard,
3522 6 : pgdata_lsn,
3523 6 : None,
3524 6 : None,
3525 6 : )
3526 0 : .await?;
3527 :
3528 6 : let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
3529 6 : let unfinished_timeline = raw_timeline.raw_timeline()?;
3530 :
3531 : // Flush the new layer files to disk, before we make the timeline as available to
3532 : // the outside world.
3533 : //
3534 : // Flush loop needs to be spawned in order to be able to flush.
3535 6 : unfinished_timeline.maybe_spawn_flush_loop();
3536 6 :
3537 6 : import_datadir::import_timeline_from_postgres_datadir(
3538 6 : unfinished_timeline,
3539 6 : &pgdata_path,
3540 6 : pgdata_lsn,
3541 6 : ctx,
3542 6 : )
3543 28925 : .await
3544 6 : .with_context(|| {
3545 0 : format!("Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}")
3546 6 : })?;
3547 :
3548 6 : fail::fail_point!("before-checkpoint-new-timeline", |_| {
3549 0 : anyhow::bail!("failpoint before-checkpoint-new-timeline");
3550 6 : });
3551 :
3552 6 : unfinished_timeline
3553 6 : .freeze_and_flush()
3554 6 : .await
3555 6 : .with_context(|| {
3556 0 : format!(
3557 0 : "Failed to flush after pgdatadir import for timeline {tenant_shard_id}/{timeline_id}"
3558 0 : )
3559 6 : })?;
3560 :
3561 : // All done!
3562 6 : let timeline = raw_timeline.finish_creation()?;
3563 :
3564 6 : Ok(timeline)
3565 6 : }
3566 :
3567 : /// Call this before constructing a timeline, to build its required structures
3568 1218 : fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
3569 1218 : let remote_client = RemoteTimelineClient::new(
3570 1218 : self.remote_storage.clone(),
3571 1218 : self.deletion_queue_client.clone(),
3572 1218 : self.conf,
3573 1218 : self.tenant_shard_id,
3574 1218 : timeline_id,
3575 1218 : self.generation,
3576 1218 : );
3577 1218 : TimelineResources {
3578 1218 : remote_client,
3579 1218 : timeline_get_throttle: self.timeline_get_throttle.clone(),
3580 1218 : l0_flush_global_state: self.l0_flush_global_state.clone(),
3581 1218 : }
3582 1218 : }
3583 :
3584 : /// Creates intermediate timeline structure and its files.
3585 : ///
3586 : /// An empty layer map is initialized, and new data and WAL can be imported starting
3587 : /// at 'disk_consistent_lsn'. After any initial data has been imported, call
3588 : /// `finish_creation` to insert the Timeline into the timelines map.
3589 1218 : async fn prepare_new_timeline<'a>(
3590 1218 : &'a self,
3591 1218 : new_timeline_id: TimelineId,
3592 1218 : new_metadata: &TimelineMetadata,
3593 1218 : create_guard: TimelineCreateGuard<'a>,
3594 1218 : start_lsn: Lsn,
3595 1218 : ancestor: Option<Arc<Timeline>>,
3596 1218 : last_aux_file_policy: Option<AuxFilePolicy>,
3597 1218 : ) -> anyhow::Result<UninitializedTimeline> {
3598 1218 : let tenant_shard_id = self.tenant_shard_id;
3599 1218 :
3600 1218 : let resources = self.build_timeline_resources(new_timeline_id);
3601 1218 : resources
3602 1218 : .remote_client
3603 1218 : .init_upload_queue_for_empty_remote(new_metadata)?;
3604 :
3605 1218 : let timeline_struct = self
3606 1218 : .create_timeline_struct(
3607 1218 : new_timeline_id,
3608 1218 : new_metadata,
3609 1218 : ancestor,
3610 1218 : resources,
3611 1218 : CreateTimelineCause::Load,
3612 1218 : last_aux_file_policy,
3613 1218 : )
3614 1218 : .context("Failed to create timeline data structure")?;
3615 :
3616 1218 : timeline_struct.init_empty_layer_map(start_lsn);
3617 :
3618 1218 : if let Err(e) = self
3619 1218 : .create_timeline_files(&create_guard.timeline_path)
3620 0 : .await
3621 : {
3622 0 : error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
3623 0 : cleanup_timeline_directory(create_guard);
3624 0 : return Err(e);
3625 1218 : }
3626 1218 :
3627 1218 : debug!(
3628 0 : "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
3629 : );
3630 :
3631 1218 : Ok(UninitializedTimeline::new(
3632 1218 : self,
3633 1218 : new_timeline_id,
3634 1218 : Some((timeline_struct, create_guard)),
3635 1218 : ))
3636 1218 : }
3637 :
3638 1218 : async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
3639 1218 : crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
3640 :
3641 1218 : fail::fail_point!("after-timeline-dir-creation", |_| {
3642 0 : anyhow::bail!("failpoint after-timeline-dir-creation");
3643 1218 : });
3644 :
3645 1218 : Ok(())
3646 1218 : }
3647 :
3648 : /// Get a guard that provides exclusive access to the timeline directory, preventing
3649 : /// concurrent attempts to create the same timeline.
3650 1236 : fn create_timeline_create_guard(
3651 1236 : &self,
3652 1236 : timeline_id: TimelineId,
3653 1236 : ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
3654 1236 : let tenant_shard_id = self.tenant_shard_id;
3655 1236 :
3656 1236 : let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
3657 :
3658 1236 : let create_guard = TimelineCreateGuard::new(self, timeline_id, timeline_path.clone())?;
3659 :
3660 : // At this stage, we have got exclusive access to in-memory state for this timeline ID
3661 : // for creation.
3662 : // A timeline directory should never exist on disk already:
3663 : // - a previous failed creation would have cleaned up after itself
3664 : // - a pageserver restart would clean up timeline directories that don't have valid remote state
3665 : //
3666 : // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
3667 : // this error may indicate a bug in cleanup on failed creations.
3668 1230 : if timeline_path.exists() {
3669 0 : return Err(TimelineExclusionError::Other(anyhow::anyhow!(
3670 0 : "Timeline directory already exists! This is a bug."
3671 0 : )));
3672 1230 : }
3673 1230 :
3674 1230 : Ok(create_guard)
3675 1236 : }
3676 :
3677 : /// Gathers inputs from all of the timelines to produce a sizing model input.
3678 : ///
3679 : /// Future is cancellation safe. Only one calculation can be running at once per tenant.
3680 0 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
3681 : pub async fn gather_size_inputs(
3682 : &self,
3683 : // `max_retention_period` overrides the cutoff that is used to calculate the size
3684 : // (only if it is shorter than the real cutoff).
3685 : max_retention_period: Option<u64>,
3686 : cause: LogicalSizeCalculationCause,
3687 : cancel: &CancellationToken,
3688 : ctx: &RequestContext,
3689 : ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
3690 : let logical_sizes_at_once = self
3691 : .conf
3692 : .concurrent_tenant_size_logical_size_queries
3693 : .inner();
3694 :
3695 : // TODO: Having a single mutex block concurrent reads is not great for performance.
3696 : //
3697 : // But the only case where we need to run multiple of these at once is when we
3698 : // request a size for a tenant manually via API, while another background calculation
3699 : // is in progress (which is not a common case).
3700 : //
3701 : // See more for on the issue #2748 condenced out of the initial PR review.
3702 : let mut shared_cache = tokio::select! {
3703 : locked = self.cached_logical_sizes.lock() => locked,
3704 : _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
3705 : _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
3706 : };
3707 :
3708 : size::gather_inputs(
3709 : self,
3710 : logical_sizes_at_once,
3711 : max_retention_period,
3712 : &mut shared_cache,
3713 : cause,
3714 : cancel,
3715 : ctx,
3716 : )
3717 : .await
3718 : }
3719 :
3720 : /// Calculate synthetic tenant size and cache the result.
3721 : /// This is periodically called by background worker.
3722 : /// result is cached in tenant struct
3723 0 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
3724 : pub async fn calculate_synthetic_size(
3725 : &self,
3726 : cause: LogicalSizeCalculationCause,
3727 : cancel: &CancellationToken,
3728 : ctx: &RequestContext,
3729 : ) -> Result<u64, size::CalculateSyntheticSizeError> {
3730 : let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
3731 :
3732 : let size = inputs.calculate();
3733 :
3734 : self.set_cached_synthetic_size(size);
3735 :
3736 : Ok(size)
3737 : }
3738 :
3739 : /// Cache given synthetic size and update the metric value
3740 0 : pub fn set_cached_synthetic_size(&self, size: u64) {
3741 0 : self.cached_synthetic_tenant_size
3742 0 : .store(size, Ordering::Relaxed);
3743 0 :
3744 0 : // Only shard zero should be calculating synthetic sizes
3745 0 : debug_assert!(self.shard_identity.is_shard_zero());
3746 :
3747 0 : TENANT_SYNTHETIC_SIZE_METRIC
3748 0 : .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
3749 0 : .unwrap()
3750 0 : .set(size);
3751 0 : }
3752 :
3753 0 : pub fn cached_synthetic_size(&self) -> u64 {
3754 0 : self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
3755 0 : }
3756 :
3757 : /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
3758 : ///
3759 : /// This function can take a long time: callers should wrap it in a timeout if calling
3760 : /// from an external API handler.
3761 : ///
3762 : /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
3763 : /// still bounded by tenant/timeline shutdown.
3764 0 : #[tracing::instrument(skip_all)]
3765 : pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
3766 : let timelines = self.timelines.lock().unwrap().clone();
3767 :
3768 0 : async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
3769 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
3770 0 : timeline.freeze_and_flush().await?;
3771 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
3772 0 : timeline.remote_client.wait_completion().await?;
3773 :
3774 0 : Ok(())
3775 0 : }
3776 :
3777 : // We do not use a JoinSet for these tasks, because we don't want them to be
3778 : // aborted when this function's future is cancelled: they should stay alive
3779 : // holding their GateGuard until they complete, to ensure their I/Os complete
3780 : // before Timeline shutdown completes.
3781 : let mut results = FuturesUnordered::new();
3782 :
3783 : for (_timeline_id, timeline) in timelines {
3784 : // Run each timeline's flush in a task holding the timeline's gate: this
3785 : // means that if this function's future is cancelled, the Timeline shutdown
3786 : // will still wait for any I/O in here to complete.
3787 : let Ok(gate) = timeline.gate.enter() else {
3788 : continue;
3789 : };
3790 0 : let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
3791 : results.push(jh);
3792 : }
3793 :
3794 : while let Some(r) = results.next().await {
3795 : if let Err(e) = r {
3796 : if !e.is_cancelled() && !e.is_panic() {
3797 : tracing::error!("unexpected join error: {e:?}");
3798 : }
3799 : }
3800 : }
3801 :
3802 : // The flushes we did above were just writes, but the Tenant might have had
3803 : // pending deletions as well from recent compaction/gc: we want to flush those
3804 : // as well. This requires flushing the global delete queue. This is cheap
3805 : // because it's typically a no-op.
3806 : match self.deletion_queue_client.flush_execute().await {
3807 : Ok(_) => {}
3808 : Err(DeletionQueueError::ShuttingDown) => {}
3809 : }
3810 :
3811 : Ok(())
3812 : }
3813 :
3814 0 : pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
3815 0 : self.tenant_conf.load().tenant_conf.clone()
3816 0 : }
3817 :
3818 : /// How much local storage would this tenant like to have? It can cope with
3819 : /// less than this (via eviction and on-demand downloads), but this function enables
3820 : /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
3821 : /// by keeping important things on local disk.
3822 : ///
3823 : /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
3824 : /// than they report here, due to layer eviction. Tenants with many active branches may
3825 : /// actually use more than they report here.
3826 0 : pub(crate) fn local_storage_wanted(&self) -> u64 {
3827 0 : let timelines = self.timelines.lock().unwrap();
3828 0 :
3829 0 : // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum. This
3830 0 : // reflects the observation that on tenants with multiple large branches, typically only one
3831 0 : // of them is used actively enough to occupy space on disk.
3832 0 : timelines
3833 0 : .values()
3834 0 : .map(|t| t.metrics.visible_physical_size_gauge.get())
3835 0 : .max()
3836 0 : .unwrap_or(0)
3837 0 : }
3838 : }
3839 :
3840 : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
3841 : /// to get bootstrap data for timeline initialization.
3842 0 : async fn run_initdb(
3843 0 : conf: &'static PageServerConf,
3844 0 : initdb_target_dir: &Utf8Path,
3845 0 : pg_version: u32,
3846 0 : cancel: &CancellationToken,
3847 0 : ) -> Result<(), InitdbError> {
3848 0 : let initdb_bin_path = conf
3849 0 : .pg_bin_dir(pg_version)
3850 0 : .map_err(InitdbError::Other)?
3851 0 : .join("initdb");
3852 0 : let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
3853 0 : info!(
3854 0 : "running {} in {}, libdir: {}",
3855 : initdb_bin_path, initdb_target_dir, initdb_lib_dir,
3856 : );
3857 :
3858 0 : let _permit = INIT_DB_SEMAPHORE.acquire().await;
3859 :
3860 0 : let initdb_command = tokio::process::Command::new(&initdb_bin_path)
3861 0 : .args(["-D", initdb_target_dir.as_ref()])
3862 0 : .args(["-U", &conf.superuser])
3863 0 : .args(["-E", "utf8"])
3864 0 : .arg("--no-instructions")
3865 0 : .arg("--no-sync")
3866 0 : .env_clear()
3867 0 : .env("LD_LIBRARY_PATH", &initdb_lib_dir)
3868 0 : .env("DYLD_LIBRARY_PATH", &initdb_lib_dir)
3869 0 : .stdin(std::process::Stdio::null())
3870 0 : // stdout invocation produces the same output every time, we don't need it
3871 0 : .stdout(std::process::Stdio::null())
3872 0 : // we would be interested in the stderr output, if there was any
3873 0 : .stderr(std::process::Stdio::piped())
3874 0 : .spawn()?;
3875 :
3876 : // Ideally we'd select here with the cancellation token, but the problem is that
3877 : // we can't safely terminate initdb: it launches processes of its own, and killing
3878 : // initdb doesn't kill them. After we return from this function, we want the target
3879 : // directory to be able to be cleaned up.
3880 : // See https://github.com/neondatabase/neon/issues/6385
3881 0 : let initdb_output = initdb_command.wait_with_output().await?;
3882 0 : if !initdb_output.status.success() {
3883 0 : return Err(InitdbError::Failed(
3884 0 : initdb_output.status,
3885 0 : initdb_output.stderr,
3886 0 : ));
3887 0 : }
3888 0 :
3889 0 : // This isn't true cancellation support, see above. Still return an error to
3890 0 : // excercise the cancellation code path.
3891 0 : if cancel.is_cancelled() {
3892 0 : return Err(InitdbError::Cancelled);
3893 0 : }
3894 0 :
3895 0 : Ok(())
3896 0 : }
3897 :
3898 : /// Dump contents of a layer file to stdout.
3899 0 : pub async fn dump_layerfile_from_path(
3900 0 : path: &Utf8Path,
3901 0 : verbose: bool,
3902 0 : ctx: &RequestContext,
3903 0 : ) -> anyhow::Result<()> {
3904 : use std::os::unix::fs::FileExt;
3905 :
3906 : // All layer files start with a two-byte "magic" value, to identify the kind of
3907 : // file.
3908 0 : let file = File::open(path)?;
3909 0 : let mut header_buf = [0u8; 2];
3910 0 : file.read_exact_at(&mut header_buf, 0)?;
3911 :
3912 0 : match u16::from_be_bytes(header_buf) {
3913 : crate::IMAGE_FILE_MAGIC => {
3914 0 : ImageLayer::new_for_path(path, file)?
3915 0 : .dump(verbose, ctx)
3916 0 : .await?
3917 : }
3918 : crate::DELTA_FILE_MAGIC => {
3919 0 : DeltaLayer::new_for_path(path, file)?
3920 0 : .dump(verbose, ctx)
3921 0 : .await?
3922 : }
3923 0 : magic => bail!("unrecognized magic identifier: {:?}", magic),
3924 : }
3925 :
3926 0 : Ok(())
3927 0 : }
3928 :
3929 : #[cfg(test)]
3930 : pub(crate) mod harness {
3931 : use bytes::{Bytes, BytesMut};
3932 : use once_cell::sync::OnceCell;
3933 : use pageserver_api::models::ShardParameters;
3934 : use pageserver_api::shard::ShardIndex;
3935 : use utils::logging;
3936 :
3937 : use crate::deletion_queue::mock::MockDeletionQueue;
3938 : use crate::l0_flush::L0FlushConfig;
3939 : use crate::walredo::apply_neon;
3940 : use crate::{repository::Key, walrecord::NeonWalRecord};
3941 :
3942 : use super::*;
3943 : use hex_literal::hex;
3944 : use utils::id::TenantId;
3945 :
3946 : pub const TIMELINE_ID: TimelineId =
3947 : TimelineId::from_array(hex!("11223344556677881122334455667788"));
3948 : pub const NEW_TIMELINE_ID: TimelineId =
3949 : TimelineId::from_array(hex!("AA223344556677881122334455667788"));
3950 :
3951 : /// Convenience function to create a page image with given string as the only content
3952 15086172 : pub fn test_img(s: &str) -> Bytes {
3953 15086172 : let mut buf = BytesMut::new();
3954 15086172 : buf.extend_from_slice(s.as_bytes());
3955 15086172 : buf.resize(64, 0);
3956 15086172 :
3957 15086172 : buf.freeze()
3958 15086172 : }
3959 :
3960 : impl From<TenantConf> for TenantConfOpt {
3961 564 : fn from(tenant_conf: TenantConf) -> Self {
3962 564 : Self {
3963 564 : checkpoint_distance: Some(tenant_conf.checkpoint_distance),
3964 564 : checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
3965 564 : compaction_target_size: Some(tenant_conf.compaction_target_size),
3966 564 : compaction_period: Some(tenant_conf.compaction_period),
3967 564 : compaction_threshold: Some(tenant_conf.compaction_threshold),
3968 564 : compaction_algorithm: Some(tenant_conf.compaction_algorithm),
3969 564 : gc_horizon: Some(tenant_conf.gc_horizon),
3970 564 : gc_period: Some(tenant_conf.gc_period),
3971 564 : image_creation_threshold: Some(tenant_conf.image_creation_threshold),
3972 564 : pitr_interval: Some(tenant_conf.pitr_interval),
3973 564 : walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
3974 564 : lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
3975 564 : max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
3976 564 : eviction_policy: Some(tenant_conf.eviction_policy),
3977 564 : min_resident_size_override: tenant_conf.min_resident_size_override,
3978 564 : evictions_low_residence_duration_metric_threshold: Some(
3979 564 : tenant_conf.evictions_low_residence_duration_metric_threshold,
3980 564 : ),
3981 564 : heatmap_period: Some(tenant_conf.heatmap_period),
3982 564 : lazy_slru_download: Some(tenant_conf.lazy_slru_download),
3983 564 : timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
3984 564 : image_layer_creation_check_threshold: Some(
3985 564 : tenant_conf.image_layer_creation_check_threshold,
3986 564 : ),
3987 564 : switch_aux_file_policy: Some(tenant_conf.switch_aux_file_policy),
3988 564 : lsn_lease_length: Some(tenant_conf.lsn_lease_length),
3989 564 : lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
3990 564 : }
3991 564 : }
3992 : }
3993 :
3994 : pub struct TenantHarness {
3995 : pub conf: &'static PageServerConf,
3996 : pub tenant_conf: TenantConf,
3997 : pub tenant_shard_id: TenantShardId,
3998 : pub generation: Generation,
3999 : pub shard: ShardIndex,
4000 : pub remote_storage: GenericRemoteStorage,
4001 : pub remote_fs_dir: Utf8PathBuf,
4002 : pub deletion_queue: MockDeletionQueue,
4003 : }
4004 :
4005 : static LOG_HANDLE: OnceCell<()> = OnceCell::new();
4006 :
4007 606 : pub(crate) fn setup_logging() {
4008 606 : LOG_HANDLE.get_or_init(|| {
4009 570 : logging::init(
4010 570 : logging::LogFormat::Test,
4011 570 : // enable it in case the tests exercise code paths that use
4012 570 : // debug_assert_current_span_has_tenant_and_timeline_id
4013 570 : logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
4014 570 : logging::Output::Stdout,
4015 570 : )
4016 570 : .expect("Failed to init test logging")
4017 606 : });
4018 606 : }
4019 :
4020 : impl TenantHarness {
4021 564 : pub async fn create_custom(
4022 564 : test_name: &'static str,
4023 564 : tenant_conf: TenantConf,
4024 564 : tenant_id: TenantId,
4025 564 : shard_identity: ShardIdentity,
4026 564 : generation: Generation,
4027 564 : ) -> anyhow::Result<Self> {
4028 564 : setup_logging();
4029 564 :
4030 564 : let repo_dir = PageServerConf::test_repo_dir(test_name);
4031 564 : let _ = fs::remove_dir_all(&repo_dir);
4032 564 : fs::create_dir_all(&repo_dir)?;
4033 :
4034 564 : let conf = PageServerConf::dummy_conf(repo_dir);
4035 564 : // Make a static copy of the config. This can never be free'd, but that's
4036 564 : // OK in a test.
4037 564 : let conf: &'static PageServerConf = Box::leak(Box::new(conf));
4038 564 :
4039 564 : let shard = shard_identity.shard_index();
4040 564 : let tenant_shard_id = TenantShardId {
4041 564 : tenant_id,
4042 564 : shard_number: shard.shard_number,
4043 564 : shard_count: shard.shard_count,
4044 564 : };
4045 564 : fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
4046 564 : fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
4047 :
4048 : use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
4049 564 : let remote_fs_dir = conf.workdir.join("localfs");
4050 564 : std::fs::create_dir_all(&remote_fs_dir).unwrap();
4051 564 : let config = RemoteStorageConfig {
4052 564 : storage: RemoteStorageKind::LocalFs {
4053 564 : local_path: remote_fs_dir.clone(),
4054 564 : },
4055 564 : timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
4056 564 : };
4057 564 : let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
4058 564 : let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
4059 564 :
4060 564 : Ok(Self {
4061 564 : conf,
4062 564 : tenant_conf,
4063 564 : tenant_shard_id,
4064 564 : generation,
4065 564 : shard,
4066 564 : remote_storage,
4067 564 : remote_fs_dir,
4068 564 : deletion_queue,
4069 564 : })
4070 564 : }
4071 :
4072 528 : pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
4073 528 : // Disable automatic GC and compaction to make the unit tests more deterministic.
4074 528 : // The tests perform them manually if needed.
4075 528 : let tenant_conf = TenantConf {
4076 528 : gc_period: Duration::ZERO,
4077 528 : compaction_period: Duration::ZERO,
4078 528 : ..TenantConf::default()
4079 528 : };
4080 528 : let tenant_id = TenantId::generate();
4081 528 : let shard = ShardIdentity::unsharded();
4082 528 : Self::create_custom(
4083 528 : test_name,
4084 528 : tenant_conf,
4085 528 : tenant_id,
4086 528 : shard,
4087 528 : Generation::new(0xdeadbeef),
4088 528 : )
4089 0 : .await
4090 528 : }
4091 :
4092 60 : pub fn span(&self) -> tracing::Span {
4093 60 : info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
4094 60 : }
4095 :
4096 564 : pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
4097 564 : let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
4098 564 : (
4099 564 : self.do_try_load(&ctx)
4100 2263 : .await
4101 564 : .expect("failed to load test tenant"),
4102 564 : ctx,
4103 564 : )
4104 564 : }
4105 :
4106 564 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
4107 : pub(crate) async fn do_try_load(
4108 : &self,
4109 : ctx: &RequestContext,
4110 : ) -> anyhow::Result<Arc<Tenant>> {
4111 : let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
4112 :
4113 : let tenant = Arc::new(Tenant::new(
4114 : TenantState::Loading,
4115 : self.conf,
4116 : AttachedTenantConf::try_from(LocationConf::attached_single(
4117 : TenantConfOpt::from(self.tenant_conf.clone()),
4118 : self.generation,
4119 : &ShardParameters::default(),
4120 : ))
4121 : .unwrap(),
4122 : // This is a legacy/test code path: sharding isn't supported here.
4123 : ShardIdentity::unsharded(),
4124 : Some(walredo_mgr),
4125 : self.tenant_shard_id,
4126 : self.remote_storage.clone(),
4127 : self.deletion_queue.new_client(),
4128 : // TODO: ideally we should run all unit tests with both configs
4129 : L0FlushGlobalState::new(L0FlushConfig::default()),
4130 : ));
4131 :
4132 : let preload = tenant
4133 : .preload(&self.remote_storage, CancellationToken::new())
4134 : .await?;
4135 : tenant.attach(Some(preload), ctx).await?;
4136 :
4137 : tenant.state.send_replace(TenantState::Active);
4138 : for timeline in tenant.timelines.lock().unwrap().values() {
4139 : timeline.set_state(TimelineState::Active);
4140 : }
4141 : Ok(tenant)
4142 : }
4143 :
4144 6 : pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
4145 6 : self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
4146 6 : }
4147 : }
4148 :
4149 : // Mock WAL redo manager that doesn't do much
4150 : pub(crate) struct TestRedoManager;
4151 :
4152 : impl TestRedoManager {
4153 : /// # Cancel-Safety
4154 : ///
4155 : /// This method is cancellation-safe.
4156 978 : pub async fn request_redo(
4157 978 : &self,
4158 978 : key: Key,
4159 978 : lsn: Lsn,
4160 978 : base_img: Option<(Lsn, Bytes)>,
4161 978 : records: Vec<(Lsn, NeonWalRecord)>,
4162 978 : _pg_version: u32,
4163 978 : ) -> Result<Bytes, walredo::Error> {
4164 1326 : let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
4165 978 : if records_neon {
4166 : // For Neon wal records, we can decode without spawning postgres, so do so.
4167 978 : let base_img = base_img.expect("Neon WAL redo requires base image").1;
4168 978 : let mut page = BytesMut::new();
4169 978 : page.extend_from_slice(&base_img);
4170 2304 : for (record_lsn, record) in records {
4171 1326 : apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
4172 : }
4173 978 : Ok(page.freeze())
4174 : } else {
4175 : // We never spawn a postgres walredo process in unit tests: just log what we might have done.
4176 0 : let s = format!(
4177 0 : "redo for {} to get to {}, with {} and {} records",
4178 0 : key,
4179 0 : lsn,
4180 0 : if base_img.is_some() {
4181 0 : "base image"
4182 : } else {
4183 0 : "no base image"
4184 : },
4185 0 : records.len()
4186 0 : );
4187 0 : println!("{s}");
4188 0 :
4189 0 : Ok(test_img(&s))
4190 : }
4191 978 : }
4192 : }
4193 : }
4194 :
4195 : #[cfg(test)]
4196 : mod tests {
4197 : use std::collections::{BTreeMap, BTreeSet};
4198 :
4199 : use super::*;
4200 : use crate::keyspace::KeySpaceAccum;
4201 : use crate::pgdatadir_mapping::AuxFilesDirectory;
4202 : use crate::repository::{Key, Value};
4203 : use crate::tenant::harness::*;
4204 : use crate::tenant::timeline::CompactFlags;
4205 : use crate::walrecord::NeonWalRecord;
4206 : use crate::DEFAULT_PG_VERSION;
4207 : use bytes::{Bytes, BytesMut};
4208 : use hex_literal::hex;
4209 : use itertools::Itertools;
4210 : use pageserver_api::key::{AUX_FILES_KEY, AUX_KEY_PREFIX, NON_INHERITED_RANGE};
4211 : use pageserver_api::keyspace::KeySpace;
4212 : use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
4213 : use rand::{thread_rng, Rng};
4214 : use storage_layer::PersistentLayerKey;
4215 : use tests::storage_layer::ValuesReconstructState;
4216 : use tests::timeline::{GetVectoredError, ShutdownMode};
4217 : use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
4218 : use timeline::{DeltaLayerTestDesc, GcInfo};
4219 : use utils::bin_ser::BeSer;
4220 : use utils::id::TenantId;
4221 :
4222 : static TEST_KEY: Lazy<Key> =
4223 54 : Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
4224 :
4225 : #[tokio::test]
4226 6 : async fn test_basic() -> anyhow::Result<()> {
4227 24 : let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
4228 6 : let tline = tenant
4229 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
4230 12 : .await?;
4231 6 :
4232 6 : let mut writer = tline.writer().await;
4233 6 : writer
4234 6 : .put(
4235 6 : *TEST_KEY,
4236 6 : Lsn(0x10),
4237 6 : &Value::Image(test_img("foo at 0x10")),
4238 6 : &ctx,
4239 6 : )
4240 6 : .await?;
4241 6 : writer.finish_write(Lsn(0x10));
4242 6 : drop(writer);
4243 6 :
4244 6 : let mut writer = tline.writer().await;
4245 6 : writer
4246 6 : .put(
4247 6 : *TEST_KEY,
4248 6 : Lsn(0x20),
4249 6 : &Value::Image(test_img("foo at 0x20")),
4250 6 : &ctx,
4251 6 : )
4252 6 : .await?;
4253 6 : writer.finish_write(Lsn(0x20));
4254 6 : drop(writer);
4255 6 :
4256 6 : assert_eq!(
4257 6 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
4258 6 : test_img("foo at 0x10")
4259 6 : );
4260 6 : assert_eq!(
4261 6 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
4262 6 : test_img("foo at 0x10")
4263 6 : );
4264 6 : assert_eq!(
4265 6 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
4266 6 : test_img("foo at 0x20")
4267 6 : );
4268 6 :
4269 6 : Ok(())
4270 6 : }
4271 :
4272 : #[tokio::test]
4273 6 : async fn no_duplicate_timelines() -> anyhow::Result<()> {
4274 6 : let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
4275 6 : .await?
4276 6 : .load()
4277 24 : .await;
4278 6 : let _ = tenant
4279 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4280 12 : .await?;
4281 6 :
4282 6 : match tenant
4283 6 : .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4284 6 : .await
4285 6 : {
4286 6 : Ok(_) => panic!("duplicate timeline creation should fail"),
4287 6 : Err(e) => assert_eq!(e.to_string(), "Already exists".to_string()),
4288 6 : }
4289 6 :
4290 6 : Ok(())
4291 6 : }
4292 :
4293 : /// Convenience function to create a page image with given string as the only content
4294 30 : pub fn test_value(s: &str) -> Value {
4295 30 : let mut buf = BytesMut::new();
4296 30 : buf.extend_from_slice(s.as_bytes());
4297 30 : Value::Image(buf.freeze())
4298 30 : }
4299 :
4300 : ///
4301 : /// Test branch creation
4302 : ///
4303 : #[tokio::test]
4304 6 : async fn test_branch() -> anyhow::Result<()> {
4305 6 : use std::str::from_utf8;
4306 6 :
4307 24 : let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
4308 6 : let tline = tenant
4309 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4310 12 : .await?;
4311 6 : let mut writer = tline.writer().await;
4312 6 :
4313 6 : #[allow(non_snake_case)]
4314 6 : let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
4315 6 : #[allow(non_snake_case)]
4316 6 : let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
4317 6 :
4318 6 : // Insert a value on the timeline
4319 6 : writer
4320 6 : .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
4321 6 : .await?;
4322 6 : writer
4323 6 : .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
4324 6 : .await?;
4325 6 : writer.finish_write(Lsn(0x20));
4326 6 :
4327 6 : writer
4328 6 : .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
4329 6 : .await?;
4330 6 : writer.finish_write(Lsn(0x30));
4331 6 : writer
4332 6 : .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
4333 6 : .await?;
4334 6 : writer.finish_write(Lsn(0x40));
4335 6 :
4336 6 : //assert_current_logical_size(&tline, Lsn(0x40));
4337 6 :
4338 6 : // Branch the history, modify relation differently on the new timeline
4339 6 : tenant
4340 6 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
4341 6 : .await?;
4342 6 : let newtline = tenant
4343 6 : .get_timeline(NEW_TIMELINE_ID, true)
4344 6 : .expect("Should have a local timeline");
4345 6 : let mut new_writer = newtline.writer().await;
4346 6 : new_writer
4347 6 : .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
4348 6 : .await?;
4349 6 : new_writer.finish_write(Lsn(0x40));
4350 6 :
4351 6 : // Check page contents on both branches
4352 6 : assert_eq!(
4353 6 : from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
4354 6 : "foo at 0x40"
4355 6 : );
4356 6 : assert_eq!(
4357 6 : from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
4358 6 : "bar at 0x40"
4359 6 : );
4360 6 : assert_eq!(
4361 6 : from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
4362 6 : "foobar at 0x20"
4363 6 : );
4364 6 :
4365 6 : //assert_current_logical_size(&tline, Lsn(0x40));
4366 6 :
4367 6 : Ok(())
4368 6 : }
4369 :
4370 60 : async fn make_some_layers(
4371 60 : tline: &Timeline,
4372 60 : start_lsn: Lsn,
4373 60 : ctx: &RequestContext,
4374 60 : ) -> anyhow::Result<()> {
4375 60 : let mut lsn = start_lsn;
4376 : {
4377 60 : let mut writer = tline.writer().await;
4378 : // Create a relation on the timeline
4379 60 : writer
4380 60 : .put(
4381 60 : *TEST_KEY,
4382 60 : lsn,
4383 60 : &Value::Image(test_img(&format!("foo at {}", lsn))),
4384 60 : ctx,
4385 60 : )
4386 30 : .await?;
4387 60 : writer.finish_write(lsn);
4388 60 : lsn += 0x10;
4389 60 : writer
4390 60 : .put(
4391 60 : *TEST_KEY,
4392 60 : lsn,
4393 60 : &Value::Image(test_img(&format!("foo at {}", lsn))),
4394 60 : ctx,
4395 60 : )
4396 0 : .await?;
4397 60 : writer.finish_write(lsn);
4398 60 : lsn += 0x10;
4399 60 : }
4400 60 : tline.freeze_and_flush().await?;
4401 : {
4402 60 : let mut writer = tline.writer().await;
4403 60 : writer
4404 60 : .put(
4405 60 : *TEST_KEY,
4406 60 : lsn,
4407 60 : &Value::Image(test_img(&format!("foo at {}", lsn))),
4408 60 : ctx,
4409 60 : )
4410 30 : .await?;
4411 60 : writer.finish_write(lsn);
4412 60 : lsn += 0x10;
4413 60 : writer
4414 60 : .put(
4415 60 : *TEST_KEY,
4416 60 : lsn,
4417 60 : &Value::Image(test_img(&format!("foo at {}", lsn))),
4418 60 : ctx,
4419 60 : )
4420 0 : .await?;
4421 60 : writer.finish_write(lsn);
4422 60 : }
4423 61 : tline.freeze_and_flush().await.map_err(|e| e.into())
4424 60 : }
4425 :
4426 : #[tokio::test]
4427 6 : async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
4428 6 : let (tenant, ctx) =
4429 6 : TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
4430 6 : .await?
4431 6 : .load()
4432 24 : .await;
4433 6 : let tline = tenant
4434 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4435 12 : .await?;
4436 18 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
4437 6 :
4438 6 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
4439 6 : // FIXME: this doesn't actually remove any layer currently, given how the flushing
4440 6 : // and compaction works. But it does set the 'cutoff' point so that the cross check
4441 6 : // below should fail.
4442 6 : tenant
4443 6 : .gc_iteration(
4444 6 : Some(TIMELINE_ID),
4445 6 : 0x10,
4446 6 : Duration::ZERO,
4447 6 : &CancellationToken::new(),
4448 6 : &ctx,
4449 6 : )
4450 6 : .await?;
4451 6 :
4452 6 : // try to branch at lsn 25, should fail because we already garbage collected the data
4453 6 : match tenant
4454 6 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
4455 6 : .await
4456 6 : {
4457 6 : Ok(_) => panic!("branching should have failed"),
4458 6 : Err(err) => {
4459 6 : let CreateTimelineError::AncestorLsn(err) = err else {
4460 6 : panic!("wrong error type")
4461 6 : };
4462 6 : assert!(err.to_string().contains("invalid branch start lsn"));
4463 6 : assert!(err
4464 6 : .source()
4465 6 : .unwrap()
4466 6 : .to_string()
4467 6 : .contains("we might've already garbage collected needed data"))
4468 6 : }
4469 6 : }
4470 6 :
4471 6 : Ok(())
4472 6 : }
4473 :
4474 : #[tokio::test]
4475 6 : async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
4476 6 : let (tenant, ctx) =
4477 6 : TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
4478 6 : .await?
4479 6 : .load()
4480 24 : .await;
4481 6 :
4482 6 : let tline = tenant
4483 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
4484 12 : .await?;
4485 6 : // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
4486 6 : match tenant
4487 6 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
4488 6 : .await
4489 6 : {
4490 6 : Ok(_) => panic!("branching should have failed"),
4491 6 : Err(err) => {
4492 6 : let CreateTimelineError::AncestorLsn(err) = err else {
4493 6 : panic!("wrong error type");
4494 6 : };
4495 6 : assert!(&err.to_string().contains("invalid branch start lsn"));
4496 6 : assert!(&err
4497 6 : .source()
4498 6 : .unwrap()
4499 6 : .to_string()
4500 6 : .contains("is earlier than latest GC cutoff"));
4501 6 : }
4502 6 : }
4503 6 :
4504 6 : Ok(())
4505 6 : }
4506 :
4507 : /*
4508 : // FIXME: This currently fails to error out. Calling GC doesn't currently
4509 : // remove the old value, we'd need to work a little harder
4510 : #[tokio::test]
4511 : async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
4512 : let repo =
4513 : RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
4514 : .load();
4515 :
4516 : let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
4517 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
4518 :
4519 : repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
4520 : let latest_gc_cutoff_lsn = tline.get_latest_gc_cutoff_lsn();
4521 : assert!(*latest_gc_cutoff_lsn > Lsn(0x25));
4522 : match tline.get(*TEST_KEY, Lsn(0x25)) {
4523 : Ok(_) => panic!("request for page should have failed"),
4524 : Err(err) => assert!(err.to_string().contains("not found at")),
4525 : }
4526 : Ok(())
4527 : }
4528 : */
4529 :
4530 : #[tokio::test]
4531 6 : async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
4532 6 : let (tenant, ctx) =
4533 6 : TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
4534 6 : .await?
4535 6 : .load()
4536 24 : .await;
4537 6 : let tline = tenant
4538 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4539 12 : .await?;
4540 18 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
4541 6 :
4542 6 : tenant
4543 6 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
4544 6 : .await?;
4545 6 : let newtline = tenant
4546 6 : .get_timeline(NEW_TIMELINE_ID, true)
4547 6 : .expect("Should have a local timeline");
4548 6 :
4549 18 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
4550 6 :
4551 6 : tline.set_broken("test".to_owned());
4552 6 :
4553 6 : tenant
4554 6 : .gc_iteration(
4555 6 : Some(TIMELINE_ID),
4556 6 : 0x10,
4557 6 : Duration::ZERO,
4558 6 : &CancellationToken::new(),
4559 6 : &ctx,
4560 6 : )
4561 6 : .await?;
4562 6 :
4563 6 : // The branchpoints should contain all timelines, even ones marked
4564 6 : // as Broken.
4565 6 : {
4566 6 : let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
4567 6 : assert_eq!(branchpoints.len(), 1);
4568 6 : assert_eq!(branchpoints[0], (Lsn(0x40), NEW_TIMELINE_ID));
4569 6 : }
4570 6 :
4571 6 : // You can read the key from the child branch even though the parent is
4572 6 : // Broken, as long as you don't need to access data from the parent.
4573 6 : assert_eq!(
4574 12 : newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
4575 6 : test_img(&format!("foo at {}", Lsn(0x70)))
4576 6 : );
4577 6 :
4578 6 : // This needs to traverse to the parent, and fails.
4579 6 : let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
4580 6 : assert!(
4581 6 : err.to_string().starts_with(&format!(
4582 6 : "bad state on timeline {}: Broken",
4583 6 : tline.timeline_id
4584 6 : )),
4585 6 : "{err}"
4586 6 : );
4587 6 :
4588 6 : Ok(())
4589 6 : }
4590 :
4591 : #[tokio::test]
4592 6 : async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
4593 6 : let (tenant, ctx) =
4594 6 : TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
4595 6 : .await?
4596 6 : .load()
4597 24 : .await;
4598 6 : let tline = tenant
4599 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4600 12 : .await?;
4601 18 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
4602 6 :
4603 6 : tenant
4604 6 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
4605 6 : .await?;
4606 6 : let newtline = tenant
4607 6 : .get_timeline(NEW_TIMELINE_ID, true)
4608 6 : .expect("Should have a local timeline");
4609 6 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
4610 6 : tenant
4611 6 : .gc_iteration(
4612 6 : Some(TIMELINE_ID),
4613 6 : 0x10,
4614 6 : Duration::ZERO,
4615 6 : &CancellationToken::new(),
4616 6 : &ctx,
4617 6 : )
4618 6 : .await?;
4619 12 : assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
4620 6 :
4621 6 : Ok(())
4622 6 : }
4623 : #[tokio::test]
4624 6 : async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
4625 6 : let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
4626 6 : .await?
4627 6 : .load()
4628 24 : .await;
4629 6 : let tline = tenant
4630 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4631 12 : .await?;
4632 18 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
4633 6 :
4634 6 : tenant
4635 6 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
4636 6 : .await?;
4637 6 : let newtline = tenant
4638 6 : .get_timeline(NEW_TIMELINE_ID, true)
4639 6 : .expect("Should have a local timeline");
4640 6 :
4641 18 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
4642 6 :
4643 6 : // run gc on parent
4644 6 : tenant
4645 6 : .gc_iteration(
4646 6 : Some(TIMELINE_ID),
4647 6 : 0x10,
4648 6 : Duration::ZERO,
4649 6 : &CancellationToken::new(),
4650 6 : &ctx,
4651 6 : )
4652 6 : .await?;
4653 6 :
4654 6 : // Check that the data is still accessible on the branch.
4655 6 : assert_eq!(
4656 21 : newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
4657 6 : test_img(&format!("foo at {}", Lsn(0x40)))
4658 6 : );
4659 6 :
4660 6 : Ok(())
4661 6 : }
4662 :
4663 : #[tokio::test]
4664 6 : async fn timeline_load() -> anyhow::Result<()> {
4665 6 : const TEST_NAME: &str = "timeline_load";
4666 6 : let harness = TenantHarness::create(TEST_NAME).await?;
4667 6 : {
4668 24 : let (tenant, ctx) = harness.load().await;
4669 6 : let tline = tenant
4670 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
4671 12 : .await?;
4672 18 : make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
4673 6 : // so that all uploads finish & we can call harness.load() below again
4674 6 : tenant
4675 6 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
4676 6 : .instrument(harness.span())
4677 6 : .await
4678 6 : .ok()
4679 6 : .unwrap();
4680 6 : }
4681 6 :
4682 22 : let (tenant, _ctx) = harness.load().await;
4683 6 : tenant
4684 6 : .get_timeline(TIMELINE_ID, true)
4685 6 : .expect("cannot load timeline");
4686 6 :
4687 6 : Ok(())
4688 6 : }
4689 :
4690 : #[tokio::test]
4691 6 : async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
4692 6 : const TEST_NAME: &str = "timeline_load_with_ancestor";
4693 6 : let harness = TenantHarness::create(TEST_NAME).await?;
4694 6 : // create two timelines
4695 6 : {
4696 24 : let (tenant, ctx) = harness.load().await;
4697 6 : let tline = tenant
4698 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4699 12 : .await?;
4700 6 :
4701 18 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
4702 6 :
4703 6 : let child_tline = tenant
4704 6 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
4705 6 : .await?;
4706 6 : child_tline.set_state(TimelineState::Active);
4707 6 :
4708 6 : let newtline = tenant
4709 6 : .get_timeline(NEW_TIMELINE_ID, true)
4710 6 : .expect("Should have a local timeline");
4711 6 :
4712 18 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
4713 6 :
4714 6 : // so that all uploads finish & we can call harness.load() below again
4715 6 : tenant
4716 6 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
4717 6 : .instrument(harness.span())
4718 6 : .await
4719 6 : .ok()
4720 6 : .unwrap();
4721 6 : }
4722 6 :
4723 6 : // check that both of them are initially unloaded
4724 36 : let (tenant, _ctx) = harness.load().await;
4725 6 :
4726 6 : // check that both, child and ancestor are loaded
4727 6 : let _child_tline = tenant
4728 6 : .get_timeline(NEW_TIMELINE_ID, true)
4729 6 : .expect("cannot get child timeline loaded");
4730 6 :
4731 6 : let _ancestor_tline = tenant
4732 6 : .get_timeline(TIMELINE_ID, true)
4733 6 : .expect("cannot get ancestor timeline loaded");
4734 6 :
4735 6 : Ok(())
4736 6 : }
4737 :
4738 : #[tokio::test]
4739 6 : async fn delta_layer_dumping() -> anyhow::Result<()> {
4740 6 : use storage_layer::AsLayerDesc;
4741 6 : let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
4742 6 : .await?
4743 6 : .load()
4744 24 : .await;
4745 6 : let tline = tenant
4746 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
4747 12 : .await?;
4748 19 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
4749 6 :
4750 6 : let layer_map = tline.layers.read().await;
4751 6 : let level0_deltas = layer_map
4752 6 : .layer_map()?
4753 6 : .level0_deltas()
4754 6 : .iter()
4755 12 : .map(|desc| layer_map.get_from_desc(desc))
4756 6 : .collect::<Vec<_>>();
4757 6 :
4758 6 : assert!(!level0_deltas.is_empty());
4759 6 :
4760 18 : for delta in level0_deltas {
4761 6 : // Ensure we are dumping a delta layer here
4762 12 : assert!(delta.layer_desc().is_delta);
4763 24 : delta.dump(true, &ctx).await.unwrap();
4764 6 : }
4765 6 :
4766 6 : Ok(())
4767 6 : }
4768 :
4769 : #[tokio::test]
4770 6 : async fn test_images() -> anyhow::Result<()> {
4771 24 : let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
4772 6 : let tline = tenant
4773 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
4774 12 : .await?;
4775 6 :
4776 6 : let mut writer = tline.writer().await;
4777 6 : writer
4778 6 : .put(
4779 6 : *TEST_KEY,
4780 6 : Lsn(0x10),
4781 6 : &Value::Image(test_img("foo at 0x10")),
4782 6 : &ctx,
4783 6 : )
4784 6 : .await?;
4785 6 : writer.finish_write(Lsn(0x10));
4786 6 : drop(writer);
4787 6 :
4788 6 : tline.freeze_and_flush().await?;
4789 6 : tline
4790 6 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
4791 6 : .await?;
4792 6 :
4793 6 : let mut writer = tline.writer().await;
4794 6 : writer
4795 6 : .put(
4796 6 : *TEST_KEY,
4797 6 : Lsn(0x20),
4798 6 : &Value::Image(test_img("foo at 0x20")),
4799 6 : &ctx,
4800 6 : )
4801 6 : .await?;
4802 6 : writer.finish_write(Lsn(0x20));
4803 6 : drop(writer);
4804 6 :
4805 6 : tline.freeze_and_flush().await?;
4806 6 : tline
4807 6 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
4808 6 : .await?;
4809 6 :
4810 6 : let mut writer = tline.writer().await;
4811 6 : writer
4812 6 : .put(
4813 6 : *TEST_KEY,
4814 6 : Lsn(0x30),
4815 6 : &Value::Image(test_img("foo at 0x30")),
4816 6 : &ctx,
4817 6 : )
4818 6 : .await?;
4819 6 : writer.finish_write(Lsn(0x30));
4820 6 : drop(writer);
4821 6 :
4822 6 : tline.freeze_and_flush().await?;
4823 6 : tline
4824 6 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
4825 6 : .await?;
4826 6 :
4827 6 : let mut writer = tline.writer().await;
4828 6 : writer
4829 6 : .put(
4830 6 : *TEST_KEY,
4831 6 : Lsn(0x40),
4832 6 : &Value::Image(test_img("foo at 0x40")),
4833 6 : &ctx,
4834 6 : )
4835 6 : .await?;
4836 6 : writer.finish_write(Lsn(0x40));
4837 6 : drop(writer);
4838 6 :
4839 6 : tline.freeze_and_flush().await?;
4840 6 : tline
4841 6 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
4842 6 : .await?;
4843 6 :
4844 6 : assert_eq!(
4845 12 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
4846 6 : test_img("foo at 0x10")
4847 6 : );
4848 6 : assert_eq!(
4849 12 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
4850 6 : test_img("foo at 0x10")
4851 6 : );
4852 6 : assert_eq!(
4853 6 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
4854 6 : test_img("foo at 0x20")
4855 6 : );
4856 6 : assert_eq!(
4857 12 : tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
4858 6 : test_img("foo at 0x30")
4859 6 : );
4860 6 : assert_eq!(
4861 12 : tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
4862 6 : test_img("foo at 0x40")
4863 6 : );
4864 6 :
4865 6 : Ok(())
4866 6 : }
4867 :
4868 12 : async fn bulk_insert_compact_gc(
4869 12 : tenant: &Tenant,
4870 12 : timeline: &Arc<Timeline>,
4871 12 : ctx: &RequestContext,
4872 12 : lsn: Lsn,
4873 12 : repeat: usize,
4874 12 : key_count: usize,
4875 12 : ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
4876 12 : let compact = true;
4877 122751 : bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
4878 12 : }
4879 :
4880 24 : async fn bulk_insert_maybe_compact_gc(
4881 24 : tenant: &Tenant,
4882 24 : timeline: &Arc<Timeline>,
4883 24 : ctx: &RequestContext,
4884 24 : mut lsn: Lsn,
4885 24 : repeat: usize,
4886 24 : key_count: usize,
4887 24 : compact: bool,
4888 24 : ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
4889 24 : let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
4890 24 :
4891 24 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
4892 24 : let mut blknum = 0;
4893 24 :
4894 24 : // Enforce that key range is monotonously increasing
4895 24 : let mut keyspace = KeySpaceAccum::new();
4896 24 :
4897 24 : let cancel = CancellationToken::new();
4898 24 :
4899 24 : for _ in 0..repeat {
4900 1200 : for _ in 0..key_count {
4901 12000000 : test_key.field6 = blknum;
4902 12000000 : let mut writer = timeline.writer().await;
4903 12000000 : writer
4904 12000000 : .put(
4905 12000000 : test_key,
4906 12000000 : lsn,
4907 12000000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
4908 12000000 : ctx,
4909 12000000 : )
4910 7943 : .await?;
4911 12000000 : inserted.entry(test_key).or_default().insert(lsn);
4912 12000000 : writer.finish_write(lsn);
4913 12000000 : drop(writer);
4914 12000000 :
4915 12000000 : keyspace.add_key(test_key);
4916 12000000 :
4917 12000000 : lsn = Lsn(lsn.0 + 0x10);
4918 12000000 : blknum += 1;
4919 : }
4920 :
4921 1200 : timeline.freeze_and_flush().await?;
4922 1200 : if compact {
4923 : // this requires timeline to be &Arc<Timeline>
4924 25854 : timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
4925 600 : }
4926 :
4927 : // this doesn't really need to use the timeline_id target, but it is closer to what it
4928 : // originally was.
4929 1200 : let res = tenant
4930 1200 : .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
4931 1196 : .await?;
4932 :
4933 1200 : assert_eq!(res.layers_removed, 0, "this never removes anything");
4934 : }
4935 :
4936 24 : Ok(inserted)
4937 24 : }
4938 :
4939 : //
4940 : // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
4941 : // Repeat 50 times.
4942 : //
4943 : #[tokio::test]
4944 6 : async fn test_bulk_insert() -> anyhow::Result<()> {
4945 6 : let harness = TenantHarness::create("test_bulk_insert").await?;
4946 24 : let (tenant, ctx) = harness.load().await;
4947 6 : let tline = tenant
4948 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
4949 12 : .await?;
4950 6 :
4951 6 : let lsn = Lsn(0x10);
4952 61376 : bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
4953 6 :
4954 6 : Ok(())
4955 6 : }
4956 :
4957 : // Test the vectored get real implementation against a simple sequential implementation.
4958 : //
4959 : // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
4960 : // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
4961 : // grow to the right on the X axis.
4962 : // [Delta]
4963 : // [Delta]
4964 : // [Delta]
4965 : // [Delta]
4966 : // ------------ Image ---------------
4967 : //
4968 : // After layer generation we pick the ranges to query as follows:
4969 : // 1. The beginning of each delta layer
4970 : // 2. At the seam between two adjacent delta layers
4971 : //
4972 : // There's one major downside to this test: delta layers only contains images,
4973 : // so the search can stop at the first delta layer and doesn't traverse any deeper.
4974 : #[tokio::test]
4975 6 : async fn test_get_vectored() -> anyhow::Result<()> {
4976 6 : let harness = TenantHarness::create("test_get_vectored").await?;
4977 24 : let (tenant, ctx) = harness.load().await;
4978 6 : let tline = tenant
4979 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
4980 12 : .await?;
4981 6 :
4982 6 : let lsn = Lsn(0x10);
4983 61375 : let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
4984 6 :
4985 6 : let guard = tline.layers.read().await;
4986 6 : let lm = guard.layer_map()?;
4987 6 :
4988 6 : lm.dump(true, &ctx).await?;
4989 6 :
4990 6 : let mut reads = Vec::new();
4991 6 : let mut prev = None;
4992 36 : lm.iter_historic_layers().for_each(|desc| {
4993 36 : if !desc.is_delta() {
4994 6 : prev = Some(desc.clone());
4995 6 : return;
4996 30 : }
4997 30 :
4998 30 : let start = desc.key_range.start;
4999 30 : let end = desc
5000 30 : .key_range
5001 30 : .start
5002 30 : .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
5003 30 : reads.push(KeySpace {
5004 30 : ranges: vec![start..end],
5005 30 : });
5006 6 :
5007 30 : if let Some(prev) = &prev {
5008 30 : if !prev.is_delta() {
5009 30 : return;
5010 6 : }
5011 0 :
5012 0 : let first_range = Key {
5013 0 : field6: prev.key_range.end.field6 - 4,
5014 0 : ..prev.key_range.end
5015 0 : }..prev.key_range.end;
5016 0 :
5017 0 : let second_range = desc.key_range.start..Key {
5018 0 : field6: desc.key_range.start.field6 + 4,
5019 0 : ..desc.key_range.start
5020 0 : };
5021 0 :
5022 0 : reads.push(KeySpace {
5023 0 : ranges: vec![first_range, second_range],
5024 0 : });
5025 6 : };
5026 6 :
5027 6 : prev = Some(desc.clone());
5028 36 : });
5029 6 :
5030 6 : drop(guard);
5031 6 :
5032 6 : // Pick a big LSN such that we query over all the changes.
5033 6 : let reads_lsn = Lsn(u64::MAX - 1);
5034 6 :
5035 36 : for read in reads {
5036 30 : info!("Doing vectored read on {:?}", read);
5037 6 :
5038 30 : let vectored_res = tline
5039 30 : .get_vectored_impl(
5040 30 : read.clone(),
5041 30 : reads_lsn,
5042 30 : &mut ValuesReconstructState::new(),
5043 30 : &ctx,
5044 30 : )
5045 75 : .await;
5046 6 :
5047 30 : let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
5048 30 : let mut expect_missing = false;
5049 30 : let mut key = read.start().unwrap();
5050 990 : while key != read.end().unwrap() {
5051 960 : if let Some(lsns) = inserted.get(&key) {
5052 960 : let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
5053 960 : match expected_lsn {
5054 960 : Some(lsn) => {
5055 960 : expected_lsns.insert(key, *lsn);
5056 960 : }
5057 6 : None => {
5058 6 : expect_missing = true;
5059 0 : break;
5060 6 : }
5061 6 : }
5062 6 : } else {
5063 6 : expect_missing = true;
5064 0 : break;
5065 6 : }
5066 6 :
5067 960 : key = key.next();
5068 6 : }
5069 6 :
5070 30 : if expect_missing {
5071 6 : assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
5072 6 : } else {
5073 960 : for (key, image) in vectored_res? {
5074 960 : let expected_lsn = expected_lsns.get(&key).expect("determined above");
5075 960 : let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
5076 960 : assert_eq!(image?, expected_image);
5077 6 : }
5078 6 : }
5079 6 : }
5080 6 :
5081 6 : Ok(())
5082 6 : }
5083 :
5084 : #[tokio::test]
5085 6 : async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
5086 6 : let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
5087 6 :
5088 24 : let (tenant, ctx) = harness.load().await;
5089 6 : let tline = tenant
5090 6 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
5091 6 : .await?;
5092 6 : let tline = tline.raw_timeline().unwrap();
5093 6 :
5094 6 : let mut modification = tline.begin_modification(Lsn(0x1000));
5095 6 : modification.put_file("foo/bar1", b"content1", &ctx).await?;
5096 6 : modification.set_lsn(Lsn(0x1008))?;
5097 6 : modification.put_file("foo/bar2", b"content2", &ctx).await?;
5098 6 : modification.commit(&ctx).await?;
5099 6 :
5100 6 : let child_timeline_id = TimelineId::generate();
5101 6 : tenant
5102 6 : .branch_timeline_test(
5103 6 : tline,
5104 6 : child_timeline_id,
5105 6 : Some(tline.get_last_record_lsn()),
5106 6 : &ctx,
5107 6 : )
5108 6 : .await?;
5109 6 :
5110 6 : let child_timeline = tenant
5111 6 : .get_timeline(child_timeline_id, true)
5112 6 : .expect("Should have the branched timeline");
5113 6 :
5114 6 : let aux_keyspace = KeySpace {
5115 6 : ranges: vec![NON_INHERITED_RANGE],
5116 6 : };
5117 6 : let read_lsn = child_timeline.get_last_record_lsn();
5118 6 :
5119 6 : let vectored_res = child_timeline
5120 6 : .get_vectored_impl(
5121 6 : aux_keyspace.clone(),
5122 6 : read_lsn,
5123 6 : &mut ValuesReconstructState::new(),
5124 6 : &ctx,
5125 6 : )
5126 6 : .await;
5127 6 :
5128 6 : let images = vectored_res?;
5129 6 : assert!(images.is_empty());
5130 6 : Ok(())
5131 6 : }
5132 :
5133 : // Test that vectored get handles layer gaps correctly
5134 : // by advancing into the next ancestor timeline if required.
5135 : //
5136 : // The test generates timelines that look like the diagram below.
5137 : // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
5138 : // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
5139 : //
5140 : // ```
5141 : //-------------------------------+
5142 : // ... |
5143 : // [ L1 ] |
5144 : // [ / L1 ] | Child Timeline
5145 : // ... |
5146 : // ------------------------------+
5147 : // [ X L1 ] | Parent Timeline
5148 : // ------------------------------+
5149 : // ```
5150 : #[tokio::test]
5151 6 : async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
5152 6 : let tenant_conf = TenantConf {
5153 6 : // Make compaction deterministic
5154 6 : gc_period: Duration::ZERO,
5155 6 : compaction_period: Duration::ZERO,
5156 6 : // Encourage creation of L1 layers
5157 6 : checkpoint_distance: 16 * 1024,
5158 6 : compaction_target_size: 8 * 1024,
5159 6 : ..TenantConf::default()
5160 6 : };
5161 6 :
5162 6 : let harness = TenantHarness::create_custom(
5163 6 : "test_get_vectored_key_gap",
5164 6 : tenant_conf,
5165 6 : TenantId::generate(),
5166 6 : ShardIdentity::unsharded(),
5167 6 : Generation::new(0xdeadbeef),
5168 6 : )
5169 6 : .await?;
5170 24 : let (tenant, ctx) = harness.load().await;
5171 6 :
5172 6 : let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
5173 6 : let gap_at_key = current_key.add(100);
5174 6 : let mut current_lsn = Lsn(0x10);
5175 6 :
5176 6 : const KEY_COUNT: usize = 10_000;
5177 6 :
5178 6 : let timeline_id = TimelineId::generate();
5179 6 : let current_timeline = tenant
5180 6 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
5181 12 : .await?;
5182 6 :
5183 6 : current_lsn += 0x100;
5184 6 :
5185 6 : let mut writer = current_timeline.writer().await;
5186 6 : writer
5187 6 : .put(
5188 6 : gap_at_key,
5189 6 : current_lsn,
5190 6 : &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
5191 6 : &ctx,
5192 6 : )
5193 6 : .await?;
5194 6 : writer.finish_write(current_lsn);
5195 6 : drop(writer);
5196 6 :
5197 6 : let mut latest_lsns = HashMap::new();
5198 6 : latest_lsns.insert(gap_at_key, current_lsn);
5199 6 :
5200 6 : current_timeline.freeze_and_flush().await?;
5201 6 :
5202 6 : let child_timeline_id = TimelineId::generate();
5203 6 :
5204 6 : tenant
5205 6 : .branch_timeline_test(
5206 6 : ¤t_timeline,
5207 6 : child_timeline_id,
5208 6 : Some(current_lsn),
5209 6 : &ctx,
5210 6 : )
5211 6 : .await?;
5212 6 : let child_timeline = tenant
5213 6 : .get_timeline(child_timeline_id, true)
5214 6 : .expect("Should have the branched timeline");
5215 6 :
5216 60006 : for i in 0..KEY_COUNT {
5217 60000 : if current_key == gap_at_key {
5218 6 : current_key = current_key.next();
5219 6 : continue;
5220 59994 : }
5221 59994 :
5222 59994 : current_lsn += 0x10;
5223 6 :
5224 59994 : let mut writer = child_timeline.writer().await;
5225 59994 : writer
5226 59994 : .put(
5227 59994 : current_key,
5228 59994 : current_lsn,
5229 59994 : &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
5230 59994 : &ctx,
5231 59994 : )
5232 209 : .await?;
5233 59994 : writer.finish_write(current_lsn);
5234 59994 : drop(writer);
5235 59994 :
5236 59994 : latest_lsns.insert(current_key, current_lsn);
5237 59994 : current_key = current_key.next();
5238 59994 :
5239 59994 : // Flush every now and then to encourage layer file creation.
5240 59994 : if i % 500 == 0 {
5241 136 : child_timeline.freeze_and_flush().await?;
5242 59874 : }
5243 6 : }
5244 6 :
5245 8 : child_timeline.freeze_and_flush().await?;
5246 6 : let mut flags = EnumSet::new();
5247 6 : flags.insert(CompactFlags::ForceRepartition);
5248 6 : child_timeline
5249 6 : .compact(&CancellationToken::new(), flags, &ctx)
5250 5598 : .await?;
5251 6 :
5252 6 : let key_near_end = {
5253 6 : let mut tmp = current_key;
5254 6 : tmp.field6 -= 10;
5255 6 : tmp
5256 6 : };
5257 6 :
5258 6 : let key_near_gap = {
5259 6 : let mut tmp = gap_at_key;
5260 6 : tmp.field6 -= 10;
5261 6 : tmp
5262 6 : };
5263 6 :
5264 6 : let read = KeySpace {
5265 6 : ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
5266 6 : };
5267 6 : let results = child_timeline
5268 6 : .get_vectored_impl(
5269 6 : read.clone(),
5270 6 : current_lsn,
5271 6 : &mut ValuesReconstructState::new(),
5272 6 : &ctx,
5273 6 : )
5274 45 : .await?;
5275 6 :
5276 132 : for (key, img_res) in results {
5277 126 : let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
5278 126 : assert_eq!(img_res?, expected);
5279 6 : }
5280 6 :
5281 6 : Ok(())
5282 6 : }
5283 :
5284 : // Test that vectored get descends into ancestor timelines correctly and
5285 : // does not return an image that's newer than requested.
5286 : //
5287 : // The diagram below ilustrates an interesting case. We have a parent timeline
5288 : // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
5289 : // from the child timeline, so the parent timeline must be visited. When advacing into
5290 : // the child timeline, the read path needs to remember what the requested Lsn was in
5291 : // order to avoid returning an image that's too new. The test below constructs such
5292 : // a timeline setup and does a few queries around the Lsn of each page image.
5293 : // ```
5294 : // LSN
5295 : // ^
5296 : // |
5297 : // |
5298 : // 500 | --------------------------------------> branch point
5299 : // 400 | X
5300 : // 300 | X
5301 : // 200 | --------------------------------------> requested lsn
5302 : // 100 | X
5303 : // |---------------------------------------> Key
5304 : // |
5305 : // ------> requested key
5306 : //
5307 : // Legend:
5308 : // * X - page images
5309 : // ```
5310 : #[tokio::test]
5311 6 : async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
5312 6 : let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
5313 24 : let (tenant, ctx) = harness.load().await;
5314 6 :
5315 6 : let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
5316 6 : let end_key = start_key.add(1000);
5317 6 : let child_gap_at_key = start_key.add(500);
5318 6 : let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
5319 6 :
5320 6 : let mut current_lsn = Lsn(0x10);
5321 6 :
5322 6 : let timeline_id = TimelineId::generate();
5323 6 : let parent_timeline = tenant
5324 6 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
5325 12 : .await?;
5326 6 :
5327 6 : current_lsn += 0x100;
5328 6 :
5329 24 : for _ in 0..3 {
5330 18 : let mut key = start_key;
5331 18018 : while key < end_key {
5332 18000 : current_lsn += 0x10;
5333 18000 :
5334 18000 : let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
5335 6 :
5336 18000 : let mut writer = parent_timeline.writer().await;
5337 18000 : writer
5338 18000 : .put(
5339 18000 : key,
5340 18000 : current_lsn,
5341 18000 : &Value::Image(test_img(&image_value)),
5342 18000 : &ctx,
5343 18000 : )
5344 18 : .await?;
5345 18000 : writer.finish_write(current_lsn);
5346 18000 :
5347 18000 : if key == child_gap_at_key {
5348 18 : parent_gap_lsns.insert(current_lsn, image_value);
5349 17982 : }
5350 6 :
5351 18000 : key = key.next();
5352 6 : }
5353 6 :
5354 18 : parent_timeline.freeze_and_flush().await?;
5355 6 : }
5356 6 :
5357 6 : let child_timeline_id = TimelineId::generate();
5358 6 :
5359 6 : let child_timeline = tenant
5360 6 : .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
5361 6 : .await?;
5362 6 :
5363 6 : let mut key = start_key;
5364 6006 : while key < end_key {
5365 6000 : if key == child_gap_at_key {
5366 6 : key = key.next();
5367 6 : continue;
5368 5994 : }
5369 5994 :
5370 5994 : current_lsn += 0x10;
5371 6 :
5372 5994 : let mut writer = child_timeline.writer().await;
5373 5994 : writer
5374 5994 : .put(
5375 5994 : key,
5376 5994 : current_lsn,
5377 5994 : &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
5378 5994 : &ctx,
5379 5994 : )
5380 51 : .await?;
5381 5994 : writer.finish_write(current_lsn);
5382 5994 :
5383 5994 : key = key.next();
5384 6 : }
5385 6 :
5386 6 : child_timeline.freeze_and_flush().await?;
5387 6 :
5388 6 : let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
5389 6 : let mut query_lsns = Vec::new();
5390 18 : for image_lsn in parent_gap_lsns.keys().rev() {
5391 108 : for offset in lsn_offsets {
5392 90 : query_lsns.push(Lsn(image_lsn
5393 90 : .0
5394 90 : .checked_add_signed(offset)
5395 90 : .expect("Shouldn't overflow")));
5396 90 : }
5397 6 : }
5398 6 :
5399 96 : for query_lsn in query_lsns {
5400 90 : let results = child_timeline
5401 90 : .get_vectored_impl(
5402 90 : KeySpace {
5403 90 : ranges: vec![child_gap_at_key..child_gap_at_key.next()],
5404 90 : },
5405 90 : query_lsn,
5406 90 : &mut ValuesReconstructState::new(),
5407 90 : &ctx,
5408 90 : )
5409 87 : .await;
5410 6 :
5411 90 : let expected_item = parent_gap_lsns
5412 90 : .iter()
5413 90 : .rev()
5414 204 : .find(|(lsn, _)| **lsn <= query_lsn);
5415 90 :
5416 90 : info!(
5417 6 : "Doing vectored read at LSN {}. Expecting image to be: {:?}",
5418 6 : query_lsn, expected_item
5419 6 : );
5420 6 :
5421 90 : match expected_item {
5422 78 : Some((_, img_value)) => {
5423 78 : let key_results = results.expect("No vectored get error expected");
5424 78 : let key_result = &key_results[&child_gap_at_key];
5425 78 : let returned_img = key_result
5426 78 : .as_ref()
5427 78 : .expect("No page reconstruct error expected");
5428 78 :
5429 78 : info!(
5430 6 : "Vectored read at LSN {} returned image {}",
5431 0 : query_lsn,
5432 0 : std::str::from_utf8(returned_img)?
5433 6 : );
5434 78 : assert_eq!(*returned_img, test_img(img_value));
5435 6 : }
5436 6 : None => {
5437 12 : assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
5438 6 : }
5439 6 : }
5440 6 : }
5441 6 :
5442 6 : Ok(())
5443 6 : }
5444 :
5445 : #[tokio::test]
5446 6 : async fn test_random_updates() -> anyhow::Result<()> {
5447 6 : let names_algorithms = [
5448 6 : ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
5449 6 : ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
5450 6 : ];
5451 18 : for (name, algorithm) in names_algorithms {
5452 289079 : test_random_updates_algorithm(name, algorithm).await?;
5453 6 : }
5454 6 : Ok(())
5455 6 : }
5456 :
5457 12 : async fn test_random_updates_algorithm(
5458 12 : name: &'static str,
5459 12 : compaction_algorithm: CompactionAlgorithm,
5460 12 : ) -> anyhow::Result<()> {
5461 12 : let mut harness = TenantHarness::create(name).await?;
5462 12 : harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
5463 12 : kind: compaction_algorithm,
5464 12 : };
5465 48 : let (tenant, ctx) = harness.load().await;
5466 12 : let tline = tenant
5467 12 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5468 21 : .await?;
5469 :
5470 : const NUM_KEYS: usize = 1000;
5471 12 : let cancel = CancellationToken::new();
5472 12 :
5473 12 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
5474 12 : let mut test_key_end = test_key;
5475 12 : test_key_end.field6 = NUM_KEYS as u32;
5476 12 : tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
5477 12 :
5478 12 : let mut keyspace = KeySpaceAccum::new();
5479 12 :
5480 12 : // Track when each page was last modified. Used to assert that
5481 12 : // a read sees the latest page version.
5482 12 : let mut updated = [Lsn(0); NUM_KEYS];
5483 12 :
5484 12 : let mut lsn = Lsn(0x10);
5485 : #[allow(clippy::needless_range_loop)]
5486 12012 : for blknum in 0..NUM_KEYS {
5487 12000 : lsn = Lsn(lsn.0 + 0x10);
5488 12000 : test_key.field6 = blknum as u32;
5489 12000 : let mut writer = tline.writer().await;
5490 12000 : writer
5491 12000 : .put(
5492 12000 : test_key,
5493 12000 : lsn,
5494 12000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
5495 12000 : &ctx,
5496 12000 : )
5497 12 : .await?;
5498 12000 : writer.finish_write(lsn);
5499 12000 : updated[blknum] = lsn;
5500 12000 : drop(writer);
5501 12000 :
5502 12000 : keyspace.add_key(test_key);
5503 : }
5504 :
5505 612 : for _ in 0..50 {
5506 600600 : for _ in 0..NUM_KEYS {
5507 600000 : lsn = Lsn(lsn.0 + 0x10);
5508 600000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
5509 600000 : test_key.field6 = blknum as u32;
5510 600000 : let mut writer = tline.writer().await;
5511 600000 : writer
5512 600000 : .put(
5513 600000 : test_key,
5514 600000 : lsn,
5515 600000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
5516 600000 : &ctx,
5517 600000 : )
5518 639 : .await?;
5519 600000 : writer.finish_write(lsn);
5520 600000 : drop(writer);
5521 600000 : updated[blknum] = lsn;
5522 : }
5523 :
5524 : // Read all the blocks
5525 600000 : for (blknum, last_lsn) in updated.iter().enumerate() {
5526 600000 : test_key.field6 = blknum as u32;
5527 600000 : assert_eq!(
5528 600000 : tline.get(test_key, lsn, &ctx).await?,
5529 600000 : test_img(&format!("{} at {}", blknum, last_lsn))
5530 : );
5531 : }
5532 :
5533 : // Perform a cycle of flush, and GC
5534 607 : tline.freeze_and_flush().await?;
5535 600 : tenant
5536 600 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
5537 589 : .await?;
5538 : }
5539 :
5540 12 : Ok(())
5541 12 : }
5542 :
5543 : #[tokio::test]
5544 6 : async fn test_traverse_branches() -> anyhow::Result<()> {
5545 6 : let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
5546 6 : .await?
5547 6 : .load()
5548 24 : .await;
5549 6 : let mut tline = tenant
5550 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5551 12 : .await?;
5552 6 :
5553 6 : const NUM_KEYS: usize = 1000;
5554 6 :
5555 6 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
5556 6 :
5557 6 : let mut keyspace = KeySpaceAccum::new();
5558 6 :
5559 6 : let cancel = CancellationToken::new();
5560 6 :
5561 6 : // Track when each page was last modified. Used to assert that
5562 6 : // a read sees the latest page version.
5563 6 : let mut updated = [Lsn(0); NUM_KEYS];
5564 6 :
5565 6 : let mut lsn = Lsn(0x10);
5566 6 : #[allow(clippy::needless_range_loop)]
5567 6006 : for blknum in 0..NUM_KEYS {
5568 6000 : lsn = Lsn(lsn.0 + 0x10);
5569 6000 : test_key.field6 = blknum as u32;
5570 6000 : let mut writer = tline.writer().await;
5571 6000 : writer
5572 6000 : .put(
5573 6000 : test_key,
5574 6000 : lsn,
5575 6000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
5576 6000 : &ctx,
5577 6000 : )
5578 6 : .await?;
5579 6000 : writer.finish_write(lsn);
5580 6000 : updated[blknum] = lsn;
5581 6000 : drop(writer);
5582 6000 :
5583 6000 : keyspace.add_key(test_key);
5584 6 : }
5585 6 :
5586 306 : for _ in 0..50 {
5587 300 : let new_tline_id = TimelineId::generate();
5588 300 : tenant
5589 300 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
5590 6 : .await?;
5591 300 : tline = tenant
5592 300 : .get_timeline(new_tline_id, true)
5593 300 : .expect("Should have the branched timeline");
5594 6 :
5595 300300 : for _ in 0..NUM_KEYS {
5596 300000 : lsn = Lsn(lsn.0 + 0x10);
5597 300000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
5598 300000 : test_key.field6 = blknum as u32;
5599 300000 : let mut writer = tline.writer().await;
5600 300000 : writer
5601 300000 : .put(
5602 300000 : test_key,
5603 300000 : lsn,
5604 300000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
5605 300000 : &ctx,
5606 300000 : )
5607 2538 : .await?;
5608 300000 : println!("updating {} at {}", blknum, lsn);
5609 300000 : writer.finish_write(lsn);
5610 300000 : drop(writer);
5611 300000 : updated[blknum] = lsn;
5612 6 : }
5613 6 :
5614 6 : // Read all the blocks
5615 300000 : for (blknum, last_lsn) in updated.iter().enumerate() {
5616 300000 : test_key.field6 = blknum as u32;
5617 300000 : assert_eq!(
5618 300000 : tline.get(test_key, lsn, &ctx).await?,
5619 300000 : test_img(&format!("{} at {}", blknum, last_lsn))
5620 6 : );
5621 6 : }
5622 6 :
5623 6 : // Perform a cycle of flush, compact, and GC
5624 303 : tline.freeze_and_flush().await?;
5625 45249 : tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
5626 300 : tenant
5627 300 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
5628 297 : .await?;
5629 6 : }
5630 6 :
5631 6 : Ok(())
5632 6 : }
5633 :
5634 : #[tokio::test]
5635 6 : async fn test_traverse_ancestors() -> anyhow::Result<()> {
5636 6 : let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
5637 6 : .await?
5638 6 : .load()
5639 24 : .await;
5640 6 : let mut tline = tenant
5641 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5642 12 : .await?;
5643 6 :
5644 6 : const NUM_KEYS: usize = 100;
5645 6 : const NUM_TLINES: usize = 50;
5646 6 :
5647 6 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
5648 6 : // Track page mutation lsns across different timelines.
5649 6 : let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
5650 6 :
5651 6 : let mut lsn = Lsn(0x10);
5652 6 :
5653 6 : #[allow(clippy::needless_range_loop)]
5654 306 : for idx in 0..NUM_TLINES {
5655 300 : let new_tline_id = TimelineId::generate();
5656 300 : tenant
5657 300 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
5658 6 : .await?;
5659 300 : tline = tenant
5660 300 : .get_timeline(new_tline_id, true)
5661 300 : .expect("Should have the branched timeline");
5662 6 :
5663 30300 : for _ in 0..NUM_KEYS {
5664 30000 : lsn = Lsn(lsn.0 + 0x10);
5665 30000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
5666 30000 : test_key.field6 = blknum as u32;
5667 30000 : let mut writer = tline.writer().await;
5668 30000 : writer
5669 30000 : .put(
5670 30000 : test_key,
5671 30000 : lsn,
5672 30000 : &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
5673 30000 : &ctx,
5674 30000 : )
5675 264 : .await?;
5676 30000 : println!("updating [{}][{}] at {}", idx, blknum, lsn);
5677 30000 : writer.finish_write(lsn);
5678 30000 : drop(writer);
5679 30000 : updated[idx][blknum] = lsn;
5680 6 : }
5681 6 : }
5682 6 :
5683 6 : // Read pages from leaf timeline across all ancestors.
5684 300 : for (idx, lsns) in updated.iter().enumerate() {
5685 30000 : for (blknum, lsn) in lsns.iter().enumerate() {
5686 6 : // Skip empty mutations.
5687 30000 : if lsn.0 == 0 {
5688 11010 : continue;
5689 18990 : }
5690 18990 : println!("checking [{idx}][{blknum}] at {lsn}");
5691 18990 : test_key.field6 = blknum as u32;
5692 18990 : assert_eq!(
5693 18990 : tline.get(test_key, *lsn, &ctx).await?,
5694 18990 : test_img(&format!("{idx} {blknum} at {lsn}"))
5695 6 : );
5696 6 : }
5697 6 : }
5698 6 : Ok(())
5699 6 : }
5700 :
5701 : #[tokio::test]
5702 6 : async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
5703 6 : let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
5704 6 : .await?
5705 6 : .load()
5706 24 : .await;
5707 6 :
5708 6 : let initdb_lsn = Lsn(0x20);
5709 6 : let utline = tenant
5710 6 : .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
5711 6 : .await?;
5712 6 : let tline = utline.raw_timeline().unwrap();
5713 6 :
5714 6 : // Spawn flush loop now so that we can set the `expect_initdb_optimization`
5715 6 : tline.maybe_spawn_flush_loop();
5716 6 :
5717 6 : // Make sure the timeline has the minimum set of required keys for operation.
5718 6 : // The only operation you can always do on an empty timeline is to `put` new data.
5719 6 : // Except if you `put` at `initdb_lsn`.
5720 6 : // In that case, there's an optimization to directly create image layers instead of delta layers.
5721 6 : // It uses `repartition()`, which assumes some keys to be present.
5722 6 : // Let's make sure the test timeline can handle that case.
5723 6 : {
5724 6 : let mut state = tline.flush_loop_state.lock().unwrap();
5725 6 : assert_eq!(
5726 6 : timeline::FlushLoopState::Running {
5727 6 : expect_initdb_optimization: false,
5728 6 : initdb_optimization_count: 0,
5729 6 : },
5730 6 : *state
5731 6 : );
5732 6 : *state = timeline::FlushLoopState::Running {
5733 6 : expect_initdb_optimization: true,
5734 6 : initdb_optimization_count: 0,
5735 6 : };
5736 6 : }
5737 6 :
5738 6 : // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
5739 6 : // As explained above, the optimization requires some keys to be present.
5740 6 : // As per `create_empty_timeline` documentation, use init_empty to set them.
5741 6 : // This is what `create_test_timeline` does, by the way.
5742 6 : let mut modification = tline.begin_modification(initdb_lsn);
5743 6 : modification
5744 6 : .init_empty_test_timeline()
5745 6 : .context("init_empty_test_timeline")?;
5746 6 : modification
5747 6 : .commit(&ctx)
5748 6 : .await
5749 6 : .context("commit init_empty_test_timeline modification")?;
5750 6 :
5751 6 : // Do the flush. The flush code will check the expectations that we set above.
5752 6 : tline.freeze_and_flush().await?;
5753 6 :
5754 6 : // assert freeze_and_flush exercised the initdb optimization
5755 6 : {
5756 6 : let state = tline.flush_loop_state.lock().unwrap();
5757 6 : let timeline::FlushLoopState::Running {
5758 6 : expect_initdb_optimization,
5759 6 : initdb_optimization_count,
5760 6 : } = *state
5761 6 : else {
5762 6 : panic!("unexpected state: {:?}", *state);
5763 6 : };
5764 6 : assert!(expect_initdb_optimization);
5765 6 : assert!(initdb_optimization_count > 0);
5766 6 : }
5767 6 : Ok(())
5768 6 : }
5769 :
5770 : #[tokio::test]
5771 6 : async fn test_create_guard_crash() -> anyhow::Result<()> {
5772 6 : let name = "test_create_guard_crash";
5773 6 : let harness = TenantHarness::create(name).await?;
5774 6 : {
5775 24 : let (tenant, ctx) = harness.load().await;
5776 6 : let tline = tenant
5777 6 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
5778 6 : .await?;
5779 6 : // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
5780 6 : let raw_tline = tline.raw_timeline().unwrap();
5781 6 : raw_tline
5782 6 : .shutdown(super::timeline::ShutdownMode::Hard)
5783 6 : .instrument(info_span!("test_shutdown", tenant_id=%raw_tline.tenant_shard_id, shard_id=%raw_tline.tenant_shard_id.shard_slug(), timeline_id=%TIMELINE_ID))
5784 6 : .await;
5785 6 : std::mem::forget(tline);
5786 6 : }
5787 6 :
5788 24 : let (tenant, _) = harness.load().await;
5789 6 : match tenant.get_timeline(TIMELINE_ID, false) {
5790 6 : Ok(_) => panic!("timeline should've been removed during load"),
5791 6 : Err(e) => {
5792 6 : assert_eq!(
5793 6 : e,
5794 6 : GetTimelineError::NotFound {
5795 6 : tenant_id: tenant.tenant_shard_id,
5796 6 : timeline_id: TIMELINE_ID,
5797 6 : }
5798 6 : )
5799 6 : }
5800 6 : }
5801 6 :
5802 6 : assert!(!harness
5803 6 : .conf
5804 6 : .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
5805 6 : .exists());
5806 6 :
5807 6 : Ok(())
5808 6 : }
5809 :
5810 : #[tokio::test]
5811 6 : async fn test_read_at_max_lsn() -> anyhow::Result<()> {
5812 6 : let names_algorithms = [
5813 6 : ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
5814 6 : ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
5815 6 : ];
5816 18 : for (name, algorithm) in names_algorithms {
5817 98198 : test_read_at_max_lsn_algorithm(name, algorithm).await?;
5818 6 : }
5819 6 : Ok(())
5820 6 : }
5821 :
5822 12 : async fn test_read_at_max_lsn_algorithm(
5823 12 : name: &'static str,
5824 12 : compaction_algorithm: CompactionAlgorithm,
5825 12 : ) -> anyhow::Result<()> {
5826 12 : let mut harness = TenantHarness::create(name).await?;
5827 12 : harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
5828 12 : kind: compaction_algorithm,
5829 12 : };
5830 48 : let (tenant, ctx) = harness.load().await;
5831 12 : let tline = tenant
5832 12 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
5833 21 : .await?;
5834 :
5835 12 : let lsn = Lsn(0x10);
5836 12 : let compact = false;
5837 96899 : bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
5838 :
5839 12 : let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
5840 12 : let read_lsn = Lsn(u64::MAX - 1);
5841 :
5842 1230 : let result = tline.get(test_key, read_lsn, &ctx).await;
5843 12 : assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
5844 :
5845 12 : Ok(())
5846 12 : }
5847 :
5848 : #[tokio::test]
5849 6 : async fn test_metadata_scan() -> anyhow::Result<()> {
5850 6 : let harness = TenantHarness::create("test_metadata_scan").await?;
5851 24 : let (tenant, ctx) = harness.load().await;
5852 6 : let tline = tenant
5853 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5854 12 : .await?;
5855 6 :
5856 6 : const NUM_KEYS: usize = 1000;
5857 6 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
5858 6 :
5859 6 : let cancel = CancellationToken::new();
5860 6 :
5861 6 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
5862 6 : base_key.field1 = AUX_KEY_PREFIX;
5863 6 : let mut test_key = base_key;
5864 6 :
5865 6 : // Track when each page was last modified. Used to assert that
5866 6 : // a read sees the latest page version.
5867 6 : let mut updated = [Lsn(0); NUM_KEYS];
5868 6 :
5869 6 : let mut lsn = Lsn(0x10);
5870 6 : #[allow(clippy::needless_range_loop)]
5871 6006 : for blknum in 0..NUM_KEYS {
5872 6000 : lsn = Lsn(lsn.0 + 0x10);
5873 6000 : test_key.field6 = (blknum * STEP) as u32;
5874 6000 : let mut writer = tline.writer().await;
5875 6000 : writer
5876 6000 : .put(
5877 6000 : test_key,
5878 6000 : lsn,
5879 6000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
5880 6000 : &ctx,
5881 6000 : )
5882 6 : .await?;
5883 6000 : writer.finish_write(lsn);
5884 6000 : updated[blknum] = lsn;
5885 6000 : drop(writer);
5886 6 : }
5887 6 :
5888 6 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
5889 6 :
5890 72 : for iter in 0..=10 {
5891 6 : // Read all the blocks
5892 66000 : for (blknum, last_lsn) in updated.iter().enumerate() {
5893 66000 : test_key.field6 = (blknum * STEP) as u32;
5894 66000 : assert_eq!(
5895 66000 : tline.get(test_key, lsn, &ctx).await?,
5896 66000 : test_img(&format!("{} at {}", blknum, last_lsn))
5897 6 : );
5898 6 : }
5899 6 :
5900 66 : let mut cnt = 0;
5901 66000 : for (key, value) in tline
5902 66 : .get_vectored_impl(
5903 66 : keyspace.clone(),
5904 66 : lsn,
5905 66 : &mut ValuesReconstructState::default(),
5906 66 : &ctx,
5907 66 : )
5908 12668 : .await?
5909 6 : {
5910 66000 : let blknum = key.field6 as usize;
5911 66000 : let value = value?;
5912 66000 : assert!(blknum % STEP == 0);
5913 66000 : let blknum = blknum / STEP;
5914 66000 : assert_eq!(
5915 66000 : value,
5916 66000 : test_img(&format!("{} at {}", blknum, updated[blknum]))
5917 66000 : );
5918 66000 : cnt += 1;
5919 6 : }
5920 6 :
5921 66 : assert_eq!(cnt, NUM_KEYS);
5922 6 :
5923 66066 : for _ in 0..NUM_KEYS {
5924 66000 : lsn = Lsn(lsn.0 + 0x10);
5925 66000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
5926 66000 : test_key.field6 = (blknum * STEP) as u32;
5927 66000 : let mut writer = tline.writer().await;
5928 66000 : writer
5929 66000 : .put(
5930 66000 : test_key,
5931 66000 : lsn,
5932 66000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
5933 66000 : &ctx,
5934 66000 : )
5935 455 : .await?;
5936 66000 : writer.finish_write(lsn);
5937 66000 : drop(writer);
5938 66000 : updated[blknum] = lsn;
5939 6 : }
5940 6 :
5941 6 : // Perform two cycles of flush, compact, and GC
5942 198 : for round in 0..2 {
5943 132 : tline.freeze_and_flush().await?;
5944 132 : tline
5945 132 : .compact(
5946 132 : &cancel,
5947 132 : if iter % 5 == 0 && round == 0 {
5948 18 : let mut flags = EnumSet::new();
5949 18 : flags.insert(CompactFlags::ForceImageLayerCreation);
5950 18 : flags.insert(CompactFlags::ForceRepartition);
5951 18 : flags
5952 6 : } else {
5953 114 : EnumSet::empty()
5954 6 : },
5955 132 : &ctx,
5956 6 : )
5957 23913 : .await?;
5958 132 : tenant
5959 132 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
5960 126 : .await?;
5961 6 : }
5962 6 : }
5963 6 :
5964 6 : Ok(())
5965 6 : }
5966 :
5967 : #[tokio::test]
5968 6 : async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
5969 6 : let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
5970 24 : let (tenant, ctx) = harness.load().await;
5971 6 : let tline = tenant
5972 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5973 12 : .await?;
5974 6 :
5975 6 : let cancel = CancellationToken::new();
5976 6 :
5977 6 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
5978 6 : base_key.field1 = AUX_KEY_PREFIX;
5979 6 : let test_key = base_key;
5980 6 : let mut lsn = Lsn(0x10);
5981 6 :
5982 126 : for _ in 0..20 {
5983 120 : lsn = Lsn(lsn.0 + 0x10);
5984 120 : let mut writer = tline.writer().await;
5985 120 : writer
5986 120 : .put(
5987 120 : test_key,
5988 120 : lsn,
5989 120 : &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
5990 120 : &ctx,
5991 120 : )
5992 60 : .await?;
5993 120 : writer.finish_write(lsn);
5994 120 : drop(writer);
5995 122 : tline.freeze_and_flush().await?; // force create a delta layer
5996 6 : }
5997 6 :
5998 6 : let before_num_l0_delta_files =
5999 6 : tline.layers.read().await.layer_map()?.level0_deltas().len();
6000 6 :
6001 330 : tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
6002 6 :
6003 6 : let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
6004 6 :
6005 6 : assert!(after_num_l0_delta_files < before_num_l0_delta_files, "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}");
6006 6 :
6007 6 : assert_eq!(
6008 12 : tline.get(test_key, lsn, &ctx).await?,
6009 6 : test_img(&format!("{} at {}", 0, lsn))
6010 6 : );
6011 6 :
6012 6 : Ok(())
6013 6 : }
6014 :
6015 : #[tokio::test]
6016 6 : async fn test_branch_copies_dirty_aux_file_flag() {
6017 6 : let harness = TenantHarness::create("test_branch_copies_dirty_aux_file_flag")
6018 6 : .await
6019 6 : .unwrap();
6020 6 :
6021 6 : // the default aux file policy to switch is v2 if not set by the admins
6022 6 : assert_eq!(
6023 6 : harness.tenant_conf.switch_aux_file_policy,
6024 6 : AuxFilePolicy::default_tenant_config()
6025 6 : );
6026 24 : let (tenant, ctx) = harness.load().await;
6027 6 :
6028 6 : let mut lsn = Lsn(0x08);
6029 6 :
6030 6 : let tline: Arc<Timeline> = tenant
6031 6 : .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
6032 12 : .await
6033 6 : .unwrap();
6034 6 :
6035 6 : // no aux file is written at this point, so the persistent flag should be unset
6036 6 : assert_eq!(tline.last_aux_file_policy.load(), None);
6037 6 :
6038 6 : {
6039 6 : lsn += 8;
6040 6 : let mut modification = tline.begin_modification(lsn);
6041 6 : modification
6042 6 : .put_file("pg_logical/mappings/test1", b"first", &ctx)
6043 6 : .await
6044 6 : .unwrap();
6045 6 : modification.commit(&ctx).await.unwrap();
6046 6 : }
6047 6 :
6048 6 : // there is no tenant manager to pass the configuration through, so lets mimic it
6049 6 : tenant.set_new_location_config(
6050 6 : AttachedTenantConf::try_from(LocationConf::attached_single(
6051 6 : TenantConfOpt {
6052 6 : switch_aux_file_policy: Some(AuxFilePolicy::V2),
6053 6 : ..Default::default()
6054 6 : },
6055 6 : tenant.generation,
6056 6 : &pageserver_api::models::ShardParameters::default(),
6057 6 : ))
6058 6 : .unwrap(),
6059 6 : );
6060 6 :
6061 6 : assert_eq!(
6062 6 : tline.get_switch_aux_file_policy(),
6063 6 : AuxFilePolicy::V2,
6064 6 : "wanted state has been updated"
6065 6 : );
6066 6 : assert_eq!(
6067 6 : tline.last_aux_file_policy.load(),
6068 6 : Some(AuxFilePolicy::V2),
6069 6 : "aux file is written with switch_aux_file_policy unset (which is v2), so we should use v2 there"
6070 6 : );
6071 6 :
6072 6 : // we can read everything from the storage
6073 6 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6074 6 : assert_eq!(
6075 6 : files.get("pg_logical/mappings/test1"),
6076 6 : Some(&bytes::Bytes::from_static(b"first"))
6077 6 : );
6078 6 :
6079 6 : {
6080 6 : lsn += 8;
6081 6 : let mut modification = tline.begin_modification(lsn);
6082 6 : modification
6083 6 : .put_file("pg_logical/mappings/test2", b"second", &ctx)
6084 6 : .await
6085 6 : .unwrap();
6086 6 : modification.commit(&ctx).await.unwrap();
6087 6 : }
6088 6 :
6089 6 : assert_eq!(
6090 6 : tline.last_aux_file_policy.load(),
6091 6 : Some(AuxFilePolicy::V2),
6092 6 : "keep v2 storage format when new files are written"
6093 6 : );
6094 6 :
6095 6 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6096 6 : assert_eq!(
6097 6 : files.get("pg_logical/mappings/test2"),
6098 6 : Some(&bytes::Bytes::from_static(b"second"))
6099 6 : );
6100 6 :
6101 6 : let child = tenant
6102 6 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
6103 6 : .await
6104 6 : .unwrap();
6105 6 :
6106 6 : // child copies the last flag even if that is not on remote storage yet
6107 6 : assert_eq!(child.get_switch_aux_file_policy(), AuxFilePolicy::V2);
6108 6 : assert_eq!(child.last_aux_file_policy.load(), Some(AuxFilePolicy::V2));
6109 6 :
6110 6 : let files = child.list_aux_files(lsn, &ctx).await.unwrap();
6111 6 : assert_eq!(files.get("pg_logical/mappings/test1"), None);
6112 6 : assert_eq!(files.get("pg_logical/mappings/test2"), None);
6113 6 :
6114 6 : // even if we crash here without flushing parent timeline with it's new
6115 6 : // last_aux_file_policy we are safe, because child was never meant to access ancestor's
6116 6 : // files. the ancestor can even switch back to V1 because of a migration safely.
6117 6 : }
6118 :
6119 : #[tokio::test]
6120 6 : async fn aux_file_policy_switch() {
6121 6 : let mut harness = TenantHarness::create("aux_file_policy_switch")
6122 6 : .await
6123 6 : .unwrap();
6124 6 : harness.tenant_conf.switch_aux_file_policy = AuxFilePolicy::CrossValidation; // set to cross-validation mode
6125 24 : let (tenant, ctx) = harness.load().await;
6126 6 :
6127 6 : let mut lsn = Lsn(0x08);
6128 6 :
6129 6 : let tline: Arc<Timeline> = tenant
6130 6 : .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
6131 12 : .await
6132 6 : .unwrap();
6133 6 :
6134 6 : assert_eq!(
6135 6 : tline.last_aux_file_policy.load(),
6136 6 : None,
6137 6 : "no aux file is written so it should be unset"
6138 6 : );
6139 6 :
6140 6 : {
6141 6 : lsn += 8;
6142 6 : let mut modification = tline.begin_modification(lsn);
6143 6 : modification
6144 6 : .put_file("pg_logical/mappings/test1", b"first", &ctx)
6145 15 : .await
6146 6 : .unwrap();
6147 6 : modification.commit(&ctx).await.unwrap();
6148 6 : }
6149 6 :
6150 6 : // there is no tenant manager to pass the configuration through, so lets mimic it
6151 6 : tenant.set_new_location_config(
6152 6 : AttachedTenantConf::try_from(LocationConf::attached_single(
6153 6 : TenantConfOpt {
6154 6 : switch_aux_file_policy: Some(AuxFilePolicy::V2),
6155 6 : ..Default::default()
6156 6 : },
6157 6 : tenant.generation,
6158 6 : &pageserver_api::models::ShardParameters::default(),
6159 6 : ))
6160 6 : .unwrap(),
6161 6 : );
6162 6 :
6163 6 : assert_eq!(
6164 6 : tline.get_switch_aux_file_policy(),
6165 6 : AuxFilePolicy::V2,
6166 6 : "wanted state has been updated"
6167 6 : );
6168 6 : assert_eq!(
6169 6 : tline.last_aux_file_policy.load(),
6170 6 : Some(AuxFilePolicy::CrossValidation),
6171 6 : "dirty index_part.json reflected state is yet to be updated"
6172 6 : );
6173 6 :
6174 6 : // we can still read the auxfile v1 before we ingest anything new
6175 6 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6176 6 : assert_eq!(
6177 6 : files.get("pg_logical/mappings/test1"),
6178 6 : Some(&bytes::Bytes::from_static(b"first"))
6179 6 : );
6180 6 :
6181 6 : {
6182 6 : lsn += 8;
6183 6 : let mut modification = tline.begin_modification(lsn);
6184 6 : modification
6185 6 : .put_file("pg_logical/mappings/test2", b"second", &ctx)
6186 6 : .await
6187 6 : .unwrap();
6188 6 : modification.commit(&ctx).await.unwrap();
6189 6 : }
6190 6 :
6191 6 : assert_eq!(
6192 6 : tline.last_aux_file_policy.load(),
6193 6 : Some(AuxFilePolicy::V2),
6194 6 : "ingesting a file should apply the wanted switch state when applicable"
6195 6 : );
6196 6 :
6197 6 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6198 6 : assert_eq!(
6199 6 : files.get("pg_logical/mappings/test1"),
6200 6 : Some(&bytes::Bytes::from_static(b"first")),
6201 6 : "cross validation writes to both v1 and v2 so this should be available in v2"
6202 6 : );
6203 6 : assert_eq!(
6204 6 : files.get("pg_logical/mappings/test2"),
6205 6 : Some(&bytes::Bytes::from_static(b"second"))
6206 6 : );
6207 6 :
6208 6 : // mimic again by trying to flip it from V2 to V1 (not switched to while ingesting a file)
6209 6 : tenant.set_new_location_config(
6210 6 : AttachedTenantConf::try_from(LocationConf::attached_single(
6211 6 : TenantConfOpt {
6212 6 : switch_aux_file_policy: Some(AuxFilePolicy::V1),
6213 6 : ..Default::default()
6214 6 : },
6215 6 : tenant.generation,
6216 6 : &pageserver_api::models::ShardParameters::default(),
6217 6 : ))
6218 6 : .unwrap(),
6219 6 : );
6220 6 :
6221 6 : {
6222 6 : lsn += 8;
6223 6 : let mut modification = tline.begin_modification(lsn);
6224 6 : modification
6225 6 : .put_file("pg_logical/mappings/test2", b"third", &ctx)
6226 6 : .await
6227 6 : .unwrap();
6228 6 : modification.commit(&ctx).await.unwrap();
6229 6 : }
6230 6 :
6231 6 : assert_eq!(
6232 6 : tline.get_switch_aux_file_policy(),
6233 6 : AuxFilePolicy::V1,
6234 6 : "wanted state has been updated again, even if invalid request"
6235 6 : );
6236 6 :
6237 6 : assert_eq!(
6238 6 : tline.last_aux_file_policy.load(),
6239 6 : Some(AuxFilePolicy::V2),
6240 6 : "ingesting a file should apply the wanted switch state when applicable"
6241 6 : );
6242 6 :
6243 6 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6244 6 : assert_eq!(
6245 6 : files.get("pg_logical/mappings/test1"),
6246 6 : Some(&bytes::Bytes::from_static(b"first"))
6247 6 : );
6248 6 : assert_eq!(
6249 6 : files.get("pg_logical/mappings/test2"),
6250 6 : Some(&bytes::Bytes::from_static(b"third"))
6251 6 : );
6252 6 :
6253 6 : // mimic again by trying to flip it from from V1 to V2 (not switched to while ingesting a file)
6254 6 : tenant.set_new_location_config(
6255 6 : AttachedTenantConf::try_from(LocationConf::attached_single(
6256 6 : TenantConfOpt {
6257 6 : switch_aux_file_policy: Some(AuxFilePolicy::V2),
6258 6 : ..Default::default()
6259 6 : },
6260 6 : tenant.generation,
6261 6 : &pageserver_api::models::ShardParameters::default(),
6262 6 : ))
6263 6 : .unwrap(),
6264 6 : );
6265 6 :
6266 6 : {
6267 6 : lsn += 8;
6268 6 : let mut modification = tline.begin_modification(lsn);
6269 6 : modification
6270 6 : .put_file("pg_logical/mappings/test3", b"last", &ctx)
6271 6 : .await
6272 6 : .unwrap();
6273 6 : modification.commit(&ctx).await.unwrap();
6274 6 : }
6275 6 :
6276 6 : assert_eq!(tline.get_switch_aux_file_policy(), AuxFilePolicy::V2);
6277 6 :
6278 6 : assert_eq!(tline.last_aux_file_policy.load(), Some(AuxFilePolicy::V2));
6279 6 :
6280 6 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6281 6 : assert_eq!(
6282 6 : files.get("pg_logical/mappings/test1"),
6283 6 : Some(&bytes::Bytes::from_static(b"first"))
6284 6 : );
6285 6 : assert_eq!(
6286 6 : files.get("pg_logical/mappings/test2"),
6287 6 : Some(&bytes::Bytes::from_static(b"third"))
6288 6 : );
6289 6 : assert_eq!(
6290 6 : files.get("pg_logical/mappings/test3"),
6291 6 : Some(&bytes::Bytes::from_static(b"last"))
6292 6 : );
6293 6 : }
6294 :
6295 : #[tokio::test]
6296 6 : async fn aux_file_policy_force_switch() {
6297 6 : let mut harness = TenantHarness::create("aux_file_policy_force_switch")
6298 6 : .await
6299 6 : .unwrap();
6300 6 : harness.tenant_conf.switch_aux_file_policy = AuxFilePolicy::V1;
6301 24 : let (tenant, ctx) = harness.load().await;
6302 6 :
6303 6 : let mut lsn = Lsn(0x08);
6304 6 :
6305 6 : let tline: Arc<Timeline> = tenant
6306 6 : .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
6307 12 : .await
6308 6 : .unwrap();
6309 6 :
6310 6 : assert_eq!(
6311 6 : tline.last_aux_file_policy.load(),
6312 6 : None,
6313 6 : "no aux file is written so it should be unset"
6314 6 : );
6315 6 :
6316 6 : {
6317 6 : lsn += 8;
6318 6 : let mut modification = tline.begin_modification(lsn);
6319 6 : modification
6320 6 : .put_file("pg_logical/mappings/test1", b"first", &ctx)
6321 15 : .await
6322 6 : .unwrap();
6323 6 : modification.commit(&ctx).await.unwrap();
6324 6 : }
6325 6 :
6326 6 : tline.do_switch_aux_policy(AuxFilePolicy::V2).unwrap();
6327 6 :
6328 6 : assert_eq!(
6329 6 : tline.last_aux_file_policy.load(),
6330 6 : Some(AuxFilePolicy::V2),
6331 6 : "dirty index_part.json reflected state is yet to be updated"
6332 6 : );
6333 6 :
6334 6 : // lose all data from v1
6335 6 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6336 6 : assert_eq!(files.get("pg_logical/mappings/test1"), None);
6337 6 :
6338 6 : {
6339 6 : lsn += 8;
6340 6 : let mut modification = tline.begin_modification(lsn);
6341 6 : modification
6342 6 : .put_file("pg_logical/mappings/test2", b"second", &ctx)
6343 6 : .await
6344 6 : .unwrap();
6345 6 : modification.commit(&ctx).await.unwrap();
6346 6 : }
6347 6 :
6348 6 : // read data ingested in v2
6349 6 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6350 6 : assert_eq!(
6351 6 : files.get("pg_logical/mappings/test2"),
6352 6 : Some(&bytes::Bytes::from_static(b"second"))
6353 6 : );
6354 6 : // lose all data from v1
6355 6 : assert_eq!(files.get("pg_logical/mappings/test1"), None);
6356 6 : }
6357 :
6358 : #[tokio::test]
6359 6 : async fn aux_file_policy_auto_detect() {
6360 6 : let mut harness = TenantHarness::create("aux_file_policy_auto_detect")
6361 6 : .await
6362 6 : .unwrap();
6363 6 : harness.tenant_conf.switch_aux_file_policy = AuxFilePolicy::V2; // set to cross-validation mode
6364 23 : let (tenant, ctx) = harness.load().await;
6365 6 :
6366 6 : let mut lsn = Lsn(0x08);
6367 6 :
6368 6 : let tline: Arc<Timeline> = tenant
6369 6 : .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
6370 12 : .await
6371 6 : .unwrap();
6372 6 :
6373 6 : assert_eq!(
6374 6 : tline.last_aux_file_policy.load(),
6375 6 : None,
6376 6 : "no aux file is written so it should be unset"
6377 6 : );
6378 6 :
6379 6 : {
6380 6 : lsn += 8;
6381 6 : let mut modification = tline.begin_modification(lsn);
6382 6 : let buf = AuxFilesDirectory::ser(&AuxFilesDirectory {
6383 6 : files: vec![(
6384 6 : "test_file".to_string(),
6385 6 : Bytes::copy_from_slice(b"test_file"),
6386 6 : )]
6387 6 : .into_iter()
6388 6 : .collect(),
6389 6 : })
6390 6 : .unwrap();
6391 6 : modification.put_for_test(AUX_FILES_KEY, Value::Image(Bytes::from(buf)));
6392 6 : modification.commit(&ctx).await.unwrap();
6393 6 : }
6394 6 :
6395 6 : {
6396 6 : lsn += 8;
6397 6 : let mut modification = tline.begin_modification(lsn);
6398 6 : modification
6399 6 : .put_file("pg_logical/mappings/test1", b"first", &ctx)
6400 6 : .await
6401 6 : .unwrap();
6402 6 : modification.commit(&ctx).await.unwrap();
6403 6 : }
6404 6 :
6405 6 : assert_eq!(
6406 6 : tline.last_aux_file_policy.load(),
6407 6 : Some(AuxFilePolicy::V1),
6408 6 : "keep using v1 because there are aux files writting with v1"
6409 6 : );
6410 6 :
6411 6 : // we can still read the auxfile v1
6412 6 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
6413 6 : assert_eq!(
6414 6 : files.get("pg_logical/mappings/test1"),
6415 6 : Some(&bytes::Bytes::from_static(b"first"))
6416 6 : );
6417 6 : assert_eq!(
6418 6 : files.get("test_file"),
6419 6 : Some(&bytes::Bytes::from_static(b"test_file"))
6420 6 : );
6421 6 : }
6422 :
6423 : #[tokio::test]
6424 6 : async fn test_metadata_image_creation() -> anyhow::Result<()> {
6425 6 : let harness = TenantHarness::create("test_metadata_image_creation").await?;
6426 24 : let (tenant, ctx) = harness.load().await;
6427 6 : let tline = tenant
6428 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6429 12 : .await?;
6430 6 :
6431 6 : const NUM_KEYS: usize = 1000;
6432 6 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
6433 6 :
6434 6 : let cancel = CancellationToken::new();
6435 6 :
6436 6 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
6437 6 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
6438 6 : let mut test_key = base_key;
6439 6 : let mut lsn = Lsn(0x10);
6440 6 :
6441 24 : async fn scan_with_statistics(
6442 24 : tline: &Timeline,
6443 24 : keyspace: &KeySpace,
6444 24 : lsn: Lsn,
6445 24 : ctx: &RequestContext,
6446 24 : ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
6447 24 : let mut reconstruct_state = ValuesReconstructState::default();
6448 24 : let res = tline
6449 24 : .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
6450 4042 : .await?;
6451 24 : Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
6452 24 : }
6453 6 :
6454 6 : #[allow(clippy::needless_range_loop)]
6455 6006 : for blknum in 0..NUM_KEYS {
6456 6000 : lsn = Lsn(lsn.0 + 0x10);
6457 6000 : test_key.field6 = (blknum * STEP) as u32;
6458 6000 : let mut writer = tline.writer().await;
6459 6000 : writer
6460 6000 : .put(
6461 6000 : test_key,
6462 6000 : lsn,
6463 6000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
6464 6000 : &ctx,
6465 6000 : )
6466 6 : .await?;
6467 6000 : writer.finish_write(lsn);
6468 6000 : drop(writer);
6469 6 : }
6470 6 :
6471 6 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
6472 6 :
6473 66 : for iter in 1..=10 {
6474 60060 : for _ in 0..NUM_KEYS {
6475 60000 : lsn = Lsn(lsn.0 + 0x10);
6476 60000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
6477 60000 : test_key.field6 = (blknum * STEP) as u32;
6478 60000 : let mut writer = tline.writer().await;
6479 60000 : writer
6480 60000 : .put(
6481 60000 : test_key,
6482 60000 : lsn,
6483 60000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
6484 60000 : &ctx,
6485 60000 : )
6486 104 : .await?;
6487 60000 : writer.finish_write(lsn);
6488 60000 : drop(writer);
6489 6 : }
6490 6 :
6491 60 : tline.freeze_and_flush().await?;
6492 6 :
6493 60 : if iter % 5 == 0 {
6494 12 : let (_, before_delta_file_accessed) =
6495 4018 : scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
6496 12 : tline
6497 12 : .compact(
6498 12 : &cancel,
6499 12 : {
6500 12 : let mut flags = EnumSet::new();
6501 12 : flags.insert(CompactFlags::ForceImageLayerCreation);
6502 12 : flags.insert(CompactFlags::ForceRepartition);
6503 12 : flags
6504 12 : },
6505 12 : &ctx,
6506 12 : )
6507 17249 : .await?;
6508 12 : let (_, after_delta_file_accessed) =
6509 24 : scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
6510 12 : assert!(after_delta_file_accessed < before_delta_file_accessed, "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}");
6511 6 : // Given that we already produced an image layer, there should be no delta layer needed for the scan, but still setting a low threshold there for unforeseen circumstances.
6512 12 : assert!(
6513 12 : after_delta_file_accessed <= 2,
6514 6 : "after_delta_file_accessed={after_delta_file_accessed}"
6515 6 : );
6516 48 : }
6517 6 : }
6518 6 :
6519 6 : Ok(())
6520 6 : }
6521 :
6522 : #[tokio::test]
6523 6 : async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
6524 6 : let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
6525 24 : let (tenant, ctx) = harness.load().await;
6526 6 :
6527 6 : let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
6528 6 : let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
6529 6 : let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
6530 6 :
6531 6 : let tline = tenant
6532 6 : .create_test_timeline_with_layers(
6533 6 : TIMELINE_ID,
6534 6 : Lsn(0x10),
6535 6 : DEFAULT_PG_VERSION,
6536 6 : &ctx,
6537 6 : Vec::new(), // delta layers
6538 6 : vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
6539 6 : Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
6540 6 : )
6541 33 : .await?;
6542 6 : tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
6543 6 :
6544 6 : let child = tenant
6545 6 : .branch_timeline_test_with_layers(
6546 6 : &tline,
6547 6 : NEW_TIMELINE_ID,
6548 6 : Some(Lsn(0x20)),
6549 6 : &ctx,
6550 6 : Vec::new(), // delta layers
6551 6 : vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
6552 6 : Lsn(0x30),
6553 6 : )
6554 21 : .await
6555 6 : .unwrap();
6556 6 :
6557 6 : let lsn = Lsn(0x30);
6558 6 :
6559 6 : // test vectored get on parent timeline
6560 6 : assert_eq!(
6561 12 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
6562 6 : Some(test_img("data key 1"))
6563 6 : );
6564 6 : assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
6565 9 : .await
6566 6 : .unwrap_err()
6567 6 : .is_missing_key_error());
6568 6 : assert!(
6569 6 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
6570 6 : .await
6571 6 : .unwrap_err()
6572 6 : .is_missing_key_error()
6573 6 : );
6574 6 :
6575 6 : // test vectored get on child timeline
6576 6 : assert_eq!(
6577 6 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
6578 6 : Some(test_img("data key 1"))
6579 6 : );
6580 6 : assert_eq!(
6581 12 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
6582 6 : Some(test_img("data key 2"))
6583 6 : );
6584 6 : assert!(
6585 6 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
6586 6 : .await
6587 6 : .unwrap_err()
6588 6 : .is_missing_key_error()
6589 6 : );
6590 6 :
6591 6 : Ok(())
6592 6 : }
6593 :
6594 : #[tokio::test]
6595 6 : async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
6596 6 : let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
6597 24 : let (tenant, ctx) = harness.load().await;
6598 6 :
6599 6 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
6600 6 : let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
6601 6 : let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
6602 6 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
6603 6 :
6604 6 : let tline = tenant
6605 6 : .create_test_timeline_with_layers(
6606 6 : TIMELINE_ID,
6607 6 : Lsn(0x10),
6608 6 : DEFAULT_PG_VERSION,
6609 6 : &ctx,
6610 6 : Vec::new(), // delta layers
6611 6 : vec![(Lsn(0x20), vec![(base_key, test_img("metadata key 1"))])], // image layers
6612 6 : Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
6613 6 : )
6614 33 : .await?;
6615 6 :
6616 6 : let child = tenant
6617 6 : .branch_timeline_test_with_layers(
6618 6 : &tline,
6619 6 : NEW_TIMELINE_ID,
6620 6 : Some(Lsn(0x20)),
6621 6 : &ctx,
6622 6 : Vec::new(), // delta layers
6623 6 : vec![(
6624 6 : Lsn(0x30),
6625 6 : vec![(base_key_child, test_img("metadata key 2"))],
6626 6 : )], // image layers
6627 6 : Lsn(0x30),
6628 6 : )
6629 21 : .await
6630 6 : .unwrap();
6631 6 :
6632 6 : let lsn = Lsn(0x30);
6633 6 :
6634 6 : // test vectored get on parent timeline
6635 6 : assert_eq!(
6636 12 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
6637 6 : Some(test_img("metadata key 1"))
6638 6 : );
6639 6 : assert_eq!(
6640 6 : get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
6641 6 : None
6642 6 : );
6643 6 : assert_eq!(
6644 6 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
6645 6 : None
6646 6 : );
6647 6 :
6648 6 : // test vectored get on child timeline
6649 6 : assert_eq!(
6650 6 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
6651 6 : None
6652 6 : );
6653 6 : assert_eq!(
6654 12 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
6655 6 : Some(test_img("metadata key 2"))
6656 6 : );
6657 6 : assert_eq!(
6658 6 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
6659 6 : None
6660 6 : );
6661 6 :
6662 6 : Ok(())
6663 6 : }
6664 :
6665 108 : async fn get_vectored_impl_wrapper(
6666 108 : tline: &Arc<Timeline>,
6667 108 : key: Key,
6668 108 : lsn: Lsn,
6669 108 : ctx: &RequestContext,
6670 108 : ) -> Result<Option<Bytes>, GetVectoredError> {
6671 108 : let mut reconstruct_state = ValuesReconstructState::new();
6672 108 : let mut res = tline
6673 108 : .get_vectored_impl(
6674 108 : KeySpace::single(key..key.next()),
6675 108 : lsn,
6676 108 : &mut reconstruct_state,
6677 108 : ctx,
6678 108 : )
6679 99 : .await?;
6680 90 : Ok(res.pop_last().map(|(k, v)| {
6681 54 : assert_eq!(k, key);
6682 54 : v.unwrap()
6683 90 : }))
6684 108 : }
6685 :
6686 : #[tokio::test]
6687 6 : async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
6688 6 : let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
6689 23 : let (tenant, ctx) = harness.load().await;
6690 6 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
6691 6 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
6692 6 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
6693 6 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
6694 6 :
6695 6 : // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
6696 6 : // Lsn 0x30 key0, key3, no key1+key2
6697 6 : // Lsn 0x20 key1+key2 tomestones
6698 6 : // Lsn 0x10 key1 in image, key2 in delta
6699 6 : let tline = tenant
6700 6 : .create_test_timeline_with_layers(
6701 6 : TIMELINE_ID,
6702 6 : Lsn(0x10),
6703 6 : DEFAULT_PG_VERSION,
6704 6 : &ctx,
6705 6 : // delta layers
6706 6 : vec![
6707 6 : DeltaLayerTestDesc::new_with_inferred_key_range(
6708 6 : Lsn(0x10)..Lsn(0x20),
6709 6 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
6710 6 : ),
6711 6 : DeltaLayerTestDesc::new_with_inferred_key_range(
6712 6 : Lsn(0x20)..Lsn(0x30),
6713 6 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
6714 6 : ),
6715 6 : DeltaLayerTestDesc::new_with_inferred_key_range(
6716 6 : Lsn(0x20)..Lsn(0x30),
6717 6 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
6718 6 : ),
6719 6 : ],
6720 6 : // image layers
6721 6 : vec![
6722 6 : (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
6723 6 : (
6724 6 : Lsn(0x30),
6725 6 : vec![
6726 6 : (key0, test_img("metadata key 0")),
6727 6 : (key3, test_img("metadata key 3")),
6728 6 : ],
6729 6 : ),
6730 6 : ],
6731 6 : Lsn(0x30),
6732 6 : )
6733 114 : .await?;
6734 6 :
6735 6 : let lsn = Lsn(0x30);
6736 6 : let old_lsn = Lsn(0x20);
6737 6 :
6738 6 : assert_eq!(
6739 12 : get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
6740 6 : Some(test_img("metadata key 0"))
6741 6 : );
6742 6 : assert_eq!(
6743 6 : get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
6744 6 : None,
6745 6 : );
6746 6 : assert_eq!(
6747 6 : get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
6748 6 : None,
6749 6 : );
6750 6 : assert_eq!(
6751 12 : get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
6752 6 : Some(Bytes::new()),
6753 6 : );
6754 6 : assert_eq!(
6755 12 : get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
6756 6 : Some(Bytes::new()),
6757 6 : );
6758 6 : assert_eq!(
6759 6 : get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
6760 6 : Some(test_img("metadata key 3"))
6761 6 : );
6762 6 :
6763 6 : Ok(())
6764 6 : }
6765 :
6766 : #[tokio::test]
6767 6 : async fn test_metadata_tombstone_image_creation() {
6768 6 : let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
6769 6 : .await
6770 6 : .unwrap();
6771 24 : let (tenant, ctx) = harness.load().await;
6772 6 :
6773 6 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
6774 6 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
6775 6 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
6776 6 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
6777 6 :
6778 6 : let tline = tenant
6779 6 : .create_test_timeline_with_layers(
6780 6 : TIMELINE_ID,
6781 6 : Lsn(0x10),
6782 6 : DEFAULT_PG_VERSION,
6783 6 : &ctx,
6784 6 : // delta layers
6785 6 : vec![
6786 6 : DeltaLayerTestDesc::new_with_inferred_key_range(
6787 6 : Lsn(0x10)..Lsn(0x20),
6788 6 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
6789 6 : ),
6790 6 : DeltaLayerTestDesc::new_with_inferred_key_range(
6791 6 : Lsn(0x20)..Lsn(0x30),
6792 6 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
6793 6 : ),
6794 6 : DeltaLayerTestDesc::new_with_inferred_key_range(
6795 6 : Lsn(0x20)..Lsn(0x30),
6796 6 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
6797 6 : ),
6798 6 : DeltaLayerTestDesc::new_with_inferred_key_range(
6799 6 : Lsn(0x30)..Lsn(0x40),
6800 6 : vec![
6801 6 : (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
6802 6 : (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
6803 6 : ],
6804 6 : ),
6805 6 : ],
6806 6 : // image layers
6807 6 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
6808 6 : Lsn(0x40),
6809 6 : )
6810 105 : .await
6811 6 : .unwrap();
6812 6 :
6813 6 : let cancel = CancellationToken::new();
6814 6 :
6815 6 : tline
6816 6 : .compact(
6817 6 : &cancel,
6818 6 : {
6819 6 : let mut flags = EnumSet::new();
6820 6 : flags.insert(CompactFlags::ForceImageLayerCreation);
6821 6 : flags.insert(CompactFlags::ForceRepartition);
6822 6 : flags
6823 6 : },
6824 6 : &ctx,
6825 6 : )
6826 165 : .await
6827 6 : .unwrap();
6828 6 :
6829 6 : // Image layers are created at last_record_lsn
6830 6 : let images = tline
6831 6 : .inspect_image_layers(Lsn(0x40), &ctx)
6832 24 : .await
6833 6 : .unwrap()
6834 6 : .into_iter()
6835 54 : .filter(|(k, _)| k.is_metadata_key())
6836 6 : .collect::<Vec<_>>();
6837 6 : assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
6838 6 : }
6839 :
6840 : #[tokio::test]
6841 6 : async fn test_metadata_tombstone_empty_image_creation() {
6842 6 : let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
6843 6 : .await
6844 6 : .unwrap();
6845 24 : let (tenant, ctx) = harness.load().await;
6846 6 :
6847 6 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
6848 6 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
6849 6 :
6850 6 : let tline = tenant
6851 6 : .create_test_timeline_with_layers(
6852 6 : TIMELINE_ID,
6853 6 : Lsn(0x10),
6854 6 : DEFAULT_PG_VERSION,
6855 6 : &ctx,
6856 6 : // delta layers
6857 6 : vec![
6858 6 : DeltaLayerTestDesc::new_with_inferred_key_range(
6859 6 : Lsn(0x10)..Lsn(0x20),
6860 6 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
6861 6 : ),
6862 6 : DeltaLayerTestDesc::new_with_inferred_key_range(
6863 6 : Lsn(0x20)..Lsn(0x30),
6864 6 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
6865 6 : ),
6866 6 : DeltaLayerTestDesc::new_with_inferred_key_range(
6867 6 : Lsn(0x20)..Lsn(0x30),
6868 6 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
6869 6 : ),
6870 6 : ],
6871 6 : // image layers
6872 6 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
6873 6 : Lsn(0x30),
6874 6 : )
6875 87 : .await
6876 6 : .unwrap();
6877 6 :
6878 6 : let cancel = CancellationToken::new();
6879 6 :
6880 6 : tline
6881 6 : .compact(
6882 6 : &cancel,
6883 6 : {
6884 6 : let mut flags = EnumSet::new();
6885 6 : flags.insert(CompactFlags::ForceImageLayerCreation);
6886 6 : flags.insert(CompactFlags::ForceRepartition);
6887 6 : flags
6888 6 : },
6889 6 : &ctx,
6890 6 : )
6891 129 : .await
6892 6 : .unwrap();
6893 6 :
6894 6 : // Image layers are created at last_record_lsn
6895 6 : let images = tline
6896 6 : .inspect_image_layers(Lsn(0x30), &ctx)
6897 12 : .await
6898 6 : .unwrap()
6899 6 : .into_iter()
6900 42 : .filter(|(k, _)| k.is_metadata_key())
6901 6 : .collect::<Vec<_>>();
6902 6 : assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
6903 6 : }
6904 :
6905 : #[tokio::test]
6906 6 : async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
6907 6 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
6908 24 : let (tenant, ctx) = harness.load().await;
6909 6 :
6910 306 : fn get_key(id: u32) -> Key {
6911 306 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
6912 306 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
6913 306 : key.field6 = id;
6914 306 : key
6915 306 : }
6916 6 :
6917 6 : // We create
6918 6 : // - one bottom-most image layer,
6919 6 : // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
6920 6 : // - a delta layer D2 crossing the GC horizon with data only below the horizon,
6921 6 : // - a delta layer D3 above the horizon.
6922 6 : //
6923 6 : // | D3 |
6924 6 : // | D1 |
6925 6 : // -| |-- gc horizon -----------------
6926 6 : // | | | D2 |
6927 6 : // --------- img layer ------------------
6928 6 : //
6929 6 : // What we should expact from this compaction is:
6930 6 : // | D3 |
6931 6 : // | Part of D1 |
6932 6 : // --------- img layer with D1+D2 at GC horizon------------------
6933 6 :
6934 6 : // img layer at 0x10
6935 6 : let img_layer = (0..10)
6936 60 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
6937 6 : .collect_vec();
6938 6 :
6939 6 : let delta1 = vec![
6940 6 : (
6941 6 : get_key(1),
6942 6 : Lsn(0x20),
6943 6 : Value::Image(Bytes::from("value 1@0x20")),
6944 6 : ),
6945 6 : (
6946 6 : get_key(2),
6947 6 : Lsn(0x30),
6948 6 : Value::Image(Bytes::from("value 2@0x30")),
6949 6 : ),
6950 6 : (
6951 6 : get_key(3),
6952 6 : Lsn(0x40),
6953 6 : Value::Image(Bytes::from("value 3@0x40")),
6954 6 : ),
6955 6 : ];
6956 6 : let delta2 = vec![
6957 6 : (
6958 6 : get_key(5),
6959 6 : Lsn(0x20),
6960 6 : Value::Image(Bytes::from("value 5@0x20")),
6961 6 : ),
6962 6 : (
6963 6 : get_key(6),
6964 6 : Lsn(0x20),
6965 6 : Value::Image(Bytes::from("value 6@0x20")),
6966 6 : ),
6967 6 : ];
6968 6 : let delta3 = vec![
6969 6 : (
6970 6 : get_key(8),
6971 6 : Lsn(0x48),
6972 6 : Value::Image(Bytes::from("value 8@0x48")),
6973 6 : ),
6974 6 : (
6975 6 : get_key(9),
6976 6 : Lsn(0x48),
6977 6 : Value::Image(Bytes::from("value 9@0x48")),
6978 6 : ),
6979 6 : ];
6980 6 :
6981 6 : let tline = tenant
6982 6 : .create_test_timeline_with_layers(
6983 6 : TIMELINE_ID,
6984 6 : Lsn(0x10),
6985 6 : DEFAULT_PG_VERSION,
6986 6 : &ctx,
6987 6 : vec![
6988 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
6989 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
6990 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
6991 6 : ], // delta layers
6992 6 : vec![(Lsn(0x10), img_layer)], // image layers
6993 6 : Lsn(0x50),
6994 6 : )
6995 141 : .await?;
6996 6 : {
6997 6 : // Update GC info
6998 6 : let mut guard = tline.gc_info.write().unwrap();
6999 6 : guard.cutoffs.time = Lsn(0x30);
7000 6 : guard.cutoffs.space = Lsn(0x30);
7001 6 : }
7002 6 :
7003 6 : let expected_result = [
7004 6 : Bytes::from_static(b"value 0@0x10"),
7005 6 : Bytes::from_static(b"value 1@0x20"),
7006 6 : Bytes::from_static(b"value 2@0x30"),
7007 6 : Bytes::from_static(b"value 3@0x40"),
7008 6 : Bytes::from_static(b"value 4@0x10"),
7009 6 : Bytes::from_static(b"value 5@0x20"),
7010 6 : Bytes::from_static(b"value 6@0x20"),
7011 6 : Bytes::from_static(b"value 7@0x10"),
7012 6 : Bytes::from_static(b"value 8@0x48"),
7013 6 : Bytes::from_static(b"value 9@0x48"),
7014 6 : ];
7015 6 :
7016 60 : for (idx, expected) in expected_result.iter().enumerate() {
7017 60 : assert_eq!(
7018 60 : tline
7019 60 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
7020 69 : .await
7021 60 : .unwrap(),
7022 6 : expected
7023 6 : );
7024 6 : }
7025 6 :
7026 6 : let cancel = CancellationToken::new();
7027 6 : tline
7028 6 : .compact_with_gc(&cancel, EnumSet::new(), &ctx)
7029 159 : .await
7030 6 : .unwrap();
7031 6 :
7032 60 : for (idx, expected) in expected_result.iter().enumerate() {
7033 60 : assert_eq!(
7034 60 : tline
7035 60 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
7036 48 : .await
7037 60 : .unwrap(),
7038 6 : expected
7039 6 : );
7040 6 : }
7041 6 :
7042 6 : // Check if the image layer at the GC horizon contains exactly what we want
7043 6 : let image_at_gc_horizon = tline
7044 6 : .inspect_image_layers(Lsn(0x30), &ctx)
7045 6 : .await
7046 6 : .unwrap()
7047 6 : .into_iter()
7048 102 : .filter(|(k, _)| k.is_metadata_key())
7049 6 : .collect::<Vec<_>>();
7050 6 :
7051 6 : assert_eq!(image_at_gc_horizon.len(), 10);
7052 6 : let expected_result = [
7053 6 : Bytes::from_static(b"value 0@0x10"),
7054 6 : Bytes::from_static(b"value 1@0x20"),
7055 6 : Bytes::from_static(b"value 2@0x30"),
7056 6 : Bytes::from_static(b"value 3@0x10"),
7057 6 : Bytes::from_static(b"value 4@0x10"),
7058 6 : Bytes::from_static(b"value 5@0x20"),
7059 6 : Bytes::from_static(b"value 6@0x20"),
7060 6 : Bytes::from_static(b"value 7@0x10"),
7061 6 : Bytes::from_static(b"value 8@0x10"),
7062 6 : Bytes::from_static(b"value 9@0x10"),
7063 6 : ];
7064 66 : for idx in 0..10 {
7065 60 : assert_eq!(
7066 60 : image_at_gc_horizon[idx],
7067 60 : (get_key(idx as u32), expected_result[idx].clone())
7068 60 : );
7069 6 : }
7070 6 :
7071 6 : // Check if old layers are removed / new layers have the expected LSN
7072 6 : let mut all_layers = tline.inspect_historic_layers().await.unwrap();
7073 12 : all_layers.sort_by(|k1, k2| {
7074 12 : (
7075 12 : k1.is_delta,
7076 12 : k1.key_range.start,
7077 12 : k1.key_range.end,
7078 12 : k1.lsn_range.start,
7079 12 : k1.lsn_range.end,
7080 12 : )
7081 12 : .cmp(&(
7082 12 : k2.is_delta,
7083 12 : k2.key_range.start,
7084 12 : k2.key_range.end,
7085 12 : k2.lsn_range.start,
7086 12 : k2.lsn_range.end,
7087 12 : ))
7088 12 : });
7089 6 : assert_eq!(
7090 6 : all_layers,
7091 6 : vec![
7092 6 : // Image layer at GC horizon
7093 6 : PersistentLayerKey {
7094 6 : key_range: Key::MIN..Key::MAX,
7095 6 : lsn_range: Lsn(0x30)..Lsn(0x31),
7096 6 : is_delta: false
7097 6 : },
7098 6 : // The delta layer below the horizon
7099 6 : PersistentLayerKey {
7100 6 : key_range: get_key(3)..get_key(4),
7101 6 : lsn_range: Lsn(0x30)..Lsn(0x48),
7102 6 : is_delta: true
7103 6 : },
7104 6 : // The delta3 layer that should not be picked for the compaction
7105 6 : PersistentLayerKey {
7106 6 : key_range: get_key(8)..get_key(10),
7107 6 : lsn_range: Lsn(0x48)..Lsn(0x50),
7108 6 : is_delta: true
7109 6 : }
7110 6 : ]
7111 6 : );
7112 6 :
7113 6 : // increase GC horizon and compact again
7114 6 : {
7115 6 : // Update GC info
7116 6 : let mut guard = tline.gc_info.write().unwrap();
7117 6 : guard.cutoffs.time = Lsn(0x40);
7118 6 : guard.cutoffs.space = Lsn(0x40);
7119 6 : }
7120 6 : tline
7121 6 : .compact_with_gc(&cancel, EnumSet::new(), &ctx)
7122 126 : .await
7123 6 : .unwrap();
7124 6 :
7125 6 : Ok(())
7126 6 : }
7127 :
7128 : #[tokio::test]
7129 6 : async fn test_neon_test_record() -> anyhow::Result<()> {
7130 6 : let harness = TenantHarness::create("test_neon_test_record").await?;
7131 24 : let (tenant, ctx) = harness.load().await;
7132 6 :
7133 72 : fn get_key(id: u32) -> Key {
7134 72 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
7135 72 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
7136 72 : key.field6 = id;
7137 72 : key
7138 72 : }
7139 6 :
7140 6 : let delta1 = vec![
7141 6 : (
7142 6 : get_key(1),
7143 6 : Lsn(0x20),
7144 6 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
7145 6 : ),
7146 6 : (
7147 6 : get_key(1),
7148 6 : Lsn(0x30),
7149 6 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
7150 6 : ),
7151 6 : (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
7152 6 : (
7153 6 : get_key(2),
7154 6 : Lsn(0x20),
7155 6 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
7156 6 : ),
7157 6 : (
7158 6 : get_key(2),
7159 6 : Lsn(0x30),
7160 6 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
7161 6 : ),
7162 6 : (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
7163 6 : (
7164 6 : get_key(3),
7165 6 : Lsn(0x20),
7166 6 : Value::WalRecord(NeonWalRecord::wal_clear()),
7167 6 : ),
7168 6 : (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
7169 6 : (
7170 6 : get_key(4),
7171 6 : Lsn(0x20),
7172 6 : Value::WalRecord(NeonWalRecord::wal_init()),
7173 6 : ),
7174 6 : ];
7175 6 : let image1 = vec![(get_key(1), "0x10".into())];
7176 6 :
7177 6 : let tline = tenant
7178 6 : .create_test_timeline_with_layers(
7179 6 : TIMELINE_ID,
7180 6 : Lsn(0x10),
7181 6 : DEFAULT_PG_VERSION,
7182 6 : &ctx,
7183 6 : vec![DeltaLayerTestDesc::new_with_inferred_key_range(
7184 6 : Lsn(0x10)..Lsn(0x40),
7185 6 : delta1,
7186 6 : )], // delta layers
7187 6 : vec![(Lsn(0x10), image1)], // image layers
7188 6 : Lsn(0x50),
7189 6 : )
7190 51 : .await?;
7191 6 :
7192 6 : assert_eq!(
7193 24 : tline.get(get_key(1), Lsn(0x50), &ctx).await?,
7194 6 : Bytes::from_static(b"0x10,0x20,0x30")
7195 6 : );
7196 6 : assert_eq!(
7197 6 : tline.get(get_key(2), Lsn(0x50), &ctx).await?,
7198 6 : Bytes::from_static(b"0x10,0x20,0x30")
7199 6 : );
7200 6 :
7201 6 : // Need to remove the limit of "Neon WAL redo requires base image".
7202 6 :
7203 6 : // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
7204 6 : // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
7205 6 :
7206 6 : Ok(())
7207 6 : }
7208 :
7209 : #[tokio::test]
7210 6 : async fn test_lsn_lease() -> anyhow::Result<()> {
7211 24 : let (tenant, ctx) = TenantHarness::create("test_lsn_lease").await?.load().await;
7212 6 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7213 6 :
7214 6 : let end_lsn = Lsn(0x100);
7215 6 : let image_layers = (0x20..=0x90)
7216 6 : .step_by(0x10)
7217 48 : .map(|n| {
7218 48 : (
7219 48 : Lsn(n),
7220 48 : vec![(key, test_img(&format!("data key at {:x}", n)))],
7221 48 : )
7222 48 : })
7223 6 : .collect();
7224 6 :
7225 6 : let timeline = tenant
7226 6 : .create_test_timeline_with_layers(
7227 6 : TIMELINE_ID,
7228 6 : Lsn(0x10),
7229 6 : DEFAULT_PG_VERSION,
7230 6 : &ctx,
7231 6 : Vec::new(),
7232 6 : image_layers,
7233 6 : end_lsn,
7234 6 : )
7235 180 : .await?;
7236 6 :
7237 6 : let leased_lsns = [0x30, 0x50, 0x70];
7238 6 : let mut leases = Vec::new();
7239 18 : let _: anyhow::Result<_> = leased_lsns.iter().try_for_each(|n| {
7240 18 : leases.push(timeline.make_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)?);
7241 18 : Ok(())
7242 18 : });
7243 6 :
7244 6 : // Renewing with shorter lease should not change the lease.
7245 6 : let updated_lease_0 =
7246 6 : timeline.make_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)?;
7247 6 : assert_eq!(updated_lease_0.valid_until, leases[0].valid_until);
7248 6 :
7249 6 : // Renewing with a long lease should renew lease with later expiration time.
7250 6 : let updated_lease_1 = timeline.make_lsn_lease(
7251 6 : Lsn(leased_lsns[1]),
7252 6 : timeline.get_lsn_lease_length() * 2,
7253 6 : &ctx,
7254 6 : )?;
7255 6 :
7256 6 : assert!(updated_lease_1.valid_until > leases[1].valid_until);
7257 6 :
7258 6 : // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
7259 6 : info!(
7260 6 : "latest_gc_cutoff_lsn: {}",
7261 0 : *timeline.get_latest_gc_cutoff_lsn()
7262 6 : );
7263 6 : timeline.force_set_disk_consistent_lsn(end_lsn);
7264 6 :
7265 6 : let res = tenant
7266 6 : .gc_iteration(
7267 6 : Some(TIMELINE_ID),
7268 6 : 0,
7269 6 : Duration::ZERO,
7270 6 : &CancellationToken::new(),
7271 6 : &ctx,
7272 6 : )
7273 6 : .await?;
7274 6 :
7275 6 : // Keeping everything <= Lsn(0x80) b/c leases:
7276 6 : // 0/10: initdb layer
7277 6 : // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
7278 6 : assert_eq!(res.layers_needed_by_leases, 7);
7279 6 : // Keeping 0/90 b/c it is the latest layer.
7280 6 : assert_eq!(res.layers_not_updated, 1);
7281 6 : // Removed 0/80.
7282 6 : assert_eq!(res.layers_removed, 1);
7283 6 :
7284 6 : // Make lease on a already GC-ed LSN.
7285 6 : // 0/80 does not have a valid lease + is below latest_gc_cutoff
7286 6 : assert!(Lsn(0x80) < *timeline.get_latest_gc_cutoff_lsn());
7287 6 : let res = timeline.make_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx);
7288 6 : assert!(res.is_err());
7289 6 :
7290 6 : // Should still be able to renew a currently valid lease
7291 6 : // Assumption: original lease to is still valid for 0/50.
7292 6 : let _ =
7293 6 : timeline.make_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)?;
7294 6 :
7295 6 : Ok(())
7296 6 : }
7297 :
7298 : #[tokio::test]
7299 6 : async fn test_simple_bottom_most_compaction_deltas() -> anyhow::Result<()> {
7300 6 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_deltas").await?;
7301 24 : let (tenant, ctx) = harness.load().await;
7302 6 :
7303 354 : fn get_key(id: u32) -> Key {
7304 354 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
7305 354 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
7306 354 : key.field6 = id;
7307 354 : key
7308 354 : }
7309 6 :
7310 6 : // We create
7311 6 : // - one bottom-most image layer,
7312 6 : // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
7313 6 : // - a delta layer D2 crossing the GC horizon with data only below the horizon,
7314 6 : // - a delta layer D3 above the horizon.
7315 6 : //
7316 6 : // | D3 |
7317 6 : // | D1 |
7318 6 : // -| |-- gc horizon -----------------
7319 6 : // | | | D2 |
7320 6 : // --------- img layer ------------------
7321 6 : //
7322 6 : // What we should expact from this compaction is:
7323 6 : // | D3 |
7324 6 : // | Part of D1 |
7325 6 : // --------- img layer with D1+D2 at GC horizon------------------
7326 6 :
7327 6 : // img layer at 0x10
7328 6 : let img_layer = (0..10)
7329 60 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
7330 6 : .collect_vec();
7331 6 :
7332 6 : let delta1 = vec![
7333 6 : (
7334 6 : get_key(1),
7335 6 : Lsn(0x20),
7336 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
7337 6 : ),
7338 6 : (
7339 6 : get_key(2),
7340 6 : Lsn(0x30),
7341 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
7342 6 : ),
7343 6 : (
7344 6 : get_key(3),
7345 6 : Lsn(0x28),
7346 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
7347 6 : ),
7348 6 : (
7349 6 : get_key(3),
7350 6 : Lsn(0x30),
7351 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
7352 6 : ),
7353 6 : (
7354 6 : get_key(3),
7355 6 : Lsn(0x40),
7356 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
7357 6 : ),
7358 6 : ];
7359 6 : let delta2 = vec![
7360 6 : (
7361 6 : get_key(5),
7362 6 : Lsn(0x20),
7363 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
7364 6 : ),
7365 6 : (
7366 6 : get_key(6),
7367 6 : Lsn(0x20),
7368 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
7369 6 : ),
7370 6 : ];
7371 6 : let delta3 = vec![
7372 6 : (
7373 6 : get_key(8),
7374 6 : Lsn(0x48),
7375 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
7376 6 : ),
7377 6 : (
7378 6 : get_key(9),
7379 6 : Lsn(0x48),
7380 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
7381 6 : ),
7382 6 : ];
7383 6 :
7384 6 : let tline = tenant
7385 6 : .create_test_timeline_with_layers(
7386 6 : TIMELINE_ID,
7387 6 : Lsn(0x10),
7388 6 : DEFAULT_PG_VERSION,
7389 6 : &ctx,
7390 6 : vec![
7391 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
7392 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
7393 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
7394 6 : ], // delta layers
7395 6 : vec![(Lsn(0x10), img_layer)], // image layers
7396 6 : Lsn(0x50),
7397 6 : )
7398 141 : .await?;
7399 6 : {
7400 6 : // Update GC info
7401 6 : let mut guard = tline.gc_info.write().unwrap();
7402 6 : *guard = GcInfo {
7403 6 : retain_lsns: vec![],
7404 6 : cutoffs: GcCutoffs {
7405 6 : time: Lsn(0x30),
7406 6 : space: Lsn(0x30),
7407 6 : },
7408 6 : leases: Default::default(),
7409 6 : within_ancestor_pitr: false,
7410 6 : };
7411 6 : }
7412 6 :
7413 6 : let expected_result = [
7414 6 : Bytes::from_static(b"value 0@0x10"),
7415 6 : Bytes::from_static(b"value 1@0x10@0x20"),
7416 6 : Bytes::from_static(b"value 2@0x10@0x30"),
7417 6 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
7418 6 : Bytes::from_static(b"value 4@0x10"),
7419 6 : Bytes::from_static(b"value 5@0x10@0x20"),
7420 6 : Bytes::from_static(b"value 6@0x10@0x20"),
7421 6 : Bytes::from_static(b"value 7@0x10"),
7422 6 : Bytes::from_static(b"value 8@0x10@0x48"),
7423 6 : Bytes::from_static(b"value 9@0x10@0x48"),
7424 6 : ];
7425 6 :
7426 6 : let expected_result_at_gc_horizon = [
7427 6 : Bytes::from_static(b"value 0@0x10"),
7428 6 : Bytes::from_static(b"value 1@0x10@0x20"),
7429 6 : Bytes::from_static(b"value 2@0x10@0x30"),
7430 6 : Bytes::from_static(b"value 3@0x10@0x28@0x30"),
7431 6 : Bytes::from_static(b"value 4@0x10"),
7432 6 : Bytes::from_static(b"value 5@0x10@0x20"),
7433 6 : Bytes::from_static(b"value 6@0x10@0x20"),
7434 6 : Bytes::from_static(b"value 7@0x10"),
7435 6 : Bytes::from_static(b"value 8@0x10"),
7436 6 : Bytes::from_static(b"value 9@0x10"),
7437 6 : ];
7438 6 :
7439 66 : for idx in 0..10 {
7440 60 : assert_eq!(
7441 60 : tline
7442 60 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
7443 93 : .await
7444 60 : .unwrap(),
7445 60 : &expected_result[idx]
7446 6 : );
7447 60 : assert_eq!(
7448 60 : tline
7449 60 : .get(get_key(idx as u32), Lsn(0x30), &ctx)
7450 45 : .await
7451 60 : .unwrap(),
7452 60 : &expected_result_at_gc_horizon[idx]
7453 6 : );
7454 6 : }
7455 6 :
7456 6 : let cancel = CancellationToken::new();
7457 6 : tline
7458 6 : .compact_with_gc(&cancel, EnumSet::new(), &ctx)
7459 156 : .await
7460 6 : .unwrap();
7461 6 :
7462 66 : for idx in 0..10 {
7463 60 : assert_eq!(
7464 60 : tline
7465 60 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
7466 60 : .await
7467 60 : .unwrap(),
7468 60 : &expected_result[idx]
7469 6 : );
7470 60 : assert_eq!(
7471 60 : tline
7472 60 : .get(get_key(idx as u32), Lsn(0x30), &ctx)
7473 30 : .await
7474 60 : .unwrap(),
7475 60 : &expected_result_at_gc_horizon[idx]
7476 6 : );
7477 6 : }
7478 6 :
7479 6 : // increase GC horizon and compact again
7480 6 : {
7481 6 : // Update GC info
7482 6 : let mut guard = tline.gc_info.write().unwrap();
7483 6 : guard.cutoffs.time = Lsn(0x40);
7484 6 : guard.cutoffs.space = Lsn(0x40);
7485 6 : }
7486 6 : tline
7487 6 : .compact_with_gc(&cancel, EnumSet::new(), &ctx)
7488 126 : .await
7489 6 : .unwrap();
7490 6 :
7491 6 : Ok(())
7492 6 : }
7493 :
7494 : #[tokio::test]
7495 6 : async fn test_generate_key_retention() -> anyhow::Result<()> {
7496 6 : let harness = TenantHarness::create("test_generate_key_retention").await?;
7497 24 : let (tenant, ctx) = harness.load().await;
7498 6 : let tline = tenant
7499 6 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7500 12 : .await?;
7501 6 : tline.force_advance_lsn(Lsn(0x70));
7502 6 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7503 6 : let history = vec![
7504 6 : (
7505 6 : key,
7506 6 : Lsn(0x10),
7507 6 : Value::Image(Bytes::copy_from_slice(b"0x10")),
7508 6 : ),
7509 6 : (
7510 6 : key,
7511 6 : Lsn(0x20),
7512 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
7513 6 : ),
7514 6 : (
7515 6 : key,
7516 6 : Lsn(0x30),
7517 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
7518 6 : ),
7519 6 : (
7520 6 : key,
7521 6 : Lsn(0x40),
7522 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
7523 6 : ),
7524 6 : (
7525 6 : key,
7526 6 : Lsn(0x50),
7527 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
7528 6 : ),
7529 6 : (
7530 6 : key,
7531 6 : Lsn(0x60),
7532 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
7533 6 : ),
7534 6 : (
7535 6 : key,
7536 6 : Lsn(0x70),
7537 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
7538 6 : ),
7539 6 : (
7540 6 : key,
7541 6 : Lsn(0x80),
7542 6 : Value::Image(Bytes::copy_from_slice(
7543 6 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
7544 6 : )),
7545 6 : ),
7546 6 : (
7547 6 : key,
7548 6 : Lsn(0x90),
7549 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
7550 6 : ),
7551 6 : ];
7552 6 : let res = tline
7553 6 : .generate_key_retention(
7554 6 : key,
7555 6 : &history,
7556 6 : Lsn(0x60),
7557 6 : &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
7558 6 : 3,
7559 6 : None,
7560 6 : )
7561 6 : .await
7562 6 : .unwrap();
7563 6 : let expected_res = KeyHistoryRetention {
7564 6 : below_horizon: vec![
7565 6 : (
7566 6 : Lsn(0x20),
7567 6 : KeyLogAtLsn(vec![(
7568 6 : Lsn(0x20),
7569 6 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20")),
7570 6 : )]),
7571 6 : ),
7572 6 : (
7573 6 : Lsn(0x40),
7574 6 : KeyLogAtLsn(vec![
7575 6 : (
7576 6 : Lsn(0x30),
7577 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
7578 6 : ),
7579 6 : (
7580 6 : Lsn(0x40),
7581 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
7582 6 : ),
7583 6 : ]),
7584 6 : ),
7585 6 : (
7586 6 : Lsn(0x50),
7587 6 : KeyLogAtLsn(vec![(
7588 6 : Lsn(0x50),
7589 6 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
7590 6 : )]),
7591 6 : ),
7592 6 : (
7593 6 : Lsn(0x60),
7594 6 : KeyLogAtLsn(vec![(
7595 6 : Lsn(0x60),
7596 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
7597 6 : )]),
7598 6 : ),
7599 6 : ],
7600 6 : above_horizon: KeyLogAtLsn(vec![
7601 6 : (
7602 6 : Lsn(0x70),
7603 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
7604 6 : ),
7605 6 : (
7606 6 : Lsn(0x80),
7607 6 : Value::Image(Bytes::copy_from_slice(
7608 6 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
7609 6 : )),
7610 6 : ),
7611 6 : (
7612 6 : Lsn(0x90),
7613 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
7614 6 : ),
7615 6 : ]),
7616 6 : };
7617 6 : assert_eq!(res, expected_res);
7618 6 :
7619 6 : // We expect GC-compaction to run with the original GC. This would create a situation that
7620 6 : // the original GC algorithm removes some delta layers b/c there are full image coverage,
7621 6 : // therefore causing some keys to have an incomplete history below the lowest retain LSN.
7622 6 : // For example, we have
7623 6 : // ```plain
7624 6 : // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
7625 6 : // ```
7626 6 : // Now the GC horizon moves up, and we have
7627 6 : // ```plain
7628 6 : // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
7629 6 : // ```
7630 6 : // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
7631 6 : // We will end up with
7632 6 : // ```plain
7633 6 : // delta @ 0x30, image @ 0x40 (gc_horizon)
7634 6 : // ```
7635 6 : // Now we run the GC-compaction, and this key does not have a full history.
7636 6 : // We should be able to handle this partial history and drop everything before the
7637 6 : // gc_horizon image.
7638 6 :
7639 6 : let history = vec![
7640 6 : (
7641 6 : key,
7642 6 : Lsn(0x20),
7643 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
7644 6 : ),
7645 6 : (
7646 6 : key,
7647 6 : Lsn(0x30),
7648 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
7649 6 : ),
7650 6 : (
7651 6 : key,
7652 6 : Lsn(0x40),
7653 6 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
7654 6 : ),
7655 6 : (
7656 6 : key,
7657 6 : Lsn(0x50),
7658 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
7659 6 : ),
7660 6 : (
7661 6 : key,
7662 6 : Lsn(0x60),
7663 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
7664 6 : ),
7665 6 : (
7666 6 : key,
7667 6 : Lsn(0x70),
7668 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
7669 6 : ),
7670 6 : (
7671 6 : key,
7672 6 : Lsn(0x80),
7673 6 : Value::Image(Bytes::copy_from_slice(
7674 6 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
7675 6 : )),
7676 6 : ),
7677 6 : (
7678 6 : key,
7679 6 : Lsn(0x90),
7680 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
7681 6 : ),
7682 6 : ];
7683 6 : let res = tline
7684 6 : .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
7685 6 : .await
7686 6 : .unwrap();
7687 6 : let expected_res = KeyHistoryRetention {
7688 6 : below_horizon: vec![
7689 6 : (
7690 6 : Lsn(0x40),
7691 6 : KeyLogAtLsn(vec![(
7692 6 : Lsn(0x40),
7693 6 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
7694 6 : )]),
7695 6 : ),
7696 6 : (
7697 6 : Lsn(0x50),
7698 6 : KeyLogAtLsn(vec![(
7699 6 : Lsn(0x50),
7700 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
7701 6 : )]),
7702 6 : ),
7703 6 : (
7704 6 : Lsn(0x60),
7705 6 : KeyLogAtLsn(vec![(
7706 6 : Lsn(0x60),
7707 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
7708 6 : )]),
7709 6 : ),
7710 6 : ],
7711 6 : above_horizon: KeyLogAtLsn(vec![
7712 6 : (
7713 6 : Lsn(0x70),
7714 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
7715 6 : ),
7716 6 : (
7717 6 : Lsn(0x80),
7718 6 : Value::Image(Bytes::copy_from_slice(
7719 6 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
7720 6 : )),
7721 6 : ),
7722 6 : (
7723 6 : Lsn(0x90),
7724 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
7725 6 : ),
7726 6 : ]),
7727 6 : };
7728 6 : assert_eq!(res, expected_res);
7729 6 :
7730 6 : // In case of branch compaction, the branch itself does not have the full history, and we need to provide
7731 6 : // the ancestor image in the test case.
7732 6 :
7733 6 : let history = vec![
7734 6 : (
7735 6 : key,
7736 6 : Lsn(0x20),
7737 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
7738 6 : ),
7739 6 : (
7740 6 : key,
7741 6 : Lsn(0x30),
7742 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
7743 6 : ),
7744 6 : (
7745 6 : key,
7746 6 : Lsn(0x40),
7747 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
7748 6 : ),
7749 6 : (
7750 6 : key,
7751 6 : Lsn(0x70),
7752 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
7753 6 : ),
7754 6 : ];
7755 6 : let res = tline
7756 6 : .generate_key_retention(
7757 6 : key,
7758 6 : &history,
7759 6 : Lsn(0x60),
7760 6 : &[],
7761 6 : 3,
7762 6 : Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
7763 6 : )
7764 6 : .await
7765 6 : .unwrap();
7766 6 : let expected_res = KeyHistoryRetention {
7767 6 : below_horizon: vec![(
7768 6 : Lsn(0x60),
7769 6 : KeyLogAtLsn(vec![(
7770 6 : Lsn(0x60),
7771 6 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
7772 6 : )]),
7773 6 : )],
7774 6 : above_horizon: KeyLogAtLsn(vec![(
7775 6 : Lsn(0x70),
7776 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
7777 6 : )]),
7778 6 : };
7779 6 : assert_eq!(res, expected_res);
7780 6 :
7781 6 : let history = vec![
7782 6 : (
7783 6 : key,
7784 6 : Lsn(0x20),
7785 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
7786 6 : ),
7787 6 : (
7788 6 : key,
7789 6 : Lsn(0x40),
7790 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
7791 6 : ),
7792 6 : (
7793 6 : key,
7794 6 : Lsn(0x60),
7795 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
7796 6 : ),
7797 6 : (
7798 6 : key,
7799 6 : Lsn(0x70),
7800 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
7801 6 : ),
7802 6 : ];
7803 6 : let res = tline
7804 6 : .generate_key_retention(
7805 6 : key,
7806 6 : &history,
7807 6 : Lsn(0x60),
7808 6 : &[Lsn(0x30)],
7809 6 : 3,
7810 6 : Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
7811 6 : )
7812 6 : .await
7813 6 : .unwrap();
7814 6 : let expected_res = KeyHistoryRetention {
7815 6 : below_horizon: vec![
7816 6 : (
7817 6 : Lsn(0x30),
7818 6 : KeyLogAtLsn(vec![(
7819 6 : Lsn(0x20),
7820 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
7821 6 : )]),
7822 6 : ),
7823 6 : (
7824 6 : Lsn(0x60),
7825 6 : KeyLogAtLsn(vec![(
7826 6 : Lsn(0x60),
7827 6 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
7828 6 : )]),
7829 6 : ),
7830 6 : ],
7831 6 : above_horizon: KeyLogAtLsn(vec![(
7832 6 : Lsn(0x70),
7833 6 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
7834 6 : )]),
7835 6 : };
7836 6 : assert_eq!(res, expected_res);
7837 6 :
7838 6 : Ok(())
7839 6 : }
7840 :
7841 : #[tokio::test]
7842 6 : async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
7843 6 : let harness =
7844 6 : TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
7845 23 : let (tenant, ctx) = harness.load().await;
7846 6 :
7847 1554 : fn get_key(id: u32) -> Key {
7848 1554 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
7849 1554 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
7850 1554 : key.field6 = id;
7851 1554 : key
7852 1554 : }
7853 6 :
7854 6 : let img_layer = (0..10)
7855 60 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
7856 6 : .collect_vec();
7857 6 :
7858 6 : let delta1 = vec![
7859 6 : (
7860 6 : get_key(1),
7861 6 : Lsn(0x20),
7862 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
7863 6 : ),
7864 6 : (
7865 6 : get_key(2),
7866 6 : Lsn(0x30),
7867 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
7868 6 : ),
7869 6 : (
7870 6 : get_key(3),
7871 6 : Lsn(0x28),
7872 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
7873 6 : ),
7874 6 : (
7875 6 : get_key(3),
7876 6 : Lsn(0x30),
7877 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
7878 6 : ),
7879 6 : (
7880 6 : get_key(3),
7881 6 : Lsn(0x40),
7882 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
7883 6 : ),
7884 6 : ];
7885 6 : let delta2 = vec![
7886 6 : (
7887 6 : get_key(5),
7888 6 : Lsn(0x20),
7889 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
7890 6 : ),
7891 6 : (
7892 6 : get_key(6),
7893 6 : Lsn(0x20),
7894 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
7895 6 : ),
7896 6 : ];
7897 6 : let delta3 = vec![
7898 6 : (
7899 6 : get_key(8),
7900 6 : Lsn(0x48),
7901 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
7902 6 : ),
7903 6 : (
7904 6 : get_key(9),
7905 6 : Lsn(0x48),
7906 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
7907 6 : ),
7908 6 : ];
7909 6 :
7910 6 : let tline = tenant
7911 6 : .create_test_timeline_with_layers(
7912 6 : TIMELINE_ID,
7913 6 : Lsn(0x10),
7914 6 : DEFAULT_PG_VERSION,
7915 6 : &ctx,
7916 6 : vec![
7917 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
7918 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
7919 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
7920 6 : ], // delta layers
7921 6 : vec![(Lsn(0x10), img_layer)], // image layers
7922 6 : Lsn(0x50),
7923 6 : )
7924 141 : .await?;
7925 6 : {
7926 6 : // Update GC info
7927 6 : let mut guard = tline.gc_info.write().unwrap();
7928 6 : *guard = GcInfo {
7929 6 : retain_lsns: vec![
7930 6 : (Lsn(0x10), tline.timeline_id),
7931 6 : (Lsn(0x20), tline.timeline_id),
7932 6 : ],
7933 6 : cutoffs: GcCutoffs {
7934 6 : time: Lsn(0x30),
7935 6 : space: Lsn(0x30),
7936 6 : },
7937 6 : leases: Default::default(),
7938 6 : within_ancestor_pitr: false,
7939 6 : };
7940 6 : }
7941 6 :
7942 6 : let expected_result = [
7943 6 : Bytes::from_static(b"value 0@0x10"),
7944 6 : Bytes::from_static(b"value 1@0x10@0x20"),
7945 6 : Bytes::from_static(b"value 2@0x10@0x30"),
7946 6 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
7947 6 : Bytes::from_static(b"value 4@0x10"),
7948 6 : Bytes::from_static(b"value 5@0x10@0x20"),
7949 6 : Bytes::from_static(b"value 6@0x10@0x20"),
7950 6 : Bytes::from_static(b"value 7@0x10"),
7951 6 : Bytes::from_static(b"value 8@0x10@0x48"),
7952 6 : Bytes::from_static(b"value 9@0x10@0x48"),
7953 6 : ];
7954 6 :
7955 6 : let expected_result_at_gc_horizon = [
7956 6 : Bytes::from_static(b"value 0@0x10"),
7957 6 : Bytes::from_static(b"value 1@0x10@0x20"),
7958 6 : Bytes::from_static(b"value 2@0x10@0x30"),
7959 6 : Bytes::from_static(b"value 3@0x10@0x28@0x30"),
7960 6 : Bytes::from_static(b"value 4@0x10"),
7961 6 : Bytes::from_static(b"value 5@0x10@0x20"),
7962 6 : Bytes::from_static(b"value 6@0x10@0x20"),
7963 6 : Bytes::from_static(b"value 7@0x10"),
7964 6 : Bytes::from_static(b"value 8@0x10"),
7965 6 : Bytes::from_static(b"value 9@0x10"),
7966 6 : ];
7967 6 :
7968 6 : let expected_result_at_lsn_20 = [
7969 6 : Bytes::from_static(b"value 0@0x10"),
7970 6 : Bytes::from_static(b"value 1@0x10@0x20"),
7971 6 : Bytes::from_static(b"value 2@0x10"),
7972 6 : Bytes::from_static(b"value 3@0x10"),
7973 6 : Bytes::from_static(b"value 4@0x10"),
7974 6 : Bytes::from_static(b"value 5@0x10@0x20"),
7975 6 : Bytes::from_static(b"value 6@0x10@0x20"),
7976 6 : Bytes::from_static(b"value 7@0x10"),
7977 6 : Bytes::from_static(b"value 8@0x10"),
7978 6 : Bytes::from_static(b"value 9@0x10"),
7979 6 : ];
7980 6 :
7981 6 : let expected_result_at_lsn_10 = [
7982 6 : Bytes::from_static(b"value 0@0x10"),
7983 6 : Bytes::from_static(b"value 1@0x10"),
7984 6 : Bytes::from_static(b"value 2@0x10"),
7985 6 : Bytes::from_static(b"value 3@0x10"),
7986 6 : Bytes::from_static(b"value 4@0x10"),
7987 6 : Bytes::from_static(b"value 5@0x10"),
7988 6 : Bytes::from_static(b"value 6@0x10"),
7989 6 : Bytes::from_static(b"value 7@0x10"),
7990 6 : Bytes::from_static(b"value 8@0x10"),
7991 6 : Bytes::from_static(b"value 9@0x10"),
7992 6 : ];
7993 6 :
7994 36 : let verify_result = || async {
7995 36 : let gc_horizon = {
7996 36 : let gc_info = tline.gc_info.read().unwrap();
7997 36 : gc_info.cutoffs.time
7998 6 : };
7999 396 : for idx in 0..10 {
8000 360 : assert_eq!(
8001 360 : tline
8002 360 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8003 369 : .await
8004 360 : .unwrap(),
8005 360 : &expected_result[idx]
8006 6 : );
8007 360 : assert_eq!(
8008 360 : tline
8009 360 : .get(get_key(idx as u32), gc_horizon, &ctx)
8010 288 : .await
8011 360 : .unwrap(),
8012 360 : &expected_result_at_gc_horizon[idx]
8013 6 : );
8014 360 : assert_eq!(
8015 360 : tline
8016 360 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
8017 243 : .await
8018 360 : .unwrap(),
8019 360 : &expected_result_at_lsn_20[idx]
8020 6 : );
8021 360 : assert_eq!(
8022 360 : tline
8023 360 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
8024 186 : .await
8025 360 : .unwrap(),
8026 360 : &expected_result_at_lsn_10[idx]
8027 6 : );
8028 6 : }
8029 72 : };
8030 6 :
8031 210 : verify_result().await;
8032 6 :
8033 6 : let cancel = CancellationToken::new();
8034 6 : let mut dryrun_flags = EnumSet::new();
8035 6 : dryrun_flags.insert(CompactFlags::DryRun);
8036 6 :
8037 6 : tline
8038 6 : .compact_with_gc(&cancel, dryrun_flags, &ctx)
8039 129 : .await
8040 6 : .unwrap();
8041 6 : // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
8042 6 : // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
8043 171 : verify_result().await;
8044 6 :
8045 6 : tline
8046 6 : .compact_with_gc(&cancel, EnumSet::new(), &ctx)
8047 150 : .await
8048 6 : .unwrap();
8049 192 : verify_result().await;
8050 6 :
8051 6 : // compact again
8052 6 : tline
8053 6 : .compact_with_gc(&cancel, EnumSet::new(), &ctx)
8054 114 : .await
8055 6 : .unwrap();
8056 171 : verify_result().await;
8057 6 :
8058 6 : // increase GC horizon and compact again
8059 6 : {
8060 6 : // Update GC info
8061 6 : let mut guard = tline.gc_info.write().unwrap();
8062 6 : guard.cutoffs.time = Lsn(0x38);
8063 6 : guard.cutoffs.space = Lsn(0x38);
8064 6 : }
8065 6 : tline
8066 6 : .compact_with_gc(&cancel, EnumSet::new(), &ctx)
8067 117 : .await
8068 6 : .unwrap();
8069 171 : verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
8070 6 :
8071 6 : // not increasing the GC horizon and compact again
8072 6 : tline
8073 6 : .compact_with_gc(&cancel, EnumSet::new(), &ctx)
8074 117 : .await
8075 6 : .unwrap();
8076 171 : verify_result().await;
8077 6 :
8078 6 : Ok(())
8079 6 : }
8080 :
8081 : #[tokio::test]
8082 6 : async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
8083 6 : {
8084 6 : let harness =
8085 6 : TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
8086 6 : .await?;
8087 24 : let (tenant, ctx) = harness.load().await;
8088 6 :
8089 1056 : fn get_key(id: u32) -> Key {
8090 1056 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8091 1056 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8092 1056 : key.field6 = id;
8093 1056 : key
8094 1056 : }
8095 6 :
8096 6 : let img_layer = (0..10)
8097 60 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
8098 6 : .collect_vec();
8099 6 :
8100 6 : let delta1 = vec![
8101 6 : (
8102 6 : get_key(1),
8103 6 : Lsn(0x20),
8104 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8105 6 : ),
8106 6 : (
8107 6 : get_key(1),
8108 6 : Lsn(0x28),
8109 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
8110 6 : ),
8111 6 : ];
8112 6 : let delta2 = vec![
8113 6 : (
8114 6 : get_key(1),
8115 6 : Lsn(0x30),
8116 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
8117 6 : ),
8118 6 : (
8119 6 : get_key(1),
8120 6 : Lsn(0x38),
8121 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
8122 6 : ),
8123 6 : ];
8124 6 : let delta3 = vec![
8125 6 : (
8126 6 : get_key(8),
8127 6 : Lsn(0x48),
8128 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
8129 6 : ),
8130 6 : (
8131 6 : get_key(9),
8132 6 : Lsn(0x48),
8133 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
8134 6 : ),
8135 6 : ];
8136 6 :
8137 6 : let tline = tenant
8138 6 : .create_test_timeline_with_layers(
8139 6 : TIMELINE_ID,
8140 6 : Lsn(0x10),
8141 6 : DEFAULT_PG_VERSION,
8142 6 : &ctx,
8143 6 : vec![
8144 6 : // delta1 and delta 2 only contain a single key but multiple updates
8145 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
8146 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
8147 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
8148 6 : ], // delta layers
8149 6 : vec![(Lsn(0x10), img_layer)], // image layers
8150 6 : Lsn(0x50),
8151 6 : )
8152 141 : .await?;
8153 6 : {
8154 6 : // Update GC info
8155 6 : let mut guard = tline.gc_info.write().unwrap();
8156 6 : *guard = GcInfo {
8157 6 : retain_lsns: vec![
8158 6 : (Lsn(0x10), tline.timeline_id),
8159 6 : (Lsn(0x20), tline.timeline_id),
8160 6 : ],
8161 6 : cutoffs: GcCutoffs {
8162 6 : time: Lsn(0x30),
8163 6 : space: Lsn(0x30),
8164 6 : },
8165 6 : leases: Default::default(),
8166 6 : within_ancestor_pitr: false,
8167 6 : };
8168 6 : }
8169 6 :
8170 6 : let expected_result = [
8171 6 : Bytes::from_static(b"value 0@0x10"),
8172 6 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
8173 6 : Bytes::from_static(b"value 2@0x10"),
8174 6 : Bytes::from_static(b"value 3@0x10"),
8175 6 : Bytes::from_static(b"value 4@0x10"),
8176 6 : Bytes::from_static(b"value 5@0x10"),
8177 6 : Bytes::from_static(b"value 6@0x10"),
8178 6 : Bytes::from_static(b"value 7@0x10"),
8179 6 : Bytes::from_static(b"value 8@0x10@0x48"),
8180 6 : Bytes::from_static(b"value 9@0x10@0x48"),
8181 6 : ];
8182 6 :
8183 6 : let expected_result_at_gc_horizon = [
8184 6 : Bytes::from_static(b"value 0@0x10"),
8185 6 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
8186 6 : Bytes::from_static(b"value 2@0x10"),
8187 6 : Bytes::from_static(b"value 3@0x10"),
8188 6 : Bytes::from_static(b"value 4@0x10"),
8189 6 : Bytes::from_static(b"value 5@0x10"),
8190 6 : Bytes::from_static(b"value 6@0x10"),
8191 6 : Bytes::from_static(b"value 7@0x10"),
8192 6 : Bytes::from_static(b"value 8@0x10"),
8193 6 : Bytes::from_static(b"value 9@0x10"),
8194 6 : ];
8195 6 :
8196 6 : let expected_result_at_lsn_20 = [
8197 6 : Bytes::from_static(b"value 0@0x10"),
8198 6 : Bytes::from_static(b"value 1@0x10@0x20"),
8199 6 : Bytes::from_static(b"value 2@0x10"),
8200 6 : Bytes::from_static(b"value 3@0x10"),
8201 6 : Bytes::from_static(b"value 4@0x10"),
8202 6 : Bytes::from_static(b"value 5@0x10"),
8203 6 : Bytes::from_static(b"value 6@0x10"),
8204 6 : Bytes::from_static(b"value 7@0x10"),
8205 6 : Bytes::from_static(b"value 8@0x10"),
8206 6 : Bytes::from_static(b"value 9@0x10"),
8207 6 : ];
8208 6 :
8209 6 : let expected_result_at_lsn_10 = [
8210 6 : Bytes::from_static(b"value 0@0x10"),
8211 6 : Bytes::from_static(b"value 1@0x10"),
8212 6 : Bytes::from_static(b"value 2@0x10"),
8213 6 : Bytes::from_static(b"value 3@0x10"),
8214 6 : Bytes::from_static(b"value 4@0x10"),
8215 6 : Bytes::from_static(b"value 5@0x10"),
8216 6 : Bytes::from_static(b"value 6@0x10"),
8217 6 : Bytes::from_static(b"value 7@0x10"),
8218 6 : Bytes::from_static(b"value 8@0x10"),
8219 6 : Bytes::from_static(b"value 9@0x10"),
8220 6 : ];
8221 6 :
8222 24 : let verify_result = || async {
8223 24 : let gc_horizon = {
8224 24 : let gc_info = tline.gc_info.read().unwrap();
8225 24 : gc_info.cutoffs.time
8226 6 : };
8227 264 : for idx in 0..10 {
8228 240 : assert_eq!(
8229 240 : tline
8230 240 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8231 222 : .await
8232 240 : .unwrap(),
8233 240 : &expected_result[idx]
8234 6 : );
8235 240 : assert_eq!(
8236 240 : tline
8237 240 : .get(get_key(idx as u32), gc_horizon, &ctx)
8238 147 : .await
8239 240 : .unwrap(),
8240 240 : &expected_result_at_gc_horizon[idx]
8241 6 : );
8242 240 : assert_eq!(
8243 240 : tline
8244 240 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
8245 138 : .await
8246 240 : .unwrap(),
8247 240 : &expected_result_at_lsn_20[idx]
8248 6 : );
8249 240 : assert_eq!(
8250 240 : tline
8251 240 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
8252 123 : .await
8253 240 : .unwrap(),
8254 240 : &expected_result_at_lsn_10[idx]
8255 6 : );
8256 6 : }
8257 48 : };
8258 6 :
8259 183 : verify_result().await;
8260 6 :
8261 6 : let cancel = CancellationToken::new();
8262 6 : let mut dryrun_flags = EnumSet::new();
8263 6 : dryrun_flags.insert(CompactFlags::DryRun);
8264 6 :
8265 6 : tline
8266 6 : .compact_with_gc(&cancel, dryrun_flags, &ctx)
8267 135 : .await
8268 6 : .unwrap();
8269 6 : // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
8270 6 : // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
8271 147 : verify_result().await;
8272 6 :
8273 6 : tline
8274 6 : .compact_with_gc(&cancel, EnumSet::new(), &ctx)
8275 153 : .await
8276 6 : .unwrap();
8277 159 : verify_result().await;
8278 6 :
8279 6 : // compact again
8280 6 : tline
8281 6 : .compact_with_gc(&cancel, EnumSet::new(), &ctx)
8282 117 : .await
8283 6 : .unwrap();
8284 141 : verify_result().await;
8285 6 :
8286 6 : Ok(())
8287 6 : }
8288 :
8289 : #[tokio::test]
8290 6 : async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
8291 6 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
8292 24 : let (tenant, ctx) = harness.load().await;
8293 6 :
8294 378 : fn get_key(id: u32) -> Key {
8295 378 : let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
8296 378 : key.field6 = id;
8297 378 : key
8298 378 : }
8299 6 :
8300 6 : let img_layer = (0..10)
8301 60 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
8302 6 : .collect_vec();
8303 6 :
8304 6 : let delta1 = vec![
8305 6 : (
8306 6 : get_key(1),
8307 6 : Lsn(0x20),
8308 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8309 6 : ),
8310 6 : (
8311 6 : get_key(2),
8312 6 : Lsn(0x30),
8313 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
8314 6 : ),
8315 6 : (
8316 6 : get_key(3),
8317 6 : Lsn(0x28),
8318 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
8319 6 : ),
8320 6 : (
8321 6 : get_key(3),
8322 6 : Lsn(0x30),
8323 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
8324 6 : ),
8325 6 : (
8326 6 : get_key(3),
8327 6 : Lsn(0x40),
8328 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
8329 6 : ),
8330 6 : ];
8331 6 : let delta2 = vec![
8332 6 : (
8333 6 : get_key(5),
8334 6 : Lsn(0x20),
8335 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8336 6 : ),
8337 6 : (
8338 6 : get_key(6),
8339 6 : Lsn(0x20),
8340 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8341 6 : ),
8342 6 : ];
8343 6 : let delta3 = vec![
8344 6 : (
8345 6 : get_key(8),
8346 6 : Lsn(0x48),
8347 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
8348 6 : ),
8349 6 : (
8350 6 : get_key(9),
8351 6 : Lsn(0x48),
8352 6 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
8353 6 : ),
8354 6 : ];
8355 6 :
8356 6 : let parent_tline = tenant
8357 6 : .create_test_timeline_with_layers(
8358 6 : TIMELINE_ID,
8359 6 : Lsn(0x10),
8360 6 : DEFAULT_PG_VERSION,
8361 6 : &ctx,
8362 6 : vec![], // delta layers
8363 6 : vec![(Lsn(0x18), img_layer)], // image layers
8364 6 : Lsn(0x18),
8365 6 : )
8366 87 : .await?;
8367 6 :
8368 6 : parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
8369 6 :
8370 6 : let branch_tline = tenant
8371 6 : .branch_timeline_test_with_layers(
8372 6 : &parent_tline,
8373 6 : NEW_TIMELINE_ID,
8374 6 : Some(Lsn(0x18)),
8375 6 : &ctx,
8376 6 : vec![
8377 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
8378 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
8379 6 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
8380 6 : ], // delta layers
8381 6 : vec![], // image layers
8382 6 : Lsn(0x50),
8383 6 : )
8384 54 : .await?;
8385 6 :
8386 6 : branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
8387 6 :
8388 6 : {
8389 6 : // Update GC info
8390 6 : let mut guard = parent_tline.gc_info.write().unwrap();
8391 6 : *guard = GcInfo {
8392 6 : retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id)],
8393 6 : cutoffs: GcCutoffs {
8394 6 : time: Lsn(0x10),
8395 6 : space: Lsn(0x10),
8396 6 : },
8397 6 : leases: Default::default(),
8398 6 : within_ancestor_pitr: false,
8399 6 : };
8400 6 : }
8401 6 :
8402 6 : {
8403 6 : // Update GC info
8404 6 : let mut guard = branch_tline.gc_info.write().unwrap();
8405 6 : *guard = GcInfo {
8406 6 : retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id)],
8407 6 : cutoffs: GcCutoffs {
8408 6 : time: Lsn(0x50),
8409 6 : space: Lsn(0x50),
8410 6 : },
8411 6 : leases: Default::default(),
8412 6 : within_ancestor_pitr: false,
8413 6 : };
8414 6 : }
8415 6 :
8416 6 : let expected_result_at_gc_horizon = [
8417 6 : Bytes::from_static(b"value 0@0x10"),
8418 6 : Bytes::from_static(b"value 1@0x10@0x20"),
8419 6 : Bytes::from_static(b"value 2@0x10@0x30"),
8420 6 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
8421 6 : Bytes::from_static(b"value 4@0x10"),
8422 6 : Bytes::from_static(b"value 5@0x10@0x20"),
8423 6 : Bytes::from_static(b"value 6@0x10@0x20"),
8424 6 : Bytes::from_static(b"value 7@0x10"),
8425 6 : Bytes::from_static(b"value 8@0x10@0x48"),
8426 6 : Bytes::from_static(b"value 9@0x10@0x48"),
8427 6 : ];
8428 6 :
8429 6 : let expected_result_at_lsn_40 = [
8430 6 : Bytes::from_static(b"value 0@0x10"),
8431 6 : Bytes::from_static(b"value 1@0x10@0x20"),
8432 6 : Bytes::from_static(b"value 2@0x10@0x30"),
8433 6 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
8434 6 : Bytes::from_static(b"value 4@0x10"),
8435 6 : Bytes::from_static(b"value 5@0x10@0x20"),
8436 6 : Bytes::from_static(b"value 6@0x10@0x20"),
8437 6 : Bytes::from_static(b"value 7@0x10"),
8438 6 : Bytes::from_static(b"value 8@0x10"),
8439 6 : Bytes::from_static(b"value 9@0x10"),
8440 6 : ];
8441 6 :
8442 12 : let verify_result = || async {
8443 132 : for idx in 0..10 {
8444 120 : assert_eq!(
8445 120 : branch_tline
8446 120 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8447 150 : .await
8448 120 : .unwrap(),
8449 120 : &expected_result_at_gc_horizon[idx]
8450 6 : );
8451 120 : assert_eq!(
8452 120 : branch_tline
8453 120 : .get(get_key(idx as u32), Lsn(0x40), &ctx)
8454 99 : .await
8455 120 : .unwrap(),
8456 120 : &expected_result_at_lsn_40[idx]
8457 6 : );
8458 6 : }
8459 24 : };
8460 6 :
8461 138 : verify_result().await;
8462 6 :
8463 6 : let cancel = CancellationToken::new();
8464 6 : branch_tline
8465 6 : .compact_with_gc(&cancel, EnumSet::new(), &ctx)
8466 48 : .await
8467 6 : .unwrap();
8468 6 :
8469 111 : verify_result().await;
8470 6 :
8471 6 : Ok(())
8472 6 : }
8473 : }
|