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 chrono::NaiveDateTime;
20 : use enumset::EnumSet;
21 : use futures::stream::FuturesUnordered;
22 : use futures::StreamExt;
23 : use itertools::Itertools as _;
24 : use pageserver_api::models;
25 : use pageserver_api::models::CompactInfoResponse;
26 : use pageserver_api::models::LsnLease;
27 : use pageserver_api::models::TimelineArchivalState;
28 : use pageserver_api::models::TimelineState;
29 : use pageserver_api::models::TopTenantShardItem;
30 : use pageserver_api::models::WalRedoManagerStatus;
31 : use pageserver_api::shard::ShardIdentity;
32 : use pageserver_api::shard::ShardStripeSize;
33 : use pageserver_api::shard::TenantShardId;
34 : use remote_storage::DownloadError;
35 : use remote_storage::GenericRemoteStorage;
36 : use remote_storage::TimeoutOrCancel;
37 : use remote_timeline_client::manifest::{
38 : OffloadedTimelineManifest, TenantManifest, LATEST_TENANT_MANIFEST_VERSION,
39 : };
40 : use remote_timeline_client::UploadQueueNotReadyError;
41 : use remote_timeline_client::FAILED_REMOTE_OP_RETRIES;
42 : use remote_timeline_client::FAILED_UPLOAD_WARN_THRESHOLD;
43 : use std::collections::BTreeMap;
44 : use std::fmt;
45 : use std::future::Future;
46 : use std::sync::atomic::AtomicBool;
47 : use std::sync::Weak;
48 : use std::time::SystemTime;
49 : use storage_broker::BrokerClientChannel;
50 : use timeline::compaction::CompactionOutcome;
51 : use timeline::compaction::GcCompactionQueue;
52 : use timeline::import_pgdata;
53 : use timeline::offload::offload_timeline;
54 : use timeline::offload::OffloadError;
55 : use timeline::CompactFlags;
56 : use timeline::CompactOptions;
57 : use timeline::CompactionError;
58 : use timeline::ShutdownMode;
59 : use tokio::io::BufReader;
60 : use tokio::sync::watch;
61 : use tokio::sync::Notify;
62 : use tokio::task::JoinSet;
63 : use tokio_util::sync::CancellationToken;
64 : use tracing::*;
65 : use upload_queue::NotInitialized;
66 : use utils::backoff;
67 : use utils::circuit_breaker::CircuitBreaker;
68 : use utils::completion;
69 : use utils::crashsafe::path_with_suffix_extension;
70 : use utils::failpoint_support;
71 : use utils::fs_ext;
72 : use utils::pausable_failpoint;
73 : use utils::sync::gate::Gate;
74 : use utils::sync::gate::GateGuard;
75 : use utils::timeout::timeout_cancellable;
76 : use utils::timeout::TimeoutCancellableError;
77 : use utils::try_rcu::ArcSwapExt;
78 : use utils::zstd::create_zst_tarball;
79 : use utils::zstd::extract_zst_tarball;
80 :
81 : use self::config::AttachedLocationConfig;
82 : use self::config::AttachmentMode;
83 : use self::config::LocationConf;
84 : use self::config::TenantConf;
85 : use self::metadata::TimelineMetadata;
86 : use self::mgr::GetActiveTenantError;
87 : use self::mgr::GetTenantError;
88 : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
89 : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
90 : use self::timeline::uninit::TimelineCreateGuard;
91 : use self::timeline::uninit::TimelineExclusionError;
92 : use self::timeline::uninit::UninitializedTimeline;
93 : use self::timeline::EvictionTaskTenantState;
94 : use self::timeline::GcCutoffs;
95 : use self::timeline::TimelineDeleteProgress;
96 : use self::timeline::TimelineResources;
97 : use self::timeline::WaitLsnError;
98 : use crate::config::PageServerConf;
99 : use crate::context::{DownloadBehavior, RequestContext};
100 : use crate::deletion_queue::DeletionQueueClient;
101 : use crate::deletion_queue::DeletionQueueError;
102 : use crate::import_datadir;
103 : use crate::l0_flush::L0FlushGlobalState;
104 : use crate::metrics::CONCURRENT_INITDBS;
105 : use crate::metrics::INITDB_RUN_TIME;
106 : use crate::metrics::INITDB_SEMAPHORE_ACQUISITION_TIME;
107 : use crate::metrics::TENANT;
108 : use crate::metrics::{
109 : remove_tenant_metrics, BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN,
110 : TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC,
111 : };
112 : use crate::task_mgr;
113 : use crate::task_mgr::TaskKind;
114 : use crate::tenant::config::LocationMode;
115 : use crate::tenant::config::TenantConfOpt;
116 : use crate::tenant::gc_result::GcResult;
117 : pub use crate::tenant::remote_timeline_client::index::IndexPart;
118 : use crate::tenant::remote_timeline_client::remote_initdb_archive_path;
119 : use crate::tenant::remote_timeline_client::MaybeDeletedIndexPart;
120 : use crate::tenant::remote_timeline_client::INITDB_PATH;
121 : use crate::tenant::storage_layer::DeltaLayer;
122 : use crate::tenant::storage_layer::ImageLayer;
123 : use crate::walingest::WalLagCooldown;
124 : use crate::walredo;
125 : use crate::InitializationOrder;
126 : use std::collections::hash_map::Entry;
127 : use std::collections::HashMap;
128 : use std::collections::HashSet;
129 : use std::fmt::Debug;
130 : use std::fmt::Display;
131 : use std::fs;
132 : use std::fs::File;
133 : use std::sync::atomic::{AtomicU64, Ordering};
134 : use std::sync::Arc;
135 : use std::sync::Mutex;
136 : use std::time::{Duration, Instant};
137 :
138 : use crate::span;
139 : use crate::tenant::timeline::delete::DeleteTimelineFlow;
140 : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
141 : use crate::virtual_file::VirtualFile;
142 : use crate::walredo::PostgresRedoManager;
143 : use crate::TEMP_FILE_SUFFIX;
144 : use once_cell::sync::Lazy;
145 : pub use pageserver_api::models::TenantState;
146 : use tokio::sync::Semaphore;
147 :
148 0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
149 : use utils::{
150 : crashsafe,
151 : generation::Generation,
152 : id::TimelineId,
153 : lsn::{Lsn, RecordLsn},
154 : };
155 :
156 : pub mod blob_io;
157 : pub mod block_io;
158 : pub mod vectored_blob_io;
159 :
160 : pub mod disk_btree;
161 : pub(crate) mod ephemeral_file;
162 : pub mod layer_map;
163 :
164 : pub mod metadata;
165 : pub mod remote_timeline_client;
166 : pub mod storage_layer;
167 :
168 : pub mod checks;
169 : pub mod config;
170 : pub mod mgr;
171 : pub mod secondary;
172 : pub mod tasks;
173 : pub mod upload_queue;
174 :
175 : pub(crate) mod timeline;
176 :
177 : pub mod size;
178 :
179 : mod gc_block;
180 : mod gc_result;
181 : pub(crate) mod throttle;
182 :
183 : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
184 : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
185 :
186 : // re-export for use in walreceiver
187 : pub use crate::tenant::timeline::WalReceiverInfo;
188 :
189 : /// The "tenants" part of `tenants/<tenant>/timelines...`
190 : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
191 :
192 : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
193 : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
194 :
195 : /// References to shared objects that are passed into each tenant, such
196 : /// as the shared remote storage client and process initialization state.
197 : #[derive(Clone)]
198 : pub struct TenantSharedResources {
199 : pub broker_client: storage_broker::BrokerClientChannel,
200 : pub remote_storage: GenericRemoteStorage,
201 : pub deletion_queue_client: DeletionQueueClient,
202 : pub l0_flush_global_state: L0FlushGlobalState,
203 : }
204 :
205 : /// A [`Tenant`] is really an _attached_ tenant. The configuration
206 : /// for an attached tenant is a subset of the [`LocationConf`], represented
207 : /// in this struct.
208 : #[derive(Clone)]
209 : pub(super) struct AttachedTenantConf {
210 : tenant_conf: TenantConfOpt,
211 : location: AttachedLocationConfig,
212 : /// The deadline before which we are blocked from GC so that
213 : /// leases have a chance to be renewed.
214 : lsn_lease_deadline: Option<tokio::time::Instant>,
215 : }
216 :
217 : impl AttachedTenantConf {
218 440 : fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
219 : // Sets a deadline before which we cannot proceed to GC due to lsn lease.
220 : //
221 : // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
222 : // length, we guarantee that all the leases we granted before will have a chance to renew
223 : // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
224 440 : let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
225 440 : Some(
226 440 : tokio::time::Instant::now()
227 440 : + tenant_conf
228 440 : .lsn_lease_length
229 440 : .unwrap_or(LsnLease::DEFAULT_LENGTH),
230 440 : )
231 : } else {
232 : // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
233 : // because we don't do GC in these modes.
234 0 : None
235 : };
236 :
237 440 : Self {
238 440 : tenant_conf,
239 440 : location,
240 440 : lsn_lease_deadline,
241 440 : }
242 440 : }
243 :
244 440 : fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
245 440 : match &location_conf.mode {
246 440 : LocationMode::Attached(attach_conf) => {
247 440 : Ok(Self::new(location_conf.tenant_conf, *attach_conf))
248 : }
249 : LocationMode::Secondary(_) => {
250 0 : anyhow::bail!("Attempted to construct AttachedTenantConf from a LocationConf in secondary mode")
251 : }
252 : }
253 440 : }
254 :
255 1524 : fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
256 1524 : self.lsn_lease_deadline
257 1524 : .map(|d| tokio::time::Instant::now() < d)
258 1524 : .unwrap_or(false)
259 1524 : }
260 : }
261 : struct TimelinePreload {
262 : timeline_id: TimelineId,
263 : client: RemoteTimelineClient,
264 : index_part: Result<MaybeDeletedIndexPart, DownloadError>,
265 : }
266 :
267 : pub(crate) struct TenantPreload {
268 : tenant_manifest: TenantManifest,
269 : /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
270 : timelines: HashMap<TimelineId, Option<TimelinePreload>>,
271 : }
272 :
273 : /// When we spawn a tenant, there is a special mode for tenant creation that
274 : /// avoids trying to read anything from remote storage.
275 : pub(crate) enum SpawnMode {
276 : /// Activate as soon as possible
277 : Eager,
278 : /// Lazy activation in the background, with the option to skip the queue if the need comes up
279 : Lazy,
280 : }
281 :
282 : ///
283 : /// Tenant consists of multiple timelines. Keep them in a hash table.
284 : ///
285 : pub struct Tenant {
286 : // Global pageserver config parameters
287 : pub conf: &'static PageServerConf,
288 :
289 : /// The value creation timestamp, used to measure activation delay, see:
290 : /// <https://github.com/neondatabase/neon/issues/4025>
291 : constructed_at: Instant,
292 :
293 : state: watch::Sender<TenantState>,
294 :
295 : // Overridden tenant-specific config parameters.
296 : // We keep TenantConfOpt sturct here to preserve the information
297 : // about parameters that are not set.
298 : // This is necessary to allow global config updates.
299 : tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
300 :
301 : tenant_shard_id: TenantShardId,
302 :
303 : // The detailed sharding information, beyond the number/count in tenant_shard_id
304 : shard_identity: ShardIdentity,
305 :
306 : /// The remote storage generation, used to protect S3 objects from split-brain.
307 : /// Does not change over the lifetime of the [`Tenant`] object.
308 : ///
309 : /// This duplicates the generation stored in LocationConf, but that structure is mutable:
310 : /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
311 : generation: Generation,
312 :
313 : timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
314 :
315 : /// During timeline creation, we first insert the TimelineId to the
316 : /// creating map, then `timelines`, then remove it from the creating map.
317 : /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
318 : timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
319 :
320 : /// Possibly offloaded and archived timelines
321 : /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
322 : timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
323 :
324 : /// Serialize writes of the tenant manifest to remote storage. If there are concurrent operations
325 : /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
326 : /// each other (this could be optimized to coalesce writes if necessary).
327 : ///
328 : /// The contents of the Mutex are the last manifest we successfully uploaded
329 : tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
330 :
331 : // This mutex prevents creation of new timelines during GC.
332 : // Adding yet another mutex (in addition to `timelines`) is needed because holding
333 : // `timelines` mutex during all GC iteration
334 : // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
335 : // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
336 : // timeout...
337 : gc_cs: tokio::sync::Mutex<()>,
338 : walredo_mgr: Option<Arc<WalRedoManager>>,
339 :
340 : // provides access to timeline data sitting in the remote storage
341 : pub(crate) remote_storage: GenericRemoteStorage,
342 :
343 : // Access to global deletion queue for when this tenant wants to schedule a deletion
344 : deletion_queue_client: DeletionQueueClient,
345 :
346 : /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
347 : cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
348 : cached_synthetic_tenant_size: Arc<AtomicU64>,
349 :
350 : eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
351 :
352 : /// Track repeated failures to compact, so that we can back off.
353 : /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
354 : compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
355 :
356 : /// Signals the tenant compaction loop that there is L0 compaction work to be done.
357 : pub(crate) l0_compaction_trigger: Arc<Notify>,
358 :
359 : /// Scheduled gc-compaction tasks.
360 : scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
361 :
362 : /// If the tenant is in Activating state, notify this to encourage it
363 : /// to proceed to Active as soon as possible, rather than waiting for lazy
364 : /// background warmup.
365 : pub(crate) activate_now_sem: tokio::sync::Semaphore,
366 :
367 : /// Time it took for the tenant to activate. Zero if not active yet.
368 : attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
369 :
370 : // Cancellation token fires when we have entered shutdown(). This is a parent of
371 : // Timelines' cancellation token.
372 : pub(crate) cancel: CancellationToken,
373 :
374 : // Users of the Tenant such as the page service must take this Gate to avoid
375 : // trying to use a Tenant which is shutting down.
376 : pub(crate) gate: Gate,
377 :
378 : /// Throttle applied at the top of [`Timeline::get`].
379 : /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
380 : pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
381 :
382 : pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
383 :
384 : /// An ongoing timeline detach concurrency limiter.
385 : ///
386 : /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
387 : /// to have two running at the same time. A different one can be started if an earlier one
388 : /// has failed for whatever reason.
389 : ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
390 :
391 : /// `index_part.json` based gc blocking reason tracking.
392 : ///
393 : /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
394 : /// proceeding.
395 : pub(crate) gc_block: gc_block::GcBlock,
396 :
397 : l0_flush_global_state: L0FlushGlobalState,
398 : }
399 : impl std::fmt::Debug for Tenant {
400 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
401 0 : write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
402 0 : }
403 : }
404 :
405 : pub(crate) enum WalRedoManager {
406 : Prod(WalredoManagerId, PostgresRedoManager),
407 : #[cfg(test)]
408 : Test(harness::TestRedoManager),
409 : }
410 :
411 : #[derive(thiserror::Error, Debug)]
412 : #[error("pageserver is shutting down")]
413 : pub(crate) struct GlobalShutDown;
414 :
415 : impl WalRedoManager {
416 0 : pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
417 0 : let id = WalredoManagerId::next();
418 0 : let arc = Arc::new(Self::Prod(id, mgr));
419 0 : let mut guard = WALREDO_MANAGERS.lock().unwrap();
420 0 : match &mut *guard {
421 0 : Some(map) => {
422 0 : map.insert(id, Arc::downgrade(&arc));
423 0 : Ok(arc)
424 : }
425 0 : None => Err(GlobalShutDown),
426 : }
427 0 : }
428 : }
429 :
430 : impl Drop for WalRedoManager {
431 20 : fn drop(&mut self) {
432 20 : match self {
433 0 : Self::Prod(id, _) => {
434 0 : let mut guard = WALREDO_MANAGERS.lock().unwrap();
435 0 : if let Some(map) = &mut *guard {
436 0 : map.remove(id).expect("new() registers, drop() unregisters");
437 0 : }
438 : }
439 : #[cfg(test)]
440 20 : Self::Test(_) => {
441 20 : // Not applicable to test redo manager
442 20 : }
443 : }
444 20 : }
445 : }
446 :
447 : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
448 : /// the walredo processes outside of the regular order.
449 : ///
450 : /// This is necessary to work around a systemd bug where it freezes if there are
451 : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
452 : #[allow(clippy::type_complexity)]
453 : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
454 : Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
455 0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
456 : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
457 : pub(crate) struct WalredoManagerId(u64);
458 : impl WalredoManagerId {
459 0 : pub fn next() -> Self {
460 : static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
461 0 : let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
462 0 : if id == 0 {
463 0 : panic!("WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique");
464 0 : }
465 0 : Self(id)
466 0 : }
467 : }
468 :
469 : #[cfg(test)]
470 : impl From<harness::TestRedoManager> for WalRedoManager {
471 440 : fn from(mgr: harness::TestRedoManager) -> Self {
472 440 : Self::Test(mgr)
473 440 : }
474 : }
475 :
476 : impl WalRedoManager {
477 12 : pub(crate) async fn shutdown(&self) -> bool {
478 12 : match self {
479 0 : Self::Prod(_, mgr) => mgr.shutdown().await,
480 : #[cfg(test)]
481 : Self::Test(_) => {
482 : // Not applicable to test redo manager
483 12 : true
484 : }
485 : }
486 12 : }
487 :
488 0 : pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
489 0 : match self {
490 0 : Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
491 0 : #[cfg(test)]
492 0 : Self::Test(_) => {
493 0 : // Not applicable to test redo manager
494 0 : }
495 0 : }
496 0 : }
497 :
498 : /// # Cancel-Safety
499 : ///
500 : /// This method is cancellation-safe.
501 1636 : pub async fn request_redo(
502 1636 : &self,
503 1636 : key: pageserver_api::key::Key,
504 1636 : lsn: Lsn,
505 1636 : base_img: Option<(Lsn, bytes::Bytes)>,
506 1636 : records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
507 1636 : pg_version: u32,
508 1636 : ) -> Result<bytes::Bytes, walredo::Error> {
509 1636 : match self {
510 0 : Self::Prod(_, mgr) => {
511 0 : mgr.request_redo(key, lsn, base_img, records, pg_version)
512 0 : .await
513 : }
514 : #[cfg(test)]
515 1636 : Self::Test(mgr) => {
516 1636 : mgr.request_redo(key, lsn, base_img, records, pg_version)
517 1636 : .await
518 : }
519 : }
520 1636 : }
521 :
522 0 : pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
523 0 : match self {
524 0 : WalRedoManager::Prod(_, m) => Some(m.status()),
525 0 : #[cfg(test)]
526 0 : WalRedoManager::Test(_) => None,
527 0 : }
528 0 : }
529 : }
530 :
531 : /// A very lightweight memory representation of an offloaded timeline.
532 : ///
533 : /// We need to store the list of offloaded timelines so that we can perform operations on them,
534 : /// like unoffloading them, or (at a later date), decide to perform flattening.
535 : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
536 : /// more offloaded timelines than we can manage ones that aren't.
537 : pub struct OffloadedTimeline {
538 : pub tenant_shard_id: TenantShardId,
539 : pub timeline_id: TimelineId,
540 : pub ancestor_timeline_id: Option<TimelineId>,
541 : /// Whether to retain the branch lsn at the ancestor or not
542 : pub ancestor_retain_lsn: Option<Lsn>,
543 :
544 : /// When the timeline was archived.
545 : ///
546 : /// Present for future flattening deliberations.
547 : pub archived_at: NaiveDateTime,
548 :
549 : /// Prevent two tasks from deleting the timeline at the same time. If held, the
550 : /// timeline is being deleted. If 'true', the timeline has already been deleted.
551 : pub delete_progress: TimelineDeleteProgress,
552 :
553 : /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
554 : pub deleted_from_ancestor: AtomicBool,
555 : }
556 :
557 : impl OffloadedTimeline {
558 : /// Obtains an offloaded timeline from a given timeline object.
559 : ///
560 : /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
561 : /// the timeline is not in a stopped state.
562 : /// Panics if the timeline is not archived.
563 4 : fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
564 4 : let (ancestor_retain_lsn, ancestor_timeline_id) =
565 4 : if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
566 4 : let ancestor_lsn = timeline.get_ancestor_lsn();
567 4 : let ancestor_timeline_id = ancestor_timeline.timeline_id;
568 4 : let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
569 4 : gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
570 4 : (Some(ancestor_lsn), Some(ancestor_timeline_id))
571 : } else {
572 0 : (None, None)
573 : };
574 4 : let archived_at = timeline
575 4 : .remote_client
576 4 : .archived_at_stopped_queue()?
577 4 : .expect("must be called on an archived timeline");
578 4 : Ok(Self {
579 4 : tenant_shard_id: timeline.tenant_shard_id,
580 4 : timeline_id: timeline.timeline_id,
581 4 : ancestor_timeline_id,
582 4 : ancestor_retain_lsn,
583 4 : archived_at,
584 4 :
585 4 : delete_progress: timeline.delete_progress.clone(),
586 4 : deleted_from_ancestor: AtomicBool::new(false),
587 4 : })
588 4 : }
589 0 : fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
590 0 : // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
591 0 : // by the `initialize_gc_info` function.
592 0 : let OffloadedTimelineManifest {
593 0 : timeline_id,
594 0 : ancestor_timeline_id,
595 0 : ancestor_retain_lsn,
596 0 : archived_at,
597 0 : } = *manifest;
598 0 : Self {
599 0 : tenant_shard_id,
600 0 : timeline_id,
601 0 : ancestor_timeline_id,
602 0 : ancestor_retain_lsn,
603 0 : archived_at,
604 0 : delete_progress: TimelineDeleteProgress::default(),
605 0 : deleted_from_ancestor: AtomicBool::new(false),
606 0 : }
607 0 : }
608 4 : fn manifest(&self) -> OffloadedTimelineManifest {
609 4 : let Self {
610 4 : timeline_id,
611 4 : ancestor_timeline_id,
612 4 : ancestor_retain_lsn,
613 4 : archived_at,
614 4 : ..
615 4 : } = self;
616 4 : OffloadedTimelineManifest {
617 4 : timeline_id: *timeline_id,
618 4 : ancestor_timeline_id: *ancestor_timeline_id,
619 4 : ancestor_retain_lsn: *ancestor_retain_lsn,
620 4 : archived_at: *archived_at,
621 4 : }
622 4 : }
623 : /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
624 0 : fn delete_from_ancestor_with_timelines(
625 0 : &self,
626 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
627 0 : ) {
628 0 : if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
629 0 : (self.ancestor_retain_lsn, self.ancestor_timeline_id)
630 : {
631 0 : if let Some((_, ancestor_timeline)) = timelines
632 0 : .iter()
633 0 : .find(|(tid, _tl)| **tid == ancestor_timeline_id)
634 : {
635 0 : let removal_happened = ancestor_timeline
636 0 : .gc_info
637 0 : .write()
638 0 : .unwrap()
639 0 : .remove_child_offloaded(self.timeline_id);
640 0 : if !removal_happened {
641 0 : tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
642 0 : "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
643 0 : }
644 0 : }
645 0 : }
646 0 : self.deleted_from_ancestor.store(true, Ordering::Release);
647 0 : }
648 : /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
649 : ///
650 : /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
651 4 : fn defuse_for_tenant_drop(&self) {
652 4 : self.deleted_from_ancestor.store(true, Ordering::Release);
653 4 : }
654 : }
655 :
656 : impl fmt::Debug for OffloadedTimeline {
657 0 : fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
658 0 : write!(f, "OffloadedTimeline<{}>", self.timeline_id)
659 0 : }
660 : }
661 :
662 : impl Drop for OffloadedTimeline {
663 4 : fn drop(&mut self) {
664 4 : if !self.deleted_from_ancestor.load(Ordering::Acquire) {
665 0 : tracing::warn!(
666 0 : "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
667 : self.timeline_id
668 : );
669 4 : }
670 4 : }
671 : }
672 :
673 : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
674 : pub enum MaybeOffloaded {
675 : Yes,
676 : No,
677 : }
678 :
679 : #[derive(Clone, Debug)]
680 : pub enum TimelineOrOffloaded {
681 : Timeline(Arc<Timeline>),
682 : Offloaded(Arc<OffloadedTimeline>),
683 : }
684 :
685 : impl TimelineOrOffloaded {
686 0 : pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
687 0 : match self {
688 0 : TimelineOrOffloaded::Timeline(timeline) => {
689 0 : TimelineOrOffloadedArcRef::Timeline(timeline)
690 : }
691 0 : TimelineOrOffloaded::Offloaded(offloaded) => {
692 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded)
693 : }
694 : }
695 0 : }
696 0 : pub fn tenant_shard_id(&self) -> TenantShardId {
697 0 : self.arc_ref().tenant_shard_id()
698 0 : }
699 0 : pub fn timeline_id(&self) -> TimelineId {
700 0 : self.arc_ref().timeline_id()
701 0 : }
702 4 : pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
703 4 : match self {
704 4 : TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
705 0 : TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
706 : }
707 4 : }
708 0 : fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
709 0 : match self {
710 0 : TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
711 0 : TimelineOrOffloaded::Offloaded(_offloaded) => None,
712 : }
713 0 : }
714 : }
715 :
716 : pub enum TimelineOrOffloadedArcRef<'a> {
717 : Timeline(&'a Arc<Timeline>),
718 : Offloaded(&'a Arc<OffloadedTimeline>),
719 : }
720 :
721 : impl TimelineOrOffloadedArcRef<'_> {
722 0 : pub fn tenant_shard_id(&self) -> TenantShardId {
723 0 : match self {
724 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
725 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
726 : }
727 0 : }
728 0 : pub fn timeline_id(&self) -> TimelineId {
729 0 : match self {
730 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
731 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
732 : }
733 0 : }
734 : }
735 :
736 : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
737 0 : fn from(timeline: &'a Arc<Timeline>) -> Self {
738 0 : Self::Timeline(timeline)
739 0 : }
740 : }
741 :
742 : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
743 0 : fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
744 0 : Self::Offloaded(timeline)
745 0 : }
746 : }
747 :
748 : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
749 : pub enum GetTimelineError {
750 : #[error("Timeline is shutting down")]
751 : ShuttingDown,
752 : #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
753 : NotActive {
754 : tenant_id: TenantShardId,
755 : timeline_id: TimelineId,
756 : state: TimelineState,
757 : },
758 : #[error("Timeline {tenant_id}/{timeline_id} was not found")]
759 : NotFound {
760 : tenant_id: TenantShardId,
761 : timeline_id: TimelineId,
762 : },
763 : }
764 :
765 : #[derive(Debug, thiserror::Error)]
766 : pub enum LoadLocalTimelineError {
767 : #[error("FailedToLoad")]
768 : Load(#[source] anyhow::Error),
769 : #[error("FailedToResumeDeletion")]
770 : ResumeDeletion(#[source] anyhow::Error),
771 : }
772 :
773 : #[derive(thiserror::Error)]
774 : pub enum DeleteTimelineError {
775 : #[error("NotFound")]
776 : NotFound,
777 :
778 : #[error("HasChildren")]
779 : HasChildren(Vec<TimelineId>),
780 :
781 : #[error("Timeline deletion is already in progress")]
782 : AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
783 :
784 : #[error("Cancelled")]
785 : Cancelled,
786 :
787 : #[error(transparent)]
788 : Other(#[from] anyhow::Error),
789 : }
790 :
791 : impl Debug for DeleteTimelineError {
792 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
793 0 : match self {
794 0 : Self::NotFound => write!(f, "NotFound"),
795 0 : Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
796 0 : Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
797 0 : Self::Cancelled => f.debug_tuple("Cancelled").finish(),
798 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
799 : }
800 0 : }
801 : }
802 :
803 : #[derive(thiserror::Error)]
804 : pub enum TimelineArchivalError {
805 : #[error("NotFound")]
806 : NotFound,
807 :
808 : #[error("Timeout")]
809 : Timeout,
810 :
811 : #[error("Cancelled")]
812 : Cancelled,
813 :
814 : #[error("ancestor is archived: {}", .0)]
815 : HasArchivedParent(TimelineId),
816 :
817 : #[error("HasUnarchivedChildren")]
818 : HasUnarchivedChildren(Vec<TimelineId>),
819 :
820 : #[error("Timeline archival is already in progress")]
821 : AlreadyInProgress,
822 :
823 : #[error(transparent)]
824 : Other(anyhow::Error),
825 : }
826 :
827 : #[derive(thiserror::Error, Debug)]
828 : pub(crate) enum TenantManifestError {
829 : #[error("Remote storage error: {0}")]
830 : RemoteStorage(anyhow::Error),
831 :
832 : #[error("Cancelled")]
833 : Cancelled,
834 : }
835 :
836 : impl From<TenantManifestError> for TimelineArchivalError {
837 0 : fn from(e: TenantManifestError) -> Self {
838 0 : match e {
839 0 : TenantManifestError::RemoteStorage(e) => Self::Other(e),
840 0 : TenantManifestError::Cancelled => Self::Cancelled,
841 : }
842 0 : }
843 : }
844 :
845 : impl Debug for TimelineArchivalError {
846 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
847 0 : match self {
848 0 : Self::NotFound => write!(f, "NotFound"),
849 0 : Self::Timeout => write!(f, "Timeout"),
850 0 : Self::Cancelled => write!(f, "Cancelled"),
851 0 : Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
852 0 : Self::HasUnarchivedChildren(c) => {
853 0 : f.debug_tuple("HasUnarchivedChildren").field(c).finish()
854 : }
855 0 : Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
856 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
857 : }
858 0 : }
859 : }
860 :
861 : pub enum SetStoppingError {
862 : AlreadyStopping(completion::Barrier),
863 : Broken,
864 : }
865 :
866 : impl Debug for SetStoppingError {
867 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
868 0 : match self {
869 0 : Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
870 0 : Self::Broken => write!(f, "Broken"),
871 : }
872 0 : }
873 : }
874 :
875 : /// Arguments to [`Tenant::create_timeline`].
876 : ///
877 : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
878 : /// is `None`, the result of the timeline create call is not deterministic.
879 : ///
880 : /// See [`CreateTimelineIdempotency`] for an idempotency key.
881 : #[derive(Debug)]
882 : pub(crate) enum CreateTimelineParams {
883 : Bootstrap(CreateTimelineParamsBootstrap),
884 : Branch(CreateTimelineParamsBranch),
885 : ImportPgdata(CreateTimelineParamsImportPgdata),
886 : }
887 :
888 : #[derive(Debug)]
889 : pub(crate) struct CreateTimelineParamsBootstrap {
890 : pub(crate) new_timeline_id: TimelineId,
891 : pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
892 : pub(crate) pg_version: u32,
893 : }
894 :
895 : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
896 : #[derive(Debug)]
897 : pub(crate) struct CreateTimelineParamsBranch {
898 : pub(crate) new_timeline_id: TimelineId,
899 : pub(crate) ancestor_timeline_id: TimelineId,
900 : pub(crate) ancestor_start_lsn: Option<Lsn>,
901 : }
902 :
903 : #[derive(Debug)]
904 : pub(crate) struct CreateTimelineParamsImportPgdata {
905 : pub(crate) new_timeline_id: TimelineId,
906 : pub(crate) location: import_pgdata::index_part_format::Location,
907 : pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
908 : }
909 :
910 : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in [`Tenant::start_creating_timeline`] in [`Tenant::start_creating_timeline`].
911 : ///
912 : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
913 : ///
914 : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
915 : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
916 : ///
917 : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
918 : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
919 : ///
920 : /// Notes:
921 : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
922 : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
923 : /// is not considered for idempotency. We can improve on this over time if we deem it necessary.
924 : ///
925 : #[derive(Debug, Clone, PartialEq, Eq)]
926 : pub(crate) enum CreateTimelineIdempotency {
927 : /// NB: special treatment, see comment in [`Self`].
928 : FailWithConflict,
929 : Bootstrap {
930 : pg_version: u32,
931 : },
932 : /// NB: branches always have the same `pg_version` as their ancestor.
933 : /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
934 : /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
935 : /// determining the child branch pg_version.
936 : Branch {
937 : ancestor_timeline_id: TimelineId,
938 : ancestor_start_lsn: Lsn,
939 : },
940 : ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
941 : }
942 :
943 : #[derive(Debug, Clone, PartialEq, Eq)]
944 : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
945 : idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
946 : }
947 :
948 : /// What is returned by [`Tenant::start_creating_timeline`].
949 : #[must_use]
950 : enum StartCreatingTimelineResult {
951 : CreateGuard(TimelineCreateGuard),
952 : Idempotent(Arc<Timeline>),
953 : }
954 :
955 : enum TimelineInitAndSyncResult {
956 : ReadyToActivate(Arc<Timeline>),
957 : NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
958 : }
959 :
960 : impl TimelineInitAndSyncResult {
961 0 : fn ready_to_activate(self) -> Option<Arc<Timeline>> {
962 0 : match self {
963 0 : Self::ReadyToActivate(timeline) => Some(timeline),
964 0 : _ => None,
965 : }
966 0 : }
967 : }
968 :
969 : #[must_use]
970 : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
971 : timeline: Arc<Timeline>,
972 : import_pgdata: import_pgdata::index_part_format::Root,
973 : guard: TimelineCreateGuard,
974 : }
975 :
976 : /// What is returned by [`Tenant::create_timeline`].
977 : enum CreateTimelineResult {
978 : Created(Arc<Timeline>),
979 : Idempotent(Arc<Timeline>),
980 : /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
981 : /// we return this result, nor will this concrete object ever be added there.
982 : /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
983 : ImportSpawned(Arc<Timeline>),
984 : }
985 :
986 : impl CreateTimelineResult {
987 0 : fn discriminant(&self) -> &'static str {
988 0 : match self {
989 0 : Self::Created(_) => "Created",
990 0 : Self::Idempotent(_) => "Idempotent",
991 0 : Self::ImportSpawned(_) => "ImportSpawned",
992 : }
993 0 : }
994 0 : fn timeline(&self) -> &Arc<Timeline> {
995 0 : match self {
996 0 : Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
997 0 : }
998 0 : }
999 : /// Unit test timelines aren't activated, test has to do it if it needs to.
1000 : #[cfg(test)]
1001 460 : fn into_timeline_for_test(self) -> Arc<Timeline> {
1002 460 : match self {
1003 460 : Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
1004 460 : }
1005 460 : }
1006 : }
1007 :
1008 : #[derive(thiserror::Error, Debug)]
1009 : pub enum CreateTimelineError {
1010 : #[error("creation of timeline with the given ID is in progress")]
1011 : AlreadyCreating,
1012 : #[error("timeline already exists with different parameters")]
1013 : Conflict,
1014 : #[error(transparent)]
1015 : AncestorLsn(anyhow::Error),
1016 : #[error("ancestor timeline is not active")]
1017 : AncestorNotActive,
1018 : #[error("ancestor timeline is archived")]
1019 : AncestorArchived,
1020 : #[error("tenant shutting down")]
1021 : ShuttingDown,
1022 : #[error(transparent)]
1023 : Other(#[from] anyhow::Error),
1024 : }
1025 :
1026 : #[derive(thiserror::Error, Debug)]
1027 : pub enum InitdbError {
1028 : #[error("Operation was cancelled")]
1029 : Cancelled,
1030 : #[error(transparent)]
1031 : Other(anyhow::Error),
1032 : #[error(transparent)]
1033 : Inner(postgres_initdb::Error),
1034 : }
1035 :
1036 : enum CreateTimelineCause {
1037 : Load,
1038 : Delete,
1039 : }
1040 :
1041 : enum LoadTimelineCause {
1042 : Attach,
1043 : Unoffload,
1044 : ImportPgdata {
1045 : create_guard: TimelineCreateGuard,
1046 : activate: ActivateTimelineArgs,
1047 : },
1048 : }
1049 :
1050 : #[derive(thiserror::Error, Debug)]
1051 : pub(crate) enum GcError {
1052 : // The tenant is shutting down
1053 : #[error("tenant shutting down")]
1054 : TenantCancelled,
1055 :
1056 : // The tenant is shutting down
1057 : #[error("timeline shutting down")]
1058 : TimelineCancelled,
1059 :
1060 : // The tenant is in a state inelegible to run GC
1061 : #[error("not active")]
1062 : NotActive,
1063 :
1064 : // A requested GC cutoff LSN was invalid, for example it tried to move backwards
1065 : #[error("not active")]
1066 : BadLsn { why: String },
1067 :
1068 : // A remote storage error while scheduling updates after compaction
1069 : #[error(transparent)]
1070 : Remote(anyhow::Error),
1071 :
1072 : // An error reading while calculating GC cutoffs
1073 : #[error(transparent)]
1074 : GcCutoffs(PageReconstructError),
1075 :
1076 : // If GC was invoked for a particular timeline, this error means it didn't exist
1077 : #[error("timeline not found")]
1078 : TimelineNotFound,
1079 : }
1080 :
1081 : impl From<PageReconstructError> for GcError {
1082 0 : fn from(value: PageReconstructError) -> Self {
1083 0 : match value {
1084 0 : PageReconstructError::Cancelled => Self::TimelineCancelled,
1085 0 : other => Self::GcCutoffs(other),
1086 : }
1087 0 : }
1088 : }
1089 :
1090 : impl From<NotInitialized> for GcError {
1091 0 : fn from(value: NotInitialized) -> Self {
1092 0 : match value {
1093 0 : NotInitialized::Uninitialized => GcError::Remote(value.into()),
1094 0 : NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
1095 : }
1096 0 : }
1097 : }
1098 :
1099 : impl From<timeline::layer_manager::Shutdown> for GcError {
1100 0 : fn from(_: timeline::layer_manager::Shutdown) -> Self {
1101 0 : GcError::TimelineCancelled
1102 0 : }
1103 : }
1104 :
1105 : #[derive(thiserror::Error, Debug)]
1106 : pub(crate) enum LoadConfigError {
1107 : #[error("TOML deserialization error: '{0}'")]
1108 : DeserializeToml(#[from] toml_edit::de::Error),
1109 :
1110 : #[error("Config not found at {0}")]
1111 : NotFound(Utf8PathBuf),
1112 : }
1113 :
1114 : impl Tenant {
1115 : /// Yet another helper for timeline initialization.
1116 : ///
1117 : /// - Initializes the Timeline struct and inserts it into the tenant's hash map
1118 : /// - Scans the local timeline directory for layer files and builds the layer map
1119 : /// - Downloads remote index file and adds remote files to the layer map
1120 : /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
1121 : ///
1122 : /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
1123 : /// it is marked as Active.
1124 : #[allow(clippy::too_many_arguments)]
1125 12 : async fn timeline_init_and_sync(
1126 12 : self: &Arc<Self>,
1127 12 : timeline_id: TimelineId,
1128 12 : resources: TimelineResources,
1129 12 : mut index_part: IndexPart,
1130 12 : metadata: TimelineMetadata,
1131 12 : ancestor: Option<Arc<Timeline>>,
1132 12 : cause: LoadTimelineCause,
1133 12 : ctx: &RequestContext,
1134 12 : ) -> anyhow::Result<TimelineInitAndSyncResult> {
1135 12 : let tenant_id = self.tenant_shard_id;
1136 12 :
1137 12 : let import_pgdata = index_part.import_pgdata.take();
1138 12 : let idempotency = match &import_pgdata {
1139 0 : Some(import_pgdata) => {
1140 0 : CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
1141 0 : idempotency_key: import_pgdata.idempotency_key().clone(),
1142 0 : })
1143 : }
1144 : None => {
1145 12 : if metadata.ancestor_timeline().is_none() {
1146 8 : CreateTimelineIdempotency::Bootstrap {
1147 8 : pg_version: metadata.pg_version(),
1148 8 : }
1149 : } else {
1150 4 : CreateTimelineIdempotency::Branch {
1151 4 : ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
1152 4 : ancestor_start_lsn: metadata.ancestor_lsn(),
1153 4 : }
1154 : }
1155 : }
1156 : };
1157 :
1158 12 : let timeline = self.create_timeline_struct(
1159 12 : timeline_id,
1160 12 : &metadata,
1161 12 : ancestor.clone(),
1162 12 : resources,
1163 12 : CreateTimelineCause::Load,
1164 12 : idempotency.clone(),
1165 12 : )?;
1166 12 : let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
1167 12 : anyhow::ensure!(
1168 12 : disk_consistent_lsn.is_valid(),
1169 0 : "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
1170 : );
1171 12 : assert_eq!(
1172 12 : disk_consistent_lsn,
1173 12 : metadata.disk_consistent_lsn(),
1174 0 : "these are used interchangeably"
1175 : );
1176 :
1177 12 : timeline.remote_client.init_upload_queue(&index_part)?;
1178 :
1179 12 : timeline
1180 12 : .load_layer_map(disk_consistent_lsn, index_part)
1181 12 : .await
1182 12 : .with_context(|| {
1183 0 : format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
1184 12 : })?;
1185 :
1186 0 : match import_pgdata {
1187 0 : Some(import_pgdata) if !import_pgdata.is_done() => {
1188 0 : match cause {
1189 0 : LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
1190 : LoadTimelineCause::ImportPgdata { .. } => {
1191 0 : unreachable!("ImportPgdata should not be reloading timeline import is done and persisted as such in s3")
1192 : }
1193 : }
1194 0 : let mut guard = self.timelines_creating.lock().unwrap();
1195 0 : if !guard.insert(timeline_id) {
1196 : // We should never try and load the same timeline twice during startup
1197 0 : unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
1198 0 : }
1199 0 : let timeline_create_guard = TimelineCreateGuard {
1200 0 : _tenant_gate_guard: self.gate.enter()?,
1201 0 : owning_tenant: self.clone(),
1202 0 : timeline_id,
1203 0 : idempotency,
1204 0 : // The users of this specific return value don't need the timline_path in there.
1205 0 : timeline_path: timeline
1206 0 : .conf
1207 0 : .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
1208 0 : };
1209 0 : Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
1210 0 : TimelineInitAndSyncNeedsSpawnImportPgdata {
1211 0 : timeline,
1212 0 : import_pgdata,
1213 0 : guard: timeline_create_guard,
1214 0 : },
1215 0 : ))
1216 : }
1217 : Some(_) | None => {
1218 : {
1219 12 : let mut timelines_accessor = self.timelines.lock().unwrap();
1220 12 : match timelines_accessor.entry(timeline_id) {
1221 : // We should never try and load the same timeline twice during startup
1222 : Entry::Occupied(_) => {
1223 0 : unreachable!(
1224 0 : "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
1225 0 : );
1226 : }
1227 12 : Entry::Vacant(v) => {
1228 12 : v.insert(Arc::clone(&timeline));
1229 12 : timeline.maybe_spawn_flush_loop();
1230 12 : }
1231 : }
1232 : }
1233 :
1234 : // Sanity check: a timeline should have some content.
1235 12 : anyhow::ensure!(
1236 12 : ancestor.is_some()
1237 8 : || timeline
1238 8 : .layers
1239 8 : .read()
1240 8 : .await
1241 8 : .layer_map()
1242 8 : .expect("currently loading, layer manager cannot be shutdown already")
1243 8 : .iter_historic_layers()
1244 8 : .next()
1245 8 : .is_some(),
1246 0 : "Timeline has no ancestor and no layer files"
1247 : );
1248 :
1249 12 : match cause {
1250 12 : LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
1251 : LoadTimelineCause::ImportPgdata {
1252 0 : create_guard,
1253 0 : activate,
1254 0 : } => {
1255 0 : // TODO: see the comment in the task code above how I'm not so certain
1256 0 : // it is safe to activate here because of concurrent shutdowns.
1257 0 : match activate {
1258 0 : ActivateTimelineArgs::Yes { broker_client } => {
1259 0 : info!("activating timeline after reload from pgdata import task");
1260 0 : timeline.activate(self.clone(), broker_client, None, ctx);
1261 : }
1262 0 : ActivateTimelineArgs::No => (),
1263 : }
1264 0 : drop(create_guard);
1265 : }
1266 : }
1267 :
1268 12 : Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
1269 : }
1270 : }
1271 12 : }
1272 :
1273 : /// Attach a tenant that's available in cloud storage.
1274 : ///
1275 : /// This returns quickly, after just creating the in-memory object
1276 : /// Tenant struct and launching a background task to download
1277 : /// the remote index files. On return, the tenant is most likely still in
1278 : /// Attaching state, and it will become Active once the background task
1279 : /// finishes. You can use wait_until_active() to wait for the task to
1280 : /// complete.
1281 : ///
1282 : #[allow(clippy::too_many_arguments)]
1283 0 : pub(crate) fn spawn(
1284 0 : conf: &'static PageServerConf,
1285 0 : tenant_shard_id: TenantShardId,
1286 0 : resources: TenantSharedResources,
1287 0 : attached_conf: AttachedTenantConf,
1288 0 : shard_identity: ShardIdentity,
1289 0 : init_order: Option<InitializationOrder>,
1290 0 : mode: SpawnMode,
1291 0 : ctx: &RequestContext,
1292 0 : ) -> Result<Arc<Tenant>, GlobalShutDown> {
1293 0 : let wal_redo_manager =
1294 0 : WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
1295 :
1296 : let TenantSharedResources {
1297 0 : broker_client,
1298 0 : remote_storage,
1299 0 : deletion_queue_client,
1300 0 : l0_flush_global_state,
1301 0 : } = resources;
1302 0 :
1303 0 : let attach_mode = attached_conf.location.attach_mode;
1304 0 : let generation = attached_conf.location.generation;
1305 0 :
1306 0 : let tenant = Arc::new(Tenant::new(
1307 0 : TenantState::Attaching,
1308 0 : conf,
1309 0 : attached_conf,
1310 0 : shard_identity,
1311 0 : Some(wal_redo_manager),
1312 0 : tenant_shard_id,
1313 0 : remote_storage.clone(),
1314 0 : deletion_queue_client,
1315 0 : l0_flush_global_state,
1316 0 : ));
1317 0 :
1318 0 : // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
1319 0 : // we shut down while attaching.
1320 0 : let attach_gate_guard = tenant
1321 0 : .gate
1322 0 : .enter()
1323 0 : .expect("We just created the Tenant: nothing else can have shut it down yet");
1324 0 :
1325 0 : // Do all the hard work in the background
1326 0 : let tenant_clone = Arc::clone(&tenant);
1327 0 : let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
1328 0 : task_mgr::spawn(
1329 0 : &tokio::runtime::Handle::current(),
1330 0 : TaskKind::Attach,
1331 0 : tenant_shard_id,
1332 0 : None,
1333 0 : "attach tenant",
1334 0 : async move {
1335 0 :
1336 0 : info!(
1337 : ?attach_mode,
1338 0 : "Attaching tenant"
1339 : );
1340 :
1341 0 : let _gate_guard = attach_gate_guard;
1342 0 :
1343 0 : // Is this tenant being spawned as part of process startup?
1344 0 : let starting_up = init_order.is_some();
1345 0 : scopeguard::defer! {
1346 0 : if starting_up {
1347 0 : TENANT.startup_complete.inc();
1348 0 : }
1349 0 : }
1350 :
1351 : // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
1352 : enum BrokenVerbosity {
1353 : Error,
1354 : Info
1355 : }
1356 0 : let make_broken =
1357 0 : |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
1358 0 : match verbosity {
1359 : BrokenVerbosity::Info => {
1360 0 : info!("attach cancelled, setting tenant state to Broken: {err}");
1361 : },
1362 : BrokenVerbosity::Error => {
1363 0 : error!("attach failed, setting tenant state to Broken: {err:?}");
1364 : }
1365 : }
1366 0 : t.state.send_modify(|state| {
1367 0 : // The Stopping case is for when we have passed control on to DeleteTenantFlow:
1368 0 : // if it errors, we will call make_broken when tenant is already in Stopping.
1369 0 : assert!(
1370 0 : matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
1371 0 : "the attach task owns the tenant state until activation is complete"
1372 : );
1373 :
1374 0 : *state = TenantState::broken_from_reason(err.to_string());
1375 0 : });
1376 0 : };
1377 :
1378 : // TODO: should also be rejecting tenant conf changes that violate this check.
1379 0 : if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
1380 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1381 0 : return Ok(());
1382 0 : }
1383 0 :
1384 0 : let mut init_order = init_order;
1385 0 : // take the completion because initial tenant loading will complete when all of
1386 0 : // these tasks complete.
1387 0 : let _completion = init_order
1388 0 : .as_mut()
1389 0 : .and_then(|x| x.initial_tenant_load.take());
1390 0 : let remote_load_completion = init_order
1391 0 : .as_mut()
1392 0 : .and_then(|x| x.initial_tenant_load_remote.take());
1393 :
1394 : enum AttachType<'a> {
1395 : /// We are attaching this tenant lazily in the background.
1396 : Warmup {
1397 : _permit: tokio::sync::SemaphorePermit<'a>,
1398 : during_startup: bool
1399 : },
1400 : /// We are attaching this tenant as soon as we can, because for example an
1401 : /// endpoint tried to access it.
1402 : OnDemand,
1403 : /// During normal operations after startup, we are attaching a tenant, and
1404 : /// eager attach was requested.
1405 : Normal,
1406 : }
1407 :
1408 0 : let attach_type = if matches!(mode, SpawnMode::Lazy) {
1409 : // Before doing any I/O, wait for at least one of:
1410 : // - A client attempting to access to this tenant (on-demand loading)
1411 : // - A permit becoming available in the warmup semaphore (background warmup)
1412 :
1413 0 : tokio::select!(
1414 0 : permit = tenant_clone.activate_now_sem.acquire() => {
1415 0 : let _ = permit.expect("activate_now_sem is never closed");
1416 0 : tracing::info!("Activating tenant (on-demand)");
1417 0 : AttachType::OnDemand
1418 : },
1419 0 : permit = conf.concurrent_tenant_warmup.inner().acquire() => {
1420 0 : let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
1421 0 : tracing::info!("Activating tenant (warmup)");
1422 0 : AttachType::Warmup {
1423 0 : _permit,
1424 0 : during_startup: init_order.is_some()
1425 0 : }
1426 : }
1427 0 : _ = tenant_clone.cancel.cancelled() => {
1428 : // This is safe, but should be pretty rare: it is interesting if a tenant
1429 : // stayed in Activating for such a long time that shutdown found it in
1430 : // that state.
1431 0 : tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
1432 : // Make the tenant broken so that set_stopping will not hang waiting for it to leave
1433 : // the Attaching state. This is an over-reaction (nothing really broke, the tenant is
1434 : // just shutting down), but ensures progress.
1435 0 : make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
1436 0 : return Ok(());
1437 : },
1438 : )
1439 : } else {
1440 : // SpawnMode::{Create,Eager} always cause jumping ahead of the
1441 : // concurrent_tenant_warmup queue
1442 0 : AttachType::Normal
1443 : };
1444 :
1445 0 : let preload = match &mode {
1446 : SpawnMode::Eager | SpawnMode::Lazy => {
1447 0 : let _preload_timer = TENANT.preload.start_timer();
1448 0 : let res = tenant_clone
1449 0 : .preload(&remote_storage, task_mgr::shutdown_token())
1450 0 : .await;
1451 0 : match res {
1452 0 : Ok(p) => Some(p),
1453 0 : Err(e) => {
1454 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1455 0 : return Ok(());
1456 : }
1457 : }
1458 : }
1459 :
1460 : };
1461 :
1462 : // Remote preload is complete.
1463 0 : drop(remote_load_completion);
1464 0 :
1465 0 :
1466 0 : // We will time the duration of the attach phase unless this is a creation (attach will do no work)
1467 0 : let attach_start = std::time::Instant::now();
1468 0 : let attached = {
1469 0 : let _attach_timer = Some(TENANT.attach.start_timer());
1470 0 : tenant_clone.attach(preload, &ctx).await
1471 : };
1472 0 : let attach_duration = attach_start.elapsed();
1473 0 : _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
1474 0 :
1475 0 : match attached {
1476 : Ok(()) => {
1477 0 : info!("attach finished, activating");
1478 0 : tenant_clone.activate(broker_client, None, &ctx);
1479 : }
1480 0 : Err(e) => {
1481 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1482 0 : }
1483 : }
1484 :
1485 : // If we are doing an opportunistic warmup attachment at startup, initialize
1486 : // logical size at the same time. This is better than starting a bunch of idle tenants
1487 : // with cold caches and then coming back later to initialize their logical sizes.
1488 : //
1489 : // It also prevents the warmup proccess competing with the concurrency limit on
1490 : // logical size calculations: if logical size calculation semaphore is saturated,
1491 : // then warmup will wait for that before proceeding to the next tenant.
1492 0 : if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
1493 0 : let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
1494 0 : tracing::info!("Waiting for initial logical sizes while warming up...");
1495 0 : while futs.next().await.is_some() {}
1496 0 : tracing::info!("Warm-up complete");
1497 0 : }
1498 :
1499 0 : Ok(())
1500 0 : }
1501 0 : .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
1502 : );
1503 0 : Ok(tenant)
1504 0 : }
1505 :
1506 : #[instrument(skip_all)]
1507 : pub(crate) async fn preload(
1508 : self: &Arc<Self>,
1509 : remote_storage: &GenericRemoteStorage,
1510 : cancel: CancellationToken,
1511 : ) -> anyhow::Result<TenantPreload> {
1512 : span::debug_assert_current_span_has_tenant_id();
1513 : // Get list of remote timelines
1514 : // download index files for every tenant timeline
1515 : info!("listing remote timelines");
1516 : let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
1517 : remote_storage,
1518 : self.tenant_shard_id,
1519 : cancel.clone(),
1520 : )
1521 : .await?;
1522 : let (offloaded_add, tenant_manifest) =
1523 : match remote_timeline_client::download_tenant_manifest(
1524 : remote_storage,
1525 : &self.tenant_shard_id,
1526 : self.generation,
1527 : &cancel,
1528 : )
1529 : .await
1530 : {
1531 : Ok((tenant_manifest, _generation, _manifest_mtime)) => (
1532 : format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
1533 : tenant_manifest,
1534 : ),
1535 : Err(DownloadError::NotFound) => {
1536 : ("no manifest".to_string(), TenantManifest::empty())
1537 : }
1538 : Err(e) => Err(e)?,
1539 : };
1540 :
1541 : info!(
1542 : "found {} timelines, and {offloaded_add}",
1543 : remote_timeline_ids.len()
1544 : );
1545 :
1546 : for k in other_keys {
1547 : warn!("Unexpected non timeline key {k}");
1548 : }
1549 :
1550 : // Avoid downloading IndexPart of offloaded timelines.
1551 : let mut offloaded_with_prefix = HashSet::new();
1552 : for offloaded in tenant_manifest.offloaded_timelines.iter() {
1553 : if remote_timeline_ids.remove(&offloaded.timeline_id) {
1554 : offloaded_with_prefix.insert(offloaded.timeline_id);
1555 : } else {
1556 : // We'll take care later of timelines in the manifest without a prefix
1557 : }
1558 : }
1559 :
1560 : let timelines = self
1561 : .load_timelines_metadata(remote_timeline_ids, remote_storage, cancel)
1562 : .await?;
1563 :
1564 : Ok(TenantPreload {
1565 : tenant_manifest,
1566 : timelines: timelines
1567 : .into_iter()
1568 12 : .map(|(id, tl)| (id, Some(tl)))
1569 0 : .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
1570 : .collect(),
1571 : })
1572 : }
1573 :
1574 : ///
1575 : /// Background task that downloads all data for a tenant and brings it to Active state.
1576 : ///
1577 : /// No background tasks are started as part of this routine.
1578 : ///
1579 440 : async fn attach(
1580 440 : self: &Arc<Tenant>,
1581 440 : preload: Option<TenantPreload>,
1582 440 : ctx: &RequestContext,
1583 440 : ) -> anyhow::Result<()> {
1584 440 : span::debug_assert_current_span_has_tenant_id();
1585 440 :
1586 440 : failpoint_support::sleep_millis_async!("before-attaching-tenant");
1587 :
1588 440 : let Some(preload) = preload else {
1589 0 : anyhow::bail!("local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624");
1590 : };
1591 :
1592 440 : let mut offloaded_timeline_ids = HashSet::new();
1593 440 : let mut offloaded_timelines_list = Vec::new();
1594 440 : for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
1595 0 : let timeline_id = timeline_manifest.timeline_id;
1596 0 : let offloaded_timeline =
1597 0 : OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
1598 0 : offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
1599 0 : offloaded_timeline_ids.insert(timeline_id);
1600 0 : }
1601 : // Complete deletions for offloaded timeline id's from manifest.
1602 : // The manifest will be uploaded later in this function.
1603 440 : offloaded_timelines_list
1604 440 : .retain(|(offloaded_id, offloaded)| {
1605 0 : // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
1606 0 : // If there is dangling references in another location, they need to be cleaned up.
1607 0 : let delete = !preload.timelines.contains_key(offloaded_id);
1608 0 : if delete {
1609 0 : tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
1610 0 : offloaded.defuse_for_tenant_drop();
1611 0 : }
1612 0 : !delete
1613 440 : });
1614 440 :
1615 440 : let mut timelines_to_resume_deletions = vec![];
1616 440 :
1617 440 : let mut remote_index_and_client = HashMap::new();
1618 440 : let mut timeline_ancestors = HashMap::new();
1619 440 : let mut existent_timelines = HashSet::new();
1620 452 : for (timeline_id, preload) in preload.timelines {
1621 12 : let Some(preload) = preload else { continue };
1622 : // This is an invariant of the `preload` function's API
1623 12 : assert!(!offloaded_timeline_ids.contains(&timeline_id));
1624 12 : let index_part = match preload.index_part {
1625 12 : Ok(i) => {
1626 12 : debug!("remote index part exists for timeline {timeline_id}");
1627 : // We found index_part on the remote, this is the standard case.
1628 12 : existent_timelines.insert(timeline_id);
1629 12 : i
1630 : }
1631 : Err(DownloadError::NotFound) => {
1632 : // There is no index_part on the remote. We only get here
1633 : // if there is some prefix for the timeline in the remote storage.
1634 : // This can e.g. be the initdb.tar.zst archive, maybe a
1635 : // remnant from a prior incomplete creation or deletion attempt.
1636 : // Delete the local directory as the deciding criterion for a
1637 : // timeline's existence is presence of index_part.
1638 0 : info!(%timeline_id, "index_part not found on remote");
1639 0 : continue;
1640 : }
1641 0 : Err(DownloadError::Fatal(why)) => {
1642 0 : // If, while loading one remote timeline, we saw an indication that our generation
1643 0 : // number is likely invalid, then we should not load the whole tenant.
1644 0 : error!(%timeline_id, "Fatal error loading timeline: {why}");
1645 0 : anyhow::bail!(why.to_string());
1646 : }
1647 0 : Err(e) => {
1648 0 : // Some (possibly ephemeral) error happened during index_part download.
1649 0 : // Pretend the timeline exists to not delete the timeline directory,
1650 0 : // as it might be a temporary issue and we don't want to re-download
1651 0 : // everything after it resolves.
1652 0 : warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
1653 :
1654 0 : existent_timelines.insert(timeline_id);
1655 0 : continue;
1656 : }
1657 : };
1658 12 : match index_part {
1659 12 : MaybeDeletedIndexPart::IndexPart(index_part) => {
1660 12 : timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
1661 12 : remote_index_and_client.insert(timeline_id, (index_part, preload.client));
1662 12 : }
1663 0 : MaybeDeletedIndexPart::Deleted(index_part) => {
1664 0 : info!(
1665 0 : "timeline {} is deleted, picking to resume deletion",
1666 : timeline_id
1667 : );
1668 0 : timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
1669 : }
1670 : }
1671 : }
1672 :
1673 440 : let mut gc_blocks = HashMap::new();
1674 :
1675 : // For every timeline, download the metadata file, scan the local directory,
1676 : // and build a layer map that contains an entry for each remote and local
1677 : // layer file.
1678 440 : let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
1679 452 : for (timeline_id, remote_metadata) in sorted_timelines {
1680 12 : let (index_part, remote_client) = remote_index_and_client
1681 12 : .remove(&timeline_id)
1682 12 : .expect("just put it in above");
1683 :
1684 12 : if let Some(blocking) = index_part.gc_blocking.as_ref() {
1685 : // could just filter these away, but it helps while testing
1686 0 : anyhow::ensure!(
1687 0 : !blocking.reasons.is_empty(),
1688 0 : "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
1689 : );
1690 0 : let prev = gc_blocks.insert(timeline_id, blocking.reasons);
1691 0 : assert!(prev.is_none());
1692 12 : }
1693 :
1694 : // TODO again handle early failure
1695 12 : let effect = self
1696 12 : .load_remote_timeline(
1697 12 : timeline_id,
1698 12 : index_part,
1699 12 : remote_metadata,
1700 12 : self.get_timeline_resources_for(remote_client),
1701 12 : LoadTimelineCause::Attach,
1702 12 : ctx,
1703 12 : )
1704 12 : .await
1705 12 : .with_context(|| {
1706 0 : format!(
1707 0 : "failed to load remote timeline {} for tenant {}",
1708 0 : timeline_id, self.tenant_shard_id
1709 0 : )
1710 12 : })?;
1711 :
1712 12 : match effect {
1713 12 : TimelineInitAndSyncResult::ReadyToActivate(_) => {
1714 12 : // activation happens later, on Tenant::activate
1715 12 : }
1716 : TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
1717 : TimelineInitAndSyncNeedsSpawnImportPgdata {
1718 0 : timeline,
1719 0 : import_pgdata,
1720 0 : guard,
1721 0 : },
1722 0 : ) => {
1723 0 : tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
1724 0 : timeline,
1725 0 : import_pgdata,
1726 0 : ActivateTimelineArgs::No,
1727 0 : guard,
1728 0 : ));
1729 0 : }
1730 : }
1731 : }
1732 :
1733 : // Walk through deleted timelines, resume deletion
1734 440 : for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
1735 0 : remote_timeline_client
1736 0 : .init_upload_queue_stopped_to_continue_deletion(&index_part)
1737 0 : .context("init queue stopped")
1738 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1739 :
1740 0 : DeleteTimelineFlow::resume_deletion(
1741 0 : Arc::clone(self),
1742 0 : timeline_id,
1743 0 : &index_part.metadata,
1744 0 : remote_timeline_client,
1745 0 : )
1746 0 : .instrument(tracing::info_span!("timeline_delete", %timeline_id))
1747 0 : .await
1748 0 : .context("resume_deletion")
1749 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1750 : }
1751 440 : let needs_manifest_upload =
1752 440 : offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
1753 440 : {
1754 440 : let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
1755 440 : offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
1756 440 : }
1757 440 : if needs_manifest_upload {
1758 0 : self.store_tenant_manifest().await?;
1759 440 : }
1760 :
1761 : // The local filesystem contents are a cache of what's in the remote IndexPart;
1762 : // IndexPart is the source of truth.
1763 440 : self.clean_up_timelines(&existent_timelines)?;
1764 :
1765 440 : self.gc_block.set_scanned(gc_blocks);
1766 440 :
1767 440 : fail::fail_point!("attach-before-activate", |_| {
1768 0 : anyhow::bail!("attach-before-activate");
1769 440 : });
1770 440 : failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
1771 :
1772 440 : info!("Done");
1773 :
1774 440 : Ok(())
1775 440 : }
1776 :
1777 : /// Check for any local timeline directories that are temporary, or do not correspond to a
1778 : /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
1779 : /// if a timeline was deleted while the tenant was attached to a different pageserver.
1780 440 : fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
1781 440 : let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
1782 :
1783 440 : let entries = match timelines_dir.read_dir_utf8() {
1784 440 : Ok(d) => d,
1785 0 : Err(e) => {
1786 0 : if e.kind() == std::io::ErrorKind::NotFound {
1787 0 : return Ok(());
1788 : } else {
1789 0 : return Err(e).context("list timelines directory for tenant");
1790 : }
1791 : }
1792 : };
1793 :
1794 456 : for entry in entries {
1795 16 : let entry = entry.context("read timeline dir entry")?;
1796 16 : let entry_path = entry.path();
1797 :
1798 16 : let purge = if crate::is_temporary(entry_path) {
1799 0 : true
1800 : } else {
1801 16 : match TimelineId::try_from(entry_path.file_name()) {
1802 16 : Ok(i) => {
1803 16 : // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
1804 16 : !existent_timelines.contains(&i)
1805 : }
1806 0 : Err(e) => {
1807 0 : tracing::warn!(
1808 0 : "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
1809 : );
1810 : // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
1811 0 : false
1812 : }
1813 : }
1814 : };
1815 :
1816 16 : if purge {
1817 4 : tracing::info!("Purging stale timeline dentry {entry_path}");
1818 4 : if let Err(e) = match entry.file_type() {
1819 4 : Ok(t) => if t.is_dir() {
1820 4 : std::fs::remove_dir_all(entry_path)
1821 : } else {
1822 0 : std::fs::remove_file(entry_path)
1823 : }
1824 4 : .or_else(fs_ext::ignore_not_found),
1825 0 : Err(e) => Err(e),
1826 : } {
1827 0 : tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
1828 4 : }
1829 12 : }
1830 : }
1831 :
1832 440 : Ok(())
1833 440 : }
1834 :
1835 : /// Get sum of all remote timelines sizes
1836 : ///
1837 : /// This function relies on the index_part instead of listing the remote storage
1838 0 : pub fn remote_size(&self) -> u64 {
1839 0 : let mut size = 0;
1840 :
1841 0 : for timeline in self.list_timelines() {
1842 0 : size += timeline.remote_client.get_remote_physical_size();
1843 0 : }
1844 :
1845 0 : size
1846 0 : }
1847 :
1848 : #[instrument(skip_all, fields(timeline_id=%timeline_id))]
1849 : async fn load_remote_timeline(
1850 : self: &Arc<Self>,
1851 : timeline_id: TimelineId,
1852 : index_part: IndexPart,
1853 : remote_metadata: TimelineMetadata,
1854 : resources: TimelineResources,
1855 : cause: LoadTimelineCause,
1856 : ctx: &RequestContext,
1857 : ) -> anyhow::Result<TimelineInitAndSyncResult> {
1858 : span::debug_assert_current_span_has_tenant_id();
1859 :
1860 : info!("downloading index file for timeline {}", timeline_id);
1861 : tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
1862 : .await
1863 : .context("Failed to create new timeline directory")?;
1864 :
1865 : let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
1866 : let timelines = self.timelines.lock().unwrap();
1867 : Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
1868 0 : || {
1869 0 : anyhow::anyhow!(
1870 0 : "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
1871 0 : )
1872 0 : },
1873 : )?))
1874 : } else {
1875 : None
1876 : };
1877 :
1878 : self.timeline_init_and_sync(
1879 : timeline_id,
1880 : resources,
1881 : index_part,
1882 : remote_metadata,
1883 : ancestor,
1884 : cause,
1885 : ctx,
1886 : )
1887 : .await
1888 : }
1889 :
1890 440 : async fn load_timelines_metadata(
1891 440 : self: &Arc<Tenant>,
1892 440 : timeline_ids: HashSet<TimelineId>,
1893 440 : remote_storage: &GenericRemoteStorage,
1894 440 : cancel: CancellationToken,
1895 440 : ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
1896 440 : let mut part_downloads = JoinSet::new();
1897 452 : for timeline_id in timeline_ids {
1898 12 : let cancel_clone = cancel.clone();
1899 12 : part_downloads.spawn(
1900 12 : self.load_timeline_metadata(timeline_id, remote_storage.clone(), cancel_clone)
1901 12 : .instrument(info_span!("download_index_part", %timeline_id)),
1902 : );
1903 : }
1904 :
1905 440 : let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
1906 :
1907 : loop {
1908 452 : tokio::select!(
1909 452 : next = part_downloads.join_next() => {
1910 452 : match next {
1911 12 : Some(result) => {
1912 12 : let preload = result.context("join preload task")?;
1913 12 : timeline_preloads.insert(preload.timeline_id, preload);
1914 : },
1915 : None => {
1916 440 : break;
1917 : }
1918 : }
1919 : },
1920 452 : _ = cancel.cancelled() => {
1921 0 : anyhow::bail!("Cancelled while waiting for remote index download")
1922 : }
1923 : )
1924 : }
1925 :
1926 440 : Ok(timeline_preloads)
1927 440 : }
1928 :
1929 12 : fn build_timeline_client(
1930 12 : &self,
1931 12 : timeline_id: TimelineId,
1932 12 : remote_storage: GenericRemoteStorage,
1933 12 : ) -> RemoteTimelineClient {
1934 12 : RemoteTimelineClient::new(
1935 12 : remote_storage.clone(),
1936 12 : self.deletion_queue_client.clone(),
1937 12 : self.conf,
1938 12 : self.tenant_shard_id,
1939 12 : timeline_id,
1940 12 : self.generation,
1941 12 : &self.tenant_conf.load().location,
1942 12 : )
1943 12 : }
1944 :
1945 12 : fn load_timeline_metadata(
1946 12 : self: &Arc<Tenant>,
1947 12 : timeline_id: TimelineId,
1948 12 : remote_storage: GenericRemoteStorage,
1949 12 : cancel: CancellationToken,
1950 12 : ) -> impl Future<Output = TimelinePreload> {
1951 12 : let client = self.build_timeline_client(timeline_id, remote_storage);
1952 12 : async move {
1953 12 : debug_assert_current_span_has_tenant_and_timeline_id();
1954 12 : debug!("starting index part download");
1955 :
1956 12 : let index_part = client.download_index_file(&cancel).await;
1957 :
1958 12 : debug!("finished index part download");
1959 :
1960 12 : TimelinePreload {
1961 12 : client,
1962 12 : timeline_id,
1963 12 : index_part,
1964 12 : }
1965 12 : }
1966 12 : }
1967 :
1968 0 : fn check_to_be_archived_has_no_unarchived_children(
1969 0 : timeline_id: TimelineId,
1970 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
1971 0 : ) -> Result<(), TimelineArchivalError> {
1972 0 : let children: Vec<TimelineId> = timelines
1973 0 : .iter()
1974 0 : .filter_map(|(id, entry)| {
1975 0 : if entry.get_ancestor_timeline_id() != Some(timeline_id) {
1976 0 : return None;
1977 0 : }
1978 0 : if entry.is_archived() == Some(true) {
1979 0 : return None;
1980 0 : }
1981 0 : Some(*id)
1982 0 : })
1983 0 : .collect();
1984 0 :
1985 0 : if !children.is_empty() {
1986 0 : return Err(TimelineArchivalError::HasUnarchivedChildren(children));
1987 0 : }
1988 0 : Ok(())
1989 0 : }
1990 :
1991 0 : fn check_ancestor_of_to_be_unarchived_is_not_archived(
1992 0 : ancestor_timeline_id: TimelineId,
1993 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
1994 0 : offloaded_timelines: &std::sync::MutexGuard<
1995 0 : '_,
1996 0 : HashMap<TimelineId, Arc<OffloadedTimeline>>,
1997 0 : >,
1998 0 : ) -> Result<(), TimelineArchivalError> {
1999 0 : let has_archived_parent =
2000 0 : if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
2001 0 : ancestor_timeline.is_archived() == Some(true)
2002 0 : } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
2003 0 : true
2004 : } else {
2005 0 : error!("ancestor timeline {ancestor_timeline_id} not found");
2006 0 : if cfg!(debug_assertions) {
2007 0 : panic!("ancestor timeline {ancestor_timeline_id} not found");
2008 0 : }
2009 0 : return Err(TimelineArchivalError::NotFound);
2010 : };
2011 0 : if has_archived_parent {
2012 0 : return Err(TimelineArchivalError::HasArchivedParent(
2013 0 : ancestor_timeline_id,
2014 0 : ));
2015 0 : }
2016 0 : Ok(())
2017 0 : }
2018 :
2019 0 : fn check_to_be_unarchived_timeline_has_no_archived_parent(
2020 0 : timeline: &Arc<Timeline>,
2021 0 : ) -> Result<(), TimelineArchivalError> {
2022 0 : if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
2023 0 : if ancestor_timeline.is_archived() == Some(true) {
2024 0 : return Err(TimelineArchivalError::HasArchivedParent(
2025 0 : ancestor_timeline.timeline_id,
2026 0 : ));
2027 0 : }
2028 0 : }
2029 0 : Ok(())
2030 0 : }
2031 :
2032 : /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
2033 : ///
2034 : /// Counterpart to [`offload_timeline`].
2035 0 : async fn unoffload_timeline(
2036 0 : self: &Arc<Self>,
2037 0 : timeline_id: TimelineId,
2038 0 : broker_client: storage_broker::BrokerClientChannel,
2039 0 : ctx: RequestContext,
2040 0 : ) -> Result<Arc<Timeline>, TimelineArchivalError> {
2041 0 : info!("unoffloading timeline");
2042 :
2043 : // We activate the timeline below manually, so this must be called on an active tenant.
2044 : // We expect callers of this function to ensure this.
2045 0 : match self.current_state() {
2046 : TenantState::Activating { .. }
2047 : | TenantState::Attaching
2048 : | TenantState::Broken { .. } => {
2049 0 : panic!("Timeline expected to be active")
2050 : }
2051 0 : TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
2052 0 : TenantState::Active => {}
2053 0 : }
2054 0 : let cancel = self.cancel.clone();
2055 0 :
2056 0 : // Protect against concurrent attempts to use this TimelineId
2057 0 : // We don't care much about idempotency, as it's ensured a layer above.
2058 0 : let allow_offloaded = true;
2059 0 : let _create_guard = self
2060 0 : .create_timeline_create_guard(
2061 0 : timeline_id,
2062 0 : CreateTimelineIdempotency::FailWithConflict,
2063 0 : allow_offloaded,
2064 0 : )
2065 0 : .map_err(|err| match err {
2066 0 : TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
2067 : TimelineExclusionError::AlreadyExists { .. } => {
2068 0 : TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
2069 : }
2070 0 : TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
2071 0 : TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
2072 0 : })?;
2073 :
2074 0 : let timeline_preload = self
2075 0 : .load_timeline_metadata(timeline_id, self.remote_storage.clone(), cancel.clone())
2076 0 : .await;
2077 :
2078 0 : let index_part = match timeline_preload.index_part {
2079 0 : Ok(index_part) => {
2080 0 : debug!("remote index part exists for timeline {timeline_id}");
2081 0 : index_part
2082 : }
2083 : Err(DownloadError::NotFound) => {
2084 0 : error!(%timeline_id, "index_part not found on remote");
2085 0 : return Err(TimelineArchivalError::NotFound);
2086 : }
2087 0 : Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
2088 0 : Err(e) => {
2089 0 : // Some (possibly ephemeral) error happened during index_part download.
2090 0 : warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
2091 0 : return Err(TimelineArchivalError::Other(
2092 0 : anyhow::Error::new(e).context("downloading index_part from remote storage"),
2093 0 : ));
2094 : }
2095 : };
2096 0 : let index_part = match index_part {
2097 0 : MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
2098 0 : MaybeDeletedIndexPart::Deleted(_index_part) => {
2099 0 : info!("timeline is deleted according to index_part.json");
2100 0 : return Err(TimelineArchivalError::NotFound);
2101 : }
2102 : };
2103 0 : let remote_metadata = index_part.metadata.clone();
2104 0 : let timeline_resources = self.build_timeline_resources(timeline_id);
2105 0 : self.load_remote_timeline(
2106 0 : timeline_id,
2107 0 : index_part,
2108 0 : remote_metadata,
2109 0 : timeline_resources,
2110 0 : LoadTimelineCause::Unoffload,
2111 0 : &ctx,
2112 0 : )
2113 0 : .await
2114 0 : .with_context(|| {
2115 0 : format!(
2116 0 : "failed to load remote timeline {} for tenant {}",
2117 0 : timeline_id, self.tenant_shard_id
2118 0 : )
2119 0 : })
2120 0 : .map_err(TimelineArchivalError::Other)?;
2121 :
2122 0 : let timeline = {
2123 0 : let timelines = self.timelines.lock().unwrap();
2124 0 : let Some(timeline) = timelines.get(&timeline_id) else {
2125 0 : warn!("timeline not available directly after attach");
2126 : // This is not a panic because no locks are held between `load_remote_timeline`
2127 : // which puts the timeline into timelines, and our look into the timeline map.
2128 0 : return Err(TimelineArchivalError::Other(anyhow::anyhow!(
2129 0 : "timeline not available directly after attach"
2130 0 : )));
2131 : };
2132 0 : let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
2133 0 : match offloaded_timelines.remove(&timeline_id) {
2134 0 : Some(offloaded) => {
2135 0 : offloaded.delete_from_ancestor_with_timelines(&timelines);
2136 0 : }
2137 0 : None => warn!("timeline already removed from offloaded timelines"),
2138 : }
2139 :
2140 0 : self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
2141 0 :
2142 0 : Arc::clone(timeline)
2143 0 : };
2144 0 :
2145 0 : // Upload new list of offloaded timelines to S3
2146 0 : self.store_tenant_manifest().await?;
2147 :
2148 : // Activate the timeline (if it makes sense)
2149 0 : if !(timeline.is_broken() || timeline.is_stopping()) {
2150 0 : let background_jobs_can_start = None;
2151 0 : timeline.activate(
2152 0 : self.clone(),
2153 0 : broker_client.clone(),
2154 0 : background_jobs_can_start,
2155 0 : &ctx,
2156 0 : );
2157 0 : }
2158 :
2159 0 : info!("timeline unoffloading complete");
2160 0 : Ok(timeline)
2161 0 : }
2162 :
2163 0 : pub(crate) async fn apply_timeline_archival_config(
2164 0 : self: &Arc<Self>,
2165 0 : timeline_id: TimelineId,
2166 0 : new_state: TimelineArchivalState,
2167 0 : broker_client: storage_broker::BrokerClientChannel,
2168 0 : ctx: RequestContext,
2169 0 : ) -> Result<(), TimelineArchivalError> {
2170 0 : info!("setting timeline archival config");
2171 : // First part: figure out what is needed to do, and do validation
2172 0 : let timeline_or_unarchive_offloaded = 'outer: {
2173 0 : let timelines = self.timelines.lock().unwrap();
2174 :
2175 0 : let Some(timeline) = timelines.get(&timeline_id) else {
2176 0 : let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
2177 0 : let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
2178 0 : return Err(TimelineArchivalError::NotFound);
2179 : };
2180 0 : if new_state == TimelineArchivalState::Archived {
2181 : // It's offloaded already, so nothing to do
2182 0 : return Ok(());
2183 0 : }
2184 0 : if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
2185 0 : Self::check_ancestor_of_to_be_unarchived_is_not_archived(
2186 0 : ancestor_timeline_id,
2187 0 : &timelines,
2188 0 : &offloaded_timelines,
2189 0 : )?;
2190 0 : }
2191 0 : break 'outer None;
2192 : };
2193 :
2194 : // Do some validation. We release the timelines lock below, so there is potential
2195 : // for race conditions: these checks are more present to prevent misunderstandings of
2196 : // the API's capabilities, instead of serving as the sole way to defend their invariants.
2197 0 : match new_state {
2198 : TimelineArchivalState::Unarchived => {
2199 0 : Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
2200 : }
2201 : TimelineArchivalState::Archived => {
2202 0 : Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
2203 : }
2204 : }
2205 0 : Some(Arc::clone(timeline))
2206 : };
2207 :
2208 : // Second part: unoffload timeline (if needed)
2209 0 : let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
2210 0 : timeline
2211 : } else {
2212 : // Turn offloaded timeline into a non-offloaded one
2213 0 : self.unoffload_timeline(timeline_id, broker_client, ctx)
2214 0 : .await?
2215 : };
2216 :
2217 : // Third part: upload new timeline archival state and block until it is present in S3
2218 0 : let upload_needed = match timeline
2219 0 : .remote_client
2220 0 : .schedule_index_upload_for_timeline_archival_state(new_state)
2221 : {
2222 0 : Ok(upload_needed) => upload_needed,
2223 0 : Err(e) => {
2224 0 : if timeline.cancel.is_cancelled() {
2225 0 : return Err(TimelineArchivalError::Cancelled);
2226 : } else {
2227 0 : return Err(TimelineArchivalError::Other(e));
2228 : }
2229 : }
2230 : };
2231 :
2232 0 : if upload_needed {
2233 0 : info!("Uploading new state");
2234 : const MAX_WAIT: Duration = Duration::from_secs(10);
2235 0 : let Ok(v) =
2236 0 : tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
2237 : else {
2238 0 : tracing::warn!("reached timeout for waiting on upload queue");
2239 0 : return Err(TimelineArchivalError::Timeout);
2240 : };
2241 0 : v.map_err(|e| match e {
2242 0 : WaitCompletionError::NotInitialized(e) => {
2243 0 : TimelineArchivalError::Other(anyhow::anyhow!(e))
2244 : }
2245 : WaitCompletionError::UploadQueueShutDownOrStopped => {
2246 0 : TimelineArchivalError::Cancelled
2247 : }
2248 0 : })?;
2249 0 : }
2250 0 : Ok(())
2251 0 : }
2252 :
2253 4 : pub fn get_offloaded_timeline(
2254 4 : &self,
2255 4 : timeline_id: TimelineId,
2256 4 : ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
2257 4 : self.timelines_offloaded
2258 4 : .lock()
2259 4 : .unwrap()
2260 4 : .get(&timeline_id)
2261 4 : .map(Arc::clone)
2262 4 : .ok_or(GetTimelineError::NotFound {
2263 4 : tenant_id: self.tenant_shard_id,
2264 4 : timeline_id,
2265 4 : })
2266 4 : }
2267 :
2268 8 : pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
2269 8 : self.tenant_shard_id
2270 8 : }
2271 :
2272 : /// Get Timeline handle for given Neon timeline ID.
2273 : /// This function is idempotent. It doesn't change internal state in any way.
2274 444 : pub fn get_timeline(
2275 444 : &self,
2276 444 : timeline_id: TimelineId,
2277 444 : active_only: bool,
2278 444 : ) -> Result<Arc<Timeline>, GetTimelineError> {
2279 444 : let timelines_accessor = self.timelines.lock().unwrap();
2280 444 : let timeline = timelines_accessor
2281 444 : .get(&timeline_id)
2282 444 : .ok_or(GetTimelineError::NotFound {
2283 444 : tenant_id: self.tenant_shard_id,
2284 444 : timeline_id,
2285 444 : })?;
2286 :
2287 440 : if active_only && !timeline.is_active() {
2288 0 : Err(GetTimelineError::NotActive {
2289 0 : tenant_id: self.tenant_shard_id,
2290 0 : timeline_id,
2291 0 : state: timeline.current_state(),
2292 0 : })
2293 : } else {
2294 440 : Ok(Arc::clone(timeline))
2295 : }
2296 444 : }
2297 :
2298 : /// Lists timelines the tenant contains.
2299 : /// It's up to callers to omit certain timelines that are not considered ready for use.
2300 0 : pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
2301 0 : self.timelines
2302 0 : .lock()
2303 0 : .unwrap()
2304 0 : .values()
2305 0 : .map(Arc::clone)
2306 0 : .collect()
2307 0 : }
2308 :
2309 : /// Lists timelines the tenant manages, including offloaded ones.
2310 : ///
2311 : /// It's up to callers to omit certain timelines that are not considered ready for use.
2312 0 : pub fn list_timelines_and_offloaded(
2313 0 : &self,
2314 0 : ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
2315 0 : let timelines = self
2316 0 : .timelines
2317 0 : .lock()
2318 0 : .unwrap()
2319 0 : .values()
2320 0 : .map(Arc::clone)
2321 0 : .collect();
2322 0 : let offloaded = self
2323 0 : .timelines_offloaded
2324 0 : .lock()
2325 0 : .unwrap()
2326 0 : .values()
2327 0 : .map(Arc::clone)
2328 0 : .collect();
2329 0 : (timelines, offloaded)
2330 0 : }
2331 :
2332 0 : pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
2333 0 : self.timelines.lock().unwrap().keys().cloned().collect()
2334 0 : }
2335 :
2336 : /// This is used by tests & import-from-basebackup.
2337 : ///
2338 : /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
2339 : /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
2340 : ///
2341 : /// The caller is responsible for getting the timeline into a state that will be accepted
2342 : /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
2343 : /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
2344 : /// to the [`Tenant::timelines`].
2345 : ///
2346 : /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
2347 424 : pub(crate) async fn create_empty_timeline(
2348 424 : self: &Arc<Self>,
2349 424 : new_timeline_id: TimelineId,
2350 424 : initdb_lsn: Lsn,
2351 424 : pg_version: u32,
2352 424 : _ctx: &RequestContext,
2353 424 : ) -> anyhow::Result<UninitializedTimeline> {
2354 424 : anyhow::ensure!(
2355 424 : self.is_active(),
2356 0 : "Cannot create empty timelines on inactive tenant"
2357 : );
2358 :
2359 : // Protect against concurrent attempts to use this TimelineId
2360 424 : let create_guard = match self
2361 424 : .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
2362 424 : .await?
2363 : {
2364 420 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
2365 : StartCreatingTimelineResult::Idempotent(_) => {
2366 0 : unreachable!("FailWithConflict implies we get an error instead")
2367 : }
2368 : };
2369 :
2370 420 : let new_metadata = TimelineMetadata::new(
2371 420 : // Initialize disk_consistent LSN to 0, The caller must import some data to
2372 420 : // make it valid, before calling finish_creation()
2373 420 : Lsn(0),
2374 420 : None,
2375 420 : None,
2376 420 : Lsn(0),
2377 420 : initdb_lsn,
2378 420 : initdb_lsn,
2379 420 : pg_version,
2380 420 : );
2381 420 : self.prepare_new_timeline(
2382 420 : new_timeline_id,
2383 420 : &new_metadata,
2384 420 : create_guard,
2385 420 : initdb_lsn,
2386 420 : None,
2387 420 : )
2388 420 : .await
2389 424 : }
2390 :
2391 : /// Helper for unit tests to create an empty timeline.
2392 : ///
2393 : /// The timeline is has state value `Active` but its background loops are not running.
2394 : // This makes the various functions which anyhow::ensure! for Active state work in tests.
2395 : // Our current tests don't need the background loops.
2396 : #[cfg(test)]
2397 404 : pub async fn create_test_timeline(
2398 404 : self: &Arc<Self>,
2399 404 : new_timeline_id: TimelineId,
2400 404 : initdb_lsn: Lsn,
2401 404 : pg_version: u32,
2402 404 : ctx: &RequestContext,
2403 404 : ) -> anyhow::Result<Arc<Timeline>> {
2404 404 : let uninit_tl = self
2405 404 : .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
2406 404 : .await?;
2407 404 : let tline = uninit_tl.raw_timeline().expect("we just created it");
2408 404 : assert_eq!(tline.get_last_record_lsn(), Lsn(0));
2409 :
2410 : // Setup minimum keys required for the timeline to be usable.
2411 404 : let mut modification = tline.begin_modification(initdb_lsn);
2412 404 : modification
2413 404 : .init_empty_test_timeline()
2414 404 : .context("init_empty_test_timeline")?;
2415 404 : modification
2416 404 : .commit(ctx)
2417 404 : .await
2418 404 : .context("commit init_empty_test_timeline modification")?;
2419 :
2420 : // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
2421 404 : tline.maybe_spawn_flush_loop();
2422 404 : tline.freeze_and_flush().await.context("freeze_and_flush")?;
2423 :
2424 : // Make sure the freeze_and_flush reaches remote storage.
2425 404 : tline.remote_client.wait_completion().await.unwrap();
2426 :
2427 404 : let tl = uninit_tl.finish_creation().await?;
2428 : // The non-test code would call tl.activate() here.
2429 404 : tl.set_state(TimelineState::Active);
2430 404 : Ok(tl)
2431 404 : }
2432 :
2433 : /// Helper for unit tests to create a timeline with some pre-loaded states.
2434 : #[cfg(test)]
2435 : #[allow(clippy::too_many_arguments)]
2436 76 : pub async fn create_test_timeline_with_layers(
2437 76 : self: &Arc<Self>,
2438 76 : new_timeline_id: TimelineId,
2439 76 : initdb_lsn: Lsn,
2440 76 : pg_version: u32,
2441 76 : ctx: &RequestContext,
2442 76 : delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
2443 76 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
2444 76 : end_lsn: Lsn,
2445 76 : ) -> anyhow::Result<Arc<Timeline>> {
2446 : use checks::check_valid_layermap;
2447 : use itertools::Itertools;
2448 :
2449 76 : let tline = self
2450 76 : .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
2451 76 : .await?;
2452 76 : tline.force_advance_lsn(end_lsn);
2453 244 : for deltas in delta_layer_desc {
2454 168 : tline
2455 168 : .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
2456 168 : .await?;
2457 : }
2458 184 : for (lsn, images) in image_layer_desc {
2459 108 : tline
2460 108 : .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
2461 108 : .await?;
2462 : }
2463 76 : let layer_names = tline
2464 76 : .layers
2465 76 : .read()
2466 76 : .await
2467 76 : .layer_map()
2468 76 : .unwrap()
2469 76 : .iter_historic_layers()
2470 352 : .map(|layer| layer.layer_name())
2471 76 : .collect_vec();
2472 76 : if let Some(err) = check_valid_layermap(&layer_names) {
2473 0 : bail!("invalid layermap: {err}");
2474 76 : }
2475 76 : Ok(tline)
2476 76 : }
2477 :
2478 : /// Create a new timeline.
2479 : ///
2480 : /// Returns the new timeline ID and reference to its Timeline object.
2481 : ///
2482 : /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
2483 : /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
2484 : #[allow(clippy::too_many_arguments)]
2485 0 : pub(crate) async fn create_timeline(
2486 0 : self: &Arc<Tenant>,
2487 0 : params: CreateTimelineParams,
2488 0 : broker_client: storage_broker::BrokerClientChannel,
2489 0 : ctx: &RequestContext,
2490 0 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
2491 0 : if !self.is_active() {
2492 0 : if matches!(self.current_state(), TenantState::Stopping { .. }) {
2493 0 : return Err(CreateTimelineError::ShuttingDown);
2494 : } else {
2495 0 : return Err(CreateTimelineError::Other(anyhow::anyhow!(
2496 0 : "Cannot create timelines on inactive tenant"
2497 0 : )));
2498 : }
2499 0 : }
2500 :
2501 0 : let _gate = self
2502 0 : .gate
2503 0 : .enter()
2504 0 : .map_err(|_| CreateTimelineError::ShuttingDown)?;
2505 :
2506 0 : let result: CreateTimelineResult = match params {
2507 : CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
2508 0 : new_timeline_id,
2509 0 : existing_initdb_timeline_id,
2510 0 : pg_version,
2511 0 : }) => {
2512 0 : self.bootstrap_timeline(
2513 0 : new_timeline_id,
2514 0 : pg_version,
2515 0 : existing_initdb_timeline_id,
2516 0 : ctx,
2517 0 : )
2518 0 : .await?
2519 : }
2520 : CreateTimelineParams::Branch(CreateTimelineParamsBranch {
2521 0 : new_timeline_id,
2522 0 : ancestor_timeline_id,
2523 0 : mut ancestor_start_lsn,
2524 : }) => {
2525 0 : let ancestor_timeline = self
2526 0 : .get_timeline(ancestor_timeline_id, false)
2527 0 : .context("Cannot branch off the timeline that's not present in pageserver")?;
2528 :
2529 : // instead of waiting around, just deny the request because ancestor is not yet
2530 : // ready for other purposes either.
2531 0 : if !ancestor_timeline.is_active() {
2532 0 : return Err(CreateTimelineError::AncestorNotActive);
2533 0 : }
2534 0 :
2535 0 : if ancestor_timeline.is_archived() == Some(true) {
2536 0 : info!("tried to branch archived timeline");
2537 0 : return Err(CreateTimelineError::AncestorArchived);
2538 0 : }
2539 :
2540 0 : if let Some(lsn) = ancestor_start_lsn.as_mut() {
2541 0 : *lsn = lsn.align();
2542 0 :
2543 0 : let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
2544 0 : if ancestor_ancestor_lsn > *lsn {
2545 : // can we safely just branch from the ancestor instead?
2546 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
2547 0 : "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
2548 0 : lsn,
2549 0 : ancestor_timeline_id,
2550 0 : ancestor_ancestor_lsn,
2551 0 : )));
2552 0 : }
2553 0 :
2554 0 : // Wait for the WAL to arrive and be processed on the parent branch up
2555 0 : // to the requested branch point. The repository code itself doesn't
2556 0 : // require it, but if we start to receive WAL on the new timeline,
2557 0 : // decoding the new WAL might need to look up previous pages, relation
2558 0 : // sizes etc. and that would get confused if the previous page versions
2559 0 : // are not in the repository yet.
2560 0 : ancestor_timeline
2561 0 : .wait_lsn(
2562 0 : *lsn,
2563 0 : timeline::WaitLsnWaiter::Tenant,
2564 0 : timeline::WaitLsnTimeout::Default,
2565 0 : ctx,
2566 0 : )
2567 0 : .await
2568 0 : .map_err(|e| match e {
2569 0 : e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
2570 0 : CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
2571 : }
2572 0 : WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
2573 0 : })?;
2574 0 : }
2575 :
2576 0 : self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
2577 0 : .await?
2578 : }
2579 0 : CreateTimelineParams::ImportPgdata(params) => {
2580 0 : self.create_timeline_import_pgdata(
2581 0 : params,
2582 0 : ActivateTimelineArgs::Yes {
2583 0 : broker_client: broker_client.clone(),
2584 0 : },
2585 0 : ctx,
2586 0 : )
2587 0 : .await?
2588 : }
2589 : };
2590 :
2591 : // At this point we have dropped our guard on [`Self::timelines_creating`], and
2592 : // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet. We must
2593 : // not send a success to the caller until it is. The same applies to idempotent retries.
2594 : //
2595 : // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
2596 : // assume that, because they can see the timeline via API, that the creation is done and
2597 : // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
2598 : // until it is durable, e.g., by extending the time we hold the creation guard. This also
2599 : // interacts with UninitializedTimeline and is generally a bit tricky.
2600 : //
2601 : // To re-emphasize: the only correct way to create a timeline is to repeat calling the
2602 : // creation API until it returns success. Only then is durability guaranteed.
2603 0 : info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
2604 0 : result
2605 0 : .timeline()
2606 0 : .remote_client
2607 0 : .wait_completion()
2608 0 : .await
2609 0 : .map_err(|e| match e {
2610 : WaitCompletionError::NotInitialized(
2611 0 : e, // If the queue is already stopped, it's a shutdown error.
2612 0 : ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
2613 : WaitCompletionError::NotInitialized(_) => {
2614 : // This is a bug: we should never try to wait for uploads before initializing the timeline
2615 0 : debug_assert!(false);
2616 0 : CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
2617 : }
2618 : WaitCompletionError::UploadQueueShutDownOrStopped => {
2619 0 : CreateTimelineError::ShuttingDown
2620 : }
2621 0 : })?;
2622 :
2623 : // The creating task is responsible for activating the timeline.
2624 : // We do this after `wait_completion()` so that we don't spin up tasks that start
2625 : // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
2626 0 : let activated_timeline = match result {
2627 0 : CreateTimelineResult::Created(timeline) => {
2628 0 : timeline.activate(self.clone(), broker_client, None, ctx);
2629 0 : timeline
2630 : }
2631 0 : CreateTimelineResult::Idempotent(timeline) => {
2632 0 : info!(
2633 0 : "request was deemed idempotent, activation will be done by the creating task"
2634 : );
2635 0 : timeline
2636 : }
2637 0 : CreateTimelineResult::ImportSpawned(timeline) => {
2638 0 : info!("import task spawned, timeline will become visible and activated once the import is done");
2639 0 : timeline
2640 : }
2641 : };
2642 :
2643 0 : Ok(activated_timeline)
2644 0 : }
2645 :
2646 : /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
2647 : /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
2648 : /// [`Tenant::timelines`] map when the import completes.
2649 : /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
2650 : /// for the response.
2651 0 : async fn create_timeline_import_pgdata(
2652 0 : self: &Arc<Tenant>,
2653 0 : params: CreateTimelineParamsImportPgdata,
2654 0 : activate: ActivateTimelineArgs,
2655 0 : ctx: &RequestContext,
2656 0 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
2657 0 : let CreateTimelineParamsImportPgdata {
2658 0 : new_timeline_id,
2659 0 : location,
2660 0 : idempotency_key,
2661 0 : } = params;
2662 0 :
2663 0 : let started_at = chrono::Utc::now().naive_utc();
2664 :
2665 : //
2666 : // There's probably a simpler way to upload an index part, but, remote_timeline_client
2667 : // is the canonical way we do it.
2668 : // - create an empty timeline in-memory
2669 : // - use its remote_timeline_client to do the upload
2670 : // - dispose of the uninit timeline
2671 : // - keep the creation guard alive
2672 :
2673 0 : let timeline_create_guard = match self
2674 0 : .start_creating_timeline(
2675 0 : new_timeline_id,
2676 0 : CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
2677 0 : idempotency_key: idempotency_key.clone(),
2678 0 : }),
2679 0 : )
2680 0 : .await?
2681 : {
2682 0 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
2683 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
2684 0 : return Ok(CreateTimelineResult::Idempotent(timeline))
2685 : }
2686 : };
2687 :
2688 0 : let mut uninit_timeline = {
2689 0 : let this = &self;
2690 0 : let initdb_lsn = Lsn(0);
2691 0 : let _ctx = ctx;
2692 0 : async move {
2693 0 : let new_metadata = TimelineMetadata::new(
2694 0 : // Initialize disk_consistent LSN to 0, The caller must import some data to
2695 0 : // make it valid, before calling finish_creation()
2696 0 : Lsn(0),
2697 0 : None,
2698 0 : None,
2699 0 : Lsn(0),
2700 0 : initdb_lsn,
2701 0 : initdb_lsn,
2702 0 : 15,
2703 0 : );
2704 0 : this.prepare_new_timeline(
2705 0 : new_timeline_id,
2706 0 : &new_metadata,
2707 0 : timeline_create_guard,
2708 0 : initdb_lsn,
2709 0 : None,
2710 0 : )
2711 0 : .await
2712 0 : }
2713 0 : }
2714 0 : .await?;
2715 :
2716 0 : let in_progress = import_pgdata::index_part_format::InProgress {
2717 0 : idempotency_key,
2718 0 : location,
2719 0 : started_at,
2720 0 : };
2721 0 : let index_part = import_pgdata::index_part_format::Root::V1(
2722 0 : import_pgdata::index_part_format::V1::InProgress(in_progress),
2723 0 : );
2724 0 : uninit_timeline
2725 0 : .raw_timeline()
2726 0 : .unwrap()
2727 0 : .remote_client
2728 0 : .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
2729 :
2730 : // wait_completion happens in caller
2731 :
2732 0 : let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
2733 0 :
2734 0 : tokio::spawn(self.clone().create_timeline_import_pgdata_task(
2735 0 : timeline.clone(),
2736 0 : index_part,
2737 0 : activate,
2738 0 : timeline_create_guard,
2739 0 : ));
2740 0 :
2741 0 : // NB: the timeline doesn't exist in self.timelines at this point
2742 0 : Ok(CreateTimelineResult::ImportSpawned(timeline))
2743 0 : }
2744 :
2745 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), timeline_id=%timeline.timeline_id))]
2746 : async fn create_timeline_import_pgdata_task(
2747 : self: Arc<Tenant>,
2748 : timeline: Arc<Timeline>,
2749 : index_part: import_pgdata::index_part_format::Root,
2750 : activate: ActivateTimelineArgs,
2751 : timeline_create_guard: TimelineCreateGuard,
2752 : ) {
2753 : debug_assert_current_span_has_tenant_and_timeline_id();
2754 : info!("starting");
2755 : scopeguard::defer! {info!("exiting")};
2756 :
2757 : let res = self
2758 : .create_timeline_import_pgdata_task_impl(
2759 : timeline,
2760 : index_part,
2761 : activate,
2762 : timeline_create_guard,
2763 : )
2764 : .await;
2765 : if let Err(err) = &res {
2766 : error!(?err, "task failed");
2767 : // TODO sleep & retry, sensitive to tenant shutdown
2768 : // TODO: allow timeline deletion requests => should cancel the task
2769 : }
2770 : }
2771 :
2772 0 : async fn create_timeline_import_pgdata_task_impl(
2773 0 : self: Arc<Tenant>,
2774 0 : timeline: Arc<Timeline>,
2775 0 : index_part: import_pgdata::index_part_format::Root,
2776 0 : activate: ActivateTimelineArgs,
2777 0 : timeline_create_guard: TimelineCreateGuard,
2778 0 : ) -> Result<(), anyhow::Error> {
2779 0 : let ctx = RequestContext::new(TaskKind::ImportPgdata, DownloadBehavior::Warn);
2780 0 :
2781 0 : info!("importing pgdata");
2782 0 : import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
2783 0 : .await
2784 0 : .context("import")?;
2785 0 : info!("import done");
2786 :
2787 : //
2788 : // Reload timeline from remote.
2789 : // This proves that the remote state is attachable, and it reuses the code.
2790 : //
2791 : // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
2792 : // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
2793 : // But our activate() call might launch new background tasks after Tenant::shutdown
2794 : // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
2795 : // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
2796 : // down while bootstrapping/branching + activating), but, the race condition is much more likely
2797 : // to manifest because of the long runtime of this import task.
2798 :
2799 : // in theory this shouldn't even .await anything except for coop yield
2800 0 : info!("shutting down timeline");
2801 0 : timeline.shutdown(ShutdownMode::Hard).await;
2802 0 : info!("timeline shut down, reloading from remote");
2803 : // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
2804 : // let Some(timeline) = Arc::into_inner(timeline) else {
2805 : // anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
2806 : // };
2807 0 : let timeline_id = timeline.timeline_id;
2808 0 :
2809 0 : // load from object storage like Tenant::attach does
2810 0 : let resources = self.build_timeline_resources(timeline_id);
2811 0 : let index_part = resources
2812 0 : .remote_client
2813 0 : .download_index_file(&self.cancel)
2814 0 : .await?;
2815 0 : let index_part = match index_part {
2816 : MaybeDeletedIndexPart::Deleted(_) => {
2817 : // likely concurrent delete call, cplane should prevent this
2818 0 : anyhow::bail!("index part says deleted but we are not done creating yet, this should not happen but")
2819 : }
2820 0 : MaybeDeletedIndexPart::IndexPart(p) => p,
2821 0 : };
2822 0 : let metadata = index_part.metadata.clone();
2823 0 : self
2824 0 : .load_remote_timeline(timeline_id, index_part, metadata, resources, LoadTimelineCause::ImportPgdata{
2825 0 : create_guard: timeline_create_guard, activate, }, &ctx)
2826 0 : .await?
2827 0 : .ready_to_activate()
2828 0 : .context("implementation error: reloaded timeline still needs import after import reported success")?;
2829 :
2830 0 : anyhow::Ok(())
2831 0 : }
2832 :
2833 0 : pub(crate) async fn delete_timeline(
2834 0 : self: Arc<Self>,
2835 0 : timeline_id: TimelineId,
2836 0 : ) -> Result<(), DeleteTimelineError> {
2837 0 : DeleteTimelineFlow::run(&self, timeline_id).await?;
2838 :
2839 0 : Ok(())
2840 0 : }
2841 :
2842 : /// perform one garbage collection iteration, removing old data files from disk.
2843 : /// this function is periodically called by gc task.
2844 : /// also it can be explicitly requested through page server api 'do_gc' command.
2845 : ///
2846 : /// `target_timeline_id` specifies the timeline to GC, or None for all.
2847 : ///
2848 : /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
2849 : /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
2850 : /// the amount of history, as LSN difference from current latest LSN on each timeline.
2851 : /// `pitr` specifies the same as a time difference from the current time. The effective
2852 : /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
2853 : /// requires more history to be retained.
2854 : //
2855 1508 : pub(crate) async fn gc_iteration(
2856 1508 : &self,
2857 1508 : target_timeline_id: Option<TimelineId>,
2858 1508 : horizon: u64,
2859 1508 : pitr: Duration,
2860 1508 : cancel: &CancellationToken,
2861 1508 : ctx: &RequestContext,
2862 1508 : ) -> Result<GcResult, GcError> {
2863 1508 : // Don't start doing work during shutdown
2864 1508 : if let TenantState::Stopping { .. } = self.current_state() {
2865 0 : return Ok(GcResult::default());
2866 1508 : }
2867 1508 :
2868 1508 : // there is a global allowed_error for this
2869 1508 : if !self.is_active() {
2870 0 : return Err(GcError::NotActive);
2871 1508 : }
2872 1508 :
2873 1508 : {
2874 1508 : let conf = self.tenant_conf.load();
2875 1508 :
2876 1508 : // If we may not delete layers, then simply skip GC. Even though a tenant
2877 1508 : // in AttachedMulti state could do GC and just enqueue the blocked deletions,
2878 1508 : // the only advantage to doing it is to perhaps shrink the LayerMap metadata
2879 1508 : // a bit sooner than we would achieve by waiting for AttachedSingle status.
2880 1508 : if !conf.location.may_delete_layers_hint() {
2881 0 : info!("Skipping GC in location state {:?}", conf.location);
2882 0 : return Ok(GcResult::default());
2883 1508 : }
2884 1508 :
2885 1508 : if conf.is_gc_blocked_by_lsn_lease_deadline() {
2886 1500 : info!("Skipping GC because lsn lease deadline is not reached");
2887 1500 : return Ok(GcResult::default());
2888 8 : }
2889 : }
2890 :
2891 8 : let _guard = match self.gc_block.start().await {
2892 8 : Ok(guard) => guard,
2893 0 : Err(reasons) => {
2894 0 : info!("Skipping GC: {reasons}");
2895 0 : return Ok(GcResult::default());
2896 : }
2897 : };
2898 :
2899 8 : self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
2900 8 : .await
2901 1508 : }
2902 :
2903 : /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
2904 : /// whether another compaction is needed, if we still have pending work or if we yield for
2905 : /// immediate L0 compaction.
2906 : ///
2907 : /// Compaction can also be explicitly requested for a timeline via the HTTP API.
2908 0 : async fn compaction_iteration(
2909 0 : self: &Arc<Self>,
2910 0 : cancel: &CancellationToken,
2911 0 : ctx: &RequestContext,
2912 0 : ) -> Result<CompactionOutcome, CompactionError> {
2913 0 : // Don't compact inactive tenants.
2914 0 : if !self.is_active() {
2915 0 : return Ok(CompactionOutcome::Skipped);
2916 0 : }
2917 0 :
2918 0 : // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
2919 0 : // since we need to compact L0 even in AttachedMulti to bound read amplification.
2920 0 : let location = self.tenant_conf.load().location;
2921 0 : if !location.may_upload_layers_hint() {
2922 0 : info!("skipping compaction in location state {location:?}");
2923 0 : return Ok(CompactionOutcome::Skipped);
2924 0 : }
2925 0 :
2926 0 : // Don't compact if the circuit breaker is tripped.
2927 0 : if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
2928 0 : info!("skipping compaction due to previous failures");
2929 0 : return Ok(CompactionOutcome::Skipped);
2930 0 : }
2931 0 :
2932 0 : // Collect all timelines to compact, along with offload instructions and L0 counts.
2933 0 : let mut compact: Vec<Arc<Timeline>> = Vec::new();
2934 0 : let mut offload: HashSet<TimelineId> = HashSet::new();
2935 0 : let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
2936 0 :
2937 0 : {
2938 0 : let offload_enabled = self.get_timeline_offloading_enabled();
2939 0 : let timelines = self.timelines.lock().unwrap();
2940 0 : for (&timeline_id, timeline) in timelines.iter() {
2941 : // Skip inactive timelines.
2942 0 : if !timeline.is_active() {
2943 0 : continue;
2944 0 : }
2945 0 :
2946 0 : // Schedule the timeline for compaction.
2947 0 : compact.push(timeline.clone());
2948 :
2949 : // Schedule the timeline for offloading if eligible.
2950 0 : let can_offload = offload_enabled
2951 0 : && timeline.can_offload().0
2952 0 : && !timelines
2953 0 : .iter()
2954 0 : .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
2955 0 : if can_offload {
2956 0 : offload.insert(timeline_id);
2957 0 : }
2958 : }
2959 : } // release timelines lock
2960 :
2961 0 : for timeline in &compact {
2962 : // Collect L0 counts. Can't await while holding lock above.
2963 0 : if let Ok(lm) = timeline.layers.read().await.layer_map() {
2964 0 : l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
2965 0 : }
2966 : }
2967 :
2968 : // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
2969 : // bound read amplification.
2970 : //
2971 : // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
2972 : // compaction and offloading. We leave that as a potential problem to solve later. Consider
2973 : // splitting L0 and image/GC compaction to separate background jobs.
2974 0 : if self.get_compaction_l0_first() {
2975 0 : let compaction_threshold = self.get_compaction_threshold();
2976 0 : let compact_l0 = compact
2977 0 : .iter()
2978 0 : .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
2979 0 : .filter(|&(_, l0)| l0 >= compaction_threshold)
2980 0 : .sorted_by_key(|&(_, l0)| l0)
2981 0 : .rev()
2982 0 : .map(|(tli, _)| tli.clone())
2983 0 : .collect_vec();
2984 0 :
2985 0 : let mut has_pending_l0 = false;
2986 0 : for timeline in compact_l0 {
2987 0 : let outcome = timeline
2988 0 : .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
2989 0 : .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
2990 0 : .await
2991 0 : .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
2992 0 : match outcome {
2993 0 : CompactionOutcome::Done => {}
2994 0 : CompactionOutcome::Skipped => {}
2995 0 : CompactionOutcome::Pending => has_pending_l0 = true,
2996 0 : CompactionOutcome::YieldForL0 => has_pending_l0 = true,
2997 : }
2998 : }
2999 0 : if has_pending_l0 {
3000 0 : return Ok(CompactionOutcome::YieldForL0); // do another pass
3001 0 : }
3002 0 : }
3003 :
3004 : // Pass 2: image compaction and timeline offloading. If any timelines have accumulated
3005 : // more L0 layers, they may also be compacted here.
3006 : //
3007 : // NB: image compaction may yield if there is pending L0 compaction.
3008 : //
3009 : // TODO: it will only yield if there is pending L0 compaction on the same timeline. If a
3010 : // different timeline needs compaction, it won't. It should check `l0_compaction_trigger`.
3011 : // We leave this for a later PR.
3012 : //
3013 : // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
3014 : // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
3015 0 : let mut has_pending = false;
3016 0 : for timeline in compact {
3017 0 : if !timeline.is_active() {
3018 0 : continue;
3019 0 : }
3020 :
3021 0 : let mut outcome = timeline
3022 0 : .compact(cancel, EnumSet::default(), ctx)
3023 0 : .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
3024 0 : .await
3025 0 : .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
3026 :
3027 : // If we're done compacting, check the scheduled GC compaction queue for more work.
3028 0 : if outcome == CompactionOutcome::Done {
3029 0 : let queue = self
3030 0 : .scheduled_compaction_tasks
3031 0 : .lock()
3032 0 : .unwrap()
3033 0 : .get(&timeline.timeline_id)
3034 0 : .cloned();
3035 0 : if let Some(queue) = queue {
3036 0 : outcome = queue
3037 0 : .iteration(cancel, ctx, &self.gc_block, &timeline)
3038 0 : .await?;
3039 0 : }
3040 0 : }
3041 :
3042 : // If we're done compacting, offload the timeline if requested.
3043 0 : if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
3044 0 : pausable_failpoint!("before-timeline-auto-offload");
3045 0 : offload_timeline(self, &timeline)
3046 0 : .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
3047 0 : .await
3048 0 : .or_else(|err| match err {
3049 : // Ignore this, we likely raced with unarchival.
3050 0 : OffloadError::NotArchived => Ok(()),
3051 0 : err => Err(err),
3052 0 : })?;
3053 0 : }
3054 :
3055 0 : match outcome {
3056 0 : CompactionOutcome::Done => {}
3057 0 : CompactionOutcome::Skipped => {}
3058 0 : CompactionOutcome::Pending => has_pending = true,
3059 : // This mostly makes sense when the L0-only pass above is enabled, since there's
3060 : // otherwise no guarantee that we'll start with the timeline that has high L0.
3061 0 : CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
3062 : }
3063 : }
3064 :
3065 : // Success! Untrip the breaker if necessary.
3066 0 : self.compaction_circuit_breaker
3067 0 : .lock()
3068 0 : .unwrap()
3069 0 : .success(&CIRCUIT_BREAKERS_UNBROKEN);
3070 0 :
3071 0 : match has_pending {
3072 0 : true => Ok(CompactionOutcome::Pending),
3073 0 : false => Ok(CompactionOutcome::Done),
3074 : }
3075 0 : }
3076 :
3077 : /// Trips the compaction circuit breaker if appropriate.
3078 0 : pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
3079 0 : match err {
3080 0 : CompactionError::ShuttingDown => (),
3081 : // Offload failures don't trip the circuit breaker, since they're cheap to retry and
3082 : // shouldn't block compaction.
3083 0 : CompactionError::Offload(_) => {}
3084 0 : CompactionError::Other(err) => {
3085 0 : self.compaction_circuit_breaker
3086 0 : .lock()
3087 0 : .unwrap()
3088 0 : .fail(&CIRCUIT_BREAKERS_BROKEN, err);
3089 0 : }
3090 : }
3091 0 : }
3092 :
3093 : /// Cancel scheduled compaction tasks
3094 0 : pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
3095 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3096 0 : if let Some(q) = guard.get_mut(&timeline_id) {
3097 0 : q.cancel_scheduled();
3098 0 : }
3099 0 : }
3100 :
3101 0 : pub(crate) fn get_scheduled_compaction_tasks(
3102 0 : &self,
3103 0 : timeline_id: TimelineId,
3104 0 : ) -> Vec<CompactInfoResponse> {
3105 0 : let res = {
3106 0 : let guard = self.scheduled_compaction_tasks.lock().unwrap();
3107 0 : guard.get(&timeline_id).map(|q| q.remaining_jobs())
3108 : };
3109 0 : let Some((running, remaining)) = res else {
3110 0 : return Vec::new();
3111 : };
3112 0 : let mut result = Vec::new();
3113 0 : if let Some((id, running)) = running {
3114 0 : result.extend(running.into_compact_info_resp(id, true));
3115 0 : }
3116 0 : for (id, job) in remaining {
3117 0 : result.extend(job.into_compact_info_resp(id, false));
3118 0 : }
3119 0 : result
3120 0 : }
3121 :
3122 : /// Schedule a compaction task for a timeline.
3123 0 : pub(crate) async fn schedule_compaction(
3124 0 : &self,
3125 0 : timeline_id: TimelineId,
3126 0 : options: CompactOptions,
3127 0 : ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
3128 0 : let (tx, rx) = tokio::sync::oneshot::channel();
3129 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3130 0 : let q = guard
3131 0 : .entry(timeline_id)
3132 0 : .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
3133 0 : q.schedule_manual_compaction(options, Some(tx));
3134 0 : Ok(rx)
3135 0 : }
3136 :
3137 : /// Performs periodic housekeeping, via the tenant housekeeping background task.
3138 0 : async fn housekeeping(&self) {
3139 0 : // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
3140 0 : // during ingest, but we don't want idle timelines to hold open layers for too long.
3141 0 : let timelines = self
3142 0 : .timelines
3143 0 : .lock()
3144 0 : .unwrap()
3145 0 : .values()
3146 0 : .filter(|tli| tli.is_active())
3147 0 : .cloned()
3148 0 : .collect_vec();
3149 :
3150 0 : for timeline in timelines {
3151 0 : timeline.maybe_freeze_ephemeral_layer().await;
3152 : }
3153 :
3154 : // Shut down walredo if idle.
3155 : const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
3156 0 : if let Some(ref walredo_mgr) = self.walredo_mgr {
3157 0 : walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
3158 0 : }
3159 0 : }
3160 :
3161 0 : pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
3162 0 : let timelines = self.timelines.lock().unwrap();
3163 0 : !timelines
3164 0 : .iter()
3165 0 : .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
3166 0 : }
3167 :
3168 3464 : pub fn current_state(&self) -> TenantState {
3169 3464 : self.state.borrow().clone()
3170 3464 : }
3171 :
3172 1940 : pub fn is_active(&self) -> bool {
3173 1940 : self.current_state() == TenantState::Active
3174 1940 : }
3175 :
3176 0 : pub fn generation(&self) -> Generation {
3177 0 : self.generation
3178 0 : }
3179 :
3180 0 : pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
3181 0 : self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
3182 0 : }
3183 :
3184 : /// Changes tenant status to active, unless shutdown was already requested.
3185 : ///
3186 : /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
3187 : /// to delay background jobs. Background jobs can be started right away when None is given.
3188 0 : fn activate(
3189 0 : self: &Arc<Self>,
3190 0 : broker_client: BrokerClientChannel,
3191 0 : background_jobs_can_start: Option<&completion::Barrier>,
3192 0 : ctx: &RequestContext,
3193 0 : ) {
3194 0 : span::debug_assert_current_span_has_tenant_id();
3195 0 :
3196 0 : let mut activating = false;
3197 0 : self.state.send_modify(|current_state| {
3198 : use pageserver_api::models::ActivatingFrom;
3199 0 : match &*current_state {
3200 : TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
3201 0 : panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
3202 : }
3203 0 : TenantState::Attaching => {
3204 0 : *current_state = TenantState::Activating(ActivatingFrom::Attaching);
3205 0 : }
3206 0 : }
3207 0 : debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
3208 0 : activating = true;
3209 0 : // Continue outside the closure. We need to grab timelines.lock()
3210 0 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
3211 0 : });
3212 0 :
3213 0 : if activating {
3214 0 : let timelines_accessor = self.timelines.lock().unwrap();
3215 0 : let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
3216 0 : let timelines_to_activate = timelines_accessor
3217 0 : .values()
3218 0 : .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
3219 0 :
3220 0 : // Before activation, populate each Timeline's GcInfo with information about its children
3221 0 : self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
3222 0 :
3223 0 : // Spawn gc and compaction loops. The loops will shut themselves
3224 0 : // down when they notice that the tenant is inactive.
3225 0 : tasks::start_background_loops(self, background_jobs_can_start);
3226 0 :
3227 0 : let mut activated_timelines = 0;
3228 :
3229 0 : for timeline in timelines_to_activate {
3230 0 : timeline.activate(
3231 0 : self.clone(),
3232 0 : broker_client.clone(),
3233 0 : background_jobs_can_start,
3234 0 : ctx,
3235 0 : );
3236 0 : activated_timelines += 1;
3237 0 : }
3238 :
3239 0 : self.state.send_modify(move |current_state| {
3240 0 : assert!(
3241 0 : matches!(current_state, TenantState::Activating(_)),
3242 0 : "set_stopping and set_broken wait for us to leave Activating state",
3243 : );
3244 0 : *current_state = TenantState::Active;
3245 0 :
3246 0 : let elapsed = self.constructed_at.elapsed();
3247 0 : let total_timelines = timelines_accessor.len();
3248 0 :
3249 0 : // log a lot of stuff, because some tenants sometimes suffer from user-visible
3250 0 : // times to activate. see https://github.com/neondatabase/neon/issues/4025
3251 0 : info!(
3252 0 : since_creation_millis = elapsed.as_millis(),
3253 0 : tenant_id = %self.tenant_shard_id.tenant_id,
3254 0 : shard_id = %self.tenant_shard_id.shard_slug(),
3255 0 : activated_timelines,
3256 0 : total_timelines,
3257 0 : post_state = <&'static str>::from(&*current_state),
3258 0 : "activation attempt finished"
3259 : );
3260 :
3261 0 : TENANT.activation.observe(elapsed.as_secs_f64());
3262 0 : });
3263 0 : }
3264 0 : }
3265 :
3266 : /// Shutdown the tenant and join all of the spawned tasks.
3267 : ///
3268 : /// The method caters for all use-cases:
3269 : /// - pageserver shutdown (freeze_and_flush == true)
3270 : /// - detach + ignore (freeze_and_flush == false)
3271 : ///
3272 : /// This will attempt to shutdown even if tenant is broken.
3273 : ///
3274 : /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
3275 : /// If the tenant is already shutting down, we return a clone of the first shutdown call's
3276 : /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
3277 : /// the ongoing shutdown.
3278 12 : async fn shutdown(
3279 12 : &self,
3280 12 : shutdown_progress: completion::Barrier,
3281 12 : shutdown_mode: timeline::ShutdownMode,
3282 12 : ) -> Result<(), completion::Barrier> {
3283 12 : span::debug_assert_current_span_has_tenant_id();
3284 :
3285 : // Set tenant (and its timlines) to Stoppping state.
3286 : //
3287 : // Since we can only transition into Stopping state after activation is complete,
3288 : // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
3289 : //
3290 : // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
3291 : // 1. Lock out any new requests to the tenants.
3292 : // 2. Signal cancellation to WAL receivers (we wait on it below).
3293 : // 3. Signal cancellation for other tenant background loops.
3294 : // 4. ???
3295 : //
3296 : // The waiting for the cancellation is not done uniformly.
3297 : // We certainly wait for WAL receivers to shut down.
3298 : // That is necessary so that no new data comes in before the freeze_and_flush.
3299 : // But the tenant background loops are joined-on in our caller.
3300 : // It's mesed up.
3301 : // we just ignore the failure to stop
3302 :
3303 : // If we're still attaching, fire the cancellation token early to drop out: this
3304 : // will prevent us flushing, but ensures timely shutdown if some I/O during attach
3305 : // is very slow.
3306 12 : let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
3307 0 : self.cancel.cancel();
3308 0 :
3309 0 : // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
3310 0 : // are children of ours, so their flush loops will have shut down already
3311 0 : timeline::ShutdownMode::Hard
3312 : } else {
3313 12 : shutdown_mode
3314 : };
3315 :
3316 12 : match self.set_stopping(shutdown_progress, false, false).await {
3317 12 : Ok(()) => {}
3318 0 : Err(SetStoppingError::Broken) => {
3319 0 : // assume that this is acceptable
3320 0 : }
3321 0 : Err(SetStoppingError::AlreadyStopping(other)) => {
3322 0 : // give caller the option to wait for this this shutdown
3323 0 : info!("Tenant::shutdown: AlreadyStopping");
3324 0 : return Err(other);
3325 : }
3326 : };
3327 :
3328 12 : let mut js = tokio::task::JoinSet::new();
3329 12 : {
3330 12 : let timelines = self.timelines.lock().unwrap();
3331 12 : timelines.values().for_each(|timeline| {
3332 12 : let timeline = Arc::clone(timeline);
3333 12 : let timeline_id = timeline.timeline_id;
3334 12 : let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
3335 12 : js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
3336 12 : });
3337 12 : }
3338 12 : {
3339 12 : let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
3340 12 : timelines_offloaded.values().for_each(|timeline| {
3341 0 : timeline.defuse_for_tenant_drop();
3342 12 : });
3343 12 : }
3344 12 : // test_long_timeline_create_then_tenant_delete is leaning on this message
3345 12 : tracing::info!("Waiting for timelines...");
3346 24 : while let Some(res) = js.join_next().await {
3347 0 : match res {
3348 12 : Ok(()) => {}
3349 0 : Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
3350 0 : Err(je) if je.is_panic() => { /* logged already */ }
3351 0 : Err(je) => warn!("unexpected JoinError: {je:?}"),
3352 : }
3353 : }
3354 :
3355 12 : if let ShutdownMode::Reload = shutdown_mode {
3356 0 : tracing::info!("Flushing deletion queue");
3357 0 : if let Err(e) = self.deletion_queue_client.flush().await {
3358 0 : match e {
3359 0 : DeletionQueueError::ShuttingDown => {
3360 0 : // This is the only error we expect for now. In the future, if more error
3361 0 : // variants are added, we should handle them here.
3362 0 : }
3363 : }
3364 0 : }
3365 12 : }
3366 :
3367 : // We cancel the Tenant's cancellation token _after_ the timelines have all shut down. This permits
3368 : // them to continue to do work during their shutdown methods, e.g. flushing data.
3369 12 : tracing::debug!("Cancelling CancellationToken");
3370 12 : self.cancel.cancel();
3371 12 :
3372 12 : // shutdown all tenant and timeline tasks: gc, compaction, page service
3373 12 : // No new tasks will be started for this tenant because it's in `Stopping` state.
3374 12 : //
3375 12 : // this will additionally shutdown and await all timeline tasks.
3376 12 : tracing::debug!("Waiting for tasks...");
3377 12 : task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
3378 :
3379 12 : if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
3380 12 : walredo_mgr.shutdown().await;
3381 0 : }
3382 :
3383 : // Wait for any in-flight operations to complete
3384 12 : self.gate.close().await;
3385 :
3386 12 : remove_tenant_metrics(&self.tenant_shard_id);
3387 12 :
3388 12 : Ok(())
3389 12 : }
3390 :
3391 : /// Change tenant status to Stopping, to mark that it is being shut down.
3392 : ///
3393 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
3394 : ///
3395 : /// This function is not cancel-safe!
3396 : ///
3397 : /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
3398 : /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
3399 12 : async fn set_stopping(
3400 12 : &self,
3401 12 : progress: completion::Barrier,
3402 12 : _allow_transition_from_loading: bool,
3403 12 : allow_transition_from_attaching: bool,
3404 12 : ) -> Result<(), SetStoppingError> {
3405 12 : let mut rx = self.state.subscribe();
3406 12 :
3407 12 : // cannot stop before we're done activating, so wait out until we're done activating
3408 12 : rx.wait_for(|state| match state {
3409 0 : TenantState::Attaching if allow_transition_from_attaching => true,
3410 : TenantState::Activating(_) | TenantState::Attaching => {
3411 0 : info!(
3412 0 : "waiting for {} to turn Active|Broken|Stopping",
3413 0 : <&'static str>::from(state)
3414 : );
3415 0 : false
3416 : }
3417 12 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
3418 12 : })
3419 12 : .await
3420 12 : .expect("cannot drop self.state while on a &self method");
3421 12 :
3422 12 : // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
3423 12 : let mut err = None;
3424 12 : let stopping = self.state.send_if_modified(|current_state| match current_state {
3425 : TenantState::Activating(_) => {
3426 0 : unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
3427 : }
3428 : TenantState::Attaching => {
3429 0 : if !allow_transition_from_attaching {
3430 0 : unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
3431 0 : };
3432 0 : *current_state = TenantState::Stopping { progress };
3433 0 : true
3434 : }
3435 : TenantState::Active => {
3436 : // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
3437 : // are created after the transition to Stopping. That's harmless, as the Timelines
3438 : // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
3439 12 : *current_state = TenantState::Stopping { progress };
3440 12 : // Continue stopping outside the closure. We need to grab timelines.lock()
3441 12 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
3442 12 : true
3443 : }
3444 0 : TenantState::Broken { reason, .. } => {
3445 0 : info!(
3446 0 : "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
3447 : );
3448 0 : err = Some(SetStoppingError::Broken);
3449 0 : false
3450 : }
3451 0 : TenantState::Stopping { progress } => {
3452 0 : info!("Tenant is already in Stopping state");
3453 0 : err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
3454 0 : false
3455 : }
3456 12 : });
3457 12 : match (stopping, err) {
3458 12 : (true, None) => {} // continue
3459 0 : (false, Some(err)) => return Err(err),
3460 0 : (true, Some(_)) => unreachable!(
3461 0 : "send_if_modified closure must error out if not transitioning to Stopping"
3462 0 : ),
3463 0 : (false, None) => unreachable!(
3464 0 : "send_if_modified closure must return true if transitioning to Stopping"
3465 0 : ),
3466 : }
3467 :
3468 12 : let timelines_accessor = self.timelines.lock().unwrap();
3469 12 : let not_broken_timelines = timelines_accessor
3470 12 : .values()
3471 12 : .filter(|timeline| !timeline.is_broken());
3472 24 : for timeline in not_broken_timelines {
3473 12 : timeline.set_state(TimelineState::Stopping);
3474 12 : }
3475 12 : Ok(())
3476 12 : }
3477 :
3478 : /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
3479 : /// `remove_tenant_from_memory`
3480 : ///
3481 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
3482 : ///
3483 : /// In tests, we also use this to set tenants to Broken state on purpose.
3484 0 : pub(crate) async fn set_broken(&self, reason: String) {
3485 0 : let mut rx = self.state.subscribe();
3486 0 :
3487 0 : // The load & attach routines own the tenant state until it has reached `Active`.
3488 0 : // So, wait until it's done.
3489 0 : rx.wait_for(|state| match state {
3490 : TenantState::Activating(_) | TenantState::Attaching => {
3491 0 : info!(
3492 0 : "waiting for {} to turn Active|Broken|Stopping",
3493 0 : <&'static str>::from(state)
3494 : );
3495 0 : false
3496 : }
3497 0 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
3498 0 : })
3499 0 : .await
3500 0 : .expect("cannot drop self.state while on a &self method");
3501 0 :
3502 0 : // we now know we're done activating, let's see whether this task is the winner to transition into Broken
3503 0 : self.set_broken_no_wait(reason)
3504 0 : }
3505 :
3506 0 : pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
3507 0 : let reason = reason.to_string();
3508 0 : self.state.send_modify(|current_state| {
3509 0 : match *current_state {
3510 : TenantState::Activating(_) | TenantState::Attaching => {
3511 0 : unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
3512 : }
3513 : TenantState::Active => {
3514 0 : if cfg!(feature = "testing") {
3515 0 : warn!("Changing Active tenant to Broken state, reason: {}", reason);
3516 0 : *current_state = TenantState::broken_from_reason(reason);
3517 : } else {
3518 0 : unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
3519 : }
3520 : }
3521 : TenantState::Broken { .. } => {
3522 0 : warn!("Tenant is already in Broken state");
3523 : }
3524 : // This is the only "expected" path, any other path is a bug.
3525 : TenantState::Stopping { .. } => {
3526 0 : warn!(
3527 0 : "Marking Stopping tenant as Broken state, reason: {}",
3528 : reason
3529 : );
3530 0 : *current_state = TenantState::broken_from_reason(reason);
3531 : }
3532 : }
3533 0 : });
3534 0 : }
3535 :
3536 0 : pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
3537 0 : self.state.subscribe()
3538 0 : }
3539 :
3540 : /// The activate_now semaphore is initialized with zero units. As soon as
3541 : /// we add a unit, waiters will be able to acquire a unit and proceed.
3542 0 : pub(crate) fn activate_now(&self) {
3543 0 : self.activate_now_sem.add_permits(1);
3544 0 : }
3545 :
3546 0 : pub(crate) async fn wait_to_become_active(
3547 0 : &self,
3548 0 : timeout: Duration,
3549 0 : ) -> Result<(), GetActiveTenantError> {
3550 0 : let mut receiver = self.state.subscribe();
3551 : loop {
3552 0 : let current_state = receiver.borrow_and_update().clone();
3553 0 : match current_state {
3554 : TenantState::Attaching | TenantState::Activating(_) => {
3555 : // in these states, there's a chance that we can reach ::Active
3556 0 : self.activate_now();
3557 0 : match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
3558 0 : Ok(r) => {
3559 0 : r.map_err(
3560 0 : |_e: tokio::sync::watch::error::RecvError|
3561 : // Tenant existed but was dropped: report it as non-existent
3562 0 : GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
3563 0 : )?
3564 : }
3565 : Err(TimeoutCancellableError::Cancelled) => {
3566 0 : return Err(GetActiveTenantError::Cancelled);
3567 : }
3568 : Err(TimeoutCancellableError::Timeout) => {
3569 0 : return Err(GetActiveTenantError::WaitForActiveTimeout {
3570 0 : latest_state: Some(self.current_state()),
3571 0 : wait_time: timeout,
3572 0 : });
3573 : }
3574 : }
3575 : }
3576 : TenantState::Active { .. } => {
3577 0 : return Ok(());
3578 : }
3579 0 : TenantState::Broken { reason, .. } => {
3580 0 : // This is fatal, and reported distinctly from the general case of "will never be active" because
3581 0 : // it's logically a 500 to external API users (broken is always a bug).
3582 0 : return Err(GetActiveTenantError::Broken(reason));
3583 : }
3584 : TenantState::Stopping { .. } => {
3585 : // There's no chance the tenant can transition back into ::Active
3586 0 : return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
3587 : }
3588 : }
3589 : }
3590 0 : }
3591 :
3592 0 : pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
3593 0 : self.tenant_conf.load().location.attach_mode
3594 0 : }
3595 :
3596 : /// For API access: generate a LocationConfig equivalent to the one that would be used to
3597 : /// create a Tenant in the same state. Do not use this in hot paths: it's for relatively
3598 : /// rare external API calls, like a reconciliation at startup.
3599 0 : pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
3600 0 : let conf = self.tenant_conf.load();
3601 :
3602 0 : let location_config_mode = match conf.location.attach_mode {
3603 0 : AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
3604 0 : AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
3605 0 : AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
3606 : };
3607 :
3608 : // We have a pageserver TenantConf, we need the API-facing TenantConfig.
3609 0 : let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
3610 0 :
3611 0 : models::LocationConfig {
3612 0 : mode: location_config_mode,
3613 0 : generation: self.generation.into(),
3614 0 : secondary_conf: None,
3615 0 : shard_number: self.shard_identity.number.0,
3616 0 : shard_count: self.shard_identity.count.literal(),
3617 0 : shard_stripe_size: self.shard_identity.stripe_size.0,
3618 0 : tenant_conf: tenant_config,
3619 0 : }
3620 0 : }
3621 :
3622 0 : pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
3623 0 : &self.tenant_shard_id
3624 0 : }
3625 :
3626 0 : pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
3627 0 : self.shard_identity.stripe_size
3628 0 : }
3629 :
3630 0 : pub(crate) fn get_generation(&self) -> Generation {
3631 0 : self.generation
3632 0 : }
3633 :
3634 : /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
3635 : /// and can leave the tenant in a bad state if it fails. The caller is responsible for
3636 : /// resetting this tenant to a valid state if we fail.
3637 0 : pub(crate) async fn split_prepare(
3638 0 : &self,
3639 0 : child_shards: &Vec<TenantShardId>,
3640 0 : ) -> anyhow::Result<()> {
3641 0 : let (timelines, offloaded) = {
3642 0 : let timelines = self.timelines.lock().unwrap();
3643 0 : let offloaded = self.timelines_offloaded.lock().unwrap();
3644 0 : (timelines.clone(), offloaded.clone())
3645 0 : };
3646 0 : let timelines_iter = timelines
3647 0 : .values()
3648 0 : .map(TimelineOrOffloadedArcRef::<'_>::from)
3649 0 : .chain(
3650 0 : offloaded
3651 0 : .values()
3652 0 : .map(TimelineOrOffloadedArcRef::<'_>::from),
3653 0 : );
3654 0 : for timeline in timelines_iter {
3655 : // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
3656 : // to ensure that they do not start a split if currently in the process of doing these.
3657 :
3658 0 : let timeline_id = timeline.timeline_id();
3659 :
3660 0 : if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
3661 : // Upload an index from the parent: this is partly to provide freshness for the
3662 : // child tenants that will copy it, and partly for general ease-of-debugging: there will
3663 : // always be a parent shard index in the same generation as we wrote the child shard index.
3664 0 : tracing::info!(%timeline_id, "Uploading index");
3665 0 : timeline
3666 0 : .remote_client
3667 0 : .schedule_index_upload_for_file_changes()?;
3668 0 : timeline.remote_client.wait_completion().await?;
3669 0 : }
3670 :
3671 0 : let remote_client = match timeline {
3672 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
3673 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
3674 0 : let remote_client = self
3675 0 : .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
3676 0 : Arc::new(remote_client)
3677 : }
3678 : };
3679 :
3680 : // Shut down the timeline's remote client: this means that the indices we write
3681 : // for child shards will not be invalidated by the parent shard deleting layers.
3682 0 : tracing::info!(%timeline_id, "Shutting down remote storage client");
3683 0 : remote_client.shutdown().await;
3684 :
3685 : // Download methods can still be used after shutdown, as they don't flow through the remote client's
3686 : // queue. In principal the RemoteTimelineClient could provide this without downloading it, but this
3687 : // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
3688 : // we use here really is the remotely persistent one).
3689 0 : tracing::info!(%timeline_id, "Downloading index_part from parent");
3690 0 : let result = remote_client
3691 0 : .download_index_file(&self.cancel)
3692 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))
3693 0 : .await?;
3694 0 : let index_part = match result {
3695 : MaybeDeletedIndexPart::Deleted(_) => {
3696 0 : anyhow::bail!("Timeline deletion happened concurrently with split")
3697 : }
3698 0 : MaybeDeletedIndexPart::IndexPart(p) => p,
3699 : };
3700 :
3701 0 : for child_shard in child_shards {
3702 0 : tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
3703 0 : upload_index_part(
3704 0 : &self.remote_storage,
3705 0 : child_shard,
3706 0 : &timeline_id,
3707 0 : self.generation,
3708 0 : &index_part,
3709 0 : &self.cancel,
3710 0 : )
3711 0 : .await?;
3712 : }
3713 : }
3714 :
3715 0 : let tenant_manifest = self.build_tenant_manifest();
3716 0 : for child_shard in child_shards {
3717 0 : tracing::info!(
3718 0 : "Uploading tenant manifest for child {}",
3719 0 : child_shard.to_index()
3720 : );
3721 0 : upload_tenant_manifest(
3722 0 : &self.remote_storage,
3723 0 : child_shard,
3724 0 : self.generation,
3725 0 : &tenant_manifest,
3726 0 : &self.cancel,
3727 0 : )
3728 0 : .await?;
3729 : }
3730 :
3731 0 : Ok(())
3732 0 : }
3733 :
3734 0 : pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
3735 0 : let mut result = TopTenantShardItem {
3736 0 : id: self.tenant_shard_id,
3737 0 : resident_size: 0,
3738 0 : physical_size: 0,
3739 0 : max_logical_size: 0,
3740 0 : };
3741 :
3742 0 : for timeline in self.timelines.lock().unwrap().values() {
3743 0 : result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
3744 0 :
3745 0 : result.physical_size += timeline
3746 0 : .remote_client
3747 0 : .metrics
3748 0 : .remote_physical_size_gauge
3749 0 : .get();
3750 0 : result.max_logical_size = std::cmp::max(
3751 0 : result.max_logical_size,
3752 0 : timeline.metrics.current_logical_size_gauge.get(),
3753 0 : );
3754 0 : }
3755 :
3756 0 : result
3757 0 : }
3758 : }
3759 :
3760 : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
3761 : /// perform a topological sort, so that the parent of each timeline comes
3762 : /// before the children.
3763 : /// E extracts the ancestor from T
3764 : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
3765 440 : fn tree_sort_timelines<T, E>(
3766 440 : timelines: HashMap<TimelineId, T>,
3767 440 : extractor: E,
3768 440 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
3769 440 : where
3770 440 : E: Fn(&T) -> Option<TimelineId>,
3771 440 : {
3772 440 : let mut result = Vec::with_capacity(timelines.len());
3773 440 :
3774 440 : let mut now = Vec::with_capacity(timelines.len());
3775 440 : // (ancestor, children)
3776 440 : let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
3777 440 : HashMap::with_capacity(timelines.len());
3778 :
3779 452 : for (timeline_id, value) in timelines {
3780 12 : if let Some(ancestor_id) = extractor(&value) {
3781 4 : let children = later.entry(ancestor_id).or_default();
3782 4 : children.push((timeline_id, value));
3783 8 : } else {
3784 8 : now.push((timeline_id, value));
3785 8 : }
3786 : }
3787 :
3788 452 : while let Some((timeline_id, metadata)) = now.pop() {
3789 12 : result.push((timeline_id, metadata));
3790 : // All children of this can be loaded now
3791 12 : if let Some(mut children) = later.remove(&timeline_id) {
3792 4 : now.append(&mut children);
3793 8 : }
3794 : }
3795 :
3796 : // All timelines should be visited now. Unless there were timelines with missing ancestors.
3797 440 : if !later.is_empty() {
3798 0 : for (missing_id, orphan_ids) in later {
3799 0 : for (orphan_id, _) in orphan_ids {
3800 0 : error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
3801 : }
3802 : }
3803 0 : bail!("could not load tenant because some timelines are missing ancestors");
3804 440 : }
3805 440 :
3806 440 : Ok(result)
3807 440 : }
3808 :
3809 : enum ActivateTimelineArgs {
3810 : Yes {
3811 : broker_client: storage_broker::BrokerClientChannel,
3812 : },
3813 : No,
3814 : }
3815 :
3816 : impl Tenant {
3817 0 : pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
3818 0 : self.tenant_conf.load().tenant_conf.clone()
3819 0 : }
3820 :
3821 0 : pub fn effective_config(&self) -> TenantConf {
3822 0 : self.tenant_specific_overrides()
3823 0 : .merge(self.conf.default_tenant_conf.clone())
3824 0 : }
3825 :
3826 0 : pub fn get_checkpoint_distance(&self) -> u64 {
3827 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3828 0 : tenant_conf
3829 0 : .checkpoint_distance
3830 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
3831 0 : }
3832 :
3833 0 : pub fn get_checkpoint_timeout(&self) -> Duration {
3834 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3835 0 : tenant_conf
3836 0 : .checkpoint_timeout
3837 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
3838 0 : }
3839 :
3840 0 : pub fn get_compaction_target_size(&self) -> u64 {
3841 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3842 0 : tenant_conf
3843 0 : .compaction_target_size
3844 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
3845 0 : }
3846 :
3847 0 : pub fn get_compaction_period(&self) -> Duration {
3848 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3849 0 : tenant_conf
3850 0 : .compaction_period
3851 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_period)
3852 0 : }
3853 :
3854 0 : pub fn get_compaction_threshold(&self) -> usize {
3855 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3856 0 : tenant_conf
3857 0 : .compaction_threshold
3858 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
3859 0 : }
3860 :
3861 0 : pub fn get_compaction_upper_limit(&self) -> usize {
3862 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3863 0 : tenant_conf
3864 0 : .compaction_upper_limit
3865 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
3866 0 : }
3867 :
3868 0 : pub fn get_compaction_l0_first(&self) -> bool {
3869 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3870 0 : tenant_conf
3871 0 : .compaction_l0_first
3872 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
3873 0 : }
3874 :
3875 0 : pub fn get_gc_horizon(&self) -> u64 {
3876 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3877 0 : tenant_conf
3878 0 : .gc_horizon
3879 0 : .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
3880 0 : }
3881 :
3882 0 : pub fn get_gc_period(&self) -> Duration {
3883 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3884 0 : tenant_conf
3885 0 : .gc_period
3886 0 : .unwrap_or(self.conf.default_tenant_conf.gc_period)
3887 0 : }
3888 :
3889 0 : pub fn get_image_creation_threshold(&self) -> usize {
3890 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3891 0 : tenant_conf
3892 0 : .image_creation_threshold
3893 0 : .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
3894 0 : }
3895 :
3896 0 : pub fn get_pitr_interval(&self) -> Duration {
3897 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3898 0 : tenant_conf
3899 0 : .pitr_interval
3900 0 : .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
3901 0 : }
3902 :
3903 0 : pub fn get_min_resident_size_override(&self) -> Option<u64> {
3904 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3905 0 : tenant_conf
3906 0 : .min_resident_size_override
3907 0 : .or(self.conf.default_tenant_conf.min_resident_size_override)
3908 0 : }
3909 :
3910 0 : pub fn get_heatmap_period(&self) -> Option<Duration> {
3911 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3912 0 : let heatmap_period = tenant_conf
3913 0 : .heatmap_period
3914 0 : .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
3915 0 : if heatmap_period.is_zero() {
3916 0 : None
3917 : } else {
3918 0 : Some(heatmap_period)
3919 : }
3920 0 : }
3921 :
3922 8 : pub fn get_lsn_lease_length(&self) -> Duration {
3923 8 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3924 8 : tenant_conf
3925 8 : .lsn_lease_length
3926 8 : .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
3927 8 : }
3928 :
3929 0 : pub fn get_timeline_offloading_enabled(&self) -> bool {
3930 0 : if self.conf.timeline_offloading {
3931 0 : return true;
3932 0 : }
3933 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3934 0 : tenant_conf
3935 0 : .timeline_offloading
3936 0 : .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
3937 0 : }
3938 :
3939 : /// Generate an up-to-date TenantManifest based on the state of this Tenant.
3940 4 : fn build_tenant_manifest(&self) -> TenantManifest {
3941 4 : let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
3942 4 :
3943 4 : let mut timeline_manifests = timelines_offloaded
3944 4 : .iter()
3945 4 : .map(|(_timeline_id, offloaded)| offloaded.manifest())
3946 4 : .collect::<Vec<_>>();
3947 4 : // Sort the manifests so that our output is deterministic
3948 4 : timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
3949 4 :
3950 4 : TenantManifest {
3951 4 : version: LATEST_TENANT_MANIFEST_VERSION,
3952 4 : offloaded_timelines: timeline_manifests,
3953 4 : }
3954 4 : }
3955 :
3956 0 : pub fn update_tenant_config<F: Fn(TenantConfOpt) -> anyhow::Result<TenantConfOpt>>(
3957 0 : &self,
3958 0 : update: F,
3959 0 : ) -> anyhow::Result<TenantConfOpt> {
3960 0 : // Use read-copy-update in order to avoid overwriting the location config
3961 0 : // state if this races with [`Tenant::set_new_location_config`]. Note that
3962 0 : // this race is not possible if both request types come from the storage
3963 0 : // controller (as they should!) because an exclusive op lock is required
3964 0 : // on the storage controller side.
3965 0 :
3966 0 : self.tenant_conf
3967 0 : .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
3968 0 : Ok(Arc::new(AttachedTenantConf {
3969 0 : tenant_conf: update(attached_conf.tenant_conf.clone())?,
3970 0 : location: attached_conf.location,
3971 0 : lsn_lease_deadline: attached_conf.lsn_lease_deadline,
3972 : }))
3973 0 : })?;
3974 :
3975 0 : let updated = self.tenant_conf.load();
3976 0 :
3977 0 : self.tenant_conf_updated(&updated.tenant_conf);
3978 0 : // Don't hold self.timelines.lock() during the notifies.
3979 0 : // There's no risk of deadlock right now, but there could be if we consolidate
3980 0 : // mutexes in struct Timeline in the future.
3981 0 : let timelines = self.list_timelines();
3982 0 : for timeline in timelines {
3983 0 : timeline.tenant_conf_updated(&updated);
3984 0 : }
3985 :
3986 0 : Ok(updated.tenant_conf.clone())
3987 0 : }
3988 :
3989 0 : pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
3990 0 : let new_tenant_conf = new_conf.tenant_conf.clone();
3991 0 :
3992 0 : self.tenant_conf.store(Arc::new(new_conf.clone()));
3993 0 :
3994 0 : self.tenant_conf_updated(&new_tenant_conf);
3995 0 : // Don't hold self.timelines.lock() during the notifies.
3996 0 : // There's no risk of deadlock right now, but there could be if we consolidate
3997 0 : // mutexes in struct Timeline in the future.
3998 0 : let timelines = self.list_timelines();
3999 0 : for timeline in timelines {
4000 0 : timeline.tenant_conf_updated(&new_conf);
4001 0 : }
4002 0 : }
4003 :
4004 440 : fn get_pagestream_throttle_config(
4005 440 : psconf: &'static PageServerConf,
4006 440 : overrides: &TenantConfOpt,
4007 440 : ) -> throttle::Config {
4008 440 : overrides
4009 440 : .timeline_get_throttle
4010 440 : .clone()
4011 440 : .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
4012 440 : }
4013 :
4014 0 : pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
4015 0 : let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
4016 0 : self.pagestream_throttle.reconfigure(conf)
4017 0 : }
4018 :
4019 : /// Helper function to create a new Timeline struct.
4020 : ///
4021 : /// The returned Timeline is in Loading state. The caller is responsible for
4022 : /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
4023 : /// map.
4024 : ///
4025 : /// `validate_ancestor == false` is used when a timeline is created for deletion
4026 : /// and we might not have the ancestor present anymore which is fine for to be
4027 : /// deleted timelines.
4028 : #[allow(clippy::too_many_arguments)]
4029 892 : fn create_timeline_struct(
4030 892 : &self,
4031 892 : new_timeline_id: TimelineId,
4032 892 : new_metadata: &TimelineMetadata,
4033 892 : ancestor: Option<Arc<Timeline>>,
4034 892 : resources: TimelineResources,
4035 892 : cause: CreateTimelineCause,
4036 892 : create_idempotency: CreateTimelineIdempotency,
4037 892 : ) -> anyhow::Result<Arc<Timeline>> {
4038 892 : let state = match cause {
4039 : CreateTimelineCause::Load => {
4040 892 : let ancestor_id = new_metadata.ancestor_timeline();
4041 892 : anyhow::ensure!(
4042 892 : ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
4043 0 : "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
4044 : );
4045 892 : TimelineState::Loading
4046 : }
4047 0 : CreateTimelineCause::Delete => TimelineState::Stopping,
4048 : };
4049 :
4050 892 : let pg_version = new_metadata.pg_version();
4051 892 :
4052 892 : let timeline = Timeline::new(
4053 892 : self.conf,
4054 892 : Arc::clone(&self.tenant_conf),
4055 892 : new_metadata,
4056 892 : ancestor,
4057 892 : new_timeline_id,
4058 892 : self.tenant_shard_id,
4059 892 : self.generation,
4060 892 : self.shard_identity,
4061 892 : self.walredo_mgr.clone(),
4062 892 : resources,
4063 892 : pg_version,
4064 892 : state,
4065 892 : self.attach_wal_lag_cooldown.clone(),
4066 892 : create_idempotency,
4067 892 : self.cancel.child_token(),
4068 892 : );
4069 892 :
4070 892 : Ok(timeline)
4071 892 : }
4072 :
4073 : /// [`Tenant::shutdown`] must be called before dropping the returned [`Tenant`] object
4074 : /// to ensure proper cleanup of background tasks and metrics.
4075 : //
4076 : // Allow too_many_arguments because a constructor's argument list naturally grows with the
4077 : // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
4078 : #[allow(clippy::too_many_arguments)]
4079 440 : fn new(
4080 440 : state: TenantState,
4081 440 : conf: &'static PageServerConf,
4082 440 : attached_conf: AttachedTenantConf,
4083 440 : shard_identity: ShardIdentity,
4084 440 : walredo_mgr: Option<Arc<WalRedoManager>>,
4085 440 : tenant_shard_id: TenantShardId,
4086 440 : remote_storage: GenericRemoteStorage,
4087 440 : deletion_queue_client: DeletionQueueClient,
4088 440 : l0_flush_global_state: L0FlushGlobalState,
4089 440 : ) -> Tenant {
4090 440 : debug_assert!(
4091 440 : !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
4092 : );
4093 :
4094 440 : let (state, mut rx) = watch::channel(state);
4095 440 :
4096 440 : tokio::spawn(async move {
4097 440 : // reflect tenant state in metrics:
4098 440 : // - global per tenant state: TENANT_STATE_METRIC
4099 440 : // - "set" of broken tenants: BROKEN_TENANTS_SET
4100 440 : //
4101 440 : // set of broken tenants should not have zero counts so that it remains accessible for
4102 440 : // alerting.
4103 440 :
4104 440 : let tid = tenant_shard_id.to_string();
4105 440 : let shard_id = tenant_shard_id.shard_slug().to_string();
4106 440 : let set_key = &[tid.as_str(), shard_id.as_str()][..];
4107 :
4108 880 : fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
4109 880 : ([state.into()], matches!(state, TenantState::Broken { .. }))
4110 880 : }
4111 :
4112 440 : let mut tuple = inspect_state(&rx.borrow_and_update());
4113 440 :
4114 440 : let is_broken = tuple.1;
4115 440 : let mut counted_broken = if is_broken {
4116 : // add the id to the set right away, there should not be any updates on the channel
4117 : // after before tenant is removed, if ever
4118 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
4119 0 : true
4120 : } else {
4121 440 : false
4122 : };
4123 :
4124 : loop {
4125 880 : let labels = &tuple.0;
4126 880 : let current = TENANT_STATE_METRIC.with_label_values(labels);
4127 880 : current.inc();
4128 880 :
4129 880 : if rx.changed().await.is_err() {
4130 : // tenant has been dropped
4131 28 : current.dec();
4132 28 : drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
4133 28 : break;
4134 440 : }
4135 440 :
4136 440 : current.dec();
4137 440 : tuple = inspect_state(&rx.borrow_and_update());
4138 440 :
4139 440 : let is_broken = tuple.1;
4140 440 : if is_broken && !counted_broken {
4141 0 : counted_broken = true;
4142 0 : // insert the tenant_id (back) into the set while avoiding needless counter
4143 0 : // access
4144 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
4145 440 : }
4146 : }
4147 440 : });
4148 440 :
4149 440 : Tenant {
4150 440 : tenant_shard_id,
4151 440 : shard_identity,
4152 440 : generation: attached_conf.location.generation,
4153 440 : conf,
4154 440 : // using now here is good enough approximation to catch tenants with really long
4155 440 : // activation times.
4156 440 : constructed_at: Instant::now(),
4157 440 : timelines: Mutex::new(HashMap::new()),
4158 440 : timelines_creating: Mutex::new(HashSet::new()),
4159 440 : timelines_offloaded: Mutex::new(HashMap::new()),
4160 440 : tenant_manifest_upload: Default::default(),
4161 440 : gc_cs: tokio::sync::Mutex::new(()),
4162 440 : walredo_mgr,
4163 440 : remote_storage,
4164 440 : deletion_queue_client,
4165 440 : state,
4166 440 : cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
4167 440 : cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
4168 440 : eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
4169 440 : compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
4170 440 : format!("compaction-{tenant_shard_id}"),
4171 440 : 5,
4172 440 : // Compaction can be a very expensive operation, and might leak disk space. It also ought
4173 440 : // to be infallible, as long as remote storage is available. So if it repeatedly fails,
4174 440 : // use an extremely long backoff.
4175 440 : Some(Duration::from_secs(3600 * 24)),
4176 440 : )),
4177 440 : l0_compaction_trigger: Arc::new(Notify::new()),
4178 440 : scheduled_compaction_tasks: Mutex::new(Default::default()),
4179 440 : activate_now_sem: tokio::sync::Semaphore::new(0),
4180 440 : attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
4181 440 : cancel: CancellationToken::default(),
4182 440 : gate: Gate::default(),
4183 440 : pagestream_throttle: Arc::new(throttle::Throttle::new(
4184 440 : Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
4185 440 : )),
4186 440 : pagestream_throttle_metrics: Arc::new(
4187 440 : crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
4188 440 : ),
4189 440 : tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
4190 440 : ongoing_timeline_detach: std::sync::Mutex::default(),
4191 440 : gc_block: Default::default(),
4192 440 : l0_flush_global_state,
4193 440 : }
4194 440 : }
4195 :
4196 : /// Locate and load config
4197 0 : pub(super) fn load_tenant_config(
4198 0 : conf: &'static PageServerConf,
4199 0 : tenant_shard_id: &TenantShardId,
4200 0 : ) -> Result<LocationConf, LoadConfigError> {
4201 0 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
4202 0 :
4203 0 : info!("loading tenant configuration from {config_path}");
4204 :
4205 : // load and parse file
4206 0 : let config = fs::read_to_string(&config_path).map_err(|e| {
4207 0 : match e.kind() {
4208 : std::io::ErrorKind::NotFound => {
4209 : // The config should almost always exist for a tenant directory:
4210 : // - When attaching a tenant, the config is the first thing we write
4211 : // - When detaching a tenant, we atomically move the directory to a tmp location
4212 : // before deleting contents.
4213 : //
4214 : // The very rare edge case that can result in a missing config is if we crash during attach
4215 : // between creating directory and writing config. Callers should handle that as if the
4216 : // directory didn't exist.
4217 :
4218 0 : LoadConfigError::NotFound(config_path)
4219 : }
4220 : _ => {
4221 : // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
4222 : // that we cannot cleanly recover
4223 0 : crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
4224 : }
4225 : }
4226 0 : })?;
4227 :
4228 0 : Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
4229 0 : }
4230 :
4231 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
4232 : pub(super) async fn persist_tenant_config(
4233 : conf: &'static PageServerConf,
4234 : tenant_shard_id: &TenantShardId,
4235 : location_conf: &LocationConf,
4236 : ) -> std::io::Result<()> {
4237 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
4238 :
4239 : Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
4240 : }
4241 :
4242 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
4243 : pub(super) async fn persist_tenant_config_at(
4244 : tenant_shard_id: &TenantShardId,
4245 : config_path: &Utf8Path,
4246 : location_conf: &LocationConf,
4247 : ) -> std::io::Result<()> {
4248 : debug!("persisting tenantconf to {config_path}");
4249 :
4250 : let mut conf_content = r#"# This file contains a specific per-tenant's config.
4251 : # It is read in case of pageserver restart.
4252 : "#
4253 : .to_string();
4254 :
4255 0 : fail::fail_point!("tenant-config-before-write", |_| {
4256 0 : Err(std::io::Error::new(
4257 0 : std::io::ErrorKind::Other,
4258 0 : "tenant-config-before-write",
4259 0 : ))
4260 0 : });
4261 :
4262 : // Convert the config to a toml file.
4263 : conf_content +=
4264 : &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
4265 :
4266 : let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
4267 :
4268 : let conf_content = conf_content.into_bytes();
4269 : VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
4270 : }
4271 :
4272 : //
4273 : // How garbage collection works:
4274 : //
4275 : // +--bar------------->
4276 : // /
4277 : // +----+-----foo---------------->
4278 : // /
4279 : // ----main--+-------------------------->
4280 : // \
4281 : // +-----baz-------->
4282 : //
4283 : //
4284 : // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
4285 : // `gc_infos` are being refreshed
4286 : // 2. Scan collected timelines, and on each timeline, make note of the
4287 : // all the points where other timelines have been branched off.
4288 : // We will refrain from removing page versions at those LSNs.
4289 : // 3. For each timeline, scan all layer files on the timeline.
4290 : // Remove all files for which a newer file exists and which
4291 : // don't cover any branch point LSNs.
4292 : //
4293 : // TODO:
4294 : // - if a relation has a non-incremental persistent layer on a child branch, then we
4295 : // don't need to keep that in the parent anymore. But currently
4296 : // we do.
4297 8 : async fn gc_iteration_internal(
4298 8 : &self,
4299 8 : target_timeline_id: Option<TimelineId>,
4300 8 : horizon: u64,
4301 8 : pitr: Duration,
4302 8 : cancel: &CancellationToken,
4303 8 : ctx: &RequestContext,
4304 8 : ) -> Result<GcResult, GcError> {
4305 8 : let mut totals: GcResult = Default::default();
4306 8 : let now = Instant::now();
4307 :
4308 8 : let gc_timelines = self
4309 8 : .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
4310 8 : .await?;
4311 :
4312 8 : failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
4313 :
4314 : // If there is nothing to GC, we don't want any messages in the INFO log.
4315 8 : if !gc_timelines.is_empty() {
4316 8 : info!("{} timelines need GC", gc_timelines.len());
4317 : } else {
4318 0 : debug!("{} timelines need GC", gc_timelines.len());
4319 : }
4320 :
4321 : // Perform GC for each timeline.
4322 : //
4323 : // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
4324 : // branch creation task, which requires the GC lock. A GC iteration can run concurrently
4325 : // with branch creation.
4326 : //
4327 : // See comments in [`Tenant::branch_timeline`] for more information about why branch
4328 : // creation task can run concurrently with timeline's GC iteration.
4329 16 : for timeline in gc_timelines {
4330 8 : if cancel.is_cancelled() {
4331 : // We were requested to shut down. Stop and return with the progress we
4332 : // made.
4333 0 : break;
4334 8 : }
4335 8 : let result = match timeline.gc().await {
4336 : Err(GcError::TimelineCancelled) => {
4337 0 : if target_timeline_id.is_some() {
4338 : // If we were targetting this specific timeline, surface cancellation to caller
4339 0 : return Err(GcError::TimelineCancelled);
4340 : } else {
4341 : // A timeline may be shutting down independently of the tenant's lifecycle: we should
4342 : // skip past this and proceed to try GC on other timelines.
4343 0 : continue;
4344 : }
4345 : }
4346 8 : r => r?,
4347 : };
4348 8 : totals += result;
4349 : }
4350 :
4351 8 : totals.elapsed = now.elapsed();
4352 8 : Ok(totals)
4353 8 : }
4354 :
4355 : /// Refreshes the Timeline::gc_info for all timelines, returning the
4356 : /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
4357 : /// [`Tenant::get_gc_horizon`].
4358 : ///
4359 : /// This is usually executed as part of periodic gc, but can now be triggered more often.
4360 0 : pub(crate) async fn refresh_gc_info(
4361 0 : &self,
4362 0 : cancel: &CancellationToken,
4363 0 : ctx: &RequestContext,
4364 0 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
4365 0 : // since this method can now be called at different rates than the configured gc loop, it
4366 0 : // might be that these configuration values get applied faster than what it was previously,
4367 0 : // since these were only read from the gc task.
4368 0 : let horizon = self.get_gc_horizon();
4369 0 : let pitr = self.get_pitr_interval();
4370 0 :
4371 0 : // refresh all timelines
4372 0 : let target_timeline_id = None;
4373 0 :
4374 0 : self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
4375 0 : .await
4376 0 : }
4377 :
4378 : /// Populate all Timelines' `GcInfo` with information about their children. We do not set the
4379 : /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
4380 : ///
4381 : /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
4382 0 : fn initialize_gc_info(
4383 0 : &self,
4384 0 : timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
4385 0 : timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
4386 0 : restrict_to_timeline: Option<TimelineId>,
4387 0 : ) {
4388 0 : if restrict_to_timeline.is_none() {
4389 : // This function must be called before activation: after activation timeline create/delete operations
4390 : // might happen, and this function is not safe to run concurrently with those.
4391 0 : assert!(!self.is_active());
4392 0 : }
4393 :
4394 : // Scan all timelines. For each timeline, remember the timeline ID and
4395 : // the branch point where it was created.
4396 0 : let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
4397 0 : BTreeMap::new();
4398 0 : timelines.iter().for_each(|(timeline_id, timeline_entry)| {
4399 0 : if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
4400 0 : let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
4401 0 : ancestor_children.push((
4402 0 : timeline_entry.get_ancestor_lsn(),
4403 0 : *timeline_id,
4404 0 : MaybeOffloaded::No,
4405 0 : ));
4406 0 : }
4407 0 : });
4408 0 : timelines_offloaded
4409 0 : .iter()
4410 0 : .for_each(|(timeline_id, timeline_entry)| {
4411 0 : let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
4412 0 : return;
4413 : };
4414 0 : let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
4415 0 : return;
4416 : };
4417 0 : let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
4418 0 : ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
4419 0 : });
4420 0 :
4421 0 : // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
4422 0 : let horizon = self.get_gc_horizon();
4423 :
4424 : // Populate each timeline's GcInfo with information about its child branches
4425 0 : let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
4426 0 : itertools::Either::Left(timelines.get(&timeline_id).into_iter())
4427 : } else {
4428 0 : itertools::Either::Right(timelines.values())
4429 : };
4430 0 : for timeline in timelines_to_write {
4431 0 : let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
4432 0 : .remove(&timeline.timeline_id)
4433 0 : .unwrap_or_default();
4434 0 :
4435 0 : branchpoints.sort_by_key(|b| b.0);
4436 0 :
4437 0 : let mut target = timeline.gc_info.write().unwrap();
4438 0 :
4439 0 : target.retain_lsns = branchpoints;
4440 0 :
4441 0 : let space_cutoff = timeline
4442 0 : .get_last_record_lsn()
4443 0 : .checked_sub(horizon)
4444 0 : .unwrap_or(Lsn(0));
4445 0 :
4446 0 : target.cutoffs = GcCutoffs {
4447 0 : space: space_cutoff,
4448 0 : time: Lsn::INVALID,
4449 0 : };
4450 0 : }
4451 0 : }
4452 :
4453 8 : async fn refresh_gc_info_internal(
4454 8 : &self,
4455 8 : target_timeline_id: Option<TimelineId>,
4456 8 : horizon: u64,
4457 8 : pitr: Duration,
4458 8 : cancel: &CancellationToken,
4459 8 : ctx: &RequestContext,
4460 8 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
4461 8 : // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
4462 8 : // currently visible timelines.
4463 8 : let timelines = self
4464 8 : .timelines
4465 8 : .lock()
4466 8 : .unwrap()
4467 8 : .values()
4468 8 : .filter(|tl| match target_timeline_id.as_ref() {
4469 8 : Some(target) => &tl.timeline_id == target,
4470 0 : None => true,
4471 8 : })
4472 8 : .cloned()
4473 8 : .collect::<Vec<_>>();
4474 8 :
4475 8 : if target_timeline_id.is_some() && timelines.is_empty() {
4476 : // We were to act on a particular timeline and it wasn't found
4477 0 : return Err(GcError::TimelineNotFound);
4478 8 : }
4479 8 :
4480 8 : let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
4481 8 : HashMap::with_capacity(timelines.len());
4482 8 :
4483 8 : // Ensures all timelines use the same start time when computing the time cutoff.
4484 8 : let now_ts_for_pitr_calc = SystemTime::now();
4485 8 : for timeline in timelines.iter() {
4486 8 : let cutoff = timeline
4487 8 : .get_last_record_lsn()
4488 8 : .checked_sub(horizon)
4489 8 : .unwrap_or(Lsn(0));
4490 :
4491 8 : let cutoffs = timeline
4492 8 : .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
4493 8 : .await?;
4494 8 : let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
4495 8 : assert!(old.is_none());
4496 : }
4497 :
4498 8 : if !self.is_active() || self.cancel.is_cancelled() {
4499 0 : return Err(GcError::TenantCancelled);
4500 8 : }
4501 :
4502 : // grab mutex to prevent new timelines from being created here; avoid doing long operations
4503 : // because that will stall branch creation.
4504 8 : let gc_cs = self.gc_cs.lock().await;
4505 :
4506 : // Ok, we now know all the branch points.
4507 : // Update the GC information for each timeline.
4508 8 : let mut gc_timelines = Vec::with_capacity(timelines.len());
4509 16 : for timeline in timelines {
4510 : // We filtered the timeline list above
4511 8 : if let Some(target_timeline_id) = target_timeline_id {
4512 8 : assert_eq!(target_timeline_id, timeline.timeline_id);
4513 0 : }
4514 :
4515 : {
4516 8 : let mut target = timeline.gc_info.write().unwrap();
4517 8 :
4518 8 : // Cull any expired leases
4519 8 : let now = SystemTime::now();
4520 12 : target.leases.retain(|_, lease| !lease.is_expired(&now));
4521 8 :
4522 8 : timeline
4523 8 : .metrics
4524 8 : .valid_lsn_lease_count_gauge
4525 8 : .set(target.leases.len() as u64);
4526 :
4527 : // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
4528 8 : if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
4529 0 : if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
4530 0 : target.within_ancestor_pitr =
4531 0 : timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
4532 0 : }
4533 8 : }
4534 :
4535 : // Update metrics that depend on GC state
4536 8 : timeline
4537 8 : .metrics
4538 8 : .archival_size
4539 8 : .set(if target.within_ancestor_pitr {
4540 0 : timeline.metrics.current_logical_size_gauge.get()
4541 : } else {
4542 8 : 0
4543 : });
4544 8 : timeline.metrics.pitr_history_size.set(
4545 8 : timeline
4546 8 : .get_last_record_lsn()
4547 8 : .checked_sub(target.cutoffs.time)
4548 8 : .unwrap_or(Lsn(0))
4549 8 : .0,
4550 8 : );
4551 :
4552 : // Apply the cutoffs we found to the Timeline's GcInfo. Why might we _not_ have cutoffs for a timeline?
4553 : // - this timeline was created while we were finding cutoffs
4554 : // - lsn for timestamp search fails for this timeline repeatedly
4555 8 : if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
4556 8 : let original_cutoffs = target.cutoffs.clone();
4557 8 : // GC cutoffs should never go back
4558 8 : target.cutoffs = GcCutoffs {
4559 8 : space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
4560 8 : time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
4561 8 : }
4562 0 : }
4563 : }
4564 :
4565 8 : gc_timelines.push(timeline);
4566 : }
4567 8 : drop(gc_cs);
4568 8 : Ok(gc_timelines)
4569 8 : }
4570 :
4571 : /// A substitute for `branch_timeline` for use in unit tests.
4572 : /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
4573 : /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
4574 : /// timeline background tasks are launched, except the flush loop.
4575 : #[cfg(test)]
4576 464 : async fn branch_timeline_test(
4577 464 : self: &Arc<Self>,
4578 464 : src_timeline: &Arc<Timeline>,
4579 464 : dst_id: TimelineId,
4580 464 : ancestor_lsn: Option<Lsn>,
4581 464 : ctx: &RequestContext,
4582 464 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
4583 464 : let tl = self
4584 464 : .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
4585 464 : .await?
4586 456 : .into_timeline_for_test();
4587 456 : tl.set_state(TimelineState::Active);
4588 456 : Ok(tl)
4589 464 : }
4590 :
4591 : /// Helper for unit tests to branch a timeline with some pre-loaded states.
4592 : #[cfg(test)]
4593 : #[allow(clippy::too_many_arguments)]
4594 12 : pub async fn branch_timeline_test_with_layers(
4595 12 : self: &Arc<Self>,
4596 12 : src_timeline: &Arc<Timeline>,
4597 12 : dst_id: TimelineId,
4598 12 : ancestor_lsn: Option<Lsn>,
4599 12 : ctx: &RequestContext,
4600 12 : delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
4601 12 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
4602 12 : end_lsn: Lsn,
4603 12 : ) -> anyhow::Result<Arc<Timeline>> {
4604 : use checks::check_valid_layermap;
4605 : use itertools::Itertools;
4606 :
4607 12 : let tline = self
4608 12 : .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
4609 12 : .await?;
4610 12 : let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
4611 12 : ancestor_lsn
4612 : } else {
4613 0 : tline.get_last_record_lsn()
4614 : };
4615 12 : assert!(end_lsn >= ancestor_lsn);
4616 12 : tline.force_advance_lsn(end_lsn);
4617 24 : for deltas in delta_layer_desc {
4618 12 : tline
4619 12 : .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
4620 12 : .await?;
4621 : }
4622 20 : for (lsn, images) in image_layer_desc {
4623 8 : tline
4624 8 : .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
4625 8 : .await?;
4626 : }
4627 12 : let layer_names = tline
4628 12 : .layers
4629 12 : .read()
4630 12 : .await
4631 12 : .layer_map()
4632 12 : .unwrap()
4633 12 : .iter_historic_layers()
4634 20 : .map(|layer| layer.layer_name())
4635 12 : .collect_vec();
4636 12 : if let Some(err) = check_valid_layermap(&layer_names) {
4637 0 : bail!("invalid layermap: {err}");
4638 12 : }
4639 12 : Ok(tline)
4640 12 : }
4641 :
4642 : /// Branch an existing timeline.
4643 0 : async fn branch_timeline(
4644 0 : self: &Arc<Self>,
4645 0 : src_timeline: &Arc<Timeline>,
4646 0 : dst_id: TimelineId,
4647 0 : start_lsn: Option<Lsn>,
4648 0 : ctx: &RequestContext,
4649 0 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
4650 0 : self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
4651 0 : .await
4652 0 : }
4653 :
4654 464 : async fn branch_timeline_impl(
4655 464 : self: &Arc<Self>,
4656 464 : src_timeline: &Arc<Timeline>,
4657 464 : dst_id: TimelineId,
4658 464 : start_lsn: Option<Lsn>,
4659 464 : _ctx: &RequestContext,
4660 464 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
4661 464 : let src_id = src_timeline.timeline_id;
4662 :
4663 : // We will validate our ancestor LSN in this function. Acquire the GC lock so that
4664 : // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
4665 : // valid while we are creating the branch.
4666 464 : let _gc_cs = self.gc_cs.lock().await;
4667 :
4668 : // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
4669 464 : let start_lsn = start_lsn.unwrap_or_else(|| {
4670 4 : let lsn = src_timeline.get_last_record_lsn();
4671 4 : info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
4672 4 : lsn
4673 464 : });
4674 :
4675 : // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
4676 464 : let timeline_create_guard = match self
4677 464 : .start_creating_timeline(
4678 464 : dst_id,
4679 464 : CreateTimelineIdempotency::Branch {
4680 464 : ancestor_timeline_id: src_timeline.timeline_id,
4681 464 : ancestor_start_lsn: start_lsn,
4682 464 : },
4683 464 : )
4684 464 : .await?
4685 : {
4686 464 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
4687 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
4688 0 : return Ok(CreateTimelineResult::Idempotent(timeline));
4689 : }
4690 : };
4691 :
4692 : // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
4693 : // horizon on the source timeline
4694 : //
4695 : // We check it against both the planned GC cutoff stored in 'gc_info',
4696 : // and the 'latest_gc_cutoff' of the last GC that was performed. The
4697 : // planned GC cutoff in 'gc_info' is normally larger than
4698 : // 'latest_gc_cutoff_lsn', but beware of corner cases like if you just
4699 : // changed the GC settings for the tenant to make the PITR window
4700 : // larger, but some of the data was already removed by an earlier GC
4701 : // iteration.
4702 :
4703 : // check against last actual 'latest_gc_cutoff' first
4704 464 : let latest_gc_cutoff_lsn = src_timeline.get_latest_gc_cutoff_lsn();
4705 464 : {
4706 464 : let gc_info = src_timeline.gc_info.read().unwrap();
4707 464 : let planned_cutoff = gc_info.min_cutoff();
4708 464 : if gc_info.lsn_covered_by_lease(start_lsn) {
4709 0 : tracing::info!("skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease", *latest_gc_cutoff_lsn);
4710 : } else {
4711 464 : src_timeline
4712 464 : .check_lsn_is_in_scope(start_lsn, &latest_gc_cutoff_lsn)
4713 464 : .context(format!(
4714 464 : "invalid branch start lsn: less than latest GC cutoff {}",
4715 464 : *latest_gc_cutoff_lsn,
4716 464 : ))
4717 464 : .map_err(CreateTimelineError::AncestorLsn)?;
4718 :
4719 : // and then the planned GC cutoff
4720 456 : if start_lsn < planned_cutoff {
4721 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
4722 0 : "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
4723 0 : )));
4724 456 : }
4725 : }
4726 : }
4727 :
4728 : //
4729 : // The branch point is valid, and we are still holding the 'gc_cs' lock
4730 : // so that GC cannot advance the GC cutoff until we are finished.
4731 : // Proceed with the branch creation.
4732 : //
4733 :
4734 : // Determine prev-LSN for the new timeline. We can only determine it if
4735 : // the timeline was branched at the current end of the source timeline.
4736 : let RecordLsn {
4737 456 : last: src_last,
4738 456 : prev: src_prev,
4739 456 : } = src_timeline.get_last_record_rlsn();
4740 456 : let dst_prev = if src_last == start_lsn {
4741 432 : Some(src_prev)
4742 : } else {
4743 24 : None
4744 : };
4745 :
4746 : // Create the metadata file, noting the ancestor of the new timeline.
4747 : // There is initially no data in it, but all the read-calls know to look
4748 : // into the ancestor.
4749 456 : let metadata = TimelineMetadata::new(
4750 456 : start_lsn,
4751 456 : dst_prev,
4752 456 : Some(src_id),
4753 456 : start_lsn,
4754 456 : *src_timeline.latest_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
4755 456 : src_timeline.initdb_lsn,
4756 456 : src_timeline.pg_version,
4757 456 : );
4758 :
4759 456 : let uninitialized_timeline = self
4760 456 : .prepare_new_timeline(
4761 456 : dst_id,
4762 456 : &metadata,
4763 456 : timeline_create_guard,
4764 456 : start_lsn + 1,
4765 456 : Some(Arc::clone(src_timeline)),
4766 456 : )
4767 456 : .await?;
4768 :
4769 456 : let new_timeline = uninitialized_timeline.finish_creation().await?;
4770 :
4771 : // Root timeline gets its layers during creation and uploads them along with the metadata.
4772 : // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
4773 : // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
4774 : // could get incorrect information and remove more layers, than needed.
4775 : // See also https://github.com/neondatabase/neon/issues/3865
4776 456 : new_timeline
4777 456 : .remote_client
4778 456 : .schedule_index_upload_for_full_metadata_update(&metadata)
4779 456 : .context("branch initial metadata upload")?;
4780 :
4781 : // Callers are responsible to wait for uploads to complete and for activating the timeline.
4782 :
4783 456 : Ok(CreateTimelineResult::Created(new_timeline))
4784 464 : }
4785 :
4786 : /// For unit tests, make this visible so that other modules can directly create timelines
4787 : #[cfg(test)]
4788 : #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
4789 : pub(crate) async fn bootstrap_timeline_test(
4790 : self: &Arc<Self>,
4791 : timeline_id: TimelineId,
4792 : pg_version: u32,
4793 : load_existing_initdb: Option<TimelineId>,
4794 : ctx: &RequestContext,
4795 : ) -> anyhow::Result<Arc<Timeline>> {
4796 : self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
4797 : .await
4798 : .map_err(anyhow::Error::new)
4799 4 : .map(|r| r.into_timeline_for_test())
4800 : }
4801 :
4802 : /// Get exclusive access to the timeline ID for creation.
4803 : ///
4804 : /// Timeline-creating code paths must use this function before making changes
4805 : /// to in-memory or persistent state.
4806 : ///
4807 : /// The `state` parameter is a description of the timeline creation operation
4808 : /// we intend to perform.
4809 : /// If the timeline was already created in the meantime, we check whether this
4810 : /// request conflicts or is idempotent , based on `state`.
4811 892 : async fn start_creating_timeline(
4812 892 : self: &Arc<Self>,
4813 892 : new_timeline_id: TimelineId,
4814 892 : idempotency: CreateTimelineIdempotency,
4815 892 : ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
4816 892 : let allow_offloaded = false;
4817 892 : match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
4818 888 : Ok(create_guard) => {
4819 888 : pausable_failpoint!("timeline-creation-after-uninit");
4820 888 : Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
4821 : }
4822 0 : Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
4823 : Err(TimelineExclusionError::AlreadyCreating) => {
4824 : // Creation is in progress, we cannot create it again, and we cannot
4825 : // check if this request matches the existing one, so caller must try
4826 : // again later.
4827 0 : Err(CreateTimelineError::AlreadyCreating)
4828 : }
4829 0 : Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
4830 : Err(TimelineExclusionError::AlreadyExists {
4831 0 : existing: TimelineOrOffloaded::Offloaded(_existing),
4832 0 : ..
4833 0 : }) => {
4834 0 : info!("timeline already exists but is offloaded");
4835 0 : Err(CreateTimelineError::Conflict)
4836 : }
4837 : Err(TimelineExclusionError::AlreadyExists {
4838 4 : existing: TimelineOrOffloaded::Timeline(existing),
4839 4 : arg,
4840 4 : }) => {
4841 4 : {
4842 4 : let existing = &existing.create_idempotency;
4843 4 : let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
4844 4 : debug!("timeline already exists");
4845 :
4846 4 : match (existing, &arg) {
4847 : // FailWithConflict => no idempotency check
4848 : (CreateTimelineIdempotency::FailWithConflict, _)
4849 : | (_, CreateTimelineIdempotency::FailWithConflict) => {
4850 4 : warn!("timeline already exists, failing request");
4851 4 : return Err(CreateTimelineError::Conflict);
4852 : }
4853 : // Idempotent <=> CreateTimelineIdempotency is identical
4854 0 : (x, y) if x == y => {
4855 0 : info!("timeline already exists and idempotency matches, succeeding request");
4856 : // fallthrough
4857 : }
4858 : (_, _) => {
4859 0 : warn!("idempotency conflict, failing request");
4860 0 : return Err(CreateTimelineError::Conflict);
4861 : }
4862 : }
4863 : }
4864 :
4865 0 : Ok(StartCreatingTimelineResult::Idempotent(existing))
4866 : }
4867 : }
4868 892 : }
4869 :
4870 0 : async fn upload_initdb(
4871 0 : &self,
4872 0 : timelines_path: &Utf8PathBuf,
4873 0 : pgdata_path: &Utf8PathBuf,
4874 0 : timeline_id: &TimelineId,
4875 0 : ) -> anyhow::Result<()> {
4876 0 : let temp_path = timelines_path.join(format!(
4877 0 : "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
4878 0 : ));
4879 0 :
4880 0 : scopeguard::defer! {
4881 0 : if let Err(e) = fs::remove_file(&temp_path) {
4882 0 : error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
4883 0 : }
4884 0 : }
4885 :
4886 0 : let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
4887 : const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
4888 0 : if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
4889 0 : warn!(
4890 0 : "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
4891 : );
4892 0 : }
4893 :
4894 0 : pausable_failpoint!("before-initdb-upload");
4895 :
4896 0 : backoff::retry(
4897 0 : || async {
4898 0 : self::remote_timeline_client::upload_initdb_dir(
4899 0 : &self.remote_storage,
4900 0 : &self.tenant_shard_id.tenant_id,
4901 0 : timeline_id,
4902 0 : pgdata_zstd.try_clone().await?,
4903 0 : tar_zst_size,
4904 0 : &self.cancel,
4905 0 : )
4906 0 : .await
4907 0 : },
4908 0 : |_| false,
4909 0 : 3,
4910 0 : u32::MAX,
4911 0 : "persist_initdb_tar_zst",
4912 0 : &self.cancel,
4913 0 : )
4914 0 : .await
4915 0 : .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
4916 0 : .and_then(|x| x)
4917 0 : }
4918 :
4919 : /// - run initdb to init temporary instance and get bootstrap data
4920 : /// - after initialization completes, tar up the temp dir and upload it to S3.
4921 4 : async fn bootstrap_timeline(
4922 4 : self: &Arc<Self>,
4923 4 : timeline_id: TimelineId,
4924 4 : pg_version: u32,
4925 4 : load_existing_initdb: Option<TimelineId>,
4926 4 : ctx: &RequestContext,
4927 4 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
4928 4 : let timeline_create_guard = match self
4929 4 : .start_creating_timeline(
4930 4 : timeline_id,
4931 4 : CreateTimelineIdempotency::Bootstrap { pg_version },
4932 4 : )
4933 4 : .await?
4934 : {
4935 4 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
4936 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
4937 0 : return Ok(CreateTimelineResult::Idempotent(timeline))
4938 : }
4939 : };
4940 :
4941 : // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
4942 : // temporary directory for basebackup files for the given timeline.
4943 :
4944 4 : let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
4945 4 : let pgdata_path = path_with_suffix_extension(
4946 4 : timelines_path.join(format!("basebackup-{timeline_id}")),
4947 4 : TEMP_FILE_SUFFIX,
4948 4 : );
4949 4 :
4950 4 : // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
4951 4 : // we won't race with other creations or existent timelines with the same path.
4952 4 : if pgdata_path.exists() {
4953 0 : fs::remove_dir_all(&pgdata_path).with_context(|| {
4954 0 : format!("Failed to remove already existing initdb directory: {pgdata_path}")
4955 0 : })?;
4956 4 : }
4957 :
4958 : // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
4959 4 : let pgdata_path_deferred = pgdata_path.clone();
4960 4 : scopeguard::defer! {
4961 4 : if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred) {
4962 4 : // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
4963 4 : error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
4964 4 : }
4965 4 : }
4966 4 : if let Some(existing_initdb_timeline_id) = load_existing_initdb {
4967 4 : if existing_initdb_timeline_id != timeline_id {
4968 0 : let source_path = &remote_initdb_archive_path(
4969 0 : &self.tenant_shard_id.tenant_id,
4970 0 : &existing_initdb_timeline_id,
4971 0 : );
4972 0 : let dest_path =
4973 0 : &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
4974 0 :
4975 0 : // if this fails, it will get retried by retried control plane requests
4976 0 : self.remote_storage
4977 0 : .copy_object(source_path, dest_path, &self.cancel)
4978 0 : .await
4979 0 : .context("copy initdb tar")?;
4980 4 : }
4981 4 : let (initdb_tar_zst_path, initdb_tar_zst) =
4982 4 : self::remote_timeline_client::download_initdb_tar_zst(
4983 4 : self.conf,
4984 4 : &self.remote_storage,
4985 4 : &self.tenant_shard_id,
4986 4 : &existing_initdb_timeline_id,
4987 4 : &self.cancel,
4988 4 : )
4989 4 : .await
4990 4 : .context("download initdb tar")?;
4991 :
4992 4 : scopeguard::defer! {
4993 4 : if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
4994 4 : error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
4995 4 : }
4996 4 : }
4997 4 :
4998 4 : let buf_read =
4999 4 : BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
5000 4 : extract_zst_tarball(&pgdata_path, buf_read)
5001 4 : .await
5002 4 : .context("extract initdb tar")?;
5003 : } else {
5004 : // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
5005 0 : run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
5006 0 : .await
5007 0 : .context("run initdb")?;
5008 :
5009 : // Upload the created data dir to S3
5010 0 : if self.tenant_shard_id().is_shard_zero() {
5011 0 : self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
5012 0 : .await?;
5013 0 : }
5014 : }
5015 4 : let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
5016 4 :
5017 4 : // Import the contents of the data directory at the initial checkpoint
5018 4 : // LSN, and any WAL after that.
5019 4 : // Initdb lsn will be equal to last_record_lsn which will be set after import.
5020 4 : // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
5021 4 : let new_metadata = TimelineMetadata::new(
5022 4 : Lsn(0),
5023 4 : None,
5024 4 : None,
5025 4 : Lsn(0),
5026 4 : pgdata_lsn,
5027 4 : pgdata_lsn,
5028 4 : pg_version,
5029 4 : );
5030 4 : let mut raw_timeline = self
5031 4 : .prepare_new_timeline(
5032 4 : timeline_id,
5033 4 : &new_metadata,
5034 4 : timeline_create_guard,
5035 4 : pgdata_lsn,
5036 4 : None,
5037 4 : )
5038 4 : .await?;
5039 :
5040 4 : let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
5041 4 : raw_timeline
5042 4 : .write(|unfinished_timeline| async move {
5043 4 : import_datadir::import_timeline_from_postgres_datadir(
5044 4 : &unfinished_timeline,
5045 4 : &pgdata_path,
5046 4 : pgdata_lsn,
5047 4 : ctx,
5048 4 : )
5049 4 : .await
5050 4 : .with_context(|| {
5051 0 : format!(
5052 0 : "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
5053 0 : )
5054 4 : })?;
5055 :
5056 4 : fail::fail_point!("before-checkpoint-new-timeline", |_| {
5057 0 : Err(CreateTimelineError::Other(anyhow::anyhow!(
5058 0 : "failpoint before-checkpoint-new-timeline"
5059 0 : )))
5060 4 : });
5061 :
5062 4 : Ok(())
5063 8 : })
5064 4 : .await?;
5065 :
5066 : // All done!
5067 4 : let timeline = raw_timeline.finish_creation().await?;
5068 :
5069 : // Callers are responsible to wait for uploads to complete and for activating the timeline.
5070 :
5071 4 : Ok(CreateTimelineResult::Created(timeline))
5072 4 : }
5073 :
5074 880 : fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
5075 880 : RemoteTimelineClient::new(
5076 880 : self.remote_storage.clone(),
5077 880 : self.deletion_queue_client.clone(),
5078 880 : self.conf,
5079 880 : self.tenant_shard_id,
5080 880 : timeline_id,
5081 880 : self.generation,
5082 880 : &self.tenant_conf.load().location,
5083 880 : )
5084 880 : }
5085 :
5086 : /// Builds required resources for a new timeline.
5087 880 : fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
5088 880 : let remote_client = self.build_timeline_remote_client(timeline_id);
5089 880 : self.get_timeline_resources_for(remote_client)
5090 880 : }
5091 :
5092 : /// Builds timeline resources for the given remote client.
5093 892 : fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
5094 892 : TimelineResources {
5095 892 : remote_client,
5096 892 : pagestream_throttle: self.pagestream_throttle.clone(),
5097 892 : pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
5098 892 : l0_compaction_trigger: self.l0_compaction_trigger.clone(),
5099 892 : l0_flush_global_state: self.l0_flush_global_state.clone(),
5100 892 : }
5101 892 : }
5102 :
5103 : /// Creates intermediate timeline structure and its files.
5104 : ///
5105 : /// An empty layer map is initialized, and new data and WAL can be imported starting
5106 : /// at 'disk_consistent_lsn'. After any initial data has been imported, call
5107 : /// `finish_creation` to insert the Timeline into the timelines map.
5108 880 : async fn prepare_new_timeline<'a>(
5109 880 : &'a self,
5110 880 : new_timeline_id: TimelineId,
5111 880 : new_metadata: &TimelineMetadata,
5112 880 : create_guard: TimelineCreateGuard,
5113 880 : start_lsn: Lsn,
5114 880 : ancestor: Option<Arc<Timeline>>,
5115 880 : ) -> anyhow::Result<UninitializedTimeline<'a>> {
5116 880 : let tenant_shard_id = self.tenant_shard_id;
5117 880 :
5118 880 : let resources = self.build_timeline_resources(new_timeline_id);
5119 880 : resources
5120 880 : .remote_client
5121 880 : .init_upload_queue_for_empty_remote(new_metadata)?;
5122 :
5123 880 : let timeline_struct = self
5124 880 : .create_timeline_struct(
5125 880 : new_timeline_id,
5126 880 : new_metadata,
5127 880 : ancestor,
5128 880 : resources,
5129 880 : CreateTimelineCause::Load,
5130 880 : create_guard.idempotency.clone(),
5131 880 : )
5132 880 : .context("Failed to create timeline data structure")?;
5133 :
5134 880 : timeline_struct.init_empty_layer_map(start_lsn);
5135 :
5136 880 : if let Err(e) = self
5137 880 : .create_timeline_files(&create_guard.timeline_path)
5138 880 : .await
5139 : {
5140 0 : error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
5141 0 : cleanup_timeline_directory(create_guard);
5142 0 : return Err(e);
5143 880 : }
5144 880 :
5145 880 : debug!(
5146 0 : "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
5147 : );
5148 :
5149 880 : Ok(UninitializedTimeline::new(
5150 880 : self,
5151 880 : new_timeline_id,
5152 880 : Some((timeline_struct, create_guard)),
5153 880 : ))
5154 880 : }
5155 :
5156 880 : async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
5157 880 : crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
5158 :
5159 880 : fail::fail_point!("after-timeline-dir-creation", |_| {
5160 0 : anyhow::bail!("failpoint after-timeline-dir-creation");
5161 880 : });
5162 :
5163 880 : Ok(())
5164 880 : }
5165 :
5166 : /// Get a guard that provides exclusive access to the timeline directory, preventing
5167 : /// concurrent attempts to create the same timeline.
5168 : ///
5169 : /// The `allow_offloaded` parameter controls whether to tolerate the existence of
5170 : /// offloaded timelines or not.
5171 892 : fn create_timeline_create_guard(
5172 892 : self: &Arc<Self>,
5173 892 : timeline_id: TimelineId,
5174 892 : idempotency: CreateTimelineIdempotency,
5175 892 : allow_offloaded: bool,
5176 892 : ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
5177 892 : let tenant_shard_id = self.tenant_shard_id;
5178 892 :
5179 892 : let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
5180 :
5181 892 : let create_guard = TimelineCreateGuard::new(
5182 892 : self,
5183 892 : timeline_id,
5184 892 : timeline_path.clone(),
5185 892 : idempotency,
5186 892 : allow_offloaded,
5187 892 : )?;
5188 :
5189 : // At this stage, we have got exclusive access to in-memory state for this timeline ID
5190 : // for creation.
5191 : // A timeline directory should never exist on disk already:
5192 : // - a previous failed creation would have cleaned up after itself
5193 : // - a pageserver restart would clean up timeline directories that don't have valid remote state
5194 : //
5195 : // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
5196 : // this error may indicate a bug in cleanup on failed creations.
5197 888 : if timeline_path.exists() {
5198 0 : return Err(TimelineExclusionError::Other(anyhow::anyhow!(
5199 0 : "Timeline directory already exists! This is a bug."
5200 0 : )));
5201 888 : }
5202 888 :
5203 888 : Ok(create_guard)
5204 892 : }
5205 :
5206 : /// Gathers inputs from all of the timelines to produce a sizing model input.
5207 : ///
5208 : /// Future is cancellation safe. Only one calculation can be running at once per tenant.
5209 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5210 : pub async fn gather_size_inputs(
5211 : &self,
5212 : // `max_retention_period` overrides the cutoff that is used to calculate the size
5213 : // (only if it is shorter than the real cutoff).
5214 : max_retention_period: Option<u64>,
5215 : cause: LogicalSizeCalculationCause,
5216 : cancel: &CancellationToken,
5217 : ctx: &RequestContext,
5218 : ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
5219 : let logical_sizes_at_once = self
5220 : .conf
5221 : .concurrent_tenant_size_logical_size_queries
5222 : .inner();
5223 :
5224 : // TODO: Having a single mutex block concurrent reads is not great for performance.
5225 : //
5226 : // But the only case where we need to run multiple of these at once is when we
5227 : // request a size for a tenant manually via API, while another background calculation
5228 : // is in progress (which is not a common case).
5229 : //
5230 : // See more for on the issue #2748 condenced out of the initial PR review.
5231 : let mut shared_cache = tokio::select! {
5232 : locked = self.cached_logical_sizes.lock() => locked,
5233 : _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
5234 : _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
5235 : };
5236 :
5237 : size::gather_inputs(
5238 : self,
5239 : logical_sizes_at_once,
5240 : max_retention_period,
5241 : &mut shared_cache,
5242 : cause,
5243 : cancel,
5244 : ctx,
5245 : )
5246 : .await
5247 : }
5248 :
5249 : /// Calculate synthetic tenant size and cache the result.
5250 : /// This is periodically called by background worker.
5251 : /// result is cached in tenant struct
5252 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5253 : pub async fn calculate_synthetic_size(
5254 : &self,
5255 : cause: LogicalSizeCalculationCause,
5256 : cancel: &CancellationToken,
5257 : ctx: &RequestContext,
5258 : ) -> Result<u64, size::CalculateSyntheticSizeError> {
5259 : let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
5260 :
5261 : let size = inputs.calculate();
5262 :
5263 : self.set_cached_synthetic_size(size);
5264 :
5265 : Ok(size)
5266 : }
5267 :
5268 : /// Cache given synthetic size and update the metric value
5269 0 : pub fn set_cached_synthetic_size(&self, size: u64) {
5270 0 : self.cached_synthetic_tenant_size
5271 0 : .store(size, Ordering::Relaxed);
5272 0 :
5273 0 : // Only shard zero should be calculating synthetic sizes
5274 0 : debug_assert!(self.shard_identity.is_shard_zero());
5275 :
5276 0 : TENANT_SYNTHETIC_SIZE_METRIC
5277 0 : .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
5278 0 : .unwrap()
5279 0 : .set(size);
5280 0 : }
5281 :
5282 0 : pub fn cached_synthetic_size(&self) -> u64 {
5283 0 : self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
5284 0 : }
5285 :
5286 : /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
5287 : ///
5288 : /// This function can take a long time: callers should wrap it in a timeout if calling
5289 : /// from an external API handler.
5290 : ///
5291 : /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
5292 : /// still bounded by tenant/timeline shutdown.
5293 : #[tracing::instrument(skip_all)]
5294 : pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
5295 : let timelines = self.timelines.lock().unwrap().clone();
5296 :
5297 0 : async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
5298 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
5299 0 : timeline.freeze_and_flush().await?;
5300 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
5301 0 : timeline.remote_client.wait_completion().await?;
5302 :
5303 0 : Ok(())
5304 0 : }
5305 :
5306 : // We do not use a JoinSet for these tasks, because we don't want them to be
5307 : // aborted when this function's future is cancelled: they should stay alive
5308 : // holding their GateGuard until they complete, to ensure their I/Os complete
5309 : // before Timeline shutdown completes.
5310 : let mut results = FuturesUnordered::new();
5311 :
5312 : for (_timeline_id, timeline) in timelines {
5313 : // Run each timeline's flush in a task holding the timeline's gate: this
5314 : // means that if this function's future is cancelled, the Timeline shutdown
5315 : // will still wait for any I/O in here to complete.
5316 : let Ok(gate) = timeline.gate.enter() else {
5317 : continue;
5318 : };
5319 0 : let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
5320 : results.push(jh);
5321 : }
5322 :
5323 : while let Some(r) = results.next().await {
5324 : if let Err(e) = r {
5325 : if !e.is_cancelled() && !e.is_panic() {
5326 : tracing::error!("unexpected join error: {e:?}");
5327 : }
5328 : }
5329 : }
5330 :
5331 : // The flushes we did above were just writes, but the Tenant might have had
5332 : // pending deletions as well from recent compaction/gc: we want to flush those
5333 : // as well. This requires flushing the global delete queue. This is cheap
5334 : // because it's typically a no-op.
5335 : match self.deletion_queue_client.flush_execute().await {
5336 : Ok(_) => {}
5337 : Err(DeletionQueueError::ShuttingDown) => {}
5338 : }
5339 :
5340 : Ok(())
5341 : }
5342 :
5343 0 : pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
5344 0 : self.tenant_conf.load().tenant_conf.clone()
5345 0 : }
5346 :
5347 : /// How much local storage would this tenant like to have? It can cope with
5348 : /// less than this (via eviction and on-demand downloads), but this function enables
5349 : /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
5350 : /// by keeping important things on local disk.
5351 : ///
5352 : /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
5353 : /// than they report here, due to layer eviction. Tenants with many active branches may
5354 : /// actually use more than they report here.
5355 0 : pub(crate) fn local_storage_wanted(&self) -> u64 {
5356 0 : let timelines = self.timelines.lock().unwrap();
5357 0 :
5358 0 : // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum. This
5359 0 : // reflects the observation that on tenants with multiple large branches, typically only one
5360 0 : // of them is used actively enough to occupy space on disk.
5361 0 : timelines
5362 0 : .values()
5363 0 : .map(|t| t.metrics.visible_physical_size_gauge.get())
5364 0 : .max()
5365 0 : .unwrap_or(0)
5366 0 : }
5367 :
5368 : /// Serialize and write the latest TenantManifest to remote storage.
5369 4 : pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
5370 : // Only one manifest write may be done at at time, and the contents of the manifest
5371 : // must be loaded while holding this lock. This makes it safe to call this function
5372 : // from anywhere without worrying about colliding updates.
5373 4 : let mut guard = tokio::select! {
5374 4 : g = self.tenant_manifest_upload.lock() => {
5375 4 : g
5376 : },
5377 4 : _ = self.cancel.cancelled() => {
5378 0 : return Err(TenantManifestError::Cancelled);
5379 : }
5380 : };
5381 :
5382 4 : let manifest = self.build_tenant_manifest();
5383 4 : if Some(&manifest) == (*guard).as_ref() {
5384 : // Optimisation: skip uploads that don't change anything.
5385 0 : return Ok(());
5386 4 : }
5387 4 :
5388 4 : // Remote storage does no retries internally, so wrap it
5389 4 : match backoff::retry(
5390 4 : || async {
5391 4 : upload_tenant_manifest(
5392 4 : &self.remote_storage,
5393 4 : &self.tenant_shard_id,
5394 4 : self.generation,
5395 4 : &manifest,
5396 4 : &self.cancel,
5397 4 : )
5398 4 : .await
5399 8 : },
5400 4 : |_e| self.cancel.is_cancelled(),
5401 4 : FAILED_UPLOAD_WARN_THRESHOLD,
5402 4 : FAILED_REMOTE_OP_RETRIES,
5403 4 : "uploading tenant manifest",
5404 4 : &self.cancel,
5405 4 : )
5406 4 : .await
5407 : {
5408 0 : None => Err(TenantManifestError::Cancelled),
5409 0 : Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
5410 0 : Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
5411 : Some(Ok(_)) => {
5412 : // Store the successfully uploaded manifest, so that future callers can avoid
5413 : // re-uploading the same thing.
5414 4 : *guard = Some(manifest);
5415 4 :
5416 4 : Ok(())
5417 : }
5418 : }
5419 4 : }
5420 : }
5421 :
5422 : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
5423 : /// to get bootstrap data for timeline initialization.
5424 0 : async fn run_initdb(
5425 0 : conf: &'static PageServerConf,
5426 0 : initdb_target_dir: &Utf8Path,
5427 0 : pg_version: u32,
5428 0 : cancel: &CancellationToken,
5429 0 : ) -> Result<(), InitdbError> {
5430 0 : let initdb_bin_path = conf
5431 0 : .pg_bin_dir(pg_version)
5432 0 : .map_err(InitdbError::Other)?
5433 0 : .join("initdb");
5434 0 : let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
5435 0 : info!(
5436 0 : "running {} in {}, libdir: {}",
5437 : initdb_bin_path, initdb_target_dir, initdb_lib_dir,
5438 : );
5439 :
5440 0 : let _permit = {
5441 0 : let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
5442 0 : INIT_DB_SEMAPHORE.acquire().await
5443 : };
5444 :
5445 0 : CONCURRENT_INITDBS.inc();
5446 0 : scopeguard::defer! {
5447 0 : CONCURRENT_INITDBS.dec();
5448 0 : }
5449 0 :
5450 0 : let _timer = INITDB_RUN_TIME.start_timer();
5451 0 : let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
5452 0 : superuser: &conf.superuser,
5453 0 : locale: &conf.locale,
5454 0 : initdb_bin: &initdb_bin_path,
5455 0 : pg_version,
5456 0 : library_search_path: &initdb_lib_dir,
5457 0 : pgdata: initdb_target_dir,
5458 0 : })
5459 0 : .await
5460 0 : .map_err(InitdbError::Inner);
5461 0 :
5462 0 : // This isn't true cancellation support, see above. Still return an error to
5463 0 : // excercise the cancellation code path.
5464 0 : if cancel.is_cancelled() {
5465 0 : return Err(InitdbError::Cancelled);
5466 0 : }
5467 0 :
5468 0 : res
5469 0 : }
5470 :
5471 : /// Dump contents of a layer file to stdout.
5472 0 : pub async fn dump_layerfile_from_path(
5473 0 : path: &Utf8Path,
5474 0 : verbose: bool,
5475 0 : ctx: &RequestContext,
5476 0 : ) -> anyhow::Result<()> {
5477 : use std::os::unix::fs::FileExt;
5478 :
5479 : // All layer files start with a two-byte "magic" value, to identify the kind of
5480 : // file.
5481 0 : let file = File::open(path)?;
5482 0 : let mut header_buf = [0u8; 2];
5483 0 : file.read_exact_at(&mut header_buf, 0)?;
5484 :
5485 0 : match u16::from_be_bytes(header_buf) {
5486 : crate::IMAGE_FILE_MAGIC => {
5487 0 : ImageLayer::new_for_path(path, file)?
5488 0 : .dump(verbose, ctx)
5489 0 : .await?
5490 : }
5491 : crate::DELTA_FILE_MAGIC => {
5492 0 : DeltaLayer::new_for_path(path, file)?
5493 0 : .dump(verbose, ctx)
5494 0 : .await?
5495 : }
5496 0 : magic => bail!("unrecognized magic identifier: {:?}", magic),
5497 : }
5498 :
5499 0 : Ok(())
5500 0 : }
5501 :
5502 : #[cfg(test)]
5503 : pub(crate) mod harness {
5504 : use bytes::{Bytes, BytesMut};
5505 : use once_cell::sync::OnceCell;
5506 : use pageserver_api::models::ShardParameters;
5507 : use pageserver_api::shard::ShardIndex;
5508 : use utils::logging;
5509 :
5510 : use crate::deletion_queue::mock::MockDeletionQueue;
5511 : use crate::l0_flush::L0FlushConfig;
5512 : use crate::walredo::apply_neon;
5513 : use pageserver_api::key::Key;
5514 : use pageserver_api::record::NeonWalRecord;
5515 :
5516 : use super::*;
5517 : use hex_literal::hex;
5518 : use utils::id::TenantId;
5519 :
5520 : pub const TIMELINE_ID: TimelineId =
5521 : TimelineId::from_array(hex!("11223344556677881122334455667788"));
5522 : pub const NEW_TIMELINE_ID: TimelineId =
5523 : TimelineId::from_array(hex!("AA223344556677881122334455667788"));
5524 :
5525 : /// Convenience function to create a page image with given string as the only content
5526 10057526 : pub fn test_img(s: &str) -> Bytes {
5527 10057526 : let mut buf = BytesMut::new();
5528 10057526 : buf.extend_from_slice(s.as_bytes());
5529 10057526 : buf.resize(64, 0);
5530 10057526 :
5531 10057526 : buf.freeze()
5532 10057526 : }
5533 :
5534 : impl From<TenantConf> for TenantConfOpt {
5535 440 : fn from(tenant_conf: TenantConf) -> Self {
5536 440 : Self {
5537 440 : checkpoint_distance: Some(tenant_conf.checkpoint_distance),
5538 440 : checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
5539 440 : compaction_target_size: Some(tenant_conf.compaction_target_size),
5540 440 : compaction_period: Some(tenant_conf.compaction_period),
5541 440 : compaction_threshold: Some(tenant_conf.compaction_threshold),
5542 440 : compaction_upper_limit: Some(tenant_conf.compaction_upper_limit),
5543 440 : compaction_algorithm: Some(tenant_conf.compaction_algorithm),
5544 440 : compaction_l0_first: Some(tenant_conf.compaction_l0_first),
5545 440 : compaction_l0_semaphore: Some(tenant_conf.compaction_l0_semaphore),
5546 440 : l0_flush_delay_threshold: tenant_conf.l0_flush_delay_threshold,
5547 440 : l0_flush_stall_threshold: tenant_conf.l0_flush_stall_threshold,
5548 440 : l0_flush_wait_upload: Some(tenant_conf.l0_flush_wait_upload),
5549 440 : gc_horizon: Some(tenant_conf.gc_horizon),
5550 440 : gc_period: Some(tenant_conf.gc_period),
5551 440 : image_creation_threshold: Some(tenant_conf.image_creation_threshold),
5552 440 : pitr_interval: Some(tenant_conf.pitr_interval),
5553 440 : walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
5554 440 : lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
5555 440 : max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
5556 440 : eviction_policy: Some(tenant_conf.eviction_policy),
5557 440 : min_resident_size_override: tenant_conf.min_resident_size_override,
5558 440 : evictions_low_residence_duration_metric_threshold: Some(
5559 440 : tenant_conf.evictions_low_residence_duration_metric_threshold,
5560 440 : ),
5561 440 : heatmap_period: Some(tenant_conf.heatmap_period),
5562 440 : lazy_slru_download: Some(tenant_conf.lazy_slru_download),
5563 440 : timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
5564 440 : image_layer_creation_check_threshold: Some(
5565 440 : tenant_conf.image_layer_creation_check_threshold,
5566 440 : ),
5567 440 : image_creation_preempt_threshold: Some(
5568 440 : tenant_conf.image_creation_preempt_threshold,
5569 440 : ),
5570 440 : lsn_lease_length: Some(tenant_conf.lsn_lease_length),
5571 440 : lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
5572 440 : timeline_offloading: Some(tenant_conf.timeline_offloading),
5573 440 : wal_receiver_protocol_override: tenant_conf.wal_receiver_protocol_override,
5574 440 : rel_size_v2_enabled: tenant_conf.rel_size_v2_enabled,
5575 440 : gc_compaction_enabled: Some(tenant_conf.gc_compaction_enabled),
5576 440 : gc_compaction_initial_threshold_kb: Some(
5577 440 : tenant_conf.gc_compaction_initial_threshold_kb,
5578 440 : ),
5579 440 : gc_compaction_ratio_percent: Some(tenant_conf.gc_compaction_ratio_percent),
5580 440 : }
5581 440 : }
5582 : }
5583 :
5584 : pub struct TenantHarness {
5585 : pub conf: &'static PageServerConf,
5586 : pub tenant_conf: TenantConf,
5587 : pub tenant_shard_id: TenantShardId,
5588 : pub generation: Generation,
5589 : pub shard: ShardIndex,
5590 : pub remote_storage: GenericRemoteStorage,
5591 : pub remote_fs_dir: Utf8PathBuf,
5592 : pub deletion_queue: MockDeletionQueue,
5593 : }
5594 :
5595 : static LOG_HANDLE: OnceCell<()> = OnceCell::new();
5596 :
5597 488 : pub(crate) fn setup_logging() {
5598 488 : LOG_HANDLE.get_or_init(|| {
5599 464 : logging::init(
5600 464 : logging::LogFormat::Test,
5601 464 : // enable it in case the tests exercise code paths that use
5602 464 : // debug_assert_current_span_has_tenant_and_timeline_id
5603 464 : logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
5604 464 : logging::Output::Stdout,
5605 464 : )
5606 464 : .expect("Failed to init test logging")
5607 488 : });
5608 488 : }
5609 :
5610 : impl TenantHarness {
5611 440 : pub async fn create_custom(
5612 440 : test_name: &'static str,
5613 440 : tenant_conf: TenantConf,
5614 440 : tenant_id: TenantId,
5615 440 : shard_identity: ShardIdentity,
5616 440 : generation: Generation,
5617 440 : ) -> anyhow::Result<Self> {
5618 440 : setup_logging();
5619 440 :
5620 440 : let repo_dir = PageServerConf::test_repo_dir(test_name);
5621 440 : let _ = fs::remove_dir_all(&repo_dir);
5622 440 : fs::create_dir_all(&repo_dir)?;
5623 :
5624 440 : let conf = PageServerConf::dummy_conf(repo_dir);
5625 440 : // Make a static copy of the config. This can never be free'd, but that's
5626 440 : // OK in a test.
5627 440 : let conf: &'static PageServerConf = Box::leak(Box::new(conf));
5628 440 :
5629 440 : let shard = shard_identity.shard_index();
5630 440 : let tenant_shard_id = TenantShardId {
5631 440 : tenant_id,
5632 440 : shard_number: shard.shard_number,
5633 440 : shard_count: shard.shard_count,
5634 440 : };
5635 440 : fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
5636 440 : fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
5637 :
5638 : use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
5639 440 : let remote_fs_dir = conf.workdir.join("localfs");
5640 440 : std::fs::create_dir_all(&remote_fs_dir).unwrap();
5641 440 : let config = RemoteStorageConfig {
5642 440 : storage: RemoteStorageKind::LocalFs {
5643 440 : local_path: remote_fs_dir.clone(),
5644 440 : },
5645 440 : timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
5646 440 : small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
5647 440 : };
5648 440 : let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
5649 440 : let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
5650 440 :
5651 440 : Ok(Self {
5652 440 : conf,
5653 440 : tenant_conf,
5654 440 : tenant_shard_id,
5655 440 : generation,
5656 440 : shard,
5657 440 : remote_storage,
5658 440 : remote_fs_dir,
5659 440 : deletion_queue,
5660 440 : })
5661 440 : }
5662 :
5663 416 : pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
5664 416 : // Disable automatic GC and compaction to make the unit tests more deterministic.
5665 416 : // The tests perform them manually if needed.
5666 416 : let tenant_conf = TenantConf {
5667 416 : gc_period: Duration::ZERO,
5668 416 : compaction_period: Duration::ZERO,
5669 416 : ..TenantConf::default()
5670 416 : };
5671 416 : let tenant_id = TenantId::generate();
5672 416 : let shard = ShardIdentity::unsharded();
5673 416 : Self::create_custom(
5674 416 : test_name,
5675 416 : tenant_conf,
5676 416 : tenant_id,
5677 416 : shard,
5678 416 : Generation::new(0xdeadbeef),
5679 416 : )
5680 416 : .await
5681 416 : }
5682 :
5683 40 : pub fn span(&self) -> tracing::Span {
5684 40 : info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
5685 40 : }
5686 :
5687 440 : pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
5688 440 : let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
5689 440 : (
5690 440 : self.do_try_load(&ctx)
5691 440 : .await
5692 440 : .expect("failed to load test tenant"),
5693 440 : ctx,
5694 440 : )
5695 440 : }
5696 :
5697 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5698 : pub(crate) async fn do_try_load(
5699 : &self,
5700 : ctx: &RequestContext,
5701 : ) -> anyhow::Result<Arc<Tenant>> {
5702 : let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
5703 :
5704 : let tenant = Arc::new(Tenant::new(
5705 : TenantState::Attaching,
5706 : self.conf,
5707 : AttachedTenantConf::try_from(LocationConf::attached_single(
5708 : TenantConfOpt::from(self.tenant_conf.clone()),
5709 : self.generation,
5710 : &ShardParameters::default(),
5711 : ))
5712 : .unwrap(),
5713 : // This is a legacy/test code path: sharding isn't supported here.
5714 : ShardIdentity::unsharded(),
5715 : Some(walredo_mgr),
5716 : self.tenant_shard_id,
5717 : self.remote_storage.clone(),
5718 : self.deletion_queue.new_client(),
5719 : // TODO: ideally we should run all unit tests with both configs
5720 : L0FlushGlobalState::new(L0FlushConfig::default()),
5721 : ));
5722 :
5723 : let preload = tenant
5724 : .preload(&self.remote_storage, CancellationToken::new())
5725 : .await?;
5726 : tenant.attach(Some(preload), ctx).await?;
5727 :
5728 : tenant.state.send_replace(TenantState::Active);
5729 : for timeline in tenant.timelines.lock().unwrap().values() {
5730 : timeline.set_state(TimelineState::Active);
5731 : }
5732 : Ok(tenant)
5733 : }
5734 :
5735 4 : pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
5736 4 : self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
5737 4 : }
5738 : }
5739 :
5740 : // Mock WAL redo manager that doesn't do much
5741 : pub(crate) struct TestRedoManager;
5742 :
5743 : impl TestRedoManager {
5744 : /// # Cancel-Safety
5745 : ///
5746 : /// This method is cancellation-safe.
5747 1636 : pub async fn request_redo(
5748 1636 : &self,
5749 1636 : key: Key,
5750 1636 : lsn: Lsn,
5751 1636 : base_img: Option<(Lsn, Bytes)>,
5752 1636 : records: Vec<(Lsn, NeonWalRecord)>,
5753 1636 : _pg_version: u32,
5754 1636 : ) -> Result<Bytes, walredo::Error> {
5755 2392 : let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
5756 1636 : if records_neon {
5757 : // For Neon wal records, we can decode without spawning postgres, so do so.
5758 1636 : let mut page = match (base_img, records.first()) {
5759 1504 : (Some((_lsn, img)), _) => {
5760 1504 : let mut page = BytesMut::new();
5761 1504 : page.extend_from_slice(&img);
5762 1504 : page
5763 : }
5764 132 : (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
5765 : _ => {
5766 0 : panic!("Neon WAL redo requires base image or will init record");
5767 : }
5768 : };
5769 :
5770 4028 : for (record_lsn, record) in records {
5771 2392 : apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
5772 : }
5773 1636 : Ok(page.freeze())
5774 : } else {
5775 : // We never spawn a postgres walredo process in unit tests: just log what we might have done.
5776 0 : let s = format!(
5777 0 : "redo for {} to get to {}, with {} and {} records",
5778 0 : key,
5779 0 : lsn,
5780 0 : if base_img.is_some() {
5781 0 : "base image"
5782 : } else {
5783 0 : "no base image"
5784 : },
5785 0 : records.len()
5786 0 : );
5787 0 : println!("{s}");
5788 0 :
5789 0 : Ok(test_img(&s))
5790 : }
5791 1636 : }
5792 : }
5793 : }
5794 :
5795 : #[cfg(test)]
5796 : mod tests {
5797 : use std::collections::{BTreeMap, BTreeSet};
5798 :
5799 : use super::*;
5800 : use crate::keyspace::KeySpaceAccum;
5801 : use crate::tenant::harness::*;
5802 : use crate::tenant::timeline::CompactFlags;
5803 : use crate::DEFAULT_PG_VERSION;
5804 : use bytes::{Bytes, BytesMut};
5805 : use hex_literal::hex;
5806 : use itertools::Itertools;
5807 : use pageserver_api::key::{Key, AUX_KEY_PREFIX, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX};
5808 : use pageserver_api::keyspace::KeySpace;
5809 : use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
5810 : use pageserver_api::value::Value;
5811 : use pageserver_compaction::helpers::overlaps_with;
5812 : use rand::{thread_rng, Rng};
5813 : use storage_layer::{IoConcurrency, PersistentLayerKey};
5814 : use tests::storage_layer::ValuesReconstructState;
5815 : use tests::timeline::{GetVectoredError, ShutdownMode};
5816 : use timeline::{CompactOptions, DeltaLayerTestDesc};
5817 : use utils::id::TenantId;
5818 :
5819 : #[cfg(feature = "testing")]
5820 : use models::CompactLsnRange;
5821 : #[cfg(feature = "testing")]
5822 : use pageserver_api::record::NeonWalRecord;
5823 : #[cfg(feature = "testing")]
5824 : use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
5825 : #[cfg(feature = "testing")]
5826 : use timeline::GcInfo;
5827 :
5828 : static TEST_KEY: Lazy<Key> =
5829 36 : Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
5830 :
5831 : #[tokio::test]
5832 4 : async fn test_basic() -> anyhow::Result<()> {
5833 4 : let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
5834 4 : let tline = tenant
5835 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
5836 4 : .await?;
5837 4 :
5838 4 : let mut writer = tline.writer().await;
5839 4 : writer
5840 4 : .put(
5841 4 : *TEST_KEY,
5842 4 : Lsn(0x10),
5843 4 : &Value::Image(test_img("foo at 0x10")),
5844 4 : &ctx,
5845 4 : )
5846 4 : .await?;
5847 4 : writer.finish_write(Lsn(0x10));
5848 4 : drop(writer);
5849 4 :
5850 4 : let mut writer = tline.writer().await;
5851 4 : writer
5852 4 : .put(
5853 4 : *TEST_KEY,
5854 4 : Lsn(0x20),
5855 4 : &Value::Image(test_img("foo at 0x20")),
5856 4 : &ctx,
5857 4 : )
5858 4 : .await?;
5859 4 : writer.finish_write(Lsn(0x20));
5860 4 : drop(writer);
5861 4 :
5862 4 : assert_eq!(
5863 4 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
5864 4 : test_img("foo at 0x10")
5865 4 : );
5866 4 : assert_eq!(
5867 4 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
5868 4 : test_img("foo at 0x10")
5869 4 : );
5870 4 : assert_eq!(
5871 4 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
5872 4 : test_img("foo at 0x20")
5873 4 : );
5874 4 :
5875 4 : Ok(())
5876 4 : }
5877 :
5878 : #[tokio::test]
5879 4 : async fn no_duplicate_timelines() -> anyhow::Result<()> {
5880 4 : let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
5881 4 : .await?
5882 4 : .load()
5883 4 : .await;
5884 4 : let _ = tenant
5885 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5886 4 : .await?;
5887 4 :
5888 4 : match tenant
5889 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5890 4 : .await
5891 4 : {
5892 4 : Ok(_) => panic!("duplicate timeline creation should fail"),
5893 4 : Err(e) => assert_eq!(
5894 4 : e.to_string(),
5895 4 : "timeline already exists with different parameters".to_string()
5896 4 : ),
5897 4 : }
5898 4 :
5899 4 : Ok(())
5900 4 : }
5901 :
5902 : /// Convenience function to create a page image with given string as the only content
5903 20 : pub fn test_value(s: &str) -> Value {
5904 20 : let mut buf = BytesMut::new();
5905 20 : buf.extend_from_slice(s.as_bytes());
5906 20 : Value::Image(buf.freeze())
5907 20 : }
5908 :
5909 : ///
5910 : /// Test branch creation
5911 : ///
5912 : #[tokio::test]
5913 4 : async fn test_branch() -> anyhow::Result<()> {
5914 4 : use std::str::from_utf8;
5915 4 :
5916 4 : let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
5917 4 : let tline = tenant
5918 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5919 4 : .await?;
5920 4 : let mut writer = tline.writer().await;
5921 4 :
5922 4 : #[allow(non_snake_case)]
5923 4 : let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
5924 4 : #[allow(non_snake_case)]
5925 4 : let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
5926 4 :
5927 4 : // Insert a value on the timeline
5928 4 : writer
5929 4 : .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
5930 4 : .await?;
5931 4 : writer
5932 4 : .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
5933 4 : .await?;
5934 4 : writer.finish_write(Lsn(0x20));
5935 4 :
5936 4 : writer
5937 4 : .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
5938 4 : .await?;
5939 4 : writer.finish_write(Lsn(0x30));
5940 4 : writer
5941 4 : .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
5942 4 : .await?;
5943 4 : writer.finish_write(Lsn(0x40));
5944 4 :
5945 4 : //assert_current_logical_size(&tline, Lsn(0x40));
5946 4 :
5947 4 : // Branch the history, modify relation differently on the new timeline
5948 4 : tenant
5949 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
5950 4 : .await?;
5951 4 : let newtline = tenant
5952 4 : .get_timeline(NEW_TIMELINE_ID, true)
5953 4 : .expect("Should have a local timeline");
5954 4 : let mut new_writer = newtline.writer().await;
5955 4 : new_writer
5956 4 : .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
5957 4 : .await?;
5958 4 : new_writer.finish_write(Lsn(0x40));
5959 4 :
5960 4 : // Check page contents on both branches
5961 4 : assert_eq!(
5962 4 : from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
5963 4 : "foo at 0x40"
5964 4 : );
5965 4 : assert_eq!(
5966 4 : from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
5967 4 : "bar at 0x40"
5968 4 : );
5969 4 : assert_eq!(
5970 4 : from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
5971 4 : "foobar at 0x20"
5972 4 : );
5973 4 :
5974 4 : //assert_current_logical_size(&tline, Lsn(0x40));
5975 4 :
5976 4 : Ok(())
5977 4 : }
5978 :
5979 40 : async fn make_some_layers(
5980 40 : tline: &Timeline,
5981 40 : start_lsn: Lsn,
5982 40 : ctx: &RequestContext,
5983 40 : ) -> anyhow::Result<()> {
5984 40 : let mut lsn = start_lsn;
5985 : {
5986 40 : let mut writer = tline.writer().await;
5987 : // Create a relation on the timeline
5988 40 : writer
5989 40 : .put(
5990 40 : *TEST_KEY,
5991 40 : lsn,
5992 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
5993 40 : ctx,
5994 40 : )
5995 40 : .await?;
5996 40 : writer.finish_write(lsn);
5997 40 : lsn += 0x10;
5998 40 : writer
5999 40 : .put(
6000 40 : *TEST_KEY,
6001 40 : lsn,
6002 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6003 40 : ctx,
6004 40 : )
6005 40 : .await?;
6006 40 : writer.finish_write(lsn);
6007 40 : lsn += 0x10;
6008 40 : }
6009 40 : tline.freeze_and_flush().await?;
6010 : {
6011 40 : let mut writer = tline.writer().await;
6012 40 : writer
6013 40 : .put(
6014 40 : *TEST_KEY,
6015 40 : lsn,
6016 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6017 40 : ctx,
6018 40 : )
6019 40 : .await?;
6020 40 : writer.finish_write(lsn);
6021 40 : lsn += 0x10;
6022 40 : writer
6023 40 : .put(
6024 40 : *TEST_KEY,
6025 40 : lsn,
6026 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6027 40 : ctx,
6028 40 : )
6029 40 : .await?;
6030 40 : writer.finish_write(lsn);
6031 40 : }
6032 40 : tline.freeze_and_flush().await.map_err(|e| e.into())
6033 40 : }
6034 :
6035 : #[tokio::test(start_paused = true)]
6036 4 : async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
6037 4 : let (tenant, ctx) =
6038 4 : TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
6039 4 : .await?
6040 4 : .load()
6041 4 : .await;
6042 4 : // Advance to the lsn lease deadline so that GC is not blocked by
6043 4 : // initial transition into AttachedSingle.
6044 4 : tokio::time::advance(tenant.get_lsn_lease_length()).await;
6045 4 : tokio::time::resume();
6046 4 : let tline = tenant
6047 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6048 4 : .await?;
6049 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6050 4 :
6051 4 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
6052 4 : // FIXME: this doesn't actually remove any layer currently, given how the flushing
6053 4 : // and compaction works. But it does set the 'cutoff' point so that the cross check
6054 4 : // below should fail.
6055 4 : tenant
6056 4 : .gc_iteration(
6057 4 : Some(TIMELINE_ID),
6058 4 : 0x10,
6059 4 : Duration::ZERO,
6060 4 : &CancellationToken::new(),
6061 4 : &ctx,
6062 4 : )
6063 4 : .await?;
6064 4 :
6065 4 : // try to branch at lsn 25, should fail because we already garbage collected the data
6066 4 : match tenant
6067 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
6068 4 : .await
6069 4 : {
6070 4 : Ok(_) => panic!("branching should have failed"),
6071 4 : Err(err) => {
6072 4 : let CreateTimelineError::AncestorLsn(err) = err else {
6073 4 : panic!("wrong error type")
6074 4 : };
6075 4 : assert!(err.to_string().contains("invalid branch start lsn"));
6076 4 : assert!(err
6077 4 : .source()
6078 4 : .unwrap()
6079 4 : .to_string()
6080 4 : .contains("we might've already garbage collected needed data"))
6081 4 : }
6082 4 : }
6083 4 :
6084 4 : Ok(())
6085 4 : }
6086 :
6087 : #[tokio::test]
6088 4 : async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
6089 4 : let (tenant, ctx) =
6090 4 : TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
6091 4 : .await?
6092 4 : .load()
6093 4 : .await;
6094 4 :
6095 4 : let tline = tenant
6096 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
6097 4 : .await?;
6098 4 : // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
6099 4 : match tenant
6100 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
6101 4 : .await
6102 4 : {
6103 4 : Ok(_) => panic!("branching should have failed"),
6104 4 : Err(err) => {
6105 4 : let CreateTimelineError::AncestorLsn(err) = err else {
6106 4 : panic!("wrong error type");
6107 4 : };
6108 4 : assert!(&err.to_string().contains("invalid branch start lsn"));
6109 4 : assert!(&err
6110 4 : .source()
6111 4 : .unwrap()
6112 4 : .to_string()
6113 4 : .contains("is earlier than latest GC cutoff"));
6114 4 : }
6115 4 : }
6116 4 :
6117 4 : Ok(())
6118 4 : }
6119 :
6120 : /*
6121 : // FIXME: This currently fails to error out. Calling GC doesn't currently
6122 : // remove the old value, we'd need to work a little harder
6123 : #[tokio::test]
6124 : async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
6125 : let repo =
6126 : RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
6127 : .load();
6128 :
6129 : let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
6130 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6131 :
6132 : repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
6133 : let latest_gc_cutoff_lsn = tline.get_latest_gc_cutoff_lsn();
6134 : assert!(*latest_gc_cutoff_lsn > Lsn(0x25));
6135 : match tline.get(*TEST_KEY, Lsn(0x25)) {
6136 : Ok(_) => panic!("request for page should have failed"),
6137 : Err(err) => assert!(err.to_string().contains("not found at")),
6138 : }
6139 : Ok(())
6140 : }
6141 : */
6142 :
6143 : #[tokio::test]
6144 4 : async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
6145 4 : let (tenant, ctx) =
6146 4 : TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
6147 4 : .await?
6148 4 : .load()
6149 4 : .await;
6150 4 : let tline = tenant
6151 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6152 4 : .await?;
6153 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6154 4 :
6155 4 : tenant
6156 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6157 4 : .await?;
6158 4 : let newtline = tenant
6159 4 : .get_timeline(NEW_TIMELINE_ID, true)
6160 4 : .expect("Should have a local timeline");
6161 4 :
6162 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6163 4 :
6164 4 : tline.set_broken("test".to_owned());
6165 4 :
6166 4 : tenant
6167 4 : .gc_iteration(
6168 4 : Some(TIMELINE_ID),
6169 4 : 0x10,
6170 4 : Duration::ZERO,
6171 4 : &CancellationToken::new(),
6172 4 : &ctx,
6173 4 : )
6174 4 : .await?;
6175 4 :
6176 4 : // The branchpoints should contain all timelines, even ones marked
6177 4 : // as Broken.
6178 4 : {
6179 4 : let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
6180 4 : assert_eq!(branchpoints.len(), 1);
6181 4 : assert_eq!(
6182 4 : branchpoints[0],
6183 4 : (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
6184 4 : );
6185 4 : }
6186 4 :
6187 4 : // You can read the key from the child branch even though the parent is
6188 4 : // Broken, as long as you don't need to access data from the parent.
6189 4 : assert_eq!(
6190 4 : newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
6191 4 : test_img(&format!("foo at {}", Lsn(0x70)))
6192 4 : );
6193 4 :
6194 4 : // This needs to traverse to the parent, and fails.
6195 4 : let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
6196 4 : assert!(
6197 4 : err.to_string().starts_with(&format!(
6198 4 : "bad state on timeline {}: Broken",
6199 4 : tline.timeline_id
6200 4 : )),
6201 4 : "{err}"
6202 4 : );
6203 4 :
6204 4 : Ok(())
6205 4 : }
6206 :
6207 : #[tokio::test]
6208 4 : async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
6209 4 : let (tenant, ctx) =
6210 4 : TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
6211 4 : .await?
6212 4 : .load()
6213 4 : .await;
6214 4 : let tline = tenant
6215 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6216 4 : .await?;
6217 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6218 4 :
6219 4 : tenant
6220 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6221 4 : .await?;
6222 4 : let newtline = tenant
6223 4 : .get_timeline(NEW_TIMELINE_ID, true)
6224 4 : .expect("Should have a local timeline");
6225 4 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
6226 4 : tenant
6227 4 : .gc_iteration(
6228 4 : Some(TIMELINE_ID),
6229 4 : 0x10,
6230 4 : Duration::ZERO,
6231 4 : &CancellationToken::new(),
6232 4 : &ctx,
6233 4 : )
6234 4 : .await?;
6235 4 : assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
6236 4 :
6237 4 : Ok(())
6238 4 : }
6239 : #[tokio::test]
6240 4 : async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
6241 4 : let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
6242 4 : .await?
6243 4 : .load()
6244 4 : .await;
6245 4 : let tline = tenant
6246 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6247 4 : .await?;
6248 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6249 4 :
6250 4 : tenant
6251 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6252 4 : .await?;
6253 4 : let newtline = tenant
6254 4 : .get_timeline(NEW_TIMELINE_ID, true)
6255 4 : .expect("Should have a local timeline");
6256 4 :
6257 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6258 4 :
6259 4 : // run gc on parent
6260 4 : tenant
6261 4 : .gc_iteration(
6262 4 : Some(TIMELINE_ID),
6263 4 : 0x10,
6264 4 : Duration::ZERO,
6265 4 : &CancellationToken::new(),
6266 4 : &ctx,
6267 4 : )
6268 4 : .await?;
6269 4 :
6270 4 : // Check that the data is still accessible on the branch.
6271 4 : assert_eq!(
6272 4 : newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
6273 4 : test_img(&format!("foo at {}", Lsn(0x40)))
6274 4 : );
6275 4 :
6276 4 : Ok(())
6277 4 : }
6278 :
6279 : #[tokio::test]
6280 4 : async fn timeline_load() -> anyhow::Result<()> {
6281 4 : const TEST_NAME: &str = "timeline_load";
6282 4 : let harness = TenantHarness::create(TEST_NAME).await?;
6283 4 : {
6284 4 : let (tenant, ctx) = harness.load().await;
6285 4 : let tline = tenant
6286 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
6287 4 : .await?;
6288 4 : make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
6289 4 : // so that all uploads finish & we can call harness.load() below again
6290 4 : tenant
6291 4 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
6292 4 : .instrument(harness.span())
6293 4 : .await
6294 4 : .ok()
6295 4 : .unwrap();
6296 4 : }
6297 4 :
6298 4 : let (tenant, _ctx) = harness.load().await;
6299 4 : tenant
6300 4 : .get_timeline(TIMELINE_ID, true)
6301 4 : .expect("cannot load timeline");
6302 4 :
6303 4 : Ok(())
6304 4 : }
6305 :
6306 : #[tokio::test]
6307 4 : async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
6308 4 : const TEST_NAME: &str = "timeline_load_with_ancestor";
6309 4 : let harness = TenantHarness::create(TEST_NAME).await?;
6310 4 : // create two timelines
6311 4 : {
6312 4 : let (tenant, ctx) = harness.load().await;
6313 4 : let tline = tenant
6314 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6315 4 : .await?;
6316 4 :
6317 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6318 4 :
6319 4 : let child_tline = tenant
6320 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6321 4 : .await?;
6322 4 : child_tline.set_state(TimelineState::Active);
6323 4 :
6324 4 : let newtline = tenant
6325 4 : .get_timeline(NEW_TIMELINE_ID, true)
6326 4 : .expect("Should have a local timeline");
6327 4 :
6328 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6329 4 :
6330 4 : // so that all uploads finish & we can call harness.load() below again
6331 4 : tenant
6332 4 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
6333 4 : .instrument(harness.span())
6334 4 : .await
6335 4 : .ok()
6336 4 : .unwrap();
6337 4 : }
6338 4 :
6339 4 : // check that both of them are initially unloaded
6340 4 : let (tenant, _ctx) = harness.load().await;
6341 4 :
6342 4 : // check that both, child and ancestor are loaded
6343 4 : let _child_tline = tenant
6344 4 : .get_timeline(NEW_TIMELINE_ID, true)
6345 4 : .expect("cannot get child timeline loaded");
6346 4 :
6347 4 : let _ancestor_tline = tenant
6348 4 : .get_timeline(TIMELINE_ID, true)
6349 4 : .expect("cannot get ancestor timeline loaded");
6350 4 :
6351 4 : Ok(())
6352 4 : }
6353 :
6354 : #[tokio::test]
6355 4 : async fn delta_layer_dumping() -> anyhow::Result<()> {
6356 4 : use storage_layer::AsLayerDesc;
6357 4 : let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
6358 4 : .await?
6359 4 : .load()
6360 4 : .await;
6361 4 : let tline = tenant
6362 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6363 4 : .await?;
6364 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6365 4 :
6366 4 : let layer_map = tline.layers.read().await;
6367 4 : let level0_deltas = layer_map
6368 4 : .layer_map()?
6369 4 : .level0_deltas()
6370 4 : .iter()
6371 8 : .map(|desc| layer_map.get_from_desc(desc))
6372 4 : .collect::<Vec<_>>();
6373 4 :
6374 4 : assert!(!level0_deltas.is_empty());
6375 4 :
6376 12 : for delta in level0_deltas {
6377 4 : // Ensure we are dumping a delta layer here
6378 8 : assert!(delta.layer_desc().is_delta);
6379 8 : delta.dump(true, &ctx).await.unwrap();
6380 4 : }
6381 4 :
6382 4 : Ok(())
6383 4 : }
6384 :
6385 : #[tokio::test]
6386 4 : async fn test_images() -> anyhow::Result<()> {
6387 4 : let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
6388 4 : let tline = tenant
6389 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6390 4 : .await?;
6391 4 :
6392 4 : let mut writer = tline.writer().await;
6393 4 : writer
6394 4 : .put(
6395 4 : *TEST_KEY,
6396 4 : Lsn(0x10),
6397 4 : &Value::Image(test_img("foo at 0x10")),
6398 4 : &ctx,
6399 4 : )
6400 4 : .await?;
6401 4 : writer.finish_write(Lsn(0x10));
6402 4 : drop(writer);
6403 4 :
6404 4 : tline.freeze_and_flush().await?;
6405 4 : tline
6406 4 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
6407 4 : .await?;
6408 4 :
6409 4 : let mut writer = tline.writer().await;
6410 4 : writer
6411 4 : .put(
6412 4 : *TEST_KEY,
6413 4 : Lsn(0x20),
6414 4 : &Value::Image(test_img("foo at 0x20")),
6415 4 : &ctx,
6416 4 : )
6417 4 : .await?;
6418 4 : writer.finish_write(Lsn(0x20));
6419 4 : drop(writer);
6420 4 :
6421 4 : tline.freeze_and_flush().await?;
6422 4 : tline
6423 4 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
6424 4 : .await?;
6425 4 :
6426 4 : let mut writer = tline.writer().await;
6427 4 : writer
6428 4 : .put(
6429 4 : *TEST_KEY,
6430 4 : Lsn(0x30),
6431 4 : &Value::Image(test_img("foo at 0x30")),
6432 4 : &ctx,
6433 4 : )
6434 4 : .await?;
6435 4 : writer.finish_write(Lsn(0x30));
6436 4 : drop(writer);
6437 4 :
6438 4 : tline.freeze_and_flush().await?;
6439 4 : tline
6440 4 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
6441 4 : .await?;
6442 4 :
6443 4 : let mut writer = tline.writer().await;
6444 4 : writer
6445 4 : .put(
6446 4 : *TEST_KEY,
6447 4 : Lsn(0x40),
6448 4 : &Value::Image(test_img("foo at 0x40")),
6449 4 : &ctx,
6450 4 : )
6451 4 : .await?;
6452 4 : writer.finish_write(Lsn(0x40));
6453 4 : drop(writer);
6454 4 :
6455 4 : tline.freeze_and_flush().await?;
6456 4 : tline
6457 4 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
6458 4 : .await?;
6459 4 :
6460 4 : assert_eq!(
6461 4 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
6462 4 : test_img("foo at 0x10")
6463 4 : );
6464 4 : assert_eq!(
6465 4 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
6466 4 : test_img("foo at 0x10")
6467 4 : );
6468 4 : assert_eq!(
6469 4 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
6470 4 : test_img("foo at 0x20")
6471 4 : );
6472 4 : assert_eq!(
6473 4 : tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
6474 4 : test_img("foo at 0x30")
6475 4 : );
6476 4 : assert_eq!(
6477 4 : tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
6478 4 : test_img("foo at 0x40")
6479 4 : );
6480 4 :
6481 4 : Ok(())
6482 4 : }
6483 :
6484 8 : async fn bulk_insert_compact_gc(
6485 8 : tenant: &Tenant,
6486 8 : timeline: &Arc<Timeline>,
6487 8 : ctx: &RequestContext,
6488 8 : lsn: Lsn,
6489 8 : repeat: usize,
6490 8 : key_count: usize,
6491 8 : ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
6492 8 : let compact = true;
6493 8 : bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
6494 8 : }
6495 :
6496 16 : async fn bulk_insert_maybe_compact_gc(
6497 16 : tenant: &Tenant,
6498 16 : timeline: &Arc<Timeline>,
6499 16 : ctx: &RequestContext,
6500 16 : mut lsn: Lsn,
6501 16 : repeat: usize,
6502 16 : key_count: usize,
6503 16 : compact: bool,
6504 16 : ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
6505 16 : let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
6506 16 :
6507 16 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6508 16 : let mut blknum = 0;
6509 16 :
6510 16 : // Enforce that key range is monotonously increasing
6511 16 : let mut keyspace = KeySpaceAccum::new();
6512 16 :
6513 16 : let cancel = CancellationToken::new();
6514 16 :
6515 16 : for _ in 0..repeat {
6516 800 : for _ in 0..key_count {
6517 8000000 : test_key.field6 = blknum;
6518 8000000 : let mut writer = timeline.writer().await;
6519 8000000 : writer
6520 8000000 : .put(
6521 8000000 : test_key,
6522 8000000 : lsn,
6523 8000000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
6524 8000000 : ctx,
6525 8000000 : )
6526 8000000 : .await?;
6527 8000000 : inserted.entry(test_key).or_default().insert(lsn);
6528 8000000 : writer.finish_write(lsn);
6529 8000000 : drop(writer);
6530 8000000 :
6531 8000000 : keyspace.add_key(test_key);
6532 8000000 :
6533 8000000 : lsn = Lsn(lsn.0 + 0x10);
6534 8000000 : blknum += 1;
6535 : }
6536 :
6537 800 : timeline.freeze_and_flush().await?;
6538 800 : if compact {
6539 : // this requires timeline to be &Arc<Timeline>
6540 400 : timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
6541 400 : }
6542 :
6543 : // this doesn't really need to use the timeline_id target, but it is closer to what it
6544 : // originally was.
6545 800 : let res = tenant
6546 800 : .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
6547 800 : .await?;
6548 :
6549 800 : assert_eq!(res.layers_removed, 0, "this never removes anything");
6550 : }
6551 :
6552 16 : Ok(inserted)
6553 16 : }
6554 :
6555 : //
6556 : // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
6557 : // Repeat 50 times.
6558 : //
6559 : #[tokio::test]
6560 4 : async fn test_bulk_insert() -> anyhow::Result<()> {
6561 4 : let harness = TenantHarness::create("test_bulk_insert").await?;
6562 4 : let (tenant, ctx) = harness.load().await;
6563 4 : let tline = tenant
6564 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6565 4 : .await?;
6566 4 :
6567 4 : let lsn = Lsn(0x10);
6568 4 : bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
6569 4 :
6570 4 : Ok(())
6571 4 : }
6572 :
6573 : // Test the vectored get real implementation against a simple sequential implementation.
6574 : //
6575 : // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
6576 : // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
6577 : // grow to the right on the X axis.
6578 : // [Delta]
6579 : // [Delta]
6580 : // [Delta]
6581 : // [Delta]
6582 : // ------------ Image ---------------
6583 : //
6584 : // After layer generation we pick the ranges to query as follows:
6585 : // 1. The beginning of each delta layer
6586 : // 2. At the seam between two adjacent delta layers
6587 : //
6588 : // There's one major downside to this test: delta layers only contains images,
6589 : // so the search can stop at the first delta layer and doesn't traverse any deeper.
6590 : #[tokio::test]
6591 4 : async fn test_get_vectored() -> anyhow::Result<()> {
6592 4 : let harness = TenantHarness::create("test_get_vectored").await?;
6593 4 : let (tenant, ctx) = harness.load().await;
6594 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6595 4 : let tline = tenant
6596 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6597 4 : .await?;
6598 4 :
6599 4 : let lsn = Lsn(0x10);
6600 4 : let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
6601 4 :
6602 4 : let guard = tline.layers.read().await;
6603 4 : let lm = guard.layer_map()?;
6604 4 :
6605 4 : lm.dump(true, &ctx).await?;
6606 4 :
6607 4 : let mut reads = Vec::new();
6608 4 : let mut prev = None;
6609 24 : lm.iter_historic_layers().for_each(|desc| {
6610 24 : if !desc.is_delta() {
6611 4 : prev = Some(desc.clone());
6612 4 : return;
6613 20 : }
6614 20 :
6615 20 : let start = desc.key_range.start;
6616 20 : let end = desc
6617 20 : .key_range
6618 20 : .start
6619 20 : .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
6620 20 : reads.push(KeySpace {
6621 20 : ranges: vec![start..end],
6622 20 : });
6623 4 :
6624 20 : if let Some(prev) = &prev {
6625 20 : if !prev.is_delta() {
6626 20 : return;
6627 4 : }
6628 0 :
6629 0 : let first_range = Key {
6630 0 : field6: prev.key_range.end.field6 - 4,
6631 0 : ..prev.key_range.end
6632 0 : }..prev.key_range.end;
6633 0 :
6634 0 : let second_range = desc.key_range.start..Key {
6635 0 : field6: desc.key_range.start.field6 + 4,
6636 0 : ..desc.key_range.start
6637 0 : };
6638 0 :
6639 0 : reads.push(KeySpace {
6640 0 : ranges: vec![first_range, second_range],
6641 0 : });
6642 4 : };
6643 4 :
6644 4 : prev = Some(desc.clone());
6645 24 : });
6646 4 :
6647 4 : drop(guard);
6648 4 :
6649 4 : // Pick a big LSN such that we query over all the changes.
6650 4 : let reads_lsn = Lsn(u64::MAX - 1);
6651 4 :
6652 24 : for read in reads {
6653 20 : info!("Doing vectored read on {:?}", read);
6654 4 :
6655 20 : let vectored_res = tline
6656 20 : .get_vectored_impl(
6657 20 : read.clone(),
6658 20 : reads_lsn,
6659 20 : &mut ValuesReconstructState::new(io_concurrency.clone()),
6660 20 : &ctx,
6661 20 : )
6662 20 : .await;
6663 4 :
6664 20 : let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
6665 20 : let mut expect_missing = false;
6666 20 : let mut key = read.start().unwrap();
6667 660 : while key != read.end().unwrap() {
6668 640 : if let Some(lsns) = inserted.get(&key) {
6669 640 : let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
6670 640 : match expected_lsn {
6671 640 : Some(lsn) => {
6672 640 : expected_lsns.insert(key, *lsn);
6673 640 : }
6674 4 : None => {
6675 4 : expect_missing = true;
6676 0 : break;
6677 4 : }
6678 4 : }
6679 4 : } else {
6680 4 : expect_missing = true;
6681 0 : break;
6682 4 : }
6683 4 :
6684 640 : key = key.next();
6685 4 : }
6686 4 :
6687 20 : if expect_missing {
6688 4 : assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
6689 4 : } else {
6690 640 : for (key, image) in vectored_res? {
6691 640 : let expected_lsn = expected_lsns.get(&key).expect("determined above");
6692 640 : let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
6693 640 : assert_eq!(image?, expected_image);
6694 4 : }
6695 4 : }
6696 4 : }
6697 4 :
6698 4 : Ok(())
6699 4 : }
6700 :
6701 : #[tokio::test]
6702 4 : async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
6703 4 : let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
6704 4 :
6705 4 : let (tenant, ctx) = harness.load().await;
6706 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6707 4 : let tline = tenant
6708 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
6709 4 : .await?;
6710 4 : let tline = tline.raw_timeline().unwrap();
6711 4 :
6712 4 : let mut modification = tline.begin_modification(Lsn(0x1000));
6713 4 : modification.put_file("foo/bar1", b"content1", &ctx).await?;
6714 4 : modification.set_lsn(Lsn(0x1008))?;
6715 4 : modification.put_file("foo/bar2", b"content2", &ctx).await?;
6716 4 : modification.commit(&ctx).await?;
6717 4 :
6718 4 : let child_timeline_id = TimelineId::generate();
6719 4 : tenant
6720 4 : .branch_timeline_test(
6721 4 : tline,
6722 4 : child_timeline_id,
6723 4 : Some(tline.get_last_record_lsn()),
6724 4 : &ctx,
6725 4 : )
6726 4 : .await?;
6727 4 :
6728 4 : let child_timeline = tenant
6729 4 : .get_timeline(child_timeline_id, true)
6730 4 : .expect("Should have the branched timeline");
6731 4 :
6732 4 : let aux_keyspace = KeySpace {
6733 4 : ranges: vec![NON_INHERITED_RANGE],
6734 4 : };
6735 4 : let read_lsn = child_timeline.get_last_record_lsn();
6736 4 :
6737 4 : let vectored_res = child_timeline
6738 4 : .get_vectored_impl(
6739 4 : aux_keyspace.clone(),
6740 4 : read_lsn,
6741 4 : &mut ValuesReconstructState::new(io_concurrency.clone()),
6742 4 : &ctx,
6743 4 : )
6744 4 : .await;
6745 4 :
6746 4 : let images = vectored_res?;
6747 4 : assert!(images.is_empty());
6748 4 : Ok(())
6749 4 : }
6750 :
6751 : // Test that vectored get handles layer gaps correctly
6752 : // by advancing into the next ancestor timeline if required.
6753 : //
6754 : // The test generates timelines that look like the diagram below.
6755 : // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
6756 : // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
6757 : //
6758 : // ```
6759 : //-------------------------------+
6760 : // ... |
6761 : // [ L1 ] |
6762 : // [ / L1 ] | Child Timeline
6763 : // ... |
6764 : // ------------------------------+
6765 : // [ X L1 ] | Parent Timeline
6766 : // ------------------------------+
6767 : // ```
6768 : #[tokio::test]
6769 4 : async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
6770 4 : let tenant_conf = TenantConf {
6771 4 : // Make compaction deterministic
6772 4 : gc_period: Duration::ZERO,
6773 4 : compaction_period: Duration::ZERO,
6774 4 : // Encourage creation of L1 layers
6775 4 : checkpoint_distance: 16 * 1024,
6776 4 : compaction_target_size: 8 * 1024,
6777 4 : ..TenantConf::default()
6778 4 : };
6779 4 :
6780 4 : let harness = TenantHarness::create_custom(
6781 4 : "test_get_vectored_key_gap",
6782 4 : tenant_conf,
6783 4 : TenantId::generate(),
6784 4 : ShardIdentity::unsharded(),
6785 4 : Generation::new(0xdeadbeef),
6786 4 : )
6787 4 : .await?;
6788 4 : let (tenant, ctx) = harness.load().await;
6789 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6790 4 :
6791 4 : let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6792 4 : let gap_at_key = current_key.add(100);
6793 4 : let mut current_lsn = Lsn(0x10);
6794 4 :
6795 4 : const KEY_COUNT: usize = 10_000;
6796 4 :
6797 4 : let timeline_id = TimelineId::generate();
6798 4 : let current_timeline = tenant
6799 4 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
6800 4 : .await?;
6801 4 :
6802 4 : current_lsn += 0x100;
6803 4 :
6804 4 : let mut writer = current_timeline.writer().await;
6805 4 : writer
6806 4 : .put(
6807 4 : gap_at_key,
6808 4 : current_lsn,
6809 4 : &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
6810 4 : &ctx,
6811 4 : )
6812 4 : .await?;
6813 4 : writer.finish_write(current_lsn);
6814 4 : drop(writer);
6815 4 :
6816 4 : let mut latest_lsns = HashMap::new();
6817 4 : latest_lsns.insert(gap_at_key, current_lsn);
6818 4 :
6819 4 : current_timeline.freeze_and_flush().await?;
6820 4 :
6821 4 : let child_timeline_id = TimelineId::generate();
6822 4 :
6823 4 : tenant
6824 4 : .branch_timeline_test(
6825 4 : ¤t_timeline,
6826 4 : child_timeline_id,
6827 4 : Some(current_lsn),
6828 4 : &ctx,
6829 4 : )
6830 4 : .await?;
6831 4 : let child_timeline = tenant
6832 4 : .get_timeline(child_timeline_id, true)
6833 4 : .expect("Should have the branched timeline");
6834 4 :
6835 40004 : for i in 0..KEY_COUNT {
6836 40000 : if current_key == gap_at_key {
6837 4 : current_key = current_key.next();
6838 4 : continue;
6839 39996 : }
6840 39996 :
6841 39996 : current_lsn += 0x10;
6842 4 :
6843 39996 : let mut writer = child_timeline.writer().await;
6844 39996 : writer
6845 39996 : .put(
6846 39996 : current_key,
6847 39996 : current_lsn,
6848 39996 : &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
6849 39996 : &ctx,
6850 39996 : )
6851 39996 : .await?;
6852 39996 : writer.finish_write(current_lsn);
6853 39996 : drop(writer);
6854 39996 :
6855 39996 : latest_lsns.insert(current_key, current_lsn);
6856 39996 : current_key = current_key.next();
6857 39996 :
6858 39996 : // Flush every now and then to encourage layer file creation.
6859 39996 : if i % 500 == 0 {
6860 80 : child_timeline.freeze_and_flush().await?;
6861 39916 : }
6862 4 : }
6863 4 :
6864 4 : child_timeline.freeze_and_flush().await?;
6865 4 : let mut flags = EnumSet::new();
6866 4 : flags.insert(CompactFlags::ForceRepartition);
6867 4 : child_timeline
6868 4 : .compact(&CancellationToken::new(), flags, &ctx)
6869 4 : .await?;
6870 4 :
6871 4 : let key_near_end = {
6872 4 : let mut tmp = current_key;
6873 4 : tmp.field6 -= 10;
6874 4 : tmp
6875 4 : };
6876 4 :
6877 4 : let key_near_gap = {
6878 4 : let mut tmp = gap_at_key;
6879 4 : tmp.field6 -= 10;
6880 4 : tmp
6881 4 : };
6882 4 :
6883 4 : let read = KeySpace {
6884 4 : ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
6885 4 : };
6886 4 : let results = child_timeline
6887 4 : .get_vectored_impl(
6888 4 : read.clone(),
6889 4 : current_lsn,
6890 4 : &mut ValuesReconstructState::new(io_concurrency.clone()),
6891 4 : &ctx,
6892 4 : )
6893 4 : .await?;
6894 4 :
6895 88 : for (key, img_res) in results {
6896 84 : let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
6897 84 : assert_eq!(img_res?, expected);
6898 4 : }
6899 4 :
6900 4 : Ok(())
6901 4 : }
6902 :
6903 : // Test that vectored get descends into ancestor timelines correctly and
6904 : // does not return an image that's newer than requested.
6905 : //
6906 : // The diagram below ilustrates an interesting case. We have a parent timeline
6907 : // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
6908 : // from the child timeline, so the parent timeline must be visited. When advacing into
6909 : // the child timeline, the read path needs to remember what the requested Lsn was in
6910 : // order to avoid returning an image that's too new. The test below constructs such
6911 : // a timeline setup and does a few queries around the Lsn of each page image.
6912 : // ```
6913 : // LSN
6914 : // ^
6915 : // |
6916 : // |
6917 : // 500 | --------------------------------------> branch point
6918 : // 400 | X
6919 : // 300 | X
6920 : // 200 | --------------------------------------> requested lsn
6921 : // 100 | X
6922 : // |---------------------------------------> Key
6923 : // |
6924 : // ------> requested key
6925 : //
6926 : // Legend:
6927 : // * X - page images
6928 : // ```
6929 : #[tokio::test]
6930 4 : async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
6931 4 : let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
6932 4 : let (tenant, ctx) = harness.load().await;
6933 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6934 4 :
6935 4 : let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6936 4 : let end_key = start_key.add(1000);
6937 4 : let child_gap_at_key = start_key.add(500);
6938 4 : let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
6939 4 :
6940 4 : let mut current_lsn = Lsn(0x10);
6941 4 :
6942 4 : let timeline_id = TimelineId::generate();
6943 4 : let parent_timeline = tenant
6944 4 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
6945 4 : .await?;
6946 4 :
6947 4 : current_lsn += 0x100;
6948 4 :
6949 16 : for _ in 0..3 {
6950 12 : let mut key = start_key;
6951 12012 : while key < end_key {
6952 12000 : current_lsn += 0x10;
6953 12000 :
6954 12000 : let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
6955 4 :
6956 12000 : let mut writer = parent_timeline.writer().await;
6957 12000 : writer
6958 12000 : .put(
6959 12000 : key,
6960 12000 : current_lsn,
6961 12000 : &Value::Image(test_img(&image_value)),
6962 12000 : &ctx,
6963 12000 : )
6964 12000 : .await?;
6965 12000 : writer.finish_write(current_lsn);
6966 12000 :
6967 12000 : if key == child_gap_at_key {
6968 12 : parent_gap_lsns.insert(current_lsn, image_value);
6969 11988 : }
6970 4 :
6971 12000 : key = key.next();
6972 4 : }
6973 4 :
6974 12 : parent_timeline.freeze_and_flush().await?;
6975 4 : }
6976 4 :
6977 4 : let child_timeline_id = TimelineId::generate();
6978 4 :
6979 4 : let child_timeline = tenant
6980 4 : .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
6981 4 : .await?;
6982 4 :
6983 4 : let mut key = start_key;
6984 4004 : while key < end_key {
6985 4000 : if key == child_gap_at_key {
6986 4 : key = key.next();
6987 4 : continue;
6988 3996 : }
6989 3996 :
6990 3996 : current_lsn += 0x10;
6991 4 :
6992 3996 : let mut writer = child_timeline.writer().await;
6993 3996 : writer
6994 3996 : .put(
6995 3996 : key,
6996 3996 : current_lsn,
6997 3996 : &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
6998 3996 : &ctx,
6999 3996 : )
7000 3996 : .await?;
7001 3996 : writer.finish_write(current_lsn);
7002 3996 :
7003 3996 : key = key.next();
7004 4 : }
7005 4 :
7006 4 : child_timeline.freeze_and_flush().await?;
7007 4 :
7008 4 : let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
7009 4 : let mut query_lsns = Vec::new();
7010 12 : for image_lsn in parent_gap_lsns.keys().rev() {
7011 72 : for offset in lsn_offsets {
7012 60 : query_lsns.push(Lsn(image_lsn
7013 60 : .0
7014 60 : .checked_add_signed(offset)
7015 60 : .expect("Shouldn't overflow")));
7016 60 : }
7017 4 : }
7018 4 :
7019 64 : for query_lsn in query_lsns {
7020 60 : let results = child_timeline
7021 60 : .get_vectored_impl(
7022 60 : KeySpace {
7023 60 : ranges: vec![child_gap_at_key..child_gap_at_key.next()],
7024 60 : },
7025 60 : query_lsn,
7026 60 : &mut ValuesReconstructState::new(io_concurrency.clone()),
7027 60 : &ctx,
7028 60 : )
7029 60 : .await;
7030 4 :
7031 60 : let expected_item = parent_gap_lsns
7032 60 : .iter()
7033 60 : .rev()
7034 136 : .find(|(lsn, _)| **lsn <= query_lsn);
7035 60 :
7036 60 : info!(
7037 4 : "Doing vectored read at LSN {}. Expecting image to be: {:?}",
7038 4 : query_lsn, expected_item
7039 4 : );
7040 4 :
7041 60 : match expected_item {
7042 52 : Some((_, img_value)) => {
7043 52 : let key_results = results.expect("No vectored get error expected");
7044 52 : let key_result = &key_results[&child_gap_at_key];
7045 52 : let returned_img = key_result
7046 52 : .as_ref()
7047 52 : .expect("No page reconstruct error expected");
7048 52 :
7049 52 : info!(
7050 4 : "Vectored read at LSN {} returned image {}",
7051 0 : query_lsn,
7052 0 : std::str::from_utf8(returned_img)?
7053 4 : );
7054 52 : assert_eq!(*returned_img, test_img(img_value));
7055 4 : }
7056 4 : None => {
7057 8 : assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
7058 4 : }
7059 4 : }
7060 4 : }
7061 4 :
7062 4 : Ok(())
7063 4 : }
7064 :
7065 : #[tokio::test]
7066 4 : async fn test_random_updates() -> anyhow::Result<()> {
7067 4 : let names_algorithms = [
7068 4 : ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
7069 4 : ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
7070 4 : ];
7071 12 : for (name, algorithm) in names_algorithms {
7072 8 : test_random_updates_algorithm(name, algorithm).await?;
7073 4 : }
7074 4 : Ok(())
7075 4 : }
7076 :
7077 8 : async fn test_random_updates_algorithm(
7078 8 : name: &'static str,
7079 8 : compaction_algorithm: CompactionAlgorithm,
7080 8 : ) -> anyhow::Result<()> {
7081 8 : let mut harness = TenantHarness::create(name).await?;
7082 8 : harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
7083 8 : kind: compaction_algorithm,
7084 8 : };
7085 8 : let (tenant, ctx) = harness.load().await;
7086 8 : let tline = tenant
7087 8 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7088 8 : .await?;
7089 :
7090 : const NUM_KEYS: usize = 1000;
7091 8 : let cancel = CancellationToken::new();
7092 8 :
7093 8 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7094 8 : let mut test_key_end = test_key;
7095 8 : test_key_end.field6 = NUM_KEYS as u32;
7096 8 : tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
7097 8 :
7098 8 : let mut keyspace = KeySpaceAccum::new();
7099 8 :
7100 8 : // Track when each page was last modified. Used to assert that
7101 8 : // a read sees the latest page version.
7102 8 : let mut updated = [Lsn(0); NUM_KEYS];
7103 8 :
7104 8 : let mut lsn = Lsn(0x10);
7105 : #[allow(clippy::needless_range_loop)]
7106 8008 : for blknum in 0..NUM_KEYS {
7107 8000 : lsn = Lsn(lsn.0 + 0x10);
7108 8000 : test_key.field6 = blknum as u32;
7109 8000 : let mut writer = tline.writer().await;
7110 8000 : writer
7111 8000 : .put(
7112 8000 : test_key,
7113 8000 : lsn,
7114 8000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7115 8000 : &ctx,
7116 8000 : )
7117 8000 : .await?;
7118 8000 : writer.finish_write(lsn);
7119 8000 : updated[blknum] = lsn;
7120 8000 : drop(writer);
7121 8000 :
7122 8000 : keyspace.add_key(test_key);
7123 : }
7124 :
7125 408 : for _ in 0..50 {
7126 400400 : for _ in 0..NUM_KEYS {
7127 400000 : lsn = Lsn(lsn.0 + 0x10);
7128 400000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7129 400000 : test_key.field6 = blknum as u32;
7130 400000 : let mut writer = tline.writer().await;
7131 400000 : writer
7132 400000 : .put(
7133 400000 : test_key,
7134 400000 : lsn,
7135 400000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7136 400000 : &ctx,
7137 400000 : )
7138 400000 : .await?;
7139 400000 : writer.finish_write(lsn);
7140 400000 : drop(writer);
7141 400000 : updated[blknum] = lsn;
7142 : }
7143 :
7144 : // Read all the blocks
7145 400000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7146 400000 : test_key.field6 = blknum as u32;
7147 400000 : assert_eq!(
7148 400000 : tline.get(test_key, lsn, &ctx).await?,
7149 400000 : test_img(&format!("{} at {}", blknum, last_lsn))
7150 : );
7151 : }
7152 :
7153 : // Perform a cycle of flush, and GC
7154 400 : tline.freeze_and_flush().await?;
7155 400 : tenant
7156 400 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7157 400 : .await?;
7158 : }
7159 :
7160 8 : Ok(())
7161 8 : }
7162 :
7163 : #[tokio::test]
7164 4 : async fn test_traverse_branches() -> anyhow::Result<()> {
7165 4 : let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
7166 4 : .await?
7167 4 : .load()
7168 4 : .await;
7169 4 : let mut tline = tenant
7170 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7171 4 : .await?;
7172 4 :
7173 4 : const NUM_KEYS: usize = 1000;
7174 4 :
7175 4 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7176 4 :
7177 4 : let mut keyspace = KeySpaceAccum::new();
7178 4 :
7179 4 : let cancel = CancellationToken::new();
7180 4 :
7181 4 : // Track when each page was last modified. Used to assert that
7182 4 : // a read sees the latest page version.
7183 4 : let mut updated = [Lsn(0); NUM_KEYS];
7184 4 :
7185 4 : let mut lsn = Lsn(0x10);
7186 4 : #[allow(clippy::needless_range_loop)]
7187 4004 : for blknum in 0..NUM_KEYS {
7188 4000 : lsn = Lsn(lsn.0 + 0x10);
7189 4000 : test_key.field6 = blknum as u32;
7190 4000 : let mut writer = tline.writer().await;
7191 4000 : writer
7192 4000 : .put(
7193 4000 : test_key,
7194 4000 : lsn,
7195 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7196 4000 : &ctx,
7197 4000 : )
7198 4000 : .await?;
7199 4000 : writer.finish_write(lsn);
7200 4000 : updated[blknum] = lsn;
7201 4000 : drop(writer);
7202 4000 :
7203 4000 : keyspace.add_key(test_key);
7204 4 : }
7205 4 :
7206 204 : for _ in 0..50 {
7207 200 : let new_tline_id = TimelineId::generate();
7208 200 : tenant
7209 200 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
7210 200 : .await?;
7211 200 : tline = tenant
7212 200 : .get_timeline(new_tline_id, true)
7213 200 : .expect("Should have the branched timeline");
7214 4 :
7215 200200 : for _ in 0..NUM_KEYS {
7216 200000 : lsn = Lsn(lsn.0 + 0x10);
7217 200000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7218 200000 : test_key.field6 = blknum as u32;
7219 200000 : let mut writer = tline.writer().await;
7220 200000 : writer
7221 200000 : .put(
7222 200000 : test_key,
7223 200000 : lsn,
7224 200000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7225 200000 : &ctx,
7226 200000 : )
7227 200000 : .await?;
7228 200000 : println!("updating {} at {}", blknum, lsn);
7229 200000 : writer.finish_write(lsn);
7230 200000 : drop(writer);
7231 200000 : updated[blknum] = lsn;
7232 4 : }
7233 4 :
7234 4 : // Read all the blocks
7235 200000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7236 200000 : test_key.field6 = blknum as u32;
7237 200000 : assert_eq!(
7238 200000 : tline.get(test_key, lsn, &ctx).await?,
7239 200000 : test_img(&format!("{} at {}", blknum, last_lsn))
7240 4 : );
7241 4 : }
7242 4 :
7243 4 : // Perform a cycle of flush, compact, and GC
7244 200 : tline.freeze_and_flush().await?;
7245 200 : tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
7246 200 : tenant
7247 200 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7248 200 : .await?;
7249 4 : }
7250 4 :
7251 4 : Ok(())
7252 4 : }
7253 :
7254 : #[tokio::test]
7255 4 : async fn test_traverse_ancestors() -> anyhow::Result<()> {
7256 4 : let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
7257 4 : .await?
7258 4 : .load()
7259 4 : .await;
7260 4 : let mut tline = tenant
7261 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7262 4 : .await?;
7263 4 :
7264 4 : const NUM_KEYS: usize = 100;
7265 4 : const NUM_TLINES: usize = 50;
7266 4 :
7267 4 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7268 4 : // Track page mutation lsns across different timelines.
7269 4 : let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
7270 4 :
7271 4 : let mut lsn = Lsn(0x10);
7272 4 :
7273 4 : #[allow(clippy::needless_range_loop)]
7274 204 : for idx in 0..NUM_TLINES {
7275 200 : let new_tline_id = TimelineId::generate();
7276 200 : tenant
7277 200 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
7278 200 : .await?;
7279 200 : tline = tenant
7280 200 : .get_timeline(new_tline_id, true)
7281 200 : .expect("Should have the branched timeline");
7282 4 :
7283 20200 : for _ in 0..NUM_KEYS {
7284 20000 : lsn = Lsn(lsn.0 + 0x10);
7285 20000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7286 20000 : test_key.field6 = blknum as u32;
7287 20000 : let mut writer = tline.writer().await;
7288 20000 : writer
7289 20000 : .put(
7290 20000 : test_key,
7291 20000 : lsn,
7292 20000 : &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
7293 20000 : &ctx,
7294 20000 : )
7295 20000 : .await?;
7296 20000 : println!("updating [{}][{}] at {}", idx, blknum, lsn);
7297 20000 : writer.finish_write(lsn);
7298 20000 : drop(writer);
7299 20000 : updated[idx][blknum] = lsn;
7300 4 : }
7301 4 : }
7302 4 :
7303 4 : // Read pages from leaf timeline across all ancestors.
7304 200 : for (idx, lsns) in updated.iter().enumerate() {
7305 20000 : for (blknum, lsn) in lsns.iter().enumerate() {
7306 4 : // Skip empty mutations.
7307 20000 : if lsn.0 == 0 {
7308 7354 : continue;
7309 12646 : }
7310 12646 : println!("checking [{idx}][{blknum}] at {lsn}");
7311 12646 : test_key.field6 = blknum as u32;
7312 12646 : assert_eq!(
7313 12646 : tline.get(test_key, *lsn, &ctx).await?,
7314 12646 : test_img(&format!("{idx} {blknum} at {lsn}"))
7315 4 : );
7316 4 : }
7317 4 : }
7318 4 : Ok(())
7319 4 : }
7320 :
7321 : #[tokio::test]
7322 4 : async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
7323 4 : let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
7324 4 : .await?
7325 4 : .load()
7326 4 : .await;
7327 4 :
7328 4 : let initdb_lsn = Lsn(0x20);
7329 4 : let utline = tenant
7330 4 : .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
7331 4 : .await?;
7332 4 : let tline = utline.raw_timeline().unwrap();
7333 4 :
7334 4 : // Spawn flush loop now so that we can set the `expect_initdb_optimization`
7335 4 : tline.maybe_spawn_flush_loop();
7336 4 :
7337 4 : // Make sure the timeline has the minimum set of required keys for operation.
7338 4 : // The only operation you can always do on an empty timeline is to `put` new data.
7339 4 : // Except if you `put` at `initdb_lsn`.
7340 4 : // In that case, there's an optimization to directly create image layers instead of delta layers.
7341 4 : // It uses `repartition()`, which assumes some keys to be present.
7342 4 : // Let's make sure the test timeline can handle that case.
7343 4 : {
7344 4 : let mut state = tline.flush_loop_state.lock().unwrap();
7345 4 : assert_eq!(
7346 4 : timeline::FlushLoopState::Running {
7347 4 : expect_initdb_optimization: false,
7348 4 : initdb_optimization_count: 0,
7349 4 : },
7350 4 : *state
7351 4 : );
7352 4 : *state = timeline::FlushLoopState::Running {
7353 4 : expect_initdb_optimization: true,
7354 4 : initdb_optimization_count: 0,
7355 4 : };
7356 4 : }
7357 4 :
7358 4 : // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
7359 4 : // As explained above, the optimization requires some keys to be present.
7360 4 : // As per `create_empty_timeline` documentation, use init_empty to set them.
7361 4 : // This is what `create_test_timeline` does, by the way.
7362 4 : let mut modification = tline.begin_modification(initdb_lsn);
7363 4 : modification
7364 4 : .init_empty_test_timeline()
7365 4 : .context("init_empty_test_timeline")?;
7366 4 : modification
7367 4 : .commit(&ctx)
7368 4 : .await
7369 4 : .context("commit init_empty_test_timeline modification")?;
7370 4 :
7371 4 : // Do the flush. The flush code will check the expectations that we set above.
7372 4 : tline.freeze_and_flush().await?;
7373 4 :
7374 4 : // assert freeze_and_flush exercised the initdb optimization
7375 4 : {
7376 4 : let state = tline.flush_loop_state.lock().unwrap();
7377 4 : let timeline::FlushLoopState::Running {
7378 4 : expect_initdb_optimization,
7379 4 : initdb_optimization_count,
7380 4 : } = *state
7381 4 : else {
7382 4 : panic!("unexpected state: {:?}", *state);
7383 4 : };
7384 4 : assert!(expect_initdb_optimization);
7385 4 : assert!(initdb_optimization_count > 0);
7386 4 : }
7387 4 : Ok(())
7388 4 : }
7389 :
7390 : #[tokio::test]
7391 4 : async fn test_create_guard_crash() -> anyhow::Result<()> {
7392 4 : let name = "test_create_guard_crash";
7393 4 : let harness = TenantHarness::create(name).await?;
7394 4 : {
7395 4 : let (tenant, ctx) = harness.load().await;
7396 4 : let tline = tenant
7397 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
7398 4 : .await?;
7399 4 : // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
7400 4 : let raw_tline = tline.raw_timeline().unwrap();
7401 4 : raw_tline
7402 4 : .shutdown(super::timeline::ShutdownMode::Hard)
7403 4 : .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))
7404 4 : .await;
7405 4 : std::mem::forget(tline);
7406 4 : }
7407 4 :
7408 4 : let (tenant, _) = harness.load().await;
7409 4 : match tenant.get_timeline(TIMELINE_ID, false) {
7410 4 : Ok(_) => panic!("timeline should've been removed during load"),
7411 4 : Err(e) => {
7412 4 : assert_eq!(
7413 4 : e,
7414 4 : GetTimelineError::NotFound {
7415 4 : tenant_id: tenant.tenant_shard_id,
7416 4 : timeline_id: TIMELINE_ID,
7417 4 : }
7418 4 : )
7419 4 : }
7420 4 : }
7421 4 :
7422 4 : assert!(!harness
7423 4 : .conf
7424 4 : .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
7425 4 : .exists());
7426 4 :
7427 4 : Ok(())
7428 4 : }
7429 :
7430 : #[tokio::test]
7431 4 : async fn test_read_at_max_lsn() -> anyhow::Result<()> {
7432 4 : let names_algorithms = [
7433 4 : ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
7434 4 : ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
7435 4 : ];
7436 12 : for (name, algorithm) in names_algorithms {
7437 8 : test_read_at_max_lsn_algorithm(name, algorithm).await?;
7438 4 : }
7439 4 : Ok(())
7440 4 : }
7441 :
7442 8 : async fn test_read_at_max_lsn_algorithm(
7443 8 : name: &'static str,
7444 8 : compaction_algorithm: CompactionAlgorithm,
7445 8 : ) -> anyhow::Result<()> {
7446 8 : let mut harness = TenantHarness::create(name).await?;
7447 8 : harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
7448 8 : kind: compaction_algorithm,
7449 8 : };
7450 8 : let (tenant, ctx) = harness.load().await;
7451 8 : let tline = tenant
7452 8 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
7453 8 : .await?;
7454 :
7455 8 : let lsn = Lsn(0x10);
7456 8 : let compact = false;
7457 8 : bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
7458 :
7459 8 : let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7460 8 : let read_lsn = Lsn(u64::MAX - 1);
7461 :
7462 8 : let result = tline.get(test_key, read_lsn, &ctx).await;
7463 8 : assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
7464 :
7465 8 : Ok(())
7466 8 : }
7467 :
7468 : #[tokio::test]
7469 4 : async fn test_metadata_scan() -> anyhow::Result<()> {
7470 4 : let harness = TenantHarness::create("test_metadata_scan").await?;
7471 4 : let (tenant, ctx) = harness.load().await;
7472 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7473 4 : let tline = tenant
7474 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7475 4 : .await?;
7476 4 :
7477 4 : const NUM_KEYS: usize = 1000;
7478 4 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
7479 4 :
7480 4 : let cancel = CancellationToken::new();
7481 4 :
7482 4 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7483 4 : base_key.field1 = AUX_KEY_PREFIX;
7484 4 : let mut test_key = base_key;
7485 4 :
7486 4 : // Track when each page was last modified. Used to assert that
7487 4 : // a read sees the latest page version.
7488 4 : let mut updated = [Lsn(0); NUM_KEYS];
7489 4 :
7490 4 : let mut lsn = Lsn(0x10);
7491 4 : #[allow(clippy::needless_range_loop)]
7492 4004 : for blknum in 0..NUM_KEYS {
7493 4000 : lsn = Lsn(lsn.0 + 0x10);
7494 4000 : test_key.field6 = (blknum * STEP) as u32;
7495 4000 : let mut writer = tline.writer().await;
7496 4000 : writer
7497 4000 : .put(
7498 4000 : test_key,
7499 4000 : lsn,
7500 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7501 4000 : &ctx,
7502 4000 : )
7503 4000 : .await?;
7504 4000 : writer.finish_write(lsn);
7505 4000 : updated[blknum] = lsn;
7506 4000 : drop(writer);
7507 4 : }
7508 4 :
7509 4 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
7510 4 :
7511 48 : for iter in 0..=10 {
7512 4 : // Read all the blocks
7513 44000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7514 44000 : test_key.field6 = (blknum * STEP) as u32;
7515 44000 : assert_eq!(
7516 44000 : tline.get(test_key, lsn, &ctx).await?,
7517 44000 : test_img(&format!("{} at {}", blknum, last_lsn))
7518 4 : );
7519 4 : }
7520 4 :
7521 44 : let mut cnt = 0;
7522 44000 : for (key, value) in tline
7523 44 : .get_vectored_impl(
7524 44 : keyspace.clone(),
7525 44 : lsn,
7526 44 : &mut ValuesReconstructState::new(io_concurrency.clone()),
7527 44 : &ctx,
7528 44 : )
7529 44 : .await?
7530 4 : {
7531 44000 : let blknum = key.field6 as usize;
7532 44000 : let value = value?;
7533 44000 : assert!(blknum % STEP == 0);
7534 44000 : let blknum = blknum / STEP;
7535 44000 : assert_eq!(
7536 44000 : value,
7537 44000 : test_img(&format!("{} at {}", blknum, updated[blknum]))
7538 44000 : );
7539 44000 : cnt += 1;
7540 4 : }
7541 4 :
7542 44 : assert_eq!(cnt, NUM_KEYS);
7543 4 :
7544 44044 : for _ in 0..NUM_KEYS {
7545 44000 : lsn = Lsn(lsn.0 + 0x10);
7546 44000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7547 44000 : test_key.field6 = (blknum * STEP) as u32;
7548 44000 : let mut writer = tline.writer().await;
7549 44000 : writer
7550 44000 : .put(
7551 44000 : test_key,
7552 44000 : lsn,
7553 44000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7554 44000 : &ctx,
7555 44000 : )
7556 44000 : .await?;
7557 44000 : writer.finish_write(lsn);
7558 44000 : drop(writer);
7559 44000 : updated[blknum] = lsn;
7560 4 : }
7561 4 :
7562 4 : // Perform two cycles of flush, compact, and GC
7563 132 : for round in 0..2 {
7564 88 : tline.freeze_and_flush().await?;
7565 88 : tline
7566 88 : .compact(
7567 88 : &cancel,
7568 88 : if iter % 5 == 0 && round == 0 {
7569 12 : let mut flags = EnumSet::new();
7570 12 : flags.insert(CompactFlags::ForceImageLayerCreation);
7571 12 : flags.insert(CompactFlags::ForceRepartition);
7572 12 : flags
7573 4 : } else {
7574 76 : EnumSet::empty()
7575 4 : },
7576 88 : &ctx,
7577 88 : )
7578 88 : .await?;
7579 88 : tenant
7580 88 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7581 88 : .await?;
7582 4 : }
7583 4 : }
7584 4 :
7585 4 : Ok(())
7586 4 : }
7587 :
7588 : #[tokio::test]
7589 4 : async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
7590 4 : let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
7591 4 : let (tenant, ctx) = harness.load().await;
7592 4 : let tline = tenant
7593 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7594 4 : .await?;
7595 4 :
7596 4 : let cancel = CancellationToken::new();
7597 4 :
7598 4 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7599 4 : base_key.field1 = AUX_KEY_PREFIX;
7600 4 : let test_key = base_key;
7601 4 : let mut lsn = Lsn(0x10);
7602 4 :
7603 84 : for _ in 0..20 {
7604 80 : lsn = Lsn(lsn.0 + 0x10);
7605 80 : let mut writer = tline.writer().await;
7606 80 : writer
7607 80 : .put(
7608 80 : test_key,
7609 80 : lsn,
7610 80 : &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
7611 80 : &ctx,
7612 80 : )
7613 80 : .await?;
7614 80 : writer.finish_write(lsn);
7615 80 : drop(writer);
7616 80 : tline.freeze_and_flush().await?; // force create a delta layer
7617 4 : }
7618 4 :
7619 4 : let before_num_l0_delta_files =
7620 4 : tline.layers.read().await.layer_map()?.level0_deltas().len();
7621 4 :
7622 4 : tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
7623 4 :
7624 4 : let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
7625 4 :
7626 4 : 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}");
7627 4 :
7628 4 : assert_eq!(
7629 4 : tline.get(test_key, lsn, &ctx).await?,
7630 4 : test_img(&format!("{} at {}", 0, lsn))
7631 4 : );
7632 4 :
7633 4 : Ok(())
7634 4 : }
7635 :
7636 : #[tokio::test]
7637 4 : async fn test_aux_file_e2e() {
7638 4 : let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
7639 4 :
7640 4 : let (tenant, ctx) = harness.load().await;
7641 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7642 4 :
7643 4 : let mut lsn = Lsn(0x08);
7644 4 :
7645 4 : let tline: Arc<Timeline> = tenant
7646 4 : .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
7647 4 : .await
7648 4 : .unwrap();
7649 4 :
7650 4 : {
7651 4 : lsn += 8;
7652 4 : let mut modification = tline.begin_modification(lsn);
7653 4 : modification
7654 4 : .put_file("pg_logical/mappings/test1", b"first", &ctx)
7655 4 : .await
7656 4 : .unwrap();
7657 4 : modification.commit(&ctx).await.unwrap();
7658 4 : }
7659 4 :
7660 4 : // we can read everything from the storage
7661 4 : let files = tline
7662 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7663 4 : .await
7664 4 : .unwrap();
7665 4 : assert_eq!(
7666 4 : files.get("pg_logical/mappings/test1"),
7667 4 : Some(&bytes::Bytes::from_static(b"first"))
7668 4 : );
7669 4 :
7670 4 : {
7671 4 : lsn += 8;
7672 4 : let mut modification = tline.begin_modification(lsn);
7673 4 : modification
7674 4 : .put_file("pg_logical/mappings/test2", b"second", &ctx)
7675 4 : .await
7676 4 : .unwrap();
7677 4 : modification.commit(&ctx).await.unwrap();
7678 4 : }
7679 4 :
7680 4 : let files = tline
7681 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7682 4 : .await
7683 4 : .unwrap();
7684 4 : assert_eq!(
7685 4 : files.get("pg_logical/mappings/test2"),
7686 4 : Some(&bytes::Bytes::from_static(b"second"))
7687 4 : );
7688 4 :
7689 4 : let child = tenant
7690 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
7691 4 : .await
7692 4 : .unwrap();
7693 4 :
7694 4 : let files = child
7695 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7696 4 : .await
7697 4 : .unwrap();
7698 4 : assert_eq!(files.get("pg_logical/mappings/test1"), None);
7699 4 : assert_eq!(files.get("pg_logical/mappings/test2"), None);
7700 4 : }
7701 :
7702 : #[tokio::test]
7703 4 : async fn test_metadata_image_creation() -> anyhow::Result<()> {
7704 4 : let harness = TenantHarness::create("test_metadata_image_creation").await?;
7705 4 : let (tenant, ctx) = harness.load().await;
7706 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7707 4 : let tline = tenant
7708 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7709 4 : .await?;
7710 4 :
7711 4 : const NUM_KEYS: usize = 1000;
7712 4 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
7713 4 :
7714 4 : let cancel = CancellationToken::new();
7715 4 :
7716 4 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
7717 4 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
7718 4 : let mut test_key = base_key;
7719 4 : let mut lsn = Lsn(0x10);
7720 4 :
7721 16 : async fn scan_with_statistics(
7722 16 : tline: &Timeline,
7723 16 : keyspace: &KeySpace,
7724 16 : lsn: Lsn,
7725 16 : ctx: &RequestContext,
7726 16 : io_concurrency: IoConcurrency,
7727 16 : ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
7728 16 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
7729 16 : let res = tline
7730 16 : .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
7731 16 : .await?;
7732 16 : Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
7733 16 : }
7734 4 :
7735 4 : #[allow(clippy::needless_range_loop)]
7736 4004 : for blknum in 0..NUM_KEYS {
7737 4000 : lsn = Lsn(lsn.0 + 0x10);
7738 4000 : test_key.field6 = (blknum * STEP) as u32;
7739 4000 : let mut writer = tline.writer().await;
7740 4000 : writer
7741 4000 : .put(
7742 4000 : test_key,
7743 4000 : lsn,
7744 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7745 4000 : &ctx,
7746 4000 : )
7747 4000 : .await?;
7748 4000 : writer.finish_write(lsn);
7749 4000 : drop(writer);
7750 4 : }
7751 4 :
7752 4 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
7753 4 :
7754 44 : for iter in 1..=10 {
7755 40040 : for _ in 0..NUM_KEYS {
7756 40000 : lsn = Lsn(lsn.0 + 0x10);
7757 40000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7758 40000 : test_key.field6 = (blknum * STEP) as u32;
7759 40000 : let mut writer = tline.writer().await;
7760 40000 : writer
7761 40000 : .put(
7762 40000 : test_key,
7763 40000 : lsn,
7764 40000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7765 40000 : &ctx,
7766 40000 : )
7767 40000 : .await?;
7768 40000 : writer.finish_write(lsn);
7769 40000 : drop(writer);
7770 4 : }
7771 4 :
7772 40 : tline.freeze_and_flush().await?;
7773 4 : // Force layers to L1
7774 40 : tline
7775 40 : .compact(
7776 40 : &cancel,
7777 40 : {
7778 40 : let mut flags = EnumSet::new();
7779 40 : flags.insert(CompactFlags::ForceL0Compaction);
7780 40 : flags
7781 40 : },
7782 40 : &ctx,
7783 40 : )
7784 40 : .await?;
7785 4 :
7786 40 : if iter % 5 == 0 {
7787 8 : let (_, before_delta_file_accessed) =
7788 8 : scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
7789 8 : .await?;
7790 8 : tline
7791 8 : .compact(
7792 8 : &cancel,
7793 8 : {
7794 8 : let mut flags = EnumSet::new();
7795 8 : flags.insert(CompactFlags::ForceImageLayerCreation);
7796 8 : flags.insert(CompactFlags::ForceRepartition);
7797 8 : flags.insert(CompactFlags::ForceL0Compaction);
7798 8 : flags
7799 8 : },
7800 8 : &ctx,
7801 8 : )
7802 8 : .await?;
7803 8 : let (_, after_delta_file_accessed) =
7804 8 : scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
7805 8 : .await?;
7806 8 : 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}");
7807 4 : // 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.
7808 8 : assert!(
7809 8 : after_delta_file_accessed <= 2,
7810 4 : "after_delta_file_accessed={after_delta_file_accessed}"
7811 4 : );
7812 32 : }
7813 4 : }
7814 4 :
7815 4 : Ok(())
7816 4 : }
7817 :
7818 : #[tokio::test]
7819 4 : async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
7820 4 : let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
7821 4 : let (tenant, ctx) = harness.load().await;
7822 4 :
7823 4 : let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7824 4 : let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
7825 4 : let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
7826 4 :
7827 4 : let tline = tenant
7828 4 : .create_test_timeline_with_layers(
7829 4 : TIMELINE_ID,
7830 4 : Lsn(0x10),
7831 4 : DEFAULT_PG_VERSION,
7832 4 : &ctx,
7833 4 : Vec::new(), // delta layers
7834 4 : vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
7835 4 : 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
7836 4 : )
7837 4 : .await?;
7838 4 : tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
7839 4 :
7840 4 : let child = tenant
7841 4 : .branch_timeline_test_with_layers(
7842 4 : &tline,
7843 4 : NEW_TIMELINE_ID,
7844 4 : Some(Lsn(0x20)),
7845 4 : &ctx,
7846 4 : Vec::new(), // delta layers
7847 4 : vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
7848 4 : Lsn(0x30),
7849 4 : )
7850 4 : .await
7851 4 : .unwrap();
7852 4 :
7853 4 : let lsn = Lsn(0x30);
7854 4 :
7855 4 : // test vectored get on parent timeline
7856 4 : assert_eq!(
7857 4 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
7858 4 : Some(test_img("data key 1"))
7859 4 : );
7860 4 : assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
7861 4 : .await
7862 4 : .unwrap_err()
7863 4 : .is_missing_key_error());
7864 4 : assert!(
7865 4 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
7866 4 : .await
7867 4 : .unwrap_err()
7868 4 : .is_missing_key_error()
7869 4 : );
7870 4 :
7871 4 : // test vectored get on child timeline
7872 4 : assert_eq!(
7873 4 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
7874 4 : Some(test_img("data key 1"))
7875 4 : );
7876 4 : assert_eq!(
7877 4 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
7878 4 : Some(test_img("data key 2"))
7879 4 : );
7880 4 : assert!(
7881 4 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
7882 4 : .await
7883 4 : .unwrap_err()
7884 4 : .is_missing_key_error()
7885 4 : );
7886 4 :
7887 4 : Ok(())
7888 4 : }
7889 :
7890 : #[tokio::test]
7891 4 : async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
7892 4 : let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
7893 4 : let (tenant, ctx) = harness.load().await;
7894 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7895 4 :
7896 4 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
7897 4 : let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
7898 4 : let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
7899 4 : let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
7900 4 :
7901 4 : let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
7902 4 : let base_inherited_key_child =
7903 4 : Key::from_hex("610000000033333333444444445500000001").unwrap();
7904 4 : let base_inherited_key_nonexist =
7905 4 : Key::from_hex("610000000033333333444444445500000002").unwrap();
7906 4 : let base_inherited_key_overwrite =
7907 4 : Key::from_hex("610000000033333333444444445500000003").unwrap();
7908 4 :
7909 4 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
7910 4 : assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
7911 4 :
7912 4 : let tline = tenant
7913 4 : .create_test_timeline_with_layers(
7914 4 : TIMELINE_ID,
7915 4 : Lsn(0x10),
7916 4 : DEFAULT_PG_VERSION,
7917 4 : &ctx,
7918 4 : Vec::new(), // delta layers
7919 4 : vec![(
7920 4 : Lsn(0x20),
7921 4 : vec![
7922 4 : (base_inherited_key, test_img("metadata inherited key 1")),
7923 4 : (
7924 4 : base_inherited_key_overwrite,
7925 4 : test_img("metadata key overwrite 1a"),
7926 4 : ),
7927 4 : (base_key, test_img("metadata key 1")),
7928 4 : (base_key_overwrite, test_img("metadata key overwrite 1b")),
7929 4 : ],
7930 4 : )], // image layers
7931 4 : 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
7932 4 : )
7933 4 : .await?;
7934 4 :
7935 4 : let child = tenant
7936 4 : .branch_timeline_test_with_layers(
7937 4 : &tline,
7938 4 : NEW_TIMELINE_ID,
7939 4 : Some(Lsn(0x20)),
7940 4 : &ctx,
7941 4 : Vec::new(), // delta layers
7942 4 : vec![(
7943 4 : Lsn(0x30),
7944 4 : vec![
7945 4 : (
7946 4 : base_inherited_key_child,
7947 4 : test_img("metadata inherited key 2"),
7948 4 : ),
7949 4 : (
7950 4 : base_inherited_key_overwrite,
7951 4 : test_img("metadata key overwrite 2a"),
7952 4 : ),
7953 4 : (base_key_child, test_img("metadata key 2")),
7954 4 : (base_key_overwrite, test_img("metadata key overwrite 2b")),
7955 4 : ],
7956 4 : )], // image layers
7957 4 : Lsn(0x30),
7958 4 : )
7959 4 : .await
7960 4 : .unwrap();
7961 4 :
7962 4 : let lsn = Lsn(0x30);
7963 4 :
7964 4 : // test vectored get on parent timeline
7965 4 : assert_eq!(
7966 4 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
7967 4 : Some(test_img("metadata key 1"))
7968 4 : );
7969 4 : assert_eq!(
7970 4 : get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
7971 4 : None
7972 4 : );
7973 4 : assert_eq!(
7974 4 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
7975 4 : None
7976 4 : );
7977 4 : assert_eq!(
7978 4 : get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
7979 4 : Some(test_img("metadata key overwrite 1b"))
7980 4 : );
7981 4 : assert_eq!(
7982 4 : get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
7983 4 : Some(test_img("metadata inherited key 1"))
7984 4 : );
7985 4 : assert_eq!(
7986 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
7987 4 : None
7988 4 : );
7989 4 : assert_eq!(
7990 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
7991 4 : None
7992 4 : );
7993 4 : assert_eq!(
7994 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
7995 4 : Some(test_img("metadata key overwrite 1a"))
7996 4 : );
7997 4 :
7998 4 : // test vectored get on child timeline
7999 4 : assert_eq!(
8000 4 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
8001 4 : None
8002 4 : );
8003 4 : assert_eq!(
8004 4 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
8005 4 : Some(test_img("metadata key 2"))
8006 4 : );
8007 4 : assert_eq!(
8008 4 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
8009 4 : None
8010 4 : );
8011 4 : assert_eq!(
8012 4 : get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
8013 4 : Some(test_img("metadata inherited key 1"))
8014 4 : );
8015 4 : assert_eq!(
8016 4 : get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
8017 4 : Some(test_img("metadata inherited key 2"))
8018 4 : );
8019 4 : assert_eq!(
8020 4 : get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
8021 4 : None
8022 4 : );
8023 4 : assert_eq!(
8024 4 : get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
8025 4 : Some(test_img("metadata key overwrite 2b"))
8026 4 : );
8027 4 : assert_eq!(
8028 4 : get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
8029 4 : Some(test_img("metadata key overwrite 2a"))
8030 4 : );
8031 4 :
8032 4 : // test vectored scan on parent timeline
8033 4 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
8034 4 : let res = tline
8035 4 : .get_vectored_impl(
8036 4 : KeySpace::single(Key::metadata_key_range()),
8037 4 : lsn,
8038 4 : &mut reconstruct_state,
8039 4 : &ctx,
8040 4 : )
8041 4 : .await?;
8042 4 :
8043 4 : assert_eq!(
8044 4 : res.into_iter()
8045 16 : .map(|(k, v)| (k, v.unwrap()))
8046 4 : .collect::<Vec<_>>(),
8047 4 : vec![
8048 4 : (base_inherited_key, test_img("metadata inherited key 1")),
8049 4 : (
8050 4 : base_inherited_key_overwrite,
8051 4 : test_img("metadata key overwrite 1a")
8052 4 : ),
8053 4 : (base_key, test_img("metadata key 1")),
8054 4 : (base_key_overwrite, test_img("metadata key overwrite 1b")),
8055 4 : ]
8056 4 : );
8057 4 :
8058 4 : // test vectored scan on child timeline
8059 4 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
8060 4 : let res = child
8061 4 : .get_vectored_impl(
8062 4 : KeySpace::single(Key::metadata_key_range()),
8063 4 : lsn,
8064 4 : &mut reconstruct_state,
8065 4 : &ctx,
8066 4 : )
8067 4 : .await?;
8068 4 :
8069 4 : assert_eq!(
8070 4 : res.into_iter()
8071 20 : .map(|(k, v)| (k, v.unwrap()))
8072 4 : .collect::<Vec<_>>(),
8073 4 : vec![
8074 4 : (base_inherited_key, test_img("metadata inherited key 1")),
8075 4 : (
8076 4 : base_inherited_key_child,
8077 4 : test_img("metadata inherited key 2")
8078 4 : ),
8079 4 : (
8080 4 : base_inherited_key_overwrite,
8081 4 : test_img("metadata key overwrite 2a")
8082 4 : ),
8083 4 : (base_key_child, test_img("metadata key 2")),
8084 4 : (base_key_overwrite, test_img("metadata key overwrite 2b")),
8085 4 : ]
8086 4 : );
8087 4 :
8088 4 : Ok(())
8089 4 : }
8090 :
8091 112 : async fn get_vectored_impl_wrapper(
8092 112 : tline: &Arc<Timeline>,
8093 112 : key: Key,
8094 112 : lsn: Lsn,
8095 112 : ctx: &RequestContext,
8096 112 : ) -> Result<Option<Bytes>, GetVectoredError> {
8097 112 : let io_concurrency =
8098 112 : IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
8099 112 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
8100 112 : let mut res = tline
8101 112 : .get_vectored_impl(
8102 112 : KeySpace::single(key..key.next()),
8103 112 : lsn,
8104 112 : &mut reconstruct_state,
8105 112 : ctx,
8106 112 : )
8107 112 : .await?;
8108 100 : Ok(res.pop_last().map(|(k, v)| {
8109 64 : assert_eq!(k, key);
8110 64 : v.unwrap()
8111 100 : }))
8112 112 : }
8113 :
8114 : #[tokio::test]
8115 4 : async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
8116 4 : let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
8117 4 : let (tenant, ctx) = harness.load().await;
8118 4 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
8119 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8120 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8121 4 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
8122 4 :
8123 4 : // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
8124 4 : // Lsn 0x30 key0, key3, no key1+key2
8125 4 : // Lsn 0x20 key1+key2 tomestones
8126 4 : // Lsn 0x10 key1 in image, key2 in delta
8127 4 : let tline = tenant
8128 4 : .create_test_timeline_with_layers(
8129 4 : TIMELINE_ID,
8130 4 : Lsn(0x10),
8131 4 : DEFAULT_PG_VERSION,
8132 4 : &ctx,
8133 4 : // delta layers
8134 4 : vec![
8135 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8136 4 : Lsn(0x10)..Lsn(0x20),
8137 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8138 4 : ),
8139 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8140 4 : Lsn(0x20)..Lsn(0x30),
8141 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8142 4 : ),
8143 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8144 4 : Lsn(0x20)..Lsn(0x30),
8145 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8146 4 : ),
8147 4 : ],
8148 4 : // image layers
8149 4 : vec![
8150 4 : (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
8151 4 : (
8152 4 : Lsn(0x30),
8153 4 : vec![
8154 4 : (key0, test_img("metadata key 0")),
8155 4 : (key3, test_img("metadata key 3")),
8156 4 : ],
8157 4 : ),
8158 4 : ],
8159 4 : Lsn(0x30),
8160 4 : )
8161 4 : .await?;
8162 4 :
8163 4 : let lsn = Lsn(0x30);
8164 4 : let old_lsn = Lsn(0x20);
8165 4 :
8166 4 : assert_eq!(
8167 4 : get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
8168 4 : Some(test_img("metadata key 0"))
8169 4 : );
8170 4 : assert_eq!(
8171 4 : get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
8172 4 : None,
8173 4 : );
8174 4 : assert_eq!(
8175 4 : get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
8176 4 : None,
8177 4 : );
8178 4 : assert_eq!(
8179 4 : get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
8180 4 : Some(Bytes::new()),
8181 4 : );
8182 4 : assert_eq!(
8183 4 : get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
8184 4 : Some(Bytes::new()),
8185 4 : );
8186 4 : assert_eq!(
8187 4 : get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
8188 4 : Some(test_img("metadata key 3"))
8189 4 : );
8190 4 :
8191 4 : Ok(())
8192 4 : }
8193 :
8194 : #[tokio::test]
8195 4 : async fn test_metadata_tombstone_image_creation() {
8196 4 : let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
8197 4 : .await
8198 4 : .unwrap();
8199 4 : let (tenant, ctx) = harness.load().await;
8200 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8201 4 :
8202 4 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
8203 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8204 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8205 4 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
8206 4 :
8207 4 : let tline = tenant
8208 4 : .create_test_timeline_with_layers(
8209 4 : TIMELINE_ID,
8210 4 : Lsn(0x10),
8211 4 : DEFAULT_PG_VERSION,
8212 4 : &ctx,
8213 4 : // delta layers
8214 4 : vec![
8215 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8216 4 : Lsn(0x10)..Lsn(0x20),
8217 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8218 4 : ),
8219 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8220 4 : Lsn(0x20)..Lsn(0x30),
8221 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8222 4 : ),
8223 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8224 4 : Lsn(0x20)..Lsn(0x30),
8225 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8226 4 : ),
8227 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8228 4 : Lsn(0x30)..Lsn(0x40),
8229 4 : vec![
8230 4 : (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
8231 4 : (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
8232 4 : ],
8233 4 : ),
8234 4 : ],
8235 4 : // image layers
8236 4 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
8237 4 : Lsn(0x40),
8238 4 : )
8239 4 : .await
8240 4 : .unwrap();
8241 4 :
8242 4 : let cancel = CancellationToken::new();
8243 4 :
8244 4 : // Image layer creation happens on the disk_consistent_lsn so we need to force set it now.
8245 4 : tline.force_set_disk_consistent_lsn(Lsn(0x40));
8246 4 : tline
8247 4 : .compact(
8248 4 : &cancel,
8249 4 : {
8250 4 : let mut flags = EnumSet::new();
8251 4 : flags.insert(CompactFlags::ForceImageLayerCreation);
8252 4 : flags.insert(CompactFlags::ForceRepartition);
8253 4 : flags
8254 4 : },
8255 4 : &ctx,
8256 4 : )
8257 4 : .await
8258 4 : .unwrap();
8259 4 : // Image layers are created at repartition LSN
8260 4 : let images = tline
8261 4 : .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
8262 4 : .await
8263 4 : .unwrap()
8264 4 : .into_iter()
8265 36 : .filter(|(k, _)| k.is_metadata_key())
8266 4 : .collect::<Vec<_>>();
8267 4 : assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
8268 4 : }
8269 :
8270 : #[tokio::test]
8271 4 : async fn test_metadata_tombstone_empty_image_creation() {
8272 4 : let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
8273 4 : .await
8274 4 : .unwrap();
8275 4 : let (tenant, ctx) = harness.load().await;
8276 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8277 4 :
8278 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8279 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8280 4 :
8281 4 : let tline = tenant
8282 4 : .create_test_timeline_with_layers(
8283 4 : TIMELINE_ID,
8284 4 : Lsn(0x10),
8285 4 : DEFAULT_PG_VERSION,
8286 4 : &ctx,
8287 4 : // delta layers
8288 4 : vec![
8289 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8290 4 : Lsn(0x10)..Lsn(0x20),
8291 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8292 4 : ),
8293 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8294 4 : Lsn(0x20)..Lsn(0x30),
8295 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8296 4 : ),
8297 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8298 4 : Lsn(0x20)..Lsn(0x30),
8299 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8300 4 : ),
8301 4 : ],
8302 4 : // image layers
8303 4 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
8304 4 : Lsn(0x30),
8305 4 : )
8306 4 : .await
8307 4 : .unwrap();
8308 4 :
8309 4 : let cancel = CancellationToken::new();
8310 4 :
8311 4 : tline
8312 4 : .compact(
8313 4 : &cancel,
8314 4 : {
8315 4 : let mut flags = EnumSet::new();
8316 4 : flags.insert(CompactFlags::ForceImageLayerCreation);
8317 4 : flags.insert(CompactFlags::ForceRepartition);
8318 4 : flags
8319 4 : },
8320 4 : &ctx,
8321 4 : )
8322 4 : .await
8323 4 : .unwrap();
8324 4 :
8325 4 : // Image layers are created at last_record_lsn
8326 4 : let images = tline
8327 4 : .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
8328 4 : .await
8329 4 : .unwrap()
8330 4 : .into_iter()
8331 4 : .filter(|(k, _)| k.is_metadata_key())
8332 4 : .collect::<Vec<_>>();
8333 4 : assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
8334 4 : }
8335 :
8336 : #[tokio::test]
8337 4 : async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
8338 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
8339 4 : let (tenant, ctx) = harness.load().await;
8340 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8341 4 :
8342 204 : fn get_key(id: u32) -> Key {
8343 204 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8344 204 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8345 204 : key.field6 = id;
8346 204 : key
8347 204 : }
8348 4 :
8349 4 : // We create
8350 4 : // - one bottom-most image layer,
8351 4 : // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
8352 4 : // - a delta layer D2 crossing the GC horizon with data only below the horizon,
8353 4 : // - a delta layer D3 above the horizon.
8354 4 : //
8355 4 : // | D3 |
8356 4 : // | D1 |
8357 4 : // -| |-- gc horizon -----------------
8358 4 : // | | | D2 |
8359 4 : // --------- img layer ------------------
8360 4 : //
8361 4 : // What we should expact from this compaction is:
8362 4 : // | D3 |
8363 4 : // | Part of D1 |
8364 4 : // --------- img layer with D1+D2 at GC horizon------------------
8365 4 :
8366 4 : // img layer at 0x10
8367 4 : let img_layer = (0..10)
8368 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
8369 4 : .collect_vec();
8370 4 :
8371 4 : let delta1 = vec![
8372 4 : (
8373 4 : get_key(1),
8374 4 : Lsn(0x20),
8375 4 : Value::Image(Bytes::from("value 1@0x20")),
8376 4 : ),
8377 4 : (
8378 4 : get_key(2),
8379 4 : Lsn(0x30),
8380 4 : Value::Image(Bytes::from("value 2@0x30")),
8381 4 : ),
8382 4 : (
8383 4 : get_key(3),
8384 4 : Lsn(0x40),
8385 4 : Value::Image(Bytes::from("value 3@0x40")),
8386 4 : ),
8387 4 : ];
8388 4 : let delta2 = vec![
8389 4 : (
8390 4 : get_key(5),
8391 4 : Lsn(0x20),
8392 4 : Value::Image(Bytes::from("value 5@0x20")),
8393 4 : ),
8394 4 : (
8395 4 : get_key(6),
8396 4 : Lsn(0x20),
8397 4 : Value::Image(Bytes::from("value 6@0x20")),
8398 4 : ),
8399 4 : ];
8400 4 : let delta3 = vec![
8401 4 : (
8402 4 : get_key(8),
8403 4 : Lsn(0x48),
8404 4 : Value::Image(Bytes::from("value 8@0x48")),
8405 4 : ),
8406 4 : (
8407 4 : get_key(9),
8408 4 : Lsn(0x48),
8409 4 : Value::Image(Bytes::from("value 9@0x48")),
8410 4 : ),
8411 4 : ];
8412 4 :
8413 4 : let tline = tenant
8414 4 : .create_test_timeline_with_layers(
8415 4 : TIMELINE_ID,
8416 4 : Lsn(0x10),
8417 4 : DEFAULT_PG_VERSION,
8418 4 : &ctx,
8419 4 : vec![
8420 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
8421 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
8422 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
8423 4 : ], // delta layers
8424 4 : vec![(Lsn(0x10), img_layer)], // image layers
8425 4 : Lsn(0x50),
8426 4 : )
8427 4 : .await?;
8428 4 : {
8429 4 : tline
8430 4 : .latest_gc_cutoff_lsn
8431 4 : .lock_for_write()
8432 4 : .store_and_unlock(Lsn(0x30))
8433 4 : .wait()
8434 4 : .await;
8435 4 : // Update GC info
8436 4 : let mut guard = tline.gc_info.write().unwrap();
8437 4 : guard.cutoffs.time = Lsn(0x30);
8438 4 : guard.cutoffs.space = Lsn(0x30);
8439 4 : }
8440 4 :
8441 4 : let expected_result = [
8442 4 : Bytes::from_static(b"value 0@0x10"),
8443 4 : Bytes::from_static(b"value 1@0x20"),
8444 4 : Bytes::from_static(b"value 2@0x30"),
8445 4 : Bytes::from_static(b"value 3@0x40"),
8446 4 : Bytes::from_static(b"value 4@0x10"),
8447 4 : Bytes::from_static(b"value 5@0x20"),
8448 4 : Bytes::from_static(b"value 6@0x20"),
8449 4 : Bytes::from_static(b"value 7@0x10"),
8450 4 : Bytes::from_static(b"value 8@0x48"),
8451 4 : Bytes::from_static(b"value 9@0x48"),
8452 4 : ];
8453 4 :
8454 40 : for (idx, expected) in expected_result.iter().enumerate() {
8455 40 : assert_eq!(
8456 40 : tline
8457 40 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8458 40 : .await
8459 40 : .unwrap(),
8460 4 : expected
8461 4 : );
8462 4 : }
8463 4 :
8464 4 : let cancel = CancellationToken::new();
8465 4 : tline
8466 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8467 4 : .await
8468 4 : .unwrap();
8469 4 :
8470 40 : for (idx, expected) in expected_result.iter().enumerate() {
8471 40 : assert_eq!(
8472 40 : tline
8473 40 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8474 40 : .await
8475 40 : .unwrap(),
8476 4 : expected
8477 4 : );
8478 4 : }
8479 4 :
8480 4 : // Check if the image layer at the GC horizon contains exactly what we want
8481 4 : let image_at_gc_horizon = tline
8482 4 : .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
8483 4 : .await
8484 4 : .unwrap()
8485 4 : .into_iter()
8486 68 : .filter(|(k, _)| k.is_metadata_key())
8487 4 : .collect::<Vec<_>>();
8488 4 :
8489 4 : assert_eq!(image_at_gc_horizon.len(), 10);
8490 4 : let expected_result = [
8491 4 : Bytes::from_static(b"value 0@0x10"),
8492 4 : Bytes::from_static(b"value 1@0x20"),
8493 4 : Bytes::from_static(b"value 2@0x30"),
8494 4 : Bytes::from_static(b"value 3@0x10"),
8495 4 : Bytes::from_static(b"value 4@0x10"),
8496 4 : Bytes::from_static(b"value 5@0x20"),
8497 4 : Bytes::from_static(b"value 6@0x20"),
8498 4 : Bytes::from_static(b"value 7@0x10"),
8499 4 : Bytes::from_static(b"value 8@0x10"),
8500 4 : Bytes::from_static(b"value 9@0x10"),
8501 4 : ];
8502 44 : for idx in 0..10 {
8503 40 : assert_eq!(
8504 40 : image_at_gc_horizon[idx],
8505 40 : (get_key(idx as u32), expected_result[idx].clone())
8506 40 : );
8507 4 : }
8508 4 :
8509 4 : // Check if old layers are removed / new layers have the expected LSN
8510 4 : let all_layers = inspect_and_sort(&tline, None).await;
8511 4 : assert_eq!(
8512 4 : all_layers,
8513 4 : vec![
8514 4 : // Image layer at GC horizon
8515 4 : PersistentLayerKey {
8516 4 : key_range: Key::MIN..Key::MAX,
8517 4 : lsn_range: Lsn(0x30)..Lsn(0x31),
8518 4 : is_delta: false
8519 4 : },
8520 4 : // The delta layer below the horizon
8521 4 : PersistentLayerKey {
8522 4 : key_range: get_key(3)..get_key(4),
8523 4 : lsn_range: Lsn(0x30)..Lsn(0x48),
8524 4 : is_delta: true
8525 4 : },
8526 4 : // The delta3 layer that should not be picked for the compaction
8527 4 : PersistentLayerKey {
8528 4 : key_range: get_key(8)..get_key(10),
8529 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
8530 4 : is_delta: true
8531 4 : }
8532 4 : ]
8533 4 : );
8534 4 :
8535 4 : // increase GC horizon and compact again
8536 4 : {
8537 4 : tline
8538 4 : .latest_gc_cutoff_lsn
8539 4 : .lock_for_write()
8540 4 : .store_and_unlock(Lsn(0x40))
8541 4 : .wait()
8542 4 : .await;
8543 4 : // Update GC info
8544 4 : let mut guard = tline.gc_info.write().unwrap();
8545 4 : guard.cutoffs.time = Lsn(0x40);
8546 4 : guard.cutoffs.space = Lsn(0x40);
8547 4 : }
8548 4 : tline
8549 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8550 4 : .await
8551 4 : .unwrap();
8552 4 :
8553 4 : Ok(())
8554 4 : }
8555 :
8556 : #[cfg(feature = "testing")]
8557 : #[tokio::test]
8558 4 : async fn test_neon_test_record() -> anyhow::Result<()> {
8559 4 : let harness = TenantHarness::create("test_neon_test_record").await?;
8560 4 : let (tenant, ctx) = harness.load().await;
8561 4 :
8562 48 : fn get_key(id: u32) -> Key {
8563 48 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8564 48 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8565 48 : key.field6 = id;
8566 48 : key
8567 48 : }
8568 4 :
8569 4 : let delta1 = vec![
8570 4 : (
8571 4 : get_key(1),
8572 4 : Lsn(0x20),
8573 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
8574 4 : ),
8575 4 : (
8576 4 : get_key(1),
8577 4 : Lsn(0x30),
8578 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
8579 4 : ),
8580 4 : (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
8581 4 : (
8582 4 : get_key(2),
8583 4 : Lsn(0x20),
8584 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
8585 4 : ),
8586 4 : (
8587 4 : get_key(2),
8588 4 : Lsn(0x30),
8589 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
8590 4 : ),
8591 4 : (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
8592 4 : (
8593 4 : get_key(3),
8594 4 : Lsn(0x20),
8595 4 : Value::WalRecord(NeonWalRecord::wal_clear("c")),
8596 4 : ),
8597 4 : (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
8598 4 : (
8599 4 : get_key(4),
8600 4 : Lsn(0x20),
8601 4 : Value::WalRecord(NeonWalRecord::wal_init("i")),
8602 4 : ),
8603 4 : ];
8604 4 : let image1 = vec![(get_key(1), "0x10".into())];
8605 4 :
8606 4 : let tline = tenant
8607 4 : .create_test_timeline_with_layers(
8608 4 : TIMELINE_ID,
8609 4 : Lsn(0x10),
8610 4 : DEFAULT_PG_VERSION,
8611 4 : &ctx,
8612 4 : vec![DeltaLayerTestDesc::new_with_inferred_key_range(
8613 4 : Lsn(0x10)..Lsn(0x40),
8614 4 : delta1,
8615 4 : )], // delta layers
8616 4 : vec![(Lsn(0x10), image1)], // image layers
8617 4 : Lsn(0x50),
8618 4 : )
8619 4 : .await?;
8620 4 :
8621 4 : assert_eq!(
8622 4 : tline.get(get_key(1), Lsn(0x50), &ctx).await?,
8623 4 : Bytes::from_static(b"0x10,0x20,0x30")
8624 4 : );
8625 4 : assert_eq!(
8626 4 : tline.get(get_key(2), Lsn(0x50), &ctx).await?,
8627 4 : Bytes::from_static(b"0x10,0x20,0x30")
8628 4 : );
8629 4 :
8630 4 : // Need to remove the limit of "Neon WAL redo requires base image".
8631 4 :
8632 4 : // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
8633 4 : // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
8634 4 :
8635 4 : Ok(())
8636 4 : }
8637 :
8638 : #[tokio::test(start_paused = true)]
8639 4 : async fn test_lsn_lease() -> anyhow::Result<()> {
8640 4 : let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
8641 4 : .await
8642 4 : .unwrap()
8643 4 : .load()
8644 4 : .await;
8645 4 : // Advance to the lsn lease deadline so that GC is not blocked by
8646 4 : // initial transition into AttachedSingle.
8647 4 : tokio::time::advance(tenant.get_lsn_lease_length()).await;
8648 4 : tokio::time::resume();
8649 4 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
8650 4 :
8651 4 : let end_lsn = Lsn(0x100);
8652 4 : let image_layers = (0x20..=0x90)
8653 4 : .step_by(0x10)
8654 32 : .map(|n| {
8655 32 : (
8656 32 : Lsn(n),
8657 32 : vec![(key, test_img(&format!("data key at {:x}", n)))],
8658 32 : )
8659 32 : })
8660 4 : .collect();
8661 4 :
8662 4 : let timeline = tenant
8663 4 : .create_test_timeline_with_layers(
8664 4 : TIMELINE_ID,
8665 4 : Lsn(0x10),
8666 4 : DEFAULT_PG_VERSION,
8667 4 : &ctx,
8668 4 : Vec::new(),
8669 4 : image_layers,
8670 4 : end_lsn,
8671 4 : )
8672 4 : .await?;
8673 4 :
8674 4 : let leased_lsns = [0x30, 0x50, 0x70];
8675 4 : let mut leases = Vec::new();
8676 12 : leased_lsns.iter().for_each(|n| {
8677 12 : leases.push(
8678 12 : timeline
8679 12 : .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
8680 12 : .expect("lease request should succeed"),
8681 12 : );
8682 12 : });
8683 4 :
8684 4 : let updated_lease_0 = timeline
8685 4 : .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
8686 4 : .expect("lease renewal should succeed");
8687 4 : assert_eq!(
8688 4 : updated_lease_0.valid_until, leases[0].valid_until,
8689 4 : " Renewing with shorter lease should not change the lease."
8690 4 : );
8691 4 :
8692 4 : let updated_lease_1 = timeline
8693 4 : .renew_lsn_lease(
8694 4 : Lsn(leased_lsns[1]),
8695 4 : timeline.get_lsn_lease_length() * 2,
8696 4 : &ctx,
8697 4 : )
8698 4 : .expect("lease renewal should succeed");
8699 4 : assert!(
8700 4 : updated_lease_1.valid_until > leases[1].valid_until,
8701 4 : "Renewing with a long lease should renew lease with later expiration time."
8702 4 : );
8703 4 :
8704 4 : // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
8705 4 : info!(
8706 4 : "latest_gc_cutoff_lsn: {}",
8707 0 : *timeline.get_latest_gc_cutoff_lsn()
8708 4 : );
8709 4 : timeline.force_set_disk_consistent_lsn(end_lsn);
8710 4 :
8711 4 : let res = tenant
8712 4 : .gc_iteration(
8713 4 : Some(TIMELINE_ID),
8714 4 : 0,
8715 4 : Duration::ZERO,
8716 4 : &CancellationToken::new(),
8717 4 : &ctx,
8718 4 : )
8719 4 : .await
8720 4 : .unwrap();
8721 4 :
8722 4 : // Keeping everything <= Lsn(0x80) b/c leases:
8723 4 : // 0/10: initdb layer
8724 4 : // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
8725 4 : assert_eq!(res.layers_needed_by_leases, 7);
8726 4 : // Keeping 0/90 b/c it is the latest layer.
8727 4 : assert_eq!(res.layers_not_updated, 1);
8728 4 : // Removed 0/80.
8729 4 : assert_eq!(res.layers_removed, 1);
8730 4 :
8731 4 : // Make lease on a already GC-ed LSN.
8732 4 : // 0/80 does not have a valid lease + is below latest_gc_cutoff
8733 4 : assert!(Lsn(0x80) < *timeline.get_latest_gc_cutoff_lsn());
8734 4 : timeline
8735 4 : .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
8736 4 : .expect_err("lease request on GC-ed LSN should fail");
8737 4 :
8738 4 : // Should still be able to renew a currently valid lease
8739 4 : // Assumption: original lease to is still valid for 0/50.
8740 4 : // (use `Timeline::init_lsn_lease` for testing so it always does validation)
8741 4 : timeline
8742 4 : .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
8743 4 : .expect("lease renewal with validation should succeed");
8744 4 :
8745 4 : Ok(())
8746 4 : }
8747 :
8748 : #[cfg(feature = "testing")]
8749 : #[tokio::test]
8750 4 : async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
8751 4 : test_simple_bottom_most_compaction_deltas_helper(
8752 4 : "test_simple_bottom_most_compaction_deltas_1",
8753 4 : false,
8754 4 : )
8755 4 : .await
8756 4 : }
8757 :
8758 : #[cfg(feature = "testing")]
8759 : #[tokio::test]
8760 4 : async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
8761 4 : test_simple_bottom_most_compaction_deltas_helper(
8762 4 : "test_simple_bottom_most_compaction_deltas_2",
8763 4 : true,
8764 4 : )
8765 4 : .await
8766 4 : }
8767 :
8768 : #[cfg(feature = "testing")]
8769 8 : async fn test_simple_bottom_most_compaction_deltas_helper(
8770 8 : test_name: &'static str,
8771 8 : use_delta_bottom_layer: bool,
8772 8 : ) -> anyhow::Result<()> {
8773 8 : let harness = TenantHarness::create(test_name).await?;
8774 8 : let (tenant, ctx) = harness.load().await;
8775 :
8776 552 : fn get_key(id: u32) -> Key {
8777 552 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8778 552 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8779 552 : key.field6 = id;
8780 552 : key
8781 552 : }
8782 :
8783 : // We create
8784 : // - one bottom-most image layer,
8785 : // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
8786 : // - a delta layer D2 crossing the GC horizon with data only below the horizon,
8787 : // - a delta layer D3 above the horizon.
8788 : //
8789 : // | D3 |
8790 : // | D1 |
8791 : // -| |-- gc horizon -----------------
8792 : // | | | D2 |
8793 : // --------- img layer ------------------
8794 : //
8795 : // What we should expact from this compaction is:
8796 : // | D3 |
8797 : // | Part of D1 |
8798 : // --------- img layer with D1+D2 at GC horizon------------------
8799 :
8800 : // img layer at 0x10
8801 8 : let img_layer = (0..10)
8802 80 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
8803 8 : .collect_vec();
8804 8 : // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
8805 8 : let delta4 = (0..10)
8806 80 : .map(|id| {
8807 80 : (
8808 80 : get_key(id),
8809 80 : Lsn(0x08),
8810 80 : Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
8811 80 : )
8812 80 : })
8813 8 : .collect_vec();
8814 8 :
8815 8 : let delta1 = vec![
8816 8 : (
8817 8 : get_key(1),
8818 8 : Lsn(0x20),
8819 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8820 8 : ),
8821 8 : (
8822 8 : get_key(2),
8823 8 : Lsn(0x30),
8824 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
8825 8 : ),
8826 8 : (
8827 8 : get_key(3),
8828 8 : Lsn(0x28),
8829 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
8830 8 : ),
8831 8 : (
8832 8 : get_key(3),
8833 8 : Lsn(0x30),
8834 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
8835 8 : ),
8836 8 : (
8837 8 : get_key(3),
8838 8 : Lsn(0x40),
8839 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
8840 8 : ),
8841 8 : ];
8842 8 : let delta2 = vec![
8843 8 : (
8844 8 : get_key(5),
8845 8 : Lsn(0x20),
8846 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8847 8 : ),
8848 8 : (
8849 8 : get_key(6),
8850 8 : Lsn(0x20),
8851 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8852 8 : ),
8853 8 : ];
8854 8 : let delta3 = vec![
8855 8 : (
8856 8 : get_key(8),
8857 8 : Lsn(0x48),
8858 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
8859 8 : ),
8860 8 : (
8861 8 : get_key(9),
8862 8 : Lsn(0x48),
8863 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
8864 8 : ),
8865 8 : ];
8866 :
8867 8 : let tline = if use_delta_bottom_layer {
8868 4 : tenant
8869 4 : .create_test_timeline_with_layers(
8870 4 : TIMELINE_ID,
8871 4 : Lsn(0x08),
8872 4 : DEFAULT_PG_VERSION,
8873 4 : &ctx,
8874 4 : vec![
8875 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8876 4 : Lsn(0x08)..Lsn(0x10),
8877 4 : delta4,
8878 4 : ),
8879 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8880 4 : Lsn(0x20)..Lsn(0x48),
8881 4 : delta1,
8882 4 : ),
8883 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8884 4 : Lsn(0x20)..Lsn(0x48),
8885 4 : delta2,
8886 4 : ),
8887 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8888 4 : Lsn(0x48)..Lsn(0x50),
8889 4 : delta3,
8890 4 : ),
8891 4 : ], // delta layers
8892 4 : vec![], // image layers
8893 4 : Lsn(0x50),
8894 4 : )
8895 4 : .await?
8896 : } else {
8897 4 : tenant
8898 4 : .create_test_timeline_with_layers(
8899 4 : TIMELINE_ID,
8900 4 : Lsn(0x10),
8901 4 : DEFAULT_PG_VERSION,
8902 4 : &ctx,
8903 4 : vec![
8904 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8905 4 : Lsn(0x10)..Lsn(0x48),
8906 4 : delta1,
8907 4 : ),
8908 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8909 4 : Lsn(0x10)..Lsn(0x48),
8910 4 : delta2,
8911 4 : ),
8912 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8913 4 : Lsn(0x48)..Lsn(0x50),
8914 4 : delta3,
8915 4 : ),
8916 4 : ], // delta layers
8917 4 : vec![(Lsn(0x10), img_layer)], // image layers
8918 4 : Lsn(0x50),
8919 4 : )
8920 4 : .await?
8921 : };
8922 : {
8923 8 : tline
8924 8 : .latest_gc_cutoff_lsn
8925 8 : .lock_for_write()
8926 8 : .store_and_unlock(Lsn(0x30))
8927 8 : .wait()
8928 8 : .await;
8929 : // Update GC info
8930 8 : let mut guard = tline.gc_info.write().unwrap();
8931 8 : *guard = GcInfo {
8932 8 : retain_lsns: vec![],
8933 8 : cutoffs: GcCutoffs {
8934 8 : time: Lsn(0x30),
8935 8 : space: Lsn(0x30),
8936 8 : },
8937 8 : leases: Default::default(),
8938 8 : within_ancestor_pitr: false,
8939 8 : };
8940 8 : }
8941 8 :
8942 8 : let expected_result = [
8943 8 : Bytes::from_static(b"value 0@0x10"),
8944 8 : Bytes::from_static(b"value 1@0x10@0x20"),
8945 8 : Bytes::from_static(b"value 2@0x10@0x30"),
8946 8 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
8947 8 : Bytes::from_static(b"value 4@0x10"),
8948 8 : Bytes::from_static(b"value 5@0x10@0x20"),
8949 8 : Bytes::from_static(b"value 6@0x10@0x20"),
8950 8 : Bytes::from_static(b"value 7@0x10"),
8951 8 : Bytes::from_static(b"value 8@0x10@0x48"),
8952 8 : Bytes::from_static(b"value 9@0x10@0x48"),
8953 8 : ];
8954 8 :
8955 8 : let expected_result_at_gc_horizon = [
8956 8 : Bytes::from_static(b"value 0@0x10"),
8957 8 : Bytes::from_static(b"value 1@0x10@0x20"),
8958 8 : Bytes::from_static(b"value 2@0x10@0x30"),
8959 8 : Bytes::from_static(b"value 3@0x10@0x28@0x30"),
8960 8 : Bytes::from_static(b"value 4@0x10"),
8961 8 : Bytes::from_static(b"value 5@0x10@0x20"),
8962 8 : Bytes::from_static(b"value 6@0x10@0x20"),
8963 8 : Bytes::from_static(b"value 7@0x10"),
8964 8 : Bytes::from_static(b"value 8@0x10"),
8965 8 : Bytes::from_static(b"value 9@0x10"),
8966 8 : ];
8967 :
8968 88 : for idx in 0..10 {
8969 80 : assert_eq!(
8970 80 : tline
8971 80 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8972 80 : .await
8973 80 : .unwrap(),
8974 80 : &expected_result[idx]
8975 : );
8976 80 : assert_eq!(
8977 80 : tline
8978 80 : .get(get_key(idx as u32), Lsn(0x30), &ctx)
8979 80 : .await
8980 80 : .unwrap(),
8981 80 : &expected_result_at_gc_horizon[idx]
8982 : );
8983 : }
8984 :
8985 8 : let cancel = CancellationToken::new();
8986 8 : tline
8987 8 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8988 8 : .await
8989 8 : .unwrap();
8990 :
8991 88 : for idx in 0..10 {
8992 80 : assert_eq!(
8993 80 : tline
8994 80 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8995 80 : .await
8996 80 : .unwrap(),
8997 80 : &expected_result[idx]
8998 : );
8999 80 : assert_eq!(
9000 80 : tline
9001 80 : .get(get_key(idx as u32), Lsn(0x30), &ctx)
9002 80 : .await
9003 80 : .unwrap(),
9004 80 : &expected_result_at_gc_horizon[idx]
9005 : );
9006 : }
9007 :
9008 : // increase GC horizon and compact again
9009 : {
9010 8 : tline
9011 8 : .latest_gc_cutoff_lsn
9012 8 : .lock_for_write()
9013 8 : .store_and_unlock(Lsn(0x40))
9014 8 : .wait()
9015 8 : .await;
9016 : // Update GC info
9017 8 : let mut guard = tline.gc_info.write().unwrap();
9018 8 : guard.cutoffs.time = Lsn(0x40);
9019 8 : guard.cutoffs.space = Lsn(0x40);
9020 8 : }
9021 8 : tline
9022 8 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9023 8 : .await
9024 8 : .unwrap();
9025 8 :
9026 8 : Ok(())
9027 8 : }
9028 :
9029 : #[cfg(feature = "testing")]
9030 : #[tokio::test]
9031 4 : async fn test_generate_key_retention() -> anyhow::Result<()> {
9032 4 : let harness = TenantHarness::create("test_generate_key_retention").await?;
9033 4 : let (tenant, ctx) = harness.load().await;
9034 4 : let tline = tenant
9035 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
9036 4 : .await?;
9037 4 : tline.force_advance_lsn(Lsn(0x70));
9038 4 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
9039 4 : let history = vec![
9040 4 : (
9041 4 : key,
9042 4 : Lsn(0x10),
9043 4 : Value::WalRecord(NeonWalRecord::wal_init("0x10")),
9044 4 : ),
9045 4 : (
9046 4 : key,
9047 4 : Lsn(0x20),
9048 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9049 4 : ),
9050 4 : (
9051 4 : key,
9052 4 : Lsn(0x30),
9053 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9054 4 : ),
9055 4 : (
9056 4 : key,
9057 4 : Lsn(0x40),
9058 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9059 4 : ),
9060 4 : (
9061 4 : key,
9062 4 : Lsn(0x50),
9063 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9064 4 : ),
9065 4 : (
9066 4 : key,
9067 4 : Lsn(0x60),
9068 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9069 4 : ),
9070 4 : (
9071 4 : key,
9072 4 : Lsn(0x70),
9073 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9074 4 : ),
9075 4 : (
9076 4 : key,
9077 4 : Lsn(0x80),
9078 4 : Value::Image(Bytes::copy_from_slice(
9079 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9080 4 : )),
9081 4 : ),
9082 4 : (
9083 4 : key,
9084 4 : Lsn(0x90),
9085 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9086 4 : ),
9087 4 : ];
9088 4 : let res = tline
9089 4 : .generate_key_retention(
9090 4 : key,
9091 4 : &history,
9092 4 : Lsn(0x60),
9093 4 : &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
9094 4 : 3,
9095 4 : None,
9096 4 : )
9097 4 : .await
9098 4 : .unwrap();
9099 4 : let expected_res = KeyHistoryRetention {
9100 4 : below_horizon: vec![
9101 4 : (
9102 4 : Lsn(0x20),
9103 4 : KeyLogAtLsn(vec![(
9104 4 : Lsn(0x20),
9105 4 : Value::Image(Bytes::from_static(b"0x10;0x20")),
9106 4 : )]),
9107 4 : ),
9108 4 : (
9109 4 : Lsn(0x40),
9110 4 : KeyLogAtLsn(vec![
9111 4 : (
9112 4 : Lsn(0x30),
9113 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9114 4 : ),
9115 4 : (
9116 4 : Lsn(0x40),
9117 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9118 4 : ),
9119 4 : ]),
9120 4 : ),
9121 4 : (
9122 4 : Lsn(0x50),
9123 4 : KeyLogAtLsn(vec![(
9124 4 : Lsn(0x50),
9125 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
9126 4 : )]),
9127 4 : ),
9128 4 : (
9129 4 : Lsn(0x60),
9130 4 : KeyLogAtLsn(vec![(
9131 4 : Lsn(0x60),
9132 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9133 4 : )]),
9134 4 : ),
9135 4 : ],
9136 4 : above_horizon: KeyLogAtLsn(vec![
9137 4 : (
9138 4 : Lsn(0x70),
9139 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9140 4 : ),
9141 4 : (
9142 4 : Lsn(0x80),
9143 4 : Value::Image(Bytes::copy_from_slice(
9144 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9145 4 : )),
9146 4 : ),
9147 4 : (
9148 4 : Lsn(0x90),
9149 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9150 4 : ),
9151 4 : ]),
9152 4 : };
9153 4 : assert_eq!(res, expected_res);
9154 4 :
9155 4 : // We expect GC-compaction to run with the original GC. This would create a situation that
9156 4 : // the original GC algorithm removes some delta layers b/c there are full image coverage,
9157 4 : // therefore causing some keys to have an incomplete history below the lowest retain LSN.
9158 4 : // For example, we have
9159 4 : // ```plain
9160 4 : // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
9161 4 : // ```
9162 4 : // Now the GC horizon moves up, and we have
9163 4 : // ```plain
9164 4 : // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
9165 4 : // ```
9166 4 : // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
9167 4 : // We will end up with
9168 4 : // ```plain
9169 4 : // delta @ 0x30, image @ 0x40 (gc_horizon)
9170 4 : // ```
9171 4 : // Now we run the GC-compaction, and this key does not have a full history.
9172 4 : // We should be able to handle this partial history and drop everything before the
9173 4 : // gc_horizon image.
9174 4 :
9175 4 : let history = vec![
9176 4 : (
9177 4 : key,
9178 4 : Lsn(0x20),
9179 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9180 4 : ),
9181 4 : (
9182 4 : key,
9183 4 : Lsn(0x30),
9184 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9185 4 : ),
9186 4 : (
9187 4 : key,
9188 4 : Lsn(0x40),
9189 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
9190 4 : ),
9191 4 : (
9192 4 : key,
9193 4 : Lsn(0x50),
9194 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9195 4 : ),
9196 4 : (
9197 4 : key,
9198 4 : Lsn(0x60),
9199 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9200 4 : ),
9201 4 : (
9202 4 : key,
9203 4 : Lsn(0x70),
9204 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9205 4 : ),
9206 4 : (
9207 4 : key,
9208 4 : Lsn(0x80),
9209 4 : Value::Image(Bytes::copy_from_slice(
9210 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9211 4 : )),
9212 4 : ),
9213 4 : (
9214 4 : key,
9215 4 : Lsn(0x90),
9216 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9217 4 : ),
9218 4 : ];
9219 4 : let res = tline
9220 4 : .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
9221 4 : .await
9222 4 : .unwrap();
9223 4 : let expected_res = KeyHistoryRetention {
9224 4 : below_horizon: vec![
9225 4 : (
9226 4 : Lsn(0x40),
9227 4 : KeyLogAtLsn(vec![(
9228 4 : Lsn(0x40),
9229 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
9230 4 : )]),
9231 4 : ),
9232 4 : (
9233 4 : Lsn(0x50),
9234 4 : KeyLogAtLsn(vec![(
9235 4 : Lsn(0x50),
9236 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9237 4 : )]),
9238 4 : ),
9239 4 : (
9240 4 : Lsn(0x60),
9241 4 : KeyLogAtLsn(vec![(
9242 4 : Lsn(0x60),
9243 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9244 4 : )]),
9245 4 : ),
9246 4 : ],
9247 4 : above_horizon: KeyLogAtLsn(vec![
9248 4 : (
9249 4 : Lsn(0x70),
9250 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9251 4 : ),
9252 4 : (
9253 4 : Lsn(0x80),
9254 4 : Value::Image(Bytes::copy_from_slice(
9255 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9256 4 : )),
9257 4 : ),
9258 4 : (
9259 4 : Lsn(0x90),
9260 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9261 4 : ),
9262 4 : ]),
9263 4 : };
9264 4 : assert_eq!(res, expected_res);
9265 4 :
9266 4 : // In case of branch compaction, the branch itself does not have the full history, and we need to provide
9267 4 : // the ancestor image in the test case.
9268 4 :
9269 4 : let history = vec![
9270 4 : (
9271 4 : key,
9272 4 : Lsn(0x20),
9273 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9274 4 : ),
9275 4 : (
9276 4 : key,
9277 4 : Lsn(0x30),
9278 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9279 4 : ),
9280 4 : (
9281 4 : key,
9282 4 : Lsn(0x40),
9283 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9284 4 : ),
9285 4 : (
9286 4 : key,
9287 4 : Lsn(0x70),
9288 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9289 4 : ),
9290 4 : ];
9291 4 : let res = tline
9292 4 : .generate_key_retention(
9293 4 : key,
9294 4 : &history,
9295 4 : Lsn(0x60),
9296 4 : &[],
9297 4 : 3,
9298 4 : Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
9299 4 : )
9300 4 : .await
9301 4 : .unwrap();
9302 4 : let expected_res = KeyHistoryRetention {
9303 4 : below_horizon: vec![(
9304 4 : Lsn(0x60),
9305 4 : KeyLogAtLsn(vec![(
9306 4 : Lsn(0x60),
9307 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
9308 4 : )]),
9309 4 : )],
9310 4 : above_horizon: KeyLogAtLsn(vec![(
9311 4 : Lsn(0x70),
9312 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9313 4 : )]),
9314 4 : };
9315 4 : assert_eq!(res, expected_res);
9316 4 :
9317 4 : let history = vec![
9318 4 : (
9319 4 : key,
9320 4 : Lsn(0x20),
9321 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9322 4 : ),
9323 4 : (
9324 4 : key,
9325 4 : Lsn(0x40),
9326 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9327 4 : ),
9328 4 : (
9329 4 : key,
9330 4 : Lsn(0x60),
9331 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9332 4 : ),
9333 4 : (
9334 4 : key,
9335 4 : Lsn(0x70),
9336 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9337 4 : ),
9338 4 : ];
9339 4 : let res = tline
9340 4 : .generate_key_retention(
9341 4 : key,
9342 4 : &history,
9343 4 : Lsn(0x60),
9344 4 : &[Lsn(0x30)],
9345 4 : 3,
9346 4 : Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
9347 4 : )
9348 4 : .await
9349 4 : .unwrap();
9350 4 : let expected_res = KeyHistoryRetention {
9351 4 : below_horizon: vec![
9352 4 : (
9353 4 : Lsn(0x30),
9354 4 : KeyLogAtLsn(vec![(
9355 4 : Lsn(0x20),
9356 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9357 4 : )]),
9358 4 : ),
9359 4 : (
9360 4 : Lsn(0x60),
9361 4 : KeyLogAtLsn(vec![(
9362 4 : Lsn(0x60),
9363 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
9364 4 : )]),
9365 4 : ),
9366 4 : ],
9367 4 : above_horizon: KeyLogAtLsn(vec![(
9368 4 : Lsn(0x70),
9369 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9370 4 : )]),
9371 4 : };
9372 4 : assert_eq!(res, expected_res);
9373 4 :
9374 4 : Ok(())
9375 4 : }
9376 :
9377 : #[cfg(feature = "testing")]
9378 : #[tokio::test]
9379 4 : async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
9380 4 : let harness =
9381 4 : TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
9382 4 : let (tenant, ctx) = harness.load().await;
9383 4 :
9384 1036 : fn get_key(id: u32) -> Key {
9385 1036 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
9386 1036 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
9387 1036 : key.field6 = id;
9388 1036 : key
9389 1036 : }
9390 4 :
9391 4 : let img_layer = (0..10)
9392 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9393 4 : .collect_vec();
9394 4 :
9395 4 : let delta1 = vec![
9396 4 : (
9397 4 : get_key(1),
9398 4 : Lsn(0x20),
9399 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9400 4 : ),
9401 4 : (
9402 4 : get_key(2),
9403 4 : Lsn(0x30),
9404 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9405 4 : ),
9406 4 : (
9407 4 : get_key(3),
9408 4 : Lsn(0x28),
9409 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9410 4 : ),
9411 4 : (
9412 4 : get_key(3),
9413 4 : Lsn(0x30),
9414 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9415 4 : ),
9416 4 : (
9417 4 : get_key(3),
9418 4 : Lsn(0x40),
9419 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
9420 4 : ),
9421 4 : ];
9422 4 : let delta2 = vec![
9423 4 : (
9424 4 : get_key(5),
9425 4 : Lsn(0x20),
9426 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9427 4 : ),
9428 4 : (
9429 4 : get_key(6),
9430 4 : Lsn(0x20),
9431 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9432 4 : ),
9433 4 : ];
9434 4 : let delta3 = vec![
9435 4 : (
9436 4 : get_key(8),
9437 4 : Lsn(0x48),
9438 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9439 4 : ),
9440 4 : (
9441 4 : get_key(9),
9442 4 : Lsn(0x48),
9443 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9444 4 : ),
9445 4 : ];
9446 4 :
9447 4 : let tline = tenant
9448 4 : .create_test_timeline_with_layers(
9449 4 : TIMELINE_ID,
9450 4 : Lsn(0x10),
9451 4 : DEFAULT_PG_VERSION,
9452 4 : &ctx,
9453 4 : vec![
9454 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
9455 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
9456 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
9457 4 : ], // delta layers
9458 4 : vec![(Lsn(0x10), img_layer)], // image layers
9459 4 : Lsn(0x50),
9460 4 : )
9461 4 : .await?;
9462 4 : {
9463 4 : tline
9464 4 : .latest_gc_cutoff_lsn
9465 4 : .lock_for_write()
9466 4 : .store_and_unlock(Lsn(0x30))
9467 4 : .wait()
9468 4 : .await;
9469 4 : // Update GC info
9470 4 : let mut guard = tline.gc_info.write().unwrap();
9471 4 : *guard = GcInfo {
9472 4 : retain_lsns: vec![
9473 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
9474 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
9475 4 : ],
9476 4 : cutoffs: GcCutoffs {
9477 4 : time: Lsn(0x30),
9478 4 : space: Lsn(0x30),
9479 4 : },
9480 4 : leases: Default::default(),
9481 4 : within_ancestor_pitr: false,
9482 4 : };
9483 4 : }
9484 4 :
9485 4 : let expected_result = [
9486 4 : Bytes::from_static(b"value 0@0x10"),
9487 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9488 4 : Bytes::from_static(b"value 2@0x10@0x30"),
9489 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
9490 4 : Bytes::from_static(b"value 4@0x10"),
9491 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9492 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9493 4 : Bytes::from_static(b"value 7@0x10"),
9494 4 : Bytes::from_static(b"value 8@0x10@0x48"),
9495 4 : Bytes::from_static(b"value 9@0x10@0x48"),
9496 4 : ];
9497 4 :
9498 4 : let expected_result_at_gc_horizon = [
9499 4 : Bytes::from_static(b"value 0@0x10"),
9500 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9501 4 : Bytes::from_static(b"value 2@0x10@0x30"),
9502 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30"),
9503 4 : Bytes::from_static(b"value 4@0x10"),
9504 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9505 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9506 4 : Bytes::from_static(b"value 7@0x10"),
9507 4 : Bytes::from_static(b"value 8@0x10"),
9508 4 : Bytes::from_static(b"value 9@0x10"),
9509 4 : ];
9510 4 :
9511 4 : let expected_result_at_lsn_20 = [
9512 4 : Bytes::from_static(b"value 0@0x10"),
9513 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9514 4 : Bytes::from_static(b"value 2@0x10"),
9515 4 : Bytes::from_static(b"value 3@0x10"),
9516 4 : Bytes::from_static(b"value 4@0x10"),
9517 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9518 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9519 4 : Bytes::from_static(b"value 7@0x10"),
9520 4 : Bytes::from_static(b"value 8@0x10"),
9521 4 : Bytes::from_static(b"value 9@0x10"),
9522 4 : ];
9523 4 :
9524 4 : let expected_result_at_lsn_10 = [
9525 4 : Bytes::from_static(b"value 0@0x10"),
9526 4 : Bytes::from_static(b"value 1@0x10"),
9527 4 : Bytes::from_static(b"value 2@0x10"),
9528 4 : Bytes::from_static(b"value 3@0x10"),
9529 4 : Bytes::from_static(b"value 4@0x10"),
9530 4 : Bytes::from_static(b"value 5@0x10"),
9531 4 : Bytes::from_static(b"value 6@0x10"),
9532 4 : Bytes::from_static(b"value 7@0x10"),
9533 4 : Bytes::from_static(b"value 8@0x10"),
9534 4 : Bytes::from_static(b"value 9@0x10"),
9535 4 : ];
9536 4 :
9537 24 : let verify_result = || async {
9538 24 : let gc_horizon = {
9539 24 : let gc_info = tline.gc_info.read().unwrap();
9540 24 : gc_info.cutoffs.time
9541 4 : };
9542 264 : for idx in 0..10 {
9543 240 : assert_eq!(
9544 240 : tline
9545 240 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9546 240 : .await
9547 240 : .unwrap(),
9548 240 : &expected_result[idx]
9549 4 : );
9550 240 : assert_eq!(
9551 240 : tline
9552 240 : .get(get_key(idx as u32), gc_horizon, &ctx)
9553 240 : .await
9554 240 : .unwrap(),
9555 240 : &expected_result_at_gc_horizon[idx]
9556 4 : );
9557 240 : assert_eq!(
9558 240 : tline
9559 240 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
9560 240 : .await
9561 240 : .unwrap(),
9562 240 : &expected_result_at_lsn_20[idx]
9563 4 : );
9564 240 : assert_eq!(
9565 240 : tline
9566 240 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
9567 240 : .await
9568 240 : .unwrap(),
9569 240 : &expected_result_at_lsn_10[idx]
9570 4 : );
9571 4 : }
9572 48 : };
9573 4 :
9574 4 : verify_result().await;
9575 4 :
9576 4 : let cancel = CancellationToken::new();
9577 4 : let mut dryrun_flags = EnumSet::new();
9578 4 : dryrun_flags.insert(CompactFlags::DryRun);
9579 4 :
9580 4 : tline
9581 4 : .compact_with_gc(
9582 4 : &cancel,
9583 4 : CompactOptions {
9584 4 : flags: dryrun_flags,
9585 4 : ..Default::default()
9586 4 : },
9587 4 : &ctx,
9588 4 : )
9589 4 : .await
9590 4 : .unwrap();
9591 4 : // 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
9592 4 : // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
9593 4 : verify_result().await;
9594 4 :
9595 4 : tline
9596 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9597 4 : .await
9598 4 : .unwrap();
9599 4 : verify_result().await;
9600 4 :
9601 4 : // compact again
9602 4 : tline
9603 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9604 4 : .await
9605 4 : .unwrap();
9606 4 : verify_result().await;
9607 4 :
9608 4 : // increase GC horizon and compact again
9609 4 : {
9610 4 : tline
9611 4 : .latest_gc_cutoff_lsn
9612 4 : .lock_for_write()
9613 4 : .store_and_unlock(Lsn(0x38))
9614 4 : .wait()
9615 4 : .await;
9616 4 : // Update GC info
9617 4 : let mut guard = tline.gc_info.write().unwrap();
9618 4 : guard.cutoffs.time = Lsn(0x38);
9619 4 : guard.cutoffs.space = Lsn(0x38);
9620 4 : }
9621 4 : tline
9622 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9623 4 : .await
9624 4 : .unwrap();
9625 4 : verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
9626 4 :
9627 4 : // not increasing the GC horizon and compact again
9628 4 : tline
9629 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9630 4 : .await
9631 4 : .unwrap();
9632 4 : verify_result().await;
9633 4 :
9634 4 : Ok(())
9635 4 : }
9636 :
9637 : #[cfg(feature = "testing")]
9638 : #[tokio::test]
9639 4 : async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
9640 4 : {
9641 4 : let harness =
9642 4 : TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
9643 4 : .await?;
9644 4 : let (tenant, ctx) = harness.load().await;
9645 4 :
9646 704 : fn get_key(id: u32) -> Key {
9647 704 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
9648 704 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
9649 704 : key.field6 = id;
9650 704 : key
9651 704 : }
9652 4 :
9653 4 : let img_layer = (0..10)
9654 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9655 4 : .collect_vec();
9656 4 :
9657 4 : let delta1 = vec![
9658 4 : (
9659 4 : get_key(1),
9660 4 : Lsn(0x20),
9661 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9662 4 : ),
9663 4 : (
9664 4 : get_key(1),
9665 4 : Lsn(0x28),
9666 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9667 4 : ),
9668 4 : ];
9669 4 : let delta2 = vec![
9670 4 : (
9671 4 : get_key(1),
9672 4 : Lsn(0x30),
9673 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9674 4 : ),
9675 4 : (
9676 4 : get_key(1),
9677 4 : Lsn(0x38),
9678 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
9679 4 : ),
9680 4 : ];
9681 4 : let delta3 = vec![
9682 4 : (
9683 4 : get_key(8),
9684 4 : Lsn(0x48),
9685 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9686 4 : ),
9687 4 : (
9688 4 : get_key(9),
9689 4 : Lsn(0x48),
9690 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9691 4 : ),
9692 4 : ];
9693 4 :
9694 4 : let tline = tenant
9695 4 : .create_test_timeline_with_layers(
9696 4 : TIMELINE_ID,
9697 4 : Lsn(0x10),
9698 4 : DEFAULT_PG_VERSION,
9699 4 : &ctx,
9700 4 : vec![
9701 4 : // delta1 and delta 2 only contain a single key but multiple updates
9702 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
9703 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
9704 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
9705 4 : ], // delta layers
9706 4 : vec![(Lsn(0x10), img_layer)], // image layers
9707 4 : Lsn(0x50),
9708 4 : )
9709 4 : .await?;
9710 4 : {
9711 4 : tline
9712 4 : .latest_gc_cutoff_lsn
9713 4 : .lock_for_write()
9714 4 : .store_and_unlock(Lsn(0x30))
9715 4 : .wait()
9716 4 : .await;
9717 4 : // Update GC info
9718 4 : let mut guard = tline.gc_info.write().unwrap();
9719 4 : *guard = GcInfo {
9720 4 : retain_lsns: vec![
9721 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
9722 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
9723 4 : ],
9724 4 : cutoffs: GcCutoffs {
9725 4 : time: Lsn(0x30),
9726 4 : space: Lsn(0x30),
9727 4 : },
9728 4 : leases: Default::default(),
9729 4 : within_ancestor_pitr: false,
9730 4 : };
9731 4 : }
9732 4 :
9733 4 : let expected_result = [
9734 4 : Bytes::from_static(b"value 0@0x10"),
9735 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
9736 4 : Bytes::from_static(b"value 2@0x10"),
9737 4 : Bytes::from_static(b"value 3@0x10"),
9738 4 : Bytes::from_static(b"value 4@0x10"),
9739 4 : Bytes::from_static(b"value 5@0x10"),
9740 4 : Bytes::from_static(b"value 6@0x10"),
9741 4 : Bytes::from_static(b"value 7@0x10"),
9742 4 : Bytes::from_static(b"value 8@0x10@0x48"),
9743 4 : Bytes::from_static(b"value 9@0x10@0x48"),
9744 4 : ];
9745 4 :
9746 4 : let expected_result_at_gc_horizon = [
9747 4 : Bytes::from_static(b"value 0@0x10"),
9748 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
9749 4 : Bytes::from_static(b"value 2@0x10"),
9750 4 : Bytes::from_static(b"value 3@0x10"),
9751 4 : Bytes::from_static(b"value 4@0x10"),
9752 4 : Bytes::from_static(b"value 5@0x10"),
9753 4 : Bytes::from_static(b"value 6@0x10"),
9754 4 : Bytes::from_static(b"value 7@0x10"),
9755 4 : Bytes::from_static(b"value 8@0x10"),
9756 4 : Bytes::from_static(b"value 9@0x10"),
9757 4 : ];
9758 4 :
9759 4 : let expected_result_at_lsn_20 = [
9760 4 : Bytes::from_static(b"value 0@0x10"),
9761 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9762 4 : Bytes::from_static(b"value 2@0x10"),
9763 4 : Bytes::from_static(b"value 3@0x10"),
9764 4 : Bytes::from_static(b"value 4@0x10"),
9765 4 : Bytes::from_static(b"value 5@0x10"),
9766 4 : Bytes::from_static(b"value 6@0x10"),
9767 4 : Bytes::from_static(b"value 7@0x10"),
9768 4 : Bytes::from_static(b"value 8@0x10"),
9769 4 : Bytes::from_static(b"value 9@0x10"),
9770 4 : ];
9771 4 :
9772 4 : let expected_result_at_lsn_10 = [
9773 4 : Bytes::from_static(b"value 0@0x10"),
9774 4 : Bytes::from_static(b"value 1@0x10"),
9775 4 : Bytes::from_static(b"value 2@0x10"),
9776 4 : Bytes::from_static(b"value 3@0x10"),
9777 4 : Bytes::from_static(b"value 4@0x10"),
9778 4 : Bytes::from_static(b"value 5@0x10"),
9779 4 : Bytes::from_static(b"value 6@0x10"),
9780 4 : Bytes::from_static(b"value 7@0x10"),
9781 4 : Bytes::from_static(b"value 8@0x10"),
9782 4 : Bytes::from_static(b"value 9@0x10"),
9783 4 : ];
9784 4 :
9785 16 : let verify_result = || async {
9786 16 : let gc_horizon = {
9787 16 : let gc_info = tline.gc_info.read().unwrap();
9788 16 : gc_info.cutoffs.time
9789 4 : };
9790 176 : for idx in 0..10 {
9791 160 : assert_eq!(
9792 160 : tline
9793 160 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9794 160 : .await
9795 160 : .unwrap(),
9796 160 : &expected_result[idx]
9797 4 : );
9798 160 : assert_eq!(
9799 160 : tline
9800 160 : .get(get_key(idx as u32), gc_horizon, &ctx)
9801 160 : .await
9802 160 : .unwrap(),
9803 160 : &expected_result_at_gc_horizon[idx]
9804 4 : );
9805 160 : assert_eq!(
9806 160 : tline
9807 160 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
9808 160 : .await
9809 160 : .unwrap(),
9810 160 : &expected_result_at_lsn_20[idx]
9811 4 : );
9812 160 : assert_eq!(
9813 160 : tline
9814 160 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
9815 160 : .await
9816 160 : .unwrap(),
9817 160 : &expected_result_at_lsn_10[idx]
9818 4 : );
9819 4 : }
9820 32 : };
9821 4 :
9822 4 : verify_result().await;
9823 4 :
9824 4 : let cancel = CancellationToken::new();
9825 4 : let mut dryrun_flags = EnumSet::new();
9826 4 : dryrun_flags.insert(CompactFlags::DryRun);
9827 4 :
9828 4 : tline
9829 4 : .compact_with_gc(
9830 4 : &cancel,
9831 4 : CompactOptions {
9832 4 : flags: dryrun_flags,
9833 4 : ..Default::default()
9834 4 : },
9835 4 : &ctx,
9836 4 : )
9837 4 : .await
9838 4 : .unwrap();
9839 4 : // 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
9840 4 : // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
9841 4 : verify_result().await;
9842 4 :
9843 4 : tline
9844 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9845 4 : .await
9846 4 : .unwrap();
9847 4 : verify_result().await;
9848 4 :
9849 4 : // compact again
9850 4 : tline
9851 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9852 4 : .await
9853 4 : .unwrap();
9854 4 : verify_result().await;
9855 4 :
9856 4 : Ok(())
9857 4 : }
9858 :
9859 : #[cfg(feature = "testing")]
9860 : #[tokio::test]
9861 4 : async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
9862 4 : use models::CompactLsnRange;
9863 4 :
9864 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
9865 4 : let (tenant, ctx) = harness.load().await;
9866 4 :
9867 332 : fn get_key(id: u32) -> Key {
9868 332 : let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
9869 332 : key.field6 = id;
9870 332 : key
9871 332 : }
9872 4 :
9873 4 : let img_layer = (0..10)
9874 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9875 4 : .collect_vec();
9876 4 :
9877 4 : let delta1 = vec![
9878 4 : (
9879 4 : get_key(1),
9880 4 : Lsn(0x20),
9881 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9882 4 : ),
9883 4 : (
9884 4 : get_key(2),
9885 4 : Lsn(0x30),
9886 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9887 4 : ),
9888 4 : (
9889 4 : get_key(3),
9890 4 : Lsn(0x28),
9891 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9892 4 : ),
9893 4 : (
9894 4 : get_key(3),
9895 4 : Lsn(0x30),
9896 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9897 4 : ),
9898 4 : (
9899 4 : get_key(3),
9900 4 : Lsn(0x40),
9901 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
9902 4 : ),
9903 4 : ];
9904 4 : let delta2 = vec![
9905 4 : (
9906 4 : get_key(5),
9907 4 : Lsn(0x20),
9908 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9909 4 : ),
9910 4 : (
9911 4 : get_key(6),
9912 4 : Lsn(0x20),
9913 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9914 4 : ),
9915 4 : ];
9916 4 : let delta3 = vec![
9917 4 : (
9918 4 : get_key(8),
9919 4 : Lsn(0x48),
9920 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9921 4 : ),
9922 4 : (
9923 4 : get_key(9),
9924 4 : Lsn(0x48),
9925 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9926 4 : ),
9927 4 : ];
9928 4 :
9929 4 : let parent_tline = tenant
9930 4 : .create_test_timeline_with_layers(
9931 4 : TIMELINE_ID,
9932 4 : Lsn(0x10),
9933 4 : DEFAULT_PG_VERSION,
9934 4 : &ctx,
9935 4 : vec![], // delta layers
9936 4 : vec![(Lsn(0x18), img_layer)], // image layers
9937 4 : Lsn(0x18),
9938 4 : )
9939 4 : .await?;
9940 4 :
9941 4 : parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
9942 4 :
9943 4 : let branch_tline = tenant
9944 4 : .branch_timeline_test_with_layers(
9945 4 : &parent_tline,
9946 4 : NEW_TIMELINE_ID,
9947 4 : Some(Lsn(0x18)),
9948 4 : &ctx,
9949 4 : vec![
9950 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
9951 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
9952 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
9953 4 : ], // delta layers
9954 4 : vec![], // image layers
9955 4 : Lsn(0x50),
9956 4 : )
9957 4 : .await?;
9958 4 :
9959 4 : branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
9960 4 :
9961 4 : {
9962 4 : parent_tline
9963 4 : .latest_gc_cutoff_lsn
9964 4 : .lock_for_write()
9965 4 : .store_and_unlock(Lsn(0x10))
9966 4 : .wait()
9967 4 : .await;
9968 4 : // Update GC info
9969 4 : let mut guard = parent_tline.gc_info.write().unwrap();
9970 4 : *guard = GcInfo {
9971 4 : retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
9972 4 : cutoffs: GcCutoffs {
9973 4 : time: Lsn(0x10),
9974 4 : space: Lsn(0x10),
9975 4 : },
9976 4 : leases: Default::default(),
9977 4 : within_ancestor_pitr: false,
9978 4 : };
9979 4 : }
9980 4 :
9981 4 : {
9982 4 : branch_tline
9983 4 : .latest_gc_cutoff_lsn
9984 4 : .lock_for_write()
9985 4 : .store_and_unlock(Lsn(0x50))
9986 4 : .wait()
9987 4 : .await;
9988 4 : // Update GC info
9989 4 : let mut guard = branch_tline.gc_info.write().unwrap();
9990 4 : *guard = GcInfo {
9991 4 : retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
9992 4 : cutoffs: GcCutoffs {
9993 4 : time: Lsn(0x50),
9994 4 : space: Lsn(0x50),
9995 4 : },
9996 4 : leases: Default::default(),
9997 4 : within_ancestor_pitr: false,
9998 4 : };
9999 4 : }
10000 4 :
10001 4 : let expected_result_at_gc_horizon = [
10002 4 : Bytes::from_static(b"value 0@0x10"),
10003 4 : Bytes::from_static(b"value 1@0x10@0x20"),
10004 4 : Bytes::from_static(b"value 2@0x10@0x30"),
10005 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
10006 4 : Bytes::from_static(b"value 4@0x10"),
10007 4 : Bytes::from_static(b"value 5@0x10@0x20"),
10008 4 : Bytes::from_static(b"value 6@0x10@0x20"),
10009 4 : Bytes::from_static(b"value 7@0x10"),
10010 4 : Bytes::from_static(b"value 8@0x10@0x48"),
10011 4 : Bytes::from_static(b"value 9@0x10@0x48"),
10012 4 : ];
10013 4 :
10014 4 : let expected_result_at_lsn_40 = [
10015 4 : Bytes::from_static(b"value 0@0x10"),
10016 4 : Bytes::from_static(b"value 1@0x10@0x20"),
10017 4 : Bytes::from_static(b"value 2@0x10@0x30"),
10018 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
10019 4 : Bytes::from_static(b"value 4@0x10"),
10020 4 : Bytes::from_static(b"value 5@0x10@0x20"),
10021 4 : Bytes::from_static(b"value 6@0x10@0x20"),
10022 4 : Bytes::from_static(b"value 7@0x10"),
10023 4 : Bytes::from_static(b"value 8@0x10"),
10024 4 : Bytes::from_static(b"value 9@0x10"),
10025 4 : ];
10026 4 :
10027 12 : let verify_result = || async {
10028 132 : for idx in 0..10 {
10029 120 : assert_eq!(
10030 120 : branch_tline
10031 120 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
10032 120 : .await
10033 120 : .unwrap(),
10034 120 : &expected_result_at_gc_horizon[idx]
10035 4 : );
10036 120 : assert_eq!(
10037 120 : branch_tline
10038 120 : .get(get_key(idx as u32), Lsn(0x40), &ctx)
10039 120 : .await
10040 120 : .unwrap(),
10041 120 : &expected_result_at_lsn_40[idx]
10042 4 : );
10043 4 : }
10044 24 : };
10045 4 :
10046 4 : verify_result().await;
10047 4 :
10048 4 : let cancel = CancellationToken::new();
10049 4 : branch_tline
10050 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
10051 4 : .await
10052 4 : .unwrap();
10053 4 :
10054 4 : verify_result().await;
10055 4 :
10056 4 : // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
10057 4 : // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
10058 4 : branch_tline
10059 4 : .compact_with_gc(
10060 4 : &cancel,
10061 4 : CompactOptions {
10062 4 : compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
10063 4 : ..Default::default()
10064 4 : },
10065 4 : &ctx,
10066 4 : )
10067 4 : .await
10068 4 : .unwrap();
10069 4 :
10070 4 : verify_result().await;
10071 4 :
10072 4 : Ok(())
10073 4 : }
10074 :
10075 : // Regression test for https://github.com/neondatabase/neon/issues/9012
10076 : // Create an image arrangement where we have to read at different LSN ranges
10077 : // from a delta layer. This is achieved by overlapping an image layer on top of
10078 : // a delta layer. Like so:
10079 : //
10080 : // A B
10081 : // +----------------+ -> delta_layer
10082 : // | | ^ lsn
10083 : // | =========|-> nested_image_layer |
10084 : // | C | |
10085 : // +----------------+ |
10086 : // ======== -> baseline_image_layer +-------> key
10087 : //
10088 : //
10089 : // When querying the key range [A, B) we need to read at different LSN ranges
10090 : // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
10091 : #[cfg(feature = "testing")]
10092 : #[tokio::test]
10093 4 : async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
10094 4 : let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
10095 4 : let (tenant, ctx) = harness.load().await;
10096 4 :
10097 4 : let will_init_keys = [2, 6];
10098 88 : fn get_key(id: u32) -> Key {
10099 88 : let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
10100 88 : key.field6 = id;
10101 88 : key
10102 88 : }
10103 4 :
10104 4 : let mut expected_key_values = HashMap::new();
10105 4 :
10106 4 : let baseline_image_layer_lsn = Lsn(0x10);
10107 4 : let mut baseline_img_layer = Vec::new();
10108 24 : for i in 0..5 {
10109 20 : let key = get_key(i);
10110 20 : let value = format!("value {i}@{baseline_image_layer_lsn}");
10111 20 :
10112 20 : let removed = expected_key_values.insert(key, value.clone());
10113 20 : assert!(removed.is_none());
10114 4 :
10115 20 : baseline_img_layer.push((key, Bytes::from(value)));
10116 4 : }
10117 4 :
10118 4 : let nested_image_layer_lsn = Lsn(0x50);
10119 4 : let mut nested_img_layer = Vec::new();
10120 24 : for i in 5..10 {
10121 20 : let key = get_key(i);
10122 20 : let value = format!("value {i}@{nested_image_layer_lsn}");
10123 20 :
10124 20 : let removed = expected_key_values.insert(key, value.clone());
10125 20 : assert!(removed.is_none());
10126 4 :
10127 20 : nested_img_layer.push((key, Bytes::from(value)));
10128 4 : }
10129 4 :
10130 4 : let mut delta_layer_spec = Vec::default();
10131 4 : let delta_layer_start_lsn = Lsn(0x20);
10132 4 : let mut delta_layer_end_lsn = delta_layer_start_lsn;
10133 4 :
10134 44 : for i in 0..10 {
10135 40 : let key = get_key(i);
10136 40 : let key_in_nested = nested_img_layer
10137 40 : .iter()
10138 160 : .any(|(key_with_img, _)| *key_with_img == key);
10139 40 : let lsn = {
10140 40 : if key_in_nested {
10141 20 : Lsn(nested_image_layer_lsn.0 + 0x10)
10142 4 : } else {
10143 20 : delta_layer_start_lsn
10144 4 : }
10145 4 : };
10146 4 :
10147 40 : let will_init = will_init_keys.contains(&i);
10148 40 : if will_init {
10149 8 : delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
10150 8 :
10151 8 : expected_key_values.insert(key, "".to_string());
10152 32 : } else {
10153 32 : let delta = format!("@{lsn}");
10154 32 : delta_layer_spec.push((
10155 32 : key,
10156 32 : lsn,
10157 32 : Value::WalRecord(NeonWalRecord::wal_append(&delta)),
10158 32 : ));
10159 32 :
10160 32 : expected_key_values
10161 32 : .get_mut(&key)
10162 32 : .expect("An image exists for each key")
10163 32 : .push_str(delta.as_str());
10164 32 : }
10165 40 : delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
10166 4 : }
10167 4 :
10168 4 : delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
10169 4 :
10170 4 : assert!(
10171 4 : nested_image_layer_lsn > delta_layer_start_lsn
10172 4 : && nested_image_layer_lsn < delta_layer_end_lsn
10173 4 : );
10174 4 :
10175 4 : let tline = tenant
10176 4 : .create_test_timeline_with_layers(
10177 4 : TIMELINE_ID,
10178 4 : baseline_image_layer_lsn,
10179 4 : DEFAULT_PG_VERSION,
10180 4 : &ctx,
10181 4 : vec![DeltaLayerTestDesc::new_with_inferred_key_range(
10182 4 : delta_layer_start_lsn..delta_layer_end_lsn,
10183 4 : delta_layer_spec,
10184 4 : )], // delta layers
10185 4 : vec![
10186 4 : (baseline_image_layer_lsn, baseline_img_layer),
10187 4 : (nested_image_layer_lsn, nested_img_layer),
10188 4 : ], // image layers
10189 4 : delta_layer_end_lsn,
10190 4 : )
10191 4 : .await?;
10192 4 :
10193 4 : let keyspace = KeySpace::single(get_key(0)..get_key(10));
10194 4 : let results = tline
10195 4 : .get_vectored(
10196 4 : keyspace,
10197 4 : delta_layer_end_lsn,
10198 4 : IoConcurrency::sequential(),
10199 4 : &ctx,
10200 4 : )
10201 4 : .await
10202 4 : .expect("No vectored errors");
10203 44 : for (key, res) in results {
10204 40 : let value = res.expect("No key errors");
10205 40 : let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
10206 40 : assert_eq!(value, Bytes::from(expected_value));
10207 4 : }
10208 4 :
10209 4 : Ok(())
10210 4 : }
10211 :
10212 428 : fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
10213 428 : (
10214 428 : k1.is_delta,
10215 428 : k1.key_range.start,
10216 428 : k1.key_range.end,
10217 428 : k1.lsn_range.start,
10218 428 : k1.lsn_range.end,
10219 428 : )
10220 428 : .cmp(&(
10221 428 : k2.is_delta,
10222 428 : k2.key_range.start,
10223 428 : k2.key_range.end,
10224 428 : k2.lsn_range.start,
10225 428 : k2.lsn_range.end,
10226 428 : ))
10227 428 : }
10228 :
10229 48 : async fn inspect_and_sort(
10230 48 : tline: &Arc<Timeline>,
10231 48 : filter: Option<std::ops::Range<Key>>,
10232 48 : ) -> Vec<PersistentLayerKey> {
10233 48 : let mut all_layers = tline.inspect_historic_layers().await.unwrap();
10234 48 : if let Some(filter) = filter {
10235 216 : all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
10236 44 : }
10237 48 : all_layers.sort_by(sort_layer_key);
10238 48 : all_layers
10239 48 : }
10240 :
10241 : #[cfg(feature = "testing")]
10242 44 : fn check_layer_map_key_eq(
10243 44 : mut left: Vec<PersistentLayerKey>,
10244 44 : mut right: Vec<PersistentLayerKey>,
10245 44 : ) {
10246 44 : left.sort_by(sort_layer_key);
10247 44 : right.sort_by(sort_layer_key);
10248 44 : if left != right {
10249 0 : eprintln!("---LEFT---");
10250 0 : for left in left.iter() {
10251 0 : eprintln!("{}", left);
10252 0 : }
10253 0 : eprintln!("---RIGHT---");
10254 0 : for right in right.iter() {
10255 0 : eprintln!("{}", right);
10256 0 : }
10257 0 : assert_eq!(left, right);
10258 44 : }
10259 44 : }
10260 :
10261 : #[cfg(feature = "testing")]
10262 : #[tokio::test]
10263 4 : async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
10264 4 : let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
10265 4 : let (tenant, ctx) = harness.load().await;
10266 4 :
10267 364 : fn get_key(id: u32) -> Key {
10268 364 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
10269 364 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
10270 364 : key.field6 = id;
10271 364 : key
10272 364 : }
10273 4 :
10274 4 : // img layer at 0x10
10275 4 : let img_layer = (0..10)
10276 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10277 4 : .collect_vec();
10278 4 :
10279 4 : let delta1 = vec![
10280 4 : (
10281 4 : get_key(1),
10282 4 : Lsn(0x20),
10283 4 : Value::Image(Bytes::from("value 1@0x20")),
10284 4 : ),
10285 4 : (
10286 4 : get_key(2),
10287 4 : Lsn(0x30),
10288 4 : Value::Image(Bytes::from("value 2@0x30")),
10289 4 : ),
10290 4 : (
10291 4 : get_key(3),
10292 4 : Lsn(0x40),
10293 4 : Value::Image(Bytes::from("value 3@0x40")),
10294 4 : ),
10295 4 : ];
10296 4 : let delta2 = vec![
10297 4 : (
10298 4 : get_key(5),
10299 4 : Lsn(0x20),
10300 4 : Value::Image(Bytes::from("value 5@0x20")),
10301 4 : ),
10302 4 : (
10303 4 : get_key(6),
10304 4 : Lsn(0x20),
10305 4 : Value::Image(Bytes::from("value 6@0x20")),
10306 4 : ),
10307 4 : ];
10308 4 : let delta3 = vec![
10309 4 : (
10310 4 : get_key(8),
10311 4 : Lsn(0x48),
10312 4 : Value::Image(Bytes::from("value 8@0x48")),
10313 4 : ),
10314 4 : (
10315 4 : get_key(9),
10316 4 : Lsn(0x48),
10317 4 : Value::Image(Bytes::from("value 9@0x48")),
10318 4 : ),
10319 4 : ];
10320 4 :
10321 4 : let tline = tenant
10322 4 : .create_test_timeline_with_layers(
10323 4 : TIMELINE_ID,
10324 4 : Lsn(0x10),
10325 4 : DEFAULT_PG_VERSION,
10326 4 : &ctx,
10327 4 : vec![
10328 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
10329 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
10330 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
10331 4 : ], // delta layers
10332 4 : vec![(Lsn(0x10), img_layer)], // image layers
10333 4 : Lsn(0x50),
10334 4 : )
10335 4 : .await?;
10336 4 :
10337 4 : {
10338 4 : tline
10339 4 : .latest_gc_cutoff_lsn
10340 4 : .lock_for_write()
10341 4 : .store_and_unlock(Lsn(0x30))
10342 4 : .wait()
10343 4 : .await;
10344 4 : // Update GC info
10345 4 : let mut guard = tline.gc_info.write().unwrap();
10346 4 : *guard = GcInfo {
10347 4 : retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
10348 4 : cutoffs: GcCutoffs {
10349 4 : time: Lsn(0x30),
10350 4 : space: Lsn(0x30),
10351 4 : },
10352 4 : leases: Default::default(),
10353 4 : within_ancestor_pitr: false,
10354 4 : };
10355 4 : }
10356 4 :
10357 4 : let cancel = CancellationToken::new();
10358 4 :
10359 4 : // Do a partial compaction on key range 0..2
10360 4 : tline
10361 4 : .compact_with_gc(
10362 4 : &cancel,
10363 4 : CompactOptions {
10364 4 : flags: EnumSet::new(),
10365 4 : compact_key_range: Some((get_key(0)..get_key(2)).into()),
10366 4 : ..Default::default()
10367 4 : },
10368 4 : &ctx,
10369 4 : )
10370 4 : .await
10371 4 : .unwrap();
10372 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10373 4 : check_layer_map_key_eq(
10374 4 : all_layers,
10375 4 : vec![
10376 4 : // newly-generated image layer for the partial compaction range 0-2
10377 4 : PersistentLayerKey {
10378 4 : key_range: get_key(0)..get_key(2),
10379 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10380 4 : is_delta: false,
10381 4 : },
10382 4 : PersistentLayerKey {
10383 4 : key_range: get_key(0)..get_key(10),
10384 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10385 4 : is_delta: false,
10386 4 : },
10387 4 : // delta1 is split and the second part is rewritten
10388 4 : PersistentLayerKey {
10389 4 : key_range: get_key(2)..get_key(4),
10390 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10391 4 : is_delta: true,
10392 4 : },
10393 4 : PersistentLayerKey {
10394 4 : key_range: get_key(5)..get_key(7),
10395 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10396 4 : is_delta: true,
10397 4 : },
10398 4 : PersistentLayerKey {
10399 4 : key_range: get_key(8)..get_key(10),
10400 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10401 4 : is_delta: true,
10402 4 : },
10403 4 : ],
10404 4 : );
10405 4 :
10406 4 : // Do a partial compaction on key range 2..4
10407 4 : tline
10408 4 : .compact_with_gc(
10409 4 : &cancel,
10410 4 : CompactOptions {
10411 4 : flags: EnumSet::new(),
10412 4 : compact_key_range: Some((get_key(2)..get_key(4)).into()),
10413 4 : ..Default::default()
10414 4 : },
10415 4 : &ctx,
10416 4 : )
10417 4 : .await
10418 4 : .unwrap();
10419 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10420 4 : check_layer_map_key_eq(
10421 4 : all_layers,
10422 4 : vec![
10423 4 : PersistentLayerKey {
10424 4 : key_range: get_key(0)..get_key(2),
10425 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10426 4 : is_delta: false,
10427 4 : },
10428 4 : PersistentLayerKey {
10429 4 : key_range: get_key(0)..get_key(10),
10430 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10431 4 : is_delta: false,
10432 4 : },
10433 4 : // image layer generated for the compaction range 2-4
10434 4 : PersistentLayerKey {
10435 4 : key_range: get_key(2)..get_key(4),
10436 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10437 4 : is_delta: false,
10438 4 : },
10439 4 : // we have key2/key3 above the retain_lsn, so we still need this delta layer
10440 4 : PersistentLayerKey {
10441 4 : key_range: get_key(2)..get_key(4),
10442 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10443 4 : is_delta: true,
10444 4 : },
10445 4 : PersistentLayerKey {
10446 4 : key_range: get_key(5)..get_key(7),
10447 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10448 4 : is_delta: true,
10449 4 : },
10450 4 : PersistentLayerKey {
10451 4 : key_range: get_key(8)..get_key(10),
10452 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10453 4 : is_delta: true,
10454 4 : },
10455 4 : ],
10456 4 : );
10457 4 :
10458 4 : // Do a partial compaction on key range 4..9
10459 4 : tline
10460 4 : .compact_with_gc(
10461 4 : &cancel,
10462 4 : CompactOptions {
10463 4 : flags: EnumSet::new(),
10464 4 : compact_key_range: Some((get_key(4)..get_key(9)).into()),
10465 4 : ..Default::default()
10466 4 : },
10467 4 : &ctx,
10468 4 : )
10469 4 : .await
10470 4 : .unwrap();
10471 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10472 4 : check_layer_map_key_eq(
10473 4 : all_layers,
10474 4 : vec![
10475 4 : PersistentLayerKey {
10476 4 : key_range: get_key(0)..get_key(2),
10477 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10478 4 : is_delta: false,
10479 4 : },
10480 4 : PersistentLayerKey {
10481 4 : key_range: get_key(0)..get_key(10),
10482 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10483 4 : is_delta: false,
10484 4 : },
10485 4 : PersistentLayerKey {
10486 4 : key_range: get_key(2)..get_key(4),
10487 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10488 4 : is_delta: false,
10489 4 : },
10490 4 : PersistentLayerKey {
10491 4 : key_range: get_key(2)..get_key(4),
10492 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10493 4 : is_delta: true,
10494 4 : },
10495 4 : // image layer generated for this compaction range
10496 4 : PersistentLayerKey {
10497 4 : key_range: get_key(4)..get_key(9),
10498 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10499 4 : is_delta: false,
10500 4 : },
10501 4 : PersistentLayerKey {
10502 4 : key_range: get_key(8)..get_key(10),
10503 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10504 4 : is_delta: true,
10505 4 : },
10506 4 : ],
10507 4 : );
10508 4 :
10509 4 : // Do a partial compaction on key range 9..10
10510 4 : tline
10511 4 : .compact_with_gc(
10512 4 : &cancel,
10513 4 : CompactOptions {
10514 4 : flags: EnumSet::new(),
10515 4 : compact_key_range: Some((get_key(9)..get_key(10)).into()),
10516 4 : ..Default::default()
10517 4 : },
10518 4 : &ctx,
10519 4 : )
10520 4 : .await
10521 4 : .unwrap();
10522 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10523 4 : check_layer_map_key_eq(
10524 4 : all_layers,
10525 4 : vec![
10526 4 : PersistentLayerKey {
10527 4 : key_range: get_key(0)..get_key(2),
10528 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10529 4 : is_delta: false,
10530 4 : },
10531 4 : PersistentLayerKey {
10532 4 : key_range: get_key(0)..get_key(10),
10533 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10534 4 : is_delta: false,
10535 4 : },
10536 4 : PersistentLayerKey {
10537 4 : key_range: get_key(2)..get_key(4),
10538 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10539 4 : is_delta: false,
10540 4 : },
10541 4 : PersistentLayerKey {
10542 4 : key_range: get_key(2)..get_key(4),
10543 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10544 4 : is_delta: true,
10545 4 : },
10546 4 : PersistentLayerKey {
10547 4 : key_range: get_key(4)..get_key(9),
10548 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10549 4 : is_delta: false,
10550 4 : },
10551 4 : // image layer generated for the compaction range
10552 4 : PersistentLayerKey {
10553 4 : key_range: get_key(9)..get_key(10),
10554 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10555 4 : is_delta: false,
10556 4 : },
10557 4 : PersistentLayerKey {
10558 4 : key_range: get_key(8)..get_key(10),
10559 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10560 4 : is_delta: true,
10561 4 : },
10562 4 : ],
10563 4 : );
10564 4 :
10565 4 : // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
10566 4 : tline
10567 4 : .compact_with_gc(
10568 4 : &cancel,
10569 4 : CompactOptions {
10570 4 : flags: EnumSet::new(),
10571 4 : compact_key_range: Some((get_key(0)..get_key(10)).into()),
10572 4 : ..Default::default()
10573 4 : },
10574 4 : &ctx,
10575 4 : )
10576 4 : .await
10577 4 : .unwrap();
10578 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10579 4 : check_layer_map_key_eq(
10580 4 : all_layers,
10581 4 : vec![
10582 4 : // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
10583 4 : PersistentLayerKey {
10584 4 : key_range: get_key(0)..get_key(10),
10585 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10586 4 : is_delta: false,
10587 4 : },
10588 4 : PersistentLayerKey {
10589 4 : key_range: get_key(2)..get_key(4),
10590 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10591 4 : is_delta: true,
10592 4 : },
10593 4 : PersistentLayerKey {
10594 4 : key_range: get_key(8)..get_key(10),
10595 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10596 4 : is_delta: true,
10597 4 : },
10598 4 : ],
10599 4 : );
10600 4 : Ok(())
10601 4 : }
10602 :
10603 : #[cfg(feature = "testing")]
10604 : #[tokio::test]
10605 4 : async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
10606 4 : let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
10607 4 : .await
10608 4 : .unwrap();
10609 4 : let (tenant, ctx) = harness.load().await;
10610 4 : let tline_parent = tenant
10611 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
10612 4 : .await
10613 4 : .unwrap();
10614 4 : let tline_child = tenant
10615 4 : .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
10616 4 : .await
10617 4 : .unwrap();
10618 4 : {
10619 4 : let gc_info_parent = tline_parent.gc_info.read().unwrap();
10620 4 : assert_eq!(
10621 4 : gc_info_parent.retain_lsns,
10622 4 : vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
10623 4 : );
10624 4 : }
10625 4 : // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
10626 4 : tline_child
10627 4 : .remote_client
10628 4 : .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
10629 4 : .unwrap();
10630 4 : tline_child.remote_client.wait_completion().await.unwrap();
10631 4 : offload_timeline(&tenant, &tline_child)
10632 4 : .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
10633 4 : .await.unwrap();
10634 4 : let child_timeline_id = tline_child.timeline_id;
10635 4 : Arc::try_unwrap(tline_child).unwrap();
10636 4 :
10637 4 : {
10638 4 : let gc_info_parent = tline_parent.gc_info.read().unwrap();
10639 4 : assert_eq!(
10640 4 : gc_info_parent.retain_lsns,
10641 4 : vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
10642 4 : );
10643 4 : }
10644 4 :
10645 4 : tenant
10646 4 : .get_offloaded_timeline(child_timeline_id)
10647 4 : .unwrap()
10648 4 : .defuse_for_tenant_drop();
10649 4 :
10650 4 : Ok(())
10651 4 : }
10652 :
10653 : #[cfg(feature = "testing")]
10654 : #[tokio::test]
10655 4 : async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
10656 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
10657 4 : let (tenant, ctx) = harness.load().await;
10658 4 :
10659 592 : fn get_key(id: u32) -> Key {
10660 592 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
10661 592 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
10662 592 : key.field6 = id;
10663 592 : key
10664 592 : }
10665 4 :
10666 4 : let img_layer = (0..10)
10667 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10668 4 : .collect_vec();
10669 4 :
10670 4 : let delta1 = vec![(
10671 4 : get_key(1),
10672 4 : Lsn(0x20),
10673 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10674 4 : )];
10675 4 : let delta4 = vec![(
10676 4 : get_key(1),
10677 4 : Lsn(0x28),
10678 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
10679 4 : )];
10680 4 : let delta2 = vec![
10681 4 : (
10682 4 : get_key(1),
10683 4 : Lsn(0x30),
10684 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
10685 4 : ),
10686 4 : (
10687 4 : get_key(1),
10688 4 : Lsn(0x38),
10689 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
10690 4 : ),
10691 4 : ];
10692 4 : let delta3 = vec![
10693 4 : (
10694 4 : get_key(8),
10695 4 : Lsn(0x48),
10696 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10697 4 : ),
10698 4 : (
10699 4 : get_key(9),
10700 4 : Lsn(0x48),
10701 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10702 4 : ),
10703 4 : ];
10704 4 :
10705 4 : let tline = tenant
10706 4 : .create_test_timeline_with_layers(
10707 4 : TIMELINE_ID,
10708 4 : Lsn(0x10),
10709 4 : DEFAULT_PG_VERSION,
10710 4 : &ctx,
10711 4 : vec![
10712 4 : // delta1/2/4 only contain a single key but multiple updates
10713 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
10714 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
10715 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
10716 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
10717 4 : ], // delta layers
10718 4 : vec![(Lsn(0x10), img_layer)], // image layers
10719 4 : Lsn(0x50),
10720 4 : )
10721 4 : .await?;
10722 4 : {
10723 4 : tline
10724 4 : .latest_gc_cutoff_lsn
10725 4 : .lock_for_write()
10726 4 : .store_and_unlock(Lsn(0x30))
10727 4 : .wait()
10728 4 : .await;
10729 4 : // Update GC info
10730 4 : let mut guard = tline.gc_info.write().unwrap();
10731 4 : *guard = GcInfo {
10732 4 : retain_lsns: vec![
10733 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
10734 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
10735 4 : ],
10736 4 : cutoffs: GcCutoffs {
10737 4 : time: Lsn(0x30),
10738 4 : space: Lsn(0x30),
10739 4 : },
10740 4 : leases: Default::default(),
10741 4 : within_ancestor_pitr: false,
10742 4 : };
10743 4 : }
10744 4 :
10745 4 : let expected_result = [
10746 4 : Bytes::from_static(b"value 0@0x10"),
10747 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
10748 4 : Bytes::from_static(b"value 2@0x10"),
10749 4 : Bytes::from_static(b"value 3@0x10"),
10750 4 : Bytes::from_static(b"value 4@0x10"),
10751 4 : Bytes::from_static(b"value 5@0x10"),
10752 4 : Bytes::from_static(b"value 6@0x10"),
10753 4 : Bytes::from_static(b"value 7@0x10"),
10754 4 : Bytes::from_static(b"value 8@0x10@0x48"),
10755 4 : Bytes::from_static(b"value 9@0x10@0x48"),
10756 4 : ];
10757 4 :
10758 4 : let expected_result_at_gc_horizon = [
10759 4 : Bytes::from_static(b"value 0@0x10"),
10760 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
10761 4 : Bytes::from_static(b"value 2@0x10"),
10762 4 : Bytes::from_static(b"value 3@0x10"),
10763 4 : Bytes::from_static(b"value 4@0x10"),
10764 4 : Bytes::from_static(b"value 5@0x10"),
10765 4 : Bytes::from_static(b"value 6@0x10"),
10766 4 : Bytes::from_static(b"value 7@0x10"),
10767 4 : Bytes::from_static(b"value 8@0x10"),
10768 4 : Bytes::from_static(b"value 9@0x10"),
10769 4 : ];
10770 4 :
10771 4 : let expected_result_at_lsn_20 = [
10772 4 : Bytes::from_static(b"value 0@0x10"),
10773 4 : Bytes::from_static(b"value 1@0x10@0x20"),
10774 4 : Bytes::from_static(b"value 2@0x10"),
10775 4 : Bytes::from_static(b"value 3@0x10"),
10776 4 : Bytes::from_static(b"value 4@0x10"),
10777 4 : Bytes::from_static(b"value 5@0x10"),
10778 4 : Bytes::from_static(b"value 6@0x10"),
10779 4 : Bytes::from_static(b"value 7@0x10"),
10780 4 : Bytes::from_static(b"value 8@0x10"),
10781 4 : Bytes::from_static(b"value 9@0x10"),
10782 4 : ];
10783 4 :
10784 4 : let expected_result_at_lsn_10 = [
10785 4 : Bytes::from_static(b"value 0@0x10"),
10786 4 : Bytes::from_static(b"value 1@0x10"),
10787 4 : Bytes::from_static(b"value 2@0x10"),
10788 4 : Bytes::from_static(b"value 3@0x10"),
10789 4 : Bytes::from_static(b"value 4@0x10"),
10790 4 : Bytes::from_static(b"value 5@0x10"),
10791 4 : Bytes::from_static(b"value 6@0x10"),
10792 4 : Bytes::from_static(b"value 7@0x10"),
10793 4 : Bytes::from_static(b"value 8@0x10"),
10794 4 : Bytes::from_static(b"value 9@0x10"),
10795 4 : ];
10796 4 :
10797 12 : let verify_result = || async {
10798 12 : let gc_horizon = {
10799 12 : let gc_info = tline.gc_info.read().unwrap();
10800 12 : gc_info.cutoffs.time
10801 4 : };
10802 132 : for idx in 0..10 {
10803 120 : assert_eq!(
10804 120 : tline
10805 120 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
10806 120 : .await
10807 120 : .unwrap(),
10808 120 : &expected_result[idx]
10809 4 : );
10810 120 : assert_eq!(
10811 120 : tline
10812 120 : .get(get_key(idx as u32), gc_horizon, &ctx)
10813 120 : .await
10814 120 : .unwrap(),
10815 120 : &expected_result_at_gc_horizon[idx]
10816 4 : );
10817 120 : assert_eq!(
10818 120 : tline
10819 120 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
10820 120 : .await
10821 120 : .unwrap(),
10822 120 : &expected_result_at_lsn_20[idx]
10823 4 : );
10824 120 : assert_eq!(
10825 120 : tline
10826 120 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
10827 120 : .await
10828 120 : .unwrap(),
10829 120 : &expected_result_at_lsn_10[idx]
10830 4 : );
10831 4 : }
10832 24 : };
10833 4 :
10834 4 : verify_result().await;
10835 4 :
10836 4 : let cancel = CancellationToken::new();
10837 4 : tline
10838 4 : .compact_with_gc(
10839 4 : &cancel,
10840 4 : CompactOptions {
10841 4 : compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
10842 4 : ..Default::default()
10843 4 : },
10844 4 : &ctx,
10845 4 : )
10846 4 : .await
10847 4 : .unwrap();
10848 4 : verify_result().await;
10849 4 :
10850 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10851 4 : check_layer_map_key_eq(
10852 4 : all_layers,
10853 4 : vec![
10854 4 : // The original image layer, not compacted
10855 4 : PersistentLayerKey {
10856 4 : key_range: get_key(0)..get_key(10),
10857 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10858 4 : is_delta: false,
10859 4 : },
10860 4 : // Delta layer below the specified above_lsn not compacted
10861 4 : PersistentLayerKey {
10862 4 : key_range: get_key(1)..get_key(2),
10863 4 : lsn_range: Lsn(0x20)..Lsn(0x28),
10864 4 : is_delta: true,
10865 4 : },
10866 4 : // Delta layer compacted above the LSN
10867 4 : PersistentLayerKey {
10868 4 : key_range: get_key(1)..get_key(10),
10869 4 : lsn_range: Lsn(0x28)..Lsn(0x50),
10870 4 : is_delta: true,
10871 4 : },
10872 4 : ],
10873 4 : );
10874 4 :
10875 4 : // compact again
10876 4 : tline
10877 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
10878 4 : .await
10879 4 : .unwrap();
10880 4 : verify_result().await;
10881 4 :
10882 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10883 4 : check_layer_map_key_eq(
10884 4 : all_layers,
10885 4 : vec![
10886 4 : // The compacted image layer (full key range)
10887 4 : PersistentLayerKey {
10888 4 : key_range: Key::MIN..Key::MAX,
10889 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10890 4 : is_delta: false,
10891 4 : },
10892 4 : // All other data in the delta layer
10893 4 : PersistentLayerKey {
10894 4 : key_range: get_key(1)..get_key(10),
10895 4 : lsn_range: Lsn(0x10)..Lsn(0x50),
10896 4 : is_delta: true,
10897 4 : },
10898 4 : ],
10899 4 : );
10900 4 :
10901 4 : Ok(())
10902 4 : }
10903 :
10904 : #[cfg(feature = "testing")]
10905 : #[tokio::test]
10906 4 : async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
10907 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
10908 4 : let (tenant, ctx) = harness.load().await;
10909 4 :
10910 1016 : fn get_key(id: u32) -> Key {
10911 1016 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
10912 1016 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
10913 1016 : key.field6 = id;
10914 1016 : key
10915 1016 : }
10916 4 :
10917 4 : let img_layer = (0..10)
10918 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10919 4 : .collect_vec();
10920 4 :
10921 4 : let delta1 = vec![(
10922 4 : get_key(1),
10923 4 : Lsn(0x20),
10924 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10925 4 : )];
10926 4 : let delta4 = vec![(
10927 4 : get_key(1),
10928 4 : Lsn(0x28),
10929 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
10930 4 : )];
10931 4 : let delta2 = vec![
10932 4 : (
10933 4 : get_key(1),
10934 4 : Lsn(0x30),
10935 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
10936 4 : ),
10937 4 : (
10938 4 : get_key(1),
10939 4 : Lsn(0x38),
10940 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
10941 4 : ),
10942 4 : ];
10943 4 : let delta3 = vec![
10944 4 : (
10945 4 : get_key(8),
10946 4 : Lsn(0x48),
10947 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10948 4 : ),
10949 4 : (
10950 4 : get_key(9),
10951 4 : Lsn(0x48),
10952 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10953 4 : ),
10954 4 : ];
10955 4 :
10956 4 : let tline = tenant
10957 4 : .create_test_timeline_with_layers(
10958 4 : TIMELINE_ID,
10959 4 : Lsn(0x10),
10960 4 : DEFAULT_PG_VERSION,
10961 4 : &ctx,
10962 4 : vec![
10963 4 : // delta1/2/4 only contain a single key but multiple updates
10964 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
10965 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
10966 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
10967 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
10968 4 : ], // delta layers
10969 4 : vec![(Lsn(0x10), img_layer)], // image layers
10970 4 : Lsn(0x50),
10971 4 : )
10972 4 : .await?;
10973 4 : {
10974 4 : tline
10975 4 : .latest_gc_cutoff_lsn
10976 4 : .lock_for_write()
10977 4 : .store_and_unlock(Lsn(0x30))
10978 4 : .wait()
10979 4 : .await;
10980 4 : // Update GC info
10981 4 : let mut guard = tline.gc_info.write().unwrap();
10982 4 : *guard = GcInfo {
10983 4 : retain_lsns: vec![
10984 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
10985 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
10986 4 : ],
10987 4 : cutoffs: GcCutoffs {
10988 4 : time: Lsn(0x30),
10989 4 : space: Lsn(0x30),
10990 4 : },
10991 4 : leases: Default::default(),
10992 4 : within_ancestor_pitr: false,
10993 4 : };
10994 4 : }
10995 4 :
10996 4 : let expected_result = [
10997 4 : Bytes::from_static(b"value 0@0x10"),
10998 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
10999 4 : Bytes::from_static(b"value 2@0x10"),
11000 4 : Bytes::from_static(b"value 3@0x10"),
11001 4 : Bytes::from_static(b"value 4@0x10"),
11002 4 : Bytes::from_static(b"value 5@0x10"),
11003 4 : Bytes::from_static(b"value 6@0x10"),
11004 4 : Bytes::from_static(b"value 7@0x10"),
11005 4 : Bytes::from_static(b"value 8@0x10@0x48"),
11006 4 : Bytes::from_static(b"value 9@0x10@0x48"),
11007 4 : ];
11008 4 :
11009 4 : let expected_result_at_gc_horizon = [
11010 4 : Bytes::from_static(b"value 0@0x10"),
11011 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
11012 4 : Bytes::from_static(b"value 2@0x10"),
11013 4 : Bytes::from_static(b"value 3@0x10"),
11014 4 : Bytes::from_static(b"value 4@0x10"),
11015 4 : Bytes::from_static(b"value 5@0x10"),
11016 4 : Bytes::from_static(b"value 6@0x10"),
11017 4 : Bytes::from_static(b"value 7@0x10"),
11018 4 : Bytes::from_static(b"value 8@0x10"),
11019 4 : Bytes::from_static(b"value 9@0x10"),
11020 4 : ];
11021 4 :
11022 4 : let expected_result_at_lsn_20 = [
11023 4 : Bytes::from_static(b"value 0@0x10"),
11024 4 : Bytes::from_static(b"value 1@0x10@0x20"),
11025 4 : Bytes::from_static(b"value 2@0x10"),
11026 4 : Bytes::from_static(b"value 3@0x10"),
11027 4 : Bytes::from_static(b"value 4@0x10"),
11028 4 : Bytes::from_static(b"value 5@0x10"),
11029 4 : Bytes::from_static(b"value 6@0x10"),
11030 4 : Bytes::from_static(b"value 7@0x10"),
11031 4 : Bytes::from_static(b"value 8@0x10"),
11032 4 : Bytes::from_static(b"value 9@0x10"),
11033 4 : ];
11034 4 :
11035 4 : let expected_result_at_lsn_10 = [
11036 4 : Bytes::from_static(b"value 0@0x10"),
11037 4 : Bytes::from_static(b"value 1@0x10"),
11038 4 : Bytes::from_static(b"value 2@0x10"),
11039 4 : Bytes::from_static(b"value 3@0x10"),
11040 4 : Bytes::from_static(b"value 4@0x10"),
11041 4 : Bytes::from_static(b"value 5@0x10"),
11042 4 : Bytes::from_static(b"value 6@0x10"),
11043 4 : Bytes::from_static(b"value 7@0x10"),
11044 4 : Bytes::from_static(b"value 8@0x10"),
11045 4 : Bytes::from_static(b"value 9@0x10"),
11046 4 : ];
11047 4 :
11048 20 : let verify_result = || async {
11049 20 : let gc_horizon = {
11050 20 : let gc_info = tline.gc_info.read().unwrap();
11051 20 : gc_info.cutoffs.time
11052 4 : };
11053 220 : for idx in 0..10 {
11054 200 : assert_eq!(
11055 200 : tline
11056 200 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
11057 200 : .await
11058 200 : .unwrap(),
11059 200 : &expected_result[idx]
11060 4 : );
11061 200 : assert_eq!(
11062 200 : tline
11063 200 : .get(get_key(idx as u32), gc_horizon, &ctx)
11064 200 : .await
11065 200 : .unwrap(),
11066 200 : &expected_result_at_gc_horizon[idx]
11067 4 : );
11068 200 : assert_eq!(
11069 200 : tline
11070 200 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
11071 200 : .await
11072 200 : .unwrap(),
11073 200 : &expected_result_at_lsn_20[idx]
11074 4 : );
11075 200 : assert_eq!(
11076 200 : tline
11077 200 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
11078 200 : .await
11079 200 : .unwrap(),
11080 200 : &expected_result_at_lsn_10[idx]
11081 4 : );
11082 4 : }
11083 40 : };
11084 4 :
11085 4 : verify_result().await;
11086 4 :
11087 4 : let cancel = CancellationToken::new();
11088 4 :
11089 4 : tline
11090 4 : .compact_with_gc(
11091 4 : &cancel,
11092 4 : CompactOptions {
11093 4 : compact_key_range: Some((get_key(0)..get_key(2)).into()),
11094 4 : compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
11095 4 : ..Default::default()
11096 4 : },
11097 4 : &ctx,
11098 4 : )
11099 4 : .await
11100 4 : .unwrap();
11101 4 : verify_result().await;
11102 4 :
11103 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11104 4 : check_layer_map_key_eq(
11105 4 : all_layers,
11106 4 : vec![
11107 4 : // The original image layer, not compacted
11108 4 : PersistentLayerKey {
11109 4 : key_range: get_key(0)..get_key(10),
11110 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11111 4 : is_delta: false,
11112 4 : },
11113 4 : // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
11114 4 : // the layer 0x28-0x30 into one.
11115 4 : PersistentLayerKey {
11116 4 : key_range: get_key(1)..get_key(2),
11117 4 : lsn_range: Lsn(0x20)..Lsn(0x30),
11118 4 : is_delta: true,
11119 4 : },
11120 4 : // Above the upper bound and untouched
11121 4 : PersistentLayerKey {
11122 4 : key_range: get_key(1)..get_key(2),
11123 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11124 4 : is_delta: true,
11125 4 : },
11126 4 : // This layer is untouched
11127 4 : PersistentLayerKey {
11128 4 : key_range: get_key(8)..get_key(10),
11129 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11130 4 : is_delta: true,
11131 4 : },
11132 4 : ],
11133 4 : );
11134 4 :
11135 4 : tline
11136 4 : .compact_with_gc(
11137 4 : &cancel,
11138 4 : CompactOptions {
11139 4 : compact_key_range: Some((get_key(3)..get_key(8)).into()),
11140 4 : compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
11141 4 : ..Default::default()
11142 4 : },
11143 4 : &ctx,
11144 4 : )
11145 4 : .await
11146 4 : .unwrap();
11147 4 : verify_result().await;
11148 4 :
11149 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11150 4 : check_layer_map_key_eq(
11151 4 : all_layers,
11152 4 : vec![
11153 4 : // The original image layer, not compacted
11154 4 : PersistentLayerKey {
11155 4 : key_range: get_key(0)..get_key(10),
11156 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11157 4 : is_delta: false,
11158 4 : },
11159 4 : // Not in the compaction key range, uncompacted
11160 4 : PersistentLayerKey {
11161 4 : key_range: get_key(1)..get_key(2),
11162 4 : lsn_range: Lsn(0x20)..Lsn(0x30),
11163 4 : is_delta: true,
11164 4 : },
11165 4 : // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
11166 4 : PersistentLayerKey {
11167 4 : key_range: get_key(1)..get_key(2),
11168 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11169 4 : is_delta: true,
11170 4 : },
11171 4 : // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
11172 4 : // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
11173 4 : // becomes 0x50.
11174 4 : PersistentLayerKey {
11175 4 : key_range: get_key(8)..get_key(10),
11176 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11177 4 : is_delta: true,
11178 4 : },
11179 4 : ],
11180 4 : );
11181 4 :
11182 4 : // compact again
11183 4 : tline
11184 4 : .compact_with_gc(
11185 4 : &cancel,
11186 4 : CompactOptions {
11187 4 : compact_key_range: Some((get_key(0)..get_key(5)).into()),
11188 4 : compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
11189 4 : ..Default::default()
11190 4 : },
11191 4 : &ctx,
11192 4 : )
11193 4 : .await
11194 4 : .unwrap();
11195 4 : verify_result().await;
11196 4 :
11197 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11198 4 : check_layer_map_key_eq(
11199 4 : all_layers,
11200 4 : vec![
11201 4 : // The original image layer, not compacted
11202 4 : PersistentLayerKey {
11203 4 : key_range: get_key(0)..get_key(10),
11204 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11205 4 : is_delta: false,
11206 4 : },
11207 4 : // The range gets compacted
11208 4 : PersistentLayerKey {
11209 4 : key_range: get_key(1)..get_key(2),
11210 4 : lsn_range: Lsn(0x20)..Lsn(0x50),
11211 4 : is_delta: true,
11212 4 : },
11213 4 : // Not touched during this iteration of compaction
11214 4 : PersistentLayerKey {
11215 4 : key_range: get_key(8)..get_key(10),
11216 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11217 4 : is_delta: true,
11218 4 : },
11219 4 : ],
11220 4 : );
11221 4 :
11222 4 : // final full compaction
11223 4 : tline
11224 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
11225 4 : .await
11226 4 : .unwrap();
11227 4 : verify_result().await;
11228 4 :
11229 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11230 4 : check_layer_map_key_eq(
11231 4 : all_layers,
11232 4 : vec![
11233 4 : // The compacted image layer (full key range)
11234 4 : PersistentLayerKey {
11235 4 : key_range: Key::MIN..Key::MAX,
11236 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11237 4 : is_delta: false,
11238 4 : },
11239 4 : // All other data in the delta layer
11240 4 : PersistentLayerKey {
11241 4 : key_range: get_key(1)..get_key(10),
11242 4 : lsn_range: Lsn(0x10)..Lsn(0x50),
11243 4 : is_delta: true,
11244 4 : },
11245 4 : ],
11246 4 : );
11247 4 :
11248 4 : Ok(())
11249 4 : }
11250 : }
|