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 pageserver_api::models;
24 : use pageserver_api::models::LsnLease;
25 : use pageserver_api::models::TimelineArchivalState;
26 : use pageserver_api::models::TimelineState;
27 : use pageserver_api::models::TopTenantShardItem;
28 : use pageserver_api::models::WalRedoManagerStatus;
29 : use pageserver_api::shard::ShardIdentity;
30 : use pageserver_api::shard::ShardStripeSize;
31 : use pageserver_api::shard::TenantShardId;
32 : use remote_storage::DownloadError;
33 : use remote_storage::GenericRemoteStorage;
34 : use remote_storage::TimeoutOrCancel;
35 : use remote_timeline_client::manifest::{
36 : OffloadedTimelineManifest, TenantManifest, LATEST_TENANT_MANIFEST_VERSION,
37 : };
38 : use remote_timeline_client::UploadQueueNotReadyError;
39 : use std::collections::BTreeMap;
40 : use std::collections::VecDeque;
41 : use std::fmt;
42 : use std::future::Future;
43 : use std::sync::atomic::AtomicBool;
44 : use std::sync::Weak;
45 : use std::time::SystemTime;
46 : use storage_broker::BrokerClientChannel;
47 : use timeline::compaction::GcCompactJob;
48 : use timeline::compaction::ScheduledCompactionTask;
49 : use timeline::import_pgdata;
50 : use timeline::offload::offload_timeline;
51 : use timeline::offload::OffloadError;
52 : use timeline::CompactFlags;
53 : use timeline::CompactOptions;
54 : use timeline::CompactionError;
55 : use timeline::ShutdownMode;
56 : use tokio::io::BufReader;
57 : use tokio::sync::watch;
58 : use tokio::task::JoinSet;
59 : use tokio_util::sync::CancellationToken;
60 : use tracing::*;
61 : use upload_queue::NotInitialized;
62 : use utils::backoff;
63 : use utils::circuit_breaker::CircuitBreaker;
64 : use utils::completion;
65 : use utils::crashsafe::path_with_suffix_extension;
66 : use utils::failpoint_support;
67 : use utils::fs_ext;
68 : use utils::pausable_failpoint;
69 : use utils::sync::gate::Gate;
70 : use utils::sync::gate::GateGuard;
71 : use utils::timeout::timeout_cancellable;
72 : use utils::timeout::TimeoutCancellableError;
73 : use utils::try_rcu::ArcSwapExt;
74 : use utils::zstd::create_zst_tarball;
75 : use utils::zstd::extract_zst_tarball;
76 :
77 : use self::config::AttachedLocationConfig;
78 : use self::config::AttachmentMode;
79 : use self::config::LocationConf;
80 : use self::config::TenantConf;
81 : use self::metadata::TimelineMetadata;
82 : use self::mgr::GetActiveTenantError;
83 : use self::mgr::GetTenantError;
84 : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
85 : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
86 : use self::timeline::uninit::TimelineCreateGuard;
87 : use self::timeline::uninit::TimelineExclusionError;
88 : use self::timeline::uninit::UninitializedTimeline;
89 : use self::timeline::EvictionTaskTenantState;
90 : use self::timeline::GcCutoffs;
91 : use self::timeline::TimelineDeleteProgress;
92 : use self::timeline::TimelineResources;
93 : use self::timeline::WaitLsnError;
94 : use crate::config::PageServerConf;
95 : use crate::context::{DownloadBehavior, RequestContext};
96 : use crate::deletion_queue::DeletionQueueClient;
97 : use crate::deletion_queue::DeletionQueueError;
98 : use crate::import_datadir;
99 : use crate::is_uninit_mark;
100 : use crate::l0_flush::L0FlushGlobalState;
101 : use crate::metrics::TENANT;
102 : use crate::metrics::{
103 : remove_tenant_metrics, BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN,
104 : TENANT_STATE_METRIC, TENANT_SYNTHETIC_SIZE_METRIC,
105 : };
106 : use crate::task_mgr;
107 : use crate::task_mgr::TaskKind;
108 : use crate::tenant::config::LocationMode;
109 : use crate::tenant::config::TenantConfOpt;
110 : use crate::tenant::gc_result::GcResult;
111 : pub use crate::tenant::remote_timeline_client::index::IndexPart;
112 : use crate::tenant::remote_timeline_client::remote_initdb_archive_path;
113 : use crate::tenant::remote_timeline_client::MaybeDeletedIndexPart;
114 : use crate::tenant::remote_timeline_client::INITDB_PATH;
115 : use crate::tenant::storage_layer::DeltaLayer;
116 : use crate::tenant::storage_layer::ImageLayer;
117 : use crate::walingest::WalLagCooldown;
118 : use crate::walredo;
119 : use crate::InitializationOrder;
120 : use std::collections::hash_map::Entry;
121 : use std::collections::HashMap;
122 : use std::collections::HashSet;
123 : use std::fmt::Debug;
124 : use std::fmt::Display;
125 : use std::fs;
126 : use std::fs::File;
127 : use std::sync::atomic::{AtomicU64, Ordering};
128 : use std::sync::Arc;
129 : use std::sync::Mutex;
130 : use std::time::{Duration, Instant};
131 :
132 : use crate::span;
133 : use crate::tenant::timeline::delete::DeleteTimelineFlow;
134 : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
135 : use crate::virtual_file::VirtualFile;
136 : use crate::walredo::PostgresRedoManager;
137 : use crate::TEMP_FILE_SUFFIX;
138 : use once_cell::sync::Lazy;
139 : pub use pageserver_api::models::TenantState;
140 : use tokio::sync::Semaphore;
141 :
142 0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
143 : use utils::{
144 : crashsafe,
145 : generation::Generation,
146 : id::TimelineId,
147 : lsn::{Lsn, RecordLsn},
148 : };
149 :
150 : pub mod blob_io;
151 : pub mod block_io;
152 : pub mod vectored_blob_io;
153 :
154 : pub mod disk_btree;
155 : pub(crate) mod ephemeral_file;
156 : pub mod layer_map;
157 :
158 : pub mod metadata;
159 : pub mod remote_timeline_client;
160 : pub mod storage_layer;
161 :
162 : pub mod checks;
163 : pub mod config;
164 : pub mod mgr;
165 : pub mod secondary;
166 : pub mod tasks;
167 : pub mod upload_queue;
168 :
169 : pub(crate) mod timeline;
170 :
171 : pub mod size;
172 :
173 : mod gc_block;
174 : mod gc_result;
175 : pub(crate) mod throttle;
176 :
177 : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
178 : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
179 :
180 : // re-export for use in walreceiver
181 : pub use crate::tenant::timeline::WalReceiverInfo;
182 :
183 : /// The "tenants" part of `tenants/<tenant>/timelines...`
184 : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
185 :
186 : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
187 : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
188 :
189 : /// References to shared objects that are passed into each tenant, such
190 : /// as the shared remote storage client and process initialization state.
191 : #[derive(Clone)]
192 : pub struct TenantSharedResources {
193 : pub broker_client: storage_broker::BrokerClientChannel,
194 : pub remote_storage: GenericRemoteStorage,
195 : pub deletion_queue_client: DeletionQueueClient,
196 : pub l0_flush_global_state: L0FlushGlobalState,
197 : }
198 :
199 : /// A [`Tenant`] is really an _attached_ tenant. The configuration
200 : /// for an attached tenant is a subset of the [`LocationConf`], represented
201 : /// in this struct.
202 : #[derive(Clone)]
203 : pub(super) struct AttachedTenantConf {
204 : tenant_conf: TenantConfOpt,
205 : location: AttachedLocationConfig,
206 : /// The deadline before which we are blocked from GC so that
207 : /// leases have a chance to be renewed.
208 : lsn_lease_deadline: Option<tokio::time::Instant>,
209 : }
210 :
211 : impl AttachedTenantConf {
212 196 : fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
213 : // Sets a deadline before which we cannot proceed to GC due to lsn lease.
214 : //
215 : // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
216 : // length, we guarantee that all the leases we granted before will have a chance to renew
217 : // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
218 196 : let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
219 196 : Some(
220 196 : tokio::time::Instant::now()
221 196 : + tenant_conf
222 196 : .lsn_lease_length
223 196 : .unwrap_or(LsnLease::DEFAULT_LENGTH),
224 196 : )
225 : } else {
226 : // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
227 : // because we don't do GC in these modes.
228 0 : None
229 : };
230 :
231 196 : Self {
232 196 : tenant_conf,
233 196 : location,
234 196 : lsn_lease_deadline,
235 196 : }
236 196 : }
237 :
238 196 : fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
239 196 : match &location_conf.mode {
240 196 : LocationMode::Attached(attach_conf) => {
241 196 : Ok(Self::new(location_conf.tenant_conf, *attach_conf))
242 : }
243 : LocationMode::Secondary(_) => {
244 0 : anyhow::bail!("Attempted to construct AttachedTenantConf from a LocationConf in secondary mode")
245 : }
246 : }
247 196 : }
248 :
249 762 : fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
250 762 : self.lsn_lease_deadline
251 762 : .map(|d| tokio::time::Instant::now() < d)
252 762 : .unwrap_or(false)
253 762 : }
254 : }
255 : struct TimelinePreload {
256 : timeline_id: TimelineId,
257 : client: RemoteTimelineClient,
258 : index_part: Result<MaybeDeletedIndexPart, DownloadError>,
259 : }
260 :
261 : pub(crate) struct TenantPreload {
262 : tenant_manifest: TenantManifest,
263 : /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
264 : timelines: HashMap<TimelineId, Option<TimelinePreload>>,
265 : }
266 :
267 : /// When we spawn a tenant, there is a special mode for tenant creation that
268 : /// avoids trying to read anything from remote storage.
269 : pub(crate) enum SpawnMode {
270 : /// Activate as soon as possible
271 : Eager,
272 : /// Lazy activation in the background, with the option to skip the queue if the need comes up
273 : Lazy,
274 : }
275 :
276 : ///
277 : /// Tenant consists of multiple timelines. Keep them in a hash table.
278 : ///
279 : pub struct Tenant {
280 : // Global pageserver config parameters
281 : pub conf: &'static PageServerConf,
282 :
283 : /// The value creation timestamp, used to measure activation delay, see:
284 : /// <https://github.com/neondatabase/neon/issues/4025>
285 : constructed_at: Instant,
286 :
287 : state: watch::Sender<TenantState>,
288 :
289 : // Overridden tenant-specific config parameters.
290 : // We keep TenantConfOpt sturct here to preserve the information
291 : // about parameters that are not set.
292 : // This is necessary to allow global config updates.
293 : tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
294 :
295 : tenant_shard_id: TenantShardId,
296 :
297 : // The detailed sharding information, beyond the number/count in tenant_shard_id
298 : shard_identity: ShardIdentity,
299 :
300 : /// The remote storage generation, used to protect S3 objects from split-brain.
301 : /// Does not change over the lifetime of the [`Tenant`] object.
302 : ///
303 : /// This duplicates the generation stored in LocationConf, but that structure is mutable:
304 : /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
305 : generation: Generation,
306 :
307 : timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
308 :
309 : /// During timeline creation, we first insert the TimelineId to the
310 : /// creating map, then `timelines`, then remove it from the creating map.
311 : /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
312 : timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
313 :
314 : /// Possibly offloaded and archived timelines
315 : /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
316 : timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
317 :
318 : /// Serialize writes of the tenant manifest to remote storage. If there are concurrent operations
319 : /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
320 : /// each other (this could be optimized to coalesce writes if necessary).
321 : ///
322 : /// The contents of the Mutex are the last manifest we successfully uploaded
323 : tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
324 :
325 : // This mutex prevents creation of new timelines during GC.
326 : // Adding yet another mutex (in addition to `timelines`) is needed because holding
327 : // `timelines` mutex during all GC iteration
328 : // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
329 : // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
330 : // timeout...
331 : gc_cs: tokio::sync::Mutex<()>,
332 : walredo_mgr: Option<Arc<WalRedoManager>>,
333 :
334 : // provides access to timeline data sitting in the remote storage
335 : pub(crate) remote_storage: GenericRemoteStorage,
336 :
337 : // Access to global deletion queue for when this tenant wants to schedule a deletion
338 : deletion_queue_client: DeletionQueueClient,
339 :
340 : /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
341 : cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
342 : cached_synthetic_tenant_size: Arc<AtomicU64>,
343 :
344 : eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
345 :
346 : /// Track repeated failures to compact, so that we can back off.
347 : /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
348 : compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
349 :
350 : /// Scheduled compaction tasks. Currently, this can only be populated by triggering
351 : /// a manual gc-compaction from the manual compaction API.
352 : scheduled_compaction_tasks:
353 : std::sync::Mutex<HashMap<TimelineId, VecDeque<ScheduledCompactionTask>>>,
354 :
355 : /// If the tenant is in Activating state, notify this to encourage it
356 : /// to proceed to Active as soon as possible, rather than waiting for lazy
357 : /// background warmup.
358 : pub(crate) activate_now_sem: tokio::sync::Semaphore,
359 :
360 : /// Time it took for the tenant to activate. Zero if not active yet.
361 : attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
362 :
363 : // Cancellation token fires when we have entered shutdown(). This is a parent of
364 : // Timelines' cancellation token.
365 : pub(crate) cancel: CancellationToken,
366 :
367 : // Users of the Tenant such as the page service must take this Gate to avoid
368 : // trying to use a Tenant which is shutting down.
369 : pub(crate) gate: Gate,
370 :
371 : /// Throttle applied at the top of [`Timeline::get`].
372 : /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
373 : pub(crate) pagestream_throttle:
374 : Arc<throttle::Throttle<crate::metrics::tenant_throttling::Pagestream>>,
375 :
376 : /// An ongoing timeline detach concurrency limiter.
377 : ///
378 : /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
379 : /// to have two running at the same time. A different one can be started if an earlier one
380 : /// has failed for whatever reason.
381 : ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
382 :
383 : /// `index_part.json` based gc blocking reason tracking.
384 : ///
385 : /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
386 : /// proceeding.
387 : pub(crate) gc_block: gc_block::GcBlock,
388 :
389 : l0_flush_global_state: L0FlushGlobalState,
390 : }
391 : impl std::fmt::Debug for Tenant {
392 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
393 0 : write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
394 0 : }
395 : }
396 :
397 : pub(crate) enum WalRedoManager {
398 : Prod(WalredoManagerId, PostgresRedoManager),
399 : #[cfg(test)]
400 : Test(harness::TestRedoManager),
401 : }
402 :
403 : #[derive(thiserror::Error, Debug)]
404 : #[error("pageserver is shutting down")]
405 : pub(crate) struct GlobalShutDown;
406 :
407 : impl WalRedoManager {
408 0 : pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
409 0 : let id = WalredoManagerId::next();
410 0 : let arc = Arc::new(Self::Prod(id, mgr));
411 0 : let mut guard = WALREDO_MANAGERS.lock().unwrap();
412 0 : match &mut *guard {
413 0 : Some(map) => {
414 0 : map.insert(id, Arc::downgrade(&arc));
415 0 : Ok(arc)
416 : }
417 0 : None => Err(GlobalShutDown),
418 : }
419 0 : }
420 : }
421 :
422 : impl Drop for WalRedoManager {
423 10 : fn drop(&mut self) {
424 10 : match self {
425 0 : Self::Prod(id, _) => {
426 0 : let mut guard = WALREDO_MANAGERS.lock().unwrap();
427 0 : if let Some(map) = &mut *guard {
428 0 : map.remove(id).expect("new() registers, drop() unregisters");
429 0 : }
430 : }
431 : #[cfg(test)]
432 10 : Self::Test(_) => {
433 10 : // Not applicable to test redo manager
434 10 : }
435 : }
436 10 : }
437 : }
438 :
439 : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
440 : /// the walredo processes outside of the regular order.
441 : ///
442 : /// This is necessary to work around a systemd bug where it freezes if there are
443 : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
444 : #[allow(clippy::type_complexity)]
445 : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
446 : Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
447 0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
448 : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
449 : pub(crate) struct WalredoManagerId(u64);
450 : impl WalredoManagerId {
451 0 : pub fn next() -> Self {
452 : static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
453 0 : let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
454 0 : if id == 0 {
455 0 : panic!("WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique");
456 0 : }
457 0 : Self(id)
458 0 : }
459 : }
460 :
461 : #[cfg(test)]
462 : impl From<harness::TestRedoManager> for WalRedoManager {
463 196 : fn from(mgr: harness::TestRedoManager) -> Self {
464 196 : Self::Test(mgr)
465 196 : }
466 : }
467 :
468 : impl WalRedoManager {
469 6 : pub(crate) async fn shutdown(&self) -> bool {
470 6 : match self {
471 0 : Self::Prod(_, mgr) => mgr.shutdown().await,
472 : #[cfg(test)]
473 : Self::Test(_) => {
474 : // Not applicable to test redo manager
475 6 : true
476 : }
477 : }
478 6 : }
479 :
480 0 : pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
481 0 : match self {
482 0 : Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
483 0 : #[cfg(test)]
484 0 : Self::Test(_) => {
485 0 : // Not applicable to test redo manager
486 0 : }
487 0 : }
488 0 : }
489 :
490 : /// # Cancel-Safety
491 : ///
492 : /// This method is cancellation-safe.
493 520 : pub async fn request_redo(
494 520 : &self,
495 520 : key: pageserver_api::key::Key,
496 520 : lsn: Lsn,
497 520 : base_img: Option<(Lsn, bytes::Bytes)>,
498 520 : records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
499 520 : pg_version: u32,
500 520 : ) -> Result<bytes::Bytes, walredo::Error> {
501 520 : match self {
502 0 : Self::Prod(_, mgr) => {
503 0 : mgr.request_redo(key, lsn, base_img, records, pg_version)
504 0 : .await
505 : }
506 : #[cfg(test)]
507 520 : Self::Test(mgr) => {
508 520 : mgr.request_redo(key, lsn, base_img, records, pg_version)
509 520 : .await
510 : }
511 : }
512 520 : }
513 :
514 0 : pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
515 0 : match self {
516 0 : WalRedoManager::Prod(_, m) => Some(m.status()),
517 0 : #[cfg(test)]
518 0 : WalRedoManager::Test(_) => None,
519 0 : }
520 0 : }
521 : }
522 :
523 : /// A very lightweight memory representation of an offloaded timeline.
524 : ///
525 : /// We need to store the list of offloaded timelines so that we can perform operations on them,
526 : /// like unoffloading them, or (at a later date), decide to perform flattening.
527 : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
528 : /// more offloaded timelines than we can manage ones that aren't.
529 : pub struct OffloadedTimeline {
530 : pub tenant_shard_id: TenantShardId,
531 : pub timeline_id: TimelineId,
532 : pub ancestor_timeline_id: Option<TimelineId>,
533 : /// Whether to retain the branch lsn at the ancestor or not
534 : pub ancestor_retain_lsn: Option<Lsn>,
535 :
536 : /// When the timeline was archived.
537 : ///
538 : /// Present for future flattening deliberations.
539 : pub archived_at: NaiveDateTime,
540 :
541 : /// Prevent two tasks from deleting the timeline at the same time. If held, the
542 : /// timeline is being deleted. If 'true', the timeline has already been deleted.
543 : pub delete_progress: TimelineDeleteProgress,
544 :
545 : /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
546 : pub deleted_from_ancestor: AtomicBool,
547 : }
548 :
549 : impl OffloadedTimeline {
550 : /// Obtains an offloaded timeline from a given timeline object.
551 : ///
552 : /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
553 : /// the timeline is not in a stopped state.
554 : /// Panics if the timeline is not archived.
555 2 : fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
556 2 : let (ancestor_retain_lsn, ancestor_timeline_id) =
557 2 : if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
558 2 : let ancestor_lsn = timeline.get_ancestor_lsn();
559 2 : let ancestor_timeline_id = ancestor_timeline.timeline_id;
560 2 : let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
561 2 : gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
562 2 : (Some(ancestor_lsn), Some(ancestor_timeline_id))
563 : } else {
564 0 : (None, None)
565 : };
566 2 : let archived_at = timeline
567 2 : .remote_client
568 2 : .archived_at_stopped_queue()?
569 2 : .expect("must be called on an archived timeline");
570 2 : Ok(Self {
571 2 : tenant_shard_id: timeline.tenant_shard_id,
572 2 : timeline_id: timeline.timeline_id,
573 2 : ancestor_timeline_id,
574 2 : ancestor_retain_lsn,
575 2 : archived_at,
576 2 :
577 2 : delete_progress: timeline.delete_progress.clone(),
578 2 : deleted_from_ancestor: AtomicBool::new(false),
579 2 : })
580 2 : }
581 0 : fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
582 0 : // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
583 0 : // by the `initialize_gc_info` function.
584 0 : let OffloadedTimelineManifest {
585 0 : timeline_id,
586 0 : ancestor_timeline_id,
587 0 : ancestor_retain_lsn,
588 0 : archived_at,
589 0 : } = *manifest;
590 0 : Self {
591 0 : tenant_shard_id,
592 0 : timeline_id,
593 0 : ancestor_timeline_id,
594 0 : ancestor_retain_lsn,
595 0 : archived_at,
596 0 : delete_progress: TimelineDeleteProgress::default(),
597 0 : deleted_from_ancestor: AtomicBool::new(false),
598 0 : }
599 0 : }
600 2 : fn manifest(&self) -> OffloadedTimelineManifest {
601 2 : let Self {
602 2 : timeline_id,
603 2 : ancestor_timeline_id,
604 2 : ancestor_retain_lsn,
605 2 : archived_at,
606 2 : ..
607 2 : } = self;
608 2 : OffloadedTimelineManifest {
609 2 : timeline_id: *timeline_id,
610 2 : ancestor_timeline_id: *ancestor_timeline_id,
611 2 : ancestor_retain_lsn: *ancestor_retain_lsn,
612 2 : archived_at: *archived_at,
613 2 : }
614 2 : }
615 : /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
616 0 : fn delete_from_ancestor_with_timelines(
617 0 : &self,
618 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
619 0 : ) {
620 0 : if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
621 0 : (self.ancestor_retain_lsn, self.ancestor_timeline_id)
622 : {
623 0 : if let Some((_, ancestor_timeline)) = timelines
624 0 : .iter()
625 0 : .find(|(tid, _tl)| **tid == ancestor_timeline_id)
626 : {
627 0 : let removal_happened = ancestor_timeline
628 0 : .gc_info
629 0 : .write()
630 0 : .unwrap()
631 0 : .remove_child_offloaded(self.timeline_id);
632 0 : if !removal_happened {
633 0 : tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
634 0 : "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
635 0 : }
636 0 : }
637 0 : }
638 0 : self.deleted_from_ancestor.store(true, Ordering::Release);
639 0 : }
640 : /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
641 : ///
642 : /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
643 2 : fn defuse_for_tenant_drop(&self) {
644 2 : self.deleted_from_ancestor.store(true, Ordering::Release);
645 2 : }
646 : }
647 :
648 : impl fmt::Debug for OffloadedTimeline {
649 0 : fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
650 0 : write!(f, "OffloadedTimeline<{}>", self.timeline_id)
651 0 : }
652 : }
653 :
654 : impl Drop for OffloadedTimeline {
655 2 : fn drop(&mut self) {
656 2 : if !self.deleted_from_ancestor.load(Ordering::Acquire) {
657 0 : tracing::warn!(
658 0 : "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
659 : self.timeline_id
660 : );
661 2 : }
662 2 : }
663 : }
664 :
665 : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
666 : pub enum MaybeOffloaded {
667 : Yes,
668 : No,
669 : }
670 :
671 : #[derive(Clone, Debug)]
672 : pub enum TimelineOrOffloaded {
673 : Timeline(Arc<Timeline>),
674 : Offloaded(Arc<OffloadedTimeline>),
675 : }
676 :
677 : impl TimelineOrOffloaded {
678 0 : pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
679 0 : match self {
680 0 : TimelineOrOffloaded::Timeline(timeline) => {
681 0 : TimelineOrOffloadedArcRef::Timeline(timeline)
682 : }
683 0 : TimelineOrOffloaded::Offloaded(offloaded) => {
684 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded)
685 : }
686 : }
687 0 : }
688 0 : pub fn tenant_shard_id(&self) -> TenantShardId {
689 0 : self.arc_ref().tenant_shard_id()
690 0 : }
691 0 : pub fn timeline_id(&self) -> TimelineId {
692 0 : self.arc_ref().timeline_id()
693 0 : }
694 2 : pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
695 2 : match self {
696 2 : TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
697 0 : TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
698 : }
699 2 : }
700 0 : fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
701 0 : match self {
702 0 : TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
703 0 : TimelineOrOffloaded::Offloaded(_offloaded) => None,
704 : }
705 0 : }
706 : }
707 :
708 : pub enum TimelineOrOffloadedArcRef<'a> {
709 : Timeline(&'a Arc<Timeline>),
710 : Offloaded(&'a Arc<OffloadedTimeline>),
711 : }
712 :
713 : impl TimelineOrOffloadedArcRef<'_> {
714 0 : pub fn tenant_shard_id(&self) -> TenantShardId {
715 0 : match self {
716 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
717 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
718 : }
719 0 : }
720 0 : pub fn timeline_id(&self) -> TimelineId {
721 0 : match self {
722 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
723 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
724 : }
725 0 : }
726 : }
727 :
728 : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
729 0 : fn from(timeline: &'a Arc<Timeline>) -> Self {
730 0 : Self::Timeline(timeline)
731 0 : }
732 : }
733 :
734 : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
735 0 : fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
736 0 : Self::Offloaded(timeline)
737 0 : }
738 : }
739 :
740 : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
741 : pub enum GetTimelineError {
742 : #[error("Timeline is shutting down")]
743 : ShuttingDown,
744 : #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
745 : NotActive {
746 : tenant_id: TenantShardId,
747 : timeline_id: TimelineId,
748 : state: TimelineState,
749 : },
750 : #[error("Timeline {tenant_id}/{timeline_id} was not found")]
751 : NotFound {
752 : tenant_id: TenantShardId,
753 : timeline_id: TimelineId,
754 : },
755 : }
756 :
757 : #[derive(Debug, thiserror::Error)]
758 : pub enum LoadLocalTimelineError {
759 : #[error("FailedToLoad")]
760 : Load(#[source] anyhow::Error),
761 : #[error("FailedToResumeDeletion")]
762 : ResumeDeletion(#[source] anyhow::Error),
763 : }
764 :
765 : #[derive(thiserror::Error)]
766 : pub enum DeleteTimelineError {
767 : #[error("NotFound")]
768 : NotFound,
769 :
770 : #[error("HasChildren")]
771 : HasChildren(Vec<TimelineId>),
772 :
773 : #[error("Timeline deletion is already in progress")]
774 : AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
775 :
776 : #[error("Cancelled")]
777 : Cancelled,
778 :
779 : #[error(transparent)]
780 : Other(#[from] anyhow::Error),
781 : }
782 :
783 : impl Debug for DeleteTimelineError {
784 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
785 0 : match self {
786 0 : Self::NotFound => write!(f, "NotFound"),
787 0 : Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
788 0 : Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
789 0 : Self::Cancelled => f.debug_tuple("Cancelled").finish(),
790 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
791 : }
792 0 : }
793 : }
794 :
795 : #[derive(thiserror::Error)]
796 : pub enum TimelineArchivalError {
797 : #[error("NotFound")]
798 : NotFound,
799 :
800 : #[error("Timeout")]
801 : Timeout,
802 :
803 : #[error("Cancelled")]
804 : Cancelled,
805 :
806 : #[error("ancestor is archived: {}", .0)]
807 : HasArchivedParent(TimelineId),
808 :
809 : #[error("HasUnarchivedChildren")]
810 : HasUnarchivedChildren(Vec<TimelineId>),
811 :
812 : #[error("Timeline archival is already in progress")]
813 : AlreadyInProgress,
814 :
815 : #[error(transparent)]
816 : Other(anyhow::Error),
817 : }
818 :
819 : #[derive(thiserror::Error, Debug)]
820 : pub(crate) enum TenantManifestError {
821 : #[error("Remote storage error: {0}")]
822 : RemoteStorage(anyhow::Error),
823 :
824 : #[error("Cancelled")]
825 : Cancelled,
826 : }
827 :
828 : impl From<TenantManifestError> for TimelineArchivalError {
829 0 : fn from(e: TenantManifestError) -> Self {
830 0 : match e {
831 0 : TenantManifestError::RemoteStorage(e) => Self::Other(e),
832 0 : TenantManifestError::Cancelled => Self::Cancelled,
833 : }
834 0 : }
835 : }
836 :
837 : impl Debug for TimelineArchivalError {
838 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
839 0 : match self {
840 0 : Self::NotFound => write!(f, "NotFound"),
841 0 : Self::Timeout => write!(f, "Timeout"),
842 0 : Self::Cancelled => write!(f, "Cancelled"),
843 0 : Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
844 0 : Self::HasUnarchivedChildren(c) => {
845 0 : f.debug_tuple("HasUnarchivedChildren").field(c).finish()
846 : }
847 0 : Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
848 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
849 : }
850 0 : }
851 : }
852 :
853 : pub enum SetStoppingError {
854 : AlreadyStopping(completion::Barrier),
855 : Broken,
856 : }
857 :
858 : impl Debug for SetStoppingError {
859 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
860 0 : match self {
861 0 : Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
862 0 : Self::Broken => write!(f, "Broken"),
863 : }
864 0 : }
865 : }
866 :
867 : /// Arguments to [`Tenant::create_timeline`].
868 : ///
869 : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
870 : /// is `None`, the result of the timeline create call is not deterministic.
871 : ///
872 : /// See [`CreateTimelineIdempotency`] for an idempotency key.
873 : #[derive(Debug)]
874 : pub(crate) enum CreateTimelineParams {
875 : Bootstrap(CreateTimelineParamsBootstrap),
876 : Branch(CreateTimelineParamsBranch),
877 : ImportPgdata(CreateTimelineParamsImportPgdata),
878 : }
879 :
880 : #[derive(Debug)]
881 : pub(crate) struct CreateTimelineParamsBootstrap {
882 : pub(crate) new_timeline_id: TimelineId,
883 : pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
884 : pub(crate) pg_version: u32,
885 : }
886 :
887 : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
888 : #[derive(Debug)]
889 : pub(crate) struct CreateTimelineParamsBranch {
890 : pub(crate) new_timeline_id: TimelineId,
891 : pub(crate) ancestor_timeline_id: TimelineId,
892 : pub(crate) ancestor_start_lsn: Option<Lsn>,
893 : }
894 :
895 : #[derive(Debug)]
896 : pub(crate) struct CreateTimelineParamsImportPgdata {
897 : pub(crate) new_timeline_id: TimelineId,
898 : pub(crate) location: import_pgdata::index_part_format::Location,
899 : pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
900 : }
901 :
902 : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in [`Tenant::start_creating_timeline`] in [`Tenant::start_creating_timeline`].
903 : ///
904 : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
905 : ///
906 : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
907 : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
908 : ///
909 : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
910 : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
911 : ///
912 : /// Notes:
913 : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
914 : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
915 : /// is not considered for idempotency. We can improve on this over time if we deem it necessary.
916 : ///
917 : #[derive(Debug, Clone, PartialEq, Eq)]
918 : pub(crate) enum CreateTimelineIdempotency {
919 : /// NB: special treatment, see comment in [`Self`].
920 : FailWithConflict,
921 : Bootstrap {
922 : pg_version: u32,
923 : },
924 : /// NB: branches always have the same `pg_version` as their ancestor.
925 : /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
926 : /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
927 : /// determining the child branch pg_version.
928 : Branch {
929 : ancestor_timeline_id: TimelineId,
930 : ancestor_start_lsn: Lsn,
931 : },
932 : ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
933 : }
934 :
935 : #[derive(Debug, Clone, PartialEq, Eq)]
936 : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
937 : idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
938 : }
939 :
940 : /// What is returned by [`Tenant::start_creating_timeline`].
941 : #[must_use]
942 : enum StartCreatingTimelineResult {
943 : CreateGuard(TimelineCreateGuard),
944 : Idempotent(Arc<Timeline>),
945 : }
946 :
947 : enum TimelineInitAndSyncResult {
948 : ReadyToActivate(Arc<Timeline>),
949 : NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
950 : }
951 :
952 : impl TimelineInitAndSyncResult {
953 0 : fn ready_to_activate(self) -> Option<Arc<Timeline>> {
954 0 : match self {
955 0 : Self::ReadyToActivate(timeline) => Some(timeline),
956 0 : _ => None,
957 : }
958 0 : }
959 : }
960 :
961 : #[must_use]
962 : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
963 : timeline: Arc<Timeline>,
964 : import_pgdata: import_pgdata::index_part_format::Root,
965 : guard: TimelineCreateGuard,
966 : }
967 :
968 : /// What is returned by [`Tenant::create_timeline`].
969 : enum CreateTimelineResult {
970 : Created(Arc<Timeline>),
971 : Idempotent(Arc<Timeline>),
972 : /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
973 : /// we return this result, nor will this concrete object ever be added there.
974 : /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
975 : ImportSpawned(Arc<Timeline>),
976 : }
977 :
978 : impl CreateTimelineResult {
979 0 : fn discriminant(&self) -> &'static str {
980 0 : match self {
981 0 : Self::Created(_) => "Created",
982 0 : Self::Idempotent(_) => "Idempotent",
983 0 : Self::ImportSpawned(_) => "ImportSpawned",
984 : }
985 0 : }
986 0 : fn timeline(&self) -> &Arc<Timeline> {
987 0 : match self {
988 0 : Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
989 0 : }
990 0 : }
991 : /// Unit test timelines aren't activated, test has to do it if it needs to.
992 : #[cfg(test)]
993 230 : fn into_timeline_for_test(self) -> Arc<Timeline> {
994 230 : match self {
995 230 : Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
996 230 : }
997 230 : }
998 : }
999 :
1000 : #[derive(thiserror::Error, Debug)]
1001 : pub enum CreateTimelineError {
1002 : #[error("creation of timeline with the given ID is in progress")]
1003 : AlreadyCreating,
1004 : #[error("timeline already exists with different parameters")]
1005 : Conflict,
1006 : #[error(transparent)]
1007 : AncestorLsn(anyhow::Error),
1008 : #[error("ancestor timeline is not active")]
1009 : AncestorNotActive,
1010 : #[error("ancestor timeline is archived")]
1011 : AncestorArchived,
1012 : #[error("tenant shutting down")]
1013 : ShuttingDown,
1014 : #[error(transparent)]
1015 : Other(#[from] anyhow::Error),
1016 : }
1017 :
1018 : #[derive(thiserror::Error, Debug)]
1019 : pub enum InitdbError {
1020 : #[error("Operation was cancelled")]
1021 : Cancelled,
1022 : #[error(transparent)]
1023 : Other(anyhow::Error),
1024 : #[error(transparent)]
1025 : Inner(postgres_initdb::Error),
1026 : }
1027 :
1028 : enum CreateTimelineCause {
1029 : Load,
1030 : Delete,
1031 : }
1032 :
1033 : enum LoadTimelineCause {
1034 : Attach,
1035 : Unoffload,
1036 : ImportPgdata {
1037 : create_guard: TimelineCreateGuard,
1038 : activate: ActivateTimelineArgs,
1039 : },
1040 : }
1041 :
1042 : #[derive(thiserror::Error, Debug)]
1043 : pub(crate) enum GcError {
1044 : // The tenant is shutting down
1045 : #[error("tenant shutting down")]
1046 : TenantCancelled,
1047 :
1048 : // The tenant is shutting down
1049 : #[error("timeline shutting down")]
1050 : TimelineCancelled,
1051 :
1052 : // The tenant is in a state inelegible to run GC
1053 : #[error("not active")]
1054 : NotActive,
1055 :
1056 : // A requested GC cutoff LSN was invalid, for example it tried to move backwards
1057 : #[error("not active")]
1058 : BadLsn { why: String },
1059 :
1060 : // A remote storage error while scheduling updates after compaction
1061 : #[error(transparent)]
1062 : Remote(anyhow::Error),
1063 :
1064 : // An error reading while calculating GC cutoffs
1065 : #[error(transparent)]
1066 : GcCutoffs(PageReconstructError),
1067 :
1068 : // If GC was invoked for a particular timeline, this error means it didn't exist
1069 : #[error("timeline not found")]
1070 : TimelineNotFound,
1071 : }
1072 :
1073 : impl From<PageReconstructError> for GcError {
1074 0 : fn from(value: PageReconstructError) -> Self {
1075 0 : match value {
1076 0 : PageReconstructError::Cancelled => Self::TimelineCancelled,
1077 0 : other => Self::GcCutoffs(other),
1078 : }
1079 0 : }
1080 : }
1081 :
1082 : impl From<NotInitialized> for GcError {
1083 0 : fn from(value: NotInitialized) -> Self {
1084 0 : match value {
1085 0 : NotInitialized::Uninitialized => GcError::Remote(value.into()),
1086 0 : NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
1087 : }
1088 0 : }
1089 : }
1090 :
1091 : impl From<timeline::layer_manager::Shutdown> for GcError {
1092 0 : fn from(_: timeline::layer_manager::Shutdown) -> Self {
1093 0 : GcError::TimelineCancelled
1094 0 : }
1095 : }
1096 :
1097 : #[derive(thiserror::Error, Debug)]
1098 : pub(crate) enum LoadConfigError {
1099 : #[error("TOML deserialization error: '{0}'")]
1100 : DeserializeToml(#[from] toml_edit::de::Error),
1101 :
1102 : #[error("Config not found at {0}")]
1103 : NotFound(Utf8PathBuf),
1104 : }
1105 :
1106 : impl Tenant {
1107 : /// Yet another helper for timeline initialization.
1108 : ///
1109 : /// - Initializes the Timeline struct and inserts it into the tenant's hash map
1110 : /// - Scans the local timeline directory for layer files and builds the layer map
1111 : /// - Downloads remote index file and adds remote files to the layer map
1112 : /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
1113 : ///
1114 : /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
1115 : /// it is marked as Active.
1116 : #[allow(clippy::too_many_arguments)]
1117 6 : async fn timeline_init_and_sync(
1118 6 : self: &Arc<Self>,
1119 6 : timeline_id: TimelineId,
1120 6 : resources: TimelineResources,
1121 6 : mut index_part: IndexPart,
1122 6 : metadata: TimelineMetadata,
1123 6 : ancestor: Option<Arc<Timeline>>,
1124 6 : cause: LoadTimelineCause,
1125 6 : ctx: &RequestContext,
1126 6 : ) -> anyhow::Result<TimelineInitAndSyncResult> {
1127 6 : let tenant_id = self.tenant_shard_id;
1128 6 :
1129 6 : let import_pgdata = index_part.import_pgdata.take();
1130 6 : let idempotency = match &import_pgdata {
1131 0 : Some(import_pgdata) => {
1132 0 : CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
1133 0 : idempotency_key: import_pgdata.idempotency_key().clone(),
1134 0 : })
1135 : }
1136 : None => {
1137 6 : if metadata.ancestor_timeline().is_none() {
1138 4 : CreateTimelineIdempotency::Bootstrap {
1139 4 : pg_version: metadata.pg_version(),
1140 4 : }
1141 : } else {
1142 2 : CreateTimelineIdempotency::Branch {
1143 2 : ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
1144 2 : ancestor_start_lsn: metadata.ancestor_lsn(),
1145 2 : }
1146 : }
1147 : }
1148 : };
1149 :
1150 6 : let timeline = self.create_timeline_struct(
1151 6 : timeline_id,
1152 6 : &metadata,
1153 6 : ancestor.clone(),
1154 6 : resources,
1155 6 : CreateTimelineCause::Load,
1156 6 : idempotency.clone(),
1157 6 : )?;
1158 6 : let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
1159 6 : anyhow::ensure!(
1160 6 : disk_consistent_lsn.is_valid(),
1161 0 : "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
1162 : );
1163 6 : assert_eq!(
1164 6 : disk_consistent_lsn,
1165 6 : metadata.disk_consistent_lsn(),
1166 0 : "these are used interchangeably"
1167 : );
1168 :
1169 6 : timeline.remote_client.init_upload_queue(&index_part)?;
1170 :
1171 6 : timeline
1172 6 : .load_layer_map(disk_consistent_lsn, index_part)
1173 6 : .await
1174 6 : .with_context(|| {
1175 0 : format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
1176 6 : })?;
1177 :
1178 0 : match import_pgdata {
1179 0 : Some(import_pgdata) if !import_pgdata.is_done() => {
1180 0 : match cause {
1181 0 : LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
1182 : LoadTimelineCause::ImportPgdata { .. } => {
1183 0 : unreachable!("ImportPgdata should not be reloading timeline import is done and persisted as such in s3")
1184 : }
1185 : }
1186 0 : let mut guard = self.timelines_creating.lock().unwrap();
1187 0 : if !guard.insert(timeline_id) {
1188 : // We should never try and load the same timeline twice during startup
1189 0 : unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
1190 0 : }
1191 0 : let timeline_create_guard = TimelineCreateGuard {
1192 0 : _tenant_gate_guard: self.gate.enter()?,
1193 0 : owning_tenant: self.clone(),
1194 0 : timeline_id,
1195 0 : idempotency,
1196 0 : // The users of this specific return value don't need the timline_path in there.
1197 0 : timeline_path: timeline
1198 0 : .conf
1199 0 : .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
1200 0 : };
1201 0 : Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
1202 0 : TimelineInitAndSyncNeedsSpawnImportPgdata {
1203 0 : timeline,
1204 0 : import_pgdata,
1205 0 : guard: timeline_create_guard,
1206 0 : },
1207 0 : ))
1208 : }
1209 : Some(_) | None => {
1210 : {
1211 6 : let mut timelines_accessor = self.timelines.lock().unwrap();
1212 6 : match timelines_accessor.entry(timeline_id) {
1213 : // We should never try and load the same timeline twice during startup
1214 : Entry::Occupied(_) => {
1215 0 : unreachable!(
1216 0 : "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
1217 0 : );
1218 : }
1219 6 : Entry::Vacant(v) => {
1220 6 : v.insert(Arc::clone(&timeline));
1221 6 : timeline.maybe_spawn_flush_loop();
1222 6 : }
1223 : }
1224 : }
1225 :
1226 : // Sanity check: a timeline should have some content.
1227 6 : anyhow::ensure!(
1228 6 : ancestor.is_some()
1229 4 : || timeline
1230 4 : .layers
1231 4 : .read()
1232 4 : .await
1233 4 : .layer_map()
1234 4 : .expect("currently loading, layer manager cannot be shutdown already")
1235 4 : .iter_historic_layers()
1236 4 : .next()
1237 4 : .is_some(),
1238 0 : "Timeline has no ancestor and no layer files"
1239 : );
1240 :
1241 6 : match cause {
1242 6 : LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
1243 : LoadTimelineCause::ImportPgdata {
1244 0 : create_guard,
1245 0 : activate,
1246 0 : } => {
1247 0 : // TODO: see the comment in the task code above how I'm not so certain
1248 0 : // it is safe to activate here because of concurrent shutdowns.
1249 0 : match activate {
1250 0 : ActivateTimelineArgs::Yes { broker_client } => {
1251 0 : info!("activating timeline after reload from pgdata import task");
1252 0 : timeline.activate(self.clone(), broker_client, None, ctx);
1253 : }
1254 0 : ActivateTimelineArgs::No => (),
1255 : }
1256 0 : drop(create_guard);
1257 : }
1258 : }
1259 :
1260 6 : Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
1261 : }
1262 : }
1263 6 : }
1264 :
1265 : /// Attach a tenant that's available in cloud storage.
1266 : ///
1267 : /// This returns quickly, after just creating the in-memory object
1268 : /// Tenant struct and launching a background task to download
1269 : /// the remote index files. On return, the tenant is most likely still in
1270 : /// Attaching state, and it will become Active once the background task
1271 : /// finishes. You can use wait_until_active() to wait for the task to
1272 : /// complete.
1273 : ///
1274 : #[allow(clippy::too_many_arguments)]
1275 0 : pub(crate) fn spawn(
1276 0 : conf: &'static PageServerConf,
1277 0 : tenant_shard_id: TenantShardId,
1278 0 : resources: TenantSharedResources,
1279 0 : attached_conf: AttachedTenantConf,
1280 0 : shard_identity: ShardIdentity,
1281 0 : init_order: Option<InitializationOrder>,
1282 0 : mode: SpawnMode,
1283 0 : ctx: &RequestContext,
1284 0 : ) -> Result<Arc<Tenant>, GlobalShutDown> {
1285 0 : let wal_redo_manager =
1286 0 : WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
1287 :
1288 : let TenantSharedResources {
1289 0 : broker_client,
1290 0 : remote_storage,
1291 0 : deletion_queue_client,
1292 0 : l0_flush_global_state,
1293 0 : } = resources;
1294 0 :
1295 0 : let attach_mode = attached_conf.location.attach_mode;
1296 0 : let generation = attached_conf.location.generation;
1297 0 :
1298 0 : let tenant = Arc::new(Tenant::new(
1299 0 : TenantState::Attaching,
1300 0 : conf,
1301 0 : attached_conf,
1302 0 : shard_identity,
1303 0 : Some(wal_redo_manager),
1304 0 : tenant_shard_id,
1305 0 : remote_storage.clone(),
1306 0 : deletion_queue_client,
1307 0 : l0_flush_global_state,
1308 0 : ));
1309 0 :
1310 0 : // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
1311 0 : // we shut down while attaching.
1312 0 : let attach_gate_guard = tenant
1313 0 : .gate
1314 0 : .enter()
1315 0 : .expect("We just created the Tenant: nothing else can have shut it down yet");
1316 0 :
1317 0 : // Do all the hard work in the background
1318 0 : let tenant_clone = Arc::clone(&tenant);
1319 0 : let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
1320 0 : task_mgr::spawn(
1321 0 : &tokio::runtime::Handle::current(),
1322 0 : TaskKind::Attach,
1323 0 : tenant_shard_id,
1324 0 : None,
1325 0 : "attach tenant",
1326 0 : async move {
1327 0 :
1328 0 : info!(
1329 : ?attach_mode,
1330 0 : "Attaching tenant"
1331 : );
1332 :
1333 0 : let _gate_guard = attach_gate_guard;
1334 0 :
1335 0 : // Is this tenant being spawned as part of process startup?
1336 0 : let starting_up = init_order.is_some();
1337 0 : scopeguard::defer! {
1338 0 : if starting_up {
1339 0 : TENANT.startup_complete.inc();
1340 0 : }
1341 0 : }
1342 :
1343 : // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
1344 : enum BrokenVerbosity {
1345 : Error,
1346 : Info
1347 : }
1348 0 : let make_broken =
1349 0 : |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
1350 0 : match verbosity {
1351 : BrokenVerbosity::Info => {
1352 0 : info!("attach cancelled, setting tenant state to Broken: {err}");
1353 : },
1354 : BrokenVerbosity::Error => {
1355 0 : error!("attach failed, setting tenant state to Broken: {err:?}");
1356 : }
1357 : }
1358 0 : t.state.send_modify(|state| {
1359 0 : // The Stopping case is for when we have passed control on to DeleteTenantFlow:
1360 0 : // if it errors, we will call make_broken when tenant is already in Stopping.
1361 0 : assert!(
1362 0 : matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
1363 0 : "the attach task owns the tenant state until activation is complete"
1364 : );
1365 :
1366 0 : *state = TenantState::broken_from_reason(err.to_string());
1367 0 : });
1368 0 : };
1369 :
1370 : // TODO: should also be rejecting tenant conf changes that violate this check.
1371 0 : if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
1372 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1373 0 : return Ok(());
1374 0 : }
1375 0 :
1376 0 : let mut init_order = init_order;
1377 0 : // take the completion because initial tenant loading will complete when all of
1378 0 : // these tasks complete.
1379 0 : let _completion = init_order
1380 0 : .as_mut()
1381 0 : .and_then(|x| x.initial_tenant_load.take());
1382 0 : let remote_load_completion = init_order
1383 0 : .as_mut()
1384 0 : .and_then(|x| x.initial_tenant_load_remote.take());
1385 :
1386 : enum AttachType<'a> {
1387 : /// We are attaching this tenant lazily in the background.
1388 : Warmup {
1389 : _permit: tokio::sync::SemaphorePermit<'a>,
1390 : during_startup: bool
1391 : },
1392 : /// We are attaching this tenant as soon as we can, because for example an
1393 : /// endpoint tried to access it.
1394 : OnDemand,
1395 : /// During normal operations after startup, we are attaching a tenant, and
1396 : /// eager attach was requested.
1397 : Normal,
1398 : }
1399 :
1400 0 : let attach_type = if matches!(mode, SpawnMode::Lazy) {
1401 : // Before doing any I/O, wait for at least one of:
1402 : // - A client attempting to access to this tenant (on-demand loading)
1403 : // - A permit becoming available in the warmup semaphore (background warmup)
1404 :
1405 0 : tokio::select!(
1406 0 : permit = tenant_clone.activate_now_sem.acquire() => {
1407 0 : let _ = permit.expect("activate_now_sem is never closed");
1408 0 : tracing::info!("Activating tenant (on-demand)");
1409 0 : AttachType::OnDemand
1410 : },
1411 0 : permit = conf.concurrent_tenant_warmup.inner().acquire() => {
1412 0 : let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
1413 0 : tracing::info!("Activating tenant (warmup)");
1414 0 : AttachType::Warmup {
1415 0 : _permit,
1416 0 : during_startup: init_order.is_some()
1417 0 : }
1418 : }
1419 0 : _ = tenant_clone.cancel.cancelled() => {
1420 : // This is safe, but should be pretty rare: it is interesting if a tenant
1421 : // stayed in Activating for such a long time that shutdown found it in
1422 : // that state.
1423 0 : tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
1424 : // Make the tenant broken so that set_stopping will not hang waiting for it to leave
1425 : // the Attaching state. This is an over-reaction (nothing really broke, the tenant is
1426 : // just shutting down), but ensures progress.
1427 0 : make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
1428 0 : return Ok(());
1429 : },
1430 : )
1431 : } else {
1432 : // SpawnMode::{Create,Eager} always cause jumping ahead of the
1433 : // concurrent_tenant_warmup queue
1434 0 : AttachType::Normal
1435 : };
1436 :
1437 0 : let preload = match &mode {
1438 : SpawnMode::Eager | SpawnMode::Lazy => {
1439 0 : let _preload_timer = TENANT.preload.start_timer();
1440 0 : let res = tenant_clone
1441 0 : .preload(&remote_storage, task_mgr::shutdown_token())
1442 0 : .await;
1443 0 : match res {
1444 0 : Ok(p) => Some(p),
1445 0 : Err(e) => {
1446 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1447 0 : return Ok(());
1448 : }
1449 : }
1450 : }
1451 :
1452 : };
1453 :
1454 : // Remote preload is complete.
1455 0 : drop(remote_load_completion);
1456 0 :
1457 0 :
1458 0 : // We will time the duration of the attach phase unless this is a creation (attach will do no work)
1459 0 : let attach_start = std::time::Instant::now();
1460 0 : let attached = {
1461 0 : let _attach_timer = Some(TENANT.attach.start_timer());
1462 0 : tenant_clone.attach(preload, &ctx).await
1463 : };
1464 0 : let attach_duration = attach_start.elapsed();
1465 0 : _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
1466 0 :
1467 0 : match attached {
1468 : Ok(()) => {
1469 0 : info!("attach finished, activating");
1470 0 : tenant_clone.activate(broker_client, None, &ctx);
1471 : }
1472 0 : Err(e) => {
1473 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1474 0 : }
1475 : }
1476 :
1477 : // If we are doing an opportunistic warmup attachment at startup, initialize
1478 : // logical size at the same time. This is better than starting a bunch of idle tenants
1479 : // with cold caches and then coming back later to initialize their logical sizes.
1480 : //
1481 : // It also prevents the warmup proccess competing with the concurrency limit on
1482 : // logical size calculations: if logical size calculation semaphore is saturated,
1483 : // then warmup will wait for that before proceeding to the next tenant.
1484 0 : if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
1485 0 : let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
1486 0 : tracing::info!("Waiting for initial logical sizes while warming up...");
1487 0 : while futs.next().await.is_some() {}
1488 0 : tracing::info!("Warm-up complete");
1489 0 : }
1490 :
1491 0 : Ok(())
1492 0 : }
1493 0 : .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
1494 : );
1495 0 : Ok(tenant)
1496 0 : }
1497 :
1498 : #[instrument(skip_all)]
1499 : pub(crate) async fn preload(
1500 : self: &Arc<Self>,
1501 : remote_storage: &GenericRemoteStorage,
1502 : cancel: CancellationToken,
1503 : ) -> anyhow::Result<TenantPreload> {
1504 : span::debug_assert_current_span_has_tenant_id();
1505 : // Get list of remote timelines
1506 : // download index files for every tenant timeline
1507 : info!("listing remote timelines");
1508 : let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
1509 : remote_storage,
1510 : self.tenant_shard_id,
1511 : cancel.clone(),
1512 : )
1513 : .await?;
1514 : let (offloaded_add, tenant_manifest) =
1515 : match remote_timeline_client::download_tenant_manifest(
1516 : remote_storage,
1517 : &self.tenant_shard_id,
1518 : self.generation,
1519 : &cancel,
1520 : )
1521 : .await
1522 : {
1523 : Ok((tenant_manifest, _generation, _manifest_mtime)) => (
1524 : format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
1525 : tenant_manifest,
1526 : ),
1527 : Err(DownloadError::NotFound) => {
1528 : ("no manifest".to_string(), TenantManifest::empty())
1529 : }
1530 : Err(e) => Err(e)?,
1531 : };
1532 :
1533 : info!(
1534 : "found {} timelines, and {offloaded_add}",
1535 : remote_timeline_ids.len()
1536 : );
1537 :
1538 : for k in other_keys {
1539 : warn!("Unexpected non timeline key {k}");
1540 : }
1541 :
1542 : // Avoid downloading IndexPart of offloaded timelines.
1543 : let mut offloaded_with_prefix = HashSet::new();
1544 : for offloaded in tenant_manifest.offloaded_timelines.iter() {
1545 : if remote_timeline_ids.remove(&offloaded.timeline_id) {
1546 : offloaded_with_prefix.insert(offloaded.timeline_id);
1547 : } else {
1548 : // We'll take care later of timelines in the manifest without a prefix
1549 : }
1550 : }
1551 :
1552 : let timelines = self
1553 : .load_timelines_metadata(remote_timeline_ids, remote_storage, cancel)
1554 : .await?;
1555 :
1556 : Ok(TenantPreload {
1557 : tenant_manifest,
1558 : timelines: timelines
1559 : .into_iter()
1560 6 : .map(|(id, tl)| (id, Some(tl)))
1561 0 : .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
1562 : .collect(),
1563 : })
1564 : }
1565 :
1566 : ///
1567 : /// Background task that downloads all data for a tenant and brings it to Active state.
1568 : ///
1569 : /// No background tasks are started as part of this routine.
1570 : ///
1571 196 : async fn attach(
1572 196 : self: &Arc<Tenant>,
1573 196 : preload: Option<TenantPreload>,
1574 196 : ctx: &RequestContext,
1575 196 : ) -> anyhow::Result<()> {
1576 196 : span::debug_assert_current_span_has_tenant_id();
1577 196 :
1578 196 : failpoint_support::sleep_millis_async!("before-attaching-tenant");
1579 :
1580 196 : let Some(preload) = preload else {
1581 0 : anyhow::bail!("local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624");
1582 : };
1583 :
1584 196 : let mut offloaded_timeline_ids = HashSet::new();
1585 196 : let mut offloaded_timelines_list = Vec::new();
1586 196 : for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
1587 0 : let timeline_id = timeline_manifest.timeline_id;
1588 0 : let offloaded_timeline =
1589 0 : OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
1590 0 : offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
1591 0 : offloaded_timeline_ids.insert(timeline_id);
1592 0 : }
1593 : // Complete deletions for offloaded timeline id's from manifest.
1594 : // The manifest will be uploaded later in this function.
1595 196 : offloaded_timelines_list
1596 196 : .retain(|(offloaded_id, offloaded)| {
1597 0 : // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
1598 0 : // If there is dangling references in another location, they need to be cleaned up.
1599 0 : let delete = !preload.timelines.contains_key(offloaded_id);
1600 0 : if delete {
1601 0 : tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
1602 0 : offloaded.defuse_for_tenant_drop();
1603 0 : }
1604 0 : !delete
1605 196 : });
1606 196 :
1607 196 : let mut timelines_to_resume_deletions = vec![];
1608 196 :
1609 196 : let mut remote_index_and_client = HashMap::new();
1610 196 : let mut timeline_ancestors = HashMap::new();
1611 196 : let mut existent_timelines = HashSet::new();
1612 202 : for (timeline_id, preload) in preload.timelines {
1613 6 : let Some(preload) = preload else { continue };
1614 : // This is an invariant of the `preload` function's API
1615 6 : assert!(!offloaded_timeline_ids.contains(&timeline_id));
1616 6 : let index_part = match preload.index_part {
1617 6 : Ok(i) => {
1618 6 : debug!("remote index part exists for timeline {timeline_id}");
1619 : // We found index_part on the remote, this is the standard case.
1620 6 : existent_timelines.insert(timeline_id);
1621 6 : i
1622 : }
1623 : Err(DownloadError::NotFound) => {
1624 : // There is no index_part on the remote. We only get here
1625 : // if there is some prefix for the timeline in the remote storage.
1626 : // This can e.g. be the initdb.tar.zst archive, maybe a
1627 : // remnant from a prior incomplete creation or deletion attempt.
1628 : // Delete the local directory as the deciding criterion for a
1629 : // timeline's existence is presence of index_part.
1630 0 : info!(%timeline_id, "index_part not found on remote");
1631 0 : continue;
1632 : }
1633 0 : Err(DownloadError::Fatal(why)) => {
1634 0 : // If, while loading one remote timeline, we saw an indication that our generation
1635 0 : // number is likely invalid, then we should not load the whole tenant.
1636 0 : error!(%timeline_id, "Fatal error loading timeline: {why}");
1637 0 : anyhow::bail!(why.to_string());
1638 : }
1639 0 : Err(e) => {
1640 0 : // Some (possibly ephemeral) error happened during index_part download.
1641 0 : // Pretend the timeline exists to not delete the timeline directory,
1642 0 : // as it might be a temporary issue and we don't want to re-download
1643 0 : // everything after it resolves.
1644 0 : warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
1645 :
1646 0 : existent_timelines.insert(timeline_id);
1647 0 : continue;
1648 : }
1649 : };
1650 6 : match index_part {
1651 6 : MaybeDeletedIndexPart::IndexPart(index_part) => {
1652 6 : timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
1653 6 : remote_index_and_client.insert(timeline_id, (index_part, preload.client));
1654 6 : }
1655 0 : MaybeDeletedIndexPart::Deleted(index_part) => {
1656 0 : info!(
1657 0 : "timeline {} is deleted, picking to resume deletion",
1658 : timeline_id
1659 : );
1660 0 : timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
1661 : }
1662 : }
1663 : }
1664 :
1665 196 : let mut gc_blocks = HashMap::new();
1666 :
1667 : // For every timeline, download the metadata file, scan the local directory,
1668 : // and build a layer map that contains an entry for each remote and local
1669 : // layer file.
1670 196 : let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
1671 202 : for (timeline_id, remote_metadata) in sorted_timelines {
1672 6 : let (index_part, remote_client) = remote_index_and_client
1673 6 : .remove(&timeline_id)
1674 6 : .expect("just put it in above");
1675 :
1676 6 : if let Some(blocking) = index_part.gc_blocking.as_ref() {
1677 : // could just filter these away, but it helps while testing
1678 0 : anyhow::ensure!(
1679 0 : !blocking.reasons.is_empty(),
1680 0 : "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
1681 : );
1682 0 : let prev = gc_blocks.insert(timeline_id, blocking.reasons);
1683 0 : assert!(prev.is_none());
1684 6 : }
1685 :
1686 : // TODO again handle early failure
1687 6 : let effect = self
1688 6 : .load_remote_timeline(
1689 6 : timeline_id,
1690 6 : index_part,
1691 6 : remote_metadata,
1692 6 : TimelineResources {
1693 6 : remote_client,
1694 6 : pagestream_throttle: self.pagestream_throttle.clone(),
1695 6 : l0_flush_global_state: self.l0_flush_global_state.clone(),
1696 6 : },
1697 6 : LoadTimelineCause::Attach,
1698 6 : ctx,
1699 6 : )
1700 6 : .await
1701 6 : .with_context(|| {
1702 0 : format!(
1703 0 : "failed to load remote timeline {} for tenant {}",
1704 0 : timeline_id, self.tenant_shard_id
1705 0 : )
1706 6 : })?;
1707 :
1708 6 : match effect {
1709 6 : TimelineInitAndSyncResult::ReadyToActivate(_) => {
1710 6 : // activation happens later, on Tenant::activate
1711 6 : }
1712 : TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
1713 : TimelineInitAndSyncNeedsSpawnImportPgdata {
1714 0 : timeline,
1715 0 : import_pgdata,
1716 0 : guard,
1717 0 : },
1718 0 : ) => {
1719 0 : tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
1720 0 : timeline,
1721 0 : import_pgdata,
1722 0 : ActivateTimelineArgs::No,
1723 0 : guard,
1724 0 : ));
1725 0 : }
1726 : }
1727 : }
1728 :
1729 : // Walk through deleted timelines, resume deletion
1730 196 : for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
1731 0 : remote_timeline_client
1732 0 : .init_upload_queue_stopped_to_continue_deletion(&index_part)
1733 0 : .context("init queue stopped")
1734 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1735 :
1736 0 : DeleteTimelineFlow::resume_deletion(
1737 0 : Arc::clone(self),
1738 0 : timeline_id,
1739 0 : &index_part.metadata,
1740 0 : remote_timeline_client,
1741 0 : )
1742 0 : .instrument(tracing::info_span!("timeline_delete", %timeline_id))
1743 0 : .await
1744 0 : .context("resume_deletion")
1745 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1746 : }
1747 196 : let needs_manifest_upload =
1748 196 : offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
1749 196 : {
1750 196 : let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
1751 196 : offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
1752 196 : }
1753 196 : if needs_manifest_upload {
1754 0 : self.store_tenant_manifest().await?;
1755 196 : }
1756 :
1757 : // The local filesystem contents are a cache of what's in the remote IndexPart;
1758 : // IndexPart is the source of truth.
1759 196 : self.clean_up_timelines(&existent_timelines)?;
1760 :
1761 196 : self.gc_block.set_scanned(gc_blocks);
1762 196 :
1763 196 : fail::fail_point!("attach-before-activate", |_| {
1764 0 : anyhow::bail!("attach-before-activate");
1765 196 : });
1766 196 : failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
1767 :
1768 196 : info!("Done");
1769 :
1770 196 : Ok(())
1771 196 : }
1772 :
1773 : /// Check for any local timeline directories that are temporary, or do not correspond to a
1774 : /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
1775 : /// if a timeline was deleted while the tenant was attached to a different pageserver.
1776 196 : fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
1777 196 : let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
1778 :
1779 196 : let entries = match timelines_dir.read_dir_utf8() {
1780 196 : Ok(d) => d,
1781 0 : Err(e) => {
1782 0 : if e.kind() == std::io::ErrorKind::NotFound {
1783 0 : return Ok(());
1784 : } else {
1785 0 : return Err(e).context("list timelines directory for tenant");
1786 : }
1787 : }
1788 : };
1789 :
1790 204 : for entry in entries {
1791 8 : let entry = entry.context("read timeline dir entry")?;
1792 8 : let entry_path = entry.path();
1793 :
1794 8 : let purge = if crate::is_temporary(entry_path)
1795 : // TODO: remove uninit mark code (https://github.com/neondatabase/neon/issues/5718)
1796 8 : || is_uninit_mark(entry_path)
1797 8 : || crate::is_delete_mark(entry_path)
1798 : {
1799 0 : true
1800 : } else {
1801 8 : match TimelineId::try_from(entry_path.file_name()) {
1802 8 : Ok(i) => {
1803 8 : // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
1804 8 : !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 8 : if purge {
1817 2 : tracing::info!("Purging stale timeline dentry {entry_path}");
1818 2 : if let Err(e) = match entry.file_type() {
1819 2 : Ok(t) => if t.is_dir() {
1820 2 : std::fs::remove_dir_all(entry_path)
1821 : } else {
1822 0 : std::fs::remove_file(entry_path)
1823 : }
1824 2 : .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 2 : }
1829 6 : }
1830 : }
1831 :
1832 196 : Ok(())
1833 196 : }
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 196 : async fn load_timelines_metadata(
1891 196 : self: &Arc<Tenant>,
1892 196 : timeline_ids: HashSet<TimelineId>,
1893 196 : remote_storage: &GenericRemoteStorage,
1894 196 : cancel: CancellationToken,
1895 196 : ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
1896 196 : let mut part_downloads = JoinSet::new();
1897 202 : for timeline_id in timeline_ids {
1898 6 : let cancel_clone = cancel.clone();
1899 6 : part_downloads.spawn(
1900 6 : self.load_timeline_metadata(timeline_id, remote_storage.clone(), cancel_clone)
1901 6 : .instrument(info_span!("download_index_part", %timeline_id)),
1902 : );
1903 : }
1904 :
1905 196 : let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
1906 :
1907 : loop {
1908 202 : tokio::select!(
1909 202 : next = part_downloads.join_next() => {
1910 202 : match next {
1911 6 : Some(result) => {
1912 6 : let preload = result.context("join preload task")?;
1913 6 : timeline_preloads.insert(preload.timeline_id, preload);
1914 : },
1915 : None => {
1916 196 : break;
1917 : }
1918 : }
1919 : },
1920 202 : _ = cancel.cancelled() => {
1921 0 : anyhow::bail!("Cancelled while waiting for remote index download")
1922 : }
1923 : )
1924 : }
1925 :
1926 196 : Ok(timeline_preloads)
1927 196 : }
1928 :
1929 6 : fn build_timeline_client(
1930 6 : &self,
1931 6 : timeline_id: TimelineId,
1932 6 : remote_storage: GenericRemoteStorage,
1933 6 : ) -> RemoteTimelineClient {
1934 6 : RemoteTimelineClient::new(
1935 6 : remote_storage.clone(),
1936 6 : self.deletion_queue_client.clone(),
1937 6 : self.conf,
1938 6 : self.tenant_shard_id,
1939 6 : timeline_id,
1940 6 : self.generation,
1941 6 : &self.tenant_conf.load().location,
1942 6 : )
1943 6 : }
1944 :
1945 6 : fn load_timeline_metadata(
1946 6 : self: &Arc<Tenant>,
1947 6 : timeline_id: TimelineId,
1948 6 : remote_storage: GenericRemoteStorage,
1949 6 : cancel: CancellationToken,
1950 6 : ) -> impl Future<Output = TimelinePreload> {
1951 6 : let client = self.build_timeline_client(timeline_id, remote_storage);
1952 6 : async move {
1953 6 : debug_assert_current_span_has_tenant_and_timeline_id();
1954 6 : debug!("starting index part download");
1955 :
1956 6 : let index_part = client.download_index_file(&cancel).await;
1957 :
1958 6 : debug!("finished index part download");
1959 :
1960 6 : TimelinePreload {
1961 6 : client,
1962 6 : timeline_id,
1963 6 : index_part,
1964 6 : }
1965 6 : }
1966 6 : }
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 2 : pub fn get_offloaded_timeline(
2254 2 : &self,
2255 2 : timeline_id: TimelineId,
2256 2 : ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
2257 2 : self.timelines_offloaded
2258 2 : .lock()
2259 2 : .unwrap()
2260 2 : .get(&timeline_id)
2261 2 : .map(Arc::clone)
2262 2 : .ok_or(GetTimelineError::NotFound {
2263 2 : tenant_id: self.tenant_shard_id,
2264 2 : timeline_id,
2265 2 : })
2266 2 : }
2267 :
2268 4 : pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
2269 4 : self.tenant_shard_id
2270 4 : }
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 222 : pub fn get_timeline(
2275 222 : &self,
2276 222 : timeline_id: TimelineId,
2277 222 : active_only: bool,
2278 222 : ) -> Result<Arc<Timeline>, GetTimelineError> {
2279 222 : let timelines_accessor = self.timelines.lock().unwrap();
2280 222 : let timeline = timelines_accessor
2281 222 : .get(&timeline_id)
2282 222 : .ok_or(GetTimelineError::NotFound {
2283 222 : tenant_id: self.tenant_shard_id,
2284 222 : timeline_id,
2285 222 : })?;
2286 :
2287 220 : 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 220 : Ok(Arc::clone(timeline))
2295 : }
2296 222 : }
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 188 : pub(crate) async fn create_empty_timeline(
2348 188 : self: &Arc<Self>,
2349 188 : new_timeline_id: TimelineId,
2350 188 : initdb_lsn: Lsn,
2351 188 : pg_version: u32,
2352 188 : _ctx: &RequestContext,
2353 188 : ) -> anyhow::Result<UninitializedTimeline> {
2354 188 : anyhow::ensure!(
2355 188 : self.is_active(),
2356 0 : "Cannot create empty timelines on inactive tenant"
2357 : );
2358 :
2359 : // Protect against concurrent attempts to use this TimelineId
2360 188 : let create_guard = match self
2361 188 : .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
2362 188 : .await?
2363 : {
2364 186 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
2365 : StartCreatingTimelineResult::Idempotent(_) => {
2366 0 : unreachable!("FailWithConflict implies we get an error instead")
2367 : }
2368 : };
2369 :
2370 186 : let new_metadata = TimelineMetadata::new(
2371 186 : // Initialize disk_consistent LSN to 0, The caller must import some data to
2372 186 : // make it valid, before calling finish_creation()
2373 186 : Lsn(0),
2374 186 : None,
2375 186 : None,
2376 186 : Lsn(0),
2377 186 : initdb_lsn,
2378 186 : initdb_lsn,
2379 186 : pg_version,
2380 186 : );
2381 186 : self.prepare_new_timeline(
2382 186 : new_timeline_id,
2383 186 : &new_metadata,
2384 186 : create_guard,
2385 186 : initdb_lsn,
2386 186 : None,
2387 186 : )
2388 186 : .await
2389 188 : }
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 178 : pub async fn create_test_timeline(
2398 178 : self: &Arc<Self>,
2399 178 : new_timeline_id: TimelineId,
2400 178 : initdb_lsn: Lsn,
2401 178 : pg_version: u32,
2402 178 : ctx: &RequestContext,
2403 178 : ) -> anyhow::Result<Arc<Timeline>> {
2404 178 : let uninit_tl = self
2405 178 : .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
2406 178 : .await?;
2407 178 : let tline = uninit_tl.raw_timeline().expect("we just created it");
2408 178 : assert_eq!(tline.get_last_record_lsn(), Lsn(0));
2409 :
2410 : // Setup minimum keys required for the timeline to be usable.
2411 178 : let mut modification = tline.begin_modification(initdb_lsn);
2412 178 : modification
2413 178 : .init_empty_test_timeline()
2414 178 : .context("init_empty_test_timeline")?;
2415 178 : modification
2416 178 : .commit(ctx)
2417 178 : .await
2418 178 : .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 178 : tline.maybe_spawn_flush_loop();
2422 178 : tline.freeze_and_flush().await.context("freeze_and_flush")?;
2423 :
2424 : // Make sure the freeze_and_flush reaches remote storage.
2425 178 : tline.remote_client.wait_completion().await.unwrap();
2426 :
2427 178 : let tl = uninit_tl.finish_creation()?;
2428 : // The non-test code would call tl.activate() here.
2429 178 : tl.set_state(TimelineState::Active);
2430 178 : Ok(tl)
2431 178 : }
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 36 : pub async fn create_test_timeline_with_layers(
2437 36 : self: &Arc<Self>,
2438 36 : new_timeline_id: TimelineId,
2439 36 : initdb_lsn: Lsn,
2440 36 : pg_version: u32,
2441 36 : ctx: &RequestContext,
2442 36 : delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
2443 36 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
2444 36 : end_lsn: Lsn,
2445 36 : ) -> anyhow::Result<Arc<Timeline>> {
2446 : use checks::check_valid_layermap;
2447 : use itertools::Itertools;
2448 :
2449 36 : let tline = self
2450 36 : .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
2451 36 : .await?;
2452 36 : tline.force_advance_lsn(end_lsn);
2453 120 : for deltas in delta_layer_desc {
2454 84 : tline
2455 84 : .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
2456 84 : .await?;
2457 : }
2458 88 : for (lsn, images) in image_layer_desc {
2459 52 : tline
2460 52 : .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
2461 52 : .await?;
2462 : }
2463 36 : let layer_names = tline
2464 36 : .layers
2465 36 : .read()
2466 36 : .await
2467 36 : .layer_map()
2468 36 : .unwrap()
2469 36 : .iter_historic_layers()
2470 172 : .map(|layer| layer.layer_name())
2471 36 : .collect_vec();
2472 36 : if let Some(err) = check_valid_layermap(&layer_names) {
2473 0 : bail!("invalid layermap: {err}");
2474 36 : }
2475 36 : Ok(tline)
2476 36 : }
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(*lsn, timeline::WaitLsnWaiter::Tenant, ctx)
2562 0 : .await
2563 0 : .map_err(|e| match e {
2564 0 : e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
2565 0 : CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
2566 : }
2567 0 : WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
2568 0 : })?;
2569 0 : }
2570 :
2571 0 : self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
2572 0 : .await?
2573 : }
2574 0 : CreateTimelineParams::ImportPgdata(params) => {
2575 0 : self.create_timeline_import_pgdata(
2576 0 : params,
2577 0 : ActivateTimelineArgs::Yes {
2578 0 : broker_client: broker_client.clone(),
2579 0 : },
2580 0 : ctx,
2581 0 : )
2582 0 : .await?
2583 : }
2584 : };
2585 :
2586 : // At this point we have dropped our guard on [`Self::timelines_creating`], and
2587 : // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet. We must
2588 : // not send a success to the caller until it is. The same applies to idempotent retries.
2589 : //
2590 : // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
2591 : // assume that, because they can see the timeline via API, that the creation is done and
2592 : // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
2593 : // until it is durable, e.g., by extending the time we hold the creation guard. This also
2594 : // interacts with UninitializedTimeline and is generally a bit tricky.
2595 : //
2596 : // To re-emphasize: the only correct way to create a timeline is to repeat calling the
2597 : // creation API until it returns success. Only then is durability guaranteed.
2598 0 : info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
2599 0 : result
2600 0 : .timeline()
2601 0 : .remote_client
2602 0 : .wait_completion()
2603 0 : .await
2604 0 : .map_err(|e| match e {
2605 : WaitCompletionError::NotInitialized(
2606 0 : e, // If the queue is already stopped, it's a shutdown error.
2607 0 : ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
2608 : WaitCompletionError::NotInitialized(_) => {
2609 : // This is a bug: we should never try to wait for uploads before initializing the timeline
2610 0 : debug_assert!(false);
2611 0 : CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
2612 : }
2613 : WaitCompletionError::UploadQueueShutDownOrStopped => {
2614 0 : CreateTimelineError::ShuttingDown
2615 : }
2616 0 : })?;
2617 :
2618 : // The creating task is responsible for activating the timeline.
2619 : // We do this after `wait_completion()` so that we don't spin up tasks that start
2620 : // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
2621 0 : let activated_timeline = match result {
2622 0 : CreateTimelineResult::Created(timeline) => {
2623 0 : timeline.activate(self.clone(), broker_client, None, ctx);
2624 0 : timeline
2625 : }
2626 0 : CreateTimelineResult::Idempotent(timeline) => {
2627 0 : info!(
2628 0 : "request was deemed idempotent, activation will be done by the creating task"
2629 : );
2630 0 : timeline
2631 : }
2632 0 : CreateTimelineResult::ImportSpawned(timeline) => {
2633 0 : info!("import task spawned, timeline will become visible and activated once the import is done");
2634 0 : timeline
2635 : }
2636 : };
2637 :
2638 0 : Ok(activated_timeline)
2639 0 : }
2640 :
2641 : /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
2642 : /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
2643 : /// [`Tenant::timelines`] map when the import completes.
2644 : /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
2645 : /// for the response.
2646 0 : async fn create_timeline_import_pgdata(
2647 0 : self: &Arc<Tenant>,
2648 0 : params: CreateTimelineParamsImportPgdata,
2649 0 : activate: ActivateTimelineArgs,
2650 0 : ctx: &RequestContext,
2651 0 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
2652 0 : let CreateTimelineParamsImportPgdata {
2653 0 : new_timeline_id,
2654 0 : location,
2655 0 : idempotency_key,
2656 0 : } = params;
2657 0 :
2658 0 : let started_at = chrono::Utc::now().naive_utc();
2659 :
2660 : //
2661 : // There's probably a simpler way to upload an index part, but, remote_timeline_client
2662 : // is the canonical way we do it.
2663 : // - create an empty timeline in-memory
2664 : // - use its remote_timeline_client to do the upload
2665 : // - dispose of the uninit timeline
2666 : // - keep the creation guard alive
2667 :
2668 0 : let timeline_create_guard = match self
2669 0 : .start_creating_timeline(
2670 0 : new_timeline_id,
2671 0 : CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
2672 0 : idempotency_key: idempotency_key.clone(),
2673 0 : }),
2674 0 : )
2675 0 : .await?
2676 : {
2677 0 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
2678 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
2679 0 : return Ok(CreateTimelineResult::Idempotent(timeline))
2680 : }
2681 : };
2682 :
2683 0 : let mut uninit_timeline = {
2684 0 : let this = &self;
2685 0 : let initdb_lsn = Lsn(0);
2686 0 : let _ctx = ctx;
2687 0 : async move {
2688 0 : let new_metadata = TimelineMetadata::new(
2689 0 : // Initialize disk_consistent LSN to 0, The caller must import some data to
2690 0 : // make it valid, before calling finish_creation()
2691 0 : Lsn(0),
2692 0 : None,
2693 0 : None,
2694 0 : Lsn(0),
2695 0 : initdb_lsn,
2696 0 : initdb_lsn,
2697 0 : 15,
2698 0 : );
2699 0 : this.prepare_new_timeline(
2700 0 : new_timeline_id,
2701 0 : &new_metadata,
2702 0 : timeline_create_guard,
2703 0 : initdb_lsn,
2704 0 : None,
2705 0 : )
2706 0 : .await
2707 0 : }
2708 0 : }
2709 0 : .await?;
2710 :
2711 0 : let in_progress = import_pgdata::index_part_format::InProgress {
2712 0 : idempotency_key,
2713 0 : location,
2714 0 : started_at,
2715 0 : };
2716 0 : let index_part = import_pgdata::index_part_format::Root::V1(
2717 0 : import_pgdata::index_part_format::V1::InProgress(in_progress),
2718 0 : );
2719 0 : uninit_timeline
2720 0 : .raw_timeline()
2721 0 : .unwrap()
2722 0 : .remote_client
2723 0 : .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
2724 :
2725 : // wait_completion happens in caller
2726 :
2727 0 : let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
2728 0 :
2729 0 : tokio::spawn(self.clone().create_timeline_import_pgdata_task(
2730 0 : timeline.clone(),
2731 0 : index_part,
2732 0 : activate,
2733 0 : timeline_create_guard,
2734 0 : ));
2735 0 :
2736 0 : // NB: the timeline doesn't exist in self.timelines at this point
2737 0 : Ok(CreateTimelineResult::ImportSpawned(timeline))
2738 0 : }
2739 :
2740 : #[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))]
2741 : async fn create_timeline_import_pgdata_task(
2742 : self: Arc<Tenant>,
2743 : timeline: Arc<Timeline>,
2744 : index_part: import_pgdata::index_part_format::Root,
2745 : activate: ActivateTimelineArgs,
2746 : timeline_create_guard: TimelineCreateGuard,
2747 : ) {
2748 : debug_assert_current_span_has_tenant_and_timeline_id();
2749 : info!("starting");
2750 : scopeguard::defer! {info!("exiting")};
2751 :
2752 : let res = self
2753 : .create_timeline_import_pgdata_task_impl(
2754 : timeline,
2755 : index_part,
2756 : activate,
2757 : timeline_create_guard,
2758 : )
2759 : .await;
2760 : if let Err(err) = &res {
2761 : error!(?err, "task failed");
2762 : // TODO sleep & retry, sensitive to tenant shutdown
2763 : // TODO: allow timeline deletion requests => should cancel the task
2764 : }
2765 : }
2766 :
2767 0 : async fn create_timeline_import_pgdata_task_impl(
2768 0 : self: Arc<Tenant>,
2769 0 : timeline: Arc<Timeline>,
2770 0 : index_part: import_pgdata::index_part_format::Root,
2771 0 : activate: ActivateTimelineArgs,
2772 0 : timeline_create_guard: TimelineCreateGuard,
2773 0 : ) -> Result<(), anyhow::Error> {
2774 0 : let ctx = RequestContext::new(TaskKind::ImportPgdata, DownloadBehavior::Warn);
2775 0 :
2776 0 : info!("importing pgdata");
2777 0 : import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
2778 0 : .await
2779 0 : .context("import")?;
2780 0 : info!("import done");
2781 :
2782 : //
2783 : // Reload timeline from remote.
2784 : // This proves that the remote state is attachable, and it reuses the code.
2785 : //
2786 : // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
2787 : // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
2788 : // But our activate() call might launch new background tasks after Tenant::shutdown
2789 : // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
2790 : // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
2791 : // down while bootstrapping/branching + activating), but, the race condition is much more likely
2792 : // to manifest because of the long runtime of this import task.
2793 :
2794 : // in theory this shouldn't even .await anything except for coop yield
2795 0 : info!("shutting down timeline");
2796 0 : timeline.shutdown(ShutdownMode::Hard).await;
2797 0 : info!("timeline shut down, reloading from remote");
2798 : // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
2799 : // let Some(timeline) = Arc::into_inner(timeline) else {
2800 : // anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
2801 : // };
2802 0 : let timeline_id = timeline.timeline_id;
2803 0 :
2804 0 : // load from object storage like Tenant::attach does
2805 0 : let resources = self.build_timeline_resources(timeline_id);
2806 0 : let index_part = resources
2807 0 : .remote_client
2808 0 : .download_index_file(&self.cancel)
2809 0 : .await?;
2810 0 : let index_part = match index_part {
2811 : MaybeDeletedIndexPart::Deleted(_) => {
2812 : // likely concurrent delete call, cplane should prevent this
2813 0 : anyhow::bail!("index part says deleted but we are not done creating yet, this should not happen but")
2814 : }
2815 0 : MaybeDeletedIndexPart::IndexPart(p) => p,
2816 0 : };
2817 0 : let metadata = index_part.metadata.clone();
2818 0 : self
2819 0 : .load_remote_timeline(timeline_id, index_part, metadata, resources, LoadTimelineCause::ImportPgdata{
2820 0 : create_guard: timeline_create_guard, activate, }, &ctx)
2821 0 : .await?
2822 0 : .ready_to_activate()
2823 0 : .context("implementation error: reloaded timeline still needs import after import reported success")?;
2824 :
2825 0 : anyhow::Ok(())
2826 0 : }
2827 :
2828 0 : pub(crate) async fn delete_timeline(
2829 0 : self: Arc<Self>,
2830 0 : timeline_id: TimelineId,
2831 0 : ) -> Result<(), DeleteTimelineError> {
2832 0 : DeleteTimelineFlow::run(&self, timeline_id).await?;
2833 :
2834 0 : Ok(())
2835 0 : }
2836 :
2837 : /// perform one garbage collection iteration, removing old data files from disk.
2838 : /// this function is periodically called by gc task.
2839 : /// also it can be explicitly requested through page server api 'do_gc' command.
2840 : ///
2841 : /// `target_timeline_id` specifies the timeline to GC, or None for all.
2842 : ///
2843 : /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
2844 : /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
2845 : /// the amount of history, as LSN difference from current latest LSN on each timeline.
2846 : /// `pitr` specifies the same as a time difference from the current time. The effective
2847 : /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
2848 : /// requires more history to be retained.
2849 : //
2850 754 : pub(crate) async fn gc_iteration(
2851 754 : &self,
2852 754 : target_timeline_id: Option<TimelineId>,
2853 754 : horizon: u64,
2854 754 : pitr: Duration,
2855 754 : cancel: &CancellationToken,
2856 754 : ctx: &RequestContext,
2857 754 : ) -> Result<GcResult, GcError> {
2858 754 : // Don't start doing work during shutdown
2859 754 : if let TenantState::Stopping { .. } = self.current_state() {
2860 0 : return Ok(GcResult::default());
2861 754 : }
2862 754 :
2863 754 : // there is a global allowed_error for this
2864 754 : if !self.is_active() {
2865 0 : return Err(GcError::NotActive);
2866 754 : }
2867 754 :
2868 754 : {
2869 754 : let conf = self.tenant_conf.load();
2870 754 :
2871 754 : // If we may not delete layers, then simply skip GC. Even though a tenant
2872 754 : // in AttachedMulti state could do GC and just enqueue the blocked deletions,
2873 754 : // the only advantage to doing it is to perhaps shrink the LayerMap metadata
2874 754 : // a bit sooner than we would achieve by waiting for AttachedSingle status.
2875 754 : if !conf.location.may_delete_layers_hint() {
2876 0 : info!("Skipping GC in location state {:?}", conf.location);
2877 0 : return Ok(GcResult::default());
2878 754 : }
2879 754 :
2880 754 : if conf.is_gc_blocked_by_lsn_lease_deadline() {
2881 750 : info!("Skipping GC because lsn lease deadline is not reached");
2882 750 : return Ok(GcResult::default());
2883 4 : }
2884 : }
2885 :
2886 4 : let _guard = match self.gc_block.start().await {
2887 4 : Ok(guard) => guard,
2888 0 : Err(reasons) => {
2889 0 : info!("Skipping GC: {reasons}");
2890 0 : return Ok(GcResult::default());
2891 : }
2892 : };
2893 :
2894 4 : self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
2895 4 : .await
2896 754 : }
2897 :
2898 : /// Perform one compaction iteration.
2899 : /// This function is periodically called by compactor task.
2900 : /// Also it can be explicitly requested per timeline through page server
2901 : /// api's 'compact' command.
2902 : ///
2903 : /// Returns whether we have pending compaction task.
2904 0 : async fn compaction_iteration(
2905 0 : self: &Arc<Self>,
2906 0 : cancel: &CancellationToken,
2907 0 : ctx: &RequestContext,
2908 0 : ) -> Result<bool, timeline::CompactionError> {
2909 0 : // Don't start doing work during shutdown, or when broken, we do not need those in the logs
2910 0 : if !self.is_active() {
2911 0 : return Ok(false);
2912 0 : }
2913 0 :
2914 0 : {
2915 0 : let conf = self.tenant_conf.load();
2916 0 :
2917 0 : // Note that compaction usually requires deletions, but we don't respect
2918 0 : // may_delete_layers_hint here: that is because tenants in AttachedMulti
2919 0 : // should proceed with compaction even if they can't do deletion, to avoid
2920 0 : // accumulating dangerously deep stacks of L0 layers. Deletions will be
2921 0 : // enqueued inside RemoteTimelineClient, and executed layer if/when we transition
2922 0 : // to AttachedSingle state.
2923 0 : if !conf.location.may_upload_layers_hint() {
2924 0 : info!("Skipping compaction in location state {:?}", conf.location);
2925 0 : return Ok(false);
2926 0 : }
2927 0 : }
2928 0 :
2929 0 : // Scan through the hashmap and collect a list of all the timelines,
2930 0 : // while holding the lock. Then drop the lock and actually perform the
2931 0 : // compactions. We don't want to block everything else while the
2932 0 : // compaction runs.
2933 0 : let timelines_to_compact_or_offload;
2934 0 : {
2935 0 : let timelines = self.timelines.lock().unwrap();
2936 0 : timelines_to_compact_or_offload = timelines
2937 0 : .iter()
2938 0 : .filter_map(|(timeline_id, timeline)| {
2939 0 : let (is_active, (can_offload, _)) =
2940 0 : (timeline.is_active(), timeline.can_offload());
2941 0 : let has_no_unoffloaded_children = {
2942 0 : !timelines
2943 0 : .iter()
2944 0 : .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(*timeline_id))
2945 : };
2946 0 : let config_allows_offload = self.conf.timeline_offloading
2947 0 : || self
2948 0 : .tenant_conf
2949 0 : .load()
2950 0 : .tenant_conf
2951 0 : .timeline_offloading
2952 0 : .unwrap_or_default();
2953 0 : let can_offload =
2954 0 : can_offload && has_no_unoffloaded_children && config_allows_offload;
2955 0 : if (is_active, can_offload) == (false, false) {
2956 0 : None
2957 : } else {
2958 0 : Some((*timeline_id, timeline.clone(), (is_active, can_offload)))
2959 : }
2960 0 : })
2961 0 : .collect::<Vec<_>>();
2962 0 : drop(timelines);
2963 0 : }
2964 0 :
2965 0 : // Before doing any I/O work, check our circuit breaker
2966 0 : if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
2967 0 : info!("Skipping compaction due to previous failures");
2968 0 : return Ok(false);
2969 0 : }
2970 0 :
2971 0 : let mut has_pending_task = false;
2972 :
2973 0 : for (timeline_id, timeline, (can_compact, can_offload)) in &timelines_to_compact_or_offload
2974 : {
2975 : // pending_task_left == None: cannot compact, maybe still pending tasks
2976 : // pending_task_left == Some(true): compaction task left
2977 : // pending_task_left == Some(false): no compaction task left
2978 0 : let pending_task_left = if *can_compact {
2979 0 : let has_pending_l0_compaction_task = timeline
2980 0 : .compact(cancel, EnumSet::empty(), ctx)
2981 0 : .instrument(info_span!("compact_timeline", %timeline_id))
2982 0 : .await
2983 0 : .inspect_err(|e| match e {
2984 0 : timeline::CompactionError::ShuttingDown => (),
2985 0 : timeline::CompactionError::Offload(_) => {
2986 0 : // Failures to offload timelines do not trip the circuit breaker, because
2987 0 : // they do not do lots of writes the way compaction itself does: it is cheap
2988 0 : // to retry, and it would be bad to stop all compaction because of an issue with offloading.
2989 0 : }
2990 0 : timeline::CompactionError::Other(e) => {
2991 0 : self.compaction_circuit_breaker
2992 0 : .lock()
2993 0 : .unwrap()
2994 0 : .fail(&CIRCUIT_BREAKERS_BROKEN, e);
2995 0 : }
2996 0 : })?;
2997 0 : if has_pending_l0_compaction_task {
2998 0 : Some(true)
2999 : } else {
3000 : let mut has_pending_scheduled_compaction_task;
3001 0 : let next_scheduled_compaction_task = {
3002 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3003 0 : if let Some(tline_pending_tasks) = guard.get_mut(timeline_id) {
3004 0 : if !tline_pending_tasks.is_empty() {
3005 0 : info!(
3006 0 : "{} tasks left in the compaction schedule queue",
3007 0 : tline_pending_tasks.len()
3008 : );
3009 0 : }
3010 0 : let next_task = tline_pending_tasks.pop_front();
3011 0 : has_pending_scheduled_compaction_task = !tline_pending_tasks.is_empty();
3012 0 : next_task
3013 : } else {
3014 0 : has_pending_scheduled_compaction_task = false;
3015 0 : None
3016 : }
3017 : };
3018 0 : if let Some(mut next_scheduled_compaction_task) = next_scheduled_compaction_task
3019 : {
3020 0 : if !next_scheduled_compaction_task
3021 0 : .options
3022 0 : .flags
3023 0 : .contains(CompactFlags::EnhancedGcBottomMostCompaction)
3024 : {
3025 0 : warn!("ignoring scheduled compaction task: scheduled task must be gc compaction: {:?}", next_scheduled_compaction_task.options);
3026 0 : } else if next_scheduled_compaction_task.options.sub_compaction {
3027 0 : info!("running scheduled enhanced gc bottom-most compaction with sub-compaction, splitting compaction jobs");
3028 0 : let jobs: Vec<GcCompactJob> = timeline
3029 0 : .gc_compaction_split_jobs(
3030 0 : GcCompactJob::from_compact_options(
3031 0 : next_scheduled_compaction_task.options.clone(),
3032 0 : ),
3033 0 : next_scheduled_compaction_task
3034 0 : .options
3035 0 : .sub_compaction_max_job_size_mb,
3036 0 : )
3037 0 : .await
3038 0 : .map_err(CompactionError::Other)?;
3039 0 : if jobs.is_empty() {
3040 0 : info!("no jobs to run, skipping scheduled compaction task");
3041 : } else {
3042 0 : has_pending_scheduled_compaction_task = true;
3043 0 : let jobs_len = jobs.len();
3044 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3045 0 : let tline_pending_tasks = guard.entry(*timeline_id).or_default();
3046 0 : for (idx, job) in jobs.into_iter().enumerate() {
3047 : // Unfortunately we need to convert the `GcCompactJob` back to `CompactionOptions`
3048 : // until we do further refactors to allow directly call `compact_with_gc`.
3049 0 : let mut flags: EnumSet<CompactFlags> = EnumSet::default();
3050 0 : flags |= CompactFlags::EnhancedGcBottomMostCompaction;
3051 0 : if job.dry_run {
3052 0 : flags |= CompactFlags::DryRun;
3053 0 : }
3054 0 : let options = CompactOptions {
3055 0 : flags,
3056 0 : sub_compaction: false,
3057 0 : compact_key_range: Some(job.compact_key_range.into()),
3058 0 : compact_lsn_range: Some(job.compact_lsn_range.into()),
3059 0 : sub_compaction_max_job_size_mb: None,
3060 0 : };
3061 0 : tline_pending_tasks.push_back(if idx == jobs_len - 1 {
3062 0 : ScheduledCompactionTask {
3063 0 : options,
3064 0 : // The last job in the queue sends the signal and releases the gc guard
3065 0 : result_tx: next_scheduled_compaction_task
3066 0 : .result_tx
3067 0 : .take(),
3068 0 : gc_block: next_scheduled_compaction_task
3069 0 : .gc_block
3070 0 : .take(),
3071 0 : }
3072 : } else {
3073 0 : ScheduledCompactionTask {
3074 0 : options,
3075 0 : result_tx: None,
3076 0 : gc_block: None,
3077 0 : }
3078 : });
3079 : }
3080 0 : info!("scheduled enhanced gc bottom-most compaction with sub-compaction, split into {} jobs", jobs_len);
3081 : }
3082 : } else {
3083 0 : let _ = timeline
3084 0 : .compact_with_options(
3085 0 : cancel,
3086 0 : next_scheduled_compaction_task.options,
3087 0 : ctx,
3088 0 : )
3089 0 : .instrument(info_span!("scheduled_compact_timeline", %timeline_id))
3090 0 : .await?;
3091 0 : if let Some(tx) = next_scheduled_compaction_task.result_tx.take() {
3092 0 : // TODO: we can send compaction statistics in the future
3093 0 : tx.send(()).ok();
3094 0 : }
3095 : }
3096 0 : }
3097 0 : Some(has_pending_scheduled_compaction_task)
3098 : }
3099 : } else {
3100 0 : None
3101 : };
3102 0 : has_pending_task |= pending_task_left.unwrap_or(false);
3103 0 : if pending_task_left == Some(false) && *can_offload {
3104 0 : pausable_failpoint!("before-timeline-auto-offload");
3105 0 : match offload_timeline(self, timeline)
3106 0 : .instrument(info_span!("offload_timeline", %timeline_id))
3107 0 : .await
3108 : {
3109 : Err(OffloadError::NotArchived) => {
3110 : // Ignore this, we likely raced with unarchival
3111 0 : Ok(())
3112 : }
3113 0 : other => other,
3114 0 : }?;
3115 0 : }
3116 : }
3117 :
3118 0 : self.compaction_circuit_breaker
3119 0 : .lock()
3120 0 : .unwrap()
3121 0 : .success(&CIRCUIT_BREAKERS_UNBROKEN);
3122 0 :
3123 0 : Ok(has_pending_task)
3124 0 : }
3125 :
3126 : /// Cancel scheduled compaction tasks
3127 0 : pub(crate) fn cancel_scheduled_compaction(
3128 0 : &self,
3129 0 : timeline_id: TimelineId,
3130 0 : ) -> Vec<ScheduledCompactionTask> {
3131 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3132 0 : if let Some(tline_pending_tasks) = guard.get_mut(&timeline_id) {
3133 0 : let current_tline_pending_tasks = std::mem::take(tline_pending_tasks);
3134 0 : current_tline_pending_tasks.into_iter().collect()
3135 : } else {
3136 0 : Vec::new()
3137 : }
3138 0 : }
3139 :
3140 0 : pub(crate) fn get_scheduled_compaction_tasks(
3141 0 : &self,
3142 0 : timeline_id: TimelineId,
3143 0 : ) -> Vec<CompactOptions> {
3144 : use itertools::Itertools;
3145 0 : let guard = self.scheduled_compaction_tasks.lock().unwrap();
3146 0 : guard
3147 0 : .get(&timeline_id)
3148 0 : .map(|tline_pending_tasks| {
3149 0 : tline_pending_tasks
3150 0 : .iter()
3151 0 : .map(|x| x.options.clone())
3152 0 : .collect_vec()
3153 0 : })
3154 0 : .unwrap_or_default()
3155 0 : }
3156 :
3157 : /// Schedule a compaction task for a timeline.
3158 0 : pub(crate) async fn schedule_compaction(
3159 0 : &self,
3160 0 : timeline_id: TimelineId,
3161 0 : options: CompactOptions,
3162 0 : ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
3163 0 : let gc_guard = match self.gc_block.start().await {
3164 0 : Ok(guard) => guard,
3165 0 : Err(e) => {
3166 0 : bail!("cannot run gc-compaction because gc is blocked: {}", e);
3167 : }
3168 : };
3169 0 : let (tx, rx) = tokio::sync::oneshot::channel();
3170 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3171 0 : let tline_pending_tasks = guard.entry(timeline_id).or_default();
3172 0 : tline_pending_tasks.push_back(ScheduledCompactionTask {
3173 0 : options,
3174 0 : result_tx: Some(tx),
3175 0 : gc_block: Some(gc_guard),
3176 0 : });
3177 0 : Ok(rx)
3178 0 : }
3179 :
3180 : // Call through to all timelines to freeze ephemeral layers if needed. Usually
3181 : // this happens during ingest: this background housekeeping is for freezing layers
3182 : // that are open but haven't been written to for some time.
3183 0 : async fn ingest_housekeeping(&self) {
3184 0 : // Scan through the hashmap and collect a list of all the timelines,
3185 0 : // while holding the lock. Then drop the lock and actually perform the
3186 0 : // compactions. We don't want to block everything else while the
3187 0 : // compaction runs.
3188 0 : let timelines = {
3189 0 : self.timelines
3190 0 : .lock()
3191 0 : .unwrap()
3192 0 : .values()
3193 0 : .filter_map(|timeline| {
3194 0 : if timeline.is_active() {
3195 0 : Some(timeline.clone())
3196 : } else {
3197 0 : None
3198 : }
3199 0 : })
3200 0 : .collect::<Vec<_>>()
3201 : };
3202 :
3203 0 : for timeline in &timelines {
3204 0 : timeline.maybe_freeze_ephemeral_layer().await;
3205 : }
3206 0 : }
3207 :
3208 0 : pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
3209 0 : let timelines = self.timelines.lock().unwrap();
3210 0 : !timelines
3211 0 : .iter()
3212 0 : .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
3213 0 : }
3214 :
3215 1708 : pub fn current_state(&self) -> TenantState {
3216 1708 : self.state.borrow().clone()
3217 1708 : }
3218 :
3219 946 : pub fn is_active(&self) -> bool {
3220 946 : self.current_state() == TenantState::Active
3221 946 : }
3222 :
3223 0 : pub fn generation(&self) -> Generation {
3224 0 : self.generation
3225 0 : }
3226 :
3227 0 : pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
3228 0 : self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
3229 0 : }
3230 :
3231 : /// Changes tenant status to active, unless shutdown was already requested.
3232 : ///
3233 : /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
3234 : /// to delay background jobs. Background jobs can be started right away when None is given.
3235 0 : fn activate(
3236 0 : self: &Arc<Self>,
3237 0 : broker_client: BrokerClientChannel,
3238 0 : background_jobs_can_start: Option<&completion::Barrier>,
3239 0 : ctx: &RequestContext,
3240 0 : ) {
3241 0 : span::debug_assert_current_span_has_tenant_id();
3242 0 :
3243 0 : let mut activating = false;
3244 0 : self.state.send_modify(|current_state| {
3245 : use pageserver_api::models::ActivatingFrom;
3246 0 : match &*current_state {
3247 : TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
3248 0 : panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
3249 : }
3250 0 : TenantState::Attaching => {
3251 0 : *current_state = TenantState::Activating(ActivatingFrom::Attaching);
3252 0 : }
3253 0 : }
3254 0 : debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
3255 0 : activating = true;
3256 0 : // Continue outside the closure. We need to grab timelines.lock()
3257 0 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
3258 0 : });
3259 0 :
3260 0 : if activating {
3261 0 : let timelines_accessor = self.timelines.lock().unwrap();
3262 0 : let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
3263 0 : let timelines_to_activate = timelines_accessor
3264 0 : .values()
3265 0 : .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
3266 0 :
3267 0 : // Before activation, populate each Timeline's GcInfo with information about its children
3268 0 : self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
3269 0 :
3270 0 : // Spawn gc and compaction loops. The loops will shut themselves
3271 0 : // down when they notice that the tenant is inactive.
3272 0 : tasks::start_background_loops(self, background_jobs_can_start);
3273 0 :
3274 0 : let mut activated_timelines = 0;
3275 :
3276 0 : for timeline in timelines_to_activate {
3277 0 : timeline.activate(
3278 0 : self.clone(),
3279 0 : broker_client.clone(),
3280 0 : background_jobs_can_start,
3281 0 : ctx,
3282 0 : );
3283 0 : activated_timelines += 1;
3284 0 : }
3285 :
3286 0 : self.state.send_modify(move |current_state| {
3287 0 : assert!(
3288 0 : matches!(current_state, TenantState::Activating(_)),
3289 0 : "set_stopping and set_broken wait for us to leave Activating state",
3290 : );
3291 0 : *current_state = TenantState::Active;
3292 0 :
3293 0 : let elapsed = self.constructed_at.elapsed();
3294 0 : let total_timelines = timelines_accessor.len();
3295 0 :
3296 0 : // log a lot of stuff, because some tenants sometimes suffer from user-visible
3297 0 : // times to activate. see https://github.com/neondatabase/neon/issues/4025
3298 0 : info!(
3299 0 : since_creation_millis = elapsed.as_millis(),
3300 0 : tenant_id = %self.tenant_shard_id.tenant_id,
3301 0 : shard_id = %self.tenant_shard_id.shard_slug(),
3302 0 : activated_timelines,
3303 0 : total_timelines,
3304 0 : post_state = <&'static str>::from(&*current_state),
3305 0 : "activation attempt finished"
3306 : );
3307 :
3308 0 : TENANT.activation.observe(elapsed.as_secs_f64());
3309 0 : });
3310 0 : }
3311 0 : }
3312 :
3313 : /// Shutdown the tenant and join all of the spawned tasks.
3314 : ///
3315 : /// The method caters for all use-cases:
3316 : /// - pageserver shutdown (freeze_and_flush == true)
3317 : /// - detach + ignore (freeze_and_flush == false)
3318 : ///
3319 : /// This will attempt to shutdown even if tenant is broken.
3320 : ///
3321 : /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
3322 : /// If the tenant is already shutting down, we return a clone of the first shutdown call's
3323 : /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
3324 : /// the ongoing shutdown.
3325 6 : async fn shutdown(
3326 6 : &self,
3327 6 : shutdown_progress: completion::Barrier,
3328 6 : shutdown_mode: timeline::ShutdownMode,
3329 6 : ) -> Result<(), completion::Barrier> {
3330 6 : span::debug_assert_current_span_has_tenant_id();
3331 :
3332 : // Set tenant (and its timlines) to Stoppping state.
3333 : //
3334 : // Since we can only transition into Stopping state after activation is complete,
3335 : // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
3336 : //
3337 : // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
3338 : // 1. Lock out any new requests to the tenants.
3339 : // 2. Signal cancellation to WAL receivers (we wait on it below).
3340 : // 3. Signal cancellation for other tenant background loops.
3341 : // 4. ???
3342 : //
3343 : // The waiting for the cancellation is not done uniformly.
3344 : // We certainly wait for WAL receivers to shut down.
3345 : // That is necessary so that no new data comes in before the freeze_and_flush.
3346 : // But the tenant background loops are joined-on in our caller.
3347 : // It's mesed up.
3348 : // we just ignore the failure to stop
3349 :
3350 : // If we're still attaching, fire the cancellation token early to drop out: this
3351 : // will prevent us flushing, but ensures timely shutdown if some I/O during attach
3352 : // is very slow.
3353 6 : let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
3354 0 : self.cancel.cancel();
3355 0 :
3356 0 : // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
3357 0 : // are children of ours, so their flush loops will have shut down already
3358 0 : timeline::ShutdownMode::Hard
3359 : } else {
3360 6 : shutdown_mode
3361 : };
3362 :
3363 6 : match self.set_stopping(shutdown_progress, false, false).await {
3364 6 : Ok(()) => {}
3365 0 : Err(SetStoppingError::Broken) => {
3366 0 : // assume that this is acceptable
3367 0 : }
3368 0 : Err(SetStoppingError::AlreadyStopping(other)) => {
3369 0 : // give caller the option to wait for this this shutdown
3370 0 : info!("Tenant::shutdown: AlreadyStopping");
3371 0 : return Err(other);
3372 : }
3373 : };
3374 :
3375 6 : let mut js = tokio::task::JoinSet::new();
3376 6 : {
3377 6 : let timelines = self.timelines.lock().unwrap();
3378 6 : timelines.values().for_each(|timeline| {
3379 6 : let timeline = Arc::clone(timeline);
3380 6 : let timeline_id = timeline.timeline_id;
3381 6 : let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
3382 6 : js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
3383 6 : });
3384 6 : }
3385 6 : {
3386 6 : let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
3387 6 : timelines_offloaded.values().for_each(|timeline| {
3388 0 : timeline.defuse_for_tenant_drop();
3389 6 : });
3390 6 : }
3391 6 : // test_long_timeline_create_then_tenant_delete is leaning on this message
3392 6 : tracing::info!("Waiting for timelines...");
3393 12 : while let Some(res) = js.join_next().await {
3394 0 : match res {
3395 6 : Ok(()) => {}
3396 0 : Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
3397 0 : Err(je) if je.is_panic() => { /* logged already */ }
3398 0 : Err(je) => warn!("unexpected JoinError: {je:?}"),
3399 : }
3400 : }
3401 :
3402 6 : if let ShutdownMode::Reload = shutdown_mode {
3403 0 : tracing::info!("Flushing deletion queue");
3404 0 : if let Err(e) = self.deletion_queue_client.flush().await {
3405 0 : match e {
3406 0 : DeletionQueueError::ShuttingDown => {
3407 0 : // This is the only error we expect for now. In the future, if more error
3408 0 : // variants are added, we should handle them here.
3409 0 : }
3410 : }
3411 0 : }
3412 6 : }
3413 :
3414 : // We cancel the Tenant's cancellation token _after_ the timelines have all shut down. This permits
3415 : // them to continue to do work during their shutdown methods, e.g. flushing data.
3416 6 : tracing::debug!("Cancelling CancellationToken");
3417 6 : self.cancel.cancel();
3418 6 :
3419 6 : // shutdown all tenant and timeline tasks: gc, compaction, page service
3420 6 : // No new tasks will be started for this tenant because it's in `Stopping` state.
3421 6 : //
3422 6 : // this will additionally shutdown and await all timeline tasks.
3423 6 : tracing::debug!("Waiting for tasks...");
3424 6 : task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
3425 :
3426 6 : if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
3427 6 : walredo_mgr.shutdown().await;
3428 0 : }
3429 :
3430 : // Wait for any in-flight operations to complete
3431 6 : self.gate.close().await;
3432 :
3433 6 : remove_tenant_metrics(&self.tenant_shard_id);
3434 6 :
3435 6 : Ok(())
3436 6 : }
3437 :
3438 : /// Change tenant status to Stopping, to mark that it is being shut down.
3439 : ///
3440 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
3441 : ///
3442 : /// This function is not cancel-safe!
3443 : ///
3444 : /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
3445 : /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
3446 6 : async fn set_stopping(
3447 6 : &self,
3448 6 : progress: completion::Barrier,
3449 6 : _allow_transition_from_loading: bool,
3450 6 : allow_transition_from_attaching: bool,
3451 6 : ) -> Result<(), SetStoppingError> {
3452 6 : let mut rx = self.state.subscribe();
3453 6 :
3454 6 : // cannot stop before we're done activating, so wait out until we're done activating
3455 6 : rx.wait_for(|state| match state {
3456 0 : TenantState::Attaching if allow_transition_from_attaching => true,
3457 : TenantState::Activating(_) | TenantState::Attaching => {
3458 0 : info!(
3459 0 : "waiting for {} to turn Active|Broken|Stopping",
3460 0 : <&'static str>::from(state)
3461 : );
3462 0 : false
3463 : }
3464 6 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
3465 6 : })
3466 6 : .await
3467 6 : .expect("cannot drop self.state while on a &self method");
3468 6 :
3469 6 : // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
3470 6 : let mut err = None;
3471 6 : let stopping = self.state.send_if_modified(|current_state| match current_state {
3472 : TenantState::Activating(_) => {
3473 0 : unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
3474 : }
3475 : TenantState::Attaching => {
3476 0 : if !allow_transition_from_attaching {
3477 0 : unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
3478 0 : };
3479 0 : *current_state = TenantState::Stopping { progress };
3480 0 : true
3481 : }
3482 : TenantState::Active => {
3483 : // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
3484 : // are created after the transition to Stopping. That's harmless, as the Timelines
3485 : // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
3486 6 : *current_state = TenantState::Stopping { progress };
3487 6 : // Continue stopping outside the closure. We need to grab timelines.lock()
3488 6 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
3489 6 : true
3490 : }
3491 0 : TenantState::Broken { reason, .. } => {
3492 0 : info!(
3493 0 : "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
3494 : );
3495 0 : err = Some(SetStoppingError::Broken);
3496 0 : false
3497 : }
3498 0 : TenantState::Stopping { progress } => {
3499 0 : info!("Tenant is already in Stopping state");
3500 0 : err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
3501 0 : false
3502 : }
3503 6 : });
3504 6 : match (stopping, err) {
3505 6 : (true, None) => {} // continue
3506 0 : (false, Some(err)) => return Err(err),
3507 0 : (true, Some(_)) => unreachable!(
3508 0 : "send_if_modified closure must error out if not transitioning to Stopping"
3509 0 : ),
3510 0 : (false, None) => unreachable!(
3511 0 : "send_if_modified closure must return true if transitioning to Stopping"
3512 0 : ),
3513 : }
3514 :
3515 6 : let timelines_accessor = self.timelines.lock().unwrap();
3516 6 : let not_broken_timelines = timelines_accessor
3517 6 : .values()
3518 6 : .filter(|timeline| !timeline.is_broken());
3519 12 : for timeline in not_broken_timelines {
3520 6 : timeline.set_state(TimelineState::Stopping);
3521 6 : }
3522 6 : Ok(())
3523 6 : }
3524 :
3525 : /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
3526 : /// `remove_tenant_from_memory`
3527 : ///
3528 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
3529 : ///
3530 : /// In tests, we also use this to set tenants to Broken state on purpose.
3531 0 : pub(crate) async fn set_broken(&self, reason: String) {
3532 0 : let mut rx = self.state.subscribe();
3533 0 :
3534 0 : // The load & attach routines own the tenant state until it has reached `Active`.
3535 0 : // So, wait until it's done.
3536 0 : rx.wait_for(|state| match state {
3537 : TenantState::Activating(_) | TenantState::Attaching => {
3538 0 : info!(
3539 0 : "waiting for {} to turn Active|Broken|Stopping",
3540 0 : <&'static str>::from(state)
3541 : );
3542 0 : false
3543 : }
3544 0 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
3545 0 : })
3546 0 : .await
3547 0 : .expect("cannot drop self.state while on a &self method");
3548 0 :
3549 0 : // we now know we're done activating, let's see whether this task is the winner to transition into Broken
3550 0 : self.set_broken_no_wait(reason)
3551 0 : }
3552 :
3553 0 : pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
3554 0 : let reason = reason.to_string();
3555 0 : self.state.send_modify(|current_state| {
3556 0 : match *current_state {
3557 : TenantState::Activating(_) | TenantState::Attaching => {
3558 0 : unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
3559 : }
3560 : TenantState::Active => {
3561 0 : if cfg!(feature = "testing") {
3562 0 : warn!("Changing Active tenant to Broken state, reason: {}", reason);
3563 0 : *current_state = TenantState::broken_from_reason(reason);
3564 : } else {
3565 0 : unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
3566 : }
3567 : }
3568 : TenantState::Broken { .. } => {
3569 0 : warn!("Tenant is already in Broken state");
3570 : }
3571 : // This is the only "expected" path, any other path is a bug.
3572 : TenantState::Stopping { .. } => {
3573 0 : warn!(
3574 0 : "Marking Stopping tenant as Broken state, reason: {}",
3575 : reason
3576 : );
3577 0 : *current_state = TenantState::broken_from_reason(reason);
3578 : }
3579 : }
3580 0 : });
3581 0 : }
3582 :
3583 0 : pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
3584 0 : self.state.subscribe()
3585 0 : }
3586 :
3587 : /// The activate_now semaphore is initialized with zero units. As soon as
3588 : /// we add a unit, waiters will be able to acquire a unit and proceed.
3589 0 : pub(crate) fn activate_now(&self) {
3590 0 : self.activate_now_sem.add_permits(1);
3591 0 : }
3592 :
3593 0 : pub(crate) async fn wait_to_become_active(
3594 0 : &self,
3595 0 : timeout: Duration,
3596 0 : ) -> Result<(), GetActiveTenantError> {
3597 0 : let mut receiver = self.state.subscribe();
3598 : loop {
3599 0 : let current_state = receiver.borrow_and_update().clone();
3600 0 : match current_state {
3601 : TenantState::Attaching | TenantState::Activating(_) => {
3602 : // in these states, there's a chance that we can reach ::Active
3603 0 : self.activate_now();
3604 0 : match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
3605 0 : Ok(r) => {
3606 0 : r.map_err(
3607 0 : |_e: tokio::sync::watch::error::RecvError|
3608 : // Tenant existed but was dropped: report it as non-existent
3609 0 : GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
3610 0 : )?
3611 : }
3612 : Err(TimeoutCancellableError::Cancelled) => {
3613 0 : return Err(GetActiveTenantError::Cancelled);
3614 : }
3615 : Err(TimeoutCancellableError::Timeout) => {
3616 0 : return Err(GetActiveTenantError::WaitForActiveTimeout {
3617 0 : latest_state: Some(self.current_state()),
3618 0 : wait_time: timeout,
3619 0 : });
3620 : }
3621 : }
3622 : }
3623 : TenantState::Active { .. } => {
3624 0 : return Ok(());
3625 : }
3626 0 : TenantState::Broken { reason, .. } => {
3627 0 : // This is fatal, and reported distinctly from the general case of "will never be active" because
3628 0 : // it's logically a 500 to external API users (broken is always a bug).
3629 0 : return Err(GetActiveTenantError::Broken(reason));
3630 : }
3631 : TenantState::Stopping { .. } => {
3632 : // There's no chance the tenant can transition back into ::Active
3633 0 : return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
3634 : }
3635 : }
3636 : }
3637 0 : }
3638 :
3639 0 : pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
3640 0 : self.tenant_conf.load().location.attach_mode
3641 0 : }
3642 :
3643 : /// For API access: generate a LocationConfig equivalent to the one that would be used to
3644 : /// create a Tenant in the same state. Do not use this in hot paths: it's for relatively
3645 : /// rare external API calls, like a reconciliation at startup.
3646 0 : pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
3647 0 : let conf = self.tenant_conf.load();
3648 :
3649 0 : let location_config_mode = match conf.location.attach_mode {
3650 0 : AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
3651 0 : AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
3652 0 : AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
3653 : };
3654 :
3655 : // We have a pageserver TenantConf, we need the API-facing TenantConfig.
3656 0 : let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
3657 0 :
3658 0 : models::LocationConfig {
3659 0 : mode: location_config_mode,
3660 0 : generation: self.generation.into(),
3661 0 : secondary_conf: None,
3662 0 : shard_number: self.shard_identity.number.0,
3663 0 : shard_count: self.shard_identity.count.literal(),
3664 0 : shard_stripe_size: self.shard_identity.stripe_size.0,
3665 0 : tenant_conf: tenant_config,
3666 0 : }
3667 0 : }
3668 :
3669 0 : pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
3670 0 : &self.tenant_shard_id
3671 0 : }
3672 :
3673 0 : pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
3674 0 : self.shard_identity.stripe_size
3675 0 : }
3676 :
3677 0 : pub(crate) fn get_generation(&self) -> Generation {
3678 0 : self.generation
3679 0 : }
3680 :
3681 : /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
3682 : /// and can leave the tenant in a bad state if it fails. The caller is responsible for
3683 : /// resetting this tenant to a valid state if we fail.
3684 0 : pub(crate) async fn split_prepare(
3685 0 : &self,
3686 0 : child_shards: &Vec<TenantShardId>,
3687 0 : ) -> anyhow::Result<()> {
3688 0 : let (timelines, offloaded) = {
3689 0 : let timelines = self.timelines.lock().unwrap();
3690 0 : let offloaded = self.timelines_offloaded.lock().unwrap();
3691 0 : (timelines.clone(), offloaded.clone())
3692 0 : };
3693 0 : let timelines_iter = timelines
3694 0 : .values()
3695 0 : .map(TimelineOrOffloadedArcRef::<'_>::from)
3696 0 : .chain(
3697 0 : offloaded
3698 0 : .values()
3699 0 : .map(TimelineOrOffloadedArcRef::<'_>::from),
3700 0 : );
3701 0 : for timeline in timelines_iter {
3702 : // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
3703 : // to ensure that they do not start a split if currently in the process of doing these.
3704 :
3705 0 : let timeline_id = timeline.timeline_id();
3706 :
3707 0 : if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
3708 : // Upload an index from the parent: this is partly to provide freshness for the
3709 : // child tenants that will copy it, and partly for general ease-of-debugging: there will
3710 : // always be a parent shard index in the same generation as we wrote the child shard index.
3711 0 : tracing::info!(%timeline_id, "Uploading index");
3712 0 : timeline
3713 0 : .remote_client
3714 0 : .schedule_index_upload_for_file_changes()?;
3715 0 : timeline.remote_client.wait_completion().await?;
3716 0 : }
3717 :
3718 0 : let remote_client = match timeline {
3719 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
3720 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
3721 0 : let remote_client = self
3722 0 : .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
3723 0 : Arc::new(remote_client)
3724 : }
3725 : };
3726 :
3727 : // Shut down the timeline's remote client: this means that the indices we write
3728 : // for child shards will not be invalidated by the parent shard deleting layers.
3729 0 : tracing::info!(%timeline_id, "Shutting down remote storage client");
3730 0 : remote_client.shutdown().await;
3731 :
3732 : // Download methods can still be used after shutdown, as they don't flow through the remote client's
3733 : // queue. In principal the RemoteTimelineClient could provide this without downloading it, but this
3734 : // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
3735 : // we use here really is the remotely persistent one).
3736 0 : tracing::info!(%timeline_id, "Downloading index_part from parent");
3737 0 : let result = remote_client
3738 0 : .download_index_file(&self.cancel)
3739 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))
3740 0 : .await?;
3741 0 : let index_part = match result {
3742 : MaybeDeletedIndexPart::Deleted(_) => {
3743 0 : anyhow::bail!("Timeline deletion happened concurrently with split")
3744 : }
3745 0 : MaybeDeletedIndexPart::IndexPart(p) => p,
3746 : };
3747 :
3748 0 : for child_shard in child_shards {
3749 0 : tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
3750 0 : upload_index_part(
3751 0 : &self.remote_storage,
3752 0 : child_shard,
3753 0 : &timeline_id,
3754 0 : self.generation,
3755 0 : &index_part,
3756 0 : &self.cancel,
3757 0 : )
3758 0 : .await?;
3759 : }
3760 : }
3761 :
3762 0 : let tenant_manifest = self.build_tenant_manifest();
3763 0 : for child_shard in child_shards {
3764 0 : tracing::info!(
3765 0 : "Uploading tenant manifest for child {}",
3766 0 : child_shard.to_index()
3767 : );
3768 0 : upload_tenant_manifest(
3769 0 : &self.remote_storage,
3770 0 : child_shard,
3771 0 : self.generation,
3772 0 : &tenant_manifest,
3773 0 : &self.cancel,
3774 0 : )
3775 0 : .await?;
3776 : }
3777 :
3778 0 : Ok(())
3779 0 : }
3780 :
3781 0 : pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
3782 0 : let mut result = TopTenantShardItem {
3783 0 : id: self.tenant_shard_id,
3784 0 : resident_size: 0,
3785 0 : physical_size: 0,
3786 0 : max_logical_size: 0,
3787 0 : };
3788 :
3789 0 : for timeline in self.timelines.lock().unwrap().values() {
3790 0 : result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
3791 0 :
3792 0 : result.physical_size += timeline
3793 0 : .remote_client
3794 0 : .metrics
3795 0 : .remote_physical_size_gauge
3796 0 : .get();
3797 0 : result.max_logical_size = std::cmp::max(
3798 0 : result.max_logical_size,
3799 0 : timeline.metrics.current_logical_size_gauge.get(),
3800 0 : );
3801 0 : }
3802 :
3803 0 : result
3804 0 : }
3805 : }
3806 :
3807 : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
3808 : /// perform a topological sort, so that the parent of each timeline comes
3809 : /// before the children.
3810 : /// E extracts the ancestor from T
3811 : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
3812 196 : fn tree_sort_timelines<T, E>(
3813 196 : timelines: HashMap<TimelineId, T>,
3814 196 : extractor: E,
3815 196 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
3816 196 : where
3817 196 : E: Fn(&T) -> Option<TimelineId>,
3818 196 : {
3819 196 : let mut result = Vec::with_capacity(timelines.len());
3820 196 :
3821 196 : let mut now = Vec::with_capacity(timelines.len());
3822 196 : // (ancestor, children)
3823 196 : let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
3824 196 : HashMap::with_capacity(timelines.len());
3825 :
3826 202 : for (timeline_id, value) in timelines {
3827 6 : if let Some(ancestor_id) = extractor(&value) {
3828 2 : let children = later.entry(ancestor_id).or_default();
3829 2 : children.push((timeline_id, value));
3830 4 : } else {
3831 4 : now.push((timeline_id, value));
3832 4 : }
3833 : }
3834 :
3835 202 : while let Some((timeline_id, metadata)) = now.pop() {
3836 6 : result.push((timeline_id, metadata));
3837 : // All children of this can be loaded now
3838 6 : if let Some(mut children) = later.remove(&timeline_id) {
3839 2 : now.append(&mut children);
3840 4 : }
3841 : }
3842 :
3843 : // All timelines should be visited now. Unless there were timelines with missing ancestors.
3844 196 : if !later.is_empty() {
3845 0 : for (missing_id, orphan_ids) in later {
3846 0 : for (orphan_id, _) in orphan_ids {
3847 0 : error!("could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded");
3848 : }
3849 : }
3850 0 : bail!("could not load tenant because some timelines are missing ancestors");
3851 196 : }
3852 196 :
3853 196 : Ok(result)
3854 196 : }
3855 :
3856 : enum ActivateTimelineArgs {
3857 : Yes {
3858 : broker_client: storage_broker::BrokerClientChannel,
3859 : },
3860 : No,
3861 : }
3862 :
3863 : impl Tenant {
3864 0 : pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
3865 0 : self.tenant_conf.load().tenant_conf.clone()
3866 0 : }
3867 :
3868 0 : pub fn effective_config(&self) -> TenantConf {
3869 0 : self.tenant_specific_overrides()
3870 0 : .merge(self.conf.default_tenant_conf.clone())
3871 0 : }
3872 :
3873 0 : pub fn get_checkpoint_distance(&self) -> u64 {
3874 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3875 0 : tenant_conf
3876 0 : .checkpoint_distance
3877 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
3878 0 : }
3879 :
3880 0 : pub fn get_checkpoint_timeout(&self) -> Duration {
3881 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3882 0 : tenant_conf
3883 0 : .checkpoint_timeout
3884 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
3885 0 : }
3886 :
3887 0 : pub fn get_compaction_target_size(&self) -> u64 {
3888 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3889 0 : tenant_conf
3890 0 : .compaction_target_size
3891 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
3892 0 : }
3893 :
3894 0 : pub fn get_compaction_period(&self) -> Duration {
3895 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3896 0 : tenant_conf
3897 0 : .compaction_period
3898 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_period)
3899 0 : }
3900 :
3901 0 : pub fn get_compaction_threshold(&self) -> usize {
3902 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3903 0 : tenant_conf
3904 0 : .compaction_threshold
3905 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
3906 0 : }
3907 :
3908 0 : pub fn get_gc_horizon(&self) -> u64 {
3909 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3910 0 : tenant_conf
3911 0 : .gc_horizon
3912 0 : .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
3913 0 : }
3914 :
3915 0 : pub fn get_gc_period(&self) -> Duration {
3916 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3917 0 : tenant_conf
3918 0 : .gc_period
3919 0 : .unwrap_or(self.conf.default_tenant_conf.gc_period)
3920 0 : }
3921 :
3922 0 : pub fn get_image_creation_threshold(&self) -> usize {
3923 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3924 0 : tenant_conf
3925 0 : .image_creation_threshold
3926 0 : .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
3927 0 : }
3928 :
3929 0 : pub fn get_pitr_interval(&self) -> Duration {
3930 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3931 0 : tenant_conf
3932 0 : .pitr_interval
3933 0 : .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
3934 0 : }
3935 :
3936 0 : pub fn get_min_resident_size_override(&self) -> Option<u64> {
3937 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3938 0 : tenant_conf
3939 0 : .min_resident_size_override
3940 0 : .or(self.conf.default_tenant_conf.min_resident_size_override)
3941 0 : }
3942 :
3943 0 : pub fn get_heatmap_period(&self) -> Option<Duration> {
3944 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3945 0 : let heatmap_period = tenant_conf
3946 0 : .heatmap_period
3947 0 : .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
3948 0 : if heatmap_period.is_zero() {
3949 0 : None
3950 : } else {
3951 0 : Some(heatmap_period)
3952 : }
3953 0 : }
3954 :
3955 4 : pub fn get_lsn_lease_length(&self) -> Duration {
3956 4 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3957 4 : tenant_conf
3958 4 : .lsn_lease_length
3959 4 : .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
3960 4 : }
3961 :
3962 : /// Generate an up-to-date TenantManifest based on the state of this Tenant.
3963 2 : fn build_tenant_manifest(&self) -> TenantManifest {
3964 2 : let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
3965 2 :
3966 2 : let mut timeline_manifests = timelines_offloaded
3967 2 : .iter()
3968 2 : .map(|(_timeline_id, offloaded)| offloaded.manifest())
3969 2 : .collect::<Vec<_>>();
3970 2 : // Sort the manifests so that our output is deterministic
3971 2 : timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
3972 2 :
3973 2 : TenantManifest {
3974 2 : version: LATEST_TENANT_MANIFEST_VERSION,
3975 2 : offloaded_timelines: timeline_manifests,
3976 2 : }
3977 2 : }
3978 :
3979 0 : pub fn update_tenant_config<F: Fn(TenantConfOpt) -> anyhow::Result<TenantConfOpt>>(
3980 0 : &self,
3981 0 : update: F,
3982 0 : ) -> anyhow::Result<TenantConfOpt> {
3983 0 : // Use read-copy-update in order to avoid overwriting the location config
3984 0 : // state if this races with [`Tenant::set_new_location_config`]. Note that
3985 0 : // this race is not possible if both request types come from the storage
3986 0 : // controller (as they should!) because an exclusive op lock is required
3987 0 : // on the storage controller side.
3988 0 :
3989 0 : self.tenant_conf
3990 0 : .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
3991 0 : Ok(Arc::new(AttachedTenantConf {
3992 0 : tenant_conf: update(attached_conf.tenant_conf.clone())?,
3993 0 : location: attached_conf.location,
3994 0 : lsn_lease_deadline: attached_conf.lsn_lease_deadline,
3995 : }))
3996 0 : })?;
3997 :
3998 0 : let updated = self.tenant_conf.load();
3999 0 :
4000 0 : self.tenant_conf_updated(&updated.tenant_conf);
4001 0 : // Don't hold self.timelines.lock() during the notifies.
4002 0 : // There's no risk of deadlock right now, but there could be if we consolidate
4003 0 : // mutexes in struct Timeline in the future.
4004 0 : let timelines = self.list_timelines();
4005 0 : for timeline in timelines {
4006 0 : timeline.tenant_conf_updated(&updated);
4007 0 : }
4008 :
4009 0 : Ok(updated.tenant_conf.clone())
4010 0 : }
4011 :
4012 0 : pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
4013 0 : let new_tenant_conf = new_conf.tenant_conf.clone();
4014 0 :
4015 0 : self.tenant_conf.store(Arc::new(new_conf.clone()));
4016 0 :
4017 0 : self.tenant_conf_updated(&new_tenant_conf);
4018 0 : // Don't hold self.timelines.lock() during the notifies.
4019 0 : // There's no risk of deadlock right now, but there could be if we consolidate
4020 0 : // mutexes in struct Timeline in the future.
4021 0 : let timelines = self.list_timelines();
4022 0 : for timeline in timelines {
4023 0 : timeline.tenant_conf_updated(&new_conf);
4024 0 : }
4025 0 : }
4026 :
4027 196 : fn get_pagestream_throttle_config(
4028 196 : psconf: &'static PageServerConf,
4029 196 : overrides: &TenantConfOpt,
4030 196 : ) -> throttle::Config {
4031 196 : overrides
4032 196 : .timeline_get_throttle
4033 196 : .clone()
4034 196 : .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
4035 196 : }
4036 :
4037 0 : pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
4038 0 : let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
4039 0 : self.pagestream_throttle.reconfigure(conf)
4040 0 : }
4041 :
4042 : /// Helper function to create a new Timeline struct.
4043 : ///
4044 : /// The returned Timeline is in Loading state. The caller is responsible for
4045 : /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
4046 : /// map.
4047 : ///
4048 : /// `validate_ancestor == false` is used when a timeline is created for deletion
4049 : /// and we might not have the ancestor present anymore which is fine for to be
4050 : /// deleted timelines.
4051 : #[allow(clippy::too_many_arguments)]
4052 422 : fn create_timeline_struct(
4053 422 : &self,
4054 422 : new_timeline_id: TimelineId,
4055 422 : new_metadata: &TimelineMetadata,
4056 422 : ancestor: Option<Arc<Timeline>>,
4057 422 : resources: TimelineResources,
4058 422 : cause: CreateTimelineCause,
4059 422 : create_idempotency: CreateTimelineIdempotency,
4060 422 : ) -> anyhow::Result<Arc<Timeline>> {
4061 422 : let state = match cause {
4062 : CreateTimelineCause::Load => {
4063 422 : let ancestor_id = new_metadata.ancestor_timeline();
4064 422 : anyhow::ensure!(
4065 422 : ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
4066 0 : "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
4067 : );
4068 422 : TimelineState::Loading
4069 : }
4070 0 : CreateTimelineCause::Delete => TimelineState::Stopping,
4071 : };
4072 :
4073 422 : let pg_version = new_metadata.pg_version();
4074 422 :
4075 422 : let timeline = Timeline::new(
4076 422 : self.conf,
4077 422 : Arc::clone(&self.tenant_conf),
4078 422 : new_metadata,
4079 422 : ancestor,
4080 422 : new_timeline_id,
4081 422 : self.tenant_shard_id,
4082 422 : self.generation,
4083 422 : self.shard_identity,
4084 422 : self.walredo_mgr.clone(),
4085 422 : resources,
4086 422 : pg_version,
4087 422 : state,
4088 422 : self.attach_wal_lag_cooldown.clone(),
4089 422 : create_idempotency,
4090 422 : self.cancel.child_token(),
4091 422 : );
4092 422 :
4093 422 : Ok(timeline)
4094 422 : }
4095 :
4096 : // Allow too_many_arguments because a constructor's argument list naturally grows with the
4097 : // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
4098 : #[allow(clippy::too_many_arguments)]
4099 196 : fn new(
4100 196 : state: TenantState,
4101 196 : conf: &'static PageServerConf,
4102 196 : attached_conf: AttachedTenantConf,
4103 196 : shard_identity: ShardIdentity,
4104 196 : walredo_mgr: Option<Arc<WalRedoManager>>,
4105 196 : tenant_shard_id: TenantShardId,
4106 196 : remote_storage: GenericRemoteStorage,
4107 196 : deletion_queue_client: DeletionQueueClient,
4108 196 : l0_flush_global_state: L0FlushGlobalState,
4109 196 : ) -> Tenant {
4110 196 : debug_assert!(
4111 196 : !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
4112 : );
4113 :
4114 196 : let (state, mut rx) = watch::channel(state);
4115 196 :
4116 196 : tokio::spawn(async move {
4117 196 : // reflect tenant state in metrics:
4118 196 : // - global per tenant state: TENANT_STATE_METRIC
4119 196 : // - "set" of broken tenants: BROKEN_TENANTS_SET
4120 196 : //
4121 196 : // set of broken tenants should not have zero counts so that it remains accessible for
4122 196 : // alerting.
4123 196 :
4124 196 : let tid = tenant_shard_id.to_string();
4125 196 : let shard_id = tenant_shard_id.shard_slug().to_string();
4126 196 : let set_key = &[tid.as_str(), shard_id.as_str()][..];
4127 :
4128 392 : fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
4129 392 : ([state.into()], matches!(state, TenantState::Broken { .. }))
4130 392 : }
4131 :
4132 196 : let mut tuple = inspect_state(&rx.borrow_and_update());
4133 196 :
4134 196 : let is_broken = tuple.1;
4135 196 : let mut counted_broken = if is_broken {
4136 : // add the id to the set right away, there should not be any updates on the channel
4137 : // after before tenant is removed, if ever
4138 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
4139 0 : true
4140 : } else {
4141 196 : false
4142 : };
4143 :
4144 : loop {
4145 392 : let labels = &tuple.0;
4146 392 : let current = TENANT_STATE_METRIC.with_label_values(labels);
4147 392 : current.inc();
4148 392 :
4149 392 : if rx.changed().await.is_err() {
4150 : // tenant has been dropped
4151 14 : current.dec();
4152 14 : drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
4153 14 : break;
4154 196 : }
4155 196 :
4156 196 : current.dec();
4157 196 : tuple = inspect_state(&rx.borrow_and_update());
4158 196 :
4159 196 : let is_broken = tuple.1;
4160 196 : if is_broken && !counted_broken {
4161 0 : counted_broken = true;
4162 0 : // insert the tenant_id (back) into the set while avoiding needless counter
4163 0 : // access
4164 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
4165 196 : }
4166 : }
4167 196 : });
4168 196 :
4169 196 : Tenant {
4170 196 : tenant_shard_id,
4171 196 : shard_identity,
4172 196 : generation: attached_conf.location.generation,
4173 196 : conf,
4174 196 : // using now here is good enough approximation to catch tenants with really long
4175 196 : // activation times.
4176 196 : constructed_at: Instant::now(),
4177 196 : timelines: Mutex::new(HashMap::new()),
4178 196 : timelines_creating: Mutex::new(HashSet::new()),
4179 196 : timelines_offloaded: Mutex::new(HashMap::new()),
4180 196 : tenant_manifest_upload: Default::default(),
4181 196 : gc_cs: tokio::sync::Mutex::new(()),
4182 196 : walredo_mgr,
4183 196 : remote_storage,
4184 196 : deletion_queue_client,
4185 196 : state,
4186 196 : cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
4187 196 : cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
4188 196 : eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
4189 196 : compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
4190 196 : format!("compaction-{tenant_shard_id}"),
4191 196 : 5,
4192 196 : // Compaction can be a very expensive operation, and might leak disk space. It also ought
4193 196 : // to be infallible, as long as remote storage is available. So if it repeatedly fails,
4194 196 : // use an extremely long backoff.
4195 196 : Some(Duration::from_secs(3600 * 24)),
4196 196 : )),
4197 196 : scheduled_compaction_tasks: Mutex::new(Default::default()),
4198 196 : activate_now_sem: tokio::sync::Semaphore::new(0),
4199 196 : attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
4200 196 : cancel: CancellationToken::default(),
4201 196 : gate: Gate::default(),
4202 196 : pagestream_throttle: Arc::new(throttle::Throttle::new(
4203 196 : Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
4204 196 : crate::metrics::tenant_throttling::Metrics::new(&tenant_shard_id),
4205 196 : )),
4206 196 : tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
4207 196 : ongoing_timeline_detach: std::sync::Mutex::default(),
4208 196 : gc_block: Default::default(),
4209 196 : l0_flush_global_state,
4210 196 : }
4211 196 : }
4212 :
4213 : /// Locate and load config
4214 0 : pub(super) fn load_tenant_config(
4215 0 : conf: &'static PageServerConf,
4216 0 : tenant_shard_id: &TenantShardId,
4217 0 : ) -> Result<LocationConf, LoadConfigError> {
4218 0 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
4219 0 :
4220 0 : info!("loading tenant configuration from {config_path}");
4221 :
4222 : // load and parse file
4223 0 : let config = fs::read_to_string(&config_path).map_err(|e| {
4224 0 : match e.kind() {
4225 : std::io::ErrorKind::NotFound => {
4226 : // The config should almost always exist for a tenant directory:
4227 : // - When attaching a tenant, the config is the first thing we write
4228 : // - When detaching a tenant, we atomically move the directory to a tmp location
4229 : // before deleting contents.
4230 : //
4231 : // The very rare edge case that can result in a missing config is if we crash during attach
4232 : // between creating directory and writing config. Callers should handle that as if the
4233 : // directory didn't exist.
4234 :
4235 0 : LoadConfigError::NotFound(config_path)
4236 : }
4237 : _ => {
4238 : // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
4239 : // that we cannot cleanly recover
4240 0 : crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
4241 : }
4242 : }
4243 0 : })?;
4244 :
4245 0 : Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
4246 0 : }
4247 :
4248 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
4249 : pub(super) async fn persist_tenant_config(
4250 : conf: &'static PageServerConf,
4251 : tenant_shard_id: &TenantShardId,
4252 : location_conf: &LocationConf,
4253 : ) -> std::io::Result<()> {
4254 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
4255 :
4256 : Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
4257 : }
4258 :
4259 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
4260 : pub(super) async fn persist_tenant_config_at(
4261 : tenant_shard_id: &TenantShardId,
4262 : config_path: &Utf8Path,
4263 : location_conf: &LocationConf,
4264 : ) -> std::io::Result<()> {
4265 : debug!("persisting tenantconf to {config_path}");
4266 :
4267 : let mut conf_content = r#"# This file contains a specific per-tenant's config.
4268 : # It is read in case of pageserver restart.
4269 : "#
4270 : .to_string();
4271 :
4272 0 : fail::fail_point!("tenant-config-before-write", |_| {
4273 0 : Err(std::io::Error::new(
4274 0 : std::io::ErrorKind::Other,
4275 0 : "tenant-config-before-write",
4276 0 : ))
4277 0 : });
4278 :
4279 : // Convert the config to a toml file.
4280 : conf_content +=
4281 : &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
4282 :
4283 : let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
4284 :
4285 : let conf_content = conf_content.into_bytes();
4286 : VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
4287 : }
4288 :
4289 : //
4290 : // How garbage collection works:
4291 : //
4292 : // +--bar------------->
4293 : // /
4294 : // +----+-----foo---------------->
4295 : // /
4296 : // ----main--+-------------------------->
4297 : // \
4298 : // +-----baz-------->
4299 : //
4300 : //
4301 : // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
4302 : // `gc_infos` are being refreshed
4303 : // 2. Scan collected timelines, and on each timeline, make note of the
4304 : // all the points where other timelines have been branched off.
4305 : // We will refrain from removing page versions at those LSNs.
4306 : // 3. For each timeline, scan all layer files on the timeline.
4307 : // Remove all files for which a newer file exists and which
4308 : // don't cover any branch point LSNs.
4309 : //
4310 : // TODO:
4311 : // - if a relation has a non-incremental persistent layer on a child branch, then we
4312 : // don't need to keep that in the parent anymore. But currently
4313 : // we do.
4314 4 : async fn gc_iteration_internal(
4315 4 : &self,
4316 4 : target_timeline_id: Option<TimelineId>,
4317 4 : horizon: u64,
4318 4 : pitr: Duration,
4319 4 : cancel: &CancellationToken,
4320 4 : ctx: &RequestContext,
4321 4 : ) -> Result<GcResult, GcError> {
4322 4 : let mut totals: GcResult = Default::default();
4323 4 : let now = Instant::now();
4324 :
4325 4 : let gc_timelines = self
4326 4 : .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
4327 4 : .await?;
4328 :
4329 4 : failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
4330 :
4331 : // If there is nothing to GC, we don't want any messages in the INFO log.
4332 4 : if !gc_timelines.is_empty() {
4333 4 : info!("{} timelines need GC", gc_timelines.len());
4334 : } else {
4335 0 : debug!("{} timelines need GC", gc_timelines.len());
4336 : }
4337 :
4338 : // Perform GC for each timeline.
4339 : //
4340 : // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
4341 : // branch creation task, which requires the GC lock. A GC iteration can run concurrently
4342 : // with branch creation.
4343 : //
4344 : // See comments in [`Tenant::branch_timeline`] for more information about why branch
4345 : // creation task can run concurrently with timeline's GC iteration.
4346 8 : for timeline in gc_timelines {
4347 4 : if cancel.is_cancelled() {
4348 : // We were requested to shut down. Stop and return with the progress we
4349 : // made.
4350 0 : break;
4351 4 : }
4352 4 : let result = match timeline.gc().await {
4353 : Err(GcError::TimelineCancelled) => {
4354 0 : if target_timeline_id.is_some() {
4355 : // If we were targetting this specific timeline, surface cancellation to caller
4356 0 : return Err(GcError::TimelineCancelled);
4357 : } else {
4358 : // A timeline may be shutting down independently of the tenant's lifecycle: we should
4359 : // skip past this and proceed to try GC on other timelines.
4360 0 : continue;
4361 : }
4362 : }
4363 4 : r => r?,
4364 : };
4365 4 : totals += result;
4366 : }
4367 :
4368 4 : totals.elapsed = now.elapsed();
4369 4 : Ok(totals)
4370 4 : }
4371 :
4372 : /// Refreshes the Timeline::gc_info for all timelines, returning the
4373 : /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
4374 : /// [`Tenant::get_gc_horizon`].
4375 : ///
4376 : /// This is usually executed as part of periodic gc, but can now be triggered more often.
4377 0 : pub(crate) async fn refresh_gc_info(
4378 0 : &self,
4379 0 : cancel: &CancellationToken,
4380 0 : ctx: &RequestContext,
4381 0 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
4382 0 : // since this method can now be called at different rates than the configured gc loop, it
4383 0 : // might be that these configuration values get applied faster than what it was previously,
4384 0 : // since these were only read from the gc task.
4385 0 : let horizon = self.get_gc_horizon();
4386 0 : let pitr = self.get_pitr_interval();
4387 0 :
4388 0 : // refresh all timelines
4389 0 : let target_timeline_id = None;
4390 0 :
4391 0 : self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
4392 0 : .await
4393 0 : }
4394 :
4395 : /// Populate all Timelines' `GcInfo` with information about their children. We do not set the
4396 : /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
4397 : ///
4398 : /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
4399 0 : fn initialize_gc_info(
4400 0 : &self,
4401 0 : timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
4402 0 : timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
4403 0 : restrict_to_timeline: Option<TimelineId>,
4404 0 : ) {
4405 0 : if restrict_to_timeline.is_none() {
4406 : // This function must be called before activation: after activation timeline create/delete operations
4407 : // might happen, and this function is not safe to run concurrently with those.
4408 0 : assert!(!self.is_active());
4409 0 : }
4410 :
4411 : // Scan all timelines. For each timeline, remember the timeline ID and
4412 : // the branch point where it was created.
4413 0 : let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
4414 0 : BTreeMap::new();
4415 0 : timelines.iter().for_each(|(timeline_id, timeline_entry)| {
4416 0 : if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
4417 0 : let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
4418 0 : ancestor_children.push((
4419 0 : timeline_entry.get_ancestor_lsn(),
4420 0 : *timeline_id,
4421 0 : MaybeOffloaded::No,
4422 0 : ));
4423 0 : }
4424 0 : });
4425 0 : timelines_offloaded
4426 0 : .iter()
4427 0 : .for_each(|(timeline_id, timeline_entry)| {
4428 0 : let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
4429 0 : return;
4430 : };
4431 0 : let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
4432 0 : return;
4433 : };
4434 0 : let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
4435 0 : ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
4436 0 : });
4437 0 :
4438 0 : // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
4439 0 : let horizon = self.get_gc_horizon();
4440 :
4441 : // Populate each timeline's GcInfo with information about its child branches
4442 0 : let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
4443 0 : itertools::Either::Left(timelines.get(&timeline_id).into_iter())
4444 : } else {
4445 0 : itertools::Either::Right(timelines.values())
4446 : };
4447 0 : for timeline in timelines_to_write {
4448 0 : let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
4449 0 : .remove(&timeline.timeline_id)
4450 0 : .unwrap_or_default();
4451 0 :
4452 0 : branchpoints.sort_by_key(|b| b.0);
4453 0 :
4454 0 : let mut target = timeline.gc_info.write().unwrap();
4455 0 :
4456 0 : target.retain_lsns = branchpoints;
4457 0 :
4458 0 : let space_cutoff = timeline
4459 0 : .get_last_record_lsn()
4460 0 : .checked_sub(horizon)
4461 0 : .unwrap_or(Lsn(0));
4462 0 :
4463 0 : target.cutoffs = GcCutoffs {
4464 0 : space: space_cutoff,
4465 0 : time: Lsn::INVALID,
4466 0 : };
4467 0 : }
4468 0 : }
4469 :
4470 4 : async fn refresh_gc_info_internal(
4471 4 : &self,
4472 4 : target_timeline_id: Option<TimelineId>,
4473 4 : horizon: u64,
4474 4 : pitr: Duration,
4475 4 : cancel: &CancellationToken,
4476 4 : ctx: &RequestContext,
4477 4 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
4478 4 : // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
4479 4 : // currently visible timelines.
4480 4 : let timelines = self
4481 4 : .timelines
4482 4 : .lock()
4483 4 : .unwrap()
4484 4 : .values()
4485 4 : .filter(|tl| match target_timeline_id.as_ref() {
4486 4 : Some(target) => &tl.timeline_id == target,
4487 0 : None => true,
4488 4 : })
4489 4 : .cloned()
4490 4 : .collect::<Vec<_>>();
4491 4 :
4492 4 : if target_timeline_id.is_some() && timelines.is_empty() {
4493 : // We were to act on a particular timeline and it wasn't found
4494 0 : return Err(GcError::TimelineNotFound);
4495 4 : }
4496 4 :
4497 4 : let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
4498 4 : HashMap::with_capacity(timelines.len());
4499 4 :
4500 4 : // Ensures all timelines use the same start time when computing the time cutoff.
4501 4 : let now_ts_for_pitr_calc = SystemTime::now();
4502 4 : for timeline in timelines.iter() {
4503 4 : let cutoff = timeline
4504 4 : .get_last_record_lsn()
4505 4 : .checked_sub(horizon)
4506 4 : .unwrap_or(Lsn(0));
4507 :
4508 4 : let cutoffs = timeline
4509 4 : .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
4510 4 : .await?;
4511 4 : let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
4512 4 : assert!(old.is_none());
4513 : }
4514 :
4515 4 : if !self.is_active() || self.cancel.is_cancelled() {
4516 0 : return Err(GcError::TenantCancelled);
4517 4 : }
4518 :
4519 : // grab mutex to prevent new timelines from being created here; avoid doing long operations
4520 : // because that will stall branch creation.
4521 4 : let gc_cs = self.gc_cs.lock().await;
4522 :
4523 : // Ok, we now know all the branch points.
4524 : // Update the GC information for each timeline.
4525 4 : let mut gc_timelines = Vec::with_capacity(timelines.len());
4526 8 : for timeline in timelines {
4527 : // We filtered the timeline list above
4528 4 : if let Some(target_timeline_id) = target_timeline_id {
4529 4 : assert_eq!(target_timeline_id, timeline.timeline_id);
4530 0 : }
4531 :
4532 : {
4533 4 : let mut target = timeline.gc_info.write().unwrap();
4534 4 :
4535 4 : // Cull any expired leases
4536 4 : let now = SystemTime::now();
4537 6 : target.leases.retain(|_, lease| !lease.is_expired(&now));
4538 4 :
4539 4 : timeline
4540 4 : .metrics
4541 4 : .valid_lsn_lease_count_gauge
4542 4 : .set(target.leases.len() as u64);
4543 :
4544 : // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
4545 4 : if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
4546 0 : if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
4547 0 : target.within_ancestor_pitr =
4548 0 : timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
4549 0 : }
4550 4 : }
4551 :
4552 : // Update metrics that depend on GC state
4553 4 : timeline
4554 4 : .metrics
4555 4 : .archival_size
4556 4 : .set(if target.within_ancestor_pitr {
4557 0 : timeline.metrics.current_logical_size_gauge.get()
4558 : } else {
4559 4 : 0
4560 : });
4561 4 : timeline.metrics.pitr_history_size.set(
4562 4 : timeline
4563 4 : .get_last_record_lsn()
4564 4 : .checked_sub(target.cutoffs.time)
4565 4 : .unwrap_or(Lsn(0))
4566 4 : .0,
4567 4 : );
4568 :
4569 : // Apply the cutoffs we found to the Timeline's GcInfo. Why might we _not_ have cutoffs for a timeline?
4570 : // - this timeline was created while we were finding cutoffs
4571 : // - lsn for timestamp search fails for this timeline repeatedly
4572 4 : if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
4573 4 : let original_cutoffs = target.cutoffs.clone();
4574 4 : // GC cutoffs should never go back
4575 4 : target.cutoffs = GcCutoffs {
4576 4 : space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
4577 4 : time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
4578 4 : }
4579 0 : }
4580 : }
4581 :
4582 4 : gc_timelines.push(timeline);
4583 : }
4584 4 : drop(gc_cs);
4585 4 : Ok(gc_timelines)
4586 4 : }
4587 :
4588 : /// A substitute for `branch_timeline` for use in unit tests.
4589 : /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
4590 : /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
4591 : /// timeline background tasks are launched, except the flush loop.
4592 : #[cfg(test)]
4593 232 : async fn branch_timeline_test(
4594 232 : self: &Arc<Self>,
4595 232 : src_timeline: &Arc<Timeline>,
4596 232 : dst_id: TimelineId,
4597 232 : ancestor_lsn: Option<Lsn>,
4598 232 : ctx: &RequestContext,
4599 232 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
4600 232 : let tl = self
4601 232 : .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
4602 232 : .await?
4603 228 : .into_timeline_for_test();
4604 228 : tl.set_state(TimelineState::Active);
4605 228 : Ok(tl)
4606 232 : }
4607 :
4608 : /// Helper for unit tests to branch a timeline with some pre-loaded states.
4609 : #[cfg(test)]
4610 : #[allow(clippy::too_many_arguments)]
4611 6 : pub async fn branch_timeline_test_with_layers(
4612 6 : self: &Arc<Self>,
4613 6 : src_timeline: &Arc<Timeline>,
4614 6 : dst_id: TimelineId,
4615 6 : ancestor_lsn: Option<Lsn>,
4616 6 : ctx: &RequestContext,
4617 6 : delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
4618 6 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
4619 6 : end_lsn: Lsn,
4620 6 : ) -> anyhow::Result<Arc<Timeline>> {
4621 : use checks::check_valid_layermap;
4622 : use itertools::Itertools;
4623 :
4624 6 : let tline = self
4625 6 : .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
4626 6 : .await?;
4627 6 : let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
4628 6 : ancestor_lsn
4629 : } else {
4630 0 : tline.get_last_record_lsn()
4631 : };
4632 6 : assert!(end_lsn >= ancestor_lsn);
4633 6 : tline.force_advance_lsn(end_lsn);
4634 12 : for deltas in delta_layer_desc {
4635 6 : tline
4636 6 : .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
4637 6 : .await?;
4638 : }
4639 10 : for (lsn, images) in image_layer_desc {
4640 4 : tline
4641 4 : .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
4642 4 : .await?;
4643 : }
4644 6 : let layer_names = tline
4645 6 : .layers
4646 6 : .read()
4647 6 : .await
4648 6 : .layer_map()
4649 6 : .unwrap()
4650 6 : .iter_historic_layers()
4651 10 : .map(|layer| layer.layer_name())
4652 6 : .collect_vec();
4653 6 : if let Some(err) = check_valid_layermap(&layer_names) {
4654 0 : bail!("invalid layermap: {err}");
4655 6 : }
4656 6 : Ok(tline)
4657 6 : }
4658 :
4659 : /// Branch an existing timeline.
4660 0 : async fn branch_timeline(
4661 0 : self: &Arc<Self>,
4662 0 : src_timeline: &Arc<Timeline>,
4663 0 : dst_id: TimelineId,
4664 0 : start_lsn: Option<Lsn>,
4665 0 : ctx: &RequestContext,
4666 0 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
4667 0 : self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
4668 0 : .await
4669 0 : }
4670 :
4671 232 : async fn branch_timeline_impl(
4672 232 : self: &Arc<Self>,
4673 232 : src_timeline: &Arc<Timeline>,
4674 232 : dst_id: TimelineId,
4675 232 : start_lsn: Option<Lsn>,
4676 232 : _ctx: &RequestContext,
4677 232 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
4678 232 : let src_id = src_timeline.timeline_id;
4679 :
4680 : // We will validate our ancestor LSN in this function. Acquire the GC lock so that
4681 : // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
4682 : // valid while we are creating the branch.
4683 232 : let _gc_cs = self.gc_cs.lock().await;
4684 :
4685 : // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
4686 232 : let start_lsn = start_lsn.unwrap_or_else(|| {
4687 2 : let lsn = src_timeline.get_last_record_lsn();
4688 2 : info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
4689 2 : lsn
4690 232 : });
4691 :
4692 : // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
4693 232 : let timeline_create_guard = match self
4694 232 : .start_creating_timeline(
4695 232 : dst_id,
4696 232 : CreateTimelineIdempotency::Branch {
4697 232 : ancestor_timeline_id: src_timeline.timeline_id,
4698 232 : ancestor_start_lsn: start_lsn,
4699 232 : },
4700 232 : )
4701 232 : .await?
4702 : {
4703 232 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
4704 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
4705 0 : return Ok(CreateTimelineResult::Idempotent(timeline));
4706 : }
4707 : };
4708 :
4709 : // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
4710 : // horizon on the source timeline
4711 : //
4712 : // We check it against both the planned GC cutoff stored in 'gc_info',
4713 : // and the 'latest_gc_cutoff' of the last GC that was performed. The
4714 : // planned GC cutoff in 'gc_info' is normally larger than
4715 : // 'latest_gc_cutoff_lsn', but beware of corner cases like if you just
4716 : // changed the GC settings for the tenant to make the PITR window
4717 : // larger, but some of the data was already removed by an earlier GC
4718 : // iteration.
4719 :
4720 : // check against last actual 'latest_gc_cutoff' first
4721 232 : let latest_gc_cutoff_lsn = src_timeline.get_latest_gc_cutoff_lsn();
4722 232 : src_timeline
4723 232 : .check_lsn_is_in_scope(start_lsn, &latest_gc_cutoff_lsn)
4724 232 : .context(format!(
4725 232 : "invalid branch start lsn: less than latest GC cutoff {}",
4726 232 : *latest_gc_cutoff_lsn,
4727 232 : ))
4728 232 : .map_err(CreateTimelineError::AncestorLsn)?;
4729 :
4730 : // and then the planned GC cutoff
4731 : {
4732 228 : let gc_info = src_timeline.gc_info.read().unwrap();
4733 228 : let cutoff = gc_info.min_cutoff();
4734 228 : if start_lsn < cutoff {
4735 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
4736 0 : "invalid branch start lsn: less than planned GC cutoff {cutoff}"
4737 0 : )));
4738 228 : }
4739 228 : }
4740 228 :
4741 228 : //
4742 228 : // The branch point is valid, and we are still holding the 'gc_cs' lock
4743 228 : // so that GC cannot advance the GC cutoff until we are finished.
4744 228 : // Proceed with the branch creation.
4745 228 : //
4746 228 :
4747 228 : // Determine prev-LSN for the new timeline. We can only determine it if
4748 228 : // the timeline was branched at the current end of the source timeline.
4749 228 : let RecordLsn {
4750 228 : last: src_last,
4751 228 : prev: src_prev,
4752 228 : } = src_timeline.get_last_record_rlsn();
4753 228 : let dst_prev = if src_last == start_lsn {
4754 216 : Some(src_prev)
4755 : } else {
4756 12 : None
4757 : };
4758 :
4759 : // Create the metadata file, noting the ancestor of the new timeline.
4760 : // There is initially no data in it, but all the read-calls know to look
4761 : // into the ancestor.
4762 228 : let metadata = TimelineMetadata::new(
4763 228 : start_lsn,
4764 228 : dst_prev,
4765 228 : Some(src_id),
4766 228 : start_lsn,
4767 228 : *src_timeline.latest_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
4768 228 : src_timeline.initdb_lsn,
4769 228 : src_timeline.pg_version,
4770 228 : );
4771 :
4772 228 : let uninitialized_timeline = self
4773 228 : .prepare_new_timeline(
4774 228 : dst_id,
4775 228 : &metadata,
4776 228 : timeline_create_guard,
4777 228 : start_lsn + 1,
4778 228 : Some(Arc::clone(src_timeline)),
4779 228 : )
4780 228 : .await?;
4781 :
4782 228 : let new_timeline = uninitialized_timeline.finish_creation()?;
4783 :
4784 : // Root timeline gets its layers during creation and uploads them along with the metadata.
4785 : // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
4786 : // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
4787 : // could get incorrect information and remove more layers, than needed.
4788 : // See also https://github.com/neondatabase/neon/issues/3865
4789 228 : new_timeline
4790 228 : .remote_client
4791 228 : .schedule_index_upload_for_full_metadata_update(&metadata)
4792 228 : .context("branch initial metadata upload")?;
4793 :
4794 : // Callers are responsible to wait for uploads to complete and for activating the timeline.
4795 :
4796 228 : Ok(CreateTimelineResult::Created(new_timeline))
4797 232 : }
4798 :
4799 : /// For unit tests, make this visible so that other modules can directly create timelines
4800 : #[cfg(test)]
4801 : #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
4802 : pub(crate) async fn bootstrap_timeline_test(
4803 : self: &Arc<Self>,
4804 : timeline_id: TimelineId,
4805 : pg_version: u32,
4806 : load_existing_initdb: Option<TimelineId>,
4807 : ctx: &RequestContext,
4808 : ) -> anyhow::Result<Arc<Timeline>> {
4809 : self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
4810 : .await
4811 : .map_err(anyhow::Error::new)
4812 2 : .map(|r| r.into_timeline_for_test())
4813 : }
4814 :
4815 : /// Get exclusive access to the timeline ID for creation.
4816 : ///
4817 : /// Timeline-creating code paths must use this function before making changes
4818 : /// to in-memory or persistent state.
4819 : ///
4820 : /// The `state` parameter is a description of the timeline creation operation
4821 : /// we intend to perform.
4822 : /// If the timeline was already created in the meantime, we check whether this
4823 : /// request conflicts or is idempotent , based on `state`.
4824 422 : async fn start_creating_timeline(
4825 422 : self: &Arc<Self>,
4826 422 : new_timeline_id: TimelineId,
4827 422 : idempotency: CreateTimelineIdempotency,
4828 422 : ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
4829 422 : let allow_offloaded = false;
4830 422 : match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
4831 420 : Ok(create_guard) => {
4832 420 : pausable_failpoint!("timeline-creation-after-uninit");
4833 420 : Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
4834 : }
4835 0 : Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
4836 : Err(TimelineExclusionError::AlreadyCreating) => {
4837 : // Creation is in progress, we cannot create it again, and we cannot
4838 : // check if this request matches the existing one, so caller must try
4839 : // again later.
4840 0 : Err(CreateTimelineError::AlreadyCreating)
4841 : }
4842 0 : Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
4843 : Err(TimelineExclusionError::AlreadyExists {
4844 0 : existing: TimelineOrOffloaded::Offloaded(_existing),
4845 0 : ..
4846 0 : }) => {
4847 0 : info!("timeline already exists but is offloaded");
4848 0 : Err(CreateTimelineError::Conflict)
4849 : }
4850 : Err(TimelineExclusionError::AlreadyExists {
4851 2 : existing: TimelineOrOffloaded::Timeline(existing),
4852 2 : arg,
4853 2 : }) => {
4854 2 : {
4855 2 : let existing = &existing.create_idempotency;
4856 2 : let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
4857 2 : debug!("timeline already exists");
4858 :
4859 2 : match (existing, &arg) {
4860 : // FailWithConflict => no idempotency check
4861 : (CreateTimelineIdempotency::FailWithConflict, _)
4862 : | (_, CreateTimelineIdempotency::FailWithConflict) => {
4863 2 : warn!("timeline already exists, failing request");
4864 2 : return Err(CreateTimelineError::Conflict);
4865 : }
4866 : // Idempotent <=> CreateTimelineIdempotency is identical
4867 0 : (x, y) if x == y => {
4868 0 : info!("timeline already exists and idempotency matches, succeeding request");
4869 : // fallthrough
4870 : }
4871 : (_, _) => {
4872 0 : warn!("idempotency conflict, failing request");
4873 0 : return Err(CreateTimelineError::Conflict);
4874 : }
4875 : }
4876 : }
4877 :
4878 0 : Ok(StartCreatingTimelineResult::Idempotent(existing))
4879 : }
4880 : }
4881 422 : }
4882 :
4883 0 : async fn upload_initdb(
4884 0 : &self,
4885 0 : timelines_path: &Utf8PathBuf,
4886 0 : pgdata_path: &Utf8PathBuf,
4887 0 : timeline_id: &TimelineId,
4888 0 : ) -> anyhow::Result<()> {
4889 0 : let temp_path = timelines_path.join(format!(
4890 0 : "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
4891 0 : ));
4892 0 :
4893 0 : scopeguard::defer! {
4894 0 : if let Err(e) = fs::remove_file(&temp_path) {
4895 0 : error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
4896 0 : }
4897 0 : }
4898 :
4899 0 : let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
4900 : const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
4901 0 : if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
4902 0 : warn!(
4903 0 : "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
4904 : );
4905 0 : }
4906 :
4907 0 : pausable_failpoint!("before-initdb-upload");
4908 :
4909 0 : backoff::retry(
4910 0 : || async {
4911 0 : self::remote_timeline_client::upload_initdb_dir(
4912 0 : &self.remote_storage,
4913 0 : &self.tenant_shard_id.tenant_id,
4914 0 : timeline_id,
4915 0 : pgdata_zstd.try_clone().await?,
4916 0 : tar_zst_size,
4917 0 : &self.cancel,
4918 0 : )
4919 0 : .await
4920 0 : },
4921 0 : |_| false,
4922 0 : 3,
4923 0 : u32::MAX,
4924 0 : "persist_initdb_tar_zst",
4925 0 : &self.cancel,
4926 0 : )
4927 0 : .await
4928 0 : .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
4929 0 : .and_then(|x| x)
4930 0 : }
4931 :
4932 : /// - run initdb to init temporary instance and get bootstrap data
4933 : /// - after initialization completes, tar up the temp dir and upload it to S3.
4934 2 : async fn bootstrap_timeline(
4935 2 : self: &Arc<Self>,
4936 2 : timeline_id: TimelineId,
4937 2 : pg_version: u32,
4938 2 : load_existing_initdb: Option<TimelineId>,
4939 2 : ctx: &RequestContext,
4940 2 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
4941 2 : let timeline_create_guard = match self
4942 2 : .start_creating_timeline(
4943 2 : timeline_id,
4944 2 : CreateTimelineIdempotency::Bootstrap { pg_version },
4945 2 : )
4946 2 : .await?
4947 : {
4948 2 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
4949 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
4950 0 : return Ok(CreateTimelineResult::Idempotent(timeline))
4951 : }
4952 : };
4953 :
4954 : // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
4955 : // temporary directory for basebackup files for the given timeline.
4956 :
4957 2 : let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
4958 2 : let pgdata_path = path_with_suffix_extension(
4959 2 : timelines_path.join(format!("basebackup-{timeline_id}")),
4960 2 : TEMP_FILE_SUFFIX,
4961 2 : );
4962 2 :
4963 2 : // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
4964 2 : // we won't race with other creations or existent timelines with the same path.
4965 2 : if pgdata_path.exists() {
4966 0 : fs::remove_dir_all(&pgdata_path).with_context(|| {
4967 0 : format!("Failed to remove already existing initdb directory: {pgdata_path}")
4968 0 : })?;
4969 2 : }
4970 :
4971 : // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
4972 2 : scopeguard::defer! {
4973 2 : if let Err(e) = fs::remove_dir_all(&pgdata_path) {
4974 2 : // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
4975 2 : error!("Failed to remove temporary initdb directory '{pgdata_path}': {e}");
4976 2 : }
4977 2 : }
4978 2 : if let Some(existing_initdb_timeline_id) = load_existing_initdb {
4979 2 : if existing_initdb_timeline_id != timeline_id {
4980 0 : let source_path = &remote_initdb_archive_path(
4981 0 : &self.tenant_shard_id.tenant_id,
4982 0 : &existing_initdb_timeline_id,
4983 0 : );
4984 0 : let dest_path =
4985 0 : &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
4986 0 :
4987 0 : // if this fails, it will get retried by retried control plane requests
4988 0 : self.remote_storage
4989 0 : .copy_object(source_path, dest_path, &self.cancel)
4990 0 : .await
4991 0 : .context("copy initdb tar")?;
4992 2 : }
4993 2 : let (initdb_tar_zst_path, initdb_tar_zst) =
4994 2 : self::remote_timeline_client::download_initdb_tar_zst(
4995 2 : self.conf,
4996 2 : &self.remote_storage,
4997 2 : &self.tenant_shard_id,
4998 2 : &existing_initdb_timeline_id,
4999 2 : &self.cancel,
5000 2 : )
5001 2 : .await
5002 2 : .context("download initdb tar")?;
5003 :
5004 2 : scopeguard::defer! {
5005 2 : if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
5006 2 : error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
5007 2 : }
5008 2 : }
5009 2 :
5010 2 : let buf_read =
5011 2 : BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
5012 2 : extract_zst_tarball(&pgdata_path, buf_read)
5013 2 : .await
5014 2 : .context("extract initdb tar")?;
5015 : } else {
5016 : // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
5017 0 : run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
5018 0 : .await
5019 0 : .context("run initdb")?;
5020 :
5021 : // Upload the created data dir to S3
5022 0 : if self.tenant_shard_id().is_shard_zero() {
5023 0 : self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
5024 0 : .await?;
5025 0 : }
5026 : }
5027 2 : let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
5028 2 :
5029 2 : // Import the contents of the data directory at the initial checkpoint
5030 2 : // LSN, and any WAL after that.
5031 2 : // Initdb lsn will be equal to last_record_lsn which will be set after import.
5032 2 : // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
5033 2 : let new_metadata = TimelineMetadata::new(
5034 2 : Lsn(0),
5035 2 : None,
5036 2 : None,
5037 2 : Lsn(0),
5038 2 : pgdata_lsn,
5039 2 : pgdata_lsn,
5040 2 : pg_version,
5041 2 : );
5042 2 : let raw_timeline = self
5043 2 : .prepare_new_timeline(
5044 2 : timeline_id,
5045 2 : &new_metadata,
5046 2 : timeline_create_guard,
5047 2 : pgdata_lsn,
5048 2 : None,
5049 2 : )
5050 2 : .await?;
5051 :
5052 2 : let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
5053 2 : let unfinished_timeline = raw_timeline.raw_timeline()?;
5054 :
5055 : // Flush the new layer files to disk, before we make the timeline as available to
5056 : // the outside world.
5057 : //
5058 : // Flush loop needs to be spawned in order to be able to flush.
5059 2 : unfinished_timeline.maybe_spawn_flush_loop();
5060 2 :
5061 2 : import_datadir::import_timeline_from_postgres_datadir(
5062 2 : unfinished_timeline,
5063 2 : &pgdata_path,
5064 2 : pgdata_lsn,
5065 2 : ctx,
5066 2 : )
5067 2 : .await
5068 2 : .with_context(|| {
5069 0 : format!("Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}")
5070 2 : })?;
5071 :
5072 2 : fail::fail_point!("before-checkpoint-new-timeline", |_| {
5073 0 : Err(CreateTimelineError::Other(anyhow::anyhow!(
5074 0 : "failpoint before-checkpoint-new-timeline"
5075 0 : )))
5076 2 : });
5077 :
5078 2 : unfinished_timeline
5079 2 : .freeze_and_flush()
5080 2 : .await
5081 2 : .with_context(|| {
5082 0 : format!(
5083 0 : "Failed to flush after pgdatadir import for timeline {tenant_shard_id}/{timeline_id}"
5084 0 : )
5085 2 : })?;
5086 :
5087 : // All done!
5088 2 : let timeline = raw_timeline.finish_creation()?;
5089 :
5090 : // Callers are responsible to wait for uploads to complete and for activating the timeline.
5091 :
5092 2 : Ok(CreateTimelineResult::Created(timeline))
5093 2 : }
5094 :
5095 416 : fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
5096 416 : RemoteTimelineClient::new(
5097 416 : self.remote_storage.clone(),
5098 416 : self.deletion_queue_client.clone(),
5099 416 : self.conf,
5100 416 : self.tenant_shard_id,
5101 416 : timeline_id,
5102 416 : self.generation,
5103 416 : &self.tenant_conf.load().location,
5104 416 : )
5105 416 : }
5106 :
5107 : /// Call this before constructing a timeline, to build its required structures
5108 416 : fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
5109 416 : TimelineResources {
5110 416 : remote_client: self.build_timeline_remote_client(timeline_id),
5111 416 : pagestream_throttle: self.pagestream_throttle.clone(),
5112 416 : l0_flush_global_state: self.l0_flush_global_state.clone(),
5113 416 : }
5114 416 : }
5115 :
5116 : /// Creates intermediate timeline structure and its files.
5117 : ///
5118 : /// An empty layer map is initialized, and new data and WAL can be imported starting
5119 : /// at 'disk_consistent_lsn'. After any initial data has been imported, call
5120 : /// `finish_creation` to insert the Timeline into the timelines map.
5121 416 : async fn prepare_new_timeline<'a>(
5122 416 : &'a self,
5123 416 : new_timeline_id: TimelineId,
5124 416 : new_metadata: &TimelineMetadata,
5125 416 : create_guard: TimelineCreateGuard,
5126 416 : start_lsn: Lsn,
5127 416 : ancestor: Option<Arc<Timeline>>,
5128 416 : ) -> anyhow::Result<UninitializedTimeline<'a>> {
5129 416 : let tenant_shard_id = self.tenant_shard_id;
5130 416 :
5131 416 : let resources = self.build_timeline_resources(new_timeline_id);
5132 416 : resources
5133 416 : .remote_client
5134 416 : .init_upload_queue_for_empty_remote(new_metadata)?;
5135 :
5136 416 : let timeline_struct = self
5137 416 : .create_timeline_struct(
5138 416 : new_timeline_id,
5139 416 : new_metadata,
5140 416 : ancestor,
5141 416 : resources,
5142 416 : CreateTimelineCause::Load,
5143 416 : create_guard.idempotency.clone(),
5144 416 : )
5145 416 : .context("Failed to create timeline data structure")?;
5146 :
5147 416 : timeline_struct.init_empty_layer_map(start_lsn);
5148 :
5149 416 : if let Err(e) = self
5150 416 : .create_timeline_files(&create_guard.timeline_path)
5151 416 : .await
5152 : {
5153 0 : error!("Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}");
5154 0 : cleanup_timeline_directory(create_guard);
5155 0 : return Err(e);
5156 416 : }
5157 416 :
5158 416 : debug!(
5159 0 : "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
5160 : );
5161 :
5162 416 : Ok(UninitializedTimeline::new(
5163 416 : self,
5164 416 : new_timeline_id,
5165 416 : Some((timeline_struct, create_guard)),
5166 416 : ))
5167 416 : }
5168 :
5169 416 : async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
5170 416 : crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
5171 :
5172 416 : fail::fail_point!("after-timeline-dir-creation", |_| {
5173 0 : anyhow::bail!("failpoint after-timeline-dir-creation");
5174 416 : });
5175 :
5176 416 : Ok(())
5177 416 : }
5178 :
5179 : /// Get a guard that provides exclusive access to the timeline directory, preventing
5180 : /// concurrent attempts to create the same timeline.
5181 : ///
5182 : /// The `allow_offloaded` parameter controls whether to tolerate the existence of
5183 : /// offloaded timelines or not.
5184 422 : fn create_timeline_create_guard(
5185 422 : self: &Arc<Self>,
5186 422 : timeline_id: TimelineId,
5187 422 : idempotency: CreateTimelineIdempotency,
5188 422 : allow_offloaded: bool,
5189 422 : ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
5190 422 : let tenant_shard_id = self.tenant_shard_id;
5191 422 :
5192 422 : let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
5193 :
5194 422 : let create_guard = TimelineCreateGuard::new(
5195 422 : self,
5196 422 : timeline_id,
5197 422 : timeline_path.clone(),
5198 422 : idempotency,
5199 422 : allow_offloaded,
5200 422 : )?;
5201 :
5202 : // At this stage, we have got exclusive access to in-memory state for this timeline ID
5203 : // for creation.
5204 : // A timeline directory should never exist on disk already:
5205 : // - a previous failed creation would have cleaned up after itself
5206 : // - a pageserver restart would clean up timeline directories that don't have valid remote state
5207 : //
5208 : // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
5209 : // this error may indicate a bug in cleanup on failed creations.
5210 420 : if timeline_path.exists() {
5211 0 : return Err(TimelineExclusionError::Other(anyhow::anyhow!(
5212 0 : "Timeline directory already exists! This is a bug."
5213 0 : )));
5214 420 : }
5215 420 :
5216 420 : Ok(create_guard)
5217 422 : }
5218 :
5219 : /// Gathers inputs from all of the timelines to produce a sizing model input.
5220 : ///
5221 : /// Future is cancellation safe. Only one calculation can be running at once per tenant.
5222 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5223 : pub async fn gather_size_inputs(
5224 : &self,
5225 : // `max_retention_period` overrides the cutoff that is used to calculate the size
5226 : // (only if it is shorter than the real cutoff).
5227 : max_retention_period: Option<u64>,
5228 : cause: LogicalSizeCalculationCause,
5229 : cancel: &CancellationToken,
5230 : ctx: &RequestContext,
5231 : ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
5232 : let logical_sizes_at_once = self
5233 : .conf
5234 : .concurrent_tenant_size_logical_size_queries
5235 : .inner();
5236 :
5237 : // TODO: Having a single mutex block concurrent reads is not great for performance.
5238 : //
5239 : // But the only case where we need to run multiple of these at once is when we
5240 : // request a size for a tenant manually via API, while another background calculation
5241 : // is in progress (which is not a common case).
5242 : //
5243 : // See more for on the issue #2748 condenced out of the initial PR review.
5244 : let mut shared_cache = tokio::select! {
5245 : locked = self.cached_logical_sizes.lock() => locked,
5246 : _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
5247 : _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
5248 : };
5249 :
5250 : size::gather_inputs(
5251 : self,
5252 : logical_sizes_at_once,
5253 : max_retention_period,
5254 : &mut shared_cache,
5255 : cause,
5256 : cancel,
5257 : ctx,
5258 : )
5259 : .await
5260 : }
5261 :
5262 : /// Calculate synthetic tenant size and cache the result.
5263 : /// This is periodically called by background worker.
5264 : /// result is cached in tenant struct
5265 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5266 : pub async fn calculate_synthetic_size(
5267 : &self,
5268 : cause: LogicalSizeCalculationCause,
5269 : cancel: &CancellationToken,
5270 : ctx: &RequestContext,
5271 : ) -> Result<u64, size::CalculateSyntheticSizeError> {
5272 : let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
5273 :
5274 : let size = inputs.calculate();
5275 :
5276 : self.set_cached_synthetic_size(size);
5277 :
5278 : Ok(size)
5279 : }
5280 :
5281 : /// Cache given synthetic size and update the metric value
5282 0 : pub fn set_cached_synthetic_size(&self, size: u64) {
5283 0 : self.cached_synthetic_tenant_size
5284 0 : .store(size, Ordering::Relaxed);
5285 0 :
5286 0 : // Only shard zero should be calculating synthetic sizes
5287 0 : debug_assert!(self.shard_identity.is_shard_zero());
5288 :
5289 0 : TENANT_SYNTHETIC_SIZE_METRIC
5290 0 : .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
5291 0 : .unwrap()
5292 0 : .set(size);
5293 0 : }
5294 :
5295 0 : pub fn cached_synthetic_size(&self) -> u64 {
5296 0 : self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
5297 0 : }
5298 :
5299 : /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
5300 : ///
5301 : /// This function can take a long time: callers should wrap it in a timeout if calling
5302 : /// from an external API handler.
5303 : ///
5304 : /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
5305 : /// still bounded by tenant/timeline shutdown.
5306 : #[tracing::instrument(skip_all)]
5307 : pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
5308 : let timelines = self.timelines.lock().unwrap().clone();
5309 :
5310 0 : async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
5311 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
5312 0 : timeline.freeze_and_flush().await?;
5313 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
5314 0 : timeline.remote_client.wait_completion().await?;
5315 :
5316 0 : Ok(())
5317 0 : }
5318 :
5319 : // We do not use a JoinSet for these tasks, because we don't want them to be
5320 : // aborted when this function's future is cancelled: they should stay alive
5321 : // holding their GateGuard until they complete, to ensure their I/Os complete
5322 : // before Timeline shutdown completes.
5323 : let mut results = FuturesUnordered::new();
5324 :
5325 : for (_timeline_id, timeline) in timelines {
5326 : // Run each timeline's flush in a task holding the timeline's gate: this
5327 : // means that if this function's future is cancelled, the Timeline shutdown
5328 : // will still wait for any I/O in here to complete.
5329 : let Ok(gate) = timeline.gate.enter() else {
5330 : continue;
5331 : };
5332 0 : let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
5333 : results.push(jh);
5334 : }
5335 :
5336 : while let Some(r) = results.next().await {
5337 : if let Err(e) = r {
5338 : if !e.is_cancelled() && !e.is_panic() {
5339 : tracing::error!("unexpected join error: {e:?}");
5340 : }
5341 : }
5342 : }
5343 :
5344 : // The flushes we did above were just writes, but the Tenant might have had
5345 : // pending deletions as well from recent compaction/gc: we want to flush those
5346 : // as well. This requires flushing the global delete queue. This is cheap
5347 : // because it's typically a no-op.
5348 : match self.deletion_queue_client.flush_execute().await {
5349 : Ok(_) => {}
5350 : Err(DeletionQueueError::ShuttingDown) => {}
5351 : }
5352 :
5353 : Ok(())
5354 : }
5355 :
5356 0 : pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
5357 0 : self.tenant_conf.load().tenant_conf.clone()
5358 0 : }
5359 :
5360 : /// How much local storage would this tenant like to have? It can cope with
5361 : /// less than this (via eviction and on-demand downloads), but this function enables
5362 : /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
5363 : /// by keeping important things on local disk.
5364 : ///
5365 : /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
5366 : /// than they report here, due to layer eviction. Tenants with many active branches may
5367 : /// actually use more than they report here.
5368 0 : pub(crate) fn local_storage_wanted(&self) -> u64 {
5369 0 : let timelines = self.timelines.lock().unwrap();
5370 0 :
5371 0 : // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum. This
5372 0 : // reflects the observation that on tenants with multiple large branches, typically only one
5373 0 : // of them is used actively enough to occupy space on disk.
5374 0 : timelines
5375 0 : .values()
5376 0 : .map(|t| t.metrics.visible_physical_size_gauge.get())
5377 0 : .max()
5378 0 : .unwrap_or(0)
5379 0 : }
5380 :
5381 : /// Serialize and write the latest TenantManifest to remote storage.
5382 2 : pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
5383 : // Only one manifest write may be done at at time, and the contents of the manifest
5384 : // must be loaded while holding this lock. This makes it safe to call this function
5385 : // from anywhere without worrying about colliding updates.
5386 2 : let mut guard = tokio::select! {
5387 2 : g = self.tenant_manifest_upload.lock() => {
5388 2 : g
5389 : },
5390 2 : _ = self.cancel.cancelled() => {
5391 0 : return Err(TenantManifestError::Cancelled);
5392 : }
5393 : };
5394 :
5395 2 : let manifest = self.build_tenant_manifest();
5396 2 : if Some(&manifest) == (*guard).as_ref() {
5397 : // Optimisation: skip uploads that don't change anything.
5398 0 : return Ok(());
5399 2 : }
5400 2 :
5401 2 : upload_tenant_manifest(
5402 2 : &self.remote_storage,
5403 2 : &self.tenant_shard_id,
5404 2 : self.generation,
5405 2 : &manifest,
5406 2 : &self.cancel,
5407 2 : )
5408 2 : .await
5409 2 : .map_err(|e| {
5410 0 : if self.cancel.is_cancelled() {
5411 0 : TenantManifestError::Cancelled
5412 : } else {
5413 0 : TenantManifestError::RemoteStorage(e)
5414 : }
5415 2 : })?;
5416 :
5417 : // Store the successfully uploaded manifest, so that future callers can avoid
5418 : // re-uploading the same thing.
5419 2 : *guard = Some(manifest);
5420 2 :
5421 2 : Ok(())
5422 2 : }
5423 : }
5424 :
5425 : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
5426 : /// to get bootstrap data for timeline initialization.
5427 0 : async fn run_initdb(
5428 0 : conf: &'static PageServerConf,
5429 0 : initdb_target_dir: &Utf8Path,
5430 0 : pg_version: u32,
5431 0 : cancel: &CancellationToken,
5432 0 : ) -> Result<(), InitdbError> {
5433 0 : let initdb_bin_path = conf
5434 0 : .pg_bin_dir(pg_version)
5435 0 : .map_err(InitdbError::Other)?
5436 0 : .join("initdb");
5437 0 : let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
5438 0 : info!(
5439 0 : "running {} in {}, libdir: {}",
5440 : initdb_bin_path, initdb_target_dir, initdb_lib_dir,
5441 : );
5442 :
5443 0 : let _permit = INIT_DB_SEMAPHORE.acquire().await;
5444 :
5445 0 : let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
5446 0 : superuser: &conf.superuser,
5447 0 : locale: &conf.locale,
5448 0 : initdb_bin: &initdb_bin_path,
5449 0 : pg_version,
5450 0 : library_search_path: &initdb_lib_dir,
5451 0 : pgdata: initdb_target_dir,
5452 0 : })
5453 0 : .await
5454 0 : .map_err(InitdbError::Inner);
5455 0 :
5456 0 : // This isn't true cancellation support, see above. Still return an error to
5457 0 : // excercise the cancellation code path.
5458 0 : if cancel.is_cancelled() {
5459 0 : return Err(InitdbError::Cancelled);
5460 0 : }
5461 0 :
5462 0 : res
5463 0 : }
5464 :
5465 : /// Dump contents of a layer file to stdout.
5466 0 : pub async fn dump_layerfile_from_path(
5467 0 : path: &Utf8Path,
5468 0 : verbose: bool,
5469 0 : ctx: &RequestContext,
5470 0 : ) -> anyhow::Result<()> {
5471 : use std::os::unix::fs::FileExt;
5472 :
5473 : // All layer files start with a two-byte "magic" value, to identify the kind of
5474 : // file.
5475 0 : let file = File::open(path)?;
5476 0 : let mut header_buf = [0u8; 2];
5477 0 : file.read_exact_at(&mut header_buf, 0)?;
5478 :
5479 0 : match u16::from_be_bytes(header_buf) {
5480 : crate::IMAGE_FILE_MAGIC => {
5481 0 : ImageLayer::new_for_path(path, file)?
5482 0 : .dump(verbose, ctx)
5483 0 : .await?
5484 : }
5485 : crate::DELTA_FILE_MAGIC => {
5486 0 : DeltaLayer::new_for_path(path, file)?
5487 0 : .dump(verbose, ctx)
5488 0 : .await?
5489 : }
5490 0 : magic => bail!("unrecognized magic identifier: {:?}", magic),
5491 : }
5492 :
5493 0 : Ok(())
5494 0 : }
5495 :
5496 : #[cfg(test)]
5497 : pub(crate) mod harness {
5498 : use bytes::{Bytes, BytesMut};
5499 : use once_cell::sync::OnceCell;
5500 : use pageserver_api::models::ShardParameters;
5501 : use pageserver_api::shard::ShardIndex;
5502 : use utils::logging;
5503 :
5504 : use crate::deletion_queue::mock::MockDeletionQueue;
5505 : use crate::l0_flush::L0FlushConfig;
5506 : use crate::walredo::apply_neon;
5507 : use pageserver_api::key::Key;
5508 : use pageserver_api::record::NeonWalRecord;
5509 :
5510 : use super::*;
5511 : use hex_literal::hex;
5512 : use utils::id::TenantId;
5513 :
5514 : pub const TIMELINE_ID: TimelineId =
5515 : TimelineId::from_array(hex!("11223344556677881122334455667788"));
5516 : pub const NEW_TIMELINE_ID: TimelineId =
5517 : TimelineId::from_array(hex!("AA223344556677881122334455667788"));
5518 :
5519 : /// Convenience function to create a page image with given string as the only content
5520 5028711 : pub fn test_img(s: &str) -> Bytes {
5521 5028711 : let mut buf = BytesMut::new();
5522 5028711 : buf.extend_from_slice(s.as_bytes());
5523 5028711 : buf.resize(64, 0);
5524 5028711 :
5525 5028711 : buf.freeze()
5526 5028711 : }
5527 :
5528 : impl From<TenantConf> for TenantConfOpt {
5529 196 : fn from(tenant_conf: TenantConf) -> Self {
5530 196 : Self {
5531 196 : checkpoint_distance: Some(tenant_conf.checkpoint_distance),
5532 196 : checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
5533 196 : compaction_target_size: Some(tenant_conf.compaction_target_size),
5534 196 : compaction_period: Some(tenant_conf.compaction_period),
5535 196 : compaction_threshold: Some(tenant_conf.compaction_threshold),
5536 196 : compaction_algorithm: Some(tenant_conf.compaction_algorithm),
5537 196 : gc_horizon: Some(tenant_conf.gc_horizon),
5538 196 : gc_period: Some(tenant_conf.gc_period),
5539 196 : image_creation_threshold: Some(tenant_conf.image_creation_threshold),
5540 196 : pitr_interval: Some(tenant_conf.pitr_interval),
5541 196 : walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
5542 196 : lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
5543 196 : max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
5544 196 : eviction_policy: Some(tenant_conf.eviction_policy),
5545 196 : min_resident_size_override: tenant_conf.min_resident_size_override,
5546 196 : evictions_low_residence_duration_metric_threshold: Some(
5547 196 : tenant_conf.evictions_low_residence_duration_metric_threshold,
5548 196 : ),
5549 196 : heatmap_period: Some(tenant_conf.heatmap_period),
5550 196 : lazy_slru_download: Some(tenant_conf.lazy_slru_download),
5551 196 : timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
5552 196 : image_layer_creation_check_threshold: Some(
5553 196 : tenant_conf.image_layer_creation_check_threshold,
5554 196 : ),
5555 196 : lsn_lease_length: Some(tenant_conf.lsn_lease_length),
5556 196 : lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
5557 196 : timeline_offloading: Some(tenant_conf.timeline_offloading),
5558 196 : wal_receiver_protocol_override: tenant_conf.wal_receiver_protocol_override,
5559 196 : }
5560 196 : }
5561 : }
5562 :
5563 : pub struct TenantHarness {
5564 : pub conf: &'static PageServerConf,
5565 : pub tenant_conf: TenantConf,
5566 : pub tenant_shard_id: TenantShardId,
5567 : pub generation: Generation,
5568 : pub shard: ShardIndex,
5569 : pub remote_storage: GenericRemoteStorage,
5570 : pub remote_fs_dir: Utf8PathBuf,
5571 : pub deletion_queue: MockDeletionQueue,
5572 : }
5573 :
5574 : static LOG_HANDLE: OnceCell<()> = OnceCell::new();
5575 :
5576 212 : pub(crate) fn setup_logging() {
5577 212 : LOG_HANDLE.get_or_init(|| {
5578 200 : logging::init(
5579 200 : logging::LogFormat::Test,
5580 200 : // enable it in case the tests exercise code paths that use
5581 200 : // debug_assert_current_span_has_tenant_and_timeline_id
5582 200 : logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
5583 200 : logging::Output::Stdout,
5584 200 : )
5585 200 : .expect("Failed to init test logging")
5586 212 : });
5587 212 : }
5588 :
5589 : impl TenantHarness {
5590 196 : pub async fn create_custom(
5591 196 : test_name: &'static str,
5592 196 : tenant_conf: TenantConf,
5593 196 : tenant_id: TenantId,
5594 196 : shard_identity: ShardIdentity,
5595 196 : generation: Generation,
5596 196 : ) -> anyhow::Result<Self> {
5597 196 : setup_logging();
5598 196 :
5599 196 : let repo_dir = PageServerConf::test_repo_dir(test_name);
5600 196 : let _ = fs::remove_dir_all(&repo_dir);
5601 196 : fs::create_dir_all(&repo_dir)?;
5602 :
5603 196 : let conf = PageServerConf::dummy_conf(repo_dir);
5604 196 : // Make a static copy of the config. This can never be free'd, but that's
5605 196 : // OK in a test.
5606 196 : let conf: &'static PageServerConf = Box::leak(Box::new(conf));
5607 196 :
5608 196 : let shard = shard_identity.shard_index();
5609 196 : let tenant_shard_id = TenantShardId {
5610 196 : tenant_id,
5611 196 : shard_number: shard.shard_number,
5612 196 : shard_count: shard.shard_count,
5613 196 : };
5614 196 : fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
5615 196 : fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
5616 :
5617 : use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
5618 196 : let remote_fs_dir = conf.workdir.join("localfs");
5619 196 : std::fs::create_dir_all(&remote_fs_dir).unwrap();
5620 196 : let config = RemoteStorageConfig {
5621 196 : storage: RemoteStorageKind::LocalFs {
5622 196 : local_path: remote_fs_dir.clone(),
5623 196 : },
5624 196 : timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
5625 196 : small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
5626 196 : };
5627 196 : let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
5628 196 : let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
5629 196 :
5630 196 : Ok(Self {
5631 196 : conf,
5632 196 : tenant_conf,
5633 196 : tenant_shard_id,
5634 196 : generation,
5635 196 : shard,
5636 196 : remote_storage,
5637 196 : remote_fs_dir,
5638 196 : deletion_queue,
5639 196 : })
5640 196 : }
5641 :
5642 184 : pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
5643 184 : // Disable automatic GC and compaction to make the unit tests more deterministic.
5644 184 : // The tests perform them manually if needed.
5645 184 : let tenant_conf = TenantConf {
5646 184 : gc_period: Duration::ZERO,
5647 184 : compaction_period: Duration::ZERO,
5648 184 : ..TenantConf::default()
5649 184 : };
5650 184 : let tenant_id = TenantId::generate();
5651 184 : let shard = ShardIdentity::unsharded();
5652 184 : Self::create_custom(
5653 184 : test_name,
5654 184 : tenant_conf,
5655 184 : tenant_id,
5656 184 : shard,
5657 184 : Generation::new(0xdeadbeef),
5658 184 : )
5659 184 : .await
5660 184 : }
5661 :
5662 20 : pub fn span(&self) -> tracing::Span {
5663 20 : info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
5664 20 : }
5665 :
5666 196 : pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
5667 196 : let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
5668 196 : (
5669 196 : self.do_try_load(&ctx)
5670 196 : .await
5671 196 : .expect("failed to load test tenant"),
5672 196 : ctx,
5673 196 : )
5674 196 : }
5675 :
5676 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5677 : pub(crate) async fn do_try_load(
5678 : &self,
5679 : ctx: &RequestContext,
5680 : ) -> anyhow::Result<Arc<Tenant>> {
5681 : let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
5682 :
5683 : let tenant = Arc::new(Tenant::new(
5684 : TenantState::Attaching,
5685 : self.conf,
5686 : AttachedTenantConf::try_from(LocationConf::attached_single(
5687 : TenantConfOpt::from(self.tenant_conf.clone()),
5688 : self.generation,
5689 : &ShardParameters::default(),
5690 : ))
5691 : .unwrap(),
5692 : // This is a legacy/test code path: sharding isn't supported here.
5693 : ShardIdentity::unsharded(),
5694 : Some(walredo_mgr),
5695 : self.tenant_shard_id,
5696 : self.remote_storage.clone(),
5697 : self.deletion_queue.new_client(),
5698 : // TODO: ideally we should run all unit tests with both configs
5699 : L0FlushGlobalState::new(L0FlushConfig::default()),
5700 : ));
5701 :
5702 : let preload = tenant
5703 : .preload(&self.remote_storage, CancellationToken::new())
5704 : .await?;
5705 : tenant.attach(Some(preload), ctx).await?;
5706 :
5707 : tenant.state.send_replace(TenantState::Active);
5708 : for timeline in tenant.timelines.lock().unwrap().values() {
5709 : timeline.set_state(TimelineState::Active);
5710 : }
5711 : Ok(tenant)
5712 : }
5713 :
5714 2 : pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
5715 2 : self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
5716 2 : }
5717 : }
5718 :
5719 : // Mock WAL redo manager that doesn't do much
5720 : pub(crate) struct TestRedoManager;
5721 :
5722 : impl TestRedoManager {
5723 : /// # Cancel-Safety
5724 : ///
5725 : /// This method is cancellation-safe.
5726 520 : pub async fn request_redo(
5727 520 : &self,
5728 520 : key: Key,
5729 520 : lsn: Lsn,
5730 520 : base_img: Option<(Lsn, Bytes)>,
5731 520 : records: Vec<(Lsn, NeonWalRecord)>,
5732 520 : _pg_version: u32,
5733 520 : ) -> Result<Bytes, walredo::Error> {
5734 770 : let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
5735 520 : if records_neon {
5736 : // For Neon wal records, we can decode without spawning postgres, so do so.
5737 520 : let mut page = match (base_img, records.first()) {
5738 454 : (Some((_lsn, img)), _) => {
5739 454 : let mut page = BytesMut::new();
5740 454 : page.extend_from_slice(&img);
5741 454 : page
5742 : }
5743 66 : (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
5744 : _ => {
5745 0 : panic!("Neon WAL redo requires base image or will init record");
5746 : }
5747 : };
5748 :
5749 1290 : for (record_lsn, record) in records {
5750 770 : apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
5751 : }
5752 520 : Ok(page.freeze())
5753 : } else {
5754 : // We never spawn a postgres walredo process in unit tests: just log what we might have done.
5755 0 : let s = format!(
5756 0 : "redo for {} to get to {}, with {} and {} records",
5757 0 : key,
5758 0 : lsn,
5759 0 : if base_img.is_some() {
5760 0 : "base image"
5761 : } else {
5762 0 : "no base image"
5763 : },
5764 0 : records.len()
5765 0 : );
5766 0 : println!("{s}");
5767 0 :
5768 0 : Ok(test_img(&s))
5769 : }
5770 520 : }
5771 : }
5772 : }
5773 :
5774 : #[cfg(test)]
5775 : mod tests {
5776 : use std::collections::{BTreeMap, BTreeSet};
5777 :
5778 : use super::*;
5779 : use crate::keyspace::KeySpaceAccum;
5780 : use crate::tenant::harness::*;
5781 : use crate::tenant::timeline::CompactFlags;
5782 : use crate::DEFAULT_PG_VERSION;
5783 : use bytes::{Bytes, BytesMut};
5784 : use hex_literal::hex;
5785 : use itertools::Itertools;
5786 : use pageserver_api::key::{Key, AUX_KEY_PREFIX, NON_INHERITED_RANGE};
5787 : use pageserver_api::keyspace::KeySpace;
5788 : use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
5789 : use pageserver_api::value::Value;
5790 : use pageserver_compaction::helpers::overlaps_with;
5791 : use rand::{thread_rng, Rng};
5792 : use storage_layer::PersistentLayerKey;
5793 : use tests::storage_layer::ValuesReconstructState;
5794 : use tests::timeline::{GetVectoredError, ShutdownMode};
5795 : use timeline::{CompactOptions, DeltaLayerTestDesc};
5796 : use utils::id::TenantId;
5797 :
5798 : #[cfg(feature = "testing")]
5799 : use models::CompactLsnRange;
5800 : #[cfg(feature = "testing")]
5801 : use pageserver_api::record::NeonWalRecord;
5802 : #[cfg(feature = "testing")]
5803 : use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
5804 : #[cfg(feature = "testing")]
5805 : use timeline::GcInfo;
5806 :
5807 : static TEST_KEY: Lazy<Key> =
5808 18 : Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
5809 :
5810 : #[tokio::test]
5811 2 : async fn test_basic() -> anyhow::Result<()> {
5812 2 : let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
5813 2 : let tline = tenant
5814 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
5815 2 : .await?;
5816 2 :
5817 2 : let mut writer = tline.writer().await;
5818 2 : writer
5819 2 : .put(
5820 2 : *TEST_KEY,
5821 2 : Lsn(0x10),
5822 2 : &Value::Image(test_img("foo at 0x10")),
5823 2 : &ctx,
5824 2 : )
5825 2 : .await?;
5826 2 : writer.finish_write(Lsn(0x10));
5827 2 : drop(writer);
5828 2 :
5829 2 : let mut writer = tline.writer().await;
5830 2 : writer
5831 2 : .put(
5832 2 : *TEST_KEY,
5833 2 : Lsn(0x20),
5834 2 : &Value::Image(test_img("foo at 0x20")),
5835 2 : &ctx,
5836 2 : )
5837 2 : .await?;
5838 2 : writer.finish_write(Lsn(0x20));
5839 2 : drop(writer);
5840 2 :
5841 2 : assert_eq!(
5842 2 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
5843 2 : test_img("foo at 0x10")
5844 2 : );
5845 2 : assert_eq!(
5846 2 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
5847 2 : test_img("foo at 0x10")
5848 2 : );
5849 2 : assert_eq!(
5850 2 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
5851 2 : test_img("foo at 0x20")
5852 2 : );
5853 2 :
5854 2 : Ok(())
5855 2 : }
5856 :
5857 : #[tokio::test]
5858 2 : async fn no_duplicate_timelines() -> anyhow::Result<()> {
5859 2 : let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
5860 2 : .await?
5861 2 : .load()
5862 2 : .await;
5863 2 : let _ = tenant
5864 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5865 2 : .await?;
5866 2 :
5867 2 : match tenant
5868 2 : .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5869 2 : .await
5870 2 : {
5871 2 : Ok(_) => panic!("duplicate timeline creation should fail"),
5872 2 : Err(e) => assert_eq!(
5873 2 : e.to_string(),
5874 2 : "timeline already exists with different parameters".to_string()
5875 2 : ),
5876 2 : }
5877 2 :
5878 2 : Ok(())
5879 2 : }
5880 :
5881 : /// Convenience function to create a page image with given string as the only content
5882 10 : pub fn test_value(s: &str) -> Value {
5883 10 : let mut buf = BytesMut::new();
5884 10 : buf.extend_from_slice(s.as_bytes());
5885 10 : Value::Image(buf.freeze())
5886 10 : }
5887 :
5888 : ///
5889 : /// Test branch creation
5890 : ///
5891 : #[tokio::test]
5892 2 : async fn test_branch() -> anyhow::Result<()> {
5893 2 : use std::str::from_utf8;
5894 2 :
5895 2 : let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
5896 2 : let tline = tenant
5897 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5898 2 : .await?;
5899 2 : let mut writer = tline.writer().await;
5900 2 :
5901 2 : #[allow(non_snake_case)]
5902 2 : let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
5903 2 : #[allow(non_snake_case)]
5904 2 : let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
5905 2 :
5906 2 : // Insert a value on the timeline
5907 2 : writer
5908 2 : .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
5909 2 : .await?;
5910 2 : writer
5911 2 : .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
5912 2 : .await?;
5913 2 : writer.finish_write(Lsn(0x20));
5914 2 :
5915 2 : writer
5916 2 : .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
5917 2 : .await?;
5918 2 : writer.finish_write(Lsn(0x30));
5919 2 : writer
5920 2 : .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
5921 2 : .await?;
5922 2 : writer.finish_write(Lsn(0x40));
5923 2 :
5924 2 : //assert_current_logical_size(&tline, Lsn(0x40));
5925 2 :
5926 2 : // Branch the history, modify relation differently on the new timeline
5927 2 : tenant
5928 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
5929 2 : .await?;
5930 2 : let newtline = tenant
5931 2 : .get_timeline(NEW_TIMELINE_ID, true)
5932 2 : .expect("Should have a local timeline");
5933 2 : let mut new_writer = newtline.writer().await;
5934 2 : new_writer
5935 2 : .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
5936 2 : .await?;
5937 2 : new_writer.finish_write(Lsn(0x40));
5938 2 :
5939 2 : // Check page contents on both branches
5940 2 : assert_eq!(
5941 2 : from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
5942 2 : "foo at 0x40"
5943 2 : );
5944 2 : assert_eq!(
5945 2 : from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
5946 2 : "bar at 0x40"
5947 2 : );
5948 2 : assert_eq!(
5949 2 : from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
5950 2 : "foobar at 0x20"
5951 2 : );
5952 2 :
5953 2 : //assert_current_logical_size(&tline, Lsn(0x40));
5954 2 :
5955 2 : Ok(())
5956 2 : }
5957 :
5958 20 : async fn make_some_layers(
5959 20 : tline: &Timeline,
5960 20 : start_lsn: Lsn,
5961 20 : ctx: &RequestContext,
5962 20 : ) -> anyhow::Result<()> {
5963 20 : let mut lsn = start_lsn;
5964 : {
5965 20 : let mut writer = tline.writer().await;
5966 : // Create a relation on the timeline
5967 20 : writer
5968 20 : .put(
5969 20 : *TEST_KEY,
5970 20 : lsn,
5971 20 : &Value::Image(test_img(&format!("foo at {}", lsn))),
5972 20 : ctx,
5973 20 : )
5974 20 : .await?;
5975 20 : writer.finish_write(lsn);
5976 20 : lsn += 0x10;
5977 20 : writer
5978 20 : .put(
5979 20 : *TEST_KEY,
5980 20 : lsn,
5981 20 : &Value::Image(test_img(&format!("foo at {}", lsn))),
5982 20 : ctx,
5983 20 : )
5984 20 : .await?;
5985 20 : writer.finish_write(lsn);
5986 20 : lsn += 0x10;
5987 20 : }
5988 20 : tline.freeze_and_flush().await?;
5989 : {
5990 20 : let mut writer = tline.writer().await;
5991 20 : writer
5992 20 : .put(
5993 20 : *TEST_KEY,
5994 20 : lsn,
5995 20 : &Value::Image(test_img(&format!("foo at {}", lsn))),
5996 20 : ctx,
5997 20 : )
5998 20 : .await?;
5999 20 : writer.finish_write(lsn);
6000 20 : lsn += 0x10;
6001 20 : writer
6002 20 : .put(
6003 20 : *TEST_KEY,
6004 20 : lsn,
6005 20 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6006 20 : ctx,
6007 20 : )
6008 20 : .await?;
6009 20 : writer.finish_write(lsn);
6010 20 : }
6011 20 : tline.freeze_and_flush().await.map_err(|e| e.into())
6012 20 : }
6013 :
6014 : #[tokio::test(start_paused = true)]
6015 2 : async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
6016 2 : let (tenant, ctx) =
6017 2 : TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
6018 2 : .await?
6019 2 : .load()
6020 2 : .await;
6021 2 : // Advance to the lsn lease deadline so that GC is not blocked by
6022 2 : // initial transition into AttachedSingle.
6023 2 : tokio::time::advance(tenant.get_lsn_lease_length()).await;
6024 2 : tokio::time::resume();
6025 2 : let tline = tenant
6026 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6027 2 : .await?;
6028 2 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6029 2 :
6030 2 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
6031 2 : // FIXME: this doesn't actually remove any layer currently, given how the flushing
6032 2 : // and compaction works. But it does set the 'cutoff' point so that the cross check
6033 2 : // below should fail.
6034 2 : tenant
6035 2 : .gc_iteration(
6036 2 : Some(TIMELINE_ID),
6037 2 : 0x10,
6038 2 : Duration::ZERO,
6039 2 : &CancellationToken::new(),
6040 2 : &ctx,
6041 2 : )
6042 2 : .await?;
6043 2 :
6044 2 : // try to branch at lsn 25, should fail because we already garbage collected the data
6045 2 : match tenant
6046 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
6047 2 : .await
6048 2 : {
6049 2 : Ok(_) => panic!("branching should have failed"),
6050 2 : Err(err) => {
6051 2 : let CreateTimelineError::AncestorLsn(err) = err else {
6052 2 : panic!("wrong error type")
6053 2 : };
6054 2 : assert!(err.to_string().contains("invalid branch start lsn"));
6055 2 : assert!(err
6056 2 : .source()
6057 2 : .unwrap()
6058 2 : .to_string()
6059 2 : .contains("we might've already garbage collected needed data"))
6060 2 : }
6061 2 : }
6062 2 :
6063 2 : Ok(())
6064 2 : }
6065 :
6066 : #[tokio::test]
6067 2 : async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
6068 2 : let (tenant, ctx) =
6069 2 : TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
6070 2 : .await?
6071 2 : .load()
6072 2 : .await;
6073 2 :
6074 2 : let tline = tenant
6075 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
6076 2 : .await?;
6077 2 : // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
6078 2 : match tenant
6079 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
6080 2 : .await
6081 2 : {
6082 2 : Ok(_) => panic!("branching should have failed"),
6083 2 : Err(err) => {
6084 2 : let CreateTimelineError::AncestorLsn(err) = err else {
6085 2 : panic!("wrong error type");
6086 2 : };
6087 2 : assert!(&err.to_string().contains("invalid branch start lsn"));
6088 2 : assert!(&err
6089 2 : .source()
6090 2 : .unwrap()
6091 2 : .to_string()
6092 2 : .contains("is earlier than latest GC cutoff"));
6093 2 : }
6094 2 : }
6095 2 :
6096 2 : Ok(())
6097 2 : }
6098 :
6099 : /*
6100 : // FIXME: This currently fails to error out. Calling GC doesn't currently
6101 : // remove the old value, we'd need to work a little harder
6102 : #[tokio::test]
6103 : async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
6104 : let repo =
6105 : RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
6106 : .load();
6107 :
6108 : let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
6109 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6110 :
6111 : repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
6112 : let latest_gc_cutoff_lsn = tline.get_latest_gc_cutoff_lsn();
6113 : assert!(*latest_gc_cutoff_lsn > Lsn(0x25));
6114 : match tline.get(*TEST_KEY, Lsn(0x25)) {
6115 : Ok(_) => panic!("request for page should have failed"),
6116 : Err(err) => assert!(err.to_string().contains("not found at")),
6117 : }
6118 : Ok(())
6119 : }
6120 : */
6121 :
6122 : #[tokio::test]
6123 2 : async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
6124 2 : let (tenant, ctx) =
6125 2 : TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
6126 2 : .await?
6127 2 : .load()
6128 2 : .await;
6129 2 : let tline = tenant
6130 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6131 2 : .await?;
6132 2 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6133 2 :
6134 2 : tenant
6135 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6136 2 : .await?;
6137 2 : let newtline = tenant
6138 2 : .get_timeline(NEW_TIMELINE_ID, true)
6139 2 : .expect("Should have a local timeline");
6140 2 :
6141 2 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6142 2 :
6143 2 : tline.set_broken("test".to_owned());
6144 2 :
6145 2 : tenant
6146 2 : .gc_iteration(
6147 2 : Some(TIMELINE_ID),
6148 2 : 0x10,
6149 2 : Duration::ZERO,
6150 2 : &CancellationToken::new(),
6151 2 : &ctx,
6152 2 : )
6153 2 : .await?;
6154 2 :
6155 2 : // The branchpoints should contain all timelines, even ones marked
6156 2 : // as Broken.
6157 2 : {
6158 2 : let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
6159 2 : assert_eq!(branchpoints.len(), 1);
6160 2 : assert_eq!(
6161 2 : branchpoints[0],
6162 2 : (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
6163 2 : );
6164 2 : }
6165 2 :
6166 2 : // You can read the key from the child branch even though the parent is
6167 2 : // Broken, as long as you don't need to access data from the parent.
6168 2 : assert_eq!(
6169 2 : newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
6170 2 : test_img(&format!("foo at {}", Lsn(0x70)))
6171 2 : );
6172 2 :
6173 2 : // This needs to traverse to the parent, and fails.
6174 2 : let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
6175 2 : assert!(
6176 2 : err.to_string().starts_with(&format!(
6177 2 : "bad state on timeline {}: Broken",
6178 2 : tline.timeline_id
6179 2 : )),
6180 2 : "{err}"
6181 2 : );
6182 2 :
6183 2 : Ok(())
6184 2 : }
6185 :
6186 : #[tokio::test]
6187 2 : async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
6188 2 : let (tenant, ctx) =
6189 2 : TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
6190 2 : .await?
6191 2 : .load()
6192 2 : .await;
6193 2 : let tline = tenant
6194 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6195 2 : .await?;
6196 2 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6197 2 :
6198 2 : tenant
6199 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6200 2 : .await?;
6201 2 : let newtline = tenant
6202 2 : .get_timeline(NEW_TIMELINE_ID, true)
6203 2 : .expect("Should have a local timeline");
6204 2 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
6205 2 : tenant
6206 2 : .gc_iteration(
6207 2 : Some(TIMELINE_ID),
6208 2 : 0x10,
6209 2 : Duration::ZERO,
6210 2 : &CancellationToken::new(),
6211 2 : &ctx,
6212 2 : )
6213 2 : .await?;
6214 2 : assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
6215 2 :
6216 2 : Ok(())
6217 2 : }
6218 : #[tokio::test]
6219 2 : async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
6220 2 : let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
6221 2 : .await?
6222 2 : .load()
6223 2 : .await;
6224 2 : let tline = tenant
6225 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6226 2 : .await?;
6227 2 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6228 2 :
6229 2 : tenant
6230 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6231 2 : .await?;
6232 2 : let newtline = tenant
6233 2 : .get_timeline(NEW_TIMELINE_ID, true)
6234 2 : .expect("Should have a local timeline");
6235 2 :
6236 2 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6237 2 :
6238 2 : // run gc on parent
6239 2 : tenant
6240 2 : .gc_iteration(
6241 2 : Some(TIMELINE_ID),
6242 2 : 0x10,
6243 2 : Duration::ZERO,
6244 2 : &CancellationToken::new(),
6245 2 : &ctx,
6246 2 : )
6247 2 : .await?;
6248 2 :
6249 2 : // Check that the data is still accessible on the branch.
6250 2 : assert_eq!(
6251 2 : newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
6252 2 : test_img(&format!("foo at {}", Lsn(0x40)))
6253 2 : );
6254 2 :
6255 2 : Ok(())
6256 2 : }
6257 :
6258 : #[tokio::test]
6259 2 : async fn timeline_load() -> anyhow::Result<()> {
6260 2 : const TEST_NAME: &str = "timeline_load";
6261 2 : let harness = TenantHarness::create(TEST_NAME).await?;
6262 2 : {
6263 2 : let (tenant, ctx) = harness.load().await;
6264 2 : let tline = tenant
6265 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
6266 2 : .await?;
6267 2 : make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
6268 2 : // so that all uploads finish & we can call harness.load() below again
6269 2 : tenant
6270 2 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
6271 2 : .instrument(harness.span())
6272 2 : .await
6273 2 : .ok()
6274 2 : .unwrap();
6275 2 : }
6276 2 :
6277 2 : let (tenant, _ctx) = harness.load().await;
6278 2 : tenant
6279 2 : .get_timeline(TIMELINE_ID, true)
6280 2 : .expect("cannot load timeline");
6281 2 :
6282 2 : Ok(())
6283 2 : }
6284 :
6285 : #[tokio::test]
6286 2 : async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
6287 2 : const TEST_NAME: &str = "timeline_load_with_ancestor";
6288 2 : let harness = TenantHarness::create(TEST_NAME).await?;
6289 2 : // create two timelines
6290 2 : {
6291 2 : let (tenant, ctx) = harness.load().await;
6292 2 : let tline = tenant
6293 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6294 2 : .await?;
6295 2 :
6296 2 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6297 2 :
6298 2 : let child_tline = tenant
6299 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6300 2 : .await?;
6301 2 : child_tline.set_state(TimelineState::Active);
6302 2 :
6303 2 : let newtline = tenant
6304 2 : .get_timeline(NEW_TIMELINE_ID, true)
6305 2 : .expect("Should have a local timeline");
6306 2 :
6307 2 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6308 2 :
6309 2 : // so that all uploads finish & we can call harness.load() below again
6310 2 : tenant
6311 2 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
6312 2 : .instrument(harness.span())
6313 2 : .await
6314 2 : .ok()
6315 2 : .unwrap();
6316 2 : }
6317 2 :
6318 2 : // check that both of them are initially unloaded
6319 2 : let (tenant, _ctx) = harness.load().await;
6320 2 :
6321 2 : // check that both, child and ancestor are loaded
6322 2 : let _child_tline = tenant
6323 2 : .get_timeline(NEW_TIMELINE_ID, true)
6324 2 : .expect("cannot get child timeline loaded");
6325 2 :
6326 2 : let _ancestor_tline = tenant
6327 2 : .get_timeline(TIMELINE_ID, true)
6328 2 : .expect("cannot get ancestor timeline loaded");
6329 2 :
6330 2 : Ok(())
6331 2 : }
6332 :
6333 : #[tokio::test]
6334 2 : async fn delta_layer_dumping() -> anyhow::Result<()> {
6335 2 : use storage_layer::AsLayerDesc;
6336 2 : let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
6337 2 : .await?
6338 2 : .load()
6339 2 : .await;
6340 2 : let tline = tenant
6341 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6342 2 : .await?;
6343 2 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6344 2 :
6345 2 : let layer_map = tline.layers.read().await;
6346 2 : let level0_deltas = layer_map
6347 2 : .layer_map()?
6348 2 : .level0_deltas()
6349 2 : .iter()
6350 4 : .map(|desc| layer_map.get_from_desc(desc))
6351 2 : .collect::<Vec<_>>();
6352 2 :
6353 2 : assert!(!level0_deltas.is_empty());
6354 2 :
6355 6 : for delta in level0_deltas {
6356 2 : // Ensure we are dumping a delta layer here
6357 4 : assert!(delta.layer_desc().is_delta);
6358 4 : delta.dump(true, &ctx).await.unwrap();
6359 2 : }
6360 2 :
6361 2 : Ok(())
6362 2 : }
6363 :
6364 : #[tokio::test]
6365 2 : async fn test_images() -> anyhow::Result<()> {
6366 2 : let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
6367 2 : let tline = tenant
6368 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6369 2 : .await?;
6370 2 :
6371 2 : let mut writer = tline.writer().await;
6372 2 : writer
6373 2 : .put(
6374 2 : *TEST_KEY,
6375 2 : Lsn(0x10),
6376 2 : &Value::Image(test_img("foo at 0x10")),
6377 2 : &ctx,
6378 2 : )
6379 2 : .await?;
6380 2 : writer.finish_write(Lsn(0x10));
6381 2 : drop(writer);
6382 2 :
6383 2 : tline.freeze_and_flush().await?;
6384 2 : tline
6385 2 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
6386 2 : .await?;
6387 2 :
6388 2 : let mut writer = tline.writer().await;
6389 2 : writer
6390 2 : .put(
6391 2 : *TEST_KEY,
6392 2 : Lsn(0x20),
6393 2 : &Value::Image(test_img("foo at 0x20")),
6394 2 : &ctx,
6395 2 : )
6396 2 : .await?;
6397 2 : writer.finish_write(Lsn(0x20));
6398 2 : drop(writer);
6399 2 :
6400 2 : tline.freeze_and_flush().await?;
6401 2 : tline
6402 2 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
6403 2 : .await?;
6404 2 :
6405 2 : let mut writer = tline.writer().await;
6406 2 : writer
6407 2 : .put(
6408 2 : *TEST_KEY,
6409 2 : Lsn(0x30),
6410 2 : &Value::Image(test_img("foo at 0x30")),
6411 2 : &ctx,
6412 2 : )
6413 2 : .await?;
6414 2 : writer.finish_write(Lsn(0x30));
6415 2 : drop(writer);
6416 2 :
6417 2 : tline.freeze_and_flush().await?;
6418 2 : tline
6419 2 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
6420 2 : .await?;
6421 2 :
6422 2 : let mut writer = tline.writer().await;
6423 2 : writer
6424 2 : .put(
6425 2 : *TEST_KEY,
6426 2 : Lsn(0x40),
6427 2 : &Value::Image(test_img("foo at 0x40")),
6428 2 : &ctx,
6429 2 : )
6430 2 : .await?;
6431 2 : writer.finish_write(Lsn(0x40));
6432 2 : drop(writer);
6433 2 :
6434 2 : tline.freeze_and_flush().await?;
6435 2 : tline
6436 2 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
6437 2 : .await?;
6438 2 :
6439 2 : assert_eq!(
6440 2 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
6441 2 : test_img("foo at 0x10")
6442 2 : );
6443 2 : assert_eq!(
6444 2 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
6445 2 : test_img("foo at 0x10")
6446 2 : );
6447 2 : assert_eq!(
6448 2 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
6449 2 : test_img("foo at 0x20")
6450 2 : );
6451 2 : assert_eq!(
6452 2 : tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
6453 2 : test_img("foo at 0x30")
6454 2 : );
6455 2 : assert_eq!(
6456 2 : tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
6457 2 : test_img("foo at 0x40")
6458 2 : );
6459 2 :
6460 2 : Ok(())
6461 2 : }
6462 :
6463 4 : async fn bulk_insert_compact_gc(
6464 4 : tenant: &Tenant,
6465 4 : timeline: &Arc<Timeline>,
6466 4 : ctx: &RequestContext,
6467 4 : lsn: Lsn,
6468 4 : repeat: usize,
6469 4 : key_count: usize,
6470 4 : ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
6471 4 : let compact = true;
6472 4 : bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
6473 4 : }
6474 :
6475 8 : async fn bulk_insert_maybe_compact_gc(
6476 8 : tenant: &Tenant,
6477 8 : timeline: &Arc<Timeline>,
6478 8 : ctx: &RequestContext,
6479 8 : mut lsn: Lsn,
6480 8 : repeat: usize,
6481 8 : key_count: usize,
6482 8 : compact: bool,
6483 8 : ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
6484 8 : let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
6485 8 :
6486 8 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6487 8 : let mut blknum = 0;
6488 8 :
6489 8 : // Enforce that key range is monotonously increasing
6490 8 : let mut keyspace = KeySpaceAccum::new();
6491 8 :
6492 8 : let cancel = CancellationToken::new();
6493 8 :
6494 8 : for _ in 0..repeat {
6495 400 : for _ in 0..key_count {
6496 4000000 : test_key.field6 = blknum;
6497 4000000 : let mut writer = timeline.writer().await;
6498 4000000 : writer
6499 4000000 : .put(
6500 4000000 : test_key,
6501 4000000 : lsn,
6502 4000000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
6503 4000000 : ctx,
6504 4000000 : )
6505 4000000 : .await?;
6506 4000000 : inserted.entry(test_key).or_default().insert(lsn);
6507 4000000 : writer.finish_write(lsn);
6508 4000000 : drop(writer);
6509 4000000 :
6510 4000000 : keyspace.add_key(test_key);
6511 4000000 :
6512 4000000 : lsn = Lsn(lsn.0 + 0x10);
6513 4000000 : blknum += 1;
6514 : }
6515 :
6516 400 : timeline.freeze_and_flush().await?;
6517 400 : if compact {
6518 : // this requires timeline to be &Arc<Timeline>
6519 200 : timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
6520 200 : }
6521 :
6522 : // this doesn't really need to use the timeline_id target, but it is closer to what it
6523 : // originally was.
6524 400 : let res = tenant
6525 400 : .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
6526 400 : .await?;
6527 :
6528 400 : assert_eq!(res.layers_removed, 0, "this never removes anything");
6529 : }
6530 :
6531 8 : Ok(inserted)
6532 8 : }
6533 :
6534 : //
6535 : // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
6536 : // Repeat 50 times.
6537 : //
6538 : #[tokio::test]
6539 2 : async fn test_bulk_insert() -> anyhow::Result<()> {
6540 2 : let harness = TenantHarness::create("test_bulk_insert").await?;
6541 2 : let (tenant, ctx) = harness.load().await;
6542 2 : let tline = tenant
6543 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6544 2 : .await?;
6545 2 :
6546 2 : let lsn = Lsn(0x10);
6547 2 : bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
6548 2 :
6549 2 : Ok(())
6550 2 : }
6551 :
6552 : // Test the vectored get real implementation against a simple sequential implementation.
6553 : //
6554 : // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
6555 : // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
6556 : // grow to the right on the X axis.
6557 : // [Delta]
6558 : // [Delta]
6559 : // [Delta]
6560 : // [Delta]
6561 : // ------------ Image ---------------
6562 : //
6563 : // After layer generation we pick the ranges to query as follows:
6564 : // 1. The beginning of each delta layer
6565 : // 2. At the seam between two adjacent delta layers
6566 : //
6567 : // There's one major downside to this test: delta layers only contains images,
6568 : // so the search can stop at the first delta layer and doesn't traverse any deeper.
6569 : #[tokio::test]
6570 2 : async fn test_get_vectored() -> anyhow::Result<()> {
6571 2 : let harness = TenantHarness::create("test_get_vectored").await?;
6572 2 : let (tenant, ctx) = harness.load().await;
6573 2 : let tline = tenant
6574 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6575 2 : .await?;
6576 2 :
6577 2 : let lsn = Lsn(0x10);
6578 2 : let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
6579 2 :
6580 2 : let guard = tline.layers.read().await;
6581 2 : let lm = guard.layer_map()?;
6582 2 :
6583 2 : lm.dump(true, &ctx).await?;
6584 2 :
6585 2 : let mut reads = Vec::new();
6586 2 : let mut prev = None;
6587 12 : lm.iter_historic_layers().for_each(|desc| {
6588 12 : if !desc.is_delta() {
6589 2 : prev = Some(desc.clone());
6590 2 : return;
6591 10 : }
6592 10 :
6593 10 : let start = desc.key_range.start;
6594 10 : let end = desc
6595 10 : .key_range
6596 10 : .start
6597 10 : .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
6598 10 : reads.push(KeySpace {
6599 10 : ranges: vec![start..end],
6600 10 : });
6601 2 :
6602 10 : if let Some(prev) = &prev {
6603 10 : if !prev.is_delta() {
6604 10 : return;
6605 2 : }
6606 0 :
6607 0 : let first_range = Key {
6608 0 : field6: prev.key_range.end.field6 - 4,
6609 0 : ..prev.key_range.end
6610 0 : }..prev.key_range.end;
6611 0 :
6612 0 : let second_range = desc.key_range.start..Key {
6613 0 : field6: desc.key_range.start.field6 + 4,
6614 0 : ..desc.key_range.start
6615 0 : };
6616 0 :
6617 0 : reads.push(KeySpace {
6618 0 : ranges: vec![first_range, second_range],
6619 0 : });
6620 2 : };
6621 2 :
6622 2 : prev = Some(desc.clone());
6623 12 : });
6624 2 :
6625 2 : drop(guard);
6626 2 :
6627 2 : // Pick a big LSN such that we query over all the changes.
6628 2 : let reads_lsn = Lsn(u64::MAX - 1);
6629 2 :
6630 12 : for read in reads {
6631 10 : info!("Doing vectored read on {:?}", read);
6632 2 :
6633 10 : let vectored_res = tline
6634 10 : .get_vectored_impl(
6635 10 : read.clone(),
6636 10 : reads_lsn,
6637 10 : &mut ValuesReconstructState::new(),
6638 10 : &ctx,
6639 10 : )
6640 10 : .await;
6641 2 :
6642 10 : let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
6643 10 : let mut expect_missing = false;
6644 10 : let mut key = read.start().unwrap();
6645 330 : while key != read.end().unwrap() {
6646 320 : if let Some(lsns) = inserted.get(&key) {
6647 320 : let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
6648 320 : match expected_lsn {
6649 320 : Some(lsn) => {
6650 320 : expected_lsns.insert(key, *lsn);
6651 320 : }
6652 2 : None => {
6653 2 : expect_missing = true;
6654 0 : break;
6655 2 : }
6656 2 : }
6657 2 : } else {
6658 2 : expect_missing = true;
6659 0 : break;
6660 2 : }
6661 2 :
6662 320 : key = key.next();
6663 2 : }
6664 2 :
6665 10 : if expect_missing {
6666 2 : assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
6667 2 : } else {
6668 320 : for (key, image) in vectored_res? {
6669 320 : let expected_lsn = expected_lsns.get(&key).expect("determined above");
6670 320 : let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
6671 320 : assert_eq!(image?, expected_image);
6672 2 : }
6673 2 : }
6674 2 : }
6675 2 :
6676 2 : Ok(())
6677 2 : }
6678 :
6679 : #[tokio::test]
6680 2 : async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
6681 2 : let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
6682 2 :
6683 2 : let (tenant, ctx) = harness.load().await;
6684 2 : let tline = tenant
6685 2 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
6686 2 : .await?;
6687 2 : let tline = tline.raw_timeline().unwrap();
6688 2 :
6689 2 : let mut modification = tline.begin_modification(Lsn(0x1000));
6690 2 : modification.put_file("foo/bar1", b"content1", &ctx).await?;
6691 2 : modification.set_lsn(Lsn(0x1008))?;
6692 2 : modification.put_file("foo/bar2", b"content2", &ctx).await?;
6693 2 : modification.commit(&ctx).await?;
6694 2 :
6695 2 : let child_timeline_id = TimelineId::generate();
6696 2 : tenant
6697 2 : .branch_timeline_test(
6698 2 : tline,
6699 2 : child_timeline_id,
6700 2 : Some(tline.get_last_record_lsn()),
6701 2 : &ctx,
6702 2 : )
6703 2 : .await?;
6704 2 :
6705 2 : let child_timeline = tenant
6706 2 : .get_timeline(child_timeline_id, true)
6707 2 : .expect("Should have the branched timeline");
6708 2 :
6709 2 : let aux_keyspace = KeySpace {
6710 2 : ranges: vec![NON_INHERITED_RANGE],
6711 2 : };
6712 2 : let read_lsn = child_timeline.get_last_record_lsn();
6713 2 :
6714 2 : let vectored_res = child_timeline
6715 2 : .get_vectored_impl(
6716 2 : aux_keyspace.clone(),
6717 2 : read_lsn,
6718 2 : &mut ValuesReconstructState::new(),
6719 2 : &ctx,
6720 2 : )
6721 2 : .await;
6722 2 :
6723 2 : let images = vectored_res?;
6724 2 : assert!(images.is_empty());
6725 2 : Ok(())
6726 2 : }
6727 :
6728 : // Test that vectored get handles layer gaps correctly
6729 : // by advancing into the next ancestor timeline if required.
6730 : //
6731 : // The test generates timelines that look like the diagram below.
6732 : // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
6733 : // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
6734 : //
6735 : // ```
6736 : //-------------------------------+
6737 : // ... |
6738 : // [ L1 ] |
6739 : // [ / L1 ] | Child Timeline
6740 : // ... |
6741 : // ------------------------------+
6742 : // [ X L1 ] | Parent Timeline
6743 : // ------------------------------+
6744 : // ```
6745 : #[tokio::test]
6746 2 : async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
6747 2 : let tenant_conf = TenantConf {
6748 2 : // Make compaction deterministic
6749 2 : gc_period: Duration::ZERO,
6750 2 : compaction_period: Duration::ZERO,
6751 2 : // Encourage creation of L1 layers
6752 2 : checkpoint_distance: 16 * 1024,
6753 2 : compaction_target_size: 8 * 1024,
6754 2 : ..TenantConf::default()
6755 2 : };
6756 2 :
6757 2 : let harness = TenantHarness::create_custom(
6758 2 : "test_get_vectored_key_gap",
6759 2 : tenant_conf,
6760 2 : TenantId::generate(),
6761 2 : ShardIdentity::unsharded(),
6762 2 : Generation::new(0xdeadbeef),
6763 2 : )
6764 2 : .await?;
6765 2 : let (tenant, ctx) = harness.load().await;
6766 2 :
6767 2 : let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6768 2 : let gap_at_key = current_key.add(100);
6769 2 : let mut current_lsn = Lsn(0x10);
6770 2 :
6771 2 : const KEY_COUNT: usize = 10_000;
6772 2 :
6773 2 : let timeline_id = TimelineId::generate();
6774 2 : let current_timeline = tenant
6775 2 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
6776 2 : .await?;
6777 2 :
6778 2 : current_lsn += 0x100;
6779 2 :
6780 2 : let mut writer = current_timeline.writer().await;
6781 2 : writer
6782 2 : .put(
6783 2 : gap_at_key,
6784 2 : current_lsn,
6785 2 : &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
6786 2 : &ctx,
6787 2 : )
6788 2 : .await?;
6789 2 : writer.finish_write(current_lsn);
6790 2 : drop(writer);
6791 2 :
6792 2 : let mut latest_lsns = HashMap::new();
6793 2 : latest_lsns.insert(gap_at_key, current_lsn);
6794 2 :
6795 2 : current_timeline.freeze_and_flush().await?;
6796 2 :
6797 2 : let child_timeline_id = TimelineId::generate();
6798 2 :
6799 2 : tenant
6800 2 : .branch_timeline_test(
6801 2 : ¤t_timeline,
6802 2 : child_timeline_id,
6803 2 : Some(current_lsn),
6804 2 : &ctx,
6805 2 : )
6806 2 : .await?;
6807 2 : let child_timeline = tenant
6808 2 : .get_timeline(child_timeline_id, true)
6809 2 : .expect("Should have the branched timeline");
6810 2 :
6811 20002 : for i in 0..KEY_COUNT {
6812 20000 : if current_key == gap_at_key {
6813 2 : current_key = current_key.next();
6814 2 : continue;
6815 19998 : }
6816 19998 :
6817 19998 : current_lsn += 0x10;
6818 2 :
6819 19998 : let mut writer = child_timeline.writer().await;
6820 19998 : writer
6821 19998 : .put(
6822 19998 : current_key,
6823 19998 : current_lsn,
6824 19998 : &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
6825 19998 : &ctx,
6826 19998 : )
6827 19998 : .await?;
6828 19998 : writer.finish_write(current_lsn);
6829 19998 : drop(writer);
6830 19998 :
6831 19998 : latest_lsns.insert(current_key, current_lsn);
6832 19998 : current_key = current_key.next();
6833 19998 :
6834 19998 : // Flush every now and then to encourage layer file creation.
6835 19998 : if i % 500 == 0 {
6836 40 : child_timeline.freeze_and_flush().await?;
6837 19958 : }
6838 2 : }
6839 2 :
6840 2 : child_timeline.freeze_and_flush().await?;
6841 2 : let mut flags = EnumSet::new();
6842 2 : flags.insert(CompactFlags::ForceRepartition);
6843 2 : child_timeline
6844 2 : .compact(&CancellationToken::new(), flags, &ctx)
6845 2 : .await?;
6846 2 :
6847 2 : let key_near_end = {
6848 2 : let mut tmp = current_key;
6849 2 : tmp.field6 -= 10;
6850 2 : tmp
6851 2 : };
6852 2 :
6853 2 : let key_near_gap = {
6854 2 : let mut tmp = gap_at_key;
6855 2 : tmp.field6 -= 10;
6856 2 : tmp
6857 2 : };
6858 2 :
6859 2 : let read = KeySpace {
6860 2 : ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
6861 2 : };
6862 2 : let results = child_timeline
6863 2 : .get_vectored_impl(
6864 2 : read.clone(),
6865 2 : current_lsn,
6866 2 : &mut ValuesReconstructState::new(),
6867 2 : &ctx,
6868 2 : )
6869 2 : .await?;
6870 2 :
6871 44 : for (key, img_res) in results {
6872 42 : let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
6873 42 : assert_eq!(img_res?, expected);
6874 2 : }
6875 2 :
6876 2 : Ok(())
6877 2 : }
6878 :
6879 : // Test that vectored get descends into ancestor timelines correctly and
6880 : // does not return an image that's newer than requested.
6881 : //
6882 : // The diagram below ilustrates an interesting case. We have a parent timeline
6883 : // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
6884 : // from the child timeline, so the parent timeline must be visited. When advacing into
6885 : // the child timeline, the read path needs to remember what the requested Lsn was in
6886 : // order to avoid returning an image that's too new. The test below constructs such
6887 : // a timeline setup and does a few queries around the Lsn of each page image.
6888 : // ```
6889 : // LSN
6890 : // ^
6891 : // |
6892 : // |
6893 : // 500 | --------------------------------------> branch point
6894 : // 400 | X
6895 : // 300 | X
6896 : // 200 | --------------------------------------> requested lsn
6897 : // 100 | X
6898 : // |---------------------------------------> Key
6899 : // |
6900 : // ------> requested key
6901 : //
6902 : // Legend:
6903 : // * X - page images
6904 : // ```
6905 : #[tokio::test]
6906 2 : async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
6907 2 : let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
6908 2 : let (tenant, ctx) = harness.load().await;
6909 2 :
6910 2 : let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6911 2 : let end_key = start_key.add(1000);
6912 2 : let child_gap_at_key = start_key.add(500);
6913 2 : let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
6914 2 :
6915 2 : let mut current_lsn = Lsn(0x10);
6916 2 :
6917 2 : let timeline_id = TimelineId::generate();
6918 2 : let parent_timeline = tenant
6919 2 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
6920 2 : .await?;
6921 2 :
6922 2 : current_lsn += 0x100;
6923 2 :
6924 8 : for _ in 0..3 {
6925 6 : let mut key = start_key;
6926 6006 : while key < end_key {
6927 6000 : current_lsn += 0x10;
6928 6000 :
6929 6000 : let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
6930 2 :
6931 6000 : let mut writer = parent_timeline.writer().await;
6932 6000 : writer
6933 6000 : .put(
6934 6000 : key,
6935 6000 : current_lsn,
6936 6000 : &Value::Image(test_img(&image_value)),
6937 6000 : &ctx,
6938 6000 : )
6939 6000 : .await?;
6940 6000 : writer.finish_write(current_lsn);
6941 6000 :
6942 6000 : if key == child_gap_at_key {
6943 6 : parent_gap_lsns.insert(current_lsn, image_value);
6944 5994 : }
6945 2 :
6946 6000 : key = key.next();
6947 2 : }
6948 2 :
6949 6 : parent_timeline.freeze_and_flush().await?;
6950 2 : }
6951 2 :
6952 2 : let child_timeline_id = TimelineId::generate();
6953 2 :
6954 2 : let child_timeline = tenant
6955 2 : .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
6956 2 : .await?;
6957 2 :
6958 2 : let mut key = start_key;
6959 2002 : while key < end_key {
6960 2000 : if key == child_gap_at_key {
6961 2 : key = key.next();
6962 2 : continue;
6963 1998 : }
6964 1998 :
6965 1998 : current_lsn += 0x10;
6966 2 :
6967 1998 : let mut writer = child_timeline.writer().await;
6968 1998 : writer
6969 1998 : .put(
6970 1998 : key,
6971 1998 : current_lsn,
6972 1998 : &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
6973 1998 : &ctx,
6974 1998 : )
6975 1998 : .await?;
6976 1998 : writer.finish_write(current_lsn);
6977 1998 :
6978 1998 : key = key.next();
6979 2 : }
6980 2 :
6981 2 : child_timeline.freeze_and_flush().await?;
6982 2 :
6983 2 : let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
6984 2 : let mut query_lsns = Vec::new();
6985 6 : for image_lsn in parent_gap_lsns.keys().rev() {
6986 36 : for offset in lsn_offsets {
6987 30 : query_lsns.push(Lsn(image_lsn
6988 30 : .0
6989 30 : .checked_add_signed(offset)
6990 30 : .expect("Shouldn't overflow")));
6991 30 : }
6992 2 : }
6993 2 :
6994 32 : for query_lsn in query_lsns {
6995 30 : let results = child_timeline
6996 30 : .get_vectored_impl(
6997 30 : KeySpace {
6998 30 : ranges: vec![child_gap_at_key..child_gap_at_key.next()],
6999 30 : },
7000 30 : query_lsn,
7001 30 : &mut ValuesReconstructState::new(),
7002 30 : &ctx,
7003 30 : )
7004 30 : .await;
7005 2 :
7006 30 : let expected_item = parent_gap_lsns
7007 30 : .iter()
7008 30 : .rev()
7009 68 : .find(|(lsn, _)| **lsn <= query_lsn);
7010 30 :
7011 30 : info!(
7012 2 : "Doing vectored read at LSN {}. Expecting image to be: {:?}",
7013 2 : query_lsn, expected_item
7014 2 : );
7015 2 :
7016 30 : match expected_item {
7017 26 : Some((_, img_value)) => {
7018 26 : let key_results = results.expect("No vectored get error expected");
7019 26 : let key_result = &key_results[&child_gap_at_key];
7020 26 : let returned_img = key_result
7021 26 : .as_ref()
7022 26 : .expect("No page reconstruct error expected");
7023 26 :
7024 26 : info!(
7025 2 : "Vectored read at LSN {} returned image {}",
7026 0 : query_lsn,
7027 0 : std::str::from_utf8(returned_img)?
7028 2 : );
7029 26 : assert_eq!(*returned_img, test_img(img_value));
7030 2 : }
7031 2 : None => {
7032 4 : assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
7033 2 : }
7034 2 : }
7035 2 : }
7036 2 :
7037 2 : Ok(())
7038 2 : }
7039 :
7040 : #[tokio::test]
7041 2 : async fn test_random_updates() -> anyhow::Result<()> {
7042 2 : let names_algorithms = [
7043 2 : ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
7044 2 : ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
7045 2 : ];
7046 6 : for (name, algorithm) in names_algorithms {
7047 4 : test_random_updates_algorithm(name, algorithm).await?;
7048 2 : }
7049 2 : Ok(())
7050 2 : }
7051 :
7052 4 : async fn test_random_updates_algorithm(
7053 4 : name: &'static str,
7054 4 : compaction_algorithm: CompactionAlgorithm,
7055 4 : ) -> anyhow::Result<()> {
7056 4 : let mut harness = TenantHarness::create(name).await?;
7057 4 : harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
7058 4 : kind: compaction_algorithm,
7059 4 : };
7060 4 : let (tenant, ctx) = harness.load().await;
7061 4 : let tline = tenant
7062 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7063 4 : .await?;
7064 :
7065 : const NUM_KEYS: usize = 1000;
7066 4 : let cancel = CancellationToken::new();
7067 4 :
7068 4 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7069 4 : let mut test_key_end = test_key;
7070 4 : test_key_end.field6 = NUM_KEYS as u32;
7071 4 : tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
7072 4 :
7073 4 : let mut keyspace = KeySpaceAccum::new();
7074 4 :
7075 4 : // Track when each page was last modified. Used to assert that
7076 4 : // a read sees the latest page version.
7077 4 : let mut updated = [Lsn(0); NUM_KEYS];
7078 4 :
7079 4 : let mut lsn = Lsn(0x10);
7080 : #[allow(clippy::needless_range_loop)]
7081 4004 : for blknum in 0..NUM_KEYS {
7082 4000 : lsn = Lsn(lsn.0 + 0x10);
7083 4000 : test_key.field6 = blknum as u32;
7084 4000 : let mut writer = tline.writer().await;
7085 4000 : writer
7086 4000 : .put(
7087 4000 : test_key,
7088 4000 : lsn,
7089 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7090 4000 : &ctx,
7091 4000 : )
7092 4000 : .await?;
7093 4000 : writer.finish_write(lsn);
7094 4000 : updated[blknum] = lsn;
7095 4000 : drop(writer);
7096 4000 :
7097 4000 : keyspace.add_key(test_key);
7098 : }
7099 :
7100 204 : for _ in 0..50 {
7101 200200 : for _ in 0..NUM_KEYS {
7102 200000 : lsn = Lsn(lsn.0 + 0x10);
7103 200000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7104 200000 : test_key.field6 = blknum as u32;
7105 200000 : let mut writer = tline.writer().await;
7106 200000 : writer
7107 200000 : .put(
7108 200000 : test_key,
7109 200000 : lsn,
7110 200000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7111 200000 : &ctx,
7112 200000 : )
7113 200000 : .await?;
7114 200000 : writer.finish_write(lsn);
7115 200000 : drop(writer);
7116 200000 : updated[blknum] = lsn;
7117 : }
7118 :
7119 : // Read all the blocks
7120 200000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7121 200000 : test_key.field6 = blknum as u32;
7122 200000 : assert_eq!(
7123 200000 : tline.get(test_key, lsn, &ctx).await?,
7124 200000 : test_img(&format!("{} at {}", blknum, last_lsn))
7125 : );
7126 : }
7127 :
7128 : // Perform a cycle of flush, and GC
7129 200 : tline.freeze_and_flush().await?;
7130 200 : tenant
7131 200 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7132 200 : .await?;
7133 : }
7134 :
7135 4 : Ok(())
7136 4 : }
7137 :
7138 : #[tokio::test]
7139 2 : async fn test_traverse_branches() -> anyhow::Result<()> {
7140 2 : let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
7141 2 : .await?
7142 2 : .load()
7143 2 : .await;
7144 2 : let mut tline = tenant
7145 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7146 2 : .await?;
7147 2 :
7148 2 : const NUM_KEYS: usize = 1000;
7149 2 :
7150 2 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7151 2 :
7152 2 : let mut keyspace = KeySpaceAccum::new();
7153 2 :
7154 2 : let cancel = CancellationToken::new();
7155 2 :
7156 2 : // Track when each page was last modified. Used to assert that
7157 2 : // a read sees the latest page version.
7158 2 : let mut updated = [Lsn(0); NUM_KEYS];
7159 2 :
7160 2 : let mut lsn = Lsn(0x10);
7161 2 : #[allow(clippy::needless_range_loop)]
7162 2002 : for blknum in 0..NUM_KEYS {
7163 2000 : lsn = Lsn(lsn.0 + 0x10);
7164 2000 : test_key.field6 = blknum as u32;
7165 2000 : let mut writer = tline.writer().await;
7166 2000 : writer
7167 2000 : .put(
7168 2000 : test_key,
7169 2000 : lsn,
7170 2000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7171 2000 : &ctx,
7172 2000 : )
7173 2000 : .await?;
7174 2000 : writer.finish_write(lsn);
7175 2000 : updated[blknum] = lsn;
7176 2000 : drop(writer);
7177 2000 :
7178 2000 : keyspace.add_key(test_key);
7179 2 : }
7180 2 :
7181 102 : for _ in 0..50 {
7182 100 : let new_tline_id = TimelineId::generate();
7183 100 : tenant
7184 100 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
7185 100 : .await?;
7186 100 : tline = tenant
7187 100 : .get_timeline(new_tline_id, true)
7188 100 : .expect("Should have the branched timeline");
7189 2 :
7190 100100 : for _ in 0..NUM_KEYS {
7191 100000 : lsn = Lsn(lsn.0 + 0x10);
7192 100000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7193 100000 : test_key.field6 = blknum as u32;
7194 100000 : let mut writer = tline.writer().await;
7195 100000 : writer
7196 100000 : .put(
7197 100000 : test_key,
7198 100000 : lsn,
7199 100000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7200 100000 : &ctx,
7201 100000 : )
7202 100000 : .await?;
7203 100000 : println!("updating {} at {}", blknum, lsn);
7204 100000 : writer.finish_write(lsn);
7205 100000 : drop(writer);
7206 100000 : updated[blknum] = lsn;
7207 2 : }
7208 2 :
7209 2 : // Read all the blocks
7210 100000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7211 100000 : test_key.field6 = blknum as u32;
7212 100000 : assert_eq!(
7213 100000 : tline.get(test_key, lsn, &ctx).await?,
7214 100000 : test_img(&format!("{} at {}", blknum, last_lsn))
7215 2 : );
7216 2 : }
7217 2 :
7218 2 : // Perform a cycle of flush, compact, and GC
7219 100 : tline.freeze_and_flush().await?;
7220 100 : tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
7221 100 : tenant
7222 100 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7223 100 : .await?;
7224 2 : }
7225 2 :
7226 2 : Ok(())
7227 2 : }
7228 :
7229 : #[tokio::test]
7230 2 : async fn test_traverse_ancestors() -> anyhow::Result<()> {
7231 2 : let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
7232 2 : .await?
7233 2 : .load()
7234 2 : .await;
7235 2 : let mut tline = tenant
7236 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7237 2 : .await?;
7238 2 :
7239 2 : const NUM_KEYS: usize = 100;
7240 2 : const NUM_TLINES: usize = 50;
7241 2 :
7242 2 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7243 2 : // Track page mutation lsns across different timelines.
7244 2 : let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
7245 2 :
7246 2 : let mut lsn = Lsn(0x10);
7247 2 :
7248 2 : #[allow(clippy::needless_range_loop)]
7249 102 : for idx in 0..NUM_TLINES {
7250 100 : let new_tline_id = TimelineId::generate();
7251 100 : tenant
7252 100 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
7253 100 : .await?;
7254 100 : tline = tenant
7255 100 : .get_timeline(new_tline_id, true)
7256 100 : .expect("Should have the branched timeline");
7257 2 :
7258 10100 : for _ in 0..NUM_KEYS {
7259 10000 : lsn = Lsn(lsn.0 + 0x10);
7260 10000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7261 10000 : test_key.field6 = blknum as u32;
7262 10000 : let mut writer = tline.writer().await;
7263 10000 : writer
7264 10000 : .put(
7265 10000 : test_key,
7266 10000 : lsn,
7267 10000 : &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
7268 10000 : &ctx,
7269 10000 : )
7270 10000 : .await?;
7271 10000 : println!("updating [{}][{}] at {}", idx, blknum, lsn);
7272 10000 : writer.finish_write(lsn);
7273 10000 : drop(writer);
7274 10000 : updated[idx][blknum] = lsn;
7275 2 : }
7276 2 : }
7277 2 :
7278 2 : // Read pages from leaf timeline across all ancestors.
7279 100 : for (idx, lsns) in updated.iter().enumerate() {
7280 10000 : for (blknum, lsn) in lsns.iter().enumerate() {
7281 2 : // Skip empty mutations.
7282 10000 : if lsn.0 == 0 {
7283 3683 : continue;
7284 6317 : }
7285 6317 : println!("checking [{idx}][{blknum}] at {lsn}");
7286 6317 : test_key.field6 = blknum as u32;
7287 6317 : assert_eq!(
7288 6317 : tline.get(test_key, *lsn, &ctx).await?,
7289 6317 : test_img(&format!("{idx} {blknum} at {lsn}"))
7290 2 : );
7291 2 : }
7292 2 : }
7293 2 : Ok(())
7294 2 : }
7295 :
7296 : #[tokio::test]
7297 2 : async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
7298 2 : let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
7299 2 : .await?
7300 2 : .load()
7301 2 : .await;
7302 2 :
7303 2 : let initdb_lsn = Lsn(0x20);
7304 2 : let utline = tenant
7305 2 : .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
7306 2 : .await?;
7307 2 : let tline = utline.raw_timeline().unwrap();
7308 2 :
7309 2 : // Spawn flush loop now so that we can set the `expect_initdb_optimization`
7310 2 : tline.maybe_spawn_flush_loop();
7311 2 :
7312 2 : // Make sure the timeline has the minimum set of required keys for operation.
7313 2 : // The only operation you can always do on an empty timeline is to `put` new data.
7314 2 : // Except if you `put` at `initdb_lsn`.
7315 2 : // In that case, there's an optimization to directly create image layers instead of delta layers.
7316 2 : // It uses `repartition()`, which assumes some keys to be present.
7317 2 : // Let's make sure the test timeline can handle that case.
7318 2 : {
7319 2 : let mut state = tline.flush_loop_state.lock().unwrap();
7320 2 : assert_eq!(
7321 2 : timeline::FlushLoopState::Running {
7322 2 : expect_initdb_optimization: false,
7323 2 : initdb_optimization_count: 0,
7324 2 : },
7325 2 : *state
7326 2 : );
7327 2 : *state = timeline::FlushLoopState::Running {
7328 2 : expect_initdb_optimization: true,
7329 2 : initdb_optimization_count: 0,
7330 2 : };
7331 2 : }
7332 2 :
7333 2 : // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
7334 2 : // As explained above, the optimization requires some keys to be present.
7335 2 : // As per `create_empty_timeline` documentation, use init_empty to set them.
7336 2 : // This is what `create_test_timeline` does, by the way.
7337 2 : let mut modification = tline.begin_modification(initdb_lsn);
7338 2 : modification
7339 2 : .init_empty_test_timeline()
7340 2 : .context("init_empty_test_timeline")?;
7341 2 : modification
7342 2 : .commit(&ctx)
7343 2 : .await
7344 2 : .context("commit init_empty_test_timeline modification")?;
7345 2 :
7346 2 : // Do the flush. The flush code will check the expectations that we set above.
7347 2 : tline.freeze_and_flush().await?;
7348 2 :
7349 2 : // assert freeze_and_flush exercised the initdb optimization
7350 2 : {
7351 2 : let state = tline.flush_loop_state.lock().unwrap();
7352 2 : let timeline::FlushLoopState::Running {
7353 2 : expect_initdb_optimization,
7354 2 : initdb_optimization_count,
7355 2 : } = *state
7356 2 : else {
7357 2 : panic!("unexpected state: {:?}", *state);
7358 2 : };
7359 2 : assert!(expect_initdb_optimization);
7360 2 : assert!(initdb_optimization_count > 0);
7361 2 : }
7362 2 : Ok(())
7363 2 : }
7364 :
7365 : #[tokio::test]
7366 2 : async fn test_create_guard_crash() -> anyhow::Result<()> {
7367 2 : let name = "test_create_guard_crash";
7368 2 : let harness = TenantHarness::create(name).await?;
7369 2 : {
7370 2 : let (tenant, ctx) = harness.load().await;
7371 2 : let tline = tenant
7372 2 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
7373 2 : .await?;
7374 2 : // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
7375 2 : let raw_tline = tline.raw_timeline().unwrap();
7376 2 : raw_tline
7377 2 : .shutdown(super::timeline::ShutdownMode::Hard)
7378 2 : .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))
7379 2 : .await;
7380 2 : std::mem::forget(tline);
7381 2 : }
7382 2 :
7383 2 : let (tenant, _) = harness.load().await;
7384 2 : match tenant.get_timeline(TIMELINE_ID, false) {
7385 2 : Ok(_) => panic!("timeline should've been removed during load"),
7386 2 : Err(e) => {
7387 2 : assert_eq!(
7388 2 : e,
7389 2 : GetTimelineError::NotFound {
7390 2 : tenant_id: tenant.tenant_shard_id,
7391 2 : timeline_id: TIMELINE_ID,
7392 2 : }
7393 2 : )
7394 2 : }
7395 2 : }
7396 2 :
7397 2 : assert!(!harness
7398 2 : .conf
7399 2 : .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
7400 2 : .exists());
7401 2 :
7402 2 : Ok(())
7403 2 : }
7404 :
7405 : #[tokio::test]
7406 2 : async fn test_read_at_max_lsn() -> anyhow::Result<()> {
7407 2 : let names_algorithms = [
7408 2 : ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
7409 2 : ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
7410 2 : ];
7411 6 : for (name, algorithm) in names_algorithms {
7412 4 : test_read_at_max_lsn_algorithm(name, algorithm).await?;
7413 2 : }
7414 2 : Ok(())
7415 2 : }
7416 :
7417 4 : async fn test_read_at_max_lsn_algorithm(
7418 4 : name: &'static str,
7419 4 : compaction_algorithm: CompactionAlgorithm,
7420 4 : ) -> anyhow::Result<()> {
7421 4 : let mut harness = TenantHarness::create(name).await?;
7422 4 : harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
7423 4 : kind: compaction_algorithm,
7424 4 : };
7425 4 : let (tenant, ctx) = harness.load().await;
7426 4 : let tline = tenant
7427 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
7428 4 : .await?;
7429 :
7430 4 : let lsn = Lsn(0x10);
7431 4 : let compact = false;
7432 4 : bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
7433 :
7434 4 : let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7435 4 : let read_lsn = Lsn(u64::MAX - 1);
7436 :
7437 4 : let result = tline.get(test_key, read_lsn, &ctx).await;
7438 4 : assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
7439 :
7440 4 : Ok(())
7441 4 : }
7442 :
7443 : #[tokio::test]
7444 2 : async fn test_metadata_scan() -> anyhow::Result<()> {
7445 2 : let harness = TenantHarness::create("test_metadata_scan").await?;
7446 2 : let (tenant, ctx) = harness.load().await;
7447 2 : let tline = tenant
7448 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7449 2 : .await?;
7450 2 :
7451 2 : const NUM_KEYS: usize = 1000;
7452 2 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
7453 2 :
7454 2 : let cancel = CancellationToken::new();
7455 2 :
7456 2 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7457 2 : base_key.field1 = AUX_KEY_PREFIX;
7458 2 : let mut test_key = base_key;
7459 2 :
7460 2 : // Track when each page was last modified. Used to assert that
7461 2 : // a read sees the latest page version.
7462 2 : let mut updated = [Lsn(0); NUM_KEYS];
7463 2 :
7464 2 : let mut lsn = Lsn(0x10);
7465 2 : #[allow(clippy::needless_range_loop)]
7466 2002 : for blknum in 0..NUM_KEYS {
7467 2000 : lsn = Lsn(lsn.0 + 0x10);
7468 2000 : test_key.field6 = (blknum * STEP) as u32;
7469 2000 : let mut writer = tline.writer().await;
7470 2000 : writer
7471 2000 : .put(
7472 2000 : test_key,
7473 2000 : lsn,
7474 2000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7475 2000 : &ctx,
7476 2000 : )
7477 2000 : .await?;
7478 2000 : writer.finish_write(lsn);
7479 2000 : updated[blknum] = lsn;
7480 2000 : drop(writer);
7481 2 : }
7482 2 :
7483 2 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
7484 2 :
7485 24 : for iter in 0..=10 {
7486 2 : // Read all the blocks
7487 22000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7488 22000 : test_key.field6 = (blknum * STEP) as u32;
7489 22000 : assert_eq!(
7490 22000 : tline.get(test_key, lsn, &ctx).await?,
7491 22000 : test_img(&format!("{} at {}", blknum, last_lsn))
7492 2 : );
7493 2 : }
7494 2 :
7495 22 : let mut cnt = 0;
7496 22000 : for (key, value) in tline
7497 22 : .get_vectored_impl(
7498 22 : keyspace.clone(),
7499 22 : lsn,
7500 22 : &mut ValuesReconstructState::default(),
7501 22 : &ctx,
7502 22 : )
7503 22 : .await?
7504 2 : {
7505 22000 : let blknum = key.field6 as usize;
7506 22000 : let value = value?;
7507 22000 : assert!(blknum % STEP == 0);
7508 22000 : let blknum = blknum / STEP;
7509 22000 : assert_eq!(
7510 22000 : value,
7511 22000 : test_img(&format!("{} at {}", blknum, updated[blknum]))
7512 22000 : );
7513 22000 : cnt += 1;
7514 2 : }
7515 2 :
7516 22 : assert_eq!(cnt, NUM_KEYS);
7517 2 :
7518 22022 : for _ in 0..NUM_KEYS {
7519 22000 : lsn = Lsn(lsn.0 + 0x10);
7520 22000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7521 22000 : test_key.field6 = (blknum * STEP) as u32;
7522 22000 : let mut writer = tline.writer().await;
7523 22000 : writer
7524 22000 : .put(
7525 22000 : test_key,
7526 22000 : lsn,
7527 22000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7528 22000 : &ctx,
7529 22000 : )
7530 22000 : .await?;
7531 22000 : writer.finish_write(lsn);
7532 22000 : drop(writer);
7533 22000 : updated[blknum] = lsn;
7534 2 : }
7535 2 :
7536 2 : // Perform two cycles of flush, compact, and GC
7537 66 : for round in 0..2 {
7538 44 : tline.freeze_and_flush().await?;
7539 44 : tline
7540 44 : .compact(
7541 44 : &cancel,
7542 44 : if iter % 5 == 0 && round == 0 {
7543 6 : let mut flags = EnumSet::new();
7544 6 : flags.insert(CompactFlags::ForceImageLayerCreation);
7545 6 : flags.insert(CompactFlags::ForceRepartition);
7546 6 : flags
7547 2 : } else {
7548 38 : EnumSet::empty()
7549 2 : },
7550 44 : &ctx,
7551 44 : )
7552 44 : .await?;
7553 44 : tenant
7554 44 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7555 44 : .await?;
7556 2 : }
7557 2 : }
7558 2 :
7559 2 : Ok(())
7560 2 : }
7561 :
7562 : #[tokio::test]
7563 2 : async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
7564 2 : let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
7565 2 : let (tenant, ctx) = harness.load().await;
7566 2 : let tline = tenant
7567 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7568 2 : .await?;
7569 2 :
7570 2 : let cancel = CancellationToken::new();
7571 2 :
7572 2 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7573 2 : base_key.field1 = AUX_KEY_PREFIX;
7574 2 : let test_key = base_key;
7575 2 : let mut lsn = Lsn(0x10);
7576 2 :
7577 42 : for _ in 0..20 {
7578 40 : lsn = Lsn(lsn.0 + 0x10);
7579 40 : let mut writer = tline.writer().await;
7580 40 : writer
7581 40 : .put(
7582 40 : test_key,
7583 40 : lsn,
7584 40 : &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
7585 40 : &ctx,
7586 40 : )
7587 40 : .await?;
7588 40 : writer.finish_write(lsn);
7589 40 : drop(writer);
7590 40 : tline.freeze_and_flush().await?; // force create a delta layer
7591 2 : }
7592 2 :
7593 2 : let before_num_l0_delta_files =
7594 2 : tline.layers.read().await.layer_map()?.level0_deltas().len();
7595 2 :
7596 2 : tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
7597 2 :
7598 2 : let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
7599 2 :
7600 2 : 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}");
7601 2 :
7602 2 : assert_eq!(
7603 2 : tline.get(test_key, lsn, &ctx).await?,
7604 2 : test_img(&format!("{} at {}", 0, lsn))
7605 2 : );
7606 2 :
7607 2 : Ok(())
7608 2 : }
7609 :
7610 : #[tokio::test]
7611 2 : async fn test_aux_file_e2e() {
7612 2 : let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
7613 2 :
7614 2 : let (tenant, ctx) = harness.load().await;
7615 2 :
7616 2 : let mut lsn = Lsn(0x08);
7617 2 :
7618 2 : let tline: Arc<Timeline> = tenant
7619 2 : .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
7620 2 : .await
7621 2 : .unwrap();
7622 2 :
7623 2 : {
7624 2 : lsn += 8;
7625 2 : let mut modification = tline.begin_modification(lsn);
7626 2 : modification
7627 2 : .put_file("pg_logical/mappings/test1", b"first", &ctx)
7628 2 : .await
7629 2 : .unwrap();
7630 2 : modification.commit(&ctx).await.unwrap();
7631 2 : }
7632 2 :
7633 2 : // we can read everything from the storage
7634 2 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
7635 2 : assert_eq!(
7636 2 : files.get("pg_logical/mappings/test1"),
7637 2 : Some(&bytes::Bytes::from_static(b"first"))
7638 2 : );
7639 2 :
7640 2 : {
7641 2 : lsn += 8;
7642 2 : let mut modification = tline.begin_modification(lsn);
7643 2 : modification
7644 2 : .put_file("pg_logical/mappings/test2", b"second", &ctx)
7645 2 : .await
7646 2 : .unwrap();
7647 2 : modification.commit(&ctx).await.unwrap();
7648 2 : }
7649 2 :
7650 2 : let files = tline.list_aux_files(lsn, &ctx).await.unwrap();
7651 2 : assert_eq!(
7652 2 : files.get("pg_logical/mappings/test2"),
7653 2 : Some(&bytes::Bytes::from_static(b"second"))
7654 2 : );
7655 2 :
7656 2 : let child = tenant
7657 2 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
7658 2 : .await
7659 2 : .unwrap();
7660 2 :
7661 2 : let files = child.list_aux_files(lsn, &ctx).await.unwrap();
7662 2 : assert_eq!(files.get("pg_logical/mappings/test1"), None);
7663 2 : assert_eq!(files.get("pg_logical/mappings/test2"), None);
7664 2 : }
7665 :
7666 : #[tokio::test]
7667 2 : async fn test_metadata_image_creation() -> anyhow::Result<()> {
7668 2 : let harness = TenantHarness::create("test_metadata_image_creation").await?;
7669 2 : let (tenant, ctx) = harness.load().await;
7670 2 : let tline = tenant
7671 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7672 2 : .await?;
7673 2 :
7674 2 : const NUM_KEYS: usize = 1000;
7675 2 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
7676 2 :
7677 2 : let cancel = CancellationToken::new();
7678 2 :
7679 2 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
7680 2 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
7681 2 : let mut test_key = base_key;
7682 2 : let mut lsn = Lsn(0x10);
7683 2 :
7684 8 : async fn scan_with_statistics(
7685 8 : tline: &Timeline,
7686 8 : keyspace: &KeySpace,
7687 8 : lsn: Lsn,
7688 8 : ctx: &RequestContext,
7689 8 : ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
7690 8 : let mut reconstruct_state = ValuesReconstructState::default();
7691 8 : let res = tline
7692 8 : .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
7693 8 : .await?;
7694 8 : Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
7695 8 : }
7696 2 :
7697 2 : #[allow(clippy::needless_range_loop)]
7698 2002 : for blknum in 0..NUM_KEYS {
7699 2000 : lsn = Lsn(lsn.0 + 0x10);
7700 2000 : test_key.field6 = (blknum * STEP) as u32;
7701 2000 : let mut writer = tline.writer().await;
7702 2000 : writer
7703 2000 : .put(
7704 2000 : test_key,
7705 2000 : lsn,
7706 2000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7707 2000 : &ctx,
7708 2000 : )
7709 2000 : .await?;
7710 2000 : writer.finish_write(lsn);
7711 2000 : drop(writer);
7712 2 : }
7713 2 :
7714 2 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
7715 2 :
7716 22 : for iter in 1..=10 {
7717 20020 : for _ in 0..NUM_KEYS {
7718 20000 : lsn = Lsn(lsn.0 + 0x10);
7719 20000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7720 20000 : test_key.field6 = (blknum * STEP) as u32;
7721 20000 : let mut writer = tline.writer().await;
7722 20000 : writer
7723 20000 : .put(
7724 20000 : test_key,
7725 20000 : lsn,
7726 20000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7727 20000 : &ctx,
7728 20000 : )
7729 20000 : .await?;
7730 20000 : writer.finish_write(lsn);
7731 20000 : drop(writer);
7732 2 : }
7733 2 :
7734 20 : tline.freeze_and_flush().await?;
7735 2 :
7736 20 : if iter % 5 == 0 {
7737 4 : let (_, before_delta_file_accessed) =
7738 4 : scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
7739 4 : tline
7740 4 : .compact(
7741 4 : &cancel,
7742 4 : {
7743 4 : let mut flags = EnumSet::new();
7744 4 : flags.insert(CompactFlags::ForceImageLayerCreation);
7745 4 : flags.insert(CompactFlags::ForceRepartition);
7746 4 : flags
7747 4 : },
7748 4 : &ctx,
7749 4 : )
7750 4 : .await?;
7751 4 : let (_, after_delta_file_accessed) =
7752 4 : scan_with_statistics(&tline, &keyspace, lsn, &ctx).await?;
7753 4 : 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}");
7754 2 : // 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.
7755 4 : assert!(
7756 4 : after_delta_file_accessed <= 2,
7757 2 : "after_delta_file_accessed={after_delta_file_accessed}"
7758 2 : );
7759 16 : }
7760 2 : }
7761 2 :
7762 2 : Ok(())
7763 2 : }
7764 :
7765 : #[tokio::test]
7766 2 : async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
7767 2 : let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
7768 2 : let (tenant, ctx) = harness.load().await;
7769 2 :
7770 2 : let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7771 2 : let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
7772 2 : let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
7773 2 :
7774 2 : let tline = tenant
7775 2 : .create_test_timeline_with_layers(
7776 2 : TIMELINE_ID,
7777 2 : Lsn(0x10),
7778 2 : DEFAULT_PG_VERSION,
7779 2 : &ctx,
7780 2 : Vec::new(), // delta layers
7781 2 : vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
7782 2 : 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
7783 2 : )
7784 2 : .await?;
7785 2 : tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
7786 2 :
7787 2 : let child = tenant
7788 2 : .branch_timeline_test_with_layers(
7789 2 : &tline,
7790 2 : NEW_TIMELINE_ID,
7791 2 : Some(Lsn(0x20)),
7792 2 : &ctx,
7793 2 : Vec::new(), // delta layers
7794 2 : vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
7795 2 : Lsn(0x30),
7796 2 : )
7797 2 : .await
7798 2 : .unwrap();
7799 2 :
7800 2 : let lsn = Lsn(0x30);
7801 2 :
7802 2 : // test vectored get on parent timeline
7803 2 : assert_eq!(
7804 2 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
7805 2 : Some(test_img("data key 1"))
7806 2 : );
7807 2 : assert!(get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
7808 2 : .await
7809 2 : .unwrap_err()
7810 2 : .is_missing_key_error());
7811 2 : assert!(
7812 2 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
7813 2 : .await
7814 2 : .unwrap_err()
7815 2 : .is_missing_key_error()
7816 2 : );
7817 2 :
7818 2 : // test vectored get on child timeline
7819 2 : assert_eq!(
7820 2 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
7821 2 : Some(test_img("data key 1"))
7822 2 : );
7823 2 : assert_eq!(
7824 2 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
7825 2 : Some(test_img("data key 2"))
7826 2 : );
7827 2 : assert!(
7828 2 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
7829 2 : .await
7830 2 : .unwrap_err()
7831 2 : .is_missing_key_error()
7832 2 : );
7833 2 :
7834 2 : Ok(())
7835 2 : }
7836 :
7837 : #[tokio::test]
7838 2 : async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
7839 2 : let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
7840 2 : let (tenant, ctx) = harness.load().await;
7841 2 :
7842 2 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
7843 2 : let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
7844 2 : let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
7845 2 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
7846 2 :
7847 2 : let tline = tenant
7848 2 : .create_test_timeline_with_layers(
7849 2 : TIMELINE_ID,
7850 2 : Lsn(0x10),
7851 2 : DEFAULT_PG_VERSION,
7852 2 : &ctx,
7853 2 : Vec::new(), // delta layers
7854 2 : vec![(Lsn(0x20), vec![(base_key, test_img("metadata key 1"))])], // image layers
7855 2 : 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
7856 2 : )
7857 2 : .await?;
7858 2 :
7859 2 : let child = tenant
7860 2 : .branch_timeline_test_with_layers(
7861 2 : &tline,
7862 2 : NEW_TIMELINE_ID,
7863 2 : Some(Lsn(0x20)),
7864 2 : &ctx,
7865 2 : Vec::new(), // delta layers
7866 2 : vec![(
7867 2 : Lsn(0x30),
7868 2 : vec![(base_key_child, test_img("metadata key 2"))],
7869 2 : )], // image layers
7870 2 : Lsn(0x30),
7871 2 : )
7872 2 : .await
7873 2 : .unwrap();
7874 2 :
7875 2 : let lsn = Lsn(0x30);
7876 2 :
7877 2 : // test vectored get on parent timeline
7878 2 : assert_eq!(
7879 2 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
7880 2 : Some(test_img("metadata key 1"))
7881 2 : );
7882 2 : assert_eq!(
7883 2 : get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
7884 2 : None
7885 2 : );
7886 2 : assert_eq!(
7887 2 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
7888 2 : None
7889 2 : );
7890 2 :
7891 2 : // test vectored get on child timeline
7892 2 : assert_eq!(
7893 2 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
7894 2 : None
7895 2 : );
7896 2 : assert_eq!(
7897 2 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
7898 2 : Some(test_img("metadata key 2"))
7899 2 : );
7900 2 : assert_eq!(
7901 2 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
7902 2 : None
7903 2 : );
7904 2 :
7905 2 : Ok(())
7906 2 : }
7907 :
7908 36 : async fn get_vectored_impl_wrapper(
7909 36 : tline: &Arc<Timeline>,
7910 36 : key: Key,
7911 36 : lsn: Lsn,
7912 36 : ctx: &RequestContext,
7913 36 : ) -> Result<Option<Bytes>, GetVectoredError> {
7914 36 : let mut reconstruct_state = ValuesReconstructState::new();
7915 36 : let mut res = tline
7916 36 : .get_vectored_impl(
7917 36 : KeySpace::single(key..key.next()),
7918 36 : lsn,
7919 36 : &mut reconstruct_state,
7920 36 : ctx,
7921 36 : )
7922 36 : .await?;
7923 30 : Ok(res.pop_last().map(|(k, v)| {
7924 18 : assert_eq!(k, key);
7925 18 : v.unwrap()
7926 30 : }))
7927 36 : }
7928 :
7929 : #[tokio::test]
7930 2 : async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
7931 2 : let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
7932 2 : let (tenant, ctx) = harness.load().await;
7933 2 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
7934 2 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
7935 2 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
7936 2 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
7937 2 :
7938 2 : // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
7939 2 : // Lsn 0x30 key0, key3, no key1+key2
7940 2 : // Lsn 0x20 key1+key2 tomestones
7941 2 : // Lsn 0x10 key1 in image, key2 in delta
7942 2 : let tline = tenant
7943 2 : .create_test_timeline_with_layers(
7944 2 : TIMELINE_ID,
7945 2 : Lsn(0x10),
7946 2 : DEFAULT_PG_VERSION,
7947 2 : &ctx,
7948 2 : // delta layers
7949 2 : vec![
7950 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
7951 2 : Lsn(0x10)..Lsn(0x20),
7952 2 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
7953 2 : ),
7954 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
7955 2 : Lsn(0x20)..Lsn(0x30),
7956 2 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
7957 2 : ),
7958 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
7959 2 : Lsn(0x20)..Lsn(0x30),
7960 2 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
7961 2 : ),
7962 2 : ],
7963 2 : // image layers
7964 2 : vec![
7965 2 : (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
7966 2 : (
7967 2 : Lsn(0x30),
7968 2 : vec![
7969 2 : (key0, test_img("metadata key 0")),
7970 2 : (key3, test_img("metadata key 3")),
7971 2 : ],
7972 2 : ),
7973 2 : ],
7974 2 : Lsn(0x30),
7975 2 : )
7976 2 : .await?;
7977 2 :
7978 2 : let lsn = Lsn(0x30);
7979 2 : let old_lsn = Lsn(0x20);
7980 2 :
7981 2 : assert_eq!(
7982 2 : get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
7983 2 : Some(test_img("metadata key 0"))
7984 2 : );
7985 2 : assert_eq!(
7986 2 : get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
7987 2 : None,
7988 2 : );
7989 2 : assert_eq!(
7990 2 : get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
7991 2 : None,
7992 2 : );
7993 2 : assert_eq!(
7994 2 : get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
7995 2 : Some(Bytes::new()),
7996 2 : );
7997 2 : assert_eq!(
7998 2 : get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
7999 2 : Some(Bytes::new()),
8000 2 : );
8001 2 : assert_eq!(
8002 2 : get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
8003 2 : Some(test_img("metadata key 3"))
8004 2 : );
8005 2 :
8006 2 : Ok(())
8007 2 : }
8008 :
8009 : #[tokio::test]
8010 2 : async fn test_metadata_tombstone_image_creation() {
8011 2 : let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
8012 2 : .await
8013 2 : .unwrap();
8014 2 : let (tenant, ctx) = harness.load().await;
8015 2 :
8016 2 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
8017 2 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8018 2 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8019 2 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
8020 2 :
8021 2 : let tline = tenant
8022 2 : .create_test_timeline_with_layers(
8023 2 : TIMELINE_ID,
8024 2 : Lsn(0x10),
8025 2 : DEFAULT_PG_VERSION,
8026 2 : &ctx,
8027 2 : // delta layers
8028 2 : vec![
8029 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
8030 2 : Lsn(0x10)..Lsn(0x20),
8031 2 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8032 2 : ),
8033 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
8034 2 : Lsn(0x20)..Lsn(0x30),
8035 2 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8036 2 : ),
8037 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
8038 2 : Lsn(0x20)..Lsn(0x30),
8039 2 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8040 2 : ),
8041 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
8042 2 : Lsn(0x30)..Lsn(0x40),
8043 2 : vec![
8044 2 : (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
8045 2 : (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
8046 2 : ],
8047 2 : ),
8048 2 : ],
8049 2 : // image layers
8050 2 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
8051 2 : Lsn(0x40),
8052 2 : )
8053 2 : .await
8054 2 : .unwrap();
8055 2 :
8056 2 : let cancel = CancellationToken::new();
8057 2 :
8058 2 : tline
8059 2 : .compact(
8060 2 : &cancel,
8061 2 : {
8062 2 : let mut flags = EnumSet::new();
8063 2 : flags.insert(CompactFlags::ForceImageLayerCreation);
8064 2 : flags.insert(CompactFlags::ForceRepartition);
8065 2 : flags
8066 2 : },
8067 2 : &ctx,
8068 2 : )
8069 2 : .await
8070 2 : .unwrap();
8071 2 :
8072 2 : // Image layers are created at last_record_lsn
8073 2 : let images = tline
8074 2 : .inspect_image_layers(Lsn(0x40), &ctx)
8075 2 : .await
8076 2 : .unwrap()
8077 2 : .into_iter()
8078 18 : .filter(|(k, _)| k.is_metadata_key())
8079 2 : .collect::<Vec<_>>();
8080 2 : assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
8081 2 : }
8082 :
8083 : #[tokio::test]
8084 2 : async fn test_metadata_tombstone_empty_image_creation() {
8085 2 : let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
8086 2 : .await
8087 2 : .unwrap();
8088 2 : let (tenant, ctx) = harness.load().await;
8089 2 :
8090 2 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8091 2 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8092 2 :
8093 2 : let tline = tenant
8094 2 : .create_test_timeline_with_layers(
8095 2 : TIMELINE_ID,
8096 2 : Lsn(0x10),
8097 2 : DEFAULT_PG_VERSION,
8098 2 : &ctx,
8099 2 : // delta layers
8100 2 : vec![
8101 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
8102 2 : Lsn(0x10)..Lsn(0x20),
8103 2 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8104 2 : ),
8105 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
8106 2 : Lsn(0x20)..Lsn(0x30),
8107 2 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8108 2 : ),
8109 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
8110 2 : Lsn(0x20)..Lsn(0x30),
8111 2 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8112 2 : ),
8113 2 : ],
8114 2 : // image layers
8115 2 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
8116 2 : Lsn(0x30),
8117 2 : )
8118 2 : .await
8119 2 : .unwrap();
8120 2 :
8121 2 : let cancel = CancellationToken::new();
8122 2 :
8123 2 : tline
8124 2 : .compact(
8125 2 : &cancel,
8126 2 : {
8127 2 : let mut flags = EnumSet::new();
8128 2 : flags.insert(CompactFlags::ForceImageLayerCreation);
8129 2 : flags.insert(CompactFlags::ForceRepartition);
8130 2 : flags
8131 2 : },
8132 2 : &ctx,
8133 2 : )
8134 2 : .await
8135 2 : .unwrap();
8136 2 :
8137 2 : // Image layers are created at last_record_lsn
8138 2 : let images = tline
8139 2 : .inspect_image_layers(Lsn(0x30), &ctx)
8140 2 : .await
8141 2 : .unwrap()
8142 2 : .into_iter()
8143 14 : .filter(|(k, _)| k.is_metadata_key())
8144 2 : .collect::<Vec<_>>();
8145 2 : assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
8146 2 : }
8147 :
8148 : #[tokio::test]
8149 2 : async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
8150 2 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
8151 2 : let (tenant, ctx) = harness.load().await;
8152 2 :
8153 102 : fn get_key(id: u32) -> Key {
8154 102 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8155 102 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8156 102 : key.field6 = id;
8157 102 : key
8158 102 : }
8159 2 :
8160 2 : // We create
8161 2 : // - one bottom-most image layer,
8162 2 : // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
8163 2 : // - a delta layer D2 crossing the GC horizon with data only below the horizon,
8164 2 : // - a delta layer D3 above the horizon.
8165 2 : //
8166 2 : // | D3 |
8167 2 : // | D1 |
8168 2 : // -| |-- gc horizon -----------------
8169 2 : // | | | D2 |
8170 2 : // --------- img layer ------------------
8171 2 : //
8172 2 : // What we should expact from this compaction is:
8173 2 : // | D3 |
8174 2 : // | Part of D1 |
8175 2 : // --------- img layer with D1+D2 at GC horizon------------------
8176 2 :
8177 2 : // img layer at 0x10
8178 2 : let img_layer = (0..10)
8179 20 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
8180 2 : .collect_vec();
8181 2 :
8182 2 : let delta1 = vec![
8183 2 : (
8184 2 : get_key(1),
8185 2 : Lsn(0x20),
8186 2 : Value::Image(Bytes::from("value 1@0x20")),
8187 2 : ),
8188 2 : (
8189 2 : get_key(2),
8190 2 : Lsn(0x30),
8191 2 : Value::Image(Bytes::from("value 2@0x30")),
8192 2 : ),
8193 2 : (
8194 2 : get_key(3),
8195 2 : Lsn(0x40),
8196 2 : Value::Image(Bytes::from("value 3@0x40")),
8197 2 : ),
8198 2 : ];
8199 2 : let delta2 = vec![
8200 2 : (
8201 2 : get_key(5),
8202 2 : Lsn(0x20),
8203 2 : Value::Image(Bytes::from("value 5@0x20")),
8204 2 : ),
8205 2 : (
8206 2 : get_key(6),
8207 2 : Lsn(0x20),
8208 2 : Value::Image(Bytes::from("value 6@0x20")),
8209 2 : ),
8210 2 : ];
8211 2 : let delta3 = vec![
8212 2 : (
8213 2 : get_key(8),
8214 2 : Lsn(0x48),
8215 2 : Value::Image(Bytes::from("value 8@0x48")),
8216 2 : ),
8217 2 : (
8218 2 : get_key(9),
8219 2 : Lsn(0x48),
8220 2 : Value::Image(Bytes::from("value 9@0x48")),
8221 2 : ),
8222 2 : ];
8223 2 :
8224 2 : let tline = tenant
8225 2 : .create_test_timeline_with_layers(
8226 2 : TIMELINE_ID,
8227 2 : Lsn(0x10),
8228 2 : DEFAULT_PG_VERSION,
8229 2 : &ctx,
8230 2 : vec![
8231 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
8232 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
8233 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
8234 2 : ], // delta layers
8235 2 : vec![(Lsn(0x10), img_layer)], // image layers
8236 2 : Lsn(0x50),
8237 2 : )
8238 2 : .await?;
8239 2 : {
8240 2 : tline
8241 2 : .latest_gc_cutoff_lsn
8242 2 : .lock_for_write()
8243 2 : .store_and_unlock(Lsn(0x30))
8244 2 : .wait()
8245 2 : .await;
8246 2 : // Update GC info
8247 2 : let mut guard = tline.gc_info.write().unwrap();
8248 2 : guard.cutoffs.time = Lsn(0x30);
8249 2 : guard.cutoffs.space = Lsn(0x30);
8250 2 : }
8251 2 :
8252 2 : let expected_result = [
8253 2 : Bytes::from_static(b"value 0@0x10"),
8254 2 : Bytes::from_static(b"value 1@0x20"),
8255 2 : Bytes::from_static(b"value 2@0x30"),
8256 2 : Bytes::from_static(b"value 3@0x40"),
8257 2 : Bytes::from_static(b"value 4@0x10"),
8258 2 : Bytes::from_static(b"value 5@0x20"),
8259 2 : Bytes::from_static(b"value 6@0x20"),
8260 2 : Bytes::from_static(b"value 7@0x10"),
8261 2 : Bytes::from_static(b"value 8@0x48"),
8262 2 : Bytes::from_static(b"value 9@0x48"),
8263 2 : ];
8264 2 :
8265 20 : for (idx, expected) in expected_result.iter().enumerate() {
8266 20 : assert_eq!(
8267 20 : tline
8268 20 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8269 20 : .await
8270 20 : .unwrap(),
8271 2 : expected
8272 2 : );
8273 2 : }
8274 2 :
8275 2 : let cancel = CancellationToken::new();
8276 2 : tline
8277 2 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8278 2 : .await
8279 2 : .unwrap();
8280 2 :
8281 20 : for (idx, expected) in expected_result.iter().enumerate() {
8282 20 : assert_eq!(
8283 20 : tline
8284 20 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8285 20 : .await
8286 20 : .unwrap(),
8287 2 : expected
8288 2 : );
8289 2 : }
8290 2 :
8291 2 : // Check if the image layer at the GC horizon contains exactly what we want
8292 2 : let image_at_gc_horizon = tline
8293 2 : .inspect_image_layers(Lsn(0x30), &ctx)
8294 2 : .await
8295 2 : .unwrap()
8296 2 : .into_iter()
8297 34 : .filter(|(k, _)| k.is_metadata_key())
8298 2 : .collect::<Vec<_>>();
8299 2 :
8300 2 : assert_eq!(image_at_gc_horizon.len(), 10);
8301 2 : let expected_result = [
8302 2 : Bytes::from_static(b"value 0@0x10"),
8303 2 : Bytes::from_static(b"value 1@0x20"),
8304 2 : Bytes::from_static(b"value 2@0x30"),
8305 2 : Bytes::from_static(b"value 3@0x10"),
8306 2 : Bytes::from_static(b"value 4@0x10"),
8307 2 : Bytes::from_static(b"value 5@0x20"),
8308 2 : Bytes::from_static(b"value 6@0x20"),
8309 2 : Bytes::from_static(b"value 7@0x10"),
8310 2 : Bytes::from_static(b"value 8@0x10"),
8311 2 : Bytes::from_static(b"value 9@0x10"),
8312 2 : ];
8313 22 : for idx in 0..10 {
8314 20 : assert_eq!(
8315 20 : image_at_gc_horizon[idx],
8316 20 : (get_key(idx as u32), expected_result[idx].clone())
8317 20 : );
8318 2 : }
8319 2 :
8320 2 : // Check if old layers are removed / new layers have the expected LSN
8321 2 : let all_layers = inspect_and_sort(&tline, None).await;
8322 2 : assert_eq!(
8323 2 : all_layers,
8324 2 : vec![
8325 2 : // Image layer at GC horizon
8326 2 : PersistentLayerKey {
8327 2 : key_range: Key::MIN..Key::MAX,
8328 2 : lsn_range: Lsn(0x30)..Lsn(0x31),
8329 2 : is_delta: false
8330 2 : },
8331 2 : // The delta layer below the horizon
8332 2 : PersistentLayerKey {
8333 2 : key_range: get_key(3)..get_key(4),
8334 2 : lsn_range: Lsn(0x30)..Lsn(0x48),
8335 2 : is_delta: true
8336 2 : },
8337 2 : // The delta3 layer that should not be picked for the compaction
8338 2 : PersistentLayerKey {
8339 2 : key_range: get_key(8)..get_key(10),
8340 2 : lsn_range: Lsn(0x48)..Lsn(0x50),
8341 2 : is_delta: true
8342 2 : }
8343 2 : ]
8344 2 : );
8345 2 :
8346 2 : // increase GC horizon and compact again
8347 2 : {
8348 2 : tline
8349 2 : .latest_gc_cutoff_lsn
8350 2 : .lock_for_write()
8351 2 : .store_and_unlock(Lsn(0x40))
8352 2 : .wait()
8353 2 : .await;
8354 2 : // Update GC info
8355 2 : let mut guard = tline.gc_info.write().unwrap();
8356 2 : guard.cutoffs.time = Lsn(0x40);
8357 2 : guard.cutoffs.space = Lsn(0x40);
8358 2 : }
8359 2 : tline
8360 2 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8361 2 : .await
8362 2 : .unwrap();
8363 2 :
8364 2 : Ok(())
8365 2 : }
8366 :
8367 : #[cfg(feature = "testing")]
8368 : #[tokio::test]
8369 2 : async fn test_neon_test_record() -> anyhow::Result<()> {
8370 2 : let harness = TenantHarness::create("test_neon_test_record").await?;
8371 2 : let (tenant, ctx) = harness.load().await;
8372 2 :
8373 24 : fn get_key(id: u32) -> Key {
8374 24 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8375 24 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8376 24 : key.field6 = id;
8377 24 : key
8378 24 : }
8379 2 :
8380 2 : let delta1 = vec![
8381 2 : (
8382 2 : get_key(1),
8383 2 : Lsn(0x20),
8384 2 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
8385 2 : ),
8386 2 : (
8387 2 : get_key(1),
8388 2 : Lsn(0x30),
8389 2 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
8390 2 : ),
8391 2 : (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
8392 2 : (
8393 2 : get_key(2),
8394 2 : Lsn(0x20),
8395 2 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
8396 2 : ),
8397 2 : (
8398 2 : get_key(2),
8399 2 : Lsn(0x30),
8400 2 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
8401 2 : ),
8402 2 : (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
8403 2 : (
8404 2 : get_key(3),
8405 2 : Lsn(0x20),
8406 2 : Value::WalRecord(NeonWalRecord::wal_clear("c")),
8407 2 : ),
8408 2 : (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
8409 2 : (
8410 2 : get_key(4),
8411 2 : Lsn(0x20),
8412 2 : Value::WalRecord(NeonWalRecord::wal_init("i")),
8413 2 : ),
8414 2 : ];
8415 2 : let image1 = vec![(get_key(1), "0x10".into())];
8416 2 :
8417 2 : let tline = tenant
8418 2 : .create_test_timeline_with_layers(
8419 2 : TIMELINE_ID,
8420 2 : Lsn(0x10),
8421 2 : DEFAULT_PG_VERSION,
8422 2 : &ctx,
8423 2 : vec![DeltaLayerTestDesc::new_with_inferred_key_range(
8424 2 : Lsn(0x10)..Lsn(0x40),
8425 2 : delta1,
8426 2 : )], // delta layers
8427 2 : vec![(Lsn(0x10), image1)], // image layers
8428 2 : Lsn(0x50),
8429 2 : )
8430 2 : .await?;
8431 2 :
8432 2 : assert_eq!(
8433 2 : tline.get(get_key(1), Lsn(0x50), &ctx).await?,
8434 2 : Bytes::from_static(b"0x10,0x20,0x30")
8435 2 : );
8436 2 : assert_eq!(
8437 2 : tline.get(get_key(2), Lsn(0x50), &ctx).await?,
8438 2 : Bytes::from_static(b"0x10,0x20,0x30")
8439 2 : );
8440 2 :
8441 2 : // Need to remove the limit of "Neon WAL redo requires base image".
8442 2 :
8443 2 : // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
8444 2 : // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
8445 2 :
8446 2 : Ok(())
8447 2 : }
8448 :
8449 : #[tokio::test(start_paused = true)]
8450 2 : async fn test_lsn_lease() -> anyhow::Result<()> {
8451 2 : let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
8452 2 : .await
8453 2 : .unwrap()
8454 2 : .load()
8455 2 : .await;
8456 2 : // Advance to the lsn lease deadline so that GC is not blocked by
8457 2 : // initial transition into AttachedSingle.
8458 2 : tokio::time::advance(tenant.get_lsn_lease_length()).await;
8459 2 : tokio::time::resume();
8460 2 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
8461 2 :
8462 2 : let end_lsn = Lsn(0x100);
8463 2 : let image_layers = (0x20..=0x90)
8464 2 : .step_by(0x10)
8465 16 : .map(|n| {
8466 16 : (
8467 16 : Lsn(n),
8468 16 : vec![(key, test_img(&format!("data key at {:x}", n)))],
8469 16 : )
8470 16 : })
8471 2 : .collect();
8472 2 :
8473 2 : let timeline = tenant
8474 2 : .create_test_timeline_with_layers(
8475 2 : TIMELINE_ID,
8476 2 : Lsn(0x10),
8477 2 : DEFAULT_PG_VERSION,
8478 2 : &ctx,
8479 2 : Vec::new(),
8480 2 : image_layers,
8481 2 : end_lsn,
8482 2 : )
8483 2 : .await?;
8484 2 :
8485 2 : let leased_lsns = [0x30, 0x50, 0x70];
8486 2 : let mut leases = Vec::new();
8487 6 : leased_lsns.iter().for_each(|n| {
8488 6 : leases.push(
8489 6 : timeline
8490 6 : .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
8491 6 : .expect("lease request should succeed"),
8492 6 : );
8493 6 : });
8494 2 :
8495 2 : let updated_lease_0 = timeline
8496 2 : .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
8497 2 : .expect("lease renewal should succeed");
8498 2 : assert_eq!(
8499 2 : updated_lease_0.valid_until, leases[0].valid_until,
8500 2 : " Renewing with shorter lease should not change the lease."
8501 2 : );
8502 2 :
8503 2 : let updated_lease_1 = timeline
8504 2 : .renew_lsn_lease(
8505 2 : Lsn(leased_lsns[1]),
8506 2 : timeline.get_lsn_lease_length() * 2,
8507 2 : &ctx,
8508 2 : )
8509 2 : .expect("lease renewal should succeed");
8510 2 : assert!(
8511 2 : updated_lease_1.valid_until > leases[1].valid_until,
8512 2 : "Renewing with a long lease should renew lease with later expiration time."
8513 2 : );
8514 2 :
8515 2 : // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
8516 2 : info!(
8517 2 : "latest_gc_cutoff_lsn: {}",
8518 0 : *timeline.get_latest_gc_cutoff_lsn()
8519 2 : );
8520 2 : timeline.force_set_disk_consistent_lsn(end_lsn);
8521 2 :
8522 2 : let res = tenant
8523 2 : .gc_iteration(
8524 2 : Some(TIMELINE_ID),
8525 2 : 0,
8526 2 : Duration::ZERO,
8527 2 : &CancellationToken::new(),
8528 2 : &ctx,
8529 2 : )
8530 2 : .await
8531 2 : .unwrap();
8532 2 :
8533 2 : // Keeping everything <= Lsn(0x80) b/c leases:
8534 2 : // 0/10: initdb layer
8535 2 : // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
8536 2 : assert_eq!(res.layers_needed_by_leases, 7);
8537 2 : // Keeping 0/90 b/c it is the latest layer.
8538 2 : assert_eq!(res.layers_not_updated, 1);
8539 2 : // Removed 0/80.
8540 2 : assert_eq!(res.layers_removed, 1);
8541 2 :
8542 2 : // Make lease on a already GC-ed LSN.
8543 2 : // 0/80 does not have a valid lease + is below latest_gc_cutoff
8544 2 : assert!(Lsn(0x80) < *timeline.get_latest_gc_cutoff_lsn());
8545 2 : timeline
8546 2 : .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
8547 2 : .expect_err("lease request on GC-ed LSN should fail");
8548 2 :
8549 2 : // Should still be able to renew a currently valid lease
8550 2 : // Assumption: original lease to is still valid for 0/50.
8551 2 : // (use `Timeline::init_lsn_lease` for testing so it always does validation)
8552 2 : timeline
8553 2 : .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
8554 2 : .expect("lease renewal with validation should succeed");
8555 2 :
8556 2 : Ok(())
8557 2 : }
8558 :
8559 : #[cfg(feature = "testing")]
8560 : #[tokio::test]
8561 2 : async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
8562 2 : test_simple_bottom_most_compaction_deltas_helper(
8563 2 : "test_simple_bottom_most_compaction_deltas_1",
8564 2 : false,
8565 2 : )
8566 2 : .await
8567 2 : }
8568 :
8569 : #[cfg(feature = "testing")]
8570 : #[tokio::test]
8571 2 : async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
8572 2 : test_simple_bottom_most_compaction_deltas_helper(
8573 2 : "test_simple_bottom_most_compaction_deltas_2",
8574 2 : true,
8575 2 : )
8576 2 : .await
8577 2 : }
8578 :
8579 : #[cfg(feature = "testing")]
8580 4 : async fn test_simple_bottom_most_compaction_deltas_helper(
8581 4 : test_name: &'static str,
8582 4 : use_delta_bottom_layer: bool,
8583 4 : ) -> anyhow::Result<()> {
8584 4 : let harness = TenantHarness::create(test_name).await?;
8585 4 : let (tenant, ctx) = harness.load().await;
8586 :
8587 276 : fn get_key(id: u32) -> Key {
8588 276 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8589 276 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8590 276 : key.field6 = id;
8591 276 : key
8592 276 : }
8593 :
8594 : // We create
8595 : // - one bottom-most image layer,
8596 : // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
8597 : // - a delta layer D2 crossing the GC horizon with data only below the horizon,
8598 : // - a delta layer D3 above the horizon.
8599 : //
8600 : // | D3 |
8601 : // | D1 |
8602 : // -| |-- gc horizon -----------------
8603 : // | | | D2 |
8604 : // --------- img layer ------------------
8605 : //
8606 : // What we should expact from this compaction is:
8607 : // | D3 |
8608 : // | Part of D1 |
8609 : // --------- img layer with D1+D2 at GC horizon------------------
8610 :
8611 : // img layer at 0x10
8612 4 : let img_layer = (0..10)
8613 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
8614 4 : .collect_vec();
8615 4 : // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
8616 4 : let delta4 = (0..10)
8617 40 : .map(|id| {
8618 40 : (
8619 40 : get_key(id),
8620 40 : Lsn(0x08),
8621 40 : Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
8622 40 : )
8623 40 : })
8624 4 : .collect_vec();
8625 4 :
8626 4 : let delta1 = vec![
8627 4 : (
8628 4 : get_key(1),
8629 4 : Lsn(0x20),
8630 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8631 4 : ),
8632 4 : (
8633 4 : get_key(2),
8634 4 : Lsn(0x30),
8635 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
8636 4 : ),
8637 4 : (
8638 4 : get_key(3),
8639 4 : Lsn(0x28),
8640 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
8641 4 : ),
8642 4 : (
8643 4 : get_key(3),
8644 4 : Lsn(0x30),
8645 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
8646 4 : ),
8647 4 : (
8648 4 : get_key(3),
8649 4 : Lsn(0x40),
8650 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
8651 4 : ),
8652 4 : ];
8653 4 : let delta2 = vec![
8654 4 : (
8655 4 : get_key(5),
8656 4 : Lsn(0x20),
8657 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8658 4 : ),
8659 4 : (
8660 4 : get_key(6),
8661 4 : Lsn(0x20),
8662 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8663 4 : ),
8664 4 : ];
8665 4 : let delta3 = vec![
8666 4 : (
8667 4 : get_key(8),
8668 4 : Lsn(0x48),
8669 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
8670 4 : ),
8671 4 : (
8672 4 : get_key(9),
8673 4 : Lsn(0x48),
8674 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
8675 4 : ),
8676 4 : ];
8677 :
8678 4 : let tline = if use_delta_bottom_layer {
8679 2 : tenant
8680 2 : .create_test_timeline_with_layers(
8681 2 : TIMELINE_ID,
8682 2 : Lsn(0x08),
8683 2 : DEFAULT_PG_VERSION,
8684 2 : &ctx,
8685 2 : vec![
8686 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
8687 2 : Lsn(0x08)..Lsn(0x10),
8688 2 : delta4,
8689 2 : ),
8690 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
8691 2 : Lsn(0x20)..Lsn(0x48),
8692 2 : delta1,
8693 2 : ),
8694 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
8695 2 : Lsn(0x20)..Lsn(0x48),
8696 2 : delta2,
8697 2 : ),
8698 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
8699 2 : Lsn(0x48)..Lsn(0x50),
8700 2 : delta3,
8701 2 : ),
8702 2 : ], // delta layers
8703 2 : vec![], // image layers
8704 2 : Lsn(0x50),
8705 2 : )
8706 2 : .await?
8707 : } else {
8708 2 : tenant
8709 2 : .create_test_timeline_with_layers(
8710 2 : TIMELINE_ID,
8711 2 : Lsn(0x10),
8712 2 : DEFAULT_PG_VERSION,
8713 2 : &ctx,
8714 2 : vec![
8715 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
8716 2 : Lsn(0x10)..Lsn(0x48),
8717 2 : delta1,
8718 2 : ),
8719 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
8720 2 : Lsn(0x10)..Lsn(0x48),
8721 2 : delta2,
8722 2 : ),
8723 2 : DeltaLayerTestDesc::new_with_inferred_key_range(
8724 2 : Lsn(0x48)..Lsn(0x50),
8725 2 : delta3,
8726 2 : ),
8727 2 : ], // delta layers
8728 2 : vec![(Lsn(0x10), img_layer)], // image layers
8729 2 : Lsn(0x50),
8730 2 : )
8731 2 : .await?
8732 : };
8733 : {
8734 4 : tline
8735 4 : .latest_gc_cutoff_lsn
8736 4 : .lock_for_write()
8737 4 : .store_and_unlock(Lsn(0x30))
8738 4 : .wait()
8739 4 : .await;
8740 : // Update GC info
8741 4 : let mut guard = tline.gc_info.write().unwrap();
8742 4 : *guard = GcInfo {
8743 4 : retain_lsns: vec![],
8744 4 : cutoffs: GcCutoffs {
8745 4 : time: Lsn(0x30),
8746 4 : space: Lsn(0x30),
8747 4 : },
8748 4 : leases: Default::default(),
8749 4 : within_ancestor_pitr: false,
8750 4 : };
8751 4 : }
8752 4 :
8753 4 : let expected_result = [
8754 4 : Bytes::from_static(b"value 0@0x10"),
8755 4 : Bytes::from_static(b"value 1@0x10@0x20"),
8756 4 : Bytes::from_static(b"value 2@0x10@0x30"),
8757 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
8758 4 : Bytes::from_static(b"value 4@0x10"),
8759 4 : Bytes::from_static(b"value 5@0x10@0x20"),
8760 4 : Bytes::from_static(b"value 6@0x10@0x20"),
8761 4 : Bytes::from_static(b"value 7@0x10"),
8762 4 : Bytes::from_static(b"value 8@0x10@0x48"),
8763 4 : Bytes::from_static(b"value 9@0x10@0x48"),
8764 4 : ];
8765 4 :
8766 4 : let expected_result_at_gc_horizon = [
8767 4 : Bytes::from_static(b"value 0@0x10"),
8768 4 : Bytes::from_static(b"value 1@0x10@0x20"),
8769 4 : Bytes::from_static(b"value 2@0x10@0x30"),
8770 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30"),
8771 4 : Bytes::from_static(b"value 4@0x10"),
8772 4 : Bytes::from_static(b"value 5@0x10@0x20"),
8773 4 : Bytes::from_static(b"value 6@0x10@0x20"),
8774 4 : Bytes::from_static(b"value 7@0x10"),
8775 4 : Bytes::from_static(b"value 8@0x10"),
8776 4 : Bytes::from_static(b"value 9@0x10"),
8777 4 : ];
8778 :
8779 44 : for idx in 0..10 {
8780 40 : assert_eq!(
8781 40 : tline
8782 40 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8783 40 : .await
8784 40 : .unwrap(),
8785 40 : &expected_result[idx]
8786 : );
8787 40 : assert_eq!(
8788 40 : tline
8789 40 : .get(get_key(idx as u32), Lsn(0x30), &ctx)
8790 40 : .await
8791 40 : .unwrap(),
8792 40 : &expected_result_at_gc_horizon[idx]
8793 : );
8794 : }
8795 :
8796 4 : let cancel = CancellationToken::new();
8797 4 : tline
8798 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8799 4 : .await
8800 4 : .unwrap();
8801 :
8802 44 : for idx in 0..10 {
8803 40 : assert_eq!(
8804 40 : tline
8805 40 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8806 40 : .await
8807 40 : .unwrap(),
8808 40 : &expected_result[idx]
8809 : );
8810 40 : assert_eq!(
8811 40 : tline
8812 40 : .get(get_key(idx as u32), Lsn(0x30), &ctx)
8813 40 : .await
8814 40 : .unwrap(),
8815 40 : &expected_result_at_gc_horizon[idx]
8816 : );
8817 : }
8818 :
8819 : // increase GC horizon and compact again
8820 : {
8821 4 : tline
8822 4 : .latest_gc_cutoff_lsn
8823 4 : .lock_for_write()
8824 4 : .store_and_unlock(Lsn(0x40))
8825 4 : .wait()
8826 4 : .await;
8827 : // Update GC info
8828 4 : let mut guard = tline.gc_info.write().unwrap();
8829 4 : guard.cutoffs.time = Lsn(0x40);
8830 4 : guard.cutoffs.space = Lsn(0x40);
8831 4 : }
8832 4 : tline
8833 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8834 4 : .await
8835 4 : .unwrap();
8836 4 :
8837 4 : Ok(())
8838 4 : }
8839 :
8840 : #[cfg(feature = "testing")]
8841 : #[tokio::test]
8842 2 : async fn test_generate_key_retention() -> anyhow::Result<()> {
8843 2 : let harness = TenantHarness::create("test_generate_key_retention").await?;
8844 2 : let (tenant, ctx) = harness.load().await;
8845 2 : let tline = tenant
8846 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
8847 2 : .await?;
8848 2 : tline.force_advance_lsn(Lsn(0x70));
8849 2 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
8850 2 : let history = vec![
8851 2 : (
8852 2 : key,
8853 2 : Lsn(0x10),
8854 2 : Value::WalRecord(NeonWalRecord::wal_init("0x10")),
8855 2 : ),
8856 2 : (
8857 2 : key,
8858 2 : Lsn(0x20),
8859 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
8860 2 : ),
8861 2 : (
8862 2 : key,
8863 2 : Lsn(0x30),
8864 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
8865 2 : ),
8866 2 : (
8867 2 : key,
8868 2 : Lsn(0x40),
8869 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
8870 2 : ),
8871 2 : (
8872 2 : key,
8873 2 : Lsn(0x50),
8874 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
8875 2 : ),
8876 2 : (
8877 2 : key,
8878 2 : Lsn(0x60),
8879 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
8880 2 : ),
8881 2 : (
8882 2 : key,
8883 2 : Lsn(0x70),
8884 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
8885 2 : ),
8886 2 : (
8887 2 : key,
8888 2 : Lsn(0x80),
8889 2 : Value::Image(Bytes::copy_from_slice(
8890 2 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
8891 2 : )),
8892 2 : ),
8893 2 : (
8894 2 : key,
8895 2 : Lsn(0x90),
8896 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
8897 2 : ),
8898 2 : ];
8899 2 : let res = tline
8900 2 : .generate_key_retention(
8901 2 : key,
8902 2 : &history,
8903 2 : Lsn(0x60),
8904 2 : &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
8905 2 : 3,
8906 2 : None,
8907 2 : )
8908 2 : .await
8909 2 : .unwrap();
8910 2 : let expected_res = KeyHistoryRetention {
8911 2 : below_horizon: vec![
8912 2 : (
8913 2 : Lsn(0x20),
8914 2 : KeyLogAtLsn(vec![(
8915 2 : Lsn(0x20),
8916 2 : Value::Image(Bytes::from_static(b"0x10;0x20")),
8917 2 : )]),
8918 2 : ),
8919 2 : (
8920 2 : Lsn(0x40),
8921 2 : KeyLogAtLsn(vec![
8922 2 : (
8923 2 : Lsn(0x30),
8924 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
8925 2 : ),
8926 2 : (
8927 2 : Lsn(0x40),
8928 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
8929 2 : ),
8930 2 : ]),
8931 2 : ),
8932 2 : (
8933 2 : Lsn(0x50),
8934 2 : KeyLogAtLsn(vec![(
8935 2 : Lsn(0x50),
8936 2 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
8937 2 : )]),
8938 2 : ),
8939 2 : (
8940 2 : Lsn(0x60),
8941 2 : KeyLogAtLsn(vec![(
8942 2 : Lsn(0x60),
8943 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
8944 2 : )]),
8945 2 : ),
8946 2 : ],
8947 2 : above_horizon: KeyLogAtLsn(vec![
8948 2 : (
8949 2 : Lsn(0x70),
8950 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
8951 2 : ),
8952 2 : (
8953 2 : Lsn(0x80),
8954 2 : Value::Image(Bytes::copy_from_slice(
8955 2 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
8956 2 : )),
8957 2 : ),
8958 2 : (
8959 2 : Lsn(0x90),
8960 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
8961 2 : ),
8962 2 : ]),
8963 2 : };
8964 2 : assert_eq!(res, expected_res);
8965 2 :
8966 2 : // We expect GC-compaction to run with the original GC. This would create a situation that
8967 2 : // the original GC algorithm removes some delta layers b/c there are full image coverage,
8968 2 : // therefore causing some keys to have an incomplete history below the lowest retain LSN.
8969 2 : // For example, we have
8970 2 : // ```plain
8971 2 : // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
8972 2 : // ```
8973 2 : // Now the GC horizon moves up, and we have
8974 2 : // ```plain
8975 2 : // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
8976 2 : // ```
8977 2 : // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
8978 2 : // We will end up with
8979 2 : // ```plain
8980 2 : // delta @ 0x30, image @ 0x40 (gc_horizon)
8981 2 : // ```
8982 2 : // Now we run the GC-compaction, and this key does not have a full history.
8983 2 : // We should be able to handle this partial history and drop everything before the
8984 2 : // gc_horizon image.
8985 2 :
8986 2 : let history = vec![
8987 2 : (
8988 2 : key,
8989 2 : Lsn(0x20),
8990 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
8991 2 : ),
8992 2 : (
8993 2 : key,
8994 2 : Lsn(0x30),
8995 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
8996 2 : ),
8997 2 : (
8998 2 : key,
8999 2 : Lsn(0x40),
9000 2 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
9001 2 : ),
9002 2 : (
9003 2 : key,
9004 2 : Lsn(0x50),
9005 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9006 2 : ),
9007 2 : (
9008 2 : key,
9009 2 : Lsn(0x60),
9010 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9011 2 : ),
9012 2 : (
9013 2 : key,
9014 2 : Lsn(0x70),
9015 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9016 2 : ),
9017 2 : (
9018 2 : key,
9019 2 : Lsn(0x80),
9020 2 : Value::Image(Bytes::copy_from_slice(
9021 2 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9022 2 : )),
9023 2 : ),
9024 2 : (
9025 2 : key,
9026 2 : Lsn(0x90),
9027 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9028 2 : ),
9029 2 : ];
9030 2 : let res = tline
9031 2 : .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
9032 2 : .await
9033 2 : .unwrap();
9034 2 : let expected_res = KeyHistoryRetention {
9035 2 : below_horizon: vec![
9036 2 : (
9037 2 : Lsn(0x40),
9038 2 : KeyLogAtLsn(vec![(
9039 2 : Lsn(0x40),
9040 2 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
9041 2 : )]),
9042 2 : ),
9043 2 : (
9044 2 : Lsn(0x50),
9045 2 : KeyLogAtLsn(vec![(
9046 2 : Lsn(0x50),
9047 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9048 2 : )]),
9049 2 : ),
9050 2 : (
9051 2 : Lsn(0x60),
9052 2 : KeyLogAtLsn(vec![(
9053 2 : Lsn(0x60),
9054 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9055 2 : )]),
9056 2 : ),
9057 2 : ],
9058 2 : above_horizon: KeyLogAtLsn(vec![
9059 2 : (
9060 2 : Lsn(0x70),
9061 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9062 2 : ),
9063 2 : (
9064 2 : Lsn(0x80),
9065 2 : Value::Image(Bytes::copy_from_slice(
9066 2 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9067 2 : )),
9068 2 : ),
9069 2 : (
9070 2 : Lsn(0x90),
9071 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9072 2 : ),
9073 2 : ]),
9074 2 : };
9075 2 : assert_eq!(res, expected_res);
9076 2 :
9077 2 : // In case of branch compaction, the branch itself does not have the full history, and we need to provide
9078 2 : // the ancestor image in the test case.
9079 2 :
9080 2 : let history = vec![
9081 2 : (
9082 2 : key,
9083 2 : Lsn(0x20),
9084 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9085 2 : ),
9086 2 : (
9087 2 : key,
9088 2 : Lsn(0x30),
9089 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9090 2 : ),
9091 2 : (
9092 2 : key,
9093 2 : Lsn(0x40),
9094 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9095 2 : ),
9096 2 : (
9097 2 : key,
9098 2 : Lsn(0x70),
9099 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9100 2 : ),
9101 2 : ];
9102 2 : let res = tline
9103 2 : .generate_key_retention(
9104 2 : key,
9105 2 : &history,
9106 2 : Lsn(0x60),
9107 2 : &[],
9108 2 : 3,
9109 2 : Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
9110 2 : )
9111 2 : .await
9112 2 : .unwrap();
9113 2 : let expected_res = KeyHistoryRetention {
9114 2 : below_horizon: vec![(
9115 2 : Lsn(0x60),
9116 2 : KeyLogAtLsn(vec![(
9117 2 : Lsn(0x60),
9118 2 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
9119 2 : )]),
9120 2 : )],
9121 2 : above_horizon: KeyLogAtLsn(vec![(
9122 2 : Lsn(0x70),
9123 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9124 2 : )]),
9125 2 : };
9126 2 : assert_eq!(res, expected_res);
9127 2 :
9128 2 : let history = vec![
9129 2 : (
9130 2 : key,
9131 2 : Lsn(0x20),
9132 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9133 2 : ),
9134 2 : (
9135 2 : key,
9136 2 : Lsn(0x40),
9137 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9138 2 : ),
9139 2 : (
9140 2 : key,
9141 2 : Lsn(0x60),
9142 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9143 2 : ),
9144 2 : (
9145 2 : key,
9146 2 : Lsn(0x70),
9147 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9148 2 : ),
9149 2 : ];
9150 2 : let res = tline
9151 2 : .generate_key_retention(
9152 2 : key,
9153 2 : &history,
9154 2 : Lsn(0x60),
9155 2 : &[Lsn(0x30)],
9156 2 : 3,
9157 2 : Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
9158 2 : )
9159 2 : .await
9160 2 : .unwrap();
9161 2 : let expected_res = KeyHistoryRetention {
9162 2 : below_horizon: vec![
9163 2 : (
9164 2 : Lsn(0x30),
9165 2 : KeyLogAtLsn(vec![(
9166 2 : Lsn(0x20),
9167 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9168 2 : )]),
9169 2 : ),
9170 2 : (
9171 2 : Lsn(0x60),
9172 2 : KeyLogAtLsn(vec![(
9173 2 : Lsn(0x60),
9174 2 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
9175 2 : )]),
9176 2 : ),
9177 2 : ],
9178 2 : above_horizon: KeyLogAtLsn(vec![(
9179 2 : Lsn(0x70),
9180 2 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9181 2 : )]),
9182 2 : };
9183 2 : assert_eq!(res, expected_res);
9184 2 :
9185 2 : Ok(())
9186 2 : }
9187 :
9188 : #[cfg(feature = "testing")]
9189 : #[tokio::test]
9190 2 : async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
9191 2 : let harness =
9192 2 : TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
9193 2 : let (tenant, ctx) = harness.load().await;
9194 2 :
9195 518 : fn get_key(id: u32) -> Key {
9196 518 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
9197 518 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
9198 518 : key.field6 = id;
9199 518 : key
9200 518 : }
9201 2 :
9202 2 : let img_layer = (0..10)
9203 20 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9204 2 : .collect_vec();
9205 2 :
9206 2 : let delta1 = vec![
9207 2 : (
9208 2 : get_key(1),
9209 2 : Lsn(0x20),
9210 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9211 2 : ),
9212 2 : (
9213 2 : get_key(2),
9214 2 : Lsn(0x30),
9215 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9216 2 : ),
9217 2 : (
9218 2 : get_key(3),
9219 2 : Lsn(0x28),
9220 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9221 2 : ),
9222 2 : (
9223 2 : get_key(3),
9224 2 : Lsn(0x30),
9225 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9226 2 : ),
9227 2 : (
9228 2 : get_key(3),
9229 2 : Lsn(0x40),
9230 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
9231 2 : ),
9232 2 : ];
9233 2 : let delta2 = vec![
9234 2 : (
9235 2 : get_key(5),
9236 2 : Lsn(0x20),
9237 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9238 2 : ),
9239 2 : (
9240 2 : get_key(6),
9241 2 : Lsn(0x20),
9242 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9243 2 : ),
9244 2 : ];
9245 2 : let delta3 = vec![
9246 2 : (
9247 2 : get_key(8),
9248 2 : Lsn(0x48),
9249 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9250 2 : ),
9251 2 : (
9252 2 : get_key(9),
9253 2 : Lsn(0x48),
9254 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9255 2 : ),
9256 2 : ];
9257 2 :
9258 2 : let tline = tenant
9259 2 : .create_test_timeline_with_layers(
9260 2 : TIMELINE_ID,
9261 2 : Lsn(0x10),
9262 2 : DEFAULT_PG_VERSION,
9263 2 : &ctx,
9264 2 : vec![
9265 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
9266 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
9267 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
9268 2 : ], // delta layers
9269 2 : vec![(Lsn(0x10), img_layer)], // image layers
9270 2 : Lsn(0x50),
9271 2 : )
9272 2 : .await?;
9273 2 : {
9274 2 : tline
9275 2 : .latest_gc_cutoff_lsn
9276 2 : .lock_for_write()
9277 2 : .store_and_unlock(Lsn(0x30))
9278 2 : .wait()
9279 2 : .await;
9280 2 : // Update GC info
9281 2 : let mut guard = tline.gc_info.write().unwrap();
9282 2 : *guard = GcInfo {
9283 2 : retain_lsns: vec![
9284 2 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
9285 2 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
9286 2 : ],
9287 2 : cutoffs: GcCutoffs {
9288 2 : time: Lsn(0x30),
9289 2 : space: Lsn(0x30),
9290 2 : },
9291 2 : leases: Default::default(),
9292 2 : within_ancestor_pitr: false,
9293 2 : };
9294 2 : }
9295 2 :
9296 2 : let expected_result = [
9297 2 : Bytes::from_static(b"value 0@0x10"),
9298 2 : Bytes::from_static(b"value 1@0x10@0x20"),
9299 2 : Bytes::from_static(b"value 2@0x10@0x30"),
9300 2 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
9301 2 : Bytes::from_static(b"value 4@0x10"),
9302 2 : Bytes::from_static(b"value 5@0x10@0x20"),
9303 2 : Bytes::from_static(b"value 6@0x10@0x20"),
9304 2 : Bytes::from_static(b"value 7@0x10"),
9305 2 : Bytes::from_static(b"value 8@0x10@0x48"),
9306 2 : Bytes::from_static(b"value 9@0x10@0x48"),
9307 2 : ];
9308 2 :
9309 2 : let expected_result_at_gc_horizon = [
9310 2 : Bytes::from_static(b"value 0@0x10"),
9311 2 : Bytes::from_static(b"value 1@0x10@0x20"),
9312 2 : Bytes::from_static(b"value 2@0x10@0x30"),
9313 2 : Bytes::from_static(b"value 3@0x10@0x28@0x30"),
9314 2 : Bytes::from_static(b"value 4@0x10"),
9315 2 : Bytes::from_static(b"value 5@0x10@0x20"),
9316 2 : Bytes::from_static(b"value 6@0x10@0x20"),
9317 2 : Bytes::from_static(b"value 7@0x10"),
9318 2 : Bytes::from_static(b"value 8@0x10"),
9319 2 : Bytes::from_static(b"value 9@0x10"),
9320 2 : ];
9321 2 :
9322 2 : let expected_result_at_lsn_20 = [
9323 2 : Bytes::from_static(b"value 0@0x10"),
9324 2 : Bytes::from_static(b"value 1@0x10@0x20"),
9325 2 : Bytes::from_static(b"value 2@0x10"),
9326 2 : Bytes::from_static(b"value 3@0x10"),
9327 2 : Bytes::from_static(b"value 4@0x10"),
9328 2 : Bytes::from_static(b"value 5@0x10@0x20"),
9329 2 : Bytes::from_static(b"value 6@0x10@0x20"),
9330 2 : Bytes::from_static(b"value 7@0x10"),
9331 2 : Bytes::from_static(b"value 8@0x10"),
9332 2 : Bytes::from_static(b"value 9@0x10"),
9333 2 : ];
9334 2 :
9335 2 : let expected_result_at_lsn_10 = [
9336 2 : Bytes::from_static(b"value 0@0x10"),
9337 2 : Bytes::from_static(b"value 1@0x10"),
9338 2 : Bytes::from_static(b"value 2@0x10"),
9339 2 : Bytes::from_static(b"value 3@0x10"),
9340 2 : Bytes::from_static(b"value 4@0x10"),
9341 2 : Bytes::from_static(b"value 5@0x10"),
9342 2 : Bytes::from_static(b"value 6@0x10"),
9343 2 : Bytes::from_static(b"value 7@0x10"),
9344 2 : Bytes::from_static(b"value 8@0x10"),
9345 2 : Bytes::from_static(b"value 9@0x10"),
9346 2 : ];
9347 2 :
9348 12 : let verify_result = || async {
9349 12 : let gc_horizon = {
9350 12 : let gc_info = tline.gc_info.read().unwrap();
9351 12 : gc_info.cutoffs.time
9352 2 : };
9353 132 : for idx in 0..10 {
9354 120 : assert_eq!(
9355 120 : tline
9356 120 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9357 120 : .await
9358 120 : .unwrap(),
9359 120 : &expected_result[idx]
9360 2 : );
9361 120 : assert_eq!(
9362 120 : tline
9363 120 : .get(get_key(idx as u32), gc_horizon, &ctx)
9364 120 : .await
9365 120 : .unwrap(),
9366 120 : &expected_result_at_gc_horizon[idx]
9367 2 : );
9368 120 : assert_eq!(
9369 120 : tline
9370 120 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
9371 120 : .await
9372 120 : .unwrap(),
9373 120 : &expected_result_at_lsn_20[idx]
9374 2 : );
9375 120 : assert_eq!(
9376 120 : tline
9377 120 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
9378 120 : .await
9379 120 : .unwrap(),
9380 120 : &expected_result_at_lsn_10[idx]
9381 2 : );
9382 2 : }
9383 24 : };
9384 2 :
9385 2 : verify_result().await;
9386 2 :
9387 2 : let cancel = CancellationToken::new();
9388 2 : let mut dryrun_flags = EnumSet::new();
9389 2 : dryrun_flags.insert(CompactFlags::DryRun);
9390 2 :
9391 2 : tline
9392 2 : .compact_with_gc(
9393 2 : &cancel,
9394 2 : CompactOptions {
9395 2 : flags: dryrun_flags,
9396 2 : ..Default::default()
9397 2 : },
9398 2 : &ctx,
9399 2 : )
9400 2 : .await
9401 2 : .unwrap();
9402 2 : // 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
9403 2 : // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
9404 2 : verify_result().await;
9405 2 :
9406 2 : tline
9407 2 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9408 2 : .await
9409 2 : .unwrap();
9410 2 : verify_result().await;
9411 2 :
9412 2 : // compact again
9413 2 : tline
9414 2 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9415 2 : .await
9416 2 : .unwrap();
9417 2 : verify_result().await;
9418 2 :
9419 2 : // increase GC horizon and compact again
9420 2 : {
9421 2 : tline
9422 2 : .latest_gc_cutoff_lsn
9423 2 : .lock_for_write()
9424 2 : .store_and_unlock(Lsn(0x38))
9425 2 : .wait()
9426 2 : .await;
9427 2 : // Update GC info
9428 2 : let mut guard = tline.gc_info.write().unwrap();
9429 2 : guard.cutoffs.time = Lsn(0x38);
9430 2 : guard.cutoffs.space = Lsn(0x38);
9431 2 : }
9432 2 : tline
9433 2 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9434 2 : .await
9435 2 : .unwrap();
9436 2 : verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
9437 2 :
9438 2 : // not increasing the GC horizon and compact again
9439 2 : tline
9440 2 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9441 2 : .await
9442 2 : .unwrap();
9443 2 : verify_result().await;
9444 2 :
9445 2 : Ok(())
9446 2 : }
9447 :
9448 : #[cfg(feature = "testing")]
9449 : #[tokio::test]
9450 2 : async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
9451 2 : {
9452 2 : let harness =
9453 2 : TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
9454 2 : .await?;
9455 2 : let (tenant, ctx) = harness.load().await;
9456 2 :
9457 352 : fn get_key(id: u32) -> Key {
9458 352 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
9459 352 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
9460 352 : key.field6 = id;
9461 352 : key
9462 352 : }
9463 2 :
9464 2 : let img_layer = (0..10)
9465 20 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9466 2 : .collect_vec();
9467 2 :
9468 2 : let delta1 = vec![
9469 2 : (
9470 2 : get_key(1),
9471 2 : Lsn(0x20),
9472 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9473 2 : ),
9474 2 : (
9475 2 : get_key(1),
9476 2 : Lsn(0x28),
9477 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9478 2 : ),
9479 2 : ];
9480 2 : let delta2 = vec![
9481 2 : (
9482 2 : get_key(1),
9483 2 : Lsn(0x30),
9484 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9485 2 : ),
9486 2 : (
9487 2 : get_key(1),
9488 2 : Lsn(0x38),
9489 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
9490 2 : ),
9491 2 : ];
9492 2 : let delta3 = vec![
9493 2 : (
9494 2 : get_key(8),
9495 2 : Lsn(0x48),
9496 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9497 2 : ),
9498 2 : (
9499 2 : get_key(9),
9500 2 : Lsn(0x48),
9501 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9502 2 : ),
9503 2 : ];
9504 2 :
9505 2 : let tline = tenant
9506 2 : .create_test_timeline_with_layers(
9507 2 : TIMELINE_ID,
9508 2 : Lsn(0x10),
9509 2 : DEFAULT_PG_VERSION,
9510 2 : &ctx,
9511 2 : vec![
9512 2 : // delta1 and delta 2 only contain a single key but multiple updates
9513 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
9514 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
9515 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
9516 2 : ], // delta layers
9517 2 : vec![(Lsn(0x10), img_layer)], // image layers
9518 2 : Lsn(0x50),
9519 2 : )
9520 2 : .await?;
9521 2 : {
9522 2 : tline
9523 2 : .latest_gc_cutoff_lsn
9524 2 : .lock_for_write()
9525 2 : .store_and_unlock(Lsn(0x30))
9526 2 : .wait()
9527 2 : .await;
9528 2 : // Update GC info
9529 2 : let mut guard = tline.gc_info.write().unwrap();
9530 2 : *guard = GcInfo {
9531 2 : retain_lsns: vec![
9532 2 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
9533 2 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
9534 2 : ],
9535 2 : cutoffs: GcCutoffs {
9536 2 : time: Lsn(0x30),
9537 2 : space: Lsn(0x30),
9538 2 : },
9539 2 : leases: Default::default(),
9540 2 : within_ancestor_pitr: false,
9541 2 : };
9542 2 : }
9543 2 :
9544 2 : let expected_result = [
9545 2 : Bytes::from_static(b"value 0@0x10"),
9546 2 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
9547 2 : Bytes::from_static(b"value 2@0x10"),
9548 2 : Bytes::from_static(b"value 3@0x10"),
9549 2 : Bytes::from_static(b"value 4@0x10"),
9550 2 : Bytes::from_static(b"value 5@0x10"),
9551 2 : Bytes::from_static(b"value 6@0x10"),
9552 2 : Bytes::from_static(b"value 7@0x10"),
9553 2 : Bytes::from_static(b"value 8@0x10@0x48"),
9554 2 : Bytes::from_static(b"value 9@0x10@0x48"),
9555 2 : ];
9556 2 :
9557 2 : let expected_result_at_gc_horizon = [
9558 2 : Bytes::from_static(b"value 0@0x10"),
9559 2 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
9560 2 : Bytes::from_static(b"value 2@0x10"),
9561 2 : Bytes::from_static(b"value 3@0x10"),
9562 2 : Bytes::from_static(b"value 4@0x10"),
9563 2 : Bytes::from_static(b"value 5@0x10"),
9564 2 : Bytes::from_static(b"value 6@0x10"),
9565 2 : Bytes::from_static(b"value 7@0x10"),
9566 2 : Bytes::from_static(b"value 8@0x10"),
9567 2 : Bytes::from_static(b"value 9@0x10"),
9568 2 : ];
9569 2 :
9570 2 : let expected_result_at_lsn_20 = [
9571 2 : Bytes::from_static(b"value 0@0x10"),
9572 2 : Bytes::from_static(b"value 1@0x10@0x20"),
9573 2 : Bytes::from_static(b"value 2@0x10"),
9574 2 : Bytes::from_static(b"value 3@0x10"),
9575 2 : Bytes::from_static(b"value 4@0x10"),
9576 2 : Bytes::from_static(b"value 5@0x10"),
9577 2 : Bytes::from_static(b"value 6@0x10"),
9578 2 : Bytes::from_static(b"value 7@0x10"),
9579 2 : Bytes::from_static(b"value 8@0x10"),
9580 2 : Bytes::from_static(b"value 9@0x10"),
9581 2 : ];
9582 2 :
9583 2 : let expected_result_at_lsn_10 = [
9584 2 : Bytes::from_static(b"value 0@0x10"),
9585 2 : Bytes::from_static(b"value 1@0x10"),
9586 2 : Bytes::from_static(b"value 2@0x10"),
9587 2 : Bytes::from_static(b"value 3@0x10"),
9588 2 : Bytes::from_static(b"value 4@0x10"),
9589 2 : Bytes::from_static(b"value 5@0x10"),
9590 2 : Bytes::from_static(b"value 6@0x10"),
9591 2 : Bytes::from_static(b"value 7@0x10"),
9592 2 : Bytes::from_static(b"value 8@0x10"),
9593 2 : Bytes::from_static(b"value 9@0x10"),
9594 2 : ];
9595 2 :
9596 8 : let verify_result = || async {
9597 8 : let gc_horizon = {
9598 8 : let gc_info = tline.gc_info.read().unwrap();
9599 8 : gc_info.cutoffs.time
9600 2 : };
9601 88 : for idx in 0..10 {
9602 80 : assert_eq!(
9603 80 : tline
9604 80 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9605 80 : .await
9606 80 : .unwrap(),
9607 80 : &expected_result[idx]
9608 2 : );
9609 80 : assert_eq!(
9610 80 : tline
9611 80 : .get(get_key(idx as u32), gc_horizon, &ctx)
9612 80 : .await
9613 80 : .unwrap(),
9614 80 : &expected_result_at_gc_horizon[idx]
9615 2 : );
9616 80 : assert_eq!(
9617 80 : tline
9618 80 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
9619 80 : .await
9620 80 : .unwrap(),
9621 80 : &expected_result_at_lsn_20[idx]
9622 2 : );
9623 80 : assert_eq!(
9624 80 : tline
9625 80 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
9626 80 : .await
9627 80 : .unwrap(),
9628 80 : &expected_result_at_lsn_10[idx]
9629 2 : );
9630 2 : }
9631 16 : };
9632 2 :
9633 2 : verify_result().await;
9634 2 :
9635 2 : let cancel = CancellationToken::new();
9636 2 : let mut dryrun_flags = EnumSet::new();
9637 2 : dryrun_flags.insert(CompactFlags::DryRun);
9638 2 :
9639 2 : tline
9640 2 : .compact_with_gc(
9641 2 : &cancel,
9642 2 : CompactOptions {
9643 2 : flags: dryrun_flags,
9644 2 : ..Default::default()
9645 2 : },
9646 2 : &ctx,
9647 2 : )
9648 2 : .await
9649 2 : .unwrap();
9650 2 : // 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
9651 2 : // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
9652 2 : verify_result().await;
9653 2 :
9654 2 : tline
9655 2 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9656 2 : .await
9657 2 : .unwrap();
9658 2 : verify_result().await;
9659 2 :
9660 2 : // compact again
9661 2 : tline
9662 2 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9663 2 : .await
9664 2 : .unwrap();
9665 2 : verify_result().await;
9666 2 :
9667 2 : Ok(())
9668 2 : }
9669 :
9670 : #[cfg(feature = "testing")]
9671 : #[tokio::test]
9672 2 : async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
9673 2 : use models::CompactLsnRange;
9674 2 :
9675 2 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
9676 2 : let (tenant, ctx) = harness.load().await;
9677 2 :
9678 166 : fn get_key(id: u32) -> Key {
9679 166 : let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
9680 166 : key.field6 = id;
9681 166 : key
9682 166 : }
9683 2 :
9684 2 : let img_layer = (0..10)
9685 20 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9686 2 : .collect_vec();
9687 2 :
9688 2 : let delta1 = vec![
9689 2 : (
9690 2 : get_key(1),
9691 2 : Lsn(0x20),
9692 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9693 2 : ),
9694 2 : (
9695 2 : get_key(2),
9696 2 : Lsn(0x30),
9697 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9698 2 : ),
9699 2 : (
9700 2 : get_key(3),
9701 2 : Lsn(0x28),
9702 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9703 2 : ),
9704 2 : (
9705 2 : get_key(3),
9706 2 : Lsn(0x30),
9707 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9708 2 : ),
9709 2 : (
9710 2 : get_key(3),
9711 2 : Lsn(0x40),
9712 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
9713 2 : ),
9714 2 : ];
9715 2 : let delta2 = vec![
9716 2 : (
9717 2 : get_key(5),
9718 2 : Lsn(0x20),
9719 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9720 2 : ),
9721 2 : (
9722 2 : get_key(6),
9723 2 : Lsn(0x20),
9724 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9725 2 : ),
9726 2 : ];
9727 2 : let delta3 = vec![
9728 2 : (
9729 2 : get_key(8),
9730 2 : Lsn(0x48),
9731 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9732 2 : ),
9733 2 : (
9734 2 : get_key(9),
9735 2 : Lsn(0x48),
9736 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9737 2 : ),
9738 2 : ];
9739 2 :
9740 2 : let parent_tline = tenant
9741 2 : .create_test_timeline_with_layers(
9742 2 : TIMELINE_ID,
9743 2 : Lsn(0x10),
9744 2 : DEFAULT_PG_VERSION,
9745 2 : &ctx,
9746 2 : vec![], // delta layers
9747 2 : vec![(Lsn(0x18), img_layer)], // image layers
9748 2 : Lsn(0x18),
9749 2 : )
9750 2 : .await?;
9751 2 :
9752 2 : parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
9753 2 :
9754 2 : let branch_tline = tenant
9755 2 : .branch_timeline_test_with_layers(
9756 2 : &parent_tline,
9757 2 : NEW_TIMELINE_ID,
9758 2 : Some(Lsn(0x18)),
9759 2 : &ctx,
9760 2 : vec![
9761 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
9762 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
9763 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
9764 2 : ], // delta layers
9765 2 : vec![], // image layers
9766 2 : Lsn(0x50),
9767 2 : )
9768 2 : .await?;
9769 2 :
9770 2 : branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
9771 2 :
9772 2 : {
9773 2 : parent_tline
9774 2 : .latest_gc_cutoff_lsn
9775 2 : .lock_for_write()
9776 2 : .store_and_unlock(Lsn(0x10))
9777 2 : .wait()
9778 2 : .await;
9779 2 : // Update GC info
9780 2 : let mut guard = parent_tline.gc_info.write().unwrap();
9781 2 : *guard = GcInfo {
9782 2 : retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
9783 2 : cutoffs: GcCutoffs {
9784 2 : time: Lsn(0x10),
9785 2 : space: Lsn(0x10),
9786 2 : },
9787 2 : leases: Default::default(),
9788 2 : within_ancestor_pitr: false,
9789 2 : };
9790 2 : }
9791 2 :
9792 2 : {
9793 2 : branch_tline
9794 2 : .latest_gc_cutoff_lsn
9795 2 : .lock_for_write()
9796 2 : .store_and_unlock(Lsn(0x50))
9797 2 : .wait()
9798 2 : .await;
9799 2 : // Update GC info
9800 2 : let mut guard = branch_tline.gc_info.write().unwrap();
9801 2 : *guard = GcInfo {
9802 2 : retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
9803 2 : cutoffs: GcCutoffs {
9804 2 : time: Lsn(0x50),
9805 2 : space: Lsn(0x50),
9806 2 : },
9807 2 : leases: Default::default(),
9808 2 : within_ancestor_pitr: false,
9809 2 : };
9810 2 : }
9811 2 :
9812 2 : let expected_result_at_gc_horizon = [
9813 2 : Bytes::from_static(b"value 0@0x10"),
9814 2 : Bytes::from_static(b"value 1@0x10@0x20"),
9815 2 : Bytes::from_static(b"value 2@0x10@0x30"),
9816 2 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
9817 2 : Bytes::from_static(b"value 4@0x10"),
9818 2 : Bytes::from_static(b"value 5@0x10@0x20"),
9819 2 : Bytes::from_static(b"value 6@0x10@0x20"),
9820 2 : Bytes::from_static(b"value 7@0x10"),
9821 2 : Bytes::from_static(b"value 8@0x10@0x48"),
9822 2 : Bytes::from_static(b"value 9@0x10@0x48"),
9823 2 : ];
9824 2 :
9825 2 : let expected_result_at_lsn_40 = [
9826 2 : Bytes::from_static(b"value 0@0x10"),
9827 2 : Bytes::from_static(b"value 1@0x10@0x20"),
9828 2 : Bytes::from_static(b"value 2@0x10@0x30"),
9829 2 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
9830 2 : Bytes::from_static(b"value 4@0x10"),
9831 2 : Bytes::from_static(b"value 5@0x10@0x20"),
9832 2 : Bytes::from_static(b"value 6@0x10@0x20"),
9833 2 : Bytes::from_static(b"value 7@0x10"),
9834 2 : Bytes::from_static(b"value 8@0x10"),
9835 2 : Bytes::from_static(b"value 9@0x10"),
9836 2 : ];
9837 2 :
9838 6 : let verify_result = || async {
9839 66 : for idx in 0..10 {
9840 60 : assert_eq!(
9841 60 : branch_tline
9842 60 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9843 60 : .await
9844 60 : .unwrap(),
9845 60 : &expected_result_at_gc_horizon[idx]
9846 2 : );
9847 60 : assert_eq!(
9848 60 : branch_tline
9849 60 : .get(get_key(idx as u32), Lsn(0x40), &ctx)
9850 60 : .await
9851 60 : .unwrap(),
9852 60 : &expected_result_at_lsn_40[idx]
9853 2 : );
9854 2 : }
9855 12 : };
9856 2 :
9857 2 : verify_result().await;
9858 2 :
9859 2 : let cancel = CancellationToken::new();
9860 2 : branch_tline
9861 2 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9862 2 : .await
9863 2 : .unwrap();
9864 2 :
9865 2 : verify_result().await;
9866 2 :
9867 2 : // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
9868 2 : // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
9869 2 : branch_tline
9870 2 : .compact_with_gc(
9871 2 : &cancel,
9872 2 : CompactOptions {
9873 2 : compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
9874 2 : ..Default::default()
9875 2 : },
9876 2 : &ctx,
9877 2 : )
9878 2 : .await
9879 2 : .unwrap();
9880 2 :
9881 2 : verify_result().await;
9882 2 :
9883 2 : Ok(())
9884 2 : }
9885 :
9886 : // Regression test for https://github.com/neondatabase/neon/issues/9012
9887 : // Create an image arrangement where we have to read at different LSN ranges
9888 : // from a delta layer. This is achieved by overlapping an image layer on top of
9889 : // a delta layer. Like so:
9890 : //
9891 : // A B
9892 : // +----------------+ -> delta_layer
9893 : // | | ^ lsn
9894 : // | =========|-> nested_image_layer |
9895 : // | C | |
9896 : // +----------------+ |
9897 : // ======== -> baseline_image_layer +-------> key
9898 : //
9899 : //
9900 : // When querying the key range [A, B) we need to read at different LSN ranges
9901 : // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
9902 : #[cfg(feature = "testing")]
9903 : #[tokio::test]
9904 2 : async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
9905 2 : let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
9906 2 : let (tenant, ctx) = harness.load().await;
9907 2 :
9908 2 : let will_init_keys = [2, 6];
9909 44 : fn get_key(id: u32) -> Key {
9910 44 : let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
9911 44 : key.field6 = id;
9912 44 : key
9913 44 : }
9914 2 :
9915 2 : let mut expected_key_values = HashMap::new();
9916 2 :
9917 2 : let baseline_image_layer_lsn = Lsn(0x10);
9918 2 : let mut baseline_img_layer = Vec::new();
9919 12 : for i in 0..5 {
9920 10 : let key = get_key(i);
9921 10 : let value = format!("value {i}@{baseline_image_layer_lsn}");
9922 10 :
9923 10 : let removed = expected_key_values.insert(key, value.clone());
9924 10 : assert!(removed.is_none());
9925 2 :
9926 10 : baseline_img_layer.push((key, Bytes::from(value)));
9927 2 : }
9928 2 :
9929 2 : let nested_image_layer_lsn = Lsn(0x50);
9930 2 : let mut nested_img_layer = Vec::new();
9931 12 : for i in 5..10 {
9932 10 : let key = get_key(i);
9933 10 : let value = format!("value {i}@{nested_image_layer_lsn}");
9934 10 :
9935 10 : let removed = expected_key_values.insert(key, value.clone());
9936 10 : assert!(removed.is_none());
9937 2 :
9938 10 : nested_img_layer.push((key, Bytes::from(value)));
9939 2 : }
9940 2 :
9941 2 : let mut delta_layer_spec = Vec::default();
9942 2 : let delta_layer_start_lsn = Lsn(0x20);
9943 2 : let mut delta_layer_end_lsn = delta_layer_start_lsn;
9944 2 :
9945 22 : for i in 0..10 {
9946 20 : let key = get_key(i);
9947 20 : let key_in_nested = nested_img_layer
9948 20 : .iter()
9949 80 : .any(|(key_with_img, _)| *key_with_img == key);
9950 20 : let lsn = {
9951 20 : if key_in_nested {
9952 10 : Lsn(nested_image_layer_lsn.0 + 0x10)
9953 2 : } else {
9954 10 : delta_layer_start_lsn
9955 2 : }
9956 2 : };
9957 2 :
9958 20 : let will_init = will_init_keys.contains(&i);
9959 20 : if will_init {
9960 4 : delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
9961 4 :
9962 4 : expected_key_values.insert(key, "".to_string());
9963 16 : } else {
9964 16 : let delta = format!("@{lsn}");
9965 16 : delta_layer_spec.push((
9966 16 : key,
9967 16 : lsn,
9968 16 : Value::WalRecord(NeonWalRecord::wal_append(&delta)),
9969 16 : ));
9970 16 :
9971 16 : expected_key_values
9972 16 : .get_mut(&key)
9973 16 : .expect("An image exists for each key")
9974 16 : .push_str(delta.as_str());
9975 16 : }
9976 20 : delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
9977 2 : }
9978 2 :
9979 2 : delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
9980 2 :
9981 2 : assert!(
9982 2 : nested_image_layer_lsn > delta_layer_start_lsn
9983 2 : && nested_image_layer_lsn < delta_layer_end_lsn
9984 2 : );
9985 2 :
9986 2 : let tline = tenant
9987 2 : .create_test_timeline_with_layers(
9988 2 : TIMELINE_ID,
9989 2 : baseline_image_layer_lsn,
9990 2 : DEFAULT_PG_VERSION,
9991 2 : &ctx,
9992 2 : vec![DeltaLayerTestDesc::new_with_inferred_key_range(
9993 2 : delta_layer_start_lsn..delta_layer_end_lsn,
9994 2 : delta_layer_spec,
9995 2 : )], // delta layers
9996 2 : vec![
9997 2 : (baseline_image_layer_lsn, baseline_img_layer),
9998 2 : (nested_image_layer_lsn, nested_img_layer),
9999 2 : ], // image layers
10000 2 : delta_layer_end_lsn,
10001 2 : )
10002 2 : .await?;
10003 2 :
10004 2 : let keyspace = KeySpace::single(get_key(0)..get_key(10));
10005 2 : let results = tline
10006 2 : .get_vectored(keyspace, delta_layer_end_lsn, &ctx)
10007 2 : .await
10008 2 : .expect("No vectored errors");
10009 22 : for (key, res) in results {
10010 20 : let value = res.expect("No key errors");
10011 20 : let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
10012 20 : assert_eq!(value, Bytes::from(expected_value));
10013 2 : }
10014 2 :
10015 2 : Ok(())
10016 2 : }
10017 :
10018 214 : fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
10019 214 : (
10020 214 : k1.is_delta,
10021 214 : k1.key_range.start,
10022 214 : k1.key_range.end,
10023 214 : k1.lsn_range.start,
10024 214 : k1.lsn_range.end,
10025 214 : )
10026 214 : .cmp(&(
10027 214 : k2.is_delta,
10028 214 : k2.key_range.start,
10029 214 : k2.key_range.end,
10030 214 : k2.lsn_range.start,
10031 214 : k2.lsn_range.end,
10032 214 : ))
10033 214 : }
10034 :
10035 24 : async fn inspect_and_sort(
10036 24 : tline: &Arc<Timeline>,
10037 24 : filter: Option<std::ops::Range<Key>>,
10038 24 : ) -> Vec<PersistentLayerKey> {
10039 24 : let mut all_layers = tline.inspect_historic_layers().await.unwrap();
10040 24 : if let Some(filter) = filter {
10041 108 : all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
10042 22 : }
10043 24 : all_layers.sort_by(sort_layer_key);
10044 24 : all_layers
10045 24 : }
10046 :
10047 : #[cfg(feature = "testing")]
10048 22 : fn check_layer_map_key_eq(
10049 22 : mut left: Vec<PersistentLayerKey>,
10050 22 : mut right: Vec<PersistentLayerKey>,
10051 22 : ) {
10052 22 : left.sort_by(sort_layer_key);
10053 22 : right.sort_by(sort_layer_key);
10054 22 : if left != right {
10055 0 : eprintln!("---LEFT---");
10056 0 : for left in left.iter() {
10057 0 : eprintln!("{}", left);
10058 0 : }
10059 0 : eprintln!("---RIGHT---");
10060 0 : for right in right.iter() {
10061 0 : eprintln!("{}", right);
10062 0 : }
10063 0 : assert_eq!(left, right);
10064 22 : }
10065 22 : }
10066 :
10067 : #[cfg(feature = "testing")]
10068 : #[tokio::test]
10069 2 : async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
10070 2 : let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
10071 2 : let (tenant, ctx) = harness.load().await;
10072 2 :
10073 182 : fn get_key(id: u32) -> Key {
10074 182 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
10075 182 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
10076 182 : key.field6 = id;
10077 182 : key
10078 182 : }
10079 2 :
10080 2 : // img layer at 0x10
10081 2 : let img_layer = (0..10)
10082 20 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10083 2 : .collect_vec();
10084 2 :
10085 2 : let delta1 = vec![
10086 2 : (
10087 2 : get_key(1),
10088 2 : Lsn(0x20),
10089 2 : Value::Image(Bytes::from("value 1@0x20")),
10090 2 : ),
10091 2 : (
10092 2 : get_key(2),
10093 2 : Lsn(0x30),
10094 2 : Value::Image(Bytes::from("value 2@0x30")),
10095 2 : ),
10096 2 : (
10097 2 : get_key(3),
10098 2 : Lsn(0x40),
10099 2 : Value::Image(Bytes::from("value 3@0x40")),
10100 2 : ),
10101 2 : ];
10102 2 : let delta2 = vec![
10103 2 : (
10104 2 : get_key(5),
10105 2 : Lsn(0x20),
10106 2 : Value::Image(Bytes::from("value 5@0x20")),
10107 2 : ),
10108 2 : (
10109 2 : get_key(6),
10110 2 : Lsn(0x20),
10111 2 : Value::Image(Bytes::from("value 6@0x20")),
10112 2 : ),
10113 2 : ];
10114 2 : let delta3 = vec![
10115 2 : (
10116 2 : get_key(8),
10117 2 : Lsn(0x48),
10118 2 : Value::Image(Bytes::from("value 8@0x48")),
10119 2 : ),
10120 2 : (
10121 2 : get_key(9),
10122 2 : Lsn(0x48),
10123 2 : Value::Image(Bytes::from("value 9@0x48")),
10124 2 : ),
10125 2 : ];
10126 2 :
10127 2 : let tline = tenant
10128 2 : .create_test_timeline_with_layers(
10129 2 : TIMELINE_ID,
10130 2 : Lsn(0x10),
10131 2 : DEFAULT_PG_VERSION,
10132 2 : &ctx,
10133 2 : vec![
10134 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
10135 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
10136 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
10137 2 : ], // delta layers
10138 2 : vec![(Lsn(0x10), img_layer)], // image layers
10139 2 : Lsn(0x50),
10140 2 : )
10141 2 : .await?;
10142 2 :
10143 2 : {
10144 2 : tline
10145 2 : .latest_gc_cutoff_lsn
10146 2 : .lock_for_write()
10147 2 : .store_and_unlock(Lsn(0x30))
10148 2 : .wait()
10149 2 : .await;
10150 2 : // Update GC info
10151 2 : let mut guard = tline.gc_info.write().unwrap();
10152 2 : *guard = GcInfo {
10153 2 : retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
10154 2 : cutoffs: GcCutoffs {
10155 2 : time: Lsn(0x30),
10156 2 : space: Lsn(0x30),
10157 2 : },
10158 2 : leases: Default::default(),
10159 2 : within_ancestor_pitr: false,
10160 2 : };
10161 2 : }
10162 2 :
10163 2 : let cancel = CancellationToken::new();
10164 2 :
10165 2 : // Do a partial compaction on key range 0..2
10166 2 : tline
10167 2 : .compact_with_gc(
10168 2 : &cancel,
10169 2 : CompactOptions {
10170 2 : flags: EnumSet::new(),
10171 2 : compact_key_range: Some((get_key(0)..get_key(2)).into()),
10172 2 : ..Default::default()
10173 2 : },
10174 2 : &ctx,
10175 2 : )
10176 2 : .await
10177 2 : .unwrap();
10178 2 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10179 2 : check_layer_map_key_eq(
10180 2 : all_layers,
10181 2 : vec![
10182 2 : // newly-generated image layer for the partial compaction range 0-2
10183 2 : PersistentLayerKey {
10184 2 : key_range: get_key(0)..get_key(2),
10185 2 : lsn_range: Lsn(0x20)..Lsn(0x21),
10186 2 : is_delta: false,
10187 2 : },
10188 2 : PersistentLayerKey {
10189 2 : key_range: get_key(0)..get_key(10),
10190 2 : lsn_range: Lsn(0x10)..Lsn(0x11),
10191 2 : is_delta: false,
10192 2 : },
10193 2 : // delta1 is split and the second part is rewritten
10194 2 : PersistentLayerKey {
10195 2 : key_range: get_key(2)..get_key(4),
10196 2 : lsn_range: Lsn(0x20)..Lsn(0x48),
10197 2 : is_delta: true,
10198 2 : },
10199 2 : PersistentLayerKey {
10200 2 : key_range: get_key(5)..get_key(7),
10201 2 : lsn_range: Lsn(0x20)..Lsn(0x48),
10202 2 : is_delta: true,
10203 2 : },
10204 2 : PersistentLayerKey {
10205 2 : key_range: get_key(8)..get_key(10),
10206 2 : lsn_range: Lsn(0x48)..Lsn(0x50),
10207 2 : is_delta: true,
10208 2 : },
10209 2 : ],
10210 2 : );
10211 2 :
10212 2 : // Do a partial compaction on key range 2..4
10213 2 : tline
10214 2 : .compact_with_gc(
10215 2 : &cancel,
10216 2 : CompactOptions {
10217 2 : flags: EnumSet::new(),
10218 2 : compact_key_range: Some((get_key(2)..get_key(4)).into()),
10219 2 : ..Default::default()
10220 2 : },
10221 2 : &ctx,
10222 2 : )
10223 2 : .await
10224 2 : .unwrap();
10225 2 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10226 2 : check_layer_map_key_eq(
10227 2 : all_layers,
10228 2 : vec![
10229 2 : PersistentLayerKey {
10230 2 : key_range: get_key(0)..get_key(2),
10231 2 : lsn_range: Lsn(0x20)..Lsn(0x21),
10232 2 : is_delta: false,
10233 2 : },
10234 2 : PersistentLayerKey {
10235 2 : key_range: get_key(0)..get_key(10),
10236 2 : lsn_range: Lsn(0x10)..Lsn(0x11),
10237 2 : is_delta: false,
10238 2 : },
10239 2 : // image layer generated for the compaction range 2-4
10240 2 : PersistentLayerKey {
10241 2 : key_range: get_key(2)..get_key(4),
10242 2 : lsn_range: Lsn(0x20)..Lsn(0x21),
10243 2 : is_delta: false,
10244 2 : },
10245 2 : // we have key2/key3 above the retain_lsn, so we still need this delta layer
10246 2 : PersistentLayerKey {
10247 2 : key_range: get_key(2)..get_key(4),
10248 2 : lsn_range: Lsn(0x20)..Lsn(0x48),
10249 2 : is_delta: true,
10250 2 : },
10251 2 : PersistentLayerKey {
10252 2 : key_range: get_key(5)..get_key(7),
10253 2 : lsn_range: Lsn(0x20)..Lsn(0x48),
10254 2 : is_delta: true,
10255 2 : },
10256 2 : PersistentLayerKey {
10257 2 : key_range: get_key(8)..get_key(10),
10258 2 : lsn_range: Lsn(0x48)..Lsn(0x50),
10259 2 : is_delta: true,
10260 2 : },
10261 2 : ],
10262 2 : );
10263 2 :
10264 2 : // Do a partial compaction on key range 4..9
10265 2 : tline
10266 2 : .compact_with_gc(
10267 2 : &cancel,
10268 2 : CompactOptions {
10269 2 : flags: EnumSet::new(),
10270 2 : compact_key_range: Some((get_key(4)..get_key(9)).into()),
10271 2 : ..Default::default()
10272 2 : },
10273 2 : &ctx,
10274 2 : )
10275 2 : .await
10276 2 : .unwrap();
10277 2 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10278 2 : check_layer_map_key_eq(
10279 2 : all_layers,
10280 2 : vec![
10281 2 : PersistentLayerKey {
10282 2 : key_range: get_key(0)..get_key(2),
10283 2 : lsn_range: Lsn(0x20)..Lsn(0x21),
10284 2 : is_delta: false,
10285 2 : },
10286 2 : PersistentLayerKey {
10287 2 : key_range: get_key(0)..get_key(10),
10288 2 : lsn_range: Lsn(0x10)..Lsn(0x11),
10289 2 : is_delta: false,
10290 2 : },
10291 2 : PersistentLayerKey {
10292 2 : key_range: get_key(2)..get_key(4),
10293 2 : lsn_range: Lsn(0x20)..Lsn(0x21),
10294 2 : is_delta: false,
10295 2 : },
10296 2 : PersistentLayerKey {
10297 2 : key_range: get_key(2)..get_key(4),
10298 2 : lsn_range: Lsn(0x20)..Lsn(0x48),
10299 2 : is_delta: true,
10300 2 : },
10301 2 : // image layer generated for this compaction range
10302 2 : PersistentLayerKey {
10303 2 : key_range: get_key(4)..get_key(9),
10304 2 : lsn_range: Lsn(0x20)..Lsn(0x21),
10305 2 : is_delta: false,
10306 2 : },
10307 2 : PersistentLayerKey {
10308 2 : key_range: get_key(8)..get_key(10),
10309 2 : lsn_range: Lsn(0x48)..Lsn(0x50),
10310 2 : is_delta: true,
10311 2 : },
10312 2 : ],
10313 2 : );
10314 2 :
10315 2 : // Do a partial compaction on key range 9..10
10316 2 : tline
10317 2 : .compact_with_gc(
10318 2 : &cancel,
10319 2 : CompactOptions {
10320 2 : flags: EnumSet::new(),
10321 2 : compact_key_range: Some((get_key(9)..get_key(10)).into()),
10322 2 : ..Default::default()
10323 2 : },
10324 2 : &ctx,
10325 2 : )
10326 2 : .await
10327 2 : .unwrap();
10328 2 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10329 2 : check_layer_map_key_eq(
10330 2 : all_layers,
10331 2 : vec![
10332 2 : PersistentLayerKey {
10333 2 : key_range: get_key(0)..get_key(2),
10334 2 : lsn_range: Lsn(0x20)..Lsn(0x21),
10335 2 : is_delta: false,
10336 2 : },
10337 2 : PersistentLayerKey {
10338 2 : key_range: get_key(0)..get_key(10),
10339 2 : lsn_range: Lsn(0x10)..Lsn(0x11),
10340 2 : is_delta: false,
10341 2 : },
10342 2 : PersistentLayerKey {
10343 2 : key_range: get_key(2)..get_key(4),
10344 2 : lsn_range: Lsn(0x20)..Lsn(0x21),
10345 2 : is_delta: false,
10346 2 : },
10347 2 : PersistentLayerKey {
10348 2 : key_range: get_key(2)..get_key(4),
10349 2 : lsn_range: Lsn(0x20)..Lsn(0x48),
10350 2 : is_delta: true,
10351 2 : },
10352 2 : PersistentLayerKey {
10353 2 : key_range: get_key(4)..get_key(9),
10354 2 : lsn_range: Lsn(0x20)..Lsn(0x21),
10355 2 : is_delta: false,
10356 2 : },
10357 2 : // image layer generated for the compaction range
10358 2 : PersistentLayerKey {
10359 2 : key_range: get_key(9)..get_key(10),
10360 2 : lsn_range: Lsn(0x20)..Lsn(0x21),
10361 2 : is_delta: false,
10362 2 : },
10363 2 : PersistentLayerKey {
10364 2 : key_range: get_key(8)..get_key(10),
10365 2 : lsn_range: Lsn(0x48)..Lsn(0x50),
10366 2 : is_delta: true,
10367 2 : },
10368 2 : ],
10369 2 : );
10370 2 :
10371 2 : // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
10372 2 : tline
10373 2 : .compact_with_gc(
10374 2 : &cancel,
10375 2 : CompactOptions {
10376 2 : flags: EnumSet::new(),
10377 2 : compact_key_range: Some((get_key(0)..get_key(10)).into()),
10378 2 : ..Default::default()
10379 2 : },
10380 2 : &ctx,
10381 2 : )
10382 2 : .await
10383 2 : .unwrap();
10384 2 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10385 2 : check_layer_map_key_eq(
10386 2 : all_layers,
10387 2 : vec![
10388 2 : // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
10389 2 : PersistentLayerKey {
10390 2 : key_range: get_key(0)..get_key(10),
10391 2 : lsn_range: Lsn(0x20)..Lsn(0x21),
10392 2 : is_delta: false,
10393 2 : },
10394 2 : PersistentLayerKey {
10395 2 : key_range: get_key(2)..get_key(4),
10396 2 : lsn_range: Lsn(0x20)..Lsn(0x48),
10397 2 : is_delta: true,
10398 2 : },
10399 2 : PersistentLayerKey {
10400 2 : key_range: get_key(8)..get_key(10),
10401 2 : lsn_range: Lsn(0x48)..Lsn(0x50),
10402 2 : is_delta: true,
10403 2 : },
10404 2 : ],
10405 2 : );
10406 2 : Ok(())
10407 2 : }
10408 :
10409 : #[cfg(feature = "testing")]
10410 : #[tokio::test]
10411 2 : async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
10412 2 : let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
10413 2 : .await
10414 2 : .unwrap();
10415 2 : let (tenant, ctx) = harness.load().await;
10416 2 : let tline_parent = tenant
10417 2 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
10418 2 : .await
10419 2 : .unwrap();
10420 2 : let tline_child = tenant
10421 2 : .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
10422 2 : .await
10423 2 : .unwrap();
10424 2 : {
10425 2 : let gc_info_parent = tline_parent.gc_info.read().unwrap();
10426 2 : assert_eq!(
10427 2 : gc_info_parent.retain_lsns,
10428 2 : vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
10429 2 : );
10430 2 : }
10431 2 : // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
10432 2 : tline_child
10433 2 : .remote_client
10434 2 : .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
10435 2 : .unwrap();
10436 2 : tline_child.remote_client.wait_completion().await.unwrap();
10437 2 : offload_timeline(&tenant, &tline_child)
10438 2 : .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
10439 2 : .await.unwrap();
10440 2 : let child_timeline_id = tline_child.timeline_id;
10441 2 : Arc::try_unwrap(tline_child).unwrap();
10442 2 :
10443 2 : {
10444 2 : let gc_info_parent = tline_parent.gc_info.read().unwrap();
10445 2 : assert_eq!(
10446 2 : gc_info_parent.retain_lsns,
10447 2 : vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
10448 2 : );
10449 2 : }
10450 2 :
10451 2 : tenant
10452 2 : .get_offloaded_timeline(child_timeline_id)
10453 2 : .unwrap()
10454 2 : .defuse_for_tenant_drop();
10455 2 :
10456 2 : Ok(())
10457 2 : }
10458 :
10459 : #[cfg(feature = "testing")]
10460 : #[tokio::test]
10461 2 : async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
10462 2 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
10463 2 : let (tenant, ctx) = harness.load().await;
10464 2 :
10465 296 : fn get_key(id: u32) -> Key {
10466 296 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
10467 296 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
10468 296 : key.field6 = id;
10469 296 : key
10470 296 : }
10471 2 :
10472 2 : let img_layer = (0..10)
10473 20 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10474 2 : .collect_vec();
10475 2 :
10476 2 : let delta1 = vec![(
10477 2 : get_key(1),
10478 2 : Lsn(0x20),
10479 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10480 2 : )];
10481 2 : let delta4 = vec![(
10482 2 : get_key(1),
10483 2 : Lsn(0x28),
10484 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
10485 2 : )];
10486 2 : let delta2 = vec![
10487 2 : (
10488 2 : get_key(1),
10489 2 : Lsn(0x30),
10490 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
10491 2 : ),
10492 2 : (
10493 2 : get_key(1),
10494 2 : Lsn(0x38),
10495 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
10496 2 : ),
10497 2 : ];
10498 2 : let delta3 = vec![
10499 2 : (
10500 2 : get_key(8),
10501 2 : Lsn(0x48),
10502 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10503 2 : ),
10504 2 : (
10505 2 : get_key(9),
10506 2 : Lsn(0x48),
10507 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10508 2 : ),
10509 2 : ];
10510 2 :
10511 2 : let tline = tenant
10512 2 : .create_test_timeline_with_layers(
10513 2 : TIMELINE_ID,
10514 2 : Lsn(0x10),
10515 2 : DEFAULT_PG_VERSION,
10516 2 : &ctx,
10517 2 : vec![
10518 2 : // delta1/2/4 only contain a single key but multiple updates
10519 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
10520 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
10521 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
10522 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
10523 2 : ], // delta layers
10524 2 : vec![(Lsn(0x10), img_layer)], // image layers
10525 2 : Lsn(0x50),
10526 2 : )
10527 2 : .await?;
10528 2 : {
10529 2 : tline
10530 2 : .latest_gc_cutoff_lsn
10531 2 : .lock_for_write()
10532 2 : .store_and_unlock(Lsn(0x30))
10533 2 : .wait()
10534 2 : .await;
10535 2 : // Update GC info
10536 2 : let mut guard = tline.gc_info.write().unwrap();
10537 2 : *guard = GcInfo {
10538 2 : retain_lsns: vec![
10539 2 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
10540 2 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
10541 2 : ],
10542 2 : cutoffs: GcCutoffs {
10543 2 : time: Lsn(0x30),
10544 2 : space: Lsn(0x30),
10545 2 : },
10546 2 : leases: Default::default(),
10547 2 : within_ancestor_pitr: false,
10548 2 : };
10549 2 : }
10550 2 :
10551 2 : let expected_result = [
10552 2 : Bytes::from_static(b"value 0@0x10"),
10553 2 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
10554 2 : Bytes::from_static(b"value 2@0x10"),
10555 2 : Bytes::from_static(b"value 3@0x10"),
10556 2 : Bytes::from_static(b"value 4@0x10"),
10557 2 : Bytes::from_static(b"value 5@0x10"),
10558 2 : Bytes::from_static(b"value 6@0x10"),
10559 2 : Bytes::from_static(b"value 7@0x10"),
10560 2 : Bytes::from_static(b"value 8@0x10@0x48"),
10561 2 : Bytes::from_static(b"value 9@0x10@0x48"),
10562 2 : ];
10563 2 :
10564 2 : let expected_result_at_gc_horizon = [
10565 2 : Bytes::from_static(b"value 0@0x10"),
10566 2 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
10567 2 : Bytes::from_static(b"value 2@0x10"),
10568 2 : Bytes::from_static(b"value 3@0x10"),
10569 2 : Bytes::from_static(b"value 4@0x10"),
10570 2 : Bytes::from_static(b"value 5@0x10"),
10571 2 : Bytes::from_static(b"value 6@0x10"),
10572 2 : Bytes::from_static(b"value 7@0x10"),
10573 2 : Bytes::from_static(b"value 8@0x10"),
10574 2 : Bytes::from_static(b"value 9@0x10"),
10575 2 : ];
10576 2 :
10577 2 : let expected_result_at_lsn_20 = [
10578 2 : Bytes::from_static(b"value 0@0x10"),
10579 2 : Bytes::from_static(b"value 1@0x10@0x20"),
10580 2 : Bytes::from_static(b"value 2@0x10"),
10581 2 : Bytes::from_static(b"value 3@0x10"),
10582 2 : Bytes::from_static(b"value 4@0x10"),
10583 2 : Bytes::from_static(b"value 5@0x10"),
10584 2 : Bytes::from_static(b"value 6@0x10"),
10585 2 : Bytes::from_static(b"value 7@0x10"),
10586 2 : Bytes::from_static(b"value 8@0x10"),
10587 2 : Bytes::from_static(b"value 9@0x10"),
10588 2 : ];
10589 2 :
10590 2 : let expected_result_at_lsn_10 = [
10591 2 : Bytes::from_static(b"value 0@0x10"),
10592 2 : Bytes::from_static(b"value 1@0x10"),
10593 2 : Bytes::from_static(b"value 2@0x10"),
10594 2 : Bytes::from_static(b"value 3@0x10"),
10595 2 : Bytes::from_static(b"value 4@0x10"),
10596 2 : Bytes::from_static(b"value 5@0x10"),
10597 2 : Bytes::from_static(b"value 6@0x10"),
10598 2 : Bytes::from_static(b"value 7@0x10"),
10599 2 : Bytes::from_static(b"value 8@0x10"),
10600 2 : Bytes::from_static(b"value 9@0x10"),
10601 2 : ];
10602 2 :
10603 6 : let verify_result = || async {
10604 6 : let gc_horizon = {
10605 6 : let gc_info = tline.gc_info.read().unwrap();
10606 6 : gc_info.cutoffs.time
10607 2 : };
10608 66 : for idx in 0..10 {
10609 60 : assert_eq!(
10610 60 : tline
10611 60 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
10612 60 : .await
10613 60 : .unwrap(),
10614 60 : &expected_result[idx]
10615 2 : );
10616 60 : assert_eq!(
10617 60 : tline
10618 60 : .get(get_key(idx as u32), gc_horizon, &ctx)
10619 60 : .await
10620 60 : .unwrap(),
10621 60 : &expected_result_at_gc_horizon[idx]
10622 2 : );
10623 60 : assert_eq!(
10624 60 : tline
10625 60 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
10626 60 : .await
10627 60 : .unwrap(),
10628 60 : &expected_result_at_lsn_20[idx]
10629 2 : );
10630 60 : assert_eq!(
10631 60 : tline
10632 60 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
10633 60 : .await
10634 60 : .unwrap(),
10635 60 : &expected_result_at_lsn_10[idx]
10636 2 : );
10637 2 : }
10638 12 : };
10639 2 :
10640 2 : verify_result().await;
10641 2 :
10642 2 : let cancel = CancellationToken::new();
10643 2 : tline
10644 2 : .compact_with_gc(
10645 2 : &cancel,
10646 2 : CompactOptions {
10647 2 : compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
10648 2 : ..Default::default()
10649 2 : },
10650 2 : &ctx,
10651 2 : )
10652 2 : .await
10653 2 : .unwrap();
10654 2 : verify_result().await;
10655 2 :
10656 2 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10657 2 : check_layer_map_key_eq(
10658 2 : all_layers,
10659 2 : vec![
10660 2 : // The original image layer, not compacted
10661 2 : PersistentLayerKey {
10662 2 : key_range: get_key(0)..get_key(10),
10663 2 : lsn_range: Lsn(0x10)..Lsn(0x11),
10664 2 : is_delta: false,
10665 2 : },
10666 2 : // Delta layer below the specified above_lsn not compacted
10667 2 : PersistentLayerKey {
10668 2 : key_range: get_key(1)..get_key(2),
10669 2 : lsn_range: Lsn(0x20)..Lsn(0x28),
10670 2 : is_delta: true,
10671 2 : },
10672 2 : // Delta layer compacted above the LSN
10673 2 : PersistentLayerKey {
10674 2 : key_range: get_key(1)..get_key(10),
10675 2 : lsn_range: Lsn(0x28)..Lsn(0x50),
10676 2 : is_delta: true,
10677 2 : },
10678 2 : ],
10679 2 : );
10680 2 :
10681 2 : // compact again
10682 2 : tline
10683 2 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
10684 2 : .await
10685 2 : .unwrap();
10686 2 : verify_result().await;
10687 2 :
10688 2 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10689 2 : check_layer_map_key_eq(
10690 2 : all_layers,
10691 2 : vec![
10692 2 : // The compacted image layer (full key range)
10693 2 : PersistentLayerKey {
10694 2 : key_range: Key::MIN..Key::MAX,
10695 2 : lsn_range: Lsn(0x10)..Lsn(0x11),
10696 2 : is_delta: false,
10697 2 : },
10698 2 : // All other data in the delta layer
10699 2 : PersistentLayerKey {
10700 2 : key_range: get_key(1)..get_key(10),
10701 2 : lsn_range: Lsn(0x10)..Lsn(0x50),
10702 2 : is_delta: true,
10703 2 : },
10704 2 : ],
10705 2 : );
10706 2 :
10707 2 : Ok(())
10708 2 : }
10709 :
10710 : #[cfg(feature = "testing")]
10711 : #[tokio::test]
10712 2 : async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
10713 2 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
10714 2 : let (tenant, ctx) = harness.load().await;
10715 2 :
10716 508 : fn get_key(id: u32) -> Key {
10717 508 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
10718 508 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
10719 508 : key.field6 = id;
10720 508 : key
10721 508 : }
10722 2 :
10723 2 : let img_layer = (0..10)
10724 20 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10725 2 : .collect_vec();
10726 2 :
10727 2 : let delta1 = vec![(
10728 2 : get_key(1),
10729 2 : Lsn(0x20),
10730 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10731 2 : )];
10732 2 : let delta4 = vec![(
10733 2 : get_key(1),
10734 2 : Lsn(0x28),
10735 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
10736 2 : )];
10737 2 : let delta2 = vec![
10738 2 : (
10739 2 : get_key(1),
10740 2 : Lsn(0x30),
10741 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
10742 2 : ),
10743 2 : (
10744 2 : get_key(1),
10745 2 : Lsn(0x38),
10746 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
10747 2 : ),
10748 2 : ];
10749 2 : let delta3 = vec![
10750 2 : (
10751 2 : get_key(8),
10752 2 : Lsn(0x48),
10753 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10754 2 : ),
10755 2 : (
10756 2 : get_key(9),
10757 2 : Lsn(0x48),
10758 2 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10759 2 : ),
10760 2 : ];
10761 2 :
10762 2 : let tline = tenant
10763 2 : .create_test_timeline_with_layers(
10764 2 : TIMELINE_ID,
10765 2 : Lsn(0x10),
10766 2 : DEFAULT_PG_VERSION,
10767 2 : &ctx,
10768 2 : vec![
10769 2 : // delta1/2/4 only contain a single key but multiple updates
10770 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
10771 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
10772 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
10773 2 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
10774 2 : ], // delta layers
10775 2 : vec![(Lsn(0x10), img_layer)], // image layers
10776 2 : Lsn(0x50),
10777 2 : )
10778 2 : .await?;
10779 2 : {
10780 2 : tline
10781 2 : .latest_gc_cutoff_lsn
10782 2 : .lock_for_write()
10783 2 : .store_and_unlock(Lsn(0x30))
10784 2 : .wait()
10785 2 : .await;
10786 2 : // Update GC info
10787 2 : let mut guard = tline.gc_info.write().unwrap();
10788 2 : *guard = GcInfo {
10789 2 : retain_lsns: vec![
10790 2 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
10791 2 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
10792 2 : ],
10793 2 : cutoffs: GcCutoffs {
10794 2 : time: Lsn(0x30),
10795 2 : space: Lsn(0x30),
10796 2 : },
10797 2 : leases: Default::default(),
10798 2 : within_ancestor_pitr: false,
10799 2 : };
10800 2 : }
10801 2 :
10802 2 : let expected_result = [
10803 2 : Bytes::from_static(b"value 0@0x10"),
10804 2 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
10805 2 : Bytes::from_static(b"value 2@0x10"),
10806 2 : Bytes::from_static(b"value 3@0x10"),
10807 2 : Bytes::from_static(b"value 4@0x10"),
10808 2 : Bytes::from_static(b"value 5@0x10"),
10809 2 : Bytes::from_static(b"value 6@0x10"),
10810 2 : Bytes::from_static(b"value 7@0x10"),
10811 2 : Bytes::from_static(b"value 8@0x10@0x48"),
10812 2 : Bytes::from_static(b"value 9@0x10@0x48"),
10813 2 : ];
10814 2 :
10815 2 : let expected_result_at_gc_horizon = [
10816 2 : Bytes::from_static(b"value 0@0x10"),
10817 2 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
10818 2 : Bytes::from_static(b"value 2@0x10"),
10819 2 : Bytes::from_static(b"value 3@0x10"),
10820 2 : Bytes::from_static(b"value 4@0x10"),
10821 2 : Bytes::from_static(b"value 5@0x10"),
10822 2 : Bytes::from_static(b"value 6@0x10"),
10823 2 : Bytes::from_static(b"value 7@0x10"),
10824 2 : Bytes::from_static(b"value 8@0x10"),
10825 2 : Bytes::from_static(b"value 9@0x10"),
10826 2 : ];
10827 2 :
10828 2 : let expected_result_at_lsn_20 = [
10829 2 : Bytes::from_static(b"value 0@0x10"),
10830 2 : Bytes::from_static(b"value 1@0x10@0x20"),
10831 2 : Bytes::from_static(b"value 2@0x10"),
10832 2 : Bytes::from_static(b"value 3@0x10"),
10833 2 : Bytes::from_static(b"value 4@0x10"),
10834 2 : Bytes::from_static(b"value 5@0x10"),
10835 2 : Bytes::from_static(b"value 6@0x10"),
10836 2 : Bytes::from_static(b"value 7@0x10"),
10837 2 : Bytes::from_static(b"value 8@0x10"),
10838 2 : Bytes::from_static(b"value 9@0x10"),
10839 2 : ];
10840 2 :
10841 2 : let expected_result_at_lsn_10 = [
10842 2 : Bytes::from_static(b"value 0@0x10"),
10843 2 : Bytes::from_static(b"value 1@0x10"),
10844 2 : Bytes::from_static(b"value 2@0x10"),
10845 2 : Bytes::from_static(b"value 3@0x10"),
10846 2 : Bytes::from_static(b"value 4@0x10"),
10847 2 : Bytes::from_static(b"value 5@0x10"),
10848 2 : Bytes::from_static(b"value 6@0x10"),
10849 2 : Bytes::from_static(b"value 7@0x10"),
10850 2 : Bytes::from_static(b"value 8@0x10"),
10851 2 : Bytes::from_static(b"value 9@0x10"),
10852 2 : ];
10853 2 :
10854 10 : let verify_result = || async {
10855 10 : let gc_horizon = {
10856 10 : let gc_info = tline.gc_info.read().unwrap();
10857 10 : gc_info.cutoffs.time
10858 2 : };
10859 110 : for idx in 0..10 {
10860 100 : assert_eq!(
10861 100 : tline
10862 100 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
10863 100 : .await
10864 100 : .unwrap(),
10865 100 : &expected_result[idx]
10866 2 : );
10867 100 : assert_eq!(
10868 100 : tline
10869 100 : .get(get_key(idx as u32), gc_horizon, &ctx)
10870 100 : .await
10871 100 : .unwrap(),
10872 100 : &expected_result_at_gc_horizon[idx]
10873 2 : );
10874 100 : assert_eq!(
10875 100 : tline
10876 100 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
10877 100 : .await
10878 100 : .unwrap(),
10879 100 : &expected_result_at_lsn_20[idx]
10880 2 : );
10881 100 : assert_eq!(
10882 100 : tline
10883 100 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
10884 100 : .await
10885 100 : .unwrap(),
10886 100 : &expected_result_at_lsn_10[idx]
10887 2 : );
10888 2 : }
10889 20 : };
10890 2 :
10891 2 : verify_result().await;
10892 2 :
10893 2 : let cancel = CancellationToken::new();
10894 2 :
10895 2 : tline
10896 2 : .compact_with_gc(
10897 2 : &cancel,
10898 2 : CompactOptions {
10899 2 : compact_key_range: Some((get_key(0)..get_key(2)).into()),
10900 2 : compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
10901 2 : ..Default::default()
10902 2 : },
10903 2 : &ctx,
10904 2 : )
10905 2 : .await
10906 2 : .unwrap();
10907 2 : verify_result().await;
10908 2 :
10909 2 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10910 2 : check_layer_map_key_eq(
10911 2 : all_layers,
10912 2 : vec![
10913 2 : // The original image layer, not compacted
10914 2 : PersistentLayerKey {
10915 2 : key_range: get_key(0)..get_key(10),
10916 2 : lsn_range: Lsn(0x10)..Lsn(0x11),
10917 2 : is_delta: false,
10918 2 : },
10919 2 : // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
10920 2 : // the layer 0x28-0x30 into one.
10921 2 : PersistentLayerKey {
10922 2 : key_range: get_key(1)..get_key(2),
10923 2 : lsn_range: Lsn(0x20)..Lsn(0x30),
10924 2 : is_delta: true,
10925 2 : },
10926 2 : // Above the upper bound and untouched
10927 2 : PersistentLayerKey {
10928 2 : key_range: get_key(1)..get_key(2),
10929 2 : lsn_range: Lsn(0x30)..Lsn(0x50),
10930 2 : is_delta: true,
10931 2 : },
10932 2 : // This layer is untouched
10933 2 : PersistentLayerKey {
10934 2 : key_range: get_key(8)..get_key(10),
10935 2 : lsn_range: Lsn(0x30)..Lsn(0x50),
10936 2 : is_delta: true,
10937 2 : },
10938 2 : ],
10939 2 : );
10940 2 :
10941 2 : tline
10942 2 : .compact_with_gc(
10943 2 : &cancel,
10944 2 : CompactOptions {
10945 2 : compact_key_range: Some((get_key(3)..get_key(8)).into()),
10946 2 : compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
10947 2 : ..Default::default()
10948 2 : },
10949 2 : &ctx,
10950 2 : )
10951 2 : .await
10952 2 : .unwrap();
10953 2 : verify_result().await;
10954 2 :
10955 2 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10956 2 : check_layer_map_key_eq(
10957 2 : all_layers,
10958 2 : vec![
10959 2 : // The original image layer, not compacted
10960 2 : PersistentLayerKey {
10961 2 : key_range: get_key(0)..get_key(10),
10962 2 : lsn_range: Lsn(0x10)..Lsn(0x11),
10963 2 : is_delta: false,
10964 2 : },
10965 2 : // Not in the compaction key range, uncompacted
10966 2 : PersistentLayerKey {
10967 2 : key_range: get_key(1)..get_key(2),
10968 2 : lsn_range: Lsn(0x20)..Lsn(0x30),
10969 2 : is_delta: true,
10970 2 : },
10971 2 : // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
10972 2 : PersistentLayerKey {
10973 2 : key_range: get_key(1)..get_key(2),
10974 2 : lsn_range: Lsn(0x30)..Lsn(0x50),
10975 2 : is_delta: true,
10976 2 : },
10977 2 : // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
10978 2 : // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
10979 2 : // becomes 0x50.
10980 2 : PersistentLayerKey {
10981 2 : key_range: get_key(8)..get_key(10),
10982 2 : lsn_range: Lsn(0x30)..Lsn(0x50),
10983 2 : is_delta: true,
10984 2 : },
10985 2 : ],
10986 2 : );
10987 2 :
10988 2 : // compact again
10989 2 : tline
10990 2 : .compact_with_gc(
10991 2 : &cancel,
10992 2 : CompactOptions {
10993 2 : compact_key_range: Some((get_key(0)..get_key(5)).into()),
10994 2 : compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
10995 2 : ..Default::default()
10996 2 : },
10997 2 : &ctx,
10998 2 : )
10999 2 : .await
11000 2 : .unwrap();
11001 2 : verify_result().await;
11002 2 :
11003 2 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11004 2 : check_layer_map_key_eq(
11005 2 : all_layers,
11006 2 : vec![
11007 2 : // The original image layer, not compacted
11008 2 : PersistentLayerKey {
11009 2 : key_range: get_key(0)..get_key(10),
11010 2 : lsn_range: Lsn(0x10)..Lsn(0x11),
11011 2 : is_delta: false,
11012 2 : },
11013 2 : // The range gets compacted
11014 2 : PersistentLayerKey {
11015 2 : key_range: get_key(1)..get_key(2),
11016 2 : lsn_range: Lsn(0x20)..Lsn(0x50),
11017 2 : is_delta: true,
11018 2 : },
11019 2 : // Not touched during this iteration of compaction
11020 2 : PersistentLayerKey {
11021 2 : key_range: get_key(8)..get_key(10),
11022 2 : lsn_range: Lsn(0x30)..Lsn(0x50),
11023 2 : is_delta: true,
11024 2 : },
11025 2 : ],
11026 2 : );
11027 2 :
11028 2 : // final full compaction
11029 2 : tline
11030 2 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
11031 2 : .await
11032 2 : .unwrap();
11033 2 : verify_result().await;
11034 2 :
11035 2 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11036 2 : check_layer_map_key_eq(
11037 2 : all_layers,
11038 2 : vec![
11039 2 : // The compacted image layer (full key range)
11040 2 : PersistentLayerKey {
11041 2 : key_range: Key::MIN..Key::MAX,
11042 2 : lsn_range: Lsn(0x10)..Lsn(0x11),
11043 2 : is_delta: false,
11044 2 : },
11045 2 : // All other data in the delta layer
11046 2 : PersistentLayerKey {
11047 2 : key_range: get_key(1)..get_key(10),
11048 2 : lsn_range: Lsn(0x10)..Lsn(0x50),
11049 2 : is_delta: true,
11050 2 : },
11051 2 : ],
11052 2 : );
11053 2 :
11054 2 : Ok(())
11055 2 : }
11056 : }
|