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 std::collections::hash_map::Entry;
16 : use std::collections::{BTreeMap, HashMap, HashSet};
17 : use std::fmt::{Debug, Display};
18 : use std::fs::File;
19 : use std::future::Future;
20 : use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
21 : use std::sync::{Arc, Mutex, Weak};
22 : use std::time::{Duration, Instant, SystemTime};
23 : use std::{fmt, fs};
24 :
25 : use anyhow::{Context, bail};
26 : use arc_swap::ArcSwap;
27 : use camino::{Utf8Path, Utf8PathBuf};
28 : use chrono::NaiveDateTime;
29 : use enumset::EnumSet;
30 : use futures::StreamExt;
31 : use futures::stream::FuturesUnordered;
32 : use itertools::Itertools as _;
33 : use once_cell::sync::Lazy;
34 : pub use pageserver_api::models::TenantState;
35 : use pageserver_api::models::{self, RelSizeMigration};
36 : use pageserver_api::models::{
37 : CompactInfoResponse, LsnLease, TimelineArchivalState, TimelineState, TopTenantShardItem,
38 : WalRedoManagerStatus,
39 : };
40 : use pageserver_api::shard::{ShardIdentity, ShardStripeSize, TenantShardId};
41 : use remote_storage::{DownloadError, GenericRemoteStorage, TimeoutOrCancel};
42 : use remote_timeline_client::index::GcCompactionState;
43 : use remote_timeline_client::manifest::{
44 : LATEST_TENANT_MANIFEST_VERSION, OffloadedTimelineManifest, TenantManifest,
45 : };
46 : use remote_timeline_client::{
47 : FAILED_REMOTE_OP_RETRIES, FAILED_UPLOAD_WARN_THRESHOLD, UploadQueueNotReadyError,
48 : download_tenant_manifest,
49 : };
50 : use secondary::heatmap::{HeatMapTenant, HeatMapTimeline};
51 : use storage_broker::BrokerClientChannel;
52 : use timeline::compaction::{CompactionOutcome, GcCompactionQueue};
53 : use timeline::offload::{OffloadError, offload_timeline};
54 : use timeline::{
55 : CompactFlags, CompactOptions, CompactionError, PreviousHeatmap, ShutdownMode, import_pgdata,
56 : };
57 : use tokio::io::BufReader;
58 : use tokio::sync::{Notify, Semaphore, watch};
59 : use tokio::task::JoinSet;
60 : use tokio_util::sync::CancellationToken;
61 : use tracing::*;
62 : use upload_queue::NotInitialized;
63 : use utils::circuit_breaker::CircuitBreaker;
64 : use utils::crashsafe::path_with_suffix_extension;
65 : use utils::sync::gate::{Gate, GateGuard};
66 : use utils::timeout::{TimeoutCancellableError, timeout_cancellable};
67 : use utils::try_rcu::ArcSwapExt;
68 : use utils::zstd::{create_zst_tarball, extract_zst_tarball};
69 : use utils::{backoff, completion, failpoint_support, fs_ext, pausable_failpoint};
70 :
71 : use self::config::{AttachedLocationConfig, AttachmentMode, LocationConf};
72 : use self::metadata::TimelineMetadata;
73 : use self::mgr::{GetActiveTenantError, GetTenantError};
74 : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
75 : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
76 : use self::timeline::uninit::{TimelineCreateGuard, TimelineExclusionError, UninitializedTimeline};
77 : use self::timeline::{
78 : EvictionTaskTenantState, GcCutoffs, TimelineDeleteProgress, TimelineResources, WaitLsnError,
79 : };
80 : use crate::config::PageServerConf;
81 : use crate::context;
82 : use crate::context::RequestContextBuilder;
83 : use crate::context::{DownloadBehavior, RequestContext};
84 : use crate::deletion_queue::{DeletionQueueClient, DeletionQueueError};
85 : use crate::l0_flush::L0FlushGlobalState;
86 : use crate::metrics::{
87 : BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN, CONCURRENT_INITDBS,
88 : INITDB_RUN_TIME, INITDB_SEMAPHORE_ACQUISITION_TIME, TENANT, TENANT_STATE_METRIC,
89 : TENANT_SYNTHETIC_SIZE_METRIC, remove_tenant_metrics,
90 : };
91 : use crate::task_mgr::TaskKind;
92 : use crate::tenant::config::LocationMode;
93 : use crate::tenant::gc_result::GcResult;
94 : pub use crate::tenant::remote_timeline_client::index::IndexPart;
95 : use crate::tenant::remote_timeline_client::{
96 : INITDB_PATH, MaybeDeletedIndexPart, remote_initdb_archive_path,
97 : };
98 : use crate::tenant::storage_layer::{DeltaLayer, ImageLayer};
99 : use crate::tenant::timeline::delete::DeleteTimelineFlow;
100 : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
101 : use crate::virtual_file::VirtualFile;
102 : use crate::walingest::WalLagCooldown;
103 : use crate::walredo::{PostgresRedoManager, RedoAttemptType};
104 : use crate::{InitializationOrder, TEMP_FILE_SUFFIX, import_datadir, span, task_mgr, walredo};
105 :
106 0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
107 : use utils::crashsafe;
108 : use utils::generation::Generation;
109 : use utils::id::TimelineId;
110 : use utils::lsn::{Lsn, RecordLsn};
111 :
112 : pub mod blob_io;
113 : pub mod block_io;
114 : pub mod vectored_blob_io;
115 :
116 : pub mod disk_btree;
117 : pub(crate) mod ephemeral_file;
118 : pub mod layer_map;
119 :
120 : pub mod metadata;
121 : pub mod remote_timeline_client;
122 : pub mod storage_layer;
123 :
124 : pub mod checks;
125 : pub mod config;
126 : pub mod mgr;
127 : pub mod secondary;
128 : pub mod tasks;
129 : pub mod upload_queue;
130 :
131 : pub(crate) mod timeline;
132 :
133 : pub mod size;
134 :
135 : mod gc_block;
136 : mod gc_result;
137 : pub(crate) mod throttle;
138 :
139 : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
140 :
141 : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
142 : // re-export for use in walreceiver
143 : pub use crate::tenant::timeline::WalReceiverInfo;
144 :
145 : /// The "tenants" part of `tenants/<tenant>/timelines...`
146 : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
147 :
148 : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
149 : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
150 :
151 : /// References to shared objects that are passed into each tenant, such
152 : /// as the shared remote storage client and process initialization state.
153 : #[derive(Clone)]
154 : pub struct TenantSharedResources {
155 : pub broker_client: storage_broker::BrokerClientChannel,
156 : pub remote_storage: GenericRemoteStorage,
157 : pub deletion_queue_client: DeletionQueueClient,
158 : pub l0_flush_global_state: L0FlushGlobalState,
159 : }
160 :
161 : /// A [`Tenant`] is really an _attached_ tenant. The configuration
162 : /// for an attached tenant is a subset of the [`LocationConf`], represented
163 : /// in this struct.
164 : #[derive(Clone)]
165 : pub(super) struct AttachedTenantConf {
166 : tenant_conf: pageserver_api::models::TenantConfig,
167 : location: AttachedLocationConfig,
168 : /// The deadline before which we are blocked from GC so that
169 : /// leases have a chance to be renewed.
170 : lsn_lease_deadline: Option<tokio::time::Instant>,
171 : }
172 :
173 : impl AttachedTenantConf {
174 460 : fn new(
175 460 : tenant_conf: pageserver_api::models::TenantConfig,
176 460 : location: AttachedLocationConfig,
177 460 : ) -> Self {
178 : // Sets a deadline before which we cannot proceed to GC due to lsn lease.
179 : //
180 : // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
181 : // length, we guarantee that all the leases we granted before will have a chance to renew
182 : // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
183 460 : let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
184 460 : Some(
185 460 : tokio::time::Instant::now()
186 460 : + tenant_conf
187 460 : .lsn_lease_length
188 460 : .unwrap_or(LsnLease::DEFAULT_LENGTH),
189 460 : )
190 : } else {
191 : // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
192 : // because we don't do GC in these modes.
193 0 : None
194 : };
195 :
196 460 : Self {
197 460 : tenant_conf,
198 460 : location,
199 460 : lsn_lease_deadline,
200 460 : }
201 460 : }
202 :
203 460 : fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
204 460 : match &location_conf.mode {
205 460 : LocationMode::Attached(attach_conf) => {
206 460 : Ok(Self::new(location_conf.tenant_conf, *attach_conf))
207 : }
208 : LocationMode::Secondary(_) => {
209 0 : anyhow::bail!(
210 0 : "Attempted to construct AttachedTenantConf from a LocationConf in secondary mode"
211 0 : )
212 : }
213 : }
214 460 : }
215 :
216 1524 : fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
217 1524 : self.lsn_lease_deadline
218 1524 : .map(|d| tokio::time::Instant::now() < d)
219 1524 : .unwrap_or(false)
220 1524 : }
221 : }
222 : struct TimelinePreload {
223 : timeline_id: TimelineId,
224 : client: RemoteTimelineClient,
225 : index_part: Result<MaybeDeletedIndexPart, DownloadError>,
226 : previous_heatmap: Option<PreviousHeatmap>,
227 : }
228 :
229 : pub(crate) struct TenantPreload {
230 : /// The tenant manifest from remote storage, or None if no manifest was found.
231 : tenant_manifest: Option<TenantManifest>,
232 : /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
233 : timelines: HashMap<TimelineId, Option<TimelinePreload>>,
234 : }
235 :
236 : /// When we spawn a tenant, there is a special mode for tenant creation that
237 : /// avoids trying to read anything from remote storage.
238 : pub(crate) enum SpawnMode {
239 : /// Activate as soon as possible
240 : Eager,
241 : /// Lazy activation in the background, with the option to skip the queue if the need comes up
242 : Lazy,
243 : }
244 :
245 : ///
246 : /// Tenant consists of multiple timelines. Keep them in a hash table.
247 : ///
248 : pub struct Tenant {
249 : // Global pageserver config parameters
250 : pub conf: &'static PageServerConf,
251 :
252 : /// The value creation timestamp, used to measure activation delay, see:
253 : /// <https://github.com/neondatabase/neon/issues/4025>
254 : constructed_at: Instant,
255 :
256 : state: watch::Sender<TenantState>,
257 :
258 : // Overridden tenant-specific config parameters.
259 : // We keep pageserver_api::models::TenantConfig sturct here to preserve the information
260 : // about parameters that are not set.
261 : // This is necessary to allow global config updates.
262 : tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
263 :
264 : tenant_shard_id: TenantShardId,
265 :
266 : // The detailed sharding information, beyond the number/count in tenant_shard_id
267 : shard_identity: ShardIdentity,
268 :
269 : /// The remote storage generation, used to protect S3 objects from split-brain.
270 : /// Does not change over the lifetime of the [`Tenant`] object.
271 : ///
272 : /// This duplicates the generation stored in LocationConf, but that structure is mutable:
273 : /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
274 : generation: Generation,
275 :
276 : timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
277 :
278 : /// During timeline creation, we first insert the TimelineId to the
279 : /// creating map, then `timelines`, then remove it from the creating map.
280 : /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
281 : timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
282 :
283 : /// Possibly offloaded and archived timelines
284 : /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
285 : timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
286 :
287 : /// The last tenant manifest known to be in remote storage. None if the manifest has not yet
288 : /// been either downloaded or uploaded. Always Some after tenant attach.
289 : ///
290 : /// Initially populated during tenant attach, updated via `maybe_upload_tenant_manifest`.
291 : ///
292 : /// Do not modify this directly. It is used to check whether a new manifest needs to be
293 : /// uploaded. The manifest is constructed in `build_tenant_manifest`, and uploaded via
294 : /// `maybe_upload_tenant_manifest`.
295 : remote_tenant_manifest: tokio::sync::Mutex<Option<TenantManifest>>,
296 :
297 : // This mutex prevents creation of new timelines during GC.
298 : // Adding yet another mutex (in addition to `timelines`) is needed because holding
299 : // `timelines` mutex during all GC iteration
300 : // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
301 : // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
302 : // timeout...
303 : gc_cs: tokio::sync::Mutex<()>,
304 : walredo_mgr: Option<Arc<WalRedoManager>>,
305 :
306 : // provides access to timeline data sitting in the remote storage
307 : pub(crate) remote_storage: GenericRemoteStorage,
308 :
309 : // Access to global deletion queue for when this tenant wants to schedule a deletion
310 : deletion_queue_client: DeletionQueueClient,
311 :
312 : /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
313 : cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
314 : cached_synthetic_tenant_size: Arc<AtomicU64>,
315 :
316 : eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
317 :
318 : /// Track repeated failures to compact, so that we can back off.
319 : /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
320 : compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
321 :
322 : /// Signals the tenant compaction loop that there is L0 compaction work to be done.
323 : pub(crate) l0_compaction_trigger: Arc<Notify>,
324 :
325 : /// Scheduled gc-compaction tasks.
326 : scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
327 :
328 : /// If the tenant is in Activating state, notify this to encourage it
329 : /// to proceed to Active as soon as possible, rather than waiting for lazy
330 : /// background warmup.
331 : pub(crate) activate_now_sem: tokio::sync::Semaphore,
332 :
333 : /// Time it took for the tenant to activate. Zero if not active yet.
334 : attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
335 :
336 : // Cancellation token fires when we have entered shutdown(). This is a parent of
337 : // Timelines' cancellation token.
338 : pub(crate) cancel: CancellationToken,
339 :
340 : // Users of the Tenant such as the page service must take this Gate to avoid
341 : // trying to use a Tenant which is shutting down.
342 : pub(crate) gate: Gate,
343 :
344 : /// Throttle applied at the top of [`Timeline::get`].
345 : /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
346 : pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
347 :
348 : pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
349 :
350 : /// An ongoing timeline detach concurrency limiter.
351 : ///
352 : /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
353 : /// to have two running at the same time. A different one can be started if an earlier one
354 : /// has failed for whatever reason.
355 : ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
356 :
357 : /// `index_part.json` based gc blocking reason tracking.
358 : ///
359 : /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
360 : /// proceeding.
361 : pub(crate) gc_block: gc_block::GcBlock,
362 :
363 : l0_flush_global_state: L0FlushGlobalState,
364 : }
365 : impl std::fmt::Debug for Tenant {
366 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
367 0 : write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
368 0 : }
369 : }
370 :
371 : pub(crate) enum WalRedoManager {
372 : Prod(WalredoManagerId, PostgresRedoManager),
373 : #[cfg(test)]
374 : Test(harness::TestRedoManager),
375 : }
376 :
377 : #[derive(thiserror::Error, Debug)]
378 : #[error("pageserver is shutting down")]
379 : pub(crate) struct GlobalShutDown;
380 :
381 : impl WalRedoManager {
382 0 : pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
383 0 : let id = WalredoManagerId::next();
384 0 : let arc = Arc::new(Self::Prod(id, mgr));
385 0 : let mut guard = WALREDO_MANAGERS.lock().unwrap();
386 0 : match &mut *guard {
387 0 : Some(map) => {
388 0 : map.insert(id, Arc::downgrade(&arc));
389 0 : Ok(arc)
390 : }
391 0 : None => Err(GlobalShutDown),
392 : }
393 0 : }
394 : }
395 :
396 : impl Drop for WalRedoManager {
397 20 : fn drop(&mut self) {
398 20 : match self {
399 0 : Self::Prod(id, _) => {
400 0 : let mut guard = WALREDO_MANAGERS.lock().unwrap();
401 0 : if let Some(map) = &mut *guard {
402 0 : map.remove(id).expect("new() registers, drop() unregisters");
403 0 : }
404 : }
405 : #[cfg(test)]
406 20 : Self::Test(_) => {
407 20 : // Not applicable to test redo manager
408 20 : }
409 : }
410 20 : }
411 : }
412 :
413 : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
414 : /// the walredo processes outside of the regular order.
415 : ///
416 : /// This is necessary to work around a systemd bug where it freezes if there are
417 : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
418 : #[allow(clippy::type_complexity)]
419 : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
420 : Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
421 0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
422 : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
423 : pub(crate) struct WalredoManagerId(u64);
424 : impl WalredoManagerId {
425 0 : pub fn next() -> Self {
426 : static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
427 0 : let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
428 0 : if id == 0 {
429 0 : panic!(
430 0 : "WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique"
431 0 : );
432 0 : }
433 0 : Self(id)
434 0 : }
435 : }
436 :
437 : #[cfg(test)]
438 : impl From<harness::TestRedoManager> for WalRedoManager {
439 460 : fn from(mgr: harness::TestRedoManager) -> Self {
440 460 : Self::Test(mgr)
441 460 : }
442 : }
443 :
444 : impl WalRedoManager {
445 12 : pub(crate) async fn shutdown(&self) -> bool {
446 12 : match self {
447 0 : Self::Prod(_, mgr) => mgr.shutdown().await,
448 : #[cfg(test)]
449 : Self::Test(_) => {
450 : // Not applicable to test redo manager
451 12 : true
452 : }
453 : }
454 12 : }
455 :
456 0 : pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
457 0 : match self {
458 0 : Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
459 0 : #[cfg(test)]
460 0 : Self::Test(_) => {
461 0 : // Not applicable to test redo manager
462 0 : }
463 0 : }
464 0 : }
465 :
466 : /// # Cancel-Safety
467 : ///
468 : /// This method is cancellation-safe.
469 1696 : pub async fn request_redo(
470 1696 : &self,
471 1696 : key: pageserver_api::key::Key,
472 1696 : lsn: Lsn,
473 1696 : base_img: Option<(Lsn, bytes::Bytes)>,
474 1696 : records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
475 1696 : pg_version: u32,
476 1696 : redo_attempt_type: RedoAttemptType,
477 1696 : ) -> Result<bytes::Bytes, walredo::Error> {
478 1696 : match self {
479 0 : Self::Prod(_, mgr) => {
480 0 : mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
481 0 : .await
482 : }
483 : #[cfg(test)]
484 1696 : Self::Test(mgr) => {
485 1696 : mgr.request_redo(key, lsn, base_img, records, pg_version, redo_attempt_type)
486 1696 : .await
487 : }
488 : }
489 1696 : }
490 :
491 0 : pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
492 0 : match self {
493 0 : WalRedoManager::Prod(_, m) => Some(m.status()),
494 0 : #[cfg(test)]
495 0 : WalRedoManager::Test(_) => None,
496 0 : }
497 0 : }
498 : }
499 :
500 : /// A very lightweight memory representation of an offloaded timeline.
501 : ///
502 : /// We need to store the list of offloaded timelines so that we can perform operations on them,
503 : /// like unoffloading them, or (at a later date), decide to perform flattening.
504 : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
505 : /// more offloaded timelines than we can manage ones that aren't.
506 : pub struct OffloadedTimeline {
507 : pub tenant_shard_id: TenantShardId,
508 : pub timeline_id: TimelineId,
509 : pub ancestor_timeline_id: Option<TimelineId>,
510 : /// Whether to retain the branch lsn at the ancestor or not
511 : pub ancestor_retain_lsn: Option<Lsn>,
512 :
513 : /// When the timeline was archived.
514 : ///
515 : /// Present for future flattening deliberations.
516 : pub archived_at: NaiveDateTime,
517 :
518 : /// Prevent two tasks from deleting the timeline at the same time. If held, the
519 : /// timeline is being deleted. If 'true', the timeline has already been deleted.
520 : pub delete_progress: TimelineDeleteProgress,
521 :
522 : /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
523 : pub deleted_from_ancestor: AtomicBool,
524 : }
525 :
526 : impl OffloadedTimeline {
527 : /// Obtains an offloaded timeline from a given timeline object.
528 : ///
529 : /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
530 : /// the timeline is not in a stopped state.
531 : /// Panics if the timeline is not archived.
532 4 : fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
533 4 : let (ancestor_retain_lsn, ancestor_timeline_id) =
534 4 : if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
535 4 : let ancestor_lsn = timeline.get_ancestor_lsn();
536 4 : let ancestor_timeline_id = ancestor_timeline.timeline_id;
537 4 : let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
538 4 : gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
539 4 : (Some(ancestor_lsn), Some(ancestor_timeline_id))
540 : } else {
541 0 : (None, None)
542 : };
543 4 : let archived_at = timeline
544 4 : .remote_client
545 4 : .archived_at_stopped_queue()?
546 4 : .expect("must be called on an archived timeline");
547 4 : Ok(Self {
548 4 : tenant_shard_id: timeline.tenant_shard_id,
549 4 : timeline_id: timeline.timeline_id,
550 4 : ancestor_timeline_id,
551 4 : ancestor_retain_lsn,
552 4 : archived_at,
553 4 :
554 4 : delete_progress: timeline.delete_progress.clone(),
555 4 : deleted_from_ancestor: AtomicBool::new(false),
556 4 : })
557 4 : }
558 0 : fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
559 0 : // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
560 0 : // by the `initialize_gc_info` function.
561 0 : let OffloadedTimelineManifest {
562 0 : timeline_id,
563 0 : ancestor_timeline_id,
564 0 : ancestor_retain_lsn,
565 0 : archived_at,
566 0 : } = *manifest;
567 0 : Self {
568 0 : tenant_shard_id,
569 0 : timeline_id,
570 0 : ancestor_timeline_id,
571 0 : ancestor_retain_lsn,
572 0 : archived_at,
573 0 : delete_progress: TimelineDeleteProgress::default(),
574 0 : deleted_from_ancestor: AtomicBool::new(false),
575 0 : }
576 0 : }
577 4 : fn manifest(&self) -> OffloadedTimelineManifest {
578 4 : let Self {
579 4 : timeline_id,
580 4 : ancestor_timeline_id,
581 4 : ancestor_retain_lsn,
582 4 : archived_at,
583 4 : ..
584 4 : } = self;
585 4 : OffloadedTimelineManifest {
586 4 : timeline_id: *timeline_id,
587 4 : ancestor_timeline_id: *ancestor_timeline_id,
588 4 : ancestor_retain_lsn: *ancestor_retain_lsn,
589 4 : archived_at: *archived_at,
590 4 : }
591 4 : }
592 : /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
593 0 : fn delete_from_ancestor_with_timelines(
594 0 : &self,
595 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
596 0 : ) {
597 0 : if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
598 0 : (self.ancestor_retain_lsn, self.ancestor_timeline_id)
599 : {
600 0 : if let Some((_, ancestor_timeline)) = timelines
601 0 : .iter()
602 0 : .find(|(tid, _tl)| **tid == ancestor_timeline_id)
603 : {
604 0 : let removal_happened = ancestor_timeline
605 0 : .gc_info
606 0 : .write()
607 0 : .unwrap()
608 0 : .remove_child_offloaded(self.timeline_id);
609 0 : if !removal_happened {
610 0 : tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
611 0 : "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
612 0 : }
613 0 : }
614 0 : }
615 0 : self.deleted_from_ancestor.store(true, Ordering::Release);
616 0 : }
617 : /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
618 : ///
619 : /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
620 4 : fn defuse_for_tenant_drop(&self) {
621 4 : self.deleted_from_ancestor.store(true, Ordering::Release);
622 4 : }
623 : }
624 :
625 : impl fmt::Debug for OffloadedTimeline {
626 0 : fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627 0 : write!(f, "OffloadedTimeline<{}>", self.timeline_id)
628 0 : }
629 : }
630 :
631 : impl Drop for OffloadedTimeline {
632 4 : fn drop(&mut self) {
633 4 : if !self.deleted_from_ancestor.load(Ordering::Acquire) {
634 0 : tracing::warn!(
635 0 : "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
636 : self.timeline_id
637 : );
638 4 : }
639 4 : }
640 : }
641 :
642 : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
643 : pub enum MaybeOffloaded {
644 : Yes,
645 : No,
646 : }
647 :
648 : #[derive(Clone, Debug)]
649 : pub enum TimelineOrOffloaded {
650 : Timeline(Arc<Timeline>),
651 : Offloaded(Arc<OffloadedTimeline>),
652 : }
653 :
654 : impl TimelineOrOffloaded {
655 0 : pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
656 0 : match self {
657 0 : TimelineOrOffloaded::Timeline(timeline) => {
658 0 : TimelineOrOffloadedArcRef::Timeline(timeline)
659 : }
660 0 : TimelineOrOffloaded::Offloaded(offloaded) => {
661 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded)
662 : }
663 : }
664 0 : }
665 0 : pub fn tenant_shard_id(&self) -> TenantShardId {
666 0 : self.arc_ref().tenant_shard_id()
667 0 : }
668 0 : pub fn timeline_id(&self) -> TimelineId {
669 0 : self.arc_ref().timeline_id()
670 0 : }
671 4 : pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
672 4 : match self {
673 4 : TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
674 0 : TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
675 : }
676 4 : }
677 0 : fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
678 0 : match self {
679 0 : TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
680 0 : TimelineOrOffloaded::Offloaded(_offloaded) => None,
681 : }
682 0 : }
683 : }
684 :
685 : pub enum TimelineOrOffloadedArcRef<'a> {
686 : Timeline(&'a Arc<Timeline>),
687 : Offloaded(&'a Arc<OffloadedTimeline>),
688 : }
689 :
690 : impl TimelineOrOffloadedArcRef<'_> {
691 0 : pub fn tenant_shard_id(&self) -> TenantShardId {
692 0 : match self {
693 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
694 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
695 : }
696 0 : }
697 0 : pub fn timeline_id(&self) -> TimelineId {
698 0 : match self {
699 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
700 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
701 : }
702 0 : }
703 : }
704 :
705 : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
706 0 : fn from(timeline: &'a Arc<Timeline>) -> Self {
707 0 : Self::Timeline(timeline)
708 0 : }
709 : }
710 :
711 : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
712 0 : fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
713 0 : Self::Offloaded(timeline)
714 0 : }
715 : }
716 :
717 : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
718 : pub enum GetTimelineError {
719 : #[error("Timeline is shutting down")]
720 : ShuttingDown,
721 : #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
722 : NotActive {
723 : tenant_id: TenantShardId,
724 : timeline_id: TimelineId,
725 : state: TimelineState,
726 : },
727 : #[error("Timeline {tenant_id}/{timeline_id} was not found")]
728 : NotFound {
729 : tenant_id: TenantShardId,
730 : timeline_id: TimelineId,
731 : },
732 : }
733 :
734 : #[derive(Debug, thiserror::Error)]
735 : pub enum LoadLocalTimelineError {
736 : #[error("FailedToLoad")]
737 : Load(#[source] anyhow::Error),
738 : #[error("FailedToResumeDeletion")]
739 : ResumeDeletion(#[source] anyhow::Error),
740 : }
741 :
742 : #[derive(thiserror::Error)]
743 : pub enum DeleteTimelineError {
744 : #[error("NotFound")]
745 : NotFound,
746 :
747 : #[error("HasChildren")]
748 : HasChildren(Vec<TimelineId>),
749 :
750 : #[error("Timeline deletion is already in progress")]
751 : AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
752 :
753 : #[error("Cancelled")]
754 : Cancelled,
755 :
756 : #[error(transparent)]
757 : Other(#[from] anyhow::Error),
758 : }
759 :
760 : impl Debug for DeleteTimelineError {
761 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
762 0 : match self {
763 0 : Self::NotFound => write!(f, "NotFound"),
764 0 : Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
765 0 : Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
766 0 : Self::Cancelled => f.debug_tuple("Cancelled").finish(),
767 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
768 : }
769 0 : }
770 : }
771 :
772 : #[derive(thiserror::Error)]
773 : pub enum TimelineArchivalError {
774 : #[error("NotFound")]
775 : NotFound,
776 :
777 : #[error("Timeout")]
778 : Timeout,
779 :
780 : #[error("Cancelled")]
781 : Cancelled,
782 :
783 : #[error("ancestor is archived: {}", .0)]
784 : HasArchivedParent(TimelineId),
785 :
786 : #[error("HasUnarchivedChildren")]
787 : HasUnarchivedChildren(Vec<TimelineId>),
788 :
789 : #[error("Timeline archival is already in progress")]
790 : AlreadyInProgress,
791 :
792 : #[error(transparent)]
793 : Other(anyhow::Error),
794 : }
795 :
796 : #[derive(thiserror::Error, Debug)]
797 : pub(crate) enum TenantManifestError {
798 : #[error("Remote storage error: {0}")]
799 : RemoteStorage(anyhow::Error),
800 :
801 : #[error("Cancelled")]
802 : Cancelled,
803 : }
804 :
805 : impl From<TenantManifestError> for TimelineArchivalError {
806 0 : fn from(e: TenantManifestError) -> Self {
807 0 : match e {
808 0 : TenantManifestError::RemoteStorage(e) => Self::Other(e),
809 0 : TenantManifestError::Cancelled => Self::Cancelled,
810 : }
811 0 : }
812 : }
813 :
814 : impl Debug for TimelineArchivalError {
815 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
816 0 : match self {
817 0 : Self::NotFound => write!(f, "NotFound"),
818 0 : Self::Timeout => write!(f, "Timeout"),
819 0 : Self::Cancelled => write!(f, "Cancelled"),
820 0 : Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
821 0 : Self::HasUnarchivedChildren(c) => {
822 0 : f.debug_tuple("HasUnarchivedChildren").field(c).finish()
823 : }
824 0 : Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
825 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
826 : }
827 0 : }
828 : }
829 :
830 : pub enum SetStoppingError {
831 : AlreadyStopping(completion::Barrier),
832 : Broken,
833 : }
834 :
835 : impl Debug for SetStoppingError {
836 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
837 0 : match self {
838 0 : Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
839 0 : Self::Broken => write!(f, "Broken"),
840 : }
841 0 : }
842 : }
843 :
844 : /// Arguments to [`Tenant::create_timeline`].
845 : ///
846 : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
847 : /// is `None`, the result of the timeline create call is not deterministic.
848 : ///
849 : /// See [`CreateTimelineIdempotency`] for an idempotency key.
850 : #[derive(Debug)]
851 : pub(crate) enum CreateTimelineParams {
852 : Bootstrap(CreateTimelineParamsBootstrap),
853 : Branch(CreateTimelineParamsBranch),
854 : ImportPgdata(CreateTimelineParamsImportPgdata),
855 : }
856 :
857 : #[derive(Debug)]
858 : pub(crate) struct CreateTimelineParamsBootstrap {
859 : pub(crate) new_timeline_id: TimelineId,
860 : pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
861 : pub(crate) pg_version: u32,
862 : }
863 :
864 : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
865 : #[derive(Debug)]
866 : pub(crate) struct CreateTimelineParamsBranch {
867 : pub(crate) new_timeline_id: TimelineId,
868 : pub(crate) ancestor_timeline_id: TimelineId,
869 : pub(crate) ancestor_start_lsn: Option<Lsn>,
870 : }
871 :
872 : #[derive(Debug)]
873 : pub(crate) struct CreateTimelineParamsImportPgdata {
874 : pub(crate) new_timeline_id: TimelineId,
875 : pub(crate) location: import_pgdata::index_part_format::Location,
876 : pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
877 : }
878 :
879 : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in [`Tenant::start_creating_timeline`] in [`Tenant::start_creating_timeline`].
880 : ///
881 : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
882 : ///
883 : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
884 : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
885 : ///
886 : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
887 : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
888 : ///
889 : /// Notes:
890 : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
891 : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
892 : /// is not considered for idempotency. We can improve on this over time if we deem it necessary.
893 : ///
894 : #[derive(Debug, Clone, PartialEq, Eq)]
895 : pub(crate) enum CreateTimelineIdempotency {
896 : /// NB: special treatment, see comment in [`Self`].
897 : FailWithConflict,
898 : Bootstrap {
899 : pg_version: u32,
900 : },
901 : /// NB: branches always have the same `pg_version` as their ancestor.
902 : /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
903 : /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
904 : /// determining the child branch pg_version.
905 : Branch {
906 : ancestor_timeline_id: TimelineId,
907 : ancestor_start_lsn: Lsn,
908 : },
909 : ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
910 : }
911 :
912 : #[derive(Debug, Clone, PartialEq, Eq)]
913 : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
914 : idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
915 : }
916 :
917 : /// What is returned by [`Tenant::start_creating_timeline`].
918 : #[must_use]
919 : enum StartCreatingTimelineResult {
920 : CreateGuard(TimelineCreateGuard),
921 : Idempotent(Arc<Timeline>),
922 : }
923 :
924 : #[allow(clippy::large_enum_variant, reason = "TODO")]
925 : enum TimelineInitAndSyncResult {
926 : ReadyToActivate(Arc<Timeline>),
927 : NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
928 : }
929 :
930 : impl TimelineInitAndSyncResult {
931 0 : fn ready_to_activate(self) -> Option<Arc<Timeline>> {
932 0 : match self {
933 0 : Self::ReadyToActivate(timeline) => Some(timeline),
934 0 : _ => None,
935 : }
936 0 : }
937 : }
938 :
939 : #[must_use]
940 : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
941 : timeline: Arc<Timeline>,
942 : import_pgdata: import_pgdata::index_part_format::Root,
943 : guard: TimelineCreateGuard,
944 : }
945 :
946 : /// What is returned by [`Tenant::create_timeline`].
947 : enum CreateTimelineResult {
948 : Created(Arc<Timeline>),
949 : Idempotent(Arc<Timeline>),
950 : /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
951 : /// we return this result, nor will this concrete object ever be added there.
952 : /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
953 : ImportSpawned(Arc<Timeline>),
954 : }
955 :
956 : impl CreateTimelineResult {
957 0 : fn discriminant(&self) -> &'static str {
958 0 : match self {
959 0 : Self::Created(_) => "Created",
960 0 : Self::Idempotent(_) => "Idempotent",
961 0 : Self::ImportSpawned(_) => "ImportSpawned",
962 : }
963 0 : }
964 0 : fn timeline(&self) -> &Arc<Timeline> {
965 0 : match self {
966 0 : Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
967 0 : }
968 0 : }
969 : /// Unit test timelines aren't activated, test has to do it if it needs to.
970 : #[cfg(test)]
971 472 : fn into_timeline_for_test(self) -> Arc<Timeline> {
972 472 : match self {
973 472 : Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
974 472 : }
975 472 : }
976 : }
977 :
978 : #[derive(thiserror::Error, Debug)]
979 : pub enum CreateTimelineError {
980 : #[error("creation of timeline with the given ID is in progress")]
981 : AlreadyCreating,
982 : #[error("timeline already exists with different parameters")]
983 : Conflict,
984 : #[error(transparent)]
985 : AncestorLsn(anyhow::Error),
986 : #[error("ancestor timeline is not active")]
987 : AncestorNotActive,
988 : #[error("ancestor timeline is archived")]
989 : AncestorArchived,
990 : #[error("tenant shutting down")]
991 : ShuttingDown,
992 : #[error(transparent)]
993 : Other(#[from] anyhow::Error),
994 : }
995 :
996 : #[derive(thiserror::Error, Debug)]
997 : pub enum InitdbError {
998 : #[error("Operation was cancelled")]
999 : Cancelled,
1000 : #[error(transparent)]
1001 : Other(anyhow::Error),
1002 : #[error(transparent)]
1003 : Inner(postgres_initdb::Error),
1004 : }
1005 :
1006 : enum CreateTimelineCause {
1007 : Load,
1008 : Delete,
1009 : }
1010 :
1011 : #[allow(clippy::large_enum_variant, reason = "TODO")]
1012 : enum LoadTimelineCause {
1013 : Attach,
1014 : Unoffload,
1015 : ImportPgdata {
1016 : create_guard: TimelineCreateGuard,
1017 : activate: ActivateTimelineArgs,
1018 : },
1019 : }
1020 :
1021 : #[derive(thiserror::Error, Debug)]
1022 : pub(crate) enum GcError {
1023 : // The tenant is shutting down
1024 : #[error("tenant shutting down")]
1025 : TenantCancelled,
1026 :
1027 : // The tenant is shutting down
1028 : #[error("timeline shutting down")]
1029 : TimelineCancelled,
1030 :
1031 : // The tenant is in a state inelegible to run GC
1032 : #[error("not active")]
1033 : NotActive,
1034 :
1035 : // A requested GC cutoff LSN was invalid, for example it tried to move backwards
1036 : #[error("not active")]
1037 : BadLsn { why: String },
1038 :
1039 : // A remote storage error while scheduling updates after compaction
1040 : #[error(transparent)]
1041 : Remote(anyhow::Error),
1042 :
1043 : // An error reading while calculating GC cutoffs
1044 : #[error(transparent)]
1045 : GcCutoffs(PageReconstructError),
1046 :
1047 : // If GC was invoked for a particular timeline, this error means it didn't exist
1048 : #[error("timeline not found")]
1049 : TimelineNotFound,
1050 : }
1051 :
1052 : impl From<PageReconstructError> for GcError {
1053 0 : fn from(value: PageReconstructError) -> Self {
1054 0 : match value {
1055 0 : PageReconstructError::Cancelled => Self::TimelineCancelled,
1056 0 : other => Self::GcCutoffs(other),
1057 : }
1058 0 : }
1059 : }
1060 :
1061 : impl From<NotInitialized> for GcError {
1062 0 : fn from(value: NotInitialized) -> Self {
1063 0 : match value {
1064 0 : NotInitialized::Uninitialized => GcError::Remote(value.into()),
1065 0 : NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
1066 : }
1067 0 : }
1068 : }
1069 :
1070 : impl From<timeline::layer_manager::Shutdown> for GcError {
1071 0 : fn from(_: timeline::layer_manager::Shutdown) -> Self {
1072 0 : GcError::TimelineCancelled
1073 0 : }
1074 : }
1075 :
1076 : #[derive(thiserror::Error, Debug)]
1077 : pub(crate) enum LoadConfigError {
1078 : #[error("TOML deserialization error: '{0}'")]
1079 : DeserializeToml(#[from] toml_edit::de::Error),
1080 :
1081 : #[error("Config not found at {0}")]
1082 : NotFound(Utf8PathBuf),
1083 : }
1084 :
1085 : impl Tenant {
1086 : /// Yet another helper for timeline initialization.
1087 : ///
1088 : /// - Initializes the Timeline struct and inserts it into the tenant's hash map
1089 : /// - Scans the local timeline directory for layer files and builds the layer map
1090 : /// - Downloads remote index file and adds remote files to the layer map
1091 : /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
1092 : ///
1093 : /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
1094 : /// it is marked as Active.
1095 : #[allow(clippy::too_many_arguments)]
1096 12 : async fn timeline_init_and_sync(
1097 12 : self: &Arc<Self>,
1098 12 : timeline_id: TimelineId,
1099 12 : resources: TimelineResources,
1100 12 : mut index_part: IndexPart,
1101 12 : metadata: TimelineMetadata,
1102 12 : previous_heatmap: Option<PreviousHeatmap>,
1103 12 : ancestor: Option<Arc<Timeline>>,
1104 12 : cause: LoadTimelineCause,
1105 12 : ctx: &RequestContext,
1106 12 : ) -> anyhow::Result<TimelineInitAndSyncResult> {
1107 12 : let tenant_id = self.tenant_shard_id;
1108 12 :
1109 12 : let import_pgdata = index_part.import_pgdata.take();
1110 12 : let idempotency = match &import_pgdata {
1111 0 : Some(import_pgdata) => {
1112 0 : CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
1113 0 : idempotency_key: import_pgdata.idempotency_key().clone(),
1114 0 : })
1115 : }
1116 : None => {
1117 12 : if metadata.ancestor_timeline().is_none() {
1118 8 : CreateTimelineIdempotency::Bootstrap {
1119 8 : pg_version: metadata.pg_version(),
1120 8 : }
1121 : } else {
1122 4 : CreateTimelineIdempotency::Branch {
1123 4 : ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
1124 4 : ancestor_start_lsn: metadata.ancestor_lsn(),
1125 4 : }
1126 : }
1127 : }
1128 : };
1129 :
1130 12 : let (timeline, timeline_ctx) = self.create_timeline_struct(
1131 12 : timeline_id,
1132 12 : &metadata,
1133 12 : previous_heatmap,
1134 12 : ancestor.clone(),
1135 12 : resources,
1136 12 : CreateTimelineCause::Load,
1137 12 : idempotency.clone(),
1138 12 : index_part.gc_compaction.clone(),
1139 12 : index_part.rel_size_migration.clone(),
1140 12 : ctx,
1141 12 : )?;
1142 12 : let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
1143 12 : anyhow::ensure!(
1144 12 : disk_consistent_lsn.is_valid(),
1145 0 : "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
1146 : );
1147 12 : assert_eq!(
1148 12 : disk_consistent_lsn,
1149 12 : metadata.disk_consistent_lsn(),
1150 0 : "these are used interchangeably"
1151 : );
1152 :
1153 12 : timeline.remote_client.init_upload_queue(&index_part)?;
1154 :
1155 12 : timeline
1156 12 : .load_layer_map(disk_consistent_lsn, index_part)
1157 12 : .await
1158 12 : .with_context(|| {
1159 0 : format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
1160 12 : })?;
1161 :
1162 : // When unarchiving, we've mostly likely lost the heatmap generated prior
1163 : // to the archival operation. To allow warming this timeline up, generate
1164 : // a previous heatmap which contains all visible layers in the layer map.
1165 : // This previous heatmap will be used whenever a fresh heatmap is generated
1166 : // for the timeline.
1167 12 : if self.conf.generate_unarchival_heatmap && matches!(cause, LoadTimelineCause::Unoffload) {
1168 0 : let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
1169 0 : while let Some((tline, end_lsn)) = tline_ending_at {
1170 0 : let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
1171 : // Another unearchived timeline might have generated a heatmap for this ancestor.
1172 : // If the current branch point greater than the previous one use the the heatmap
1173 : // we just generated - it should include more layers.
1174 0 : if !tline.should_keep_previous_heatmap(end_lsn) {
1175 0 : tline
1176 0 : .previous_heatmap
1177 0 : .store(Some(Arc::new(unarchival_heatmap)));
1178 0 : } else {
1179 0 : tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
1180 : }
1181 :
1182 0 : match tline.ancestor_timeline() {
1183 0 : Some(ancestor) => {
1184 0 : if ancestor.update_layer_visibility().await.is_err() {
1185 : // Ancestor timeline is shutting down.
1186 0 : break;
1187 0 : }
1188 0 :
1189 0 : tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
1190 : }
1191 0 : None => {
1192 0 : tline_ending_at = None;
1193 0 : }
1194 : }
1195 : }
1196 12 : }
1197 :
1198 0 : match import_pgdata {
1199 0 : Some(import_pgdata) if !import_pgdata.is_done() => {
1200 0 : match cause {
1201 0 : LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
1202 : LoadTimelineCause::ImportPgdata { .. } => {
1203 0 : unreachable!(
1204 0 : "ImportPgdata should not be reloading timeline import is done and persisted as such in s3"
1205 0 : )
1206 : }
1207 : }
1208 0 : let mut guard = self.timelines_creating.lock().unwrap();
1209 0 : if !guard.insert(timeline_id) {
1210 : // We should never try and load the same timeline twice during startup
1211 0 : unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
1212 0 : }
1213 0 : let timeline_create_guard = TimelineCreateGuard {
1214 0 : _tenant_gate_guard: self.gate.enter()?,
1215 0 : owning_tenant: self.clone(),
1216 0 : timeline_id,
1217 0 : idempotency,
1218 0 : // The users of this specific return value don't need the timline_path in there.
1219 0 : timeline_path: timeline
1220 0 : .conf
1221 0 : .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
1222 0 : };
1223 0 : Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
1224 0 : TimelineInitAndSyncNeedsSpawnImportPgdata {
1225 0 : timeline,
1226 0 : import_pgdata,
1227 0 : guard: timeline_create_guard,
1228 0 : },
1229 0 : ))
1230 : }
1231 : Some(_) | None => {
1232 : {
1233 12 : let mut timelines_accessor = self.timelines.lock().unwrap();
1234 12 : match timelines_accessor.entry(timeline_id) {
1235 : // We should never try and load the same timeline twice during startup
1236 : Entry::Occupied(_) => {
1237 0 : unreachable!(
1238 0 : "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
1239 0 : );
1240 : }
1241 12 : Entry::Vacant(v) => {
1242 12 : v.insert(Arc::clone(&timeline));
1243 12 : timeline.maybe_spawn_flush_loop();
1244 12 : }
1245 : }
1246 : }
1247 :
1248 : // Sanity check: a timeline should have some content.
1249 12 : anyhow::ensure!(
1250 12 : ancestor.is_some()
1251 8 : || timeline
1252 8 : .layers
1253 8 : .read()
1254 8 : .await
1255 8 : .layer_map()
1256 8 : .expect("currently loading, layer manager cannot be shutdown already")
1257 8 : .iter_historic_layers()
1258 8 : .next()
1259 8 : .is_some(),
1260 0 : "Timeline has no ancestor and no layer files"
1261 : );
1262 :
1263 12 : match cause {
1264 12 : LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
1265 : LoadTimelineCause::ImportPgdata {
1266 0 : create_guard,
1267 0 : activate,
1268 0 : } => {
1269 0 : // TODO: see the comment in the task code above how I'm not so certain
1270 0 : // it is safe to activate here because of concurrent shutdowns.
1271 0 : match activate {
1272 0 : ActivateTimelineArgs::Yes { broker_client } => {
1273 0 : info!("activating timeline after reload from pgdata import task");
1274 0 : timeline.activate(self.clone(), broker_client, None, &timeline_ctx);
1275 : }
1276 0 : ActivateTimelineArgs::No => (),
1277 : }
1278 0 : drop(create_guard);
1279 : }
1280 : }
1281 :
1282 12 : Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
1283 : }
1284 : }
1285 12 : }
1286 :
1287 : /// Attach a tenant that's available in cloud storage.
1288 : ///
1289 : /// This returns quickly, after just creating the in-memory object
1290 : /// Tenant struct and launching a background task to download
1291 : /// the remote index files. On return, the tenant is most likely still in
1292 : /// Attaching state, and it will become Active once the background task
1293 : /// finishes. You can use wait_until_active() to wait for the task to
1294 : /// complete.
1295 : ///
1296 : #[allow(clippy::too_many_arguments)]
1297 0 : pub(crate) fn spawn(
1298 0 : conf: &'static PageServerConf,
1299 0 : tenant_shard_id: TenantShardId,
1300 0 : resources: TenantSharedResources,
1301 0 : attached_conf: AttachedTenantConf,
1302 0 : shard_identity: ShardIdentity,
1303 0 : init_order: Option<InitializationOrder>,
1304 0 : mode: SpawnMode,
1305 0 : ctx: &RequestContext,
1306 0 : ) -> Result<Arc<Tenant>, GlobalShutDown> {
1307 0 : let wal_redo_manager =
1308 0 : WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
1309 :
1310 : let TenantSharedResources {
1311 0 : broker_client,
1312 0 : remote_storage,
1313 0 : deletion_queue_client,
1314 0 : l0_flush_global_state,
1315 0 : } = resources;
1316 0 :
1317 0 : let attach_mode = attached_conf.location.attach_mode;
1318 0 : let generation = attached_conf.location.generation;
1319 0 :
1320 0 : let tenant = Arc::new(Tenant::new(
1321 0 : TenantState::Attaching,
1322 0 : conf,
1323 0 : attached_conf,
1324 0 : shard_identity,
1325 0 : Some(wal_redo_manager),
1326 0 : tenant_shard_id,
1327 0 : remote_storage.clone(),
1328 0 : deletion_queue_client,
1329 0 : l0_flush_global_state,
1330 0 : ));
1331 0 :
1332 0 : // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
1333 0 : // we shut down while attaching.
1334 0 : let attach_gate_guard = tenant
1335 0 : .gate
1336 0 : .enter()
1337 0 : .expect("We just created the Tenant: nothing else can have shut it down yet");
1338 0 :
1339 0 : // Do all the hard work in the background
1340 0 : let tenant_clone = Arc::clone(&tenant);
1341 0 : let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
1342 0 : task_mgr::spawn(
1343 0 : &tokio::runtime::Handle::current(),
1344 0 : TaskKind::Attach,
1345 0 : tenant_shard_id,
1346 0 : None,
1347 0 : "attach tenant",
1348 0 : async move {
1349 0 :
1350 0 : info!(
1351 : ?attach_mode,
1352 0 : "Attaching tenant"
1353 : );
1354 :
1355 0 : let _gate_guard = attach_gate_guard;
1356 0 :
1357 0 : // Is this tenant being spawned as part of process startup?
1358 0 : let starting_up = init_order.is_some();
1359 0 : scopeguard::defer! {
1360 0 : if starting_up {
1361 0 : TENANT.startup_complete.inc();
1362 0 : }
1363 0 : }
1364 :
1365 0 : fn make_broken_or_stopping(t: &Tenant, err: anyhow::Error) {
1366 0 : t.state.send_modify(|state| match state {
1367 : // TODO: the old code alluded to DeleteTenantFlow sometimes setting
1368 : // TenantState::Stopping before we get here, but this may be outdated.
1369 : // Let's find out with a testing assertion. If this doesn't fire, and the
1370 : // logs don't show this happening in production, remove the Stopping cases.
1371 0 : TenantState::Stopping{..} if cfg!(any(test, feature = "testing")) => {
1372 0 : panic!("unexpected TenantState::Stopping during attach")
1373 : }
1374 : // If the tenant is cancelled, assume the error was caused by cancellation.
1375 0 : TenantState::Attaching if t.cancel.is_cancelled() => {
1376 0 : info!("attach cancelled, setting tenant state to Stopping: {err}");
1377 : // NB: progress None tells `set_stopping` that attach has cancelled.
1378 0 : *state = TenantState::Stopping { progress: None };
1379 : }
1380 : // According to the old code, DeleteTenantFlow may already have set this to
1381 : // Stopping. Retain its progress.
1382 : // TODO: there is no DeleteTenantFlow. Is this still needed? See above.
1383 0 : TenantState::Stopping { progress } if t.cancel.is_cancelled() => {
1384 0 : assert!(progress.is_some(), "concurrent attach cancellation");
1385 0 : info!("attach cancelled, already Stopping: {err}");
1386 : }
1387 : // Mark the tenant as broken.
1388 : TenantState::Attaching | TenantState::Stopping { .. } => {
1389 0 : error!("attach failed, setting tenant state to Broken (was {state}): {err:?}");
1390 0 : *state = TenantState::broken_from_reason(err.to_string())
1391 : }
1392 : // The attach task owns the tenant state until activated.
1393 0 : state => panic!("invalid tenant state {state} during attach: {err:?}"),
1394 0 : });
1395 0 : }
1396 :
1397 : // TODO: should also be rejecting tenant conf changes that violate this check.
1398 0 : if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
1399 0 : make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
1400 0 : return Ok(());
1401 0 : }
1402 0 :
1403 0 : let mut init_order = init_order;
1404 0 : // take the completion because initial tenant loading will complete when all of
1405 0 : // these tasks complete.
1406 0 : let _completion = init_order
1407 0 : .as_mut()
1408 0 : .and_then(|x| x.initial_tenant_load.take());
1409 0 : let remote_load_completion = init_order
1410 0 : .as_mut()
1411 0 : .and_then(|x| x.initial_tenant_load_remote.take());
1412 :
1413 : enum AttachType<'a> {
1414 : /// We are attaching this tenant lazily in the background.
1415 : Warmup {
1416 : _permit: tokio::sync::SemaphorePermit<'a>,
1417 : during_startup: bool
1418 : },
1419 : /// We are attaching this tenant as soon as we can, because for example an
1420 : /// endpoint tried to access it.
1421 : OnDemand,
1422 : /// During normal operations after startup, we are attaching a tenant, and
1423 : /// eager attach was requested.
1424 : Normal,
1425 : }
1426 :
1427 0 : let attach_type = if matches!(mode, SpawnMode::Lazy) {
1428 : // Before doing any I/O, wait for at least one of:
1429 : // - A client attempting to access to this tenant (on-demand loading)
1430 : // - A permit becoming available in the warmup semaphore (background warmup)
1431 :
1432 0 : tokio::select!(
1433 0 : permit = tenant_clone.activate_now_sem.acquire() => {
1434 0 : let _ = permit.expect("activate_now_sem is never closed");
1435 0 : tracing::info!("Activating tenant (on-demand)");
1436 0 : AttachType::OnDemand
1437 : },
1438 0 : permit = conf.concurrent_tenant_warmup.inner().acquire() => {
1439 0 : let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
1440 0 : tracing::info!("Activating tenant (warmup)");
1441 0 : AttachType::Warmup {
1442 0 : _permit,
1443 0 : during_startup: init_order.is_some()
1444 0 : }
1445 : }
1446 0 : _ = tenant_clone.cancel.cancelled() => {
1447 : // This is safe, but should be pretty rare: it is interesting if a tenant
1448 : // stayed in Activating for such a long time that shutdown found it in
1449 : // that state.
1450 0 : tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
1451 : // Set the tenant to Stopping to signal `set_stopping` that we're done.
1452 0 : make_broken_or_stopping(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"));
1453 0 : return Ok(());
1454 : },
1455 : )
1456 : } else {
1457 : // SpawnMode::{Create,Eager} always cause jumping ahead of the
1458 : // concurrent_tenant_warmup queue
1459 0 : AttachType::Normal
1460 : };
1461 :
1462 0 : let preload = match &mode {
1463 : SpawnMode::Eager | SpawnMode::Lazy => {
1464 0 : let _preload_timer = TENANT.preload.start_timer();
1465 0 : let res = tenant_clone
1466 0 : .preload(&remote_storage, task_mgr::shutdown_token())
1467 0 : .await;
1468 0 : match res {
1469 0 : Ok(p) => Some(p),
1470 0 : Err(e) => {
1471 0 : make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e));
1472 0 : return Ok(());
1473 : }
1474 : }
1475 : }
1476 :
1477 : };
1478 :
1479 : // Remote preload is complete.
1480 0 : drop(remote_load_completion);
1481 0 :
1482 0 :
1483 0 : // We will time the duration of the attach phase unless this is a creation (attach will do no work)
1484 0 : let attach_start = std::time::Instant::now();
1485 0 : let attached = {
1486 0 : let _attach_timer = Some(TENANT.attach.start_timer());
1487 0 : tenant_clone.attach(preload, &ctx).await
1488 : };
1489 0 : let attach_duration = attach_start.elapsed();
1490 0 : _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
1491 0 :
1492 0 : match attached {
1493 : Ok(()) => {
1494 0 : info!("attach finished, activating");
1495 0 : tenant_clone.activate(broker_client, None, &ctx);
1496 : }
1497 0 : Err(e) => make_broken_or_stopping(&tenant_clone, anyhow::anyhow!(e)),
1498 : }
1499 :
1500 : // If we are doing an opportunistic warmup attachment at startup, initialize
1501 : // logical size at the same time. This is better than starting a bunch of idle tenants
1502 : // with cold caches and then coming back later to initialize their logical sizes.
1503 : //
1504 : // It also prevents the warmup proccess competing with the concurrency limit on
1505 : // logical size calculations: if logical size calculation semaphore is saturated,
1506 : // then warmup will wait for that before proceeding to the next tenant.
1507 0 : if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
1508 0 : let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
1509 0 : tracing::info!("Waiting for initial logical sizes while warming up...");
1510 0 : while futs.next().await.is_some() {}
1511 0 : tracing::info!("Warm-up complete");
1512 0 : }
1513 :
1514 0 : Ok(())
1515 0 : }
1516 0 : .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
1517 : );
1518 0 : Ok(tenant)
1519 0 : }
1520 :
1521 : #[instrument(skip_all)]
1522 : pub(crate) async fn preload(
1523 : self: &Arc<Self>,
1524 : remote_storage: &GenericRemoteStorage,
1525 : cancel: CancellationToken,
1526 : ) -> anyhow::Result<TenantPreload> {
1527 : span::debug_assert_current_span_has_tenant_id();
1528 : // Get list of remote timelines
1529 : // download index files for every tenant timeline
1530 : info!("listing remote timelines");
1531 : let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
1532 : remote_storage,
1533 : self.tenant_shard_id,
1534 : cancel.clone(),
1535 : )
1536 : .await?;
1537 :
1538 : let tenant_manifest = match download_tenant_manifest(
1539 : remote_storage,
1540 : &self.tenant_shard_id,
1541 : self.generation,
1542 : &cancel,
1543 : )
1544 : .await
1545 : {
1546 : Ok((tenant_manifest, _, _)) => Some(tenant_manifest),
1547 : Err(DownloadError::NotFound) => None,
1548 : Err(err) => return Err(err.into()),
1549 : };
1550 :
1551 : info!(
1552 : "found {} timelines ({} offloaded timelines)",
1553 : remote_timeline_ids.len(),
1554 : tenant_manifest
1555 : .as_ref()
1556 12 : .map(|m| m.offloaded_timelines.len())
1557 : .unwrap_or(0)
1558 : );
1559 :
1560 : for k in other_keys {
1561 : warn!("Unexpected non timeline key {k}");
1562 : }
1563 :
1564 : // Avoid downloading IndexPart of offloaded timelines.
1565 : let mut offloaded_with_prefix = HashSet::new();
1566 : if let Some(tenant_manifest) = &tenant_manifest {
1567 : for offloaded in tenant_manifest.offloaded_timelines.iter() {
1568 : if remote_timeline_ids.remove(&offloaded.timeline_id) {
1569 : offloaded_with_prefix.insert(offloaded.timeline_id);
1570 : } else {
1571 : // We'll take care later of timelines in the manifest without a prefix
1572 : }
1573 : }
1574 : }
1575 :
1576 : // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
1577 : // pulled the first heatmap. Not entirely necessary since the storage controller
1578 : // will kick the secondary in any case and cause a download.
1579 : let maybe_heatmap_at = self.read_on_disk_heatmap().await;
1580 :
1581 : let timelines = self
1582 : .load_timelines_metadata(
1583 : remote_timeline_ids,
1584 : remote_storage,
1585 : maybe_heatmap_at,
1586 : cancel,
1587 : )
1588 : .await?;
1589 :
1590 : Ok(TenantPreload {
1591 : tenant_manifest,
1592 : timelines: timelines
1593 : .into_iter()
1594 12 : .map(|(id, tl)| (id, Some(tl)))
1595 0 : .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
1596 : .collect(),
1597 : })
1598 : }
1599 :
1600 460 : async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
1601 460 : if !self.conf.load_previous_heatmap {
1602 0 : return None;
1603 460 : }
1604 460 :
1605 460 : let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
1606 460 : match tokio::fs::read_to_string(on_disk_heatmap_path).await {
1607 0 : Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
1608 0 : Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
1609 0 : Err(err) => {
1610 0 : error!("Failed to deserialize old heatmap: {err}");
1611 0 : None
1612 : }
1613 : },
1614 460 : Err(err) => match err.kind() {
1615 460 : std::io::ErrorKind::NotFound => None,
1616 : _ => {
1617 0 : error!("Unexpected IO error reading old heatmap: {err}");
1618 0 : None
1619 : }
1620 : },
1621 : }
1622 460 : }
1623 :
1624 : ///
1625 : /// Background task that downloads all data for a tenant and brings it to Active state.
1626 : ///
1627 : /// No background tasks are started as part of this routine.
1628 : ///
1629 460 : async fn attach(
1630 460 : self: &Arc<Tenant>,
1631 460 : preload: Option<TenantPreload>,
1632 460 : ctx: &RequestContext,
1633 460 : ) -> anyhow::Result<()> {
1634 460 : span::debug_assert_current_span_has_tenant_id();
1635 460 :
1636 460 : failpoint_support::sleep_millis_async!("before-attaching-tenant");
1637 :
1638 460 : let Some(preload) = preload else {
1639 0 : anyhow::bail!(
1640 0 : "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
1641 0 : );
1642 : };
1643 :
1644 460 : let mut offloaded_timeline_ids = HashSet::new();
1645 460 : let mut offloaded_timelines_list = Vec::new();
1646 460 : if let Some(tenant_manifest) = &preload.tenant_manifest {
1647 12 : for timeline_manifest in tenant_manifest.offloaded_timelines.iter() {
1648 0 : let timeline_id = timeline_manifest.timeline_id;
1649 0 : let offloaded_timeline =
1650 0 : OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
1651 0 : offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
1652 0 : offloaded_timeline_ids.insert(timeline_id);
1653 0 : }
1654 448 : }
1655 : // Complete deletions for offloaded timeline id's from manifest.
1656 : // The manifest will be uploaded later in this function.
1657 460 : offloaded_timelines_list
1658 460 : .retain(|(offloaded_id, offloaded)| {
1659 0 : // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
1660 0 : // If there is dangling references in another location, they need to be cleaned up.
1661 0 : let delete = !preload.timelines.contains_key(offloaded_id);
1662 0 : if delete {
1663 0 : tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
1664 0 : offloaded.defuse_for_tenant_drop();
1665 0 : }
1666 0 : !delete
1667 460 : });
1668 460 :
1669 460 : let mut timelines_to_resume_deletions = vec![];
1670 460 :
1671 460 : let mut remote_index_and_client = HashMap::new();
1672 460 : let mut timeline_ancestors = HashMap::new();
1673 460 : let mut existent_timelines = HashSet::new();
1674 472 : for (timeline_id, preload) in preload.timelines {
1675 12 : let Some(preload) = preload else { continue };
1676 : // This is an invariant of the `preload` function's API
1677 12 : assert!(!offloaded_timeline_ids.contains(&timeline_id));
1678 12 : let index_part = match preload.index_part {
1679 12 : Ok(i) => {
1680 12 : debug!("remote index part exists for timeline {timeline_id}");
1681 : // We found index_part on the remote, this is the standard case.
1682 12 : existent_timelines.insert(timeline_id);
1683 12 : i
1684 : }
1685 : Err(DownloadError::NotFound) => {
1686 : // There is no index_part on the remote. We only get here
1687 : // if there is some prefix for the timeline in the remote storage.
1688 : // This can e.g. be the initdb.tar.zst archive, maybe a
1689 : // remnant from a prior incomplete creation or deletion attempt.
1690 : // Delete the local directory as the deciding criterion for a
1691 : // timeline's existence is presence of index_part.
1692 0 : info!(%timeline_id, "index_part not found on remote");
1693 0 : continue;
1694 : }
1695 0 : Err(DownloadError::Fatal(why)) => {
1696 0 : // If, while loading one remote timeline, we saw an indication that our generation
1697 0 : // number is likely invalid, then we should not load the whole tenant.
1698 0 : error!(%timeline_id, "Fatal error loading timeline: {why}");
1699 0 : anyhow::bail!(why.to_string());
1700 : }
1701 0 : Err(e) => {
1702 0 : // Some (possibly ephemeral) error happened during index_part download.
1703 0 : // Pretend the timeline exists to not delete the timeline directory,
1704 0 : // as it might be a temporary issue and we don't want to re-download
1705 0 : // everything after it resolves.
1706 0 : warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
1707 :
1708 0 : existent_timelines.insert(timeline_id);
1709 0 : continue;
1710 : }
1711 : };
1712 12 : match index_part {
1713 12 : MaybeDeletedIndexPart::IndexPart(index_part) => {
1714 12 : timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
1715 12 : remote_index_and_client.insert(
1716 12 : timeline_id,
1717 12 : (index_part, preload.client, preload.previous_heatmap),
1718 12 : );
1719 12 : }
1720 0 : MaybeDeletedIndexPart::Deleted(index_part) => {
1721 0 : info!(
1722 0 : "timeline {} is deleted, picking to resume deletion",
1723 : timeline_id
1724 : );
1725 0 : timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
1726 : }
1727 : }
1728 : }
1729 :
1730 460 : let mut gc_blocks = HashMap::new();
1731 :
1732 : // For every timeline, download the metadata file, scan the local directory,
1733 : // and build a layer map that contains an entry for each remote and local
1734 : // layer file.
1735 460 : let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
1736 472 : for (timeline_id, remote_metadata) in sorted_timelines {
1737 12 : let (index_part, remote_client, previous_heatmap) = remote_index_and_client
1738 12 : .remove(&timeline_id)
1739 12 : .expect("just put it in above");
1740 :
1741 12 : if let Some(blocking) = index_part.gc_blocking.as_ref() {
1742 : // could just filter these away, but it helps while testing
1743 0 : anyhow::ensure!(
1744 0 : !blocking.reasons.is_empty(),
1745 0 : "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
1746 : );
1747 0 : let prev = gc_blocks.insert(timeline_id, blocking.reasons);
1748 0 : assert!(prev.is_none());
1749 12 : }
1750 :
1751 : // TODO again handle early failure
1752 12 : let effect = self
1753 12 : .load_remote_timeline(
1754 12 : timeline_id,
1755 12 : index_part,
1756 12 : remote_metadata,
1757 12 : previous_heatmap,
1758 12 : self.get_timeline_resources_for(remote_client),
1759 12 : LoadTimelineCause::Attach,
1760 12 : ctx,
1761 12 : )
1762 12 : .await
1763 12 : .with_context(|| {
1764 0 : format!(
1765 0 : "failed to load remote timeline {} for tenant {}",
1766 0 : timeline_id, self.tenant_shard_id
1767 0 : )
1768 12 : })?;
1769 :
1770 12 : match effect {
1771 12 : TimelineInitAndSyncResult::ReadyToActivate(_) => {
1772 12 : // activation happens later, on Tenant::activate
1773 12 : }
1774 : TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
1775 : TimelineInitAndSyncNeedsSpawnImportPgdata {
1776 0 : timeline,
1777 0 : import_pgdata,
1778 0 : guard,
1779 0 : },
1780 0 : ) => {
1781 0 : tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
1782 0 : timeline,
1783 0 : import_pgdata,
1784 0 : ActivateTimelineArgs::No,
1785 0 : guard,
1786 0 : ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
1787 0 : ));
1788 0 : }
1789 : }
1790 : }
1791 :
1792 : // Walk through deleted timelines, resume deletion
1793 460 : for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
1794 0 : remote_timeline_client
1795 0 : .init_upload_queue_stopped_to_continue_deletion(&index_part)
1796 0 : .context("init queue stopped")
1797 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1798 :
1799 0 : DeleteTimelineFlow::resume_deletion(
1800 0 : Arc::clone(self),
1801 0 : timeline_id,
1802 0 : &index_part.metadata,
1803 0 : remote_timeline_client,
1804 0 : ctx,
1805 0 : )
1806 0 : .instrument(tracing::info_span!("timeline_delete", %timeline_id))
1807 0 : .await
1808 0 : .context("resume_deletion")
1809 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1810 : }
1811 460 : {
1812 460 : let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
1813 460 : offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
1814 460 : }
1815 :
1816 : // Stash the preloaded tenant manifest, and upload a new manifest if changed.
1817 : //
1818 : // NB: this must happen after the tenant is fully populated above. In particular the
1819 : // offloaded timelines, which are included in the manifest.
1820 : {
1821 460 : let mut guard = self.remote_tenant_manifest.lock().await;
1822 460 : assert!(guard.is_none(), "tenant manifest set before preload"); // first populated here
1823 460 : *guard = preload.tenant_manifest;
1824 460 : }
1825 460 : self.maybe_upload_tenant_manifest().await?;
1826 :
1827 : // The local filesystem contents are a cache of what's in the remote IndexPart;
1828 : // IndexPart is the source of truth.
1829 460 : self.clean_up_timelines(&existent_timelines)?;
1830 :
1831 460 : self.gc_block.set_scanned(gc_blocks);
1832 460 :
1833 460 : fail::fail_point!("attach-before-activate", |_| {
1834 0 : anyhow::bail!("attach-before-activate");
1835 460 : });
1836 460 : failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
1837 :
1838 460 : info!("Done");
1839 :
1840 460 : Ok(())
1841 460 : }
1842 :
1843 : /// Check for any local timeline directories that are temporary, or do not correspond to a
1844 : /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
1845 : /// if a timeline was deleted while the tenant was attached to a different pageserver.
1846 460 : fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
1847 460 : let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
1848 :
1849 460 : let entries = match timelines_dir.read_dir_utf8() {
1850 460 : Ok(d) => d,
1851 0 : Err(e) => {
1852 0 : if e.kind() == std::io::ErrorKind::NotFound {
1853 0 : return Ok(());
1854 : } else {
1855 0 : return Err(e).context("list timelines directory for tenant");
1856 : }
1857 : }
1858 : };
1859 :
1860 476 : for entry in entries {
1861 16 : let entry = entry.context("read timeline dir entry")?;
1862 16 : let entry_path = entry.path();
1863 :
1864 16 : let purge = if crate::is_temporary(entry_path) {
1865 0 : true
1866 : } else {
1867 16 : match TimelineId::try_from(entry_path.file_name()) {
1868 16 : Ok(i) => {
1869 16 : // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
1870 16 : !existent_timelines.contains(&i)
1871 : }
1872 0 : Err(e) => {
1873 0 : tracing::warn!(
1874 0 : "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
1875 : );
1876 : // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
1877 0 : false
1878 : }
1879 : }
1880 : };
1881 :
1882 16 : if purge {
1883 4 : tracing::info!("Purging stale timeline dentry {entry_path}");
1884 4 : if let Err(e) = match entry.file_type() {
1885 4 : Ok(t) => if t.is_dir() {
1886 4 : std::fs::remove_dir_all(entry_path)
1887 : } else {
1888 0 : std::fs::remove_file(entry_path)
1889 : }
1890 4 : .or_else(fs_ext::ignore_not_found),
1891 0 : Err(e) => Err(e),
1892 : } {
1893 0 : tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
1894 4 : }
1895 12 : }
1896 : }
1897 :
1898 460 : Ok(())
1899 460 : }
1900 :
1901 : /// Get sum of all remote timelines sizes
1902 : ///
1903 : /// This function relies on the index_part instead of listing the remote storage
1904 0 : pub fn remote_size(&self) -> u64 {
1905 0 : let mut size = 0;
1906 :
1907 0 : for timeline in self.list_timelines() {
1908 0 : size += timeline.remote_client.get_remote_physical_size();
1909 0 : }
1910 :
1911 0 : size
1912 0 : }
1913 :
1914 : #[instrument(skip_all, fields(timeline_id=%timeline_id))]
1915 : #[allow(clippy::too_many_arguments)]
1916 : async fn load_remote_timeline(
1917 : self: &Arc<Self>,
1918 : timeline_id: TimelineId,
1919 : index_part: IndexPart,
1920 : remote_metadata: TimelineMetadata,
1921 : previous_heatmap: Option<PreviousHeatmap>,
1922 : resources: TimelineResources,
1923 : cause: LoadTimelineCause,
1924 : ctx: &RequestContext,
1925 : ) -> anyhow::Result<TimelineInitAndSyncResult> {
1926 : span::debug_assert_current_span_has_tenant_id();
1927 :
1928 : info!("downloading index file for timeline {}", timeline_id);
1929 : tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
1930 : .await
1931 : .context("Failed to create new timeline directory")?;
1932 :
1933 : let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
1934 : let timelines = self.timelines.lock().unwrap();
1935 : Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
1936 0 : || {
1937 0 : anyhow::anyhow!(
1938 0 : "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
1939 0 : )
1940 0 : },
1941 : )?))
1942 : } else {
1943 : None
1944 : };
1945 :
1946 : self.timeline_init_and_sync(
1947 : timeline_id,
1948 : resources,
1949 : index_part,
1950 : remote_metadata,
1951 : previous_heatmap,
1952 : ancestor,
1953 : cause,
1954 : ctx,
1955 : )
1956 : .await
1957 : }
1958 :
1959 460 : async fn load_timelines_metadata(
1960 460 : self: &Arc<Tenant>,
1961 460 : timeline_ids: HashSet<TimelineId>,
1962 460 : remote_storage: &GenericRemoteStorage,
1963 460 : heatmap: Option<(HeatMapTenant, std::time::Instant)>,
1964 460 : cancel: CancellationToken,
1965 460 : ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
1966 460 : let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
1967 460 :
1968 460 : let mut part_downloads = JoinSet::new();
1969 472 : for timeline_id in timeline_ids {
1970 12 : let cancel_clone = cancel.clone();
1971 12 :
1972 12 : let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
1973 0 : hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
1974 0 : heatmap: h,
1975 0 : read_at: hs.1,
1976 0 : end_lsn: None,
1977 0 : })
1978 12 : });
1979 12 : part_downloads.spawn(
1980 12 : self.load_timeline_metadata(
1981 12 : timeline_id,
1982 12 : remote_storage.clone(),
1983 12 : previous_timeline_heatmap,
1984 12 : cancel_clone,
1985 12 : )
1986 12 : .instrument(info_span!("download_index_part", %timeline_id)),
1987 : );
1988 : }
1989 :
1990 460 : let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
1991 :
1992 : loop {
1993 472 : tokio::select!(
1994 472 : next = part_downloads.join_next() => {
1995 472 : match next {
1996 12 : Some(result) => {
1997 12 : let preload = result.context("join preload task")?;
1998 12 : timeline_preloads.insert(preload.timeline_id, preload);
1999 : },
2000 : None => {
2001 460 : break;
2002 : }
2003 : }
2004 : },
2005 472 : _ = cancel.cancelled() => {
2006 0 : anyhow::bail!("Cancelled while waiting for remote index download")
2007 : }
2008 : )
2009 : }
2010 :
2011 460 : Ok(timeline_preloads)
2012 460 : }
2013 :
2014 12 : fn build_timeline_client(
2015 12 : &self,
2016 12 : timeline_id: TimelineId,
2017 12 : remote_storage: GenericRemoteStorage,
2018 12 : ) -> RemoteTimelineClient {
2019 12 : RemoteTimelineClient::new(
2020 12 : remote_storage.clone(),
2021 12 : self.deletion_queue_client.clone(),
2022 12 : self.conf,
2023 12 : self.tenant_shard_id,
2024 12 : timeline_id,
2025 12 : self.generation,
2026 12 : &self.tenant_conf.load().location,
2027 12 : )
2028 12 : }
2029 :
2030 12 : fn load_timeline_metadata(
2031 12 : self: &Arc<Tenant>,
2032 12 : timeline_id: TimelineId,
2033 12 : remote_storage: GenericRemoteStorage,
2034 12 : previous_heatmap: Option<PreviousHeatmap>,
2035 12 : cancel: CancellationToken,
2036 12 : ) -> impl Future<Output = TimelinePreload> + use<> {
2037 12 : let client = self.build_timeline_client(timeline_id, remote_storage);
2038 12 : async move {
2039 12 : debug_assert_current_span_has_tenant_and_timeline_id();
2040 12 : debug!("starting index part download");
2041 :
2042 12 : let index_part = client.download_index_file(&cancel).await;
2043 :
2044 12 : debug!("finished index part download");
2045 :
2046 12 : TimelinePreload {
2047 12 : client,
2048 12 : timeline_id,
2049 12 : index_part,
2050 12 : previous_heatmap,
2051 12 : }
2052 12 : }
2053 12 : }
2054 :
2055 0 : fn check_to_be_archived_has_no_unarchived_children(
2056 0 : timeline_id: TimelineId,
2057 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
2058 0 : ) -> Result<(), TimelineArchivalError> {
2059 0 : let children: Vec<TimelineId> = timelines
2060 0 : .iter()
2061 0 : .filter_map(|(id, entry)| {
2062 0 : if entry.get_ancestor_timeline_id() != Some(timeline_id) {
2063 0 : return None;
2064 0 : }
2065 0 : if entry.is_archived() == Some(true) {
2066 0 : return None;
2067 0 : }
2068 0 : Some(*id)
2069 0 : })
2070 0 : .collect();
2071 0 :
2072 0 : if !children.is_empty() {
2073 0 : return Err(TimelineArchivalError::HasUnarchivedChildren(children));
2074 0 : }
2075 0 : Ok(())
2076 0 : }
2077 :
2078 0 : fn check_ancestor_of_to_be_unarchived_is_not_archived(
2079 0 : ancestor_timeline_id: TimelineId,
2080 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
2081 0 : offloaded_timelines: &std::sync::MutexGuard<
2082 0 : '_,
2083 0 : HashMap<TimelineId, Arc<OffloadedTimeline>>,
2084 0 : >,
2085 0 : ) -> Result<(), TimelineArchivalError> {
2086 0 : let has_archived_parent =
2087 0 : if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
2088 0 : ancestor_timeline.is_archived() == Some(true)
2089 0 : } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
2090 0 : true
2091 : } else {
2092 0 : error!("ancestor timeline {ancestor_timeline_id} not found");
2093 0 : if cfg!(debug_assertions) {
2094 0 : panic!("ancestor timeline {ancestor_timeline_id} not found");
2095 0 : }
2096 0 : return Err(TimelineArchivalError::NotFound);
2097 : };
2098 0 : if has_archived_parent {
2099 0 : return Err(TimelineArchivalError::HasArchivedParent(
2100 0 : ancestor_timeline_id,
2101 0 : ));
2102 0 : }
2103 0 : Ok(())
2104 0 : }
2105 :
2106 0 : fn check_to_be_unarchived_timeline_has_no_archived_parent(
2107 0 : timeline: &Arc<Timeline>,
2108 0 : ) -> Result<(), TimelineArchivalError> {
2109 0 : if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
2110 0 : if ancestor_timeline.is_archived() == Some(true) {
2111 0 : return Err(TimelineArchivalError::HasArchivedParent(
2112 0 : ancestor_timeline.timeline_id,
2113 0 : ));
2114 0 : }
2115 0 : }
2116 0 : Ok(())
2117 0 : }
2118 :
2119 : /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
2120 : ///
2121 : /// Counterpart to [`offload_timeline`].
2122 0 : async fn unoffload_timeline(
2123 0 : self: &Arc<Self>,
2124 0 : timeline_id: TimelineId,
2125 0 : broker_client: storage_broker::BrokerClientChannel,
2126 0 : ctx: RequestContext,
2127 0 : ) -> Result<Arc<Timeline>, TimelineArchivalError> {
2128 0 : info!("unoffloading timeline");
2129 :
2130 : // We activate the timeline below manually, so this must be called on an active tenant.
2131 : // We expect callers of this function to ensure this.
2132 0 : match self.current_state() {
2133 : TenantState::Activating { .. }
2134 : | TenantState::Attaching
2135 : | TenantState::Broken { .. } => {
2136 0 : panic!("Timeline expected to be active")
2137 : }
2138 0 : TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
2139 0 : TenantState::Active => {}
2140 0 : }
2141 0 : let cancel = self.cancel.clone();
2142 0 :
2143 0 : // Protect against concurrent attempts to use this TimelineId
2144 0 : // We don't care much about idempotency, as it's ensured a layer above.
2145 0 : let allow_offloaded = true;
2146 0 : let _create_guard = self
2147 0 : .create_timeline_create_guard(
2148 0 : timeline_id,
2149 0 : CreateTimelineIdempotency::FailWithConflict,
2150 0 : allow_offloaded,
2151 0 : )
2152 0 : .map_err(|err| match err {
2153 0 : TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
2154 : TimelineExclusionError::AlreadyExists { .. } => {
2155 0 : TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
2156 : }
2157 0 : TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
2158 0 : TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
2159 0 : })?;
2160 :
2161 0 : let timeline_preload = self
2162 0 : .load_timeline_metadata(
2163 0 : timeline_id,
2164 0 : self.remote_storage.clone(),
2165 0 : None,
2166 0 : cancel.clone(),
2167 0 : )
2168 0 : .await;
2169 :
2170 0 : let index_part = match timeline_preload.index_part {
2171 0 : Ok(index_part) => {
2172 0 : debug!("remote index part exists for timeline {timeline_id}");
2173 0 : index_part
2174 : }
2175 : Err(DownloadError::NotFound) => {
2176 0 : error!(%timeline_id, "index_part not found on remote");
2177 0 : return Err(TimelineArchivalError::NotFound);
2178 : }
2179 0 : Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
2180 0 : Err(e) => {
2181 0 : // Some (possibly ephemeral) error happened during index_part download.
2182 0 : warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
2183 0 : return Err(TimelineArchivalError::Other(
2184 0 : anyhow::Error::new(e).context("downloading index_part from remote storage"),
2185 0 : ));
2186 : }
2187 : };
2188 0 : let index_part = match index_part {
2189 0 : MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
2190 0 : MaybeDeletedIndexPart::Deleted(_index_part) => {
2191 0 : info!("timeline is deleted according to index_part.json");
2192 0 : return Err(TimelineArchivalError::NotFound);
2193 : }
2194 : };
2195 0 : let remote_metadata = index_part.metadata.clone();
2196 0 : let timeline_resources = self.build_timeline_resources(timeline_id);
2197 0 : self.load_remote_timeline(
2198 0 : timeline_id,
2199 0 : index_part,
2200 0 : remote_metadata,
2201 0 : None,
2202 0 : timeline_resources,
2203 0 : LoadTimelineCause::Unoffload,
2204 0 : &ctx,
2205 0 : )
2206 0 : .await
2207 0 : .with_context(|| {
2208 0 : format!(
2209 0 : "failed to load remote timeline {} for tenant {}",
2210 0 : timeline_id, self.tenant_shard_id
2211 0 : )
2212 0 : })
2213 0 : .map_err(TimelineArchivalError::Other)?;
2214 :
2215 0 : let timeline = {
2216 0 : let timelines = self.timelines.lock().unwrap();
2217 0 : let Some(timeline) = timelines.get(&timeline_id) else {
2218 0 : warn!("timeline not available directly after attach");
2219 : // This is not a panic because no locks are held between `load_remote_timeline`
2220 : // which puts the timeline into timelines, and our look into the timeline map.
2221 0 : return Err(TimelineArchivalError::Other(anyhow::anyhow!(
2222 0 : "timeline not available directly after attach"
2223 0 : )));
2224 : };
2225 0 : let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
2226 0 : match offloaded_timelines.remove(&timeline_id) {
2227 0 : Some(offloaded) => {
2228 0 : offloaded.delete_from_ancestor_with_timelines(&timelines);
2229 0 : }
2230 0 : None => warn!("timeline already removed from offloaded timelines"),
2231 : }
2232 :
2233 0 : self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
2234 0 :
2235 0 : Arc::clone(timeline)
2236 0 : };
2237 0 :
2238 0 : // Upload new list of offloaded timelines to S3
2239 0 : self.maybe_upload_tenant_manifest().await?;
2240 :
2241 : // Activate the timeline (if it makes sense)
2242 0 : if !(timeline.is_broken() || timeline.is_stopping()) {
2243 0 : let background_jobs_can_start = None;
2244 0 : timeline.activate(
2245 0 : self.clone(),
2246 0 : broker_client.clone(),
2247 0 : background_jobs_can_start,
2248 0 : &ctx.with_scope_timeline(&timeline),
2249 0 : );
2250 0 : }
2251 :
2252 0 : info!("timeline unoffloading complete");
2253 0 : Ok(timeline)
2254 0 : }
2255 :
2256 0 : pub(crate) async fn apply_timeline_archival_config(
2257 0 : self: &Arc<Self>,
2258 0 : timeline_id: TimelineId,
2259 0 : new_state: TimelineArchivalState,
2260 0 : broker_client: storage_broker::BrokerClientChannel,
2261 0 : ctx: RequestContext,
2262 0 : ) -> Result<(), TimelineArchivalError> {
2263 0 : info!("setting timeline archival config");
2264 : // First part: figure out what is needed to do, and do validation
2265 0 : let timeline_or_unarchive_offloaded = 'outer: {
2266 0 : let timelines = self.timelines.lock().unwrap();
2267 :
2268 0 : let Some(timeline) = timelines.get(&timeline_id) else {
2269 0 : let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
2270 0 : let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
2271 0 : return Err(TimelineArchivalError::NotFound);
2272 : };
2273 0 : if new_state == TimelineArchivalState::Archived {
2274 : // It's offloaded already, so nothing to do
2275 0 : return Ok(());
2276 0 : }
2277 0 : if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
2278 0 : Self::check_ancestor_of_to_be_unarchived_is_not_archived(
2279 0 : ancestor_timeline_id,
2280 0 : &timelines,
2281 0 : &offloaded_timelines,
2282 0 : )?;
2283 0 : }
2284 0 : break 'outer None;
2285 : };
2286 :
2287 : // Do some validation. We release the timelines lock below, so there is potential
2288 : // for race conditions: these checks are more present to prevent misunderstandings of
2289 : // the API's capabilities, instead of serving as the sole way to defend their invariants.
2290 0 : match new_state {
2291 : TimelineArchivalState::Unarchived => {
2292 0 : Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
2293 : }
2294 : TimelineArchivalState::Archived => {
2295 0 : Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
2296 : }
2297 : }
2298 0 : Some(Arc::clone(timeline))
2299 : };
2300 :
2301 : // Second part: unoffload timeline (if needed)
2302 0 : let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
2303 0 : timeline
2304 : } else {
2305 : // Turn offloaded timeline into a non-offloaded one
2306 0 : self.unoffload_timeline(timeline_id, broker_client, ctx)
2307 0 : .await?
2308 : };
2309 :
2310 : // Third part: upload new timeline archival state and block until it is present in S3
2311 0 : let upload_needed = match timeline
2312 0 : .remote_client
2313 0 : .schedule_index_upload_for_timeline_archival_state(new_state)
2314 : {
2315 0 : Ok(upload_needed) => upload_needed,
2316 0 : Err(e) => {
2317 0 : if timeline.cancel.is_cancelled() {
2318 0 : return Err(TimelineArchivalError::Cancelled);
2319 : } else {
2320 0 : return Err(TimelineArchivalError::Other(e));
2321 : }
2322 : }
2323 : };
2324 :
2325 0 : if upload_needed {
2326 0 : info!("Uploading new state");
2327 : const MAX_WAIT: Duration = Duration::from_secs(10);
2328 0 : let Ok(v) =
2329 0 : tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
2330 : else {
2331 0 : tracing::warn!("reached timeout for waiting on upload queue");
2332 0 : return Err(TimelineArchivalError::Timeout);
2333 : };
2334 0 : v.map_err(|e| match e {
2335 0 : WaitCompletionError::NotInitialized(e) => {
2336 0 : TimelineArchivalError::Other(anyhow::anyhow!(e))
2337 : }
2338 : WaitCompletionError::UploadQueueShutDownOrStopped => {
2339 0 : TimelineArchivalError::Cancelled
2340 : }
2341 0 : })?;
2342 0 : }
2343 0 : Ok(())
2344 0 : }
2345 :
2346 4 : pub fn get_offloaded_timeline(
2347 4 : &self,
2348 4 : timeline_id: TimelineId,
2349 4 : ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
2350 4 : self.timelines_offloaded
2351 4 : .lock()
2352 4 : .unwrap()
2353 4 : .get(&timeline_id)
2354 4 : .map(Arc::clone)
2355 4 : .ok_or(GetTimelineError::NotFound {
2356 4 : tenant_id: self.tenant_shard_id,
2357 4 : timeline_id,
2358 4 : })
2359 4 : }
2360 :
2361 8 : pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
2362 8 : self.tenant_shard_id
2363 8 : }
2364 :
2365 : /// Get Timeline handle for given Neon timeline ID.
2366 : /// This function is idempotent. It doesn't change internal state in any way.
2367 444 : pub fn get_timeline(
2368 444 : &self,
2369 444 : timeline_id: TimelineId,
2370 444 : active_only: bool,
2371 444 : ) -> Result<Arc<Timeline>, GetTimelineError> {
2372 444 : let timelines_accessor = self.timelines.lock().unwrap();
2373 444 : let timeline = timelines_accessor
2374 444 : .get(&timeline_id)
2375 444 : .ok_or(GetTimelineError::NotFound {
2376 444 : tenant_id: self.tenant_shard_id,
2377 444 : timeline_id,
2378 444 : })?;
2379 :
2380 440 : if active_only && !timeline.is_active() {
2381 0 : Err(GetTimelineError::NotActive {
2382 0 : tenant_id: self.tenant_shard_id,
2383 0 : timeline_id,
2384 0 : state: timeline.current_state(),
2385 0 : })
2386 : } else {
2387 440 : Ok(Arc::clone(timeline))
2388 : }
2389 444 : }
2390 :
2391 : /// Lists timelines the tenant contains.
2392 : /// It's up to callers to omit certain timelines that are not considered ready for use.
2393 8 : pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
2394 8 : self.timelines
2395 8 : .lock()
2396 8 : .unwrap()
2397 8 : .values()
2398 8 : .map(Arc::clone)
2399 8 : .collect()
2400 8 : }
2401 :
2402 : /// Lists timelines the tenant manages, including offloaded ones.
2403 : ///
2404 : /// It's up to callers to omit certain timelines that are not considered ready for use.
2405 0 : pub fn list_timelines_and_offloaded(
2406 0 : &self,
2407 0 : ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
2408 0 : let timelines = self
2409 0 : .timelines
2410 0 : .lock()
2411 0 : .unwrap()
2412 0 : .values()
2413 0 : .map(Arc::clone)
2414 0 : .collect();
2415 0 : let offloaded = self
2416 0 : .timelines_offloaded
2417 0 : .lock()
2418 0 : .unwrap()
2419 0 : .values()
2420 0 : .map(Arc::clone)
2421 0 : .collect();
2422 0 : (timelines, offloaded)
2423 0 : }
2424 :
2425 0 : pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
2426 0 : self.timelines.lock().unwrap().keys().cloned().collect()
2427 0 : }
2428 :
2429 : /// This is used by tests & import-from-basebackup.
2430 : ///
2431 : /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
2432 : /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
2433 : ///
2434 : /// The caller is responsible for getting the timeline into a state that will be accepted
2435 : /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
2436 : /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
2437 : /// to the [`Tenant::timelines`].
2438 : ///
2439 : /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
2440 444 : pub(crate) async fn create_empty_timeline(
2441 444 : self: &Arc<Self>,
2442 444 : new_timeline_id: TimelineId,
2443 444 : initdb_lsn: Lsn,
2444 444 : pg_version: u32,
2445 444 : ctx: &RequestContext,
2446 444 : ) -> anyhow::Result<(UninitializedTimeline, RequestContext)> {
2447 444 : anyhow::ensure!(
2448 444 : self.is_active(),
2449 0 : "Cannot create empty timelines on inactive tenant"
2450 : );
2451 :
2452 : // Protect against concurrent attempts to use this TimelineId
2453 444 : let create_guard = match self
2454 444 : .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
2455 444 : .await?
2456 : {
2457 440 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
2458 : StartCreatingTimelineResult::Idempotent(_) => {
2459 0 : unreachable!("FailWithConflict implies we get an error instead")
2460 : }
2461 : };
2462 :
2463 440 : let new_metadata = TimelineMetadata::new(
2464 440 : // Initialize disk_consistent LSN to 0, The caller must import some data to
2465 440 : // make it valid, before calling finish_creation()
2466 440 : Lsn(0),
2467 440 : None,
2468 440 : None,
2469 440 : Lsn(0),
2470 440 : initdb_lsn,
2471 440 : initdb_lsn,
2472 440 : pg_version,
2473 440 : );
2474 440 : self.prepare_new_timeline(
2475 440 : new_timeline_id,
2476 440 : &new_metadata,
2477 440 : create_guard,
2478 440 : initdb_lsn,
2479 440 : None,
2480 440 : None,
2481 440 : ctx,
2482 440 : )
2483 440 : .await
2484 444 : }
2485 :
2486 : /// Helper for unit tests to create an empty timeline.
2487 : ///
2488 : /// The timeline is has state value `Active` but its background loops are not running.
2489 : // This makes the various functions which anyhow::ensure! for Active state work in tests.
2490 : // Our current tests don't need the background loops.
2491 : #[cfg(test)]
2492 424 : pub async fn create_test_timeline(
2493 424 : self: &Arc<Self>,
2494 424 : new_timeline_id: TimelineId,
2495 424 : initdb_lsn: Lsn,
2496 424 : pg_version: u32,
2497 424 : ctx: &RequestContext,
2498 424 : ) -> anyhow::Result<Arc<Timeline>> {
2499 424 : let (uninit_tl, ctx) = self
2500 424 : .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
2501 424 : .await?;
2502 424 : let tline = uninit_tl.raw_timeline().expect("we just created it");
2503 424 : assert_eq!(tline.get_last_record_lsn(), Lsn(0));
2504 :
2505 : // Setup minimum keys required for the timeline to be usable.
2506 424 : let mut modification = tline.begin_modification(initdb_lsn);
2507 424 : modification
2508 424 : .init_empty_test_timeline()
2509 424 : .context("init_empty_test_timeline")?;
2510 424 : modification
2511 424 : .commit(&ctx)
2512 424 : .await
2513 424 : .context("commit init_empty_test_timeline modification")?;
2514 :
2515 : // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
2516 424 : tline.maybe_spawn_flush_loop();
2517 424 : tline.freeze_and_flush().await.context("freeze_and_flush")?;
2518 :
2519 : // Make sure the freeze_and_flush reaches remote storage.
2520 424 : tline.remote_client.wait_completion().await.unwrap();
2521 :
2522 424 : let tl = uninit_tl.finish_creation().await?;
2523 : // The non-test code would call tl.activate() here.
2524 424 : tl.set_state(TimelineState::Active);
2525 424 : Ok(tl)
2526 424 : }
2527 :
2528 : /// Helper for unit tests to create a timeline with some pre-loaded states.
2529 : #[cfg(test)]
2530 : #[allow(clippy::too_many_arguments)]
2531 92 : pub async fn create_test_timeline_with_layers(
2532 92 : self: &Arc<Self>,
2533 92 : new_timeline_id: TimelineId,
2534 92 : initdb_lsn: Lsn,
2535 92 : pg_version: u32,
2536 92 : ctx: &RequestContext,
2537 92 : in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
2538 92 : delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
2539 92 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
2540 92 : end_lsn: Lsn,
2541 92 : ) -> anyhow::Result<Arc<Timeline>> {
2542 : use checks::check_valid_layermap;
2543 : use itertools::Itertools;
2544 :
2545 92 : let tline = self
2546 92 : .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
2547 92 : .await?;
2548 92 : tline.force_advance_lsn(end_lsn);
2549 268 : for deltas in delta_layer_desc {
2550 176 : tline
2551 176 : .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
2552 176 : .await?;
2553 : }
2554 216 : for (lsn, images) in image_layer_desc {
2555 124 : tline
2556 124 : .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
2557 124 : .await?;
2558 : }
2559 100 : for in_memory in in_memory_layer_desc {
2560 8 : tline
2561 8 : .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
2562 8 : .await?;
2563 : }
2564 92 : let layer_names = tline
2565 92 : .layers
2566 92 : .read()
2567 92 : .await
2568 92 : .layer_map()
2569 92 : .unwrap()
2570 92 : .iter_historic_layers()
2571 392 : .map(|layer| layer.layer_name())
2572 92 : .collect_vec();
2573 92 : if let Some(err) = check_valid_layermap(&layer_names) {
2574 0 : bail!("invalid layermap: {err}");
2575 92 : }
2576 92 : Ok(tline)
2577 92 : }
2578 :
2579 : /// Create a new timeline.
2580 : ///
2581 : /// Returns the new timeline ID and reference to its Timeline object.
2582 : ///
2583 : /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
2584 : /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
2585 : #[allow(clippy::too_many_arguments)]
2586 0 : pub(crate) async fn create_timeline(
2587 0 : self: &Arc<Tenant>,
2588 0 : params: CreateTimelineParams,
2589 0 : broker_client: storage_broker::BrokerClientChannel,
2590 0 : ctx: &RequestContext,
2591 0 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
2592 0 : if !self.is_active() {
2593 0 : if matches!(self.current_state(), TenantState::Stopping { .. }) {
2594 0 : return Err(CreateTimelineError::ShuttingDown);
2595 : } else {
2596 0 : return Err(CreateTimelineError::Other(anyhow::anyhow!(
2597 0 : "Cannot create timelines on inactive tenant"
2598 0 : )));
2599 : }
2600 0 : }
2601 :
2602 0 : let _gate = self
2603 0 : .gate
2604 0 : .enter()
2605 0 : .map_err(|_| CreateTimelineError::ShuttingDown)?;
2606 :
2607 0 : let result: CreateTimelineResult = match params {
2608 : CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
2609 0 : new_timeline_id,
2610 0 : existing_initdb_timeline_id,
2611 0 : pg_version,
2612 0 : }) => {
2613 0 : self.bootstrap_timeline(
2614 0 : new_timeline_id,
2615 0 : pg_version,
2616 0 : existing_initdb_timeline_id,
2617 0 : ctx,
2618 0 : )
2619 0 : .await?
2620 : }
2621 : CreateTimelineParams::Branch(CreateTimelineParamsBranch {
2622 0 : new_timeline_id,
2623 0 : ancestor_timeline_id,
2624 0 : mut ancestor_start_lsn,
2625 : }) => {
2626 0 : let ancestor_timeline = self
2627 0 : .get_timeline(ancestor_timeline_id, false)
2628 0 : .context("Cannot branch off the timeline that's not present in pageserver")?;
2629 :
2630 : // instead of waiting around, just deny the request because ancestor is not yet
2631 : // ready for other purposes either.
2632 0 : if !ancestor_timeline.is_active() {
2633 0 : return Err(CreateTimelineError::AncestorNotActive);
2634 0 : }
2635 0 :
2636 0 : if ancestor_timeline.is_archived() == Some(true) {
2637 0 : info!("tried to branch archived timeline");
2638 0 : return Err(CreateTimelineError::AncestorArchived);
2639 0 : }
2640 :
2641 0 : if let Some(lsn) = ancestor_start_lsn.as_mut() {
2642 0 : *lsn = lsn.align();
2643 0 :
2644 0 : let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
2645 0 : if ancestor_ancestor_lsn > *lsn {
2646 : // can we safely just branch from the ancestor instead?
2647 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
2648 0 : "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
2649 0 : lsn,
2650 0 : ancestor_timeline_id,
2651 0 : ancestor_ancestor_lsn,
2652 0 : )));
2653 0 : }
2654 0 :
2655 0 : // Wait for the WAL to arrive and be processed on the parent branch up
2656 0 : // to the requested branch point. The repository code itself doesn't
2657 0 : // require it, but if we start to receive WAL on the new timeline,
2658 0 : // decoding the new WAL might need to look up previous pages, relation
2659 0 : // sizes etc. and that would get confused if the previous page versions
2660 0 : // are not in the repository yet.
2661 0 : ancestor_timeline
2662 0 : .wait_lsn(
2663 0 : *lsn,
2664 0 : timeline::WaitLsnWaiter::Tenant,
2665 0 : timeline::WaitLsnTimeout::Default,
2666 0 : ctx,
2667 0 : )
2668 0 : .await
2669 0 : .map_err(|e| match e {
2670 0 : e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
2671 0 : CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
2672 : }
2673 0 : WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
2674 0 : })?;
2675 0 : }
2676 :
2677 0 : self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
2678 0 : .await?
2679 : }
2680 0 : CreateTimelineParams::ImportPgdata(params) => {
2681 0 : self.create_timeline_import_pgdata(
2682 0 : params,
2683 0 : ActivateTimelineArgs::Yes {
2684 0 : broker_client: broker_client.clone(),
2685 0 : },
2686 0 : ctx,
2687 0 : )
2688 0 : .await?
2689 : }
2690 : };
2691 :
2692 : // At this point we have dropped our guard on [`Self::timelines_creating`], and
2693 : // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet. We must
2694 : // not send a success to the caller until it is. The same applies to idempotent retries.
2695 : //
2696 : // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
2697 : // assume that, because they can see the timeline via API, that the creation is done and
2698 : // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
2699 : // until it is durable, e.g., by extending the time we hold the creation guard. This also
2700 : // interacts with UninitializedTimeline and is generally a bit tricky.
2701 : //
2702 : // To re-emphasize: the only correct way to create a timeline is to repeat calling the
2703 : // creation API until it returns success. Only then is durability guaranteed.
2704 0 : info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
2705 0 : result
2706 0 : .timeline()
2707 0 : .remote_client
2708 0 : .wait_completion()
2709 0 : .await
2710 0 : .map_err(|e| match e {
2711 : WaitCompletionError::NotInitialized(
2712 0 : e, // If the queue is already stopped, it's a shutdown error.
2713 0 : ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
2714 : WaitCompletionError::NotInitialized(_) => {
2715 : // This is a bug: we should never try to wait for uploads before initializing the timeline
2716 0 : debug_assert!(false);
2717 0 : CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
2718 : }
2719 : WaitCompletionError::UploadQueueShutDownOrStopped => {
2720 0 : CreateTimelineError::ShuttingDown
2721 : }
2722 0 : })?;
2723 :
2724 : // The creating task is responsible for activating the timeline.
2725 : // We do this after `wait_completion()` so that we don't spin up tasks that start
2726 : // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
2727 0 : let activated_timeline = match result {
2728 0 : CreateTimelineResult::Created(timeline) => {
2729 0 : timeline.activate(
2730 0 : self.clone(),
2731 0 : broker_client,
2732 0 : None,
2733 0 : &ctx.with_scope_timeline(&timeline),
2734 0 : );
2735 0 : timeline
2736 : }
2737 0 : CreateTimelineResult::Idempotent(timeline) => {
2738 0 : info!(
2739 0 : "request was deemed idempotent, activation will be done by the creating task"
2740 : );
2741 0 : timeline
2742 : }
2743 0 : CreateTimelineResult::ImportSpawned(timeline) => {
2744 0 : info!(
2745 0 : "import task spawned, timeline will become visible and activated once the import is done"
2746 : );
2747 0 : timeline
2748 : }
2749 : };
2750 :
2751 0 : Ok(activated_timeline)
2752 0 : }
2753 :
2754 : /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
2755 : /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
2756 : /// [`Tenant::timelines`] map when the import completes.
2757 : /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
2758 : /// for the response.
2759 0 : async fn create_timeline_import_pgdata(
2760 0 : self: &Arc<Tenant>,
2761 0 : params: CreateTimelineParamsImportPgdata,
2762 0 : activate: ActivateTimelineArgs,
2763 0 : ctx: &RequestContext,
2764 0 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
2765 0 : let CreateTimelineParamsImportPgdata {
2766 0 : new_timeline_id,
2767 0 : location,
2768 0 : idempotency_key,
2769 0 : } = params;
2770 0 :
2771 0 : let started_at = chrono::Utc::now().naive_utc();
2772 :
2773 : //
2774 : // There's probably a simpler way to upload an index part, but, remote_timeline_client
2775 : // is the canonical way we do it.
2776 : // - create an empty timeline in-memory
2777 : // - use its remote_timeline_client to do the upload
2778 : // - dispose of the uninit timeline
2779 : // - keep the creation guard alive
2780 :
2781 0 : let timeline_create_guard = match self
2782 0 : .start_creating_timeline(
2783 0 : new_timeline_id,
2784 0 : CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
2785 0 : idempotency_key: idempotency_key.clone(),
2786 0 : }),
2787 0 : )
2788 0 : .await?
2789 : {
2790 0 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
2791 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
2792 0 : return Ok(CreateTimelineResult::Idempotent(timeline));
2793 : }
2794 : };
2795 :
2796 0 : let (mut uninit_timeline, timeline_ctx) = {
2797 0 : let this = &self;
2798 0 : let initdb_lsn = Lsn(0);
2799 0 : async move {
2800 0 : let new_metadata = TimelineMetadata::new(
2801 0 : // Initialize disk_consistent LSN to 0, The caller must import some data to
2802 0 : // make it valid, before calling finish_creation()
2803 0 : Lsn(0),
2804 0 : None,
2805 0 : None,
2806 0 : Lsn(0),
2807 0 : initdb_lsn,
2808 0 : initdb_lsn,
2809 0 : 15,
2810 0 : );
2811 0 : this.prepare_new_timeline(
2812 0 : new_timeline_id,
2813 0 : &new_metadata,
2814 0 : timeline_create_guard,
2815 0 : initdb_lsn,
2816 0 : None,
2817 0 : None,
2818 0 : ctx,
2819 0 : )
2820 0 : .await
2821 0 : }
2822 0 : }
2823 0 : .await?;
2824 :
2825 0 : let in_progress = import_pgdata::index_part_format::InProgress {
2826 0 : idempotency_key,
2827 0 : location,
2828 0 : started_at,
2829 0 : };
2830 0 : let index_part = import_pgdata::index_part_format::Root::V1(
2831 0 : import_pgdata::index_part_format::V1::InProgress(in_progress),
2832 0 : );
2833 0 : uninit_timeline
2834 0 : .raw_timeline()
2835 0 : .unwrap()
2836 0 : .remote_client
2837 0 : .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
2838 :
2839 : // wait_completion happens in caller
2840 :
2841 0 : let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
2842 0 :
2843 0 : tokio::spawn(self.clone().create_timeline_import_pgdata_task(
2844 0 : timeline.clone(),
2845 0 : index_part,
2846 0 : activate,
2847 0 : timeline_create_guard,
2848 0 : timeline_ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
2849 0 : ));
2850 0 :
2851 0 : // NB: the timeline doesn't exist in self.timelines at this point
2852 0 : Ok(CreateTimelineResult::ImportSpawned(timeline))
2853 0 : }
2854 :
2855 : #[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))]
2856 : async fn create_timeline_import_pgdata_task(
2857 : self: Arc<Tenant>,
2858 : timeline: Arc<Timeline>,
2859 : index_part: import_pgdata::index_part_format::Root,
2860 : activate: ActivateTimelineArgs,
2861 : timeline_create_guard: TimelineCreateGuard,
2862 : ctx: RequestContext,
2863 : ) {
2864 : debug_assert_current_span_has_tenant_and_timeline_id();
2865 : info!("starting");
2866 : scopeguard::defer! {info!("exiting")};
2867 :
2868 : let res = self
2869 : .create_timeline_import_pgdata_task_impl(
2870 : timeline,
2871 : index_part,
2872 : activate,
2873 : timeline_create_guard,
2874 : ctx,
2875 : )
2876 : .await;
2877 : if let Err(err) = &res {
2878 : error!(?err, "task failed");
2879 : // TODO sleep & retry, sensitive to tenant shutdown
2880 : // TODO: allow timeline deletion requests => should cancel the task
2881 : }
2882 : }
2883 :
2884 0 : async fn create_timeline_import_pgdata_task_impl(
2885 0 : self: Arc<Tenant>,
2886 0 : timeline: Arc<Timeline>,
2887 0 : index_part: import_pgdata::index_part_format::Root,
2888 0 : activate: ActivateTimelineArgs,
2889 0 : timeline_create_guard: TimelineCreateGuard,
2890 0 : ctx: RequestContext,
2891 0 : ) -> Result<(), anyhow::Error> {
2892 0 : info!("importing pgdata");
2893 0 : import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
2894 0 : .await
2895 0 : .context("import")?;
2896 0 : info!("import done");
2897 :
2898 : //
2899 : // Reload timeline from remote.
2900 : // This proves that the remote state is attachable, and it reuses the code.
2901 : //
2902 : // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
2903 : // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
2904 : // But our activate() call might launch new background tasks after Tenant::shutdown
2905 : // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
2906 : // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
2907 : // down while bootstrapping/branching + activating), but, the race condition is much more likely
2908 : // to manifest because of the long runtime of this import task.
2909 :
2910 : // in theory this shouldn't even .await anything except for coop yield
2911 0 : info!("shutting down timeline");
2912 0 : timeline.shutdown(ShutdownMode::Hard).await;
2913 0 : info!("timeline shut down, reloading from remote");
2914 : // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
2915 : // let Some(timeline) = Arc::into_inner(timeline) else {
2916 : // anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
2917 : // };
2918 0 : let timeline_id = timeline.timeline_id;
2919 0 :
2920 0 : // load from object storage like Tenant::attach does
2921 0 : let resources = self.build_timeline_resources(timeline_id);
2922 0 : let index_part = resources
2923 0 : .remote_client
2924 0 : .download_index_file(&self.cancel)
2925 0 : .await?;
2926 0 : let index_part = match index_part {
2927 : MaybeDeletedIndexPart::Deleted(_) => {
2928 : // likely concurrent delete call, cplane should prevent this
2929 0 : anyhow::bail!(
2930 0 : "index part says deleted but we are not done creating yet, this should not happen but"
2931 0 : )
2932 : }
2933 0 : MaybeDeletedIndexPart::IndexPart(p) => p,
2934 0 : };
2935 0 : let metadata = index_part.metadata.clone();
2936 0 : self
2937 0 : .load_remote_timeline(timeline_id, index_part, metadata, None, resources, LoadTimelineCause::ImportPgdata{
2938 0 : create_guard: timeline_create_guard, activate, }, &ctx)
2939 0 : .await?
2940 0 : .ready_to_activate()
2941 0 : .context("implementation error: reloaded timeline still needs import after import reported success")?;
2942 :
2943 0 : anyhow::Ok(())
2944 0 : }
2945 :
2946 0 : pub(crate) async fn delete_timeline(
2947 0 : self: Arc<Self>,
2948 0 : timeline_id: TimelineId,
2949 0 : ) -> Result<(), DeleteTimelineError> {
2950 0 : DeleteTimelineFlow::run(&self, timeline_id).await?;
2951 :
2952 0 : Ok(())
2953 0 : }
2954 :
2955 : /// perform one garbage collection iteration, removing old data files from disk.
2956 : /// this function is periodically called by gc task.
2957 : /// also it can be explicitly requested through page server api 'do_gc' command.
2958 : ///
2959 : /// `target_timeline_id` specifies the timeline to GC, or None for all.
2960 : ///
2961 : /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
2962 : /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
2963 : /// the amount of history, as LSN difference from current latest LSN on each timeline.
2964 : /// `pitr` specifies the same as a time difference from the current time. The effective
2965 : /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
2966 : /// requires more history to be retained.
2967 : //
2968 1508 : pub(crate) async fn gc_iteration(
2969 1508 : &self,
2970 1508 : target_timeline_id: Option<TimelineId>,
2971 1508 : horizon: u64,
2972 1508 : pitr: Duration,
2973 1508 : cancel: &CancellationToken,
2974 1508 : ctx: &RequestContext,
2975 1508 : ) -> Result<GcResult, GcError> {
2976 1508 : // Don't start doing work during shutdown
2977 1508 : if let TenantState::Stopping { .. } = self.current_state() {
2978 0 : return Ok(GcResult::default());
2979 1508 : }
2980 1508 :
2981 1508 : // there is a global allowed_error for this
2982 1508 : if !self.is_active() {
2983 0 : return Err(GcError::NotActive);
2984 1508 : }
2985 1508 :
2986 1508 : {
2987 1508 : let conf = self.tenant_conf.load();
2988 1508 :
2989 1508 : // If we may not delete layers, then simply skip GC. Even though a tenant
2990 1508 : // in AttachedMulti state could do GC and just enqueue the blocked deletions,
2991 1508 : // the only advantage to doing it is to perhaps shrink the LayerMap metadata
2992 1508 : // a bit sooner than we would achieve by waiting for AttachedSingle status.
2993 1508 : if !conf.location.may_delete_layers_hint() {
2994 0 : info!("Skipping GC in location state {:?}", conf.location);
2995 0 : return Ok(GcResult::default());
2996 1508 : }
2997 1508 :
2998 1508 : if conf.is_gc_blocked_by_lsn_lease_deadline() {
2999 1500 : info!("Skipping GC because lsn lease deadline is not reached");
3000 1500 : return Ok(GcResult::default());
3001 8 : }
3002 : }
3003 :
3004 8 : let _guard = match self.gc_block.start().await {
3005 8 : Ok(guard) => guard,
3006 0 : Err(reasons) => {
3007 0 : info!("Skipping GC: {reasons}");
3008 0 : return Ok(GcResult::default());
3009 : }
3010 : };
3011 :
3012 8 : self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
3013 8 : .await
3014 1508 : }
3015 :
3016 : /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
3017 : /// whether another compaction is needed, if we still have pending work or if we yield for
3018 : /// immediate L0 compaction.
3019 : ///
3020 : /// Compaction can also be explicitly requested for a timeline via the HTTP API.
3021 0 : async fn compaction_iteration(
3022 0 : self: &Arc<Self>,
3023 0 : cancel: &CancellationToken,
3024 0 : ctx: &RequestContext,
3025 0 : ) -> Result<CompactionOutcome, CompactionError> {
3026 0 : // Don't compact inactive tenants.
3027 0 : if !self.is_active() {
3028 0 : return Ok(CompactionOutcome::Skipped);
3029 0 : }
3030 0 :
3031 0 : // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
3032 0 : // since we need to compact L0 even in AttachedMulti to bound read amplification.
3033 0 : let location = self.tenant_conf.load().location;
3034 0 : if !location.may_upload_layers_hint() {
3035 0 : info!("skipping compaction in location state {location:?}");
3036 0 : return Ok(CompactionOutcome::Skipped);
3037 0 : }
3038 0 :
3039 0 : // Don't compact if the circuit breaker is tripped.
3040 0 : if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
3041 0 : info!("skipping compaction due to previous failures");
3042 0 : return Ok(CompactionOutcome::Skipped);
3043 0 : }
3044 0 :
3045 0 : // Collect all timelines to compact, along with offload instructions and L0 counts.
3046 0 : let mut compact: Vec<Arc<Timeline>> = Vec::new();
3047 0 : let mut offload: HashSet<TimelineId> = HashSet::new();
3048 0 : let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
3049 0 :
3050 0 : {
3051 0 : let offload_enabled = self.get_timeline_offloading_enabled();
3052 0 : let timelines = self.timelines.lock().unwrap();
3053 0 : for (&timeline_id, timeline) in timelines.iter() {
3054 : // Skip inactive timelines.
3055 0 : if !timeline.is_active() {
3056 0 : continue;
3057 0 : }
3058 0 :
3059 0 : // Schedule the timeline for compaction.
3060 0 : compact.push(timeline.clone());
3061 :
3062 : // Schedule the timeline for offloading if eligible.
3063 0 : let can_offload = offload_enabled
3064 0 : && timeline.can_offload().0
3065 0 : && !timelines
3066 0 : .iter()
3067 0 : .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
3068 0 : if can_offload {
3069 0 : offload.insert(timeline_id);
3070 0 : }
3071 : }
3072 : } // release timelines lock
3073 :
3074 0 : for timeline in &compact {
3075 : // Collect L0 counts. Can't await while holding lock above.
3076 0 : if let Ok(lm) = timeline.layers.read().await.layer_map() {
3077 0 : l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
3078 0 : }
3079 : }
3080 :
3081 : // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
3082 : // bound read amplification.
3083 : //
3084 : // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
3085 : // compaction and offloading. We leave that as a potential problem to solve later. Consider
3086 : // splitting L0 and image/GC compaction to separate background jobs.
3087 0 : if self.get_compaction_l0_first() {
3088 0 : let compaction_threshold = self.get_compaction_threshold();
3089 0 : let compact_l0 = compact
3090 0 : .iter()
3091 0 : .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
3092 0 : .filter(|&(_, l0)| l0 >= compaction_threshold)
3093 0 : .sorted_by_key(|&(_, l0)| l0)
3094 0 : .rev()
3095 0 : .map(|(tli, _)| tli.clone())
3096 0 : .collect_vec();
3097 0 :
3098 0 : let mut has_pending_l0 = false;
3099 0 : for timeline in compact_l0 {
3100 0 : let ctx = &ctx.with_scope_timeline(&timeline);
3101 : // NB: don't set CompactFlags::YieldForL0, since this is an L0-only compaction pass.
3102 0 : let outcome = timeline
3103 0 : .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
3104 0 : .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
3105 0 : .await
3106 0 : .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
3107 0 : match outcome {
3108 0 : CompactionOutcome::Done => {}
3109 0 : CompactionOutcome::Skipped => {}
3110 0 : CompactionOutcome::Pending => has_pending_l0 = true,
3111 0 : CompactionOutcome::YieldForL0 => has_pending_l0 = true,
3112 : }
3113 : }
3114 0 : if has_pending_l0 {
3115 0 : return Ok(CompactionOutcome::YieldForL0); // do another pass
3116 0 : }
3117 0 : }
3118 :
3119 : // Pass 2: image compaction and timeline offloading. If any timelines have accumulated more
3120 : // L0 layers, they may also be compacted here. Image compaction will yield if there is
3121 : // pending L0 compaction on any tenant timeline.
3122 : //
3123 : // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
3124 : // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
3125 0 : let mut has_pending = false;
3126 0 : for timeline in compact {
3127 0 : if !timeline.is_active() {
3128 0 : continue;
3129 0 : }
3130 0 : let ctx = &ctx.with_scope_timeline(&timeline);
3131 0 :
3132 0 : // Yield for L0 if the separate L0 pass is enabled (otherwise there's no point).
3133 0 : let mut flags = EnumSet::default();
3134 0 : if self.get_compaction_l0_first() {
3135 0 : flags |= CompactFlags::YieldForL0;
3136 0 : }
3137 :
3138 0 : let mut outcome = timeline
3139 0 : .compact(cancel, flags, ctx)
3140 0 : .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
3141 0 : .await
3142 0 : .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
3143 :
3144 : // If we're done compacting, check the scheduled GC compaction queue for more work.
3145 0 : if outcome == CompactionOutcome::Done {
3146 0 : let queue = {
3147 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3148 0 : guard
3149 0 : .entry(timeline.timeline_id)
3150 0 : .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
3151 0 : .clone()
3152 0 : };
3153 0 : outcome = queue
3154 0 : .iteration(cancel, ctx, &self.gc_block, &timeline)
3155 0 : .instrument(
3156 0 : info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id),
3157 : )
3158 0 : .await?;
3159 0 : }
3160 :
3161 : // If we're done compacting, offload the timeline if requested.
3162 0 : if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
3163 0 : pausable_failpoint!("before-timeline-auto-offload");
3164 0 : offload_timeline(self, &timeline)
3165 0 : .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
3166 0 : .await
3167 0 : .or_else(|err| match err {
3168 : // Ignore this, we likely raced with unarchival.
3169 0 : OffloadError::NotArchived => Ok(()),
3170 0 : err => Err(err),
3171 0 : })?;
3172 0 : }
3173 :
3174 0 : match outcome {
3175 0 : CompactionOutcome::Done => {}
3176 0 : CompactionOutcome::Skipped => {}
3177 0 : CompactionOutcome::Pending => has_pending = true,
3178 : // This mostly makes sense when the L0-only pass above is enabled, since there's
3179 : // otherwise no guarantee that we'll start with the timeline that has high L0.
3180 0 : CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
3181 : }
3182 : }
3183 :
3184 : // Success! Untrip the breaker if necessary.
3185 0 : self.compaction_circuit_breaker
3186 0 : .lock()
3187 0 : .unwrap()
3188 0 : .success(&CIRCUIT_BREAKERS_UNBROKEN);
3189 0 :
3190 0 : match has_pending {
3191 0 : true => Ok(CompactionOutcome::Pending),
3192 0 : false => Ok(CompactionOutcome::Done),
3193 : }
3194 0 : }
3195 :
3196 : /// Trips the compaction circuit breaker if appropriate.
3197 0 : pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
3198 0 : match err {
3199 0 : err if err.is_cancel() => {}
3200 0 : CompactionError::ShuttingDown => (),
3201 : // Offload failures don't trip the circuit breaker, since they're cheap to retry and
3202 : // shouldn't block compaction.
3203 0 : CompactionError::Offload(_) => {}
3204 0 : CompactionError::CollectKeySpaceError(err) => {
3205 0 : // CollectKeySpaceError::Cancelled and PageRead::Cancelled are handled in `err.is_cancel` branch.
3206 0 : self.compaction_circuit_breaker
3207 0 : .lock()
3208 0 : .unwrap()
3209 0 : .fail(&CIRCUIT_BREAKERS_BROKEN, err);
3210 0 : }
3211 0 : CompactionError::Other(err) => {
3212 0 : self.compaction_circuit_breaker
3213 0 : .lock()
3214 0 : .unwrap()
3215 0 : .fail(&CIRCUIT_BREAKERS_BROKEN, err);
3216 0 : }
3217 0 : CompactionError::AlreadyRunning(_) => {}
3218 : }
3219 0 : }
3220 :
3221 : /// Cancel scheduled compaction tasks
3222 0 : pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
3223 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3224 0 : if let Some(q) = guard.get_mut(&timeline_id) {
3225 0 : q.cancel_scheduled();
3226 0 : }
3227 0 : }
3228 :
3229 0 : pub(crate) fn get_scheduled_compaction_tasks(
3230 0 : &self,
3231 0 : timeline_id: TimelineId,
3232 0 : ) -> Vec<CompactInfoResponse> {
3233 0 : let res = {
3234 0 : let guard = self.scheduled_compaction_tasks.lock().unwrap();
3235 0 : guard.get(&timeline_id).map(|q| q.remaining_jobs())
3236 : };
3237 0 : let Some((running, remaining)) = res else {
3238 0 : return Vec::new();
3239 : };
3240 0 : let mut result = Vec::new();
3241 0 : if let Some((id, running)) = running {
3242 0 : result.extend(running.into_compact_info_resp(id, true));
3243 0 : }
3244 0 : for (id, job) in remaining {
3245 0 : result.extend(job.into_compact_info_resp(id, false));
3246 0 : }
3247 0 : result
3248 0 : }
3249 :
3250 : /// Schedule a compaction task for a timeline.
3251 0 : pub(crate) async fn schedule_compaction(
3252 0 : &self,
3253 0 : timeline_id: TimelineId,
3254 0 : options: CompactOptions,
3255 0 : ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
3256 0 : let (tx, rx) = tokio::sync::oneshot::channel();
3257 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3258 0 : let q = guard
3259 0 : .entry(timeline_id)
3260 0 : .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
3261 0 : q.schedule_manual_compaction(options, Some(tx));
3262 0 : Ok(rx)
3263 0 : }
3264 :
3265 : /// Performs periodic housekeeping, via the tenant housekeeping background task.
3266 0 : async fn housekeeping(&self) {
3267 0 : // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
3268 0 : // during ingest, but we don't want idle timelines to hold open layers for too long.
3269 0 : //
3270 0 : // We don't do this if the tenant can't upload layers (i.e. it's in stale attachment mode).
3271 0 : // We don't run compaction in this case either, and don't want to keep flushing tiny L0
3272 0 : // layers that won't be compacted down.
3273 0 : if self.tenant_conf.load().location.may_upload_layers_hint() {
3274 0 : let timelines = self
3275 0 : .timelines
3276 0 : .lock()
3277 0 : .unwrap()
3278 0 : .values()
3279 0 : .filter(|tli| tli.is_active())
3280 0 : .cloned()
3281 0 : .collect_vec();
3282 :
3283 0 : for timeline in timelines {
3284 0 : timeline.maybe_freeze_ephemeral_layer().await;
3285 : }
3286 0 : }
3287 :
3288 : // Shut down walredo if idle.
3289 : const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
3290 0 : if let Some(ref walredo_mgr) = self.walredo_mgr {
3291 0 : walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
3292 0 : }
3293 0 : }
3294 :
3295 0 : pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
3296 0 : let timelines = self.timelines.lock().unwrap();
3297 0 : !timelines
3298 0 : .iter()
3299 0 : .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
3300 0 : }
3301 :
3302 3492 : pub fn current_state(&self) -> TenantState {
3303 3492 : self.state.borrow().clone()
3304 3492 : }
3305 :
3306 1968 : pub fn is_active(&self) -> bool {
3307 1968 : self.current_state() == TenantState::Active
3308 1968 : }
3309 :
3310 0 : pub fn generation(&self) -> Generation {
3311 0 : self.generation
3312 0 : }
3313 :
3314 0 : pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
3315 0 : self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
3316 0 : }
3317 :
3318 : /// Changes tenant status to active, unless shutdown was already requested.
3319 : ///
3320 : /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
3321 : /// to delay background jobs. Background jobs can be started right away when None is given.
3322 0 : fn activate(
3323 0 : self: &Arc<Self>,
3324 0 : broker_client: BrokerClientChannel,
3325 0 : background_jobs_can_start: Option<&completion::Barrier>,
3326 0 : ctx: &RequestContext,
3327 0 : ) {
3328 0 : span::debug_assert_current_span_has_tenant_id();
3329 0 :
3330 0 : let mut activating = false;
3331 0 : self.state.send_modify(|current_state| {
3332 : use pageserver_api::models::ActivatingFrom;
3333 0 : match &*current_state {
3334 : TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
3335 0 : panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
3336 : }
3337 0 : TenantState::Attaching => {
3338 0 : *current_state = TenantState::Activating(ActivatingFrom::Attaching);
3339 0 : }
3340 0 : }
3341 0 : debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
3342 0 : activating = true;
3343 0 : // Continue outside the closure. We need to grab timelines.lock()
3344 0 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
3345 0 : });
3346 0 :
3347 0 : if activating {
3348 0 : let timelines_accessor = self.timelines.lock().unwrap();
3349 0 : let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
3350 0 : let timelines_to_activate = timelines_accessor
3351 0 : .values()
3352 0 : .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
3353 0 :
3354 0 : // Before activation, populate each Timeline's GcInfo with information about its children
3355 0 : self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
3356 0 :
3357 0 : // Spawn gc and compaction loops. The loops will shut themselves
3358 0 : // down when they notice that the tenant is inactive.
3359 0 : tasks::start_background_loops(self, background_jobs_can_start);
3360 0 :
3361 0 : let mut activated_timelines = 0;
3362 :
3363 0 : for timeline in timelines_to_activate {
3364 0 : timeline.activate(
3365 0 : self.clone(),
3366 0 : broker_client.clone(),
3367 0 : background_jobs_can_start,
3368 0 : &ctx.with_scope_timeline(timeline),
3369 0 : );
3370 0 : activated_timelines += 1;
3371 0 : }
3372 :
3373 0 : self.state.send_modify(move |current_state| {
3374 0 : assert!(
3375 0 : matches!(current_state, TenantState::Activating(_)),
3376 0 : "set_stopping and set_broken wait for us to leave Activating state",
3377 : );
3378 0 : *current_state = TenantState::Active;
3379 0 :
3380 0 : let elapsed = self.constructed_at.elapsed();
3381 0 : let total_timelines = timelines_accessor.len();
3382 0 :
3383 0 : // log a lot of stuff, because some tenants sometimes suffer from user-visible
3384 0 : // times to activate. see https://github.com/neondatabase/neon/issues/4025
3385 0 : info!(
3386 0 : since_creation_millis = elapsed.as_millis(),
3387 0 : tenant_id = %self.tenant_shard_id.tenant_id,
3388 0 : shard_id = %self.tenant_shard_id.shard_slug(),
3389 0 : activated_timelines,
3390 0 : total_timelines,
3391 0 : post_state = <&'static str>::from(&*current_state),
3392 0 : "activation attempt finished"
3393 : );
3394 :
3395 0 : TENANT.activation.observe(elapsed.as_secs_f64());
3396 0 : });
3397 0 : }
3398 0 : }
3399 :
3400 : /// Shutdown the tenant and join all of the spawned tasks.
3401 : ///
3402 : /// The method caters for all use-cases:
3403 : /// - pageserver shutdown (freeze_and_flush == true)
3404 : /// - detach + ignore (freeze_and_flush == false)
3405 : ///
3406 : /// This will attempt to shutdown even if tenant is broken.
3407 : ///
3408 : /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
3409 : /// If the tenant is already shutting down, we return a clone of the first shutdown call's
3410 : /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
3411 : /// the ongoing shutdown.
3412 12 : async fn shutdown(
3413 12 : &self,
3414 12 : shutdown_progress: completion::Barrier,
3415 12 : shutdown_mode: timeline::ShutdownMode,
3416 12 : ) -> Result<(), completion::Barrier> {
3417 12 : span::debug_assert_current_span_has_tenant_id();
3418 :
3419 : // Set tenant (and its timlines) to Stoppping state.
3420 : //
3421 : // Since we can only transition into Stopping state after activation is complete,
3422 : // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
3423 : //
3424 : // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
3425 : // 1. Lock out any new requests to the tenants.
3426 : // 2. Signal cancellation to WAL receivers (we wait on it below).
3427 : // 3. Signal cancellation for other tenant background loops.
3428 : // 4. ???
3429 : //
3430 : // The waiting for the cancellation is not done uniformly.
3431 : // We certainly wait for WAL receivers to shut down.
3432 : // That is necessary so that no new data comes in before the freeze_and_flush.
3433 : // But the tenant background loops are joined-on in our caller.
3434 : // It's mesed up.
3435 : // we just ignore the failure to stop
3436 :
3437 : // If we're still attaching, fire the cancellation token early to drop out: this
3438 : // will prevent us flushing, but ensures timely shutdown if some I/O during attach
3439 : // is very slow.
3440 12 : let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
3441 0 : self.cancel.cancel();
3442 0 :
3443 0 : // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
3444 0 : // are children of ours, so their flush loops will have shut down already
3445 0 : timeline::ShutdownMode::Hard
3446 : } else {
3447 12 : shutdown_mode
3448 : };
3449 :
3450 12 : match self.set_stopping(shutdown_progress).await {
3451 12 : Ok(()) => {}
3452 0 : Err(SetStoppingError::Broken) => {
3453 0 : // assume that this is acceptable
3454 0 : }
3455 0 : Err(SetStoppingError::AlreadyStopping(other)) => {
3456 0 : // give caller the option to wait for this this shutdown
3457 0 : info!("Tenant::shutdown: AlreadyStopping");
3458 0 : return Err(other);
3459 : }
3460 : };
3461 :
3462 12 : let mut js = tokio::task::JoinSet::new();
3463 12 : {
3464 12 : let timelines = self.timelines.lock().unwrap();
3465 12 : timelines.values().for_each(|timeline| {
3466 12 : let timeline = Arc::clone(timeline);
3467 12 : let timeline_id = timeline.timeline_id;
3468 12 : let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
3469 12 : js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
3470 12 : });
3471 12 : }
3472 12 : {
3473 12 : let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
3474 12 : timelines_offloaded.values().for_each(|timeline| {
3475 0 : timeline.defuse_for_tenant_drop();
3476 12 : });
3477 12 : }
3478 12 : // test_long_timeline_create_then_tenant_delete is leaning on this message
3479 12 : tracing::info!("Waiting for timelines...");
3480 24 : while let Some(res) = js.join_next().await {
3481 0 : match res {
3482 12 : Ok(()) => {}
3483 0 : Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
3484 0 : Err(je) if je.is_panic() => { /* logged already */ }
3485 0 : Err(je) => warn!("unexpected JoinError: {je:?}"),
3486 : }
3487 : }
3488 :
3489 12 : if let ShutdownMode::Reload = shutdown_mode {
3490 0 : tracing::info!("Flushing deletion queue");
3491 0 : if let Err(e) = self.deletion_queue_client.flush().await {
3492 0 : match e {
3493 0 : DeletionQueueError::ShuttingDown => {
3494 0 : // This is the only error we expect for now. In the future, if more error
3495 0 : // variants are added, we should handle them here.
3496 0 : }
3497 : }
3498 0 : }
3499 12 : }
3500 :
3501 : // We cancel the Tenant's cancellation token _after_ the timelines have all shut down. This permits
3502 : // them to continue to do work during their shutdown methods, e.g. flushing data.
3503 12 : tracing::debug!("Cancelling CancellationToken");
3504 12 : self.cancel.cancel();
3505 12 :
3506 12 : // shutdown all tenant and timeline tasks: gc, compaction, page service
3507 12 : // No new tasks will be started for this tenant because it's in `Stopping` state.
3508 12 : //
3509 12 : // this will additionally shutdown and await all timeline tasks.
3510 12 : tracing::debug!("Waiting for tasks...");
3511 12 : task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
3512 :
3513 12 : if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
3514 12 : walredo_mgr.shutdown().await;
3515 0 : }
3516 :
3517 : // Wait for any in-flight operations to complete
3518 12 : self.gate.close().await;
3519 :
3520 12 : remove_tenant_metrics(&self.tenant_shard_id);
3521 12 :
3522 12 : Ok(())
3523 12 : }
3524 :
3525 : /// Change tenant status to Stopping, to mark that it is being shut down.
3526 : ///
3527 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
3528 : ///
3529 : /// This function is not cancel-safe!
3530 12 : async fn set_stopping(&self, progress: completion::Barrier) -> Result<(), SetStoppingError> {
3531 12 : let mut rx = self.state.subscribe();
3532 12 :
3533 12 : // cannot stop before we're done activating, so wait out until we're done activating
3534 12 : rx.wait_for(|state| match state {
3535 : TenantState::Activating(_) | TenantState::Attaching => {
3536 0 : info!("waiting for {state} to turn Active|Broken|Stopping");
3537 0 : false
3538 : }
3539 12 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
3540 12 : })
3541 12 : .await
3542 12 : .expect("cannot drop self.state while on a &self method");
3543 12 :
3544 12 : // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
3545 12 : let mut err = None;
3546 12 : let stopping = self.state.send_if_modified(|current_state| match current_state {
3547 : TenantState::Activating(_) | TenantState::Attaching => {
3548 0 : unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
3549 : }
3550 : TenantState::Active => {
3551 : // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
3552 : // are created after the transition to Stopping. That's harmless, as the Timelines
3553 : // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
3554 12 : *current_state = TenantState::Stopping { progress: Some(progress) };
3555 12 : // Continue stopping outside the closure. We need to grab timelines.lock()
3556 12 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
3557 12 : true
3558 : }
3559 : TenantState::Stopping { progress: None } => {
3560 : // An attach was cancelled, and the attach transitioned the tenant from Attaching to
3561 : // Stopping(None) to let us know it exited. Register our progress and continue.
3562 0 : *current_state = TenantState::Stopping { progress: Some(progress) };
3563 0 : true
3564 : }
3565 0 : TenantState::Broken { reason, .. } => {
3566 0 : info!(
3567 0 : "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
3568 : );
3569 0 : err = Some(SetStoppingError::Broken);
3570 0 : false
3571 : }
3572 0 : TenantState::Stopping { progress: Some(progress) } => {
3573 0 : info!("Tenant is already in Stopping state");
3574 0 : err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
3575 0 : false
3576 : }
3577 12 : });
3578 12 : match (stopping, err) {
3579 12 : (true, None) => {} // continue
3580 0 : (false, Some(err)) => return Err(err),
3581 0 : (true, Some(_)) => unreachable!(
3582 0 : "send_if_modified closure must error out if not transitioning to Stopping"
3583 0 : ),
3584 0 : (false, None) => unreachable!(
3585 0 : "send_if_modified closure must return true if transitioning to Stopping"
3586 0 : ),
3587 : }
3588 :
3589 12 : let timelines_accessor = self.timelines.lock().unwrap();
3590 12 : let not_broken_timelines = timelines_accessor
3591 12 : .values()
3592 12 : .filter(|timeline| !timeline.is_broken());
3593 24 : for timeline in not_broken_timelines {
3594 12 : timeline.set_state(TimelineState::Stopping);
3595 12 : }
3596 12 : Ok(())
3597 12 : }
3598 :
3599 : /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
3600 : /// `remove_tenant_from_memory`
3601 : ///
3602 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
3603 : ///
3604 : /// In tests, we also use this to set tenants to Broken state on purpose.
3605 0 : pub(crate) async fn set_broken(&self, reason: String) {
3606 0 : let mut rx = self.state.subscribe();
3607 0 :
3608 0 : // The load & attach routines own the tenant state until it has reached `Active`.
3609 0 : // So, wait until it's done.
3610 0 : rx.wait_for(|state| match state {
3611 : TenantState::Activating(_) | TenantState::Attaching => {
3612 0 : info!(
3613 0 : "waiting for {} to turn Active|Broken|Stopping",
3614 0 : <&'static str>::from(state)
3615 : );
3616 0 : false
3617 : }
3618 0 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
3619 0 : })
3620 0 : .await
3621 0 : .expect("cannot drop self.state while on a &self method");
3622 0 :
3623 0 : // we now know we're done activating, let's see whether this task is the winner to transition into Broken
3624 0 : self.set_broken_no_wait(reason)
3625 0 : }
3626 :
3627 0 : pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
3628 0 : let reason = reason.to_string();
3629 0 : self.state.send_modify(|current_state| {
3630 0 : match *current_state {
3631 : TenantState::Activating(_) | TenantState::Attaching => {
3632 0 : unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
3633 : }
3634 : TenantState::Active => {
3635 0 : if cfg!(feature = "testing") {
3636 0 : warn!("Changing Active tenant to Broken state, reason: {}", reason);
3637 0 : *current_state = TenantState::broken_from_reason(reason);
3638 : } else {
3639 0 : unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
3640 : }
3641 : }
3642 : TenantState::Broken { .. } => {
3643 0 : warn!("Tenant is already in Broken state");
3644 : }
3645 : // This is the only "expected" path, any other path is a bug.
3646 : TenantState::Stopping { .. } => {
3647 0 : warn!(
3648 0 : "Marking Stopping tenant as Broken state, reason: {}",
3649 : reason
3650 : );
3651 0 : *current_state = TenantState::broken_from_reason(reason);
3652 : }
3653 : }
3654 0 : });
3655 0 : }
3656 :
3657 0 : pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
3658 0 : self.state.subscribe()
3659 0 : }
3660 :
3661 : /// The activate_now semaphore is initialized with zero units. As soon as
3662 : /// we add a unit, waiters will be able to acquire a unit and proceed.
3663 0 : pub(crate) fn activate_now(&self) {
3664 0 : self.activate_now_sem.add_permits(1);
3665 0 : }
3666 :
3667 0 : pub(crate) async fn wait_to_become_active(
3668 0 : &self,
3669 0 : timeout: Duration,
3670 0 : ) -> Result<(), GetActiveTenantError> {
3671 0 : let mut receiver = self.state.subscribe();
3672 : loop {
3673 0 : let current_state = receiver.borrow_and_update().clone();
3674 0 : match current_state {
3675 : TenantState::Attaching | TenantState::Activating(_) => {
3676 : // in these states, there's a chance that we can reach ::Active
3677 0 : self.activate_now();
3678 0 : match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
3679 0 : Ok(r) => {
3680 0 : r.map_err(
3681 0 : |_e: tokio::sync::watch::error::RecvError|
3682 : // Tenant existed but was dropped: report it as non-existent
3683 0 : GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
3684 0 : )?
3685 : }
3686 : Err(TimeoutCancellableError::Cancelled) => {
3687 0 : return Err(GetActiveTenantError::Cancelled);
3688 : }
3689 : Err(TimeoutCancellableError::Timeout) => {
3690 0 : return Err(GetActiveTenantError::WaitForActiveTimeout {
3691 0 : latest_state: Some(self.current_state()),
3692 0 : wait_time: timeout,
3693 0 : });
3694 : }
3695 : }
3696 : }
3697 : TenantState::Active => {
3698 0 : return Ok(());
3699 : }
3700 0 : TenantState::Broken { reason, .. } => {
3701 0 : // This is fatal, and reported distinctly from the general case of "will never be active" because
3702 0 : // it's logically a 500 to external API users (broken is always a bug).
3703 0 : return Err(GetActiveTenantError::Broken(reason));
3704 : }
3705 : TenantState::Stopping { .. } => {
3706 : // There's no chance the tenant can transition back into ::Active
3707 0 : return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
3708 : }
3709 : }
3710 : }
3711 0 : }
3712 :
3713 0 : pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
3714 0 : self.tenant_conf.load().location.attach_mode
3715 0 : }
3716 :
3717 : /// For API access: generate a LocationConfig equivalent to the one that would be used to
3718 : /// create a Tenant in the same state. Do not use this in hot paths: it's for relatively
3719 : /// rare external API calls, like a reconciliation at startup.
3720 0 : pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
3721 0 : let attached_tenant_conf = self.tenant_conf.load();
3722 :
3723 0 : let location_config_mode = match attached_tenant_conf.location.attach_mode {
3724 0 : AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
3725 0 : AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
3726 0 : AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
3727 : };
3728 :
3729 0 : models::LocationConfig {
3730 0 : mode: location_config_mode,
3731 0 : generation: self.generation.into(),
3732 0 : secondary_conf: None,
3733 0 : shard_number: self.shard_identity.number.0,
3734 0 : shard_count: self.shard_identity.count.literal(),
3735 0 : shard_stripe_size: self.shard_identity.stripe_size.0,
3736 0 : tenant_conf: attached_tenant_conf.tenant_conf.clone(),
3737 0 : }
3738 0 : }
3739 :
3740 0 : pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
3741 0 : &self.tenant_shard_id
3742 0 : }
3743 :
3744 464 : pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
3745 464 : self.shard_identity.stripe_size
3746 464 : }
3747 :
3748 0 : pub(crate) fn get_generation(&self) -> Generation {
3749 0 : self.generation
3750 0 : }
3751 :
3752 : /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
3753 : /// and can leave the tenant in a bad state if it fails. The caller is responsible for
3754 : /// resetting this tenant to a valid state if we fail.
3755 0 : pub(crate) async fn split_prepare(
3756 0 : &self,
3757 0 : child_shards: &Vec<TenantShardId>,
3758 0 : ) -> anyhow::Result<()> {
3759 0 : let (timelines, offloaded) = {
3760 0 : let timelines = self.timelines.lock().unwrap();
3761 0 : let offloaded = self.timelines_offloaded.lock().unwrap();
3762 0 : (timelines.clone(), offloaded.clone())
3763 0 : };
3764 0 : let timelines_iter = timelines
3765 0 : .values()
3766 0 : .map(TimelineOrOffloadedArcRef::<'_>::from)
3767 0 : .chain(
3768 0 : offloaded
3769 0 : .values()
3770 0 : .map(TimelineOrOffloadedArcRef::<'_>::from),
3771 0 : );
3772 0 : for timeline in timelines_iter {
3773 : // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
3774 : // to ensure that they do not start a split if currently in the process of doing these.
3775 :
3776 0 : let timeline_id = timeline.timeline_id();
3777 :
3778 0 : if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
3779 : // Upload an index from the parent: this is partly to provide freshness for the
3780 : // child tenants that will copy it, and partly for general ease-of-debugging: there will
3781 : // always be a parent shard index in the same generation as we wrote the child shard index.
3782 0 : tracing::info!(%timeline_id, "Uploading index");
3783 0 : timeline
3784 0 : .remote_client
3785 0 : .schedule_index_upload_for_file_changes()?;
3786 0 : timeline.remote_client.wait_completion().await?;
3787 0 : }
3788 :
3789 0 : let remote_client = match timeline {
3790 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
3791 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
3792 0 : let remote_client = self
3793 0 : .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
3794 0 : Arc::new(remote_client)
3795 : }
3796 : };
3797 :
3798 : // Shut down the timeline's remote client: this means that the indices we write
3799 : // for child shards will not be invalidated by the parent shard deleting layers.
3800 0 : tracing::info!(%timeline_id, "Shutting down remote storage client");
3801 0 : remote_client.shutdown().await;
3802 :
3803 : // Download methods can still be used after shutdown, as they don't flow through the remote client's
3804 : // queue. In principal the RemoteTimelineClient could provide this without downloading it, but this
3805 : // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
3806 : // we use here really is the remotely persistent one).
3807 0 : tracing::info!(%timeline_id, "Downloading index_part from parent");
3808 0 : let result = remote_client
3809 0 : .download_index_file(&self.cancel)
3810 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))
3811 0 : .await?;
3812 0 : let index_part = match result {
3813 : MaybeDeletedIndexPart::Deleted(_) => {
3814 0 : anyhow::bail!("Timeline deletion happened concurrently with split")
3815 : }
3816 0 : MaybeDeletedIndexPart::IndexPart(p) => p,
3817 : };
3818 :
3819 0 : for child_shard in child_shards {
3820 0 : tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
3821 0 : upload_index_part(
3822 0 : &self.remote_storage,
3823 0 : child_shard,
3824 0 : &timeline_id,
3825 0 : self.generation,
3826 0 : &index_part,
3827 0 : &self.cancel,
3828 0 : )
3829 0 : .await?;
3830 : }
3831 : }
3832 :
3833 0 : let tenant_manifest = self.build_tenant_manifest();
3834 0 : for child_shard in child_shards {
3835 0 : tracing::info!(
3836 0 : "Uploading tenant manifest for child {}",
3837 0 : child_shard.to_index()
3838 : );
3839 0 : upload_tenant_manifest(
3840 0 : &self.remote_storage,
3841 0 : child_shard,
3842 0 : self.generation,
3843 0 : &tenant_manifest,
3844 0 : &self.cancel,
3845 0 : )
3846 0 : .await?;
3847 : }
3848 :
3849 0 : Ok(())
3850 0 : }
3851 :
3852 0 : pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
3853 0 : let mut result = TopTenantShardItem {
3854 0 : id: self.tenant_shard_id,
3855 0 : resident_size: 0,
3856 0 : physical_size: 0,
3857 0 : max_logical_size: 0,
3858 0 : max_logical_size_per_shard: 0,
3859 0 : };
3860 :
3861 0 : for timeline in self.timelines.lock().unwrap().values() {
3862 0 : result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
3863 0 :
3864 0 : result.physical_size += timeline
3865 0 : .remote_client
3866 0 : .metrics
3867 0 : .remote_physical_size_gauge
3868 0 : .get();
3869 0 : result.max_logical_size = std::cmp::max(
3870 0 : result.max_logical_size,
3871 0 : timeline.metrics.current_logical_size_gauge.get(),
3872 0 : );
3873 0 : }
3874 :
3875 0 : result.max_logical_size_per_shard = result
3876 0 : .max_logical_size
3877 0 : .div_ceil(self.tenant_shard_id.shard_count.count() as u64);
3878 0 :
3879 0 : result
3880 0 : }
3881 : }
3882 :
3883 : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
3884 : /// perform a topological sort, so that the parent of each timeline comes
3885 : /// before the children.
3886 : /// E extracts the ancestor from T
3887 : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
3888 460 : fn tree_sort_timelines<T, E>(
3889 460 : timelines: HashMap<TimelineId, T>,
3890 460 : extractor: E,
3891 460 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
3892 460 : where
3893 460 : E: Fn(&T) -> Option<TimelineId>,
3894 460 : {
3895 460 : let mut result = Vec::with_capacity(timelines.len());
3896 460 :
3897 460 : let mut now = Vec::with_capacity(timelines.len());
3898 460 : // (ancestor, children)
3899 460 : let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
3900 460 : HashMap::with_capacity(timelines.len());
3901 :
3902 472 : for (timeline_id, value) in timelines {
3903 12 : if let Some(ancestor_id) = extractor(&value) {
3904 4 : let children = later.entry(ancestor_id).or_default();
3905 4 : children.push((timeline_id, value));
3906 8 : } else {
3907 8 : now.push((timeline_id, value));
3908 8 : }
3909 : }
3910 :
3911 472 : while let Some((timeline_id, metadata)) = now.pop() {
3912 12 : result.push((timeline_id, metadata));
3913 : // All children of this can be loaded now
3914 12 : if let Some(mut children) = later.remove(&timeline_id) {
3915 4 : now.append(&mut children);
3916 8 : }
3917 : }
3918 :
3919 : // All timelines should be visited now. Unless there were timelines with missing ancestors.
3920 460 : if !later.is_empty() {
3921 0 : for (missing_id, orphan_ids) in later {
3922 0 : for (orphan_id, _) in orphan_ids {
3923 0 : error!(
3924 0 : "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
3925 : );
3926 : }
3927 : }
3928 0 : bail!("could not load tenant because some timelines are missing ancestors");
3929 460 : }
3930 460 :
3931 460 : Ok(result)
3932 460 : }
3933 :
3934 : enum ActivateTimelineArgs {
3935 : Yes {
3936 : broker_client: storage_broker::BrokerClientChannel,
3937 : },
3938 : No,
3939 : }
3940 :
3941 : impl Tenant {
3942 0 : pub fn tenant_specific_overrides(&self) -> pageserver_api::models::TenantConfig {
3943 0 : self.tenant_conf.load().tenant_conf.clone()
3944 0 : }
3945 :
3946 0 : pub fn effective_config(&self) -> pageserver_api::config::TenantConfigToml {
3947 0 : self.tenant_specific_overrides()
3948 0 : .merge(self.conf.default_tenant_conf.clone())
3949 0 : }
3950 :
3951 0 : pub fn get_checkpoint_distance(&self) -> u64 {
3952 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3953 0 : tenant_conf
3954 0 : .checkpoint_distance
3955 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
3956 0 : }
3957 :
3958 0 : pub fn get_checkpoint_timeout(&self) -> Duration {
3959 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3960 0 : tenant_conf
3961 0 : .checkpoint_timeout
3962 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
3963 0 : }
3964 :
3965 0 : pub fn get_compaction_target_size(&self) -> u64 {
3966 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3967 0 : tenant_conf
3968 0 : .compaction_target_size
3969 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
3970 0 : }
3971 :
3972 0 : pub fn get_compaction_period(&self) -> Duration {
3973 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3974 0 : tenant_conf
3975 0 : .compaction_period
3976 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_period)
3977 0 : }
3978 :
3979 0 : pub fn get_compaction_threshold(&self) -> usize {
3980 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3981 0 : tenant_conf
3982 0 : .compaction_threshold
3983 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
3984 0 : }
3985 :
3986 0 : pub fn get_rel_size_v2_enabled(&self) -> bool {
3987 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3988 0 : tenant_conf
3989 0 : .rel_size_v2_enabled
3990 0 : .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
3991 0 : }
3992 :
3993 0 : pub fn get_compaction_upper_limit(&self) -> usize {
3994 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3995 0 : tenant_conf
3996 0 : .compaction_upper_limit
3997 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
3998 0 : }
3999 :
4000 0 : pub fn get_compaction_l0_first(&self) -> bool {
4001 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4002 0 : tenant_conf
4003 0 : .compaction_l0_first
4004 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
4005 0 : }
4006 :
4007 8 : pub fn get_gc_horizon(&self) -> u64 {
4008 8 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4009 8 : tenant_conf
4010 8 : .gc_horizon
4011 8 : .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
4012 8 : }
4013 :
4014 0 : pub fn get_gc_period(&self) -> Duration {
4015 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4016 0 : tenant_conf
4017 0 : .gc_period
4018 0 : .unwrap_or(self.conf.default_tenant_conf.gc_period)
4019 0 : }
4020 :
4021 0 : pub fn get_image_creation_threshold(&self) -> usize {
4022 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4023 0 : tenant_conf
4024 0 : .image_creation_threshold
4025 0 : .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
4026 0 : }
4027 :
4028 8 : pub fn get_pitr_interval(&self) -> Duration {
4029 8 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4030 8 : tenant_conf
4031 8 : .pitr_interval
4032 8 : .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
4033 8 : }
4034 :
4035 0 : pub fn get_min_resident_size_override(&self) -> Option<u64> {
4036 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4037 0 : tenant_conf
4038 0 : .min_resident_size_override
4039 0 : .or(self.conf.default_tenant_conf.min_resident_size_override)
4040 0 : }
4041 :
4042 0 : pub fn get_heatmap_period(&self) -> Option<Duration> {
4043 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4044 0 : let heatmap_period = tenant_conf
4045 0 : .heatmap_period
4046 0 : .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
4047 0 : if heatmap_period.is_zero() {
4048 0 : None
4049 : } else {
4050 0 : Some(heatmap_period)
4051 : }
4052 0 : }
4053 :
4054 8 : pub fn get_lsn_lease_length(&self) -> Duration {
4055 8 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4056 8 : tenant_conf
4057 8 : .lsn_lease_length
4058 8 : .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
4059 8 : }
4060 :
4061 0 : pub fn get_timeline_offloading_enabled(&self) -> bool {
4062 0 : if self.conf.timeline_offloading {
4063 0 : return true;
4064 0 : }
4065 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4066 0 : tenant_conf
4067 0 : .timeline_offloading
4068 0 : .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
4069 0 : }
4070 :
4071 : /// Generate an up-to-date TenantManifest based on the state of this Tenant.
4072 464 : fn build_tenant_manifest(&self) -> TenantManifest {
4073 464 : // Collect the offloaded timelines, and sort them for deterministic output.
4074 464 : let offloaded_timelines = self
4075 464 : .timelines_offloaded
4076 464 : .lock()
4077 464 : .unwrap()
4078 464 : .values()
4079 464 : .map(|tli| tli.manifest())
4080 464 : .sorted_by_key(|m| m.timeline_id)
4081 464 : .collect_vec();
4082 464 :
4083 464 : TenantManifest {
4084 464 : version: LATEST_TENANT_MANIFEST_VERSION,
4085 464 : stripe_size: Some(self.get_shard_stripe_size()),
4086 464 : offloaded_timelines,
4087 464 : }
4088 464 : }
4089 :
4090 0 : pub fn update_tenant_config<
4091 0 : F: Fn(
4092 0 : pageserver_api::models::TenantConfig,
4093 0 : ) -> anyhow::Result<pageserver_api::models::TenantConfig>,
4094 0 : >(
4095 0 : &self,
4096 0 : update: F,
4097 0 : ) -> anyhow::Result<pageserver_api::models::TenantConfig> {
4098 0 : // Use read-copy-update in order to avoid overwriting the location config
4099 0 : // state if this races with [`Tenant::set_new_location_config`]. Note that
4100 0 : // this race is not possible if both request types come from the storage
4101 0 : // controller (as they should!) because an exclusive op lock is required
4102 0 : // on the storage controller side.
4103 0 :
4104 0 : self.tenant_conf
4105 0 : .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
4106 0 : Ok(Arc::new(AttachedTenantConf {
4107 0 : tenant_conf: update(attached_conf.tenant_conf.clone())?,
4108 0 : location: attached_conf.location,
4109 0 : lsn_lease_deadline: attached_conf.lsn_lease_deadline,
4110 : }))
4111 0 : })?;
4112 :
4113 0 : let updated = self.tenant_conf.load();
4114 0 :
4115 0 : self.tenant_conf_updated(&updated.tenant_conf);
4116 0 : // Don't hold self.timelines.lock() during the notifies.
4117 0 : // There's no risk of deadlock right now, but there could be if we consolidate
4118 0 : // mutexes in struct Timeline in the future.
4119 0 : let timelines = self.list_timelines();
4120 0 : for timeline in timelines {
4121 0 : timeline.tenant_conf_updated(&updated);
4122 0 : }
4123 :
4124 0 : Ok(updated.tenant_conf.clone())
4125 0 : }
4126 :
4127 0 : pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
4128 0 : let new_tenant_conf = new_conf.tenant_conf.clone();
4129 0 :
4130 0 : self.tenant_conf.store(Arc::new(new_conf.clone()));
4131 0 :
4132 0 : self.tenant_conf_updated(&new_tenant_conf);
4133 0 : // Don't hold self.timelines.lock() during the notifies.
4134 0 : // There's no risk of deadlock right now, but there could be if we consolidate
4135 0 : // mutexes in struct Timeline in the future.
4136 0 : let timelines = self.list_timelines();
4137 0 : for timeline in timelines {
4138 0 : timeline.tenant_conf_updated(&new_conf);
4139 0 : }
4140 0 : }
4141 :
4142 460 : fn get_pagestream_throttle_config(
4143 460 : psconf: &'static PageServerConf,
4144 460 : overrides: &pageserver_api::models::TenantConfig,
4145 460 : ) -> throttle::Config {
4146 460 : overrides
4147 460 : .timeline_get_throttle
4148 460 : .clone()
4149 460 : .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
4150 460 : }
4151 :
4152 0 : pub(crate) fn tenant_conf_updated(&self, new_conf: &pageserver_api::models::TenantConfig) {
4153 0 : let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
4154 0 : self.pagestream_throttle.reconfigure(conf)
4155 0 : }
4156 :
4157 : /// Helper function to create a new Timeline struct.
4158 : ///
4159 : /// The returned Timeline is in Loading state. The caller is responsible for
4160 : /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
4161 : /// map.
4162 : ///
4163 : /// `validate_ancestor == false` is used when a timeline is created for deletion
4164 : /// and we might not have the ancestor present anymore which is fine for to be
4165 : /// deleted timelines.
4166 : #[allow(clippy::too_many_arguments)]
4167 924 : fn create_timeline_struct(
4168 924 : &self,
4169 924 : new_timeline_id: TimelineId,
4170 924 : new_metadata: &TimelineMetadata,
4171 924 : previous_heatmap: Option<PreviousHeatmap>,
4172 924 : ancestor: Option<Arc<Timeline>>,
4173 924 : resources: TimelineResources,
4174 924 : cause: CreateTimelineCause,
4175 924 : create_idempotency: CreateTimelineIdempotency,
4176 924 : gc_compaction_state: Option<GcCompactionState>,
4177 924 : rel_size_v2_status: Option<RelSizeMigration>,
4178 924 : ctx: &RequestContext,
4179 924 : ) -> anyhow::Result<(Arc<Timeline>, RequestContext)> {
4180 924 : let state = match cause {
4181 : CreateTimelineCause::Load => {
4182 924 : let ancestor_id = new_metadata.ancestor_timeline();
4183 924 : anyhow::ensure!(
4184 924 : ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
4185 0 : "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
4186 : );
4187 924 : TimelineState::Loading
4188 : }
4189 0 : CreateTimelineCause::Delete => TimelineState::Stopping,
4190 : };
4191 :
4192 924 : let pg_version = new_metadata.pg_version();
4193 924 :
4194 924 : let timeline = Timeline::new(
4195 924 : self.conf,
4196 924 : Arc::clone(&self.tenant_conf),
4197 924 : new_metadata,
4198 924 : previous_heatmap,
4199 924 : ancestor,
4200 924 : new_timeline_id,
4201 924 : self.tenant_shard_id,
4202 924 : self.generation,
4203 924 : self.shard_identity,
4204 924 : self.walredo_mgr.clone(),
4205 924 : resources,
4206 924 : pg_version,
4207 924 : state,
4208 924 : self.attach_wal_lag_cooldown.clone(),
4209 924 : create_idempotency,
4210 924 : gc_compaction_state,
4211 924 : rel_size_v2_status,
4212 924 : self.cancel.child_token(),
4213 924 : );
4214 924 :
4215 924 : let timeline_ctx = RequestContextBuilder::from(ctx)
4216 924 : .scope(context::Scope::new_timeline(&timeline))
4217 924 : .detached_child();
4218 924 :
4219 924 : Ok((timeline, timeline_ctx))
4220 924 : }
4221 :
4222 : /// [`Tenant::shutdown`] must be called before dropping the returned [`Tenant`] object
4223 : /// to ensure proper cleanup of background tasks and metrics.
4224 : //
4225 : // Allow too_many_arguments because a constructor's argument list naturally grows with the
4226 : // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
4227 : #[allow(clippy::too_many_arguments)]
4228 460 : fn new(
4229 460 : state: TenantState,
4230 460 : conf: &'static PageServerConf,
4231 460 : attached_conf: AttachedTenantConf,
4232 460 : shard_identity: ShardIdentity,
4233 460 : walredo_mgr: Option<Arc<WalRedoManager>>,
4234 460 : tenant_shard_id: TenantShardId,
4235 460 : remote_storage: GenericRemoteStorage,
4236 460 : deletion_queue_client: DeletionQueueClient,
4237 460 : l0_flush_global_state: L0FlushGlobalState,
4238 460 : ) -> Tenant {
4239 460 : debug_assert!(
4240 460 : !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
4241 : );
4242 :
4243 460 : let (state, mut rx) = watch::channel(state);
4244 460 :
4245 460 : tokio::spawn(async move {
4246 460 : // reflect tenant state in metrics:
4247 460 : // - global per tenant state: TENANT_STATE_METRIC
4248 460 : // - "set" of broken tenants: BROKEN_TENANTS_SET
4249 460 : //
4250 460 : // set of broken tenants should not have zero counts so that it remains accessible for
4251 460 : // alerting.
4252 460 :
4253 460 : let tid = tenant_shard_id.to_string();
4254 460 : let shard_id = tenant_shard_id.shard_slug().to_string();
4255 460 : let set_key = &[tid.as_str(), shard_id.as_str()][..];
4256 :
4257 920 : fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
4258 920 : ([state.into()], matches!(state, TenantState::Broken { .. }))
4259 920 : }
4260 :
4261 460 : let mut tuple = inspect_state(&rx.borrow_and_update());
4262 460 :
4263 460 : let is_broken = tuple.1;
4264 460 : let mut counted_broken = if is_broken {
4265 : // add the id to the set right away, there should not be any updates on the channel
4266 : // after before tenant is removed, if ever
4267 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
4268 0 : true
4269 : } else {
4270 460 : false
4271 : };
4272 :
4273 : loop {
4274 920 : let labels = &tuple.0;
4275 920 : let current = TENANT_STATE_METRIC.with_label_values(labels);
4276 920 : current.inc();
4277 920 :
4278 920 : if rx.changed().await.is_err() {
4279 : // tenant has been dropped
4280 28 : current.dec();
4281 28 : drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
4282 28 : break;
4283 460 : }
4284 460 :
4285 460 : current.dec();
4286 460 : tuple = inspect_state(&rx.borrow_and_update());
4287 460 :
4288 460 : let is_broken = tuple.1;
4289 460 : if is_broken && !counted_broken {
4290 0 : counted_broken = true;
4291 0 : // insert the tenant_id (back) into the set while avoiding needless counter
4292 0 : // access
4293 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
4294 460 : }
4295 : }
4296 460 : });
4297 460 :
4298 460 : Tenant {
4299 460 : tenant_shard_id,
4300 460 : shard_identity,
4301 460 : generation: attached_conf.location.generation,
4302 460 : conf,
4303 460 : // using now here is good enough approximation to catch tenants with really long
4304 460 : // activation times.
4305 460 : constructed_at: Instant::now(),
4306 460 : timelines: Mutex::new(HashMap::new()),
4307 460 : timelines_creating: Mutex::new(HashSet::new()),
4308 460 : timelines_offloaded: Mutex::new(HashMap::new()),
4309 460 : remote_tenant_manifest: Default::default(),
4310 460 : gc_cs: tokio::sync::Mutex::new(()),
4311 460 : walredo_mgr,
4312 460 : remote_storage,
4313 460 : deletion_queue_client,
4314 460 : state,
4315 460 : cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
4316 460 : cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
4317 460 : eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
4318 460 : compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
4319 460 : format!("compaction-{tenant_shard_id}"),
4320 460 : 5,
4321 460 : // Compaction can be a very expensive operation, and might leak disk space. It also ought
4322 460 : // to be infallible, as long as remote storage is available. So if it repeatedly fails,
4323 460 : // use an extremely long backoff.
4324 460 : Some(Duration::from_secs(3600 * 24)),
4325 460 : )),
4326 460 : l0_compaction_trigger: Arc::new(Notify::new()),
4327 460 : scheduled_compaction_tasks: Mutex::new(Default::default()),
4328 460 : activate_now_sem: tokio::sync::Semaphore::new(0),
4329 460 : attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
4330 460 : cancel: CancellationToken::default(),
4331 460 : gate: Gate::default(),
4332 460 : pagestream_throttle: Arc::new(throttle::Throttle::new(
4333 460 : Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
4334 460 : )),
4335 460 : pagestream_throttle_metrics: Arc::new(
4336 460 : crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
4337 460 : ),
4338 460 : tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
4339 460 : ongoing_timeline_detach: std::sync::Mutex::default(),
4340 460 : gc_block: Default::default(),
4341 460 : l0_flush_global_state,
4342 460 : }
4343 460 : }
4344 :
4345 : /// Locate and load config
4346 0 : pub(super) fn load_tenant_config(
4347 0 : conf: &'static PageServerConf,
4348 0 : tenant_shard_id: &TenantShardId,
4349 0 : ) -> Result<LocationConf, LoadConfigError> {
4350 0 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
4351 0 :
4352 0 : info!("loading tenant configuration from {config_path}");
4353 :
4354 : // load and parse file
4355 0 : let config = fs::read_to_string(&config_path).map_err(|e| {
4356 0 : match e.kind() {
4357 : std::io::ErrorKind::NotFound => {
4358 : // The config should almost always exist for a tenant directory:
4359 : // - When attaching a tenant, the config is the first thing we write
4360 : // - When detaching a tenant, we atomically move the directory to a tmp location
4361 : // before deleting contents.
4362 : //
4363 : // The very rare edge case that can result in a missing config is if we crash during attach
4364 : // between creating directory and writing config. Callers should handle that as if the
4365 : // directory didn't exist.
4366 :
4367 0 : LoadConfigError::NotFound(config_path)
4368 : }
4369 : _ => {
4370 : // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
4371 : // that we cannot cleanly recover
4372 0 : crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
4373 : }
4374 : }
4375 0 : })?;
4376 :
4377 0 : Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
4378 0 : }
4379 :
4380 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
4381 : pub(super) async fn persist_tenant_config(
4382 : conf: &'static PageServerConf,
4383 : tenant_shard_id: &TenantShardId,
4384 : location_conf: &LocationConf,
4385 : ) -> std::io::Result<()> {
4386 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
4387 :
4388 : Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
4389 : }
4390 :
4391 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
4392 : pub(super) async fn persist_tenant_config_at(
4393 : tenant_shard_id: &TenantShardId,
4394 : config_path: &Utf8Path,
4395 : location_conf: &LocationConf,
4396 : ) -> std::io::Result<()> {
4397 : debug!("persisting tenantconf to {config_path}");
4398 :
4399 : let mut conf_content = r#"# This file contains a specific per-tenant's config.
4400 : # It is read in case of pageserver restart.
4401 : "#
4402 : .to_string();
4403 :
4404 0 : fail::fail_point!("tenant-config-before-write", |_| {
4405 0 : Err(std::io::Error::other("tenant-config-before-write"))
4406 0 : });
4407 :
4408 : // Convert the config to a toml file.
4409 : conf_content +=
4410 : &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
4411 :
4412 : let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
4413 :
4414 : let conf_content = conf_content.into_bytes();
4415 : VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
4416 : }
4417 :
4418 : //
4419 : // How garbage collection works:
4420 : //
4421 : // +--bar------------->
4422 : // /
4423 : // +----+-----foo---------------->
4424 : // /
4425 : // ----main--+-------------------------->
4426 : // \
4427 : // +-----baz-------->
4428 : //
4429 : //
4430 : // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
4431 : // `gc_infos` are being refreshed
4432 : // 2. Scan collected timelines, and on each timeline, make note of the
4433 : // all the points where other timelines have been branched off.
4434 : // We will refrain from removing page versions at those LSNs.
4435 : // 3. For each timeline, scan all layer files on the timeline.
4436 : // Remove all files for which a newer file exists and which
4437 : // don't cover any branch point LSNs.
4438 : //
4439 : // TODO:
4440 : // - if a relation has a non-incremental persistent layer on a child branch, then we
4441 : // don't need to keep that in the parent anymore. But currently
4442 : // we do.
4443 8 : async fn gc_iteration_internal(
4444 8 : &self,
4445 8 : target_timeline_id: Option<TimelineId>,
4446 8 : horizon: u64,
4447 8 : pitr: Duration,
4448 8 : cancel: &CancellationToken,
4449 8 : ctx: &RequestContext,
4450 8 : ) -> Result<GcResult, GcError> {
4451 8 : let mut totals: GcResult = Default::default();
4452 8 : let now = Instant::now();
4453 :
4454 8 : let gc_timelines = self
4455 8 : .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
4456 8 : .await?;
4457 :
4458 8 : failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
4459 :
4460 : // If there is nothing to GC, we don't want any messages in the INFO log.
4461 8 : if !gc_timelines.is_empty() {
4462 8 : info!("{} timelines need GC", gc_timelines.len());
4463 : } else {
4464 0 : debug!("{} timelines need GC", gc_timelines.len());
4465 : }
4466 :
4467 : // Perform GC for each timeline.
4468 : //
4469 : // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
4470 : // branch creation task, which requires the GC lock. A GC iteration can run concurrently
4471 : // with branch creation.
4472 : //
4473 : // See comments in [`Tenant::branch_timeline`] for more information about why branch
4474 : // creation task can run concurrently with timeline's GC iteration.
4475 16 : for timeline in gc_timelines {
4476 8 : if cancel.is_cancelled() {
4477 : // We were requested to shut down. Stop and return with the progress we
4478 : // made.
4479 0 : break;
4480 8 : }
4481 8 : let result = match timeline.gc().await {
4482 : Err(GcError::TimelineCancelled) => {
4483 0 : if target_timeline_id.is_some() {
4484 : // If we were targetting this specific timeline, surface cancellation to caller
4485 0 : return Err(GcError::TimelineCancelled);
4486 : } else {
4487 : // A timeline may be shutting down independently of the tenant's lifecycle: we should
4488 : // skip past this and proceed to try GC on other timelines.
4489 0 : continue;
4490 : }
4491 : }
4492 8 : r => r?,
4493 : };
4494 8 : totals += result;
4495 : }
4496 :
4497 8 : totals.elapsed = now.elapsed();
4498 8 : Ok(totals)
4499 8 : }
4500 :
4501 : /// Refreshes the Timeline::gc_info for all timelines, returning the
4502 : /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
4503 : /// [`Tenant::get_gc_horizon`].
4504 : ///
4505 : /// This is usually executed as part of periodic gc, but can now be triggered more often.
4506 8 : pub(crate) async fn refresh_gc_info(
4507 8 : &self,
4508 8 : cancel: &CancellationToken,
4509 8 : ctx: &RequestContext,
4510 8 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
4511 8 : // since this method can now be called at different rates than the configured gc loop, it
4512 8 : // might be that these configuration values get applied faster than what it was previously,
4513 8 : // since these were only read from the gc task.
4514 8 : let horizon = self.get_gc_horizon();
4515 8 : let pitr = self.get_pitr_interval();
4516 8 :
4517 8 : // refresh all timelines
4518 8 : let target_timeline_id = None;
4519 8 :
4520 8 : self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
4521 8 : .await
4522 8 : }
4523 :
4524 : /// Populate all Timelines' `GcInfo` with information about their children. We do not set the
4525 : /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
4526 : ///
4527 : /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
4528 0 : fn initialize_gc_info(
4529 0 : &self,
4530 0 : timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
4531 0 : timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
4532 0 : restrict_to_timeline: Option<TimelineId>,
4533 0 : ) {
4534 0 : if restrict_to_timeline.is_none() {
4535 : // This function must be called before activation: after activation timeline create/delete operations
4536 : // might happen, and this function is not safe to run concurrently with those.
4537 0 : assert!(!self.is_active());
4538 0 : }
4539 :
4540 : // Scan all timelines. For each timeline, remember the timeline ID and
4541 : // the branch point where it was created.
4542 0 : let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
4543 0 : BTreeMap::new();
4544 0 : timelines.iter().for_each(|(timeline_id, timeline_entry)| {
4545 0 : if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
4546 0 : let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
4547 0 : ancestor_children.push((
4548 0 : timeline_entry.get_ancestor_lsn(),
4549 0 : *timeline_id,
4550 0 : MaybeOffloaded::No,
4551 0 : ));
4552 0 : }
4553 0 : });
4554 0 : timelines_offloaded
4555 0 : .iter()
4556 0 : .for_each(|(timeline_id, timeline_entry)| {
4557 0 : let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
4558 0 : return;
4559 : };
4560 0 : let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
4561 0 : return;
4562 : };
4563 0 : let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
4564 0 : ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
4565 0 : });
4566 0 :
4567 0 : // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
4568 0 : let horizon = self.get_gc_horizon();
4569 :
4570 : // Populate each timeline's GcInfo with information about its child branches
4571 0 : let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
4572 0 : itertools::Either::Left(timelines.get(&timeline_id).into_iter())
4573 : } else {
4574 0 : itertools::Either::Right(timelines.values())
4575 : };
4576 0 : for timeline in timelines_to_write {
4577 0 : let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
4578 0 : .remove(&timeline.timeline_id)
4579 0 : .unwrap_or_default();
4580 0 :
4581 0 : branchpoints.sort_by_key(|b| b.0);
4582 0 :
4583 0 : let mut target = timeline.gc_info.write().unwrap();
4584 0 :
4585 0 : target.retain_lsns = branchpoints;
4586 0 :
4587 0 : let space_cutoff = timeline
4588 0 : .get_last_record_lsn()
4589 0 : .checked_sub(horizon)
4590 0 : .unwrap_or(Lsn(0));
4591 0 :
4592 0 : target.cutoffs = GcCutoffs {
4593 0 : space: space_cutoff,
4594 0 : time: Lsn::INVALID,
4595 0 : };
4596 0 : }
4597 0 : }
4598 :
4599 16 : async fn refresh_gc_info_internal(
4600 16 : &self,
4601 16 : target_timeline_id: Option<TimelineId>,
4602 16 : horizon: u64,
4603 16 : pitr: Duration,
4604 16 : cancel: &CancellationToken,
4605 16 : ctx: &RequestContext,
4606 16 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
4607 16 : // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
4608 16 : // currently visible timelines.
4609 16 : let timelines = self
4610 16 : .timelines
4611 16 : .lock()
4612 16 : .unwrap()
4613 16 : .values()
4614 40 : .filter(|tl| match target_timeline_id.as_ref() {
4615 8 : Some(target) => &tl.timeline_id == target,
4616 32 : None => true,
4617 40 : })
4618 16 : .cloned()
4619 16 : .collect::<Vec<_>>();
4620 16 :
4621 16 : if target_timeline_id.is_some() && timelines.is_empty() {
4622 : // We were to act on a particular timeline and it wasn't found
4623 0 : return Err(GcError::TimelineNotFound);
4624 16 : }
4625 16 :
4626 16 : let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
4627 16 : HashMap::with_capacity(timelines.len());
4628 16 :
4629 16 : // Ensures all timelines use the same start time when computing the time cutoff.
4630 16 : let now_ts_for_pitr_calc = SystemTime::now();
4631 40 : for timeline in timelines.iter() {
4632 40 : let ctx = &ctx.with_scope_timeline(timeline);
4633 40 : let cutoff = timeline
4634 40 : .get_last_record_lsn()
4635 40 : .checked_sub(horizon)
4636 40 : .unwrap_or(Lsn(0));
4637 :
4638 40 : let cutoffs = timeline
4639 40 : .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
4640 40 : .await?;
4641 40 : let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
4642 40 : assert!(old.is_none());
4643 : }
4644 :
4645 16 : if !self.is_active() || self.cancel.is_cancelled() {
4646 0 : return Err(GcError::TenantCancelled);
4647 16 : }
4648 :
4649 : // grab mutex to prevent new timelines from being created here; avoid doing long operations
4650 : // because that will stall branch creation.
4651 16 : let gc_cs = self.gc_cs.lock().await;
4652 :
4653 : // Ok, we now know all the branch points.
4654 : // Update the GC information for each timeline.
4655 16 : let mut gc_timelines = Vec::with_capacity(timelines.len());
4656 56 : for timeline in timelines {
4657 : // We filtered the timeline list above
4658 40 : if let Some(target_timeline_id) = target_timeline_id {
4659 8 : assert_eq!(target_timeline_id, timeline.timeline_id);
4660 32 : }
4661 :
4662 : {
4663 40 : let mut target = timeline.gc_info.write().unwrap();
4664 40 :
4665 40 : // Cull any expired leases
4666 40 : let now = SystemTime::now();
4667 40 : target.leases.retain(|_, lease| !lease.is_expired(&now));
4668 40 :
4669 40 : timeline
4670 40 : .metrics
4671 40 : .valid_lsn_lease_count_gauge
4672 40 : .set(target.leases.len() as u64);
4673 :
4674 : // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
4675 40 : if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
4676 24 : if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
4677 24 : target.within_ancestor_pitr =
4678 24 : timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
4679 24 : }
4680 16 : }
4681 :
4682 : // Update metrics that depend on GC state
4683 40 : timeline
4684 40 : .metrics
4685 40 : .archival_size
4686 40 : .set(if target.within_ancestor_pitr {
4687 0 : timeline.metrics.current_logical_size_gauge.get()
4688 : } else {
4689 40 : 0
4690 : });
4691 40 : timeline.metrics.pitr_history_size.set(
4692 40 : timeline
4693 40 : .get_last_record_lsn()
4694 40 : .checked_sub(target.cutoffs.time)
4695 40 : .unwrap_or(Lsn(0))
4696 40 : .0,
4697 40 : );
4698 :
4699 : // Apply the cutoffs we found to the Timeline's GcInfo. Why might we _not_ have cutoffs for a timeline?
4700 : // - this timeline was created while we were finding cutoffs
4701 : // - lsn for timestamp search fails for this timeline repeatedly
4702 40 : if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
4703 40 : let original_cutoffs = target.cutoffs.clone();
4704 40 : // GC cutoffs should never go back
4705 40 : target.cutoffs = GcCutoffs {
4706 40 : space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
4707 40 : time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
4708 40 : }
4709 0 : }
4710 : }
4711 :
4712 40 : gc_timelines.push(timeline);
4713 : }
4714 16 : drop(gc_cs);
4715 16 : Ok(gc_timelines)
4716 16 : }
4717 :
4718 : /// A substitute for `branch_timeline` for use in unit tests.
4719 : /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
4720 : /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
4721 : /// timeline background tasks are launched, except the flush loop.
4722 : #[cfg(test)]
4723 476 : async fn branch_timeline_test(
4724 476 : self: &Arc<Self>,
4725 476 : src_timeline: &Arc<Timeline>,
4726 476 : dst_id: TimelineId,
4727 476 : ancestor_lsn: Option<Lsn>,
4728 476 : ctx: &RequestContext,
4729 476 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
4730 476 : let tl = self
4731 476 : .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
4732 476 : .await?
4733 468 : .into_timeline_for_test();
4734 468 : tl.set_state(TimelineState::Active);
4735 468 : Ok(tl)
4736 476 : }
4737 :
4738 : /// Helper for unit tests to branch a timeline with some pre-loaded states.
4739 : #[cfg(test)]
4740 : #[allow(clippy::too_many_arguments)]
4741 24 : pub async fn branch_timeline_test_with_layers(
4742 24 : self: &Arc<Self>,
4743 24 : src_timeline: &Arc<Timeline>,
4744 24 : dst_id: TimelineId,
4745 24 : ancestor_lsn: Option<Lsn>,
4746 24 : ctx: &RequestContext,
4747 24 : delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
4748 24 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
4749 24 : end_lsn: Lsn,
4750 24 : ) -> anyhow::Result<Arc<Timeline>> {
4751 : use checks::check_valid_layermap;
4752 : use itertools::Itertools;
4753 :
4754 24 : let tline = self
4755 24 : .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
4756 24 : .await?;
4757 24 : let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
4758 24 : ancestor_lsn
4759 : } else {
4760 0 : tline.get_last_record_lsn()
4761 : };
4762 24 : assert!(end_lsn >= ancestor_lsn);
4763 24 : tline.force_advance_lsn(end_lsn);
4764 36 : for deltas in delta_layer_desc {
4765 12 : tline
4766 12 : .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
4767 12 : .await?;
4768 : }
4769 32 : for (lsn, images) in image_layer_desc {
4770 8 : tline
4771 8 : .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
4772 8 : .await?;
4773 : }
4774 24 : let layer_names = tline
4775 24 : .layers
4776 24 : .read()
4777 24 : .await
4778 24 : .layer_map()
4779 24 : .unwrap()
4780 24 : .iter_historic_layers()
4781 24 : .map(|layer| layer.layer_name())
4782 24 : .collect_vec();
4783 24 : if let Some(err) = check_valid_layermap(&layer_names) {
4784 0 : bail!("invalid layermap: {err}");
4785 24 : }
4786 24 : Ok(tline)
4787 24 : }
4788 :
4789 : /// Branch an existing timeline.
4790 0 : async fn branch_timeline(
4791 0 : self: &Arc<Self>,
4792 0 : src_timeline: &Arc<Timeline>,
4793 0 : dst_id: TimelineId,
4794 0 : start_lsn: Option<Lsn>,
4795 0 : ctx: &RequestContext,
4796 0 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
4797 0 : self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
4798 0 : .await
4799 0 : }
4800 :
4801 476 : async fn branch_timeline_impl(
4802 476 : self: &Arc<Self>,
4803 476 : src_timeline: &Arc<Timeline>,
4804 476 : dst_id: TimelineId,
4805 476 : start_lsn: Option<Lsn>,
4806 476 : ctx: &RequestContext,
4807 476 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
4808 476 : let src_id = src_timeline.timeline_id;
4809 :
4810 : // We will validate our ancestor LSN in this function. Acquire the GC lock so that
4811 : // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
4812 : // valid while we are creating the branch.
4813 476 : let _gc_cs = self.gc_cs.lock().await;
4814 :
4815 : // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
4816 476 : let start_lsn = start_lsn.unwrap_or_else(|| {
4817 4 : let lsn = src_timeline.get_last_record_lsn();
4818 4 : info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
4819 4 : lsn
4820 476 : });
4821 :
4822 : // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
4823 476 : let timeline_create_guard = match self
4824 476 : .start_creating_timeline(
4825 476 : dst_id,
4826 476 : CreateTimelineIdempotency::Branch {
4827 476 : ancestor_timeline_id: src_timeline.timeline_id,
4828 476 : ancestor_start_lsn: start_lsn,
4829 476 : },
4830 476 : )
4831 476 : .await?
4832 : {
4833 476 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
4834 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
4835 0 : return Ok(CreateTimelineResult::Idempotent(timeline));
4836 : }
4837 : };
4838 :
4839 : // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
4840 : // horizon on the source timeline
4841 : //
4842 : // We check it against both the planned GC cutoff stored in 'gc_info',
4843 : // and the 'latest_gc_cutoff' of the last GC that was performed. The
4844 : // planned GC cutoff in 'gc_info' is normally larger than
4845 : // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
4846 : // changed the GC settings for the tenant to make the PITR window
4847 : // larger, but some of the data was already removed by an earlier GC
4848 : // iteration.
4849 :
4850 : // check against last actual 'latest_gc_cutoff' first
4851 476 : let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
4852 476 : {
4853 476 : let gc_info = src_timeline.gc_info.read().unwrap();
4854 476 : let planned_cutoff = gc_info.min_cutoff();
4855 476 : if gc_info.lsn_covered_by_lease(start_lsn) {
4856 0 : tracing::info!(
4857 0 : "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
4858 0 : *applied_gc_cutoff_lsn
4859 : );
4860 : } else {
4861 476 : src_timeline
4862 476 : .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
4863 476 : .context(format!(
4864 476 : "invalid branch start lsn: less than latest GC cutoff {}",
4865 476 : *applied_gc_cutoff_lsn,
4866 476 : ))
4867 476 : .map_err(CreateTimelineError::AncestorLsn)?;
4868 :
4869 : // and then the planned GC cutoff
4870 468 : if start_lsn < planned_cutoff {
4871 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
4872 0 : "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
4873 0 : )));
4874 468 : }
4875 : }
4876 : }
4877 :
4878 : //
4879 : // The branch point is valid, and we are still holding the 'gc_cs' lock
4880 : // so that GC cannot advance the GC cutoff until we are finished.
4881 : // Proceed with the branch creation.
4882 : //
4883 :
4884 : // Determine prev-LSN for the new timeline. We can only determine it if
4885 : // the timeline was branched at the current end of the source timeline.
4886 : let RecordLsn {
4887 468 : last: src_last,
4888 468 : prev: src_prev,
4889 468 : } = src_timeline.get_last_record_rlsn();
4890 468 : let dst_prev = if src_last == start_lsn {
4891 432 : Some(src_prev)
4892 : } else {
4893 36 : None
4894 : };
4895 :
4896 : // Create the metadata file, noting the ancestor of the new timeline.
4897 : // There is initially no data in it, but all the read-calls know to look
4898 : // into the ancestor.
4899 468 : let metadata = TimelineMetadata::new(
4900 468 : start_lsn,
4901 468 : dst_prev,
4902 468 : Some(src_id),
4903 468 : start_lsn,
4904 468 : *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
4905 468 : src_timeline.initdb_lsn,
4906 468 : src_timeline.pg_version,
4907 468 : );
4908 :
4909 468 : let (uninitialized_timeline, _timeline_ctx) = self
4910 468 : .prepare_new_timeline(
4911 468 : dst_id,
4912 468 : &metadata,
4913 468 : timeline_create_guard,
4914 468 : start_lsn + 1,
4915 468 : Some(Arc::clone(src_timeline)),
4916 468 : Some(src_timeline.get_rel_size_v2_status()),
4917 468 : ctx,
4918 468 : )
4919 468 : .await?;
4920 :
4921 468 : let new_timeline = uninitialized_timeline.finish_creation().await?;
4922 :
4923 : // Root timeline gets its layers during creation and uploads them along with the metadata.
4924 : // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
4925 : // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
4926 : // could get incorrect information and remove more layers, than needed.
4927 : // See also https://github.com/neondatabase/neon/issues/3865
4928 468 : new_timeline
4929 468 : .remote_client
4930 468 : .schedule_index_upload_for_full_metadata_update(&metadata)
4931 468 : .context("branch initial metadata upload")?;
4932 :
4933 : // Callers are responsible to wait for uploads to complete and for activating the timeline.
4934 :
4935 468 : Ok(CreateTimelineResult::Created(new_timeline))
4936 476 : }
4937 :
4938 : /// For unit tests, make this visible so that other modules can directly create timelines
4939 : #[cfg(test)]
4940 : #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
4941 : pub(crate) async fn bootstrap_timeline_test(
4942 : self: &Arc<Self>,
4943 : timeline_id: TimelineId,
4944 : pg_version: u32,
4945 : load_existing_initdb: Option<TimelineId>,
4946 : ctx: &RequestContext,
4947 : ) -> anyhow::Result<Arc<Timeline>> {
4948 : self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
4949 : .await
4950 : .map_err(anyhow::Error::new)
4951 4 : .map(|r| r.into_timeline_for_test())
4952 : }
4953 :
4954 : /// Get exclusive access to the timeline ID for creation.
4955 : ///
4956 : /// Timeline-creating code paths must use this function before making changes
4957 : /// to in-memory or persistent state.
4958 : ///
4959 : /// The `state` parameter is a description of the timeline creation operation
4960 : /// we intend to perform.
4961 : /// If the timeline was already created in the meantime, we check whether this
4962 : /// request conflicts or is idempotent , based on `state`.
4963 924 : async fn start_creating_timeline(
4964 924 : self: &Arc<Self>,
4965 924 : new_timeline_id: TimelineId,
4966 924 : idempotency: CreateTimelineIdempotency,
4967 924 : ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
4968 924 : let allow_offloaded = false;
4969 924 : match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
4970 920 : Ok(create_guard) => {
4971 920 : pausable_failpoint!("timeline-creation-after-uninit");
4972 920 : Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
4973 : }
4974 0 : Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
4975 : Err(TimelineExclusionError::AlreadyCreating) => {
4976 : // Creation is in progress, we cannot create it again, and we cannot
4977 : // check if this request matches the existing one, so caller must try
4978 : // again later.
4979 0 : Err(CreateTimelineError::AlreadyCreating)
4980 : }
4981 0 : Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
4982 : Err(TimelineExclusionError::AlreadyExists {
4983 0 : existing: TimelineOrOffloaded::Offloaded(_existing),
4984 0 : ..
4985 0 : }) => {
4986 0 : info!("timeline already exists but is offloaded");
4987 0 : Err(CreateTimelineError::Conflict)
4988 : }
4989 : Err(TimelineExclusionError::AlreadyExists {
4990 4 : existing: TimelineOrOffloaded::Timeline(existing),
4991 4 : arg,
4992 4 : }) => {
4993 4 : {
4994 4 : let existing = &existing.create_idempotency;
4995 4 : let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
4996 4 : debug!("timeline already exists");
4997 :
4998 4 : match (existing, &arg) {
4999 : // FailWithConflict => no idempotency check
5000 : (CreateTimelineIdempotency::FailWithConflict, _)
5001 : | (_, CreateTimelineIdempotency::FailWithConflict) => {
5002 4 : warn!("timeline already exists, failing request");
5003 4 : return Err(CreateTimelineError::Conflict);
5004 : }
5005 : // Idempotent <=> CreateTimelineIdempotency is identical
5006 0 : (x, y) if x == y => {
5007 0 : info!(
5008 0 : "timeline already exists and idempotency matches, succeeding request"
5009 : );
5010 : // fallthrough
5011 : }
5012 : (_, _) => {
5013 0 : warn!("idempotency conflict, failing request");
5014 0 : return Err(CreateTimelineError::Conflict);
5015 : }
5016 : }
5017 : }
5018 :
5019 0 : Ok(StartCreatingTimelineResult::Idempotent(existing))
5020 : }
5021 : }
5022 924 : }
5023 :
5024 0 : async fn upload_initdb(
5025 0 : &self,
5026 0 : timelines_path: &Utf8PathBuf,
5027 0 : pgdata_path: &Utf8PathBuf,
5028 0 : timeline_id: &TimelineId,
5029 0 : ) -> anyhow::Result<()> {
5030 0 : let temp_path = timelines_path.join(format!(
5031 0 : "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
5032 0 : ));
5033 0 :
5034 0 : scopeguard::defer! {
5035 0 : if let Err(e) = fs::remove_file(&temp_path) {
5036 0 : error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
5037 0 : }
5038 0 : }
5039 :
5040 0 : let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
5041 : const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
5042 0 : if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
5043 0 : warn!(
5044 0 : "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
5045 : );
5046 0 : }
5047 :
5048 0 : pausable_failpoint!("before-initdb-upload");
5049 :
5050 0 : backoff::retry(
5051 0 : || async {
5052 0 : self::remote_timeline_client::upload_initdb_dir(
5053 0 : &self.remote_storage,
5054 0 : &self.tenant_shard_id.tenant_id,
5055 0 : timeline_id,
5056 0 : pgdata_zstd.try_clone().await?,
5057 0 : tar_zst_size,
5058 0 : &self.cancel,
5059 0 : )
5060 0 : .await
5061 0 : },
5062 0 : |_| false,
5063 0 : 3,
5064 0 : u32::MAX,
5065 0 : "persist_initdb_tar_zst",
5066 0 : &self.cancel,
5067 0 : )
5068 0 : .await
5069 0 : .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
5070 0 : .and_then(|x| x)
5071 0 : }
5072 :
5073 : /// - run initdb to init temporary instance and get bootstrap data
5074 : /// - after initialization completes, tar up the temp dir and upload it to S3.
5075 4 : async fn bootstrap_timeline(
5076 4 : self: &Arc<Self>,
5077 4 : timeline_id: TimelineId,
5078 4 : pg_version: u32,
5079 4 : load_existing_initdb: Option<TimelineId>,
5080 4 : ctx: &RequestContext,
5081 4 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
5082 4 : let timeline_create_guard = match self
5083 4 : .start_creating_timeline(
5084 4 : timeline_id,
5085 4 : CreateTimelineIdempotency::Bootstrap { pg_version },
5086 4 : )
5087 4 : .await?
5088 : {
5089 4 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
5090 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
5091 0 : return Ok(CreateTimelineResult::Idempotent(timeline));
5092 : }
5093 : };
5094 :
5095 : // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
5096 : // temporary directory for basebackup files for the given timeline.
5097 :
5098 4 : let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
5099 4 : let pgdata_path = path_with_suffix_extension(
5100 4 : timelines_path.join(format!("basebackup-{timeline_id}")),
5101 4 : TEMP_FILE_SUFFIX,
5102 4 : );
5103 4 :
5104 4 : // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
5105 4 : // we won't race with other creations or existent timelines with the same path.
5106 4 : if pgdata_path.exists() {
5107 0 : fs::remove_dir_all(&pgdata_path).with_context(|| {
5108 0 : format!("Failed to remove already existing initdb directory: {pgdata_path}")
5109 0 : })?;
5110 0 : tracing::info!("removed previous attempt's temporary initdb directory '{pgdata_path}'");
5111 4 : }
5112 :
5113 : // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
5114 4 : let pgdata_path_deferred = pgdata_path.clone();
5115 4 : scopeguard::defer! {
5116 4 : if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred).or_else(fs_ext::ignore_not_found) {
5117 4 : // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
5118 4 : error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
5119 4 : } else {
5120 4 : tracing::info!("removed temporary initdb directory '{pgdata_path_deferred}'");
5121 4 : }
5122 4 : }
5123 4 : if let Some(existing_initdb_timeline_id) = load_existing_initdb {
5124 4 : if existing_initdb_timeline_id != timeline_id {
5125 0 : let source_path = &remote_initdb_archive_path(
5126 0 : &self.tenant_shard_id.tenant_id,
5127 0 : &existing_initdb_timeline_id,
5128 0 : );
5129 0 : let dest_path =
5130 0 : &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
5131 0 :
5132 0 : // if this fails, it will get retried by retried control plane requests
5133 0 : self.remote_storage
5134 0 : .copy_object(source_path, dest_path, &self.cancel)
5135 0 : .await
5136 0 : .context("copy initdb tar")?;
5137 4 : }
5138 4 : let (initdb_tar_zst_path, initdb_tar_zst) =
5139 4 : self::remote_timeline_client::download_initdb_tar_zst(
5140 4 : self.conf,
5141 4 : &self.remote_storage,
5142 4 : &self.tenant_shard_id,
5143 4 : &existing_initdb_timeline_id,
5144 4 : &self.cancel,
5145 4 : )
5146 4 : .await
5147 4 : .context("download initdb tar")?;
5148 :
5149 4 : scopeguard::defer! {
5150 4 : if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
5151 4 : error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
5152 4 : }
5153 4 : }
5154 4 :
5155 4 : let buf_read =
5156 4 : BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
5157 4 : extract_zst_tarball(&pgdata_path, buf_read)
5158 4 : .await
5159 4 : .context("extract initdb tar")?;
5160 : } else {
5161 : // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
5162 0 : run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
5163 0 : .await
5164 0 : .context("run initdb")?;
5165 :
5166 : // Upload the created data dir to S3
5167 0 : if self.tenant_shard_id().is_shard_zero() {
5168 0 : self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
5169 0 : .await?;
5170 0 : }
5171 : }
5172 4 : let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
5173 4 :
5174 4 : // Import the contents of the data directory at the initial checkpoint
5175 4 : // LSN, and any WAL after that.
5176 4 : // Initdb lsn will be equal to last_record_lsn which will be set after import.
5177 4 : // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
5178 4 : let new_metadata = TimelineMetadata::new(
5179 4 : Lsn(0),
5180 4 : None,
5181 4 : None,
5182 4 : Lsn(0),
5183 4 : pgdata_lsn,
5184 4 : pgdata_lsn,
5185 4 : pg_version,
5186 4 : );
5187 4 : let (mut raw_timeline, timeline_ctx) = self
5188 4 : .prepare_new_timeline(
5189 4 : timeline_id,
5190 4 : &new_metadata,
5191 4 : timeline_create_guard,
5192 4 : pgdata_lsn,
5193 4 : None,
5194 4 : None,
5195 4 : ctx,
5196 4 : )
5197 4 : .await?;
5198 :
5199 4 : let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
5200 4 : raw_timeline
5201 4 : .write(|unfinished_timeline| async move {
5202 4 : import_datadir::import_timeline_from_postgres_datadir(
5203 4 : &unfinished_timeline,
5204 4 : &pgdata_path,
5205 4 : pgdata_lsn,
5206 4 : &timeline_ctx,
5207 4 : )
5208 4 : .await
5209 4 : .with_context(|| {
5210 0 : format!(
5211 0 : "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
5212 0 : )
5213 4 : })?;
5214 :
5215 4 : fail::fail_point!("before-checkpoint-new-timeline", |_| {
5216 0 : Err(CreateTimelineError::Other(anyhow::anyhow!(
5217 0 : "failpoint before-checkpoint-new-timeline"
5218 0 : )))
5219 4 : });
5220 :
5221 4 : Ok(())
5222 8 : })
5223 4 : .await?;
5224 :
5225 : // All done!
5226 4 : let timeline = raw_timeline.finish_creation().await?;
5227 :
5228 : // Callers are responsible to wait for uploads to complete and for activating the timeline.
5229 :
5230 4 : Ok(CreateTimelineResult::Created(timeline))
5231 4 : }
5232 :
5233 912 : fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
5234 912 : RemoteTimelineClient::new(
5235 912 : self.remote_storage.clone(),
5236 912 : self.deletion_queue_client.clone(),
5237 912 : self.conf,
5238 912 : self.tenant_shard_id,
5239 912 : timeline_id,
5240 912 : self.generation,
5241 912 : &self.tenant_conf.load().location,
5242 912 : )
5243 912 : }
5244 :
5245 : /// Builds required resources for a new timeline.
5246 912 : fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
5247 912 : let remote_client = self.build_timeline_remote_client(timeline_id);
5248 912 : self.get_timeline_resources_for(remote_client)
5249 912 : }
5250 :
5251 : /// Builds timeline resources for the given remote client.
5252 924 : fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
5253 924 : TimelineResources {
5254 924 : remote_client,
5255 924 : pagestream_throttle: self.pagestream_throttle.clone(),
5256 924 : pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
5257 924 : l0_compaction_trigger: self.l0_compaction_trigger.clone(),
5258 924 : l0_flush_global_state: self.l0_flush_global_state.clone(),
5259 924 : }
5260 924 : }
5261 :
5262 : /// Creates intermediate timeline structure and its files.
5263 : ///
5264 : /// An empty layer map is initialized, and new data and WAL can be imported starting
5265 : /// at 'disk_consistent_lsn'. After any initial data has been imported, call
5266 : /// `finish_creation` to insert the Timeline into the timelines map.
5267 : #[allow(clippy::too_many_arguments)]
5268 912 : async fn prepare_new_timeline<'a>(
5269 912 : &'a self,
5270 912 : new_timeline_id: TimelineId,
5271 912 : new_metadata: &TimelineMetadata,
5272 912 : create_guard: TimelineCreateGuard,
5273 912 : start_lsn: Lsn,
5274 912 : ancestor: Option<Arc<Timeline>>,
5275 912 : rel_size_v2_status: Option<RelSizeMigration>,
5276 912 : ctx: &RequestContext,
5277 912 : ) -> anyhow::Result<(UninitializedTimeline<'a>, RequestContext)> {
5278 912 : let tenant_shard_id = self.tenant_shard_id;
5279 912 :
5280 912 : let resources = self.build_timeline_resources(new_timeline_id);
5281 912 : resources
5282 912 : .remote_client
5283 912 : .init_upload_queue_for_empty_remote(new_metadata, rel_size_v2_status.clone())?;
5284 :
5285 912 : let (timeline_struct, timeline_ctx) = self
5286 912 : .create_timeline_struct(
5287 912 : new_timeline_id,
5288 912 : new_metadata,
5289 912 : None,
5290 912 : ancestor,
5291 912 : resources,
5292 912 : CreateTimelineCause::Load,
5293 912 : create_guard.idempotency.clone(),
5294 912 : None,
5295 912 : rel_size_v2_status,
5296 912 : ctx,
5297 912 : )
5298 912 : .context("Failed to create timeline data structure")?;
5299 :
5300 912 : timeline_struct.init_empty_layer_map(start_lsn);
5301 :
5302 912 : if let Err(e) = self
5303 912 : .create_timeline_files(&create_guard.timeline_path)
5304 912 : .await
5305 : {
5306 0 : error!(
5307 0 : "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
5308 : );
5309 0 : cleanup_timeline_directory(create_guard);
5310 0 : return Err(e);
5311 912 : }
5312 912 :
5313 912 : debug!(
5314 0 : "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
5315 : );
5316 :
5317 912 : Ok((
5318 912 : UninitializedTimeline::new(
5319 912 : self,
5320 912 : new_timeline_id,
5321 912 : Some((timeline_struct, create_guard)),
5322 912 : ),
5323 912 : timeline_ctx,
5324 912 : ))
5325 912 : }
5326 :
5327 912 : async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
5328 912 : crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
5329 :
5330 912 : fail::fail_point!("after-timeline-dir-creation", |_| {
5331 0 : anyhow::bail!("failpoint after-timeline-dir-creation");
5332 912 : });
5333 :
5334 912 : Ok(())
5335 912 : }
5336 :
5337 : /// Get a guard that provides exclusive access to the timeline directory, preventing
5338 : /// concurrent attempts to create the same timeline.
5339 : ///
5340 : /// The `allow_offloaded` parameter controls whether to tolerate the existence of
5341 : /// offloaded timelines or not.
5342 924 : fn create_timeline_create_guard(
5343 924 : self: &Arc<Self>,
5344 924 : timeline_id: TimelineId,
5345 924 : idempotency: CreateTimelineIdempotency,
5346 924 : allow_offloaded: bool,
5347 924 : ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
5348 924 : let tenant_shard_id = self.tenant_shard_id;
5349 924 :
5350 924 : let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
5351 :
5352 924 : let create_guard = TimelineCreateGuard::new(
5353 924 : self,
5354 924 : timeline_id,
5355 924 : timeline_path.clone(),
5356 924 : idempotency,
5357 924 : allow_offloaded,
5358 924 : )?;
5359 :
5360 : // At this stage, we have got exclusive access to in-memory state for this timeline ID
5361 : // for creation.
5362 : // A timeline directory should never exist on disk already:
5363 : // - a previous failed creation would have cleaned up after itself
5364 : // - a pageserver restart would clean up timeline directories that don't have valid remote state
5365 : //
5366 : // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
5367 : // this error may indicate a bug in cleanup on failed creations.
5368 920 : if timeline_path.exists() {
5369 0 : return Err(TimelineExclusionError::Other(anyhow::anyhow!(
5370 0 : "Timeline directory already exists! This is a bug."
5371 0 : )));
5372 920 : }
5373 920 :
5374 920 : Ok(create_guard)
5375 924 : }
5376 :
5377 : /// Gathers inputs from all of the timelines to produce a sizing model input.
5378 : ///
5379 : /// Future is cancellation safe. Only one calculation can be running at once per tenant.
5380 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5381 : pub async fn gather_size_inputs(
5382 : &self,
5383 : // `max_retention_period` overrides the cutoff that is used to calculate the size
5384 : // (only if it is shorter than the real cutoff).
5385 : max_retention_period: Option<u64>,
5386 : cause: LogicalSizeCalculationCause,
5387 : cancel: &CancellationToken,
5388 : ctx: &RequestContext,
5389 : ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
5390 : let logical_sizes_at_once = self
5391 : .conf
5392 : .concurrent_tenant_size_logical_size_queries
5393 : .inner();
5394 :
5395 : // TODO: Having a single mutex block concurrent reads is not great for performance.
5396 : //
5397 : // But the only case where we need to run multiple of these at once is when we
5398 : // request a size for a tenant manually via API, while another background calculation
5399 : // is in progress (which is not a common case).
5400 : //
5401 : // See more for on the issue #2748 condenced out of the initial PR review.
5402 : let mut shared_cache = tokio::select! {
5403 : locked = self.cached_logical_sizes.lock() => locked,
5404 : _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
5405 : _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
5406 : };
5407 :
5408 : size::gather_inputs(
5409 : self,
5410 : logical_sizes_at_once,
5411 : max_retention_period,
5412 : &mut shared_cache,
5413 : cause,
5414 : cancel,
5415 : ctx,
5416 : )
5417 : .await
5418 : }
5419 :
5420 : /// Calculate synthetic tenant size and cache the result.
5421 : /// This is periodically called by background worker.
5422 : /// result is cached in tenant struct
5423 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5424 : pub async fn calculate_synthetic_size(
5425 : &self,
5426 : cause: LogicalSizeCalculationCause,
5427 : cancel: &CancellationToken,
5428 : ctx: &RequestContext,
5429 : ) -> Result<u64, size::CalculateSyntheticSizeError> {
5430 : let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
5431 :
5432 : let size = inputs.calculate();
5433 :
5434 : self.set_cached_synthetic_size(size);
5435 :
5436 : Ok(size)
5437 : }
5438 :
5439 : /// Cache given synthetic size and update the metric value
5440 0 : pub fn set_cached_synthetic_size(&self, size: u64) {
5441 0 : self.cached_synthetic_tenant_size
5442 0 : .store(size, Ordering::Relaxed);
5443 0 :
5444 0 : // Only shard zero should be calculating synthetic sizes
5445 0 : debug_assert!(self.shard_identity.is_shard_zero());
5446 :
5447 0 : TENANT_SYNTHETIC_SIZE_METRIC
5448 0 : .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
5449 0 : .unwrap()
5450 0 : .set(size);
5451 0 : }
5452 :
5453 0 : pub fn cached_synthetic_size(&self) -> u64 {
5454 0 : self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
5455 0 : }
5456 :
5457 : /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
5458 : ///
5459 : /// This function can take a long time: callers should wrap it in a timeout if calling
5460 : /// from an external API handler.
5461 : ///
5462 : /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
5463 : /// still bounded by tenant/timeline shutdown.
5464 : #[tracing::instrument(skip_all)]
5465 : pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
5466 : let timelines = self.timelines.lock().unwrap().clone();
5467 :
5468 0 : async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
5469 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
5470 0 : timeline.freeze_and_flush().await?;
5471 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
5472 0 : timeline.remote_client.wait_completion().await?;
5473 :
5474 0 : Ok(())
5475 0 : }
5476 :
5477 : // We do not use a JoinSet for these tasks, because we don't want them to be
5478 : // aborted when this function's future is cancelled: they should stay alive
5479 : // holding their GateGuard until they complete, to ensure their I/Os complete
5480 : // before Timeline shutdown completes.
5481 : let mut results = FuturesUnordered::new();
5482 :
5483 : for (_timeline_id, timeline) in timelines {
5484 : // Run each timeline's flush in a task holding the timeline's gate: this
5485 : // means that if this function's future is cancelled, the Timeline shutdown
5486 : // will still wait for any I/O in here to complete.
5487 : let Ok(gate) = timeline.gate.enter() else {
5488 : continue;
5489 : };
5490 0 : let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
5491 : results.push(jh);
5492 : }
5493 :
5494 : while let Some(r) = results.next().await {
5495 : if let Err(e) = r {
5496 : if !e.is_cancelled() && !e.is_panic() {
5497 : tracing::error!("unexpected join error: {e:?}");
5498 : }
5499 : }
5500 : }
5501 :
5502 : // The flushes we did above were just writes, but the Tenant might have had
5503 : // pending deletions as well from recent compaction/gc: we want to flush those
5504 : // as well. This requires flushing the global delete queue. This is cheap
5505 : // because it's typically a no-op.
5506 : match self.deletion_queue_client.flush_execute().await {
5507 : Ok(_) => {}
5508 : Err(DeletionQueueError::ShuttingDown) => {}
5509 : }
5510 :
5511 : Ok(())
5512 : }
5513 :
5514 0 : pub(crate) fn get_tenant_conf(&self) -> pageserver_api::models::TenantConfig {
5515 0 : self.tenant_conf.load().tenant_conf.clone()
5516 0 : }
5517 :
5518 : /// How much local storage would this tenant like to have? It can cope with
5519 : /// less than this (via eviction and on-demand downloads), but this function enables
5520 : /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
5521 : /// by keeping important things on local disk.
5522 : ///
5523 : /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
5524 : /// than they report here, due to layer eviction. Tenants with many active branches may
5525 : /// actually use more than they report here.
5526 0 : pub(crate) fn local_storage_wanted(&self) -> u64 {
5527 0 : let timelines = self.timelines.lock().unwrap();
5528 0 :
5529 0 : // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum. This
5530 0 : // reflects the observation that on tenants with multiple large branches, typically only one
5531 0 : // of them is used actively enough to occupy space on disk.
5532 0 : timelines
5533 0 : .values()
5534 0 : .map(|t| t.metrics.visible_physical_size_gauge.get())
5535 0 : .max()
5536 0 : .unwrap_or(0)
5537 0 : }
5538 :
5539 : /// Builds a new tenant manifest, and uploads it if it differs from the last-known tenant
5540 : /// manifest in `Self::remote_tenant_manifest`.
5541 : ///
5542 : /// TODO: instead of requiring callers to remember to call `maybe_upload_tenant_manifest` after
5543 : /// changing any `Tenant` state that's included in the manifest, consider making the manifest
5544 : /// the authoritative source of data with an API that automatically uploads on changes. Revisit
5545 : /// this when the manifest is more widely used and we have a better idea of the data model.
5546 464 : pub(crate) async fn maybe_upload_tenant_manifest(&self) -> Result<(), TenantManifestError> {
5547 : // Multiple tasks may call this function concurrently after mutating the Tenant runtime
5548 : // state, affecting the manifest generated by `build_tenant_manifest`. We use an async mutex
5549 : // to serialize these callers. `eq_ignoring_version` acts as a slightly inefficient but
5550 : // simple coalescing mechanism.
5551 464 : let mut guard = tokio::select! {
5552 464 : guard = self.remote_tenant_manifest.lock() => guard,
5553 464 : _ = self.cancel.cancelled() => return Err(TenantManifestError::Cancelled),
5554 : };
5555 :
5556 : // Build a new manifest.
5557 464 : let manifest = self.build_tenant_manifest();
5558 :
5559 : // Check if the manifest has changed. We ignore the version number here, to avoid
5560 : // uploading every manifest on version number bumps.
5561 464 : if let Some(old) = guard.as_ref() {
5562 16 : if manifest.eq_ignoring_version(old) {
5563 12 : return Ok(());
5564 4 : }
5565 448 : }
5566 :
5567 : // Upload the manifest. Remote storage does no retries internally, so retry here.
5568 452 : match backoff::retry(
5569 452 : || async {
5570 452 : upload_tenant_manifest(
5571 452 : &self.remote_storage,
5572 452 : &self.tenant_shard_id,
5573 452 : self.generation,
5574 452 : &manifest,
5575 452 : &self.cancel,
5576 452 : )
5577 452 : .await
5578 904 : },
5579 452 : |_| self.cancel.is_cancelled(),
5580 452 : FAILED_UPLOAD_WARN_THRESHOLD,
5581 452 : FAILED_REMOTE_OP_RETRIES,
5582 452 : "uploading tenant manifest",
5583 452 : &self.cancel,
5584 452 : )
5585 452 : .await
5586 : {
5587 0 : None => Err(TenantManifestError::Cancelled),
5588 0 : Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
5589 0 : Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
5590 : Some(Ok(_)) => {
5591 : // Store the successfully uploaded manifest, so that future callers can avoid
5592 : // re-uploading the same thing.
5593 452 : *guard = Some(manifest);
5594 452 :
5595 452 : Ok(())
5596 : }
5597 : }
5598 464 : }
5599 : }
5600 :
5601 : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
5602 : /// to get bootstrap data for timeline initialization.
5603 0 : async fn run_initdb(
5604 0 : conf: &'static PageServerConf,
5605 0 : initdb_target_dir: &Utf8Path,
5606 0 : pg_version: u32,
5607 0 : cancel: &CancellationToken,
5608 0 : ) -> Result<(), InitdbError> {
5609 0 : let initdb_bin_path = conf
5610 0 : .pg_bin_dir(pg_version)
5611 0 : .map_err(InitdbError::Other)?
5612 0 : .join("initdb");
5613 0 : let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
5614 0 : info!(
5615 0 : "running {} in {}, libdir: {}",
5616 : initdb_bin_path, initdb_target_dir, initdb_lib_dir,
5617 : );
5618 :
5619 0 : let _permit = {
5620 0 : let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
5621 0 : INIT_DB_SEMAPHORE.acquire().await
5622 : };
5623 :
5624 0 : CONCURRENT_INITDBS.inc();
5625 0 : scopeguard::defer! {
5626 0 : CONCURRENT_INITDBS.dec();
5627 0 : }
5628 0 :
5629 0 : let _timer = INITDB_RUN_TIME.start_timer();
5630 0 : let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
5631 0 : superuser: &conf.superuser,
5632 0 : locale: &conf.locale,
5633 0 : initdb_bin: &initdb_bin_path,
5634 0 : pg_version,
5635 0 : library_search_path: &initdb_lib_dir,
5636 0 : pgdata: initdb_target_dir,
5637 0 : })
5638 0 : .await
5639 0 : .map_err(InitdbError::Inner);
5640 0 :
5641 0 : // This isn't true cancellation support, see above. Still return an error to
5642 0 : // excercise the cancellation code path.
5643 0 : if cancel.is_cancelled() {
5644 0 : return Err(InitdbError::Cancelled);
5645 0 : }
5646 0 :
5647 0 : res
5648 0 : }
5649 :
5650 : /// Dump contents of a layer file to stdout.
5651 0 : pub async fn dump_layerfile_from_path(
5652 0 : path: &Utf8Path,
5653 0 : verbose: bool,
5654 0 : ctx: &RequestContext,
5655 0 : ) -> anyhow::Result<()> {
5656 : use std::os::unix::fs::FileExt;
5657 :
5658 : // All layer files start with a two-byte "magic" value, to identify the kind of
5659 : // file.
5660 0 : let file = File::open(path)?;
5661 0 : let mut header_buf = [0u8; 2];
5662 0 : file.read_exact_at(&mut header_buf, 0)?;
5663 :
5664 0 : match u16::from_be_bytes(header_buf) {
5665 : crate::IMAGE_FILE_MAGIC => {
5666 0 : ImageLayer::new_for_path(path, file)?
5667 0 : .dump(verbose, ctx)
5668 0 : .await?
5669 : }
5670 : crate::DELTA_FILE_MAGIC => {
5671 0 : DeltaLayer::new_for_path(path, file)?
5672 0 : .dump(verbose, ctx)
5673 0 : .await?
5674 : }
5675 0 : magic => bail!("unrecognized magic identifier: {:?}", magic),
5676 : }
5677 :
5678 0 : Ok(())
5679 0 : }
5680 :
5681 : #[cfg(test)]
5682 : pub(crate) mod harness {
5683 : use bytes::{Bytes, BytesMut};
5684 : use hex_literal::hex;
5685 : use once_cell::sync::OnceCell;
5686 : use pageserver_api::key::Key;
5687 : use pageserver_api::models::ShardParameters;
5688 : use pageserver_api::record::NeonWalRecord;
5689 : use pageserver_api::shard::ShardIndex;
5690 : use utils::id::TenantId;
5691 : use utils::logging;
5692 :
5693 : use super::*;
5694 : use crate::deletion_queue::mock::MockDeletionQueue;
5695 : use crate::l0_flush::L0FlushConfig;
5696 : use crate::walredo::apply_neon;
5697 :
5698 : pub const TIMELINE_ID: TimelineId =
5699 : TimelineId::from_array(hex!("11223344556677881122334455667788"));
5700 : pub const NEW_TIMELINE_ID: TimelineId =
5701 : TimelineId::from_array(hex!("AA223344556677881122334455667788"));
5702 :
5703 : /// Convenience function to create a page image with given string as the only content
5704 10057659 : pub fn test_img(s: &str) -> Bytes {
5705 10057659 : let mut buf = BytesMut::new();
5706 10057659 : buf.extend_from_slice(s.as_bytes());
5707 10057659 : buf.resize(64, 0);
5708 10057659 :
5709 10057659 : buf.freeze()
5710 10057659 : }
5711 :
5712 : pub struct TenantHarness {
5713 : pub conf: &'static PageServerConf,
5714 : pub tenant_conf: pageserver_api::models::TenantConfig,
5715 : pub tenant_shard_id: TenantShardId,
5716 : pub generation: Generation,
5717 : pub shard: ShardIndex,
5718 : pub remote_storage: GenericRemoteStorage,
5719 : pub remote_fs_dir: Utf8PathBuf,
5720 : pub deletion_queue: MockDeletionQueue,
5721 : }
5722 :
5723 : static LOG_HANDLE: OnceCell<()> = OnceCell::new();
5724 :
5725 508 : pub(crate) fn setup_logging() {
5726 508 : LOG_HANDLE.get_or_init(|| {
5727 484 : logging::init(
5728 484 : logging::LogFormat::Test,
5729 484 : // enable it in case the tests exercise code paths that use
5730 484 : // debug_assert_current_span_has_tenant_and_timeline_id
5731 484 : logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
5732 484 : logging::Output::Stdout,
5733 484 : )
5734 484 : .expect("Failed to init test logging");
5735 508 : });
5736 508 : }
5737 :
5738 : impl TenantHarness {
5739 460 : pub async fn create_custom(
5740 460 : test_name: &'static str,
5741 460 : tenant_conf: pageserver_api::models::TenantConfig,
5742 460 : tenant_id: TenantId,
5743 460 : shard_identity: ShardIdentity,
5744 460 : generation: Generation,
5745 460 : ) -> anyhow::Result<Self> {
5746 460 : setup_logging();
5747 460 :
5748 460 : let repo_dir = PageServerConf::test_repo_dir(test_name);
5749 460 : let _ = fs::remove_dir_all(&repo_dir);
5750 460 : fs::create_dir_all(&repo_dir)?;
5751 :
5752 460 : let conf = PageServerConf::dummy_conf(repo_dir);
5753 460 : // Make a static copy of the config. This can never be free'd, but that's
5754 460 : // OK in a test.
5755 460 : let conf: &'static PageServerConf = Box::leak(Box::new(conf));
5756 460 :
5757 460 : let shard = shard_identity.shard_index();
5758 460 : let tenant_shard_id = TenantShardId {
5759 460 : tenant_id,
5760 460 : shard_number: shard.shard_number,
5761 460 : shard_count: shard.shard_count,
5762 460 : };
5763 460 : fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
5764 460 : fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
5765 :
5766 : use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
5767 460 : let remote_fs_dir = conf.workdir.join("localfs");
5768 460 : std::fs::create_dir_all(&remote_fs_dir).unwrap();
5769 460 : let config = RemoteStorageConfig {
5770 460 : storage: RemoteStorageKind::LocalFs {
5771 460 : local_path: remote_fs_dir.clone(),
5772 460 : },
5773 460 : timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
5774 460 : small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
5775 460 : };
5776 460 : let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
5777 460 : let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
5778 460 :
5779 460 : Ok(Self {
5780 460 : conf,
5781 460 : tenant_conf,
5782 460 : tenant_shard_id,
5783 460 : generation,
5784 460 : shard,
5785 460 : remote_storage,
5786 460 : remote_fs_dir,
5787 460 : deletion_queue,
5788 460 : })
5789 460 : }
5790 :
5791 432 : pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
5792 432 : // Disable automatic GC and compaction to make the unit tests more deterministic.
5793 432 : // The tests perform them manually if needed.
5794 432 : let tenant_conf = pageserver_api::models::TenantConfig {
5795 432 : gc_period: Some(Duration::ZERO),
5796 432 : compaction_period: Some(Duration::ZERO),
5797 432 : ..Default::default()
5798 432 : };
5799 432 : let tenant_id = TenantId::generate();
5800 432 : let shard = ShardIdentity::unsharded();
5801 432 : Self::create_custom(
5802 432 : test_name,
5803 432 : tenant_conf,
5804 432 : tenant_id,
5805 432 : shard,
5806 432 : Generation::new(0xdeadbeef),
5807 432 : )
5808 432 : .await
5809 432 : }
5810 :
5811 40 : pub fn span(&self) -> tracing::Span {
5812 40 : info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
5813 40 : }
5814 :
5815 460 : pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
5816 460 : let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error)
5817 460 : .with_scope_unit_test();
5818 460 : (
5819 460 : self.do_try_load(&ctx)
5820 460 : .await
5821 460 : .expect("failed to load test tenant"),
5822 460 : ctx,
5823 460 : )
5824 460 : }
5825 :
5826 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5827 : pub(crate) async fn do_try_load(
5828 : &self,
5829 : ctx: &RequestContext,
5830 : ) -> anyhow::Result<Arc<Tenant>> {
5831 : let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
5832 :
5833 : let tenant = Arc::new(Tenant::new(
5834 : TenantState::Attaching,
5835 : self.conf,
5836 : AttachedTenantConf::try_from(LocationConf::attached_single(
5837 : self.tenant_conf.clone(),
5838 : self.generation,
5839 : &ShardParameters::default(),
5840 : ))
5841 : .unwrap(),
5842 : // This is a legacy/test code path: sharding isn't supported here.
5843 : ShardIdentity::unsharded(),
5844 : Some(walredo_mgr),
5845 : self.tenant_shard_id,
5846 : self.remote_storage.clone(),
5847 : self.deletion_queue.new_client(),
5848 : // TODO: ideally we should run all unit tests with both configs
5849 : L0FlushGlobalState::new(L0FlushConfig::default()),
5850 : ));
5851 :
5852 : let preload = tenant
5853 : .preload(&self.remote_storage, CancellationToken::new())
5854 : .await?;
5855 : tenant.attach(Some(preload), ctx).await?;
5856 :
5857 : tenant.state.send_replace(TenantState::Active);
5858 : for timeline in tenant.timelines.lock().unwrap().values() {
5859 : timeline.set_state(TimelineState::Active);
5860 : }
5861 : Ok(tenant)
5862 : }
5863 :
5864 4 : pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
5865 4 : self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
5866 4 : }
5867 : }
5868 :
5869 : // Mock WAL redo manager that doesn't do much
5870 : pub(crate) struct TestRedoManager;
5871 :
5872 : impl TestRedoManager {
5873 : /// # Cancel-Safety
5874 : ///
5875 : /// This method is cancellation-safe.
5876 1696 : pub async fn request_redo(
5877 1696 : &self,
5878 1696 : key: Key,
5879 1696 : lsn: Lsn,
5880 1696 : base_img: Option<(Lsn, Bytes)>,
5881 1696 : records: Vec<(Lsn, NeonWalRecord)>,
5882 1696 : _pg_version: u32,
5883 1696 : _redo_attempt_type: RedoAttemptType,
5884 1696 : ) -> Result<Bytes, walredo::Error> {
5885 2516 : let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
5886 1696 : if records_neon {
5887 : // For Neon wal records, we can decode without spawning postgres, so do so.
5888 1696 : let mut page = match (base_img, records.first()) {
5889 1552 : (Some((_lsn, img)), _) => {
5890 1552 : let mut page = BytesMut::new();
5891 1552 : page.extend_from_slice(&img);
5892 1552 : page
5893 : }
5894 144 : (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
5895 : _ => {
5896 0 : panic!("Neon WAL redo requires base image or will init record");
5897 : }
5898 : };
5899 :
5900 4208 : for (record_lsn, record) in records {
5901 2516 : apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
5902 : }
5903 1692 : Ok(page.freeze())
5904 : } else {
5905 : // We never spawn a postgres walredo process in unit tests: just log what we might have done.
5906 0 : let s = format!(
5907 0 : "redo for {} to get to {}, with {} and {} records",
5908 0 : key,
5909 0 : lsn,
5910 0 : if base_img.is_some() {
5911 0 : "base image"
5912 : } else {
5913 0 : "no base image"
5914 : },
5915 0 : records.len()
5916 0 : );
5917 0 : println!("{s}");
5918 0 :
5919 0 : Ok(test_img(&s))
5920 : }
5921 1696 : }
5922 : }
5923 : }
5924 :
5925 : #[cfg(test)]
5926 : mod tests {
5927 : use std::collections::{BTreeMap, BTreeSet};
5928 :
5929 : use bytes::{Bytes, BytesMut};
5930 : use hex_literal::hex;
5931 : use itertools::Itertools;
5932 : #[cfg(feature = "testing")]
5933 : use models::CompactLsnRange;
5934 : use pageserver_api::key::{AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX};
5935 : use pageserver_api::keyspace::KeySpace;
5936 : use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
5937 : #[cfg(feature = "testing")]
5938 : use pageserver_api::record::NeonWalRecord;
5939 : use pageserver_api::value::Value;
5940 : use pageserver_compaction::helpers::overlaps_with;
5941 : use rand::{Rng, thread_rng};
5942 : use storage_layer::{IoConcurrency, PersistentLayerKey};
5943 : use tests::storage_layer::ValuesReconstructState;
5944 : use tests::timeline::{GetVectoredError, ShutdownMode};
5945 : #[cfg(feature = "testing")]
5946 : use timeline::GcInfo;
5947 : #[cfg(feature = "testing")]
5948 : use timeline::InMemoryLayerTestDesc;
5949 : #[cfg(feature = "testing")]
5950 : use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
5951 : use timeline::{CompactOptions, DeltaLayerTestDesc};
5952 : use utils::id::TenantId;
5953 :
5954 : use super::*;
5955 : use crate::DEFAULT_PG_VERSION;
5956 : use crate::keyspace::KeySpaceAccum;
5957 : use crate::tenant::harness::*;
5958 : use crate::tenant::timeline::CompactFlags;
5959 :
5960 : static TEST_KEY: Lazy<Key> =
5961 36 : Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
5962 :
5963 : #[tokio::test]
5964 4 : async fn test_basic() -> anyhow::Result<()> {
5965 4 : let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
5966 4 : let tline = tenant
5967 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
5968 4 : .await?;
5969 4 :
5970 4 : let mut writer = tline.writer().await;
5971 4 : writer
5972 4 : .put(
5973 4 : *TEST_KEY,
5974 4 : Lsn(0x10),
5975 4 : &Value::Image(test_img("foo at 0x10")),
5976 4 : &ctx,
5977 4 : )
5978 4 : .await?;
5979 4 : writer.finish_write(Lsn(0x10));
5980 4 : drop(writer);
5981 4 :
5982 4 : let mut writer = tline.writer().await;
5983 4 : writer
5984 4 : .put(
5985 4 : *TEST_KEY,
5986 4 : Lsn(0x20),
5987 4 : &Value::Image(test_img("foo at 0x20")),
5988 4 : &ctx,
5989 4 : )
5990 4 : .await?;
5991 4 : writer.finish_write(Lsn(0x20));
5992 4 : drop(writer);
5993 4 :
5994 4 : assert_eq!(
5995 4 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
5996 4 : test_img("foo at 0x10")
5997 4 : );
5998 4 : assert_eq!(
5999 4 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
6000 4 : test_img("foo at 0x10")
6001 4 : );
6002 4 : assert_eq!(
6003 4 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
6004 4 : test_img("foo at 0x20")
6005 4 : );
6006 4 :
6007 4 : Ok(())
6008 4 : }
6009 :
6010 : #[tokio::test]
6011 4 : async fn no_duplicate_timelines() -> anyhow::Result<()> {
6012 4 : let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
6013 4 : .await?
6014 4 : .load()
6015 4 : .await;
6016 4 : let _ = tenant
6017 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6018 4 : .await?;
6019 4 :
6020 4 : match tenant
6021 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6022 4 : .await
6023 4 : {
6024 4 : Ok(_) => panic!("duplicate timeline creation should fail"),
6025 4 : Err(e) => assert_eq!(
6026 4 : e.to_string(),
6027 4 : "timeline already exists with different parameters".to_string()
6028 4 : ),
6029 4 : }
6030 4 :
6031 4 : Ok(())
6032 4 : }
6033 :
6034 : /// Convenience function to create a page image with given string as the only content
6035 20 : pub fn test_value(s: &str) -> Value {
6036 20 : let mut buf = BytesMut::new();
6037 20 : buf.extend_from_slice(s.as_bytes());
6038 20 : Value::Image(buf.freeze())
6039 20 : }
6040 :
6041 : ///
6042 : /// Test branch creation
6043 : ///
6044 : #[tokio::test]
6045 4 : async fn test_branch() -> anyhow::Result<()> {
6046 4 : use std::str::from_utf8;
6047 4 :
6048 4 : let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
6049 4 : let tline = tenant
6050 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6051 4 : .await?;
6052 4 : let mut writer = tline.writer().await;
6053 4 :
6054 4 : #[allow(non_snake_case)]
6055 4 : let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
6056 4 : #[allow(non_snake_case)]
6057 4 : let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
6058 4 :
6059 4 : // Insert a value on the timeline
6060 4 : writer
6061 4 : .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
6062 4 : .await?;
6063 4 : writer
6064 4 : .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
6065 4 : .await?;
6066 4 : writer.finish_write(Lsn(0x20));
6067 4 :
6068 4 : writer
6069 4 : .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
6070 4 : .await?;
6071 4 : writer.finish_write(Lsn(0x30));
6072 4 : writer
6073 4 : .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
6074 4 : .await?;
6075 4 : writer.finish_write(Lsn(0x40));
6076 4 :
6077 4 : //assert_current_logical_size(&tline, Lsn(0x40));
6078 4 :
6079 4 : // Branch the history, modify relation differently on the new timeline
6080 4 : tenant
6081 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
6082 4 : .await?;
6083 4 : let newtline = tenant
6084 4 : .get_timeline(NEW_TIMELINE_ID, true)
6085 4 : .expect("Should have a local timeline");
6086 4 : let mut new_writer = newtline.writer().await;
6087 4 : new_writer
6088 4 : .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
6089 4 : .await?;
6090 4 : new_writer.finish_write(Lsn(0x40));
6091 4 :
6092 4 : // Check page contents on both branches
6093 4 : assert_eq!(
6094 4 : from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
6095 4 : "foo at 0x40"
6096 4 : );
6097 4 : assert_eq!(
6098 4 : from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
6099 4 : "bar at 0x40"
6100 4 : );
6101 4 : assert_eq!(
6102 4 : from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
6103 4 : "foobar at 0x20"
6104 4 : );
6105 4 :
6106 4 : //assert_current_logical_size(&tline, Lsn(0x40));
6107 4 :
6108 4 : Ok(())
6109 4 : }
6110 :
6111 40 : async fn make_some_layers(
6112 40 : tline: &Timeline,
6113 40 : start_lsn: Lsn,
6114 40 : ctx: &RequestContext,
6115 40 : ) -> anyhow::Result<()> {
6116 40 : let mut lsn = start_lsn;
6117 : {
6118 40 : let mut writer = tline.writer().await;
6119 : // Create a relation on the timeline
6120 40 : writer
6121 40 : .put(
6122 40 : *TEST_KEY,
6123 40 : lsn,
6124 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6125 40 : ctx,
6126 40 : )
6127 40 : .await?;
6128 40 : writer.finish_write(lsn);
6129 40 : lsn += 0x10;
6130 40 : writer
6131 40 : .put(
6132 40 : *TEST_KEY,
6133 40 : lsn,
6134 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6135 40 : ctx,
6136 40 : )
6137 40 : .await?;
6138 40 : writer.finish_write(lsn);
6139 40 : lsn += 0x10;
6140 40 : }
6141 40 : tline.freeze_and_flush().await?;
6142 : {
6143 40 : let mut writer = tline.writer().await;
6144 40 : writer
6145 40 : .put(
6146 40 : *TEST_KEY,
6147 40 : lsn,
6148 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6149 40 : ctx,
6150 40 : )
6151 40 : .await?;
6152 40 : writer.finish_write(lsn);
6153 40 : lsn += 0x10;
6154 40 : writer
6155 40 : .put(
6156 40 : *TEST_KEY,
6157 40 : lsn,
6158 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6159 40 : ctx,
6160 40 : )
6161 40 : .await?;
6162 40 : writer.finish_write(lsn);
6163 40 : }
6164 40 : tline.freeze_and_flush().await.map_err(|e| e.into())
6165 40 : }
6166 :
6167 : #[tokio::test(start_paused = true)]
6168 4 : async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
6169 4 : let (tenant, ctx) =
6170 4 : TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
6171 4 : .await?
6172 4 : .load()
6173 4 : .await;
6174 4 : // Advance to the lsn lease deadline so that GC is not blocked by
6175 4 : // initial transition into AttachedSingle.
6176 4 : tokio::time::advance(tenant.get_lsn_lease_length()).await;
6177 4 : tokio::time::resume();
6178 4 : let tline = tenant
6179 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6180 4 : .await?;
6181 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6182 4 :
6183 4 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
6184 4 : // FIXME: this doesn't actually remove any layer currently, given how the flushing
6185 4 : // and compaction works. But it does set the 'cutoff' point so that the cross check
6186 4 : // below should fail.
6187 4 : tenant
6188 4 : .gc_iteration(
6189 4 : Some(TIMELINE_ID),
6190 4 : 0x10,
6191 4 : Duration::ZERO,
6192 4 : &CancellationToken::new(),
6193 4 : &ctx,
6194 4 : )
6195 4 : .await?;
6196 4 :
6197 4 : // try to branch at lsn 25, should fail because we already garbage collected the data
6198 4 : match tenant
6199 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
6200 4 : .await
6201 4 : {
6202 4 : Ok(_) => panic!("branching should have failed"),
6203 4 : Err(err) => {
6204 4 : let CreateTimelineError::AncestorLsn(err) = err else {
6205 4 : panic!("wrong error type")
6206 4 : };
6207 4 : assert!(err.to_string().contains("invalid branch start lsn"));
6208 4 : assert!(
6209 4 : err.source()
6210 4 : .unwrap()
6211 4 : .to_string()
6212 4 : .contains("we might've already garbage collected needed data")
6213 4 : )
6214 4 : }
6215 4 : }
6216 4 :
6217 4 : Ok(())
6218 4 : }
6219 :
6220 : #[tokio::test]
6221 4 : async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
6222 4 : let (tenant, ctx) =
6223 4 : TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
6224 4 : .await?
6225 4 : .load()
6226 4 : .await;
6227 4 :
6228 4 : let tline = tenant
6229 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
6230 4 : .await?;
6231 4 : // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
6232 4 : match tenant
6233 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
6234 4 : .await
6235 4 : {
6236 4 : Ok(_) => panic!("branching should have failed"),
6237 4 : Err(err) => {
6238 4 : let CreateTimelineError::AncestorLsn(err) = err else {
6239 4 : panic!("wrong error type");
6240 4 : };
6241 4 : assert!(&err.to_string().contains("invalid branch start lsn"));
6242 4 : assert!(
6243 4 : &err.source()
6244 4 : .unwrap()
6245 4 : .to_string()
6246 4 : .contains("is earlier than latest GC cutoff")
6247 4 : );
6248 4 : }
6249 4 : }
6250 4 :
6251 4 : Ok(())
6252 4 : }
6253 :
6254 : /*
6255 : // FIXME: This currently fails to error out. Calling GC doesn't currently
6256 : // remove the old value, we'd need to work a little harder
6257 : #[tokio::test]
6258 : async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
6259 : let repo =
6260 : RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
6261 : .load();
6262 :
6263 : let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
6264 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6265 :
6266 : repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
6267 : let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
6268 : assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
6269 : match tline.get(*TEST_KEY, Lsn(0x25)) {
6270 : Ok(_) => panic!("request for page should have failed"),
6271 : Err(err) => assert!(err.to_string().contains("not found at")),
6272 : }
6273 : Ok(())
6274 : }
6275 : */
6276 :
6277 : #[tokio::test]
6278 4 : async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
6279 4 : let (tenant, ctx) =
6280 4 : TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
6281 4 : .await?
6282 4 : .load()
6283 4 : .await;
6284 4 : let tline = tenant
6285 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6286 4 : .await?;
6287 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6288 4 :
6289 4 : tenant
6290 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6291 4 : .await?;
6292 4 : let newtline = tenant
6293 4 : .get_timeline(NEW_TIMELINE_ID, true)
6294 4 : .expect("Should have a local timeline");
6295 4 :
6296 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6297 4 :
6298 4 : tline.set_broken("test".to_owned());
6299 4 :
6300 4 : tenant
6301 4 : .gc_iteration(
6302 4 : Some(TIMELINE_ID),
6303 4 : 0x10,
6304 4 : Duration::ZERO,
6305 4 : &CancellationToken::new(),
6306 4 : &ctx,
6307 4 : )
6308 4 : .await?;
6309 4 :
6310 4 : // The branchpoints should contain all timelines, even ones marked
6311 4 : // as Broken.
6312 4 : {
6313 4 : let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
6314 4 : assert_eq!(branchpoints.len(), 1);
6315 4 : assert_eq!(
6316 4 : branchpoints[0],
6317 4 : (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
6318 4 : );
6319 4 : }
6320 4 :
6321 4 : // You can read the key from the child branch even though the parent is
6322 4 : // Broken, as long as you don't need to access data from the parent.
6323 4 : assert_eq!(
6324 4 : newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
6325 4 : test_img(&format!("foo at {}", Lsn(0x70)))
6326 4 : );
6327 4 :
6328 4 : // This needs to traverse to the parent, and fails.
6329 4 : let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
6330 4 : assert!(
6331 4 : err.to_string().starts_with(&format!(
6332 4 : "bad state on timeline {}: Broken",
6333 4 : tline.timeline_id
6334 4 : )),
6335 4 : "{err}"
6336 4 : );
6337 4 :
6338 4 : Ok(())
6339 4 : }
6340 :
6341 : #[tokio::test]
6342 4 : async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
6343 4 : let (tenant, ctx) =
6344 4 : TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
6345 4 : .await?
6346 4 : .load()
6347 4 : .await;
6348 4 : let tline = tenant
6349 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6350 4 : .await?;
6351 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6352 4 :
6353 4 : tenant
6354 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6355 4 : .await?;
6356 4 : let newtline = tenant
6357 4 : .get_timeline(NEW_TIMELINE_ID, true)
6358 4 : .expect("Should have a local timeline");
6359 4 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
6360 4 : tenant
6361 4 : .gc_iteration(
6362 4 : Some(TIMELINE_ID),
6363 4 : 0x10,
6364 4 : Duration::ZERO,
6365 4 : &CancellationToken::new(),
6366 4 : &ctx,
6367 4 : )
6368 4 : .await?;
6369 4 : assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
6370 4 :
6371 4 : Ok(())
6372 4 : }
6373 : #[tokio::test]
6374 4 : async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
6375 4 : let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
6376 4 : .await?
6377 4 : .load()
6378 4 : .await;
6379 4 : let tline = tenant
6380 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6381 4 : .await?;
6382 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6383 4 :
6384 4 : tenant
6385 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6386 4 : .await?;
6387 4 : let newtline = tenant
6388 4 : .get_timeline(NEW_TIMELINE_ID, true)
6389 4 : .expect("Should have a local timeline");
6390 4 :
6391 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6392 4 :
6393 4 : // run gc on parent
6394 4 : tenant
6395 4 : .gc_iteration(
6396 4 : Some(TIMELINE_ID),
6397 4 : 0x10,
6398 4 : Duration::ZERO,
6399 4 : &CancellationToken::new(),
6400 4 : &ctx,
6401 4 : )
6402 4 : .await?;
6403 4 :
6404 4 : // Check that the data is still accessible on the branch.
6405 4 : assert_eq!(
6406 4 : newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
6407 4 : test_img(&format!("foo at {}", Lsn(0x40)))
6408 4 : );
6409 4 :
6410 4 : Ok(())
6411 4 : }
6412 :
6413 : #[tokio::test]
6414 4 : async fn timeline_load() -> anyhow::Result<()> {
6415 4 : const TEST_NAME: &str = "timeline_load";
6416 4 : let harness = TenantHarness::create(TEST_NAME).await?;
6417 4 : {
6418 4 : let (tenant, ctx) = harness.load().await;
6419 4 : let tline = tenant
6420 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
6421 4 : .await?;
6422 4 : make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
6423 4 : // so that all uploads finish & we can call harness.load() below again
6424 4 : tenant
6425 4 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
6426 4 : .instrument(harness.span())
6427 4 : .await
6428 4 : .ok()
6429 4 : .unwrap();
6430 4 : }
6431 4 :
6432 4 : let (tenant, _ctx) = harness.load().await;
6433 4 : tenant
6434 4 : .get_timeline(TIMELINE_ID, true)
6435 4 : .expect("cannot load timeline");
6436 4 :
6437 4 : Ok(())
6438 4 : }
6439 :
6440 : #[tokio::test]
6441 4 : async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
6442 4 : const TEST_NAME: &str = "timeline_load_with_ancestor";
6443 4 : let harness = TenantHarness::create(TEST_NAME).await?;
6444 4 : // create two timelines
6445 4 : {
6446 4 : let (tenant, ctx) = harness.load().await;
6447 4 : let tline = tenant
6448 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6449 4 : .await?;
6450 4 :
6451 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6452 4 :
6453 4 : let child_tline = tenant
6454 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6455 4 : .await?;
6456 4 : child_tline.set_state(TimelineState::Active);
6457 4 :
6458 4 : let newtline = tenant
6459 4 : .get_timeline(NEW_TIMELINE_ID, true)
6460 4 : .expect("Should have a local timeline");
6461 4 :
6462 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6463 4 :
6464 4 : // so that all uploads finish & we can call harness.load() below again
6465 4 : tenant
6466 4 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
6467 4 : .instrument(harness.span())
6468 4 : .await
6469 4 : .ok()
6470 4 : .unwrap();
6471 4 : }
6472 4 :
6473 4 : // check that both of them are initially unloaded
6474 4 : let (tenant, _ctx) = harness.load().await;
6475 4 :
6476 4 : // check that both, child and ancestor are loaded
6477 4 : let _child_tline = tenant
6478 4 : .get_timeline(NEW_TIMELINE_ID, true)
6479 4 : .expect("cannot get child timeline loaded");
6480 4 :
6481 4 : let _ancestor_tline = tenant
6482 4 : .get_timeline(TIMELINE_ID, true)
6483 4 : .expect("cannot get ancestor timeline loaded");
6484 4 :
6485 4 : Ok(())
6486 4 : }
6487 :
6488 : #[tokio::test]
6489 4 : async fn delta_layer_dumping() -> anyhow::Result<()> {
6490 4 : use storage_layer::AsLayerDesc;
6491 4 : let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
6492 4 : .await?
6493 4 : .load()
6494 4 : .await;
6495 4 : let tline = tenant
6496 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6497 4 : .await?;
6498 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6499 4 :
6500 4 : let layer_map = tline.layers.read().await;
6501 4 : let level0_deltas = layer_map
6502 4 : .layer_map()?
6503 4 : .level0_deltas()
6504 4 : .iter()
6505 8 : .map(|desc| layer_map.get_from_desc(desc))
6506 4 : .collect::<Vec<_>>();
6507 4 :
6508 4 : assert!(!level0_deltas.is_empty());
6509 4 :
6510 12 : for delta in level0_deltas {
6511 4 : // Ensure we are dumping a delta layer here
6512 8 : assert!(delta.layer_desc().is_delta);
6513 8 : delta.dump(true, &ctx).await.unwrap();
6514 4 : }
6515 4 :
6516 4 : Ok(())
6517 4 : }
6518 :
6519 : #[tokio::test]
6520 4 : async fn test_images() -> anyhow::Result<()> {
6521 4 : let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
6522 4 : let tline = tenant
6523 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6524 4 : .await?;
6525 4 :
6526 4 : let mut writer = tline.writer().await;
6527 4 : writer
6528 4 : .put(
6529 4 : *TEST_KEY,
6530 4 : Lsn(0x10),
6531 4 : &Value::Image(test_img("foo at 0x10")),
6532 4 : &ctx,
6533 4 : )
6534 4 : .await?;
6535 4 : writer.finish_write(Lsn(0x10));
6536 4 : drop(writer);
6537 4 :
6538 4 : tline.freeze_and_flush().await?;
6539 4 : tline
6540 4 : .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
6541 4 : .await?;
6542 4 :
6543 4 : let mut writer = tline.writer().await;
6544 4 : writer
6545 4 : .put(
6546 4 : *TEST_KEY,
6547 4 : Lsn(0x20),
6548 4 : &Value::Image(test_img("foo at 0x20")),
6549 4 : &ctx,
6550 4 : )
6551 4 : .await?;
6552 4 : writer.finish_write(Lsn(0x20));
6553 4 : drop(writer);
6554 4 :
6555 4 : tline.freeze_and_flush().await?;
6556 4 : tline
6557 4 : .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
6558 4 : .await?;
6559 4 :
6560 4 : let mut writer = tline.writer().await;
6561 4 : writer
6562 4 : .put(
6563 4 : *TEST_KEY,
6564 4 : Lsn(0x30),
6565 4 : &Value::Image(test_img("foo at 0x30")),
6566 4 : &ctx,
6567 4 : )
6568 4 : .await?;
6569 4 : writer.finish_write(Lsn(0x30));
6570 4 : drop(writer);
6571 4 :
6572 4 : tline.freeze_and_flush().await?;
6573 4 : tline
6574 4 : .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
6575 4 : .await?;
6576 4 :
6577 4 : let mut writer = tline.writer().await;
6578 4 : writer
6579 4 : .put(
6580 4 : *TEST_KEY,
6581 4 : Lsn(0x40),
6582 4 : &Value::Image(test_img("foo at 0x40")),
6583 4 : &ctx,
6584 4 : )
6585 4 : .await?;
6586 4 : writer.finish_write(Lsn(0x40));
6587 4 : drop(writer);
6588 4 :
6589 4 : tline.freeze_and_flush().await?;
6590 4 : tline
6591 4 : .compact(&CancellationToken::new(), EnumSet::default(), &ctx)
6592 4 : .await?;
6593 4 :
6594 4 : assert_eq!(
6595 4 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
6596 4 : test_img("foo at 0x10")
6597 4 : );
6598 4 : assert_eq!(
6599 4 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
6600 4 : test_img("foo at 0x10")
6601 4 : );
6602 4 : assert_eq!(
6603 4 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
6604 4 : test_img("foo at 0x20")
6605 4 : );
6606 4 : assert_eq!(
6607 4 : tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
6608 4 : test_img("foo at 0x30")
6609 4 : );
6610 4 : assert_eq!(
6611 4 : tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
6612 4 : test_img("foo at 0x40")
6613 4 : );
6614 4 :
6615 4 : Ok(())
6616 4 : }
6617 :
6618 8 : async fn bulk_insert_compact_gc(
6619 8 : tenant: &Tenant,
6620 8 : timeline: &Arc<Timeline>,
6621 8 : ctx: &RequestContext,
6622 8 : lsn: Lsn,
6623 8 : repeat: usize,
6624 8 : key_count: usize,
6625 8 : ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
6626 8 : let compact = true;
6627 8 : bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
6628 8 : }
6629 :
6630 16 : async fn bulk_insert_maybe_compact_gc(
6631 16 : tenant: &Tenant,
6632 16 : timeline: &Arc<Timeline>,
6633 16 : ctx: &RequestContext,
6634 16 : mut lsn: Lsn,
6635 16 : repeat: usize,
6636 16 : key_count: usize,
6637 16 : compact: bool,
6638 16 : ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
6639 16 : let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
6640 16 :
6641 16 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6642 16 : let mut blknum = 0;
6643 16 :
6644 16 : // Enforce that key range is monotonously increasing
6645 16 : let mut keyspace = KeySpaceAccum::new();
6646 16 :
6647 16 : let cancel = CancellationToken::new();
6648 16 :
6649 16 : for _ in 0..repeat {
6650 800 : for _ in 0..key_count {
6651 8000000 : test_key.field6 = blknum;
6652 8000000 : let mut writer = timeline.writer().await;
6653 8000000 : writer
6654 8000000 : .put(
6655 8000000 : test_key,
6656 8000000 : lsn,
6657 8000000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
6658 8000000 : ctx,
6659 8000000 : )
6660 8000000 : .await?;
6661 8000000 : inserted.entry(test_key).or_default().insert(lsn);
6662 8000000 : writer.finish_write(lsn);
6663 8000000 : drop(writer);
6664 8000000 :
6665 8000000 : keyspace.add_key(test_key);
6666 8000000 :
6667 8000000 : lsn = Lsn(lsn.0 + 0x10);
6668 8000000 : blknum += 1;
6669 : }
6670 :
6671 800 : timeline.freeze_and_flush().await?;
6672 800 : if compact {
6673 : // this requires timeline to be &Arc<Timeline>
6674 400 : timeline.compact(&cancel, EnumSet::default(), ctx).await?;
6675 400 : }
6676 :
6677 : // this doesn't really need to use the timeline_id target, but it is closer to what it
6678 : // originally was.
6679 800 : let res = tenant
6680 800 : .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
6681 800 : .await?;
6682 :
6683 800 : assert_eq!(res.layers_removed, 0, "this never removes anything");
6684 : }
6685 :
6686 16 : Ok(inserted)
6687 16 : }
6688 :
6689 : //
6690 : // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
6691 : // Repeat 50 times.
6692 : //
6693 : #[tokio::test]
6694 4 : async fn test_bulk_insert() -> anyhow::Result<()> {
6695 4 : let harness = TenantHarness::create("test_bulk_insert").await?;
6696 4 : let (tenant, ctx) = harness.load().await;
6697 4 : let tline = tenant
6698 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6699 4 : .await?;
6700 4 :
6701 4 : let lsn = Lsn(0x10);
6702 4 : bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
6703 4 :
6704 4 : Ok(())
6705 4 : }
6706 :
6707 : // Test the vectored get real implementation against a simple sequential implementation.
6708 : //
6709 : // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
6710 : // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
6711 : // grow to the right on the X axis.
6712 : // [Delta]
6713 : // [Delta]
6714 : // [Delta]
6715 : // [Delta]
6716 : // ------------ Image ---------------
6717 : //
6718 : // After layer generation we pick the ranges to query as follows:
6719 : // 1. The beginning of each delta layer
6720 : // 2. At the seam between two adjacent delta layers
6721 : //
6722 : // There's one major downside to this test: delta layers only contains images,
6723 : // so the search can stop at the first delta layer and doesn't traverse any deeper.
6724 : #[tokio::test]
6725 4 : async fn test_get_vectored() -> anyhow::Result<()> {
6726 4 : let harness = TenantHarness::create("test_get_vectored").await?;
6727 4 : let (tenant, ctx) = harness.load().await;
6728 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6729 4 : let tline = tenant
6730 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6731 4 : .await?;
6732 4 :
6733 4 : let lsn = Lsn(0x10);
6734 4 : let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
6735 4 :
6736 4 : let guard = tline.layers.read().await;
6737 4 : let lm = guard.layer_map()?;
6738 4 :
6739 4 : lm.dump(true, &ctx).await?;
6740 4 :
6741 4 : let mut reads = Vec::new();
6742 4 : let mut prev = None;
6743 24 : lm.iter_historic_layers().for_each(|desc| {
6744 24 : if !desc.is_delta() {
6745 4 : prev = Some(desc.clone());
6746 4 : return;
6747 20 : }
6748 20 :
6749 20 : let start = desc.key_range.start;
6750 20 : let end = desc
6751 20 : .key_range
6752 20 : .start
6753 20 : .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
6754 20 : reads.push(KeySpace {
6755 20 : ranges: vec![start..end],
6756 20 : });
6757 4 :
6758 20 : if let Some(prev) = &prev {
6759 20 : if !prev.is_delta() {
6760 20 : return;
6761 4 : }
6762 0 :
6763 0 : let first_range = Key {
6764 0 : field6: prev.key_range.end.field6 - 4,
6765 0 : ..prev.key_range.end
6766 0 : }..prev.key_range.end;
6767 0 :
6768 0 : let second_range = desc.key_range.start..Key {
6769 0 : field6: desc.key_range.start.field6 + 4,
6770 0 : ..desc.key_range.start
6771 0 : };
6772 0 :
6773 0 : reads.push(KeySpace {
6774 0 : ranges: vec![first_range, second_range],
6775 0 : });
6776 4 : };
6777 4 :
6778 4 : prev = Some(desc.clone());
6779 24 : });
6780 4 :
6781 4 : drop(guard);
6782 4 :
6783 4 : // Pick a big LSN such that we query over all the changes.
6784 4 : let reads_lsn = Lsn(u64::MAX - 1);
6785 4 :
6786 24 : for read in reads {
6787 20 : info!("Doing vectored read on {:?}", read);
6788 4 :
6789 20 : let vectored_res = tline
6790 20 : .get_vectored_impl(
6791 20 : read.clone(),
6792 20 : reads_lsn,
6793 20 : &mut ValuesReconstructState::new(io_concurrency.clone()),
6794 20 : &ctx,
6795 20 : )
6796 20 : .await;
6797 4 :
6798 20 : let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
6799 20 : let mut expect_missing = false;
6800 20 : let mut key = read.start().unwrap();
6801 660 : while key != read.end().unwrap() {
6802 640 : if let Some(lsns) = inserted.get(&key) {
6803 640 : let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
6804 640 : match expected_lsn {
6805 640 : Some(lsn) => {
6806 640 : expected_lsns.insert(key, *lsn);
6807 640 : }
6808 4 : None => {
6809 4 : expect_missing = true;
6810 0 : break;
6811 4 : }
6812 4 : }
6813 4 : } else {
6814 4 : expect_missing = true;
6815 0 : break;
6816 4 : }
6817 4 :
6818 640 : key = key.next();
6819 4 : }
6820 4 :
6821 20 : if expect_missing {
6822 4 : assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
6823 4 : } else {
6824 640 : for (key, image) in vectored_res? {
6825 640 : let expected_lsn = expected_lsns.get(&key).expect("determined above");
6826 640 : let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
6827 640 : assert_eq!(image?, expected_image);
6828 4 : }
6829 4 : }
6830 4 : }
6831 4 :
6832 4 : Ok(())
6833 4 : }
6834 :
6835 : #[tokio::test]
6836 4 : async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
6837 4 : let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
6838 4 :
6839 4 : let (tenant, ctx) = harness.load().await;
6840 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6841 4 : let (tline, ctx) = tenant
6842 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
6843 4 : .await?;
6844 4 : let tline = tline.raw_timeline().unwrap();
6845 4 :
6846 4 : let mut modification = tline.begin_modification(Lsn(0x1000));
6847 4 : modification.put_file("foo/bar1", b"content1", &ctx).await?;
6848 4 : modification.set_lsn(Lsn(0x1008))?;
6849 4 : modification.put_file("foo/bar2", b"content2", &ctx).await?;
6850 4 : modification.commit(&ctx).await?;
6851 4 :
6852 4 : let child_timeline_id = TimelineId::generate();
6853 4 : tenant
6854 4 : .branch_timeline_test(
6855 4 : tline,
6856 4 : child_timeline_id,
6857 4 : Some(tline.get_last_record_lsn()),
6858 4 : &ctx,
6859 4 : )
6860 4 : .await?;
6861 4 :
6862 4 : let child_timeline = tenant
6863 4 : .get_timeline(child_timeline_id, true)
6864 4 : .expect("Should have the branched timeline");
6865 4 :
6866 4 : let aux_keyspace = KeySpace {
6867 4 : ranges: vec![NON_INHERITED_RANGE],
6868 4 : };
6869 4 : let read_lsn = child_timeline.get_last_record_lsn();
6870 4 :
6871 4 : let vectored_res = child_timeline
6872 4 : .get_vectored_impl(
6873 4 : aux_keyspace.clone(),
6874 4 : read_lsn,
6875 4 : &mut ValuesReconstructState::new(io_concurrency.clone()),
6876 4 : &ctx,
6877 4 : )
6878 4 : .await;
6879 4 :
6880 4 : let images = vectored_res?;
6881 4 : assert!(images.is_empty());
6882 4 : Ok(())
6883 4 : }
6884 :
6885 : // Test that vectored get handles layer gaps correctly
6886 : // by advancing into the next ancestor timeline if required.
6887 : //
6888 : // The test generates timelines that look like the diagram below.
6889 : // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
6890 : // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
6891 : //
6892 : // ```
6893 : //-------------------------------+
6894 : // ... |
6895 : // [ L1 ] |
6896 : // [ / L1 ] | Child Timeline
6897 : // ... |
6898 : // ------------------------------+
6899 : // [ X L1 ] | Parent Timeline
6900 : // ------------------------------+
6901 : // ```
6902 : #[tokio::test]
6903 4 : async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
6904 4 : let tenant_conf = pageserver_api::models::TenantConfig {
6905 4 : // Make compaction deterministic
6906 4 : gc_period: Some(Duration::ZERO),
6907 4 : compaction_period: Some(Duration::ZERO),
6908 4 : // Encourage creation of L1 layers
6909 4 : checkpoint_distance: Some(16 * 1024),
6910 4 : compaction_target_size: Some(8 * 1024),
6911 4 : ..Default::default()
6912 4 : };
6913 4 :
6914 4 : let harness = TenantHarness::create_custom(
6915 4 : "test_get_vectored_key_gap",
6916 4 : tenant_conf,
6917 4 : TenantId::generate(),
6918 4 : ShardIdentity::unsharded(),
6919 4 : Generation::new(0xdeadbeef),
6920 4 : )
6921 4 : .await?;
6922 4 : let (tenant, ctx) = harness.load().await;
6923 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6924 4 :
6925 4 : let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6926 4 : let gap_at_key = current_key.add(100);
6927 4 : let mut current_lsn = Lsn(0x10);
6928 4 :
6929 4 : const KEY_COUNT: usize = 10_000;
6930 4 :
6931 4 : let timeline_id = TimelineId::generate();
6932 4 : let current_timeline = tenant
6933 4 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
6934 4 : .await?;
6935 4 :
6936 4 : current_lsn += 0x100;
6937 4 :
6938 4 : let mut writer = current_timeline.writer().await;
6939 4 : writer
6940 4 : .put(
6941 4 : gap_at_key,
6942 4 : current_lsn,
6943 4 : &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
6944 4 : &ctx,
6945 4 : )
6946 4 : .await?;
6947 4 : writer.finish_write(current_lsn);
6948 4 : drop(writer);
6949 4 :
6950 4 : let mut latest_lsns = HashMap::new();
6951 4 : latest_lsns.insert(gap_at_key, current_lsn);
6952 4 :
6953 4 : current_timeline.freeze_and_flush().await?;
6954 4 :
6955 4 : let child_timeline_id = TimelineId::generate();
6956 4 :
6957 4 : tenant
6958 4 : .branch_timeline_test(
6959 4 : ¤t_timeline,
6960 4 : child_timeline_id,
6961 4 : Some(current_lsn),
6962 4 : &ctx,
6963 4 : )
6964 4 : .await?;
6965 4 : let child_timeline = tenant
6966 4 : .get_timeline(child_timeline_id, true)
6967 4 : .expect("Should have the branched timeline");
6968 4 :
6969 40004 : for i in 0..KEY_COUNT {
6970 40000 : if current_key == gap_at_key {
6971 4 : current_key = current_key.next();
6972 4 : continue;
6973 39996 : }
6974 39996 :
6975 39996 : current_lsn += 0x10;
6976 4 :
6977 39996 : let mut writer = child_timeline.writer().await;
6978 39996 : writer
6979 39996 : .put(
6980 39996 : current_key,
6981 39996 : current_lsn,
6982 39996 : &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
6983 39996 : &ctx,
6984 39996 : )
6985 39996 : .await?;
6986 39996 : writer.finish_write(current_lsn);
6987 39996 : drop(writer);
6988 39996 :
6989 39996 : latest_lsns.insert(current_key, current_lsn);
6990 39996 : current_key = current_key.next();
6991 39996 :
6992 39996 : // Flush every now and then to encourage layer file creation.
6993 39996 : if i % 500 == 0 {
6994 80 : child_timeline.freeze_and_flush().await?;
6995 39916 : }
6996 4 : }
6997 4 :
6998 4 : child_timeline.freeze_and_flush().await?;
6999 4 : let mut flags = EnumSet::new();
7000 4 : flags.insert(CompactFlags::ForceRepartition);
7001 4 : child_timeline
7002 4 : .compact(&CancellationToken::new(), flags, &ctx)
7003 4 : .await?;
7004 4 :
7005 4 : let key_near_end = {
7006 4 : let mut tmp = current_key;
7007 4 : tmp.field6 -= 10;
7008 4 : tmp
7009 4 : };
7010 4 :
7011 4 : let key_near_gap = {
7012 4 : let mut tmp = gap_at_key;
7013 4 : tmp.field6 -= 10;
7014 4 : tmp
7015 4 : };
7016 4 :
7017 4 : let read = KeySpace {
7018 4 : ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
7019 4 : };
7020 4 : let results = child_timeline
7021 4 : .get_vectored_impl(
7022 4 : read.clone(),
7023 4 : current_lsn,
7024 4 : &mut ValuesReconstructState::new(io_concurrency.clone()),
7025 4 : &ctx,
7026 4 : )
7027 4 : .await?;
7028 4 :
7029 88 : for (key, img_res) in results {
7030 84 : let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
7031 84 : assert_eq!(img_res?, expected);
7032 4 : }
7033 4 :
7034 4 : Ok(())
7035 4 : }
7036 :
7037 : // Test that vectored get descends into ancestor timelines correctly and
7038 : // does not return an image that's newer than requested.
7039 : //
7040 : // The diagram below ilustrates an interesting case. We have a parent timeline
7041 : // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
7042 : // from the child timeline, so the parent timeline must be visited. When advacing into
7043 : // the child timeline, the read path needs to remember what the requested Lsn was in
7044 : // order to avoid returning an image that's too new. The test below constructs such
7045 : // a timeline setup and does a few queries around the Lsn of each page image.
7046 : // ```
7047 : // LSN
7048 : // ^
7049 : // |
7050 : // |
7051 : // 500 | --------------------------------------> branch point
7052 : // 400 | X
7053 : // 300 | X
7054 : // 200 | --------------------------------------> requested lsn
7055 : // 100 | X
7056 : // |---------------------------------------> Key
7057 : // |
7058 : // ------> requested key
7059 : //
7060 : // Legend:
7061 : // * X - page images
7062 : // ```
7063 : #[tokio::test]
7064 4 : async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
7065 4 : let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
7066 4 : let (tenant, ctx) = harness.load().await;
7067 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7068 4 :
7069 4 : let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7070 4 : let end_key = start_key.add(1000);
7071 4 : let child_gap_at_key = start_key.add(500);
7072 4 : let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
7073 4 :
7074 4 : let mut current_lsn = Lsn(0x10);
7075 4 :
7076 4 : let timeline_id = TimelineId::generate();
7077 4 : let parent_timeline = tenant
7078 4 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
7079 4 : .await?;
7080 4 :
7081 4 : current_lsn += 0x100;
7082 4 :
7083 16 : for _ in 0..3 {
7084 12 : let mut key = start_key;
7085 12012 : while key < end_key {
7086 12000 : current_lsn += 0x10;
7087 12000 :
7088 12000 : let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
7089 4 :
7090 12000 : let mut writer = parent_timeline.writer().await;
7091 12000 : writer
7092 12000 : .put(
7093 12000 : key,
7094 12000 : current_lsn,
7095 12000 : &Value::Image(test_img(&image_value)),
7096 12000 : &ctx,
7097 12000 : )
7098 12000 : .await?;
7099 12000 : writer.finish_write(current_lsn);
7100 12000 :
7101 12000 : if key == child_gap_at_key {
7102 12 : parent_gap_lsns.insert(current_lsn, image_value);
7103 11988 : }
7104 4 :
7105 12000 : key = key.next();
7106 4 : }
7107 4 :
7108 12 : parent_timeline.freeze_and_flush().await?;
7109 4 : }
7110 4 :
7111 4 : let child_timeline_id = TimelineId::generate();
7112 4 :
7113 4 : let child_timeline = tenant
7114 4 : .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
7115 4 : .await?;
7116 4 :
7117 4 : let mut key = start_key;
7118 4004 : while key < end_key {
7119 4000 : if key == child_gap_at_key {
7120 4 : key = key.next();
7121 4 : continue;
7122 3996 : }
7123 3996 :
7124 3996 : current_lsn += 0x10;
7125 4 :
7126 3996 : let mut writer = child_timeline.writer().await;
7127 3996 : writer
7128 3996 : .put(
7129 3996 : key,
7130 3996 : current_lsn,
7131 3996 : &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
7132 3996 : &ctx,
7133 3996 : )
7134 3996 : .await?;
7135 3996 : writer.finish_write(current_lsn);
7136 3996 :
7137 3996 : key = key.next();
7138 4 : }
7139 4 :
7140 4 : child_timeline.freeze_and_flush().await?;
7141 4 :
7142 4 : let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
7143 4 : let mut query_lsns = Vec::new();
7144 12 : for image_lsn in parent_gap_lsns.keys().rev() {
7145 72 : for offset in lsn_offsets {
7146 60 : query_lsns.push(Lsn(image_lsn
7147 60 : .0
7148 60 : .checked_add_signed(offset)
7149 60 : .expect("Shouldn't overflow")));
7150 60 : }
7151 4 : }
7152 4 :
7153 64 : for query_lsn in query_lsns {
7154 60 : let results = child_timeline
7155 60 : .get_vectored_impl(
7156 60 : KeySpace {
7157 60 : ranges: vec![child_gap_at_key..child_gap_at_key.next()],
7158 60 : },
7159 60 : query_lsn,
7160 60 : &mut ValuesReconstructState::new(io_concurrency.clone()),
7161 60 : &ctx,
7162 60 : )
7163 60 : .await;
7164 4 :
7165 60 : let expected_item = parent_gap_lsns
7166 60 : .iter()
7167 60 : .rev()
7168 136 : .find(|(lsn, _)| **lsn <= query_lsn);
7169 60 :
7170 60 : info!(
7171 4 : "Doing vectored read at LSN {}. Expecting image to be: {:?}",
7172 4 : query_lsn, expected_item
7173 4 : );
7174 4 :
7175 60 : match expected_item {
7176 52 : Some((_, img_value)) => {
7177 52 : let key_results = results.expect("No vectored get error expected");
7178 52 : let key_result = &key_results[&child_gap_at_key];
7179 52 : let returned_img = key_result
7180 52 : .as_ref()
7181 52 : .expect("No page reconstruct error expected");
7182 52 :
7183 52 : info!(
7184 4 : "Vectored read at LSN {} returned image {}",
7185 0 : query_lsn,
7186 0 : std::str::from_utf8(returned_img)?
7187 4 : );
7188 52 : assert_eq!(*returned_img, test_img(img_value));
7189 4 : }
7190 4 : None => {
7191 8 : assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
7192 4 : }
7193 4 : }
7194 4 : }
7195 4 :
7196 4 : Ok(())
7197 4 : }
7198 :
7199 : #[tokio::test]
7200 4 : async fn test_random_updates() -> anyhow::Result<()> {
7201 4 : let names_algorithms = [
7202 4 : ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
7203 4 : ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
7204 4 : ];
7205 12 : for (name, algorithm) in names_algorithms {
7206 8 : test_random_updates_algorithm(name, algorithm).await?;
7207 4 : }
7208 4 : Ok(())
7209 4 : }
7210 :
7211 8 : async fn test_random_updates_algorithm(
7212 8 : name: &'static str,
7213 8 : compaction_algorithm: CompactionAlgorithm,
7214 8 : ) -> anyhow::Result<()> {
7215 8 : let mut harness = TenantHarness::create(name).await?;
7216 8 : harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
7217 8 : kind: compaction_algorithm,
7218 8 : });
7219 8 : let (tenant, ctx) = harness.load().await;
7220 8 : let tline = tenant
7221 8 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7222 8 : .await?;
7223 :
7224 : const NUM_KEYS: usize = 1000;
7225 8 : let cancel = CancellationToken::new();
7226 8 :
7227 8 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7228 8 : let mut test_key_end = test_key;
7229 8 : test_key_end.field6 = NUM_KEYS as u32;
7230 8 : tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
7231 8 :
7232 8 : let mut keyspace = KeySpaceAccum::new();
7233 8 :
7234 8 : // Track when each page was last modified. Used to assert that
7235 8 : // a read sees the latest page version.
7236 8 : let mut updated = [Lsn(0); NUM_KEYS];
7237 8 :
7238 8 : let mut lsn = Lsn(0x10);
7239 : #[allow(clippy::needless_range_loop)]
7240 8008 : for blknum in 0..NUM_KEYS {
7241 8000 : lsn = Lsn(lsn.0 + 0x10);
7242 8000 : test_key.field6 = blknum as u32;
7243 8000 : let mut writer = tline.writer().await;
7244 8000 : writer
7245 8000 : .put(
7246 8000 : test_key,
7247 8000 : lsn,
7248 8000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7249 8000 : &ctx,
7250 8000 : )
7251 8000 : .await?;
7252 8000 : writer.finish_write(lsn);
7253 8000 : updated[blknum] = lsn;
7254 8000 : drop(writer);
7255 8000 :
7256 8000 : keyspace.add_key(test_key);
7257 : }
7258 :
7259 408 : for _ in 0..50 {
7260 400400 : for _ in 0..NUM_KEYS {
7261 400000 : lsn = Lsn(lsn.0 + 0x10);
7262 400000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7263 400000 : test_key.field6 = blknum as u32;
7264 400000 : let mut writer = tline.writer().await;
7265 400000 : writer
7266 400000 : .put(
7267 400000 : test_key,
7268 400000 : lsn,
7269 400000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7270 400000 : &ctx,
7271 400000 : )
7272 400000 : .await?;
7273 400000 : writer.finish_write(lsn);
7274 400000 : drop(writer);
7275 400000 : updated[blknum] = lsn;
7276 : }
7277 :
7278 : // Read all the blocks
7279 400000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7280 400000 : test_key.field6 = blknum as u32;
7281 400000 : assert_eq!(
7282 400000 : tline.get(test_key, lsn, &ctx).await?,
7283 400000 : test_img(&format!("{} at {}", blknum, last_lsn))
7284 : );
7285 : }
7286 :
7287 : // Perform a cycle of flush, and GC
7288 400 : tline.freeze_and_flush().await?;
7289 400 : tenant
7290 400 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7291 400 : .await?;
7292 : }
7293 :
7294 8 : Ok(())
7295 8 : }
7296 :
7297 : #[tokio::test]
7298 4 : async fn test_traverse_branches() -> anyhow::Result<()> {
7299 4 : let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
7300 4 : .await?
7301 4 : .load()
7302 4 : .await;
7303 4 : let mut tline = tenant
7304 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7305 4 : .await?;
7306 4 :
7307 4 : const NUM_KEYS: usize = 1000;
7308 4 :
7309 4 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7310 4 :
7311 4 : let mut keyspace = KeySpaceAccum::new();
7312 4 :
7313 4 : let cancel = CancellationToken::new();
7314 4 :
7315 4 : // Track when each page was last modified. Used to assert that
7316 4 : // a read sees the latest page version.
7317 4 : let mut updated = [Lsn(0); NUM_KEYS];
7318 4 :
7319 4 : let mut lsn = Lsn(0x10);
7320 4 : #[allow(clippy::needless_range_loop)]
7321 4004 : for blknum in 0..NUM_KEYS {
7322 4000 : lsn = Lsn(lsn.0 + 0x10);
7323 4000 : test_key.field6 = blknum as u32;
7324 4000 : let mut writer = tline.writer().await;
7325 4000 : writer
7326 4000 : .put(
7327 4000 : test_key,
7328 4000 : lsn,
7329 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7330 4000 : &ctx,
7331 4000 : )
7332 4000 : .await?;
7333 4000 : writer.finish_write(lsn);
7334 4000 : updated[blknum] = lsn;
7335 4000 : drop(writer);
7336 4000 :
7337 4000 : keyspace.add_key(test_key);
7338 4 : }
7339 4 :
7340 204 : for _ in 0..50 {
7341 200 : let new_tline_id = TimelineId::generate();
7342 200 : tenant
7343 200 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
7344 200 : .await?;
7345 200 : tline = tenant
7346 200 : .get_timeline(new_tline_id, true)
7347 200 : .expect("Should have the branched timeline");
7348 4 :
7349 200200 : for _ in 0..NUM_KEYS {
7350 200000 : lsn = Lsn(lsn.0 + 0x10);
7351 200000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7352 200000 : test_key.field6 = blknum as u32;
7353 200000 : let mut writer = tline.writer().await;
7354 200000 : writer
7355 200000 : .put(
7356 200000 : test_key,
7357 200000 : lsn,
7358 200000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7359 200000 : &ctx,
7360 200000 : )
7361 200000 : .await?;
7362 200000 : println!("updating {} at {}", blknum, lsn);
7363 200000 : writer.finish_write(lsn);
7364 200000 : drop(writer);
7365 200000 : updated[blknum] = lsn;
7366 4 : }
7367 4 :
7368 4 : // Read all the blocks
7369 200000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7370 200000 : test_key.field6 = blknum as u32;
7371 200000 : assert_eq!(
7372 200000 : tline.get(test_key, lsn, &ctx).await?,
7373 200000 : test_img(&format!("{} at {}", blknum, last_lsn))
7374 4 : );
7375 4 : }
7376 4 :
7377 4 : // Perform a cycle of flush, compact, and GC
7378 200 : tline.freeze_and_flush().await?;
7379 200 : tline.compact(&cancel, EnumSet::default(), &ctx).await?;
7380 200 : tenant
7381 200 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7382 200 : .await?;
7383 4 : }
7384 4 :
7385 4 : Ok(())
7386 4 : }
7387 :
7388 : #[tokio::test]
7389 4 : async fn test_traverse_ancestors() -> anyhow::Result<()> {
7390 4 : let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
7391 4 : .await?
7392 4 : .load()
7393 4 : .await;
7394 4 : let mut tline = tenant
7395 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7396 4 : .await?;
7397 4 :
7398 4 : const NUM_KEYS: usize = 100;
7399 4 : const NUM_TLINES: usize = 50;
7400 4 :
7401 4 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7402 4 : // Track page mutation lsns across different timelines.
7403 4 : let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
7404 4 :
7405 4 : let mut lsn = Lsn(0x10);
7406 4 :
7407 4 : #[allow(clippy::needless_range_loop)]
7408 204 : for idx in 0..NUM_TLINES {
7409 200 : let new_tline_id = TimelineId::generate();
7410 200 : tenant
7411 200 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
7412 200 : .await?;
7413 200 : tline = tenant
7414 200 : .get_timeline(new_tline_id, true)
7415 200 : .expect("Should have the branched timeline");
7416 4 :
7417 20200 : for _ in 0..NUM_KEYS {
7418 20000 : lsn = Lsn(lsn.0 + 0x10);
7419 20000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7420 20000 : test_key.field6 = blknum as u32;
7421 20000 : let mut writer = tline.writer().await;
7422 20000 : writer
7423 20000 : .put(
7424 20000 : test_key,
7425 20000 : lsn,
7426 20000 : &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
7427 20000 : &ctx,
7428 20000 : )
7429 20000 : .await?;
7430 20000 : println!("updating [{}][{}] at {}", idx, blknum, lsn);
7431 20000 : writer.finish_write(lsn);
7432 20000 : drop(writer);
7433 20000 : updated[idx][blknum] = lsn;
7434 4 : }
7435 4 : }
7436 4 :
7437 4 : // Read pages from leaf timeline across all ancestors.
7438 200 : for (idx, lsns) in updated.iter().enumerate() {
7439 20000 : for (blknum, lsn) in lsns.iter().enumerate() {
7440 4 : // Skip empty mutations.
7441 20000 : if lsn.0 == 0 {
7442 7229 : continue;
7443 12771 : }
7444 12771 : println!("checking [{idx}][{blknum}] at {lsn}");
7445 12771 : test_key.field6 = blknum as u32;
7446 12771 : assert_eq!(
7447 12771 : tline.get(test_key, *lsn, &ctx).await?,
7448 12771 : test_img(&format!("{idx} {blknum} at {lsn}"))
7449 4 : );
7450 4 : }
7451 4 : }
7452 4 : Ok(())
7453 4 : }
7454 :
7455 : #[tokio::test]
7456 4 : async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
7457 4 : let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
7458 4 : .await?
7459 4 : .load()
7460 4 : .await;
7461 4 :
7462 4 : let initdb_lsn = Lsn(0x20);
7463 4 : let (utline, ctx) = tenant
7464 4 : .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
7465 4 : .await?;
7466 4 : let tline = utline.raw_timeline().unwrap();
7467 4 :
7468 4 : // Spawn flush loop now so that we can set the `expect_initdb_optimization`
7469 4 : tline.maybe_spawn_flush_loop();
7470 4 :
7471 4 : // Make sure the timeline has the minimum set of required keys for operation.
7472 4 : // The only operation you can always do on an empty timeline is to `put` new data.
7473 4 : // Except if you `put` at `initdb_lsn`.
7474 4 : // In that case, there's an optimization to directly create image layers instead of delta layers.
7475 4 : // It uses `repartition()`, which assumes some keys to be present.
7476 4 : // Let's make sure the test timeline can handle that case.
7477 4 : {
7478 4 : let mut state = tline.flush_loop_state.lock().unwrap();
7479 4 : assert_eq!(
7480 4 : timeline::FlushLoopState::Running {
7481 4 : expect_initdb_optimization: false,
7482 4 : initdb_optimization_count: 0,
7483 4 : },
7484 4 : *state
7485 4 : );
7486 4 : *state = timeline::FlushLoopState::Running {
7487 4 : expect_initdb_optimization: true,
7488 4 : initdb_optimization_count: 0,
7489 4 : };
7490 4 : }
7491 4 :
7492 4 : // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
7493 4 : // As explained above, the optimization requires some keys to be present.
7494 4 : // As per `create_empty_timeline` documentation, use init_empty to set them.
7495 4 : // This is what `create_test_timeline` does, by the way.
7496 4 : let mut modification = tline.begin_modification(initdb_lsn);
7497 4 : modification
7498 4 : .init_empty_test_timeline()
7499 4 : .context("init_empty_test_timeline")?;
7500 4 : modification
7501 4 : .commit(&ctx)
7502 4 : .await
7503 4 : .context("commit init_empty_test_timeline modification")?;
7504 4 :
7505 4 : // Do the flush. The flush code will check the expectations that we set above.
7506 4 : tline.freeze_and_flush().await?;
7507 4 :
7508 4 : // assert freeze_and_flush exercised the initdb optimization
7509 4 : {
7510 4 : let state = tline.flush_loop_state.lock().unwrap();
7511 4 : let timeline::FlushLoopState::Running {
7512 4 : expect_initdb_optimization,
7513 4 : initdb_optimization_count,
7514 4 : } = *state
7515 4 : else {
7516 4 : panic!("unexpected state: {:?}", *state);
7517 4 : };
7518 4 : assert!(expect_initdb_optimization);
7519 4 : assert!(initdb_optimization_count > 0);
7520 4 : }
7521 4 : Ok(())
7522 4 : }
7523 :
7524 : #[tokio::test]
7525 4 : async fn test_create_guard_crash() -> anyhow::Result<()> {
7526 4 : let name = "test_create_guard_crash";
7527 4 : let harness = TenantHarness::create(name).await?;
7528 4 : {
7529 4 : let (tenant, ctx) = harness.load().await;
7530 4 : let (tline, _ctx) = tenant
7531 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
7532 4 : .await?;
7533 4 : // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
7534 4 : let raw_tline = tline.raw_timeline().unwrap();
7535 4 : raw_tline
7536 4 : .shutdown(super::timeline::ShutdownMode::Hard)
7537 4 : .instrument(info_span!("test_shutdown", tenant_id=%raw_tline.tenant_shard_id, shard_id=%raw_tline.tenant_shard_id.shard_slug(), timeline_id=%TIMELINE_ID))
7538 4 : .await;
7539 4 : std::mem::forget(tline);
7540 4 : }
7541 4 :
7542 4 : let (tenant, _) = harness.load().await;
7543 4 : match tenant.get_timeline(TIMELINE_ID, false) {
7544 4 : Ok(_) => panic!("timeline should've been removed during load"),
7545 4 : Err(e) => {
7546 4 : assert_eq!(
7547 4 : e,
7548 4 : GetTimelineError::NotFound {
7549 4 : tenant_id: tenant.tenant_shard_id,
7550 4 : timeline_id: TIMELINE_ID,
7551 4 : }
7552 4 : )
7553 4 : }
7554 4 : }
7555 4 :
7556 4 : assert!(
7557 4 : !harness
7558 4 : .conf
7559 4 : .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
7560 4 : .exists()
7561 4 : );
7562 4 :
7563 4 : Ok(())
7564 4 : }
7565 :
7566 : #[tokio::test]
7567 4 : async fn test_read_at_max_lsn() -> anyhow::Result<()> {
7568 4 : let names_algorithms = [
7569 4 : ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
7570 4 : ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
7571 4 : ];
7572 12 : for (name, algorithm) in names_algorithms {
7573 8 : test_read_at_max_lsn_algorithm(name, algorithm).await?;
7574 4 : }
7575 4 : Ok(())
7576 4 : }
7577 :
7578 8 : async fn test_read_at_max_lsn_algorithm(
7579 8 : name: &'static str,
7580 8 : compaction_algorithm: CompactionAlgorithm,
7581 8 : ) -> anyhow::Result<()> {
7582 8 : let mut harness = TenantHarness::create(name).await?;
7583 8 : harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
7584 8 : kind: compaction_algorithm,
7585 8 : });
7586 8 : let (tenant, ctx) = harness.load().await;
7587 8 : let tline = tenant
7588 8 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
7589 8 : .await?;
7590 :
7591 8 : let lsn = Lsn(0x10);
7592 8 : let compact = false;
7593 8 : bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
7594 :
7595 8 : let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7596 8 : let read_lsn = Lsn(u64::MAX - 1);
7597 :
7598 8 : let result = tline.get(test_key, read_lsn, &ctx).await;
7599 8 : assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
7600 :
7601 8 : Ok(())
7602 8 : }
7603 :
7604 : #[tokio::test]
7605 4 : async fn test_metadata_scan() -> anyhow::Result<()> {
7606 4 : let harness = TenantHarness::create("test_metadata_scan").await?;
7607 4 : let (tenant, ctx) = harness.load().await;
7608 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7609 4 : let tline = tenant
7610 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7611 4 : .await?;
7612 4 :
7613 4 : const NUM_KEYS: usize = 1000;
7614 4 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
7615 4 :
7616 4 : let cancel = CancellationToken::new();
7617 4 :
7618 4 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7619 4 : base_key.field1 = AUX_KEY_PREFIX;
7620 4 : let mut test_key = base_key;
7621 4 :
7622 4 : // Track when each page was last modified. Used to assert that
7623 4 : // a read sees the latest page version.
7624 4 : let mut updated = [Lsn(0); NUM_KEYS];
7625 4 :
7626 4 : let mut lsn = Lsn(0x10);
7627 4 : #[allow(clippy::needless_range_loop)]
7628 4004 : for blknum in 0..NUM_KEYS {
7629 4000 : lsn = Lsn(lsn.0 + 0x10);
7630 4000 : test_key.field6 = (blknum * STEP) as u32;
7631 4000 : let mut writer = tline.writer().await;
7632 4000 : writer
7633 4000 : .put(
7634 4000 : test_key,
7635 4000 : lsn,
7636 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7637 4000 : &ctx,
7638 4000 : )
7639 4000 : .await?;
7640 4000 : writer.finish_write(lsn);
7641 4000 : updated[blknum] = lsn;
7642 4000 : drop(writer);
7643 4 : }
7644 4 :
7645 4 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
7646 4 :
7647 48 : for iter in 0..=10 {
7648 4 : // Read all the blocks
7649 44000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7650 44000 : test_key.field6 = (blknum * STEP) as u32;
7651 44000 : assert_eq!(
7652 44000 : tline.get(test_key, lsn, &ctx).await?,
7653 44000 : test_img(&format!("{} at {}", blknum, last_lsn))
7654 4 : );
7655 4 : }
7656 4 :
7657 44 : let mut cnt = 0;
7658 44000 : for (key, value) in tline
7659 44 : .get_vectored_impl(
7660 44 : keyspace.clone(),
7661 44 : lsn,
7662 44 : &mut ValuesReconstructState::new(io_concurrency.clone()),
7663 44 : &ctx,
7664 44 : )
7665 44 : .await?
7666 4 : {
7667 44000 : let blknum = key.field6 as usize;
7668 44000 : let value = value?;
7669 44000 : assert!(blknum % STEP == 0);
7670 44000 : let blknum = blknum / STEP;
7671 44000 : assert_eq!(
7672 44000 : value,
7673 44000 : test_img(&format!("{} at {}", blknum, updated[blknum]))
7674 44000 : );
7675 44000 : cnt += 1;
7676 4 : }
7677 4 :
7678 44 : assert_eq!(cnt, NUM_KEYS);
7679 4 :
7680 44044 : for _ in 0..NUM_KEYS {
7681 44000 : lsn = Lsn(lsn.0 + 0x10);
7682 44000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7683 44000 : test_key.field6 = (blknum * STEP) as u32;
7684 44000 : let mut writer = tline.writer().await;
7685 44000 : writer
7686 44000 : .put(
7687 44000 : test_key,
7688 44000 : lsn,
7689 44000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7690 44000 : &ctx,
7691 44000 : )
7692 44000 : .await?;
7693 44000 : writer.finish_write(lsn);
7694 44000 : drop(writer);
7695 44000 : updated[blknum] = lsn;
7696 4 : }
7697 4 :
7698 4 : // Perform two cycles of flush, compact, and GC
7699 132 : for round in 0..2 {
7700 88 : tline.freeze_and_flush().await?;
7701 88 : tline
7702 88 : .compact(
7703 88 : &cancel,
7704 88 : if iter % 5 == 0 && round == 0 {
7705 12 : let mut flags = EnumSet::new();
7706 12 : flags.insert(CompactFlags::ForceImageLayerCreation);
7707 12 : flags.insert(CompactFlags::ForceRepartition);
7708 12 : flags
7709 4 : } else {
7710 76 : EnumSet::empty()
7711 4 : },
7712 88 : &ctx,
7713 88 : )
7714 88 : .await?;
7715 88 : tenant
7716 88 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7717 88 : .await?;
7718 4 : }
7719 4 : }
7720 4 :
7721 4 : Ok(())
7722 4 : }
7723 :
7724 : #[tokio::test]
7725 4 : async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
7726 4 : let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
7727 4 : let (tenant, ctx) = harness.load().await;
7728 4 : let tline = tenant
7729 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7730 4 : .await?;
7731 4 :
7732 4 : let cancel = CancellationToken::new();
7733 4 :
7734 4 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7735 4 : base_key.field1 = AUX_KEY_PREFIX;
7736 4 : let test_key = base_key;
7737 4 : let mut lsn = Lsn(0x10);
7738 4 :
7739 84 : for _ in 0..20 {
7740 80 : lsn = Lsn(lsn.0 + 0x10);
7741 80 : let mut writer = tline.writer().await;
7742 80 : writer
7743 80 : .put(
7744 80 : test_key,
7745 80 : lsn,
7746 80 : &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
7747 80 : &ctx,
7748 80 : )
7749 80 : .await?;
7750 80 : writer.finish_write(lsn);
7751 80 : drop(writer);
7752 80 : tline.freeze_and_flush().await?; // force create a delta layer
7753 4 : }
7754 4 :
7755 4 : let before_num_l0_delta_files =
7756 4 : tline.layers.read().await.layer_map()?.level0_deltas().len();
7757 4 :
7758 4 : tline.compact(&cancel, EnumSet::default(), &ctx).await?;
7759 4 :
7760 4 : let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
7761 4 :
7762 4 : assert!(
7763 4 : after_num_l0_delta_files < before_num_l0_delta_files,
7764 4 : "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
7765 4 : );
7766 4 :
7767 4 : assert_eq!(
7768 4 : tline.get(test_key, lsn, &ctx).await?,
7769 4 : test_img(&format!("{} at {}", 0, lsn))
7770 4 : );
7771 4 :
7772 4 : Ok(())
7773 4 : }
7774 :
7775 : #[tokio::test]
7776 4 : async fn test_aux_file_e2e() {
7777 4 : let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
7778 4 :
7779 4 : let (tenant, ctx) = harness.load().await;
7780 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7781 4 :
7782 4 : let mut lsn = Lsn(0x08);
7783 4 :
7784 4 : let tline: Arc<Timeline> = tenant
7785 4 : .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
7786 4 : .await
7787 4 : .unwrap();
7788 4 :
7789 4 : {
7790 4 : lsn += 8;
7791 4 : let mut modification = tline.begin_modification(lsn);
7792 4 : modification
7793 4 : .put_file("pg_logical/mappings/test1", b"first", &ctx)
7794 4 : .await
7795 4 : .unwrap();
7796 4 : modification.commit(&ctx).await.unwrap();
7797 4 : }
7798 4 :
7799 4 : // we can read everything from the storage
7800 4 : let files = tline
7801 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7802 4 : .await
7803 4 : .unwrap();
7804 4 : assert_eq!(
7805 4 : files.get("pg_logical/mappings/test1"),
7806 4 : Some(&bytes::Bytes::from_static(b"first"))
7807 4 : );
7808 4 :
7809 4 : {
7810 4 : lsn += 8;
7811 4 : let mut modification = tline.begin_modification(lsn);
7812 4 : modification
7813 4 : .put_file("pg_logical/mappings/test2", b"second", &ctx)
7814 4 : .await
7815 4 : .unwrap();
7816 4 : modification.commit(&ctx).await.unwrap();
7817 4 : }
7818 4 :
7819 4 : let files = tline
7820 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7821 4 : .await
7822 4 : .unwrap();
7823 4 : assert_eq!(
7824 4 : files.get("pg_logical/mappings/test2"),
7825 4 : Some(&bytes::Bytes::from_static(b"second"))
7826 4 : );
7827 4 :
7828 4 : let child = tenant
7829 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
7830 4 : .await
7831 4 : .unwrap();
7832 4 :
7833 4 : let files = child
7834 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7835 4 : .await
7836 4 : .unwrap();
7837 4 : assert_eq!(files.get("pg_logical/mappings/test1"), None);
7838 4 : assert_eq!(files.get("pg_logical/mappings/test2"), None);
7839 4 : }
7840 :
7841 : #[tokio::test]
7842 4 : async fn test_metadata_image_creation() -> anyhow::Result<()> {
7843 4 : let harness = TenantHarness::create("test_metadata_image_creation").await?;
7844 4 : let (tenant, ctx) = harness.load().await;
7845 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7846 4 : let tline = tenant
7847 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7848 4 : .await?;
7849 4 :
7850 4 : const NUM_KEYS: usize = 1000;
7851 4 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
7852 4 :
7853 4 : let cancel = CancellationToken::new();
7854 4 :
7855 4 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
7856 4 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
7857 4 : let mut test_key = base_key;
7858 4 : let mut lsn = Lsn(0x10);
7859 4 :
7860 16 : async fn scan_with_statistics(
7861 16 : tline: &Timeline,
7862 16 : keyspace: &KeySpace,
7863 16 : lsn: Lsn,
7864 16 : ctx: &RequestContext,
7865 16 : io_concurrency: IoConcurrency,
7866 16 : ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
7867 16 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
7868 16 : let res = tline
7869 16 : .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
7870 16 : .await?;
7871 16 : Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
7872 16 : }
7873 4 :
7874 4004 : for blknum in 0..NUM_KEYS {
7875 4000 : lsn = Lsn(lsn.0 + 0x10);
7876 4000 : test_key.field6 = (blknum * STEP) as u32;
7877 4000 : let mut writer = tline.writer().await;
7878 4000 : writer
7879 4000 : .put(
7880 4000 : test_key,
7881 4000 : lsn,
7882 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7883 4000 : &ctx,
7884 4000 : )
7885 4000 : .await?;
7886 4000 : writer.finish_write(lsn);
7887 4000 : drop(writer);
7888 4 : }
7889 4 :
7890 4 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
7891 4 :
7892 44 : for iter in 1..=10 {
7893 40040 : for _ in 0..NUM_KEYS {
7894 40000 : lsn = Lsn(lsn.0 + 0x10);
7895 40000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7896 40000 : test_key.field6 = (blknum * STEP) as u32;
7897 40000 : let mut writer = tline.writer().await;
7898 40000 : writer
7899 40000 : .put(
7900 40000 : test_key,
7901 40000 : lsn,
7902 40000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7903 40000 : &ctx,
7904 40000 : )
7905 40000 : .await?;
7906 40000 : writer.finish_write(lsn);
7907 40000 : drop(writer);
7908 4 : }
7909 4 :
7910 40 : tline.freeze_and_flush().await?;
7911 4 :
7912 40 : if iter % 5 == 0 {
7913 8 : let (_, before_delta_file_accessed) =
7914 8 : scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
7915 8 : .await?;
7916 8 : tline
7917 8 : .compact(
7918 8 : &cancel,
7919 8 : {
7920 8 : let mut flags = EnumSet::new();
7921 8 : flags.insert(CompactFlags::ForceImageLayerCreation);
7922 8 : flags.insert(CompactFlags::ForceRepartition);
7923 8 : flags
7924 8 : },
7925 8 : &ctx,
7926 8 : )
7927 8 : .await?;
7928 8 : let (_, after_delta_file_accessed) =
7929 8 : scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
7930 8 : .await?;
7931 8 : assert!(
7932 8 : after_delta_file_accessed < before_delta_file_accessed,
7933 4 : "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
7934 4 : );
7935 4 : // Given that we already produced an image layer, there should be no delta layer needed for the scan, but still setting a low threshold there for unforeseen circumstances.
7936 8 : assert!(
7937 8 : after_delta_file_accessed <= 2,
7938 4 : "after_delta_file_accessed={after_delta_file_accessed}"
7939 4 : );
7940 32 : }
7941 4 : }
7942 4 :
7943 4 : Ok(())
7944 4 : }
7945 :
7946 : #[tokio::test]
7947 4 : async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
7948 4 : let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
7949 4 : let (tenant, ctx) = harness.load().await;
7950 4 :
7951 4 : let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7952 4 : let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
7953 4 : let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
7954 4 :
7955 4 : let tline = tenant
7956 4 : .create_test_timeline_with_layers(
7957 4 : TIMELINE_ID,
7958 4 : Lsn(0x10),
7959 4 : DEFAULT_PG_VERSION,
7960 4 : &ctx,
7961 4 : Vec::new(), // in-memory layers
7962 4 : Vec::new(), // delta layers
7963 4 : vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
7964 4 : Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
7965 4 : )
7966 4 : .await?;
7967 4 : tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
7968 4 :
7969 4 : let child = tenant
7970 4 : .branch_timeline_test_with_layers(
7971 4 : &tline,
7972 4 : NEW_TIMELINE_ID,
7973 4 : Some(Lsn(0x20)),
7974 4 : &ctx,
7975 4 : Vec::new(), // delta layers
7976 4 : vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
7977 4 : Lsn(0x30),
7978 4 : )
7979 4 : .await
7980 4 : .unwrap();
7981 4 :
7982 4 : let lsn = Lsn(0x30);
7983 4 :
7984 4 : // test vectored get on parent timeline
7985 4 : assert_eq!(
7986 4 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
7987 4 : Some(test_img("data key 1"))
7988 4 : );
7989 4 : assert!(
7990 4 : get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
7991 4 : .await
7992 4 : .unwrap_err()
7993 4 : .is_missing_key_error()
7994 4 : );
7995 4 : assert!(
7996 4 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
7997 4 : .await
7998 4 : .unwrap_err()
7999 4 : .is_missing_key_error()
8000 4 : );
8001 4 :
8002 4 : // test vectored get on child timeline
8003 4 : assert_eq!(
8004 4 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
8005 4 : Some(test_img("data key 1"))
8006 4 : );
8007 4 : assert_eq!(
8008 4 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
8009 4 : Some(test_img("data key 2"))
8010 4 : );
8011 4 : assert!(
8012 4 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
8013 4 : .await
8014 4 : .unwrap_err()
8015 4 : .is_missing_key_error()
8016 4 : );
8017 4 :
8018 4 : Ok(())
8019 4 : }
8020 :
8021 : #[tokio::test]
8022 4 : async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
8023 4 : let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
8024 4 : let (tenant, ctx) = harness.load().await;
8025 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8026 4 :
8027 4 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8028 4 : let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
8029 4 : let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
8030 4 : let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
8031 4 :
8032 4 : let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
8033 4 : let base_inherited_key_child =
8034 4 : Key::from_hex("610000000033333333444444445500000001").unwrap();
8035 4 : let base_inherited_key_nonexist =
8036 4 : Key::from_hex("610000000033333333444444445500000002").unwrap();
8037 4 : let base_inherited_key_overwrite =
8038 4 : Key::from_hex("610000000033333333444444445500000003").unwrap();
8039 4 :
8040 4 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
8041 4 : assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
8042 4 :
8043 4 : let tline = tenant
8044 4 : .create_test_timeline_with_layers(
8045 4 : TIMELINE_ID,
8046 4 : Lsn(0x10),
8047 4 : DEFAULT_PG_VERSION,
8048 4 : &ctx,
8049 4 : Vec::new(), // in-memory layers
8050 4 : Vec::new(), // delta layers
8051 4 : vec![(
8052 4 : Lsn(0x20),
8053 4 : vec![
8054 4 : (base_inherited_key, test_img("metadata inherited key 1")),
8055 4 : (
8056 4 : base_inherited_key_overwrite,
8057 4 : test_img("metadata key overwrite 1a"),
8058 4 : ),
8059 4 : (base_key, test_img("metadata key 1")),
8060 4 : (base_key_overwrite, test_img("metadata key overwrite 1b")),
8061 4 : ],
8062 4 : )], // image layers
8063 4 : Lsn(0x20), // it's fine to not advance LSN to 0x30 while using 0x30 to get below because `get_vectored_impl` does not wait for LSN
8064 4 : )
8065 4 : .await?;
8066 4 :
8067 4 : let child = tenant
8068 4 : .branch_timeline_test_with_layers(
8069 4 : &tline,
8070 4 : NEW_TIMELINE_ID,
8071 4 : Some(Lsn(0x20)),
8072 4 : &ctx,
8073 4 : Vec::new(), // delta layers
8074 4 : vec![(
8075 4 : Lsn(0x30),
8076 4 : vec![
8077 4 : (
8078 4 : base_inherited_key_child,
8079 4 : test_img("metadata inherited key 2"),
8080 4 : ),
8081 4 : (
8082 4 : base_inherited_key_overwrite,
8083 4 : test_img("metadata key overwrite 2a"),
8084 4 : ),
8085 4 : (base_key_child, test_img("metadata key 2")),
8086 4 : (base_key_overwrite, test_img("metadata key overwrite 2b")),
8087 4 : ],
8088 4 : )], // image layers
8089 4 : Lsn(0x30),
8090 4 : )
8091 4 : .await
8092 4 : .unwrap();
8093 4 :
8094 4 : let lsn = Lsn(0x30);
8095 4 :
8096 4 : // test vectored get on parent timeline
8097 4 : assert_eq!(
8098 4 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
8099 4 : Some(test_img("metadata key 1"))
8100 4 : );
8101 4 : assert_eq!(
8102 4 : get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
8103 4 : None
8104 4 : );
8105 4 : assert_eq!(
8106 4 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
8107 4 : None
8108 4 : );
8109 4 : assert_eq!(
8110 4 : get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
8111 4 : Some(test_img("metadata key overwrite 1b"))
8112 4 : );
8113 4 : assert_eq!(
8114 4 : get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
8115 4 : Some(test_img("metadata inherited key 1"))
8116 4 : );
8117 4 : assert_eq!(
8118 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
8119 4 : None
8120 4 : );
8121 4 : assert_eq!(
8122 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
8123 4 : None
8124 4 : );
8125 4 : assert_eq!(
8126 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
8127 4 : Some(test_img("metadata key overwrite 1a"))
8128 4 : );
8129 4 :
8130 4 : // test vectored get on child timeline
8131 4 : assert_eq!(
8132 4 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
8133 4 : None
8134 4 : );
8135 4 : assert_eq!(
8136 4 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
8137 4 : Some(test_img("metadata key 2"))
8138 4 : );
8139 4 : assert_eq!(
8140 4 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
8141 4 : None
8142 4 : );
8143 4 : assert_eq!(
8144 4 : get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
8145 4 : Some(test_img("metadata inherited key 1"))
8146 4 : );
8147 4 : assert_eq!(
8148 4 : get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
8149 4 : Some(test_img("metadata inherited key 2"))
8150 4 : );
8151 4 : assert_eq!(
8152 4 : get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
8153 4 : None
8154 4 : );
8155 4 : assert_eq!(
8156 4 : get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
8157 4 : Some(test_img("metadata key overwrite 2b"))
8158 4 : );
8159 4 : assert_eq!(
8160 4 : get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
8161 4 : Some(test_img("metadata key overwrite 2a"))
8162 4 : );
8163 4 :
8164 4 : // test vectored scan on parent timeline
8165 4 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
8166 4 : let res = tline
8167 4 : .get_vectored_impl(
8168 4 : KeySpace::single(Key::metadata_key_range()),
8169 4 : lsn,
8170 4 : &mut reconstruct_state,
8171 4 : &ctx,
8172 4 : )
8173 4 : .await?;
8174 4 :
8175 4 : assert_eq!(
8176 4 : res.into_iter()
8177 16 : .map(|(k, v)| (k, v.unwrap()))
8178 4 : .collect::<Vec<_>>(),
8179 4 : vec![
8180 4 : (base_inherited_key, test_img("metadata inherited key 1")),
8181 4 : (
8182 4 : base_inherited_key_overwrite,
8183 4 : test_img("metadata key overwrite 1a")
8184 4 : ),
8185 4 : (base_key, test_img("metadata key 1")),
8186 4 : (base_key_overwrite, test_img("metadata key overwrite 1b")),
8187 4 : ]
8188 4 : );
8189 4 :
8190 4 : // test vectored scan on child timeline
8191 4 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
8192 4 : let res = child
8193 4 : .get_vectored_impl(
8194 4 : KeySpace::single(Key::metadata_key_range()),
8195 4 : lsn,
8196 4 : &mut reconstruct_state,
8197 4 : &ctx,
8198 4 : )
8199 4 : .await?;
8200 4 :
8201 4 : assert_eq!(
8202 4 : res.into_iter()
8203 20 : .map(|(k, v)| (k, v.unwrap()))
8204 4 : .collect::<Vec<_>>(),
8205 4 : vec![
8206 4 : (base_inherited_key, test_img("metadata inherited key 1")),
8207 4 : (
8208 4 : base_inherited_key_child,
8209 4 : test_img("metadata inherited key 2")
8210 4 : ),
8211 4 : (
8212 4 : base_inherited_key_overwrite,
8213 4 : test_img("metadata key overwrite 2a")
8214 4 : ),
8215 4 : (base_key_child, test_img("metadata key 2")),
8216 4 : (base_key_overwrite, test_img("metadata key overwrite 2b")),
8217 4 : ]
8218 4 : );
8219 4 :
8220 4 : Ok(())
8221 4 : }
8222 :
8223 112 : async fn get_vectored_impl_wrapper(
8224 112 : tline: &Arc<Timeline>,
8225 112 : key: Key,
8226 112 : lsn: Lsn,
8227 112 : ctx: &RequestContext,
8228 112 : ) -> Result<Option<Bytes>, GetVectoredError> {
8229 112 : let io_concurrency =
8230 112 : IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
8231 112 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
8232 112 : let mut res = tline
8233 112 : .get_vectored_impl(
8234 112 : KeySpace::single(key..key.next()),
8235 112 : lsn,
8236 112 : &mut reconstruct_state,
8237 112 : ctx,
8238 112 : )
8239 112 : .await?;
8240 100 : Ok(res.pop_last().map(|(k, v)| {
8241 64 : assert_eq!(k, key);
8242 64 : v.unwrap()
8243 100 : }))
8244 112 : }
8245 :
8246 : #[tokio::test]
8247 4 : async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
8248 4 : let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
8249 4 : let (tenant, ctx) = harness.load().await;
8250 4 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
8251 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8252 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8253 4 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
8254 4 :
8255 4 : // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
8256 4 : // Lsn 0x30 key0, key3, no key1+key2
8257 4 : // Lsn 0x20 key1+key2 tomestones
8258 4 : // Lsn 0x10 key1 in image, key2 in delta
8259 4 : let tline = tenant
8260 4 : .create_test_timeline_with_layers(
8261 4 : TIMELINE_ID,
8262 4 : Lsn(0x10),
8263 4 : DEFAULT_PG_VERSION,
8264 4 : &ctx,
8265 4 : Vec::new(), // in-memory layers
8266 4 : // delta layers
8267 4 : vec![
8268 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8269 4 : Lsn(0x10)..Lsn(0x20),
8270 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8271 4 : ),
8272 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8273 4 : Lsn(0x20)..Lsn(0x30),
8274 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8275 4 : ),
8276 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8277 4 : Lsn(0x20)..Lsn(0x30),
8278 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8279 4 : ),
8280 4 : ],
8281 4 : // image layers
8282 4 : vec![
8283 4 : (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
8284 4 : (
8285 4 : Lsn(0x30),
8286 4 : vec![
8287 4 : (key0, test_img("metadata key 0")),
8288 4 : (key3, test_img("metadata key 3")),
8289 4 : ],
8290 4 : ),
8291 4 : ],
8292 4 : Lsn(0x30),
8293 4 : )
8294 4 : .await?;
8295 4 :
8296 4 : let lsn = Lsn(0x30);
8297 4 : let old_lsn = Lsn(0x20);
8298 4 :
8299 4 : assert_eq!(
8300 4 : get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
8301 4 : Some(test_img("metadata key 0"))
8302 4 : );
8303 4 : assert_eq!(
8304 4 : get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
8305 4 : None,
8306 4 : );
8307 4 : assert_eq!(
8308 4 : get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
8309 4 : None,
8310 4 : );
8311 4 : assert_eq!(
8312 4 : get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
8313 4 : Some(Bytes::new()),
8314 4 : );
8315 4 : assert_eq!(
8316 4 : get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
8317 4 : Some(Bytes::new()),
8318 4 : );
8319 4 : assert_eq!(
8320 4 : get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
8321 4 : Some(test_img("metadata key 3"))
8322 4 : );
8323 4 :
8324 4 : Ok(())
8325 4 : }
8326 :
8327 : #[tokio::test]
8328 4 : async fn test_metadata_tombstone_image_creation() {
8329 4 : let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
8330 4 : .await
8331 4 : .unwrap();
8332 4 : let (tenant, ctx) = harness.load().await;
8333 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8334 4 :
8335 4 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
8336 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8337 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8338 4 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
8339 4 :
8340 4 : let tline = tenant
8341 4 : .create_test_timeline_with_layers(
8342 4 : TIMELINE_ID,
8343 4 : Lsn(0x10),
8344 4 : DEFAULT_PG_VERSION,
8345 4 : &ctx,
8346 4 : Vec::new(), // in-memory layers
8347 4 : // delta layers
8348 4 : vec![
8349 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8350 4 : Lsn(0x10)..Lsn(0x20),
8351 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8352 4 : ),
8353 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8354 4 : Lsn(0x20)..Lsn(0x30),
8355 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8356 4 : ),
8357 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8358 4 : Lsn(0x20)..Lsn(0x30),
8359 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8360 4 : ),
8361 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8362 4 : Lsn(0x30)..Lsn(0x40),
8363 4 : vec![
8364 4 : (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
8365 4 : (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
8366 4 : ],
8367 4 : ),
8368 4 : ],
8369 4 : // image layers
8370 4 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
8371 4 : Lsn(0x40),
8372 4 : )
8373 4 : .await
8374 4 : .unwrap();
8375 4 :
8376 4 : let cancel = CancellationToken::new();
8377 4 :
8378 4 : tline
8379 4 : .compact(
8380 4 : &cancel,
8381 4 : {
8382 4 : let mut flags = EnumSet::new();
8383 4 : flags.insert(CompactFlags::ForceImageLayerCreation);
8384 4 : flags.insert(CompactFlags::ForceRepartition);
8385 4 : flags
8386 4 : },
8387 4 : &ctx,
8388 4 : )
8389 4 : .await
8390 4 : .unwrap();
8391 4 :
8392 4 : // Image layers are created at last_record_lsn
8393 4 : let images = tline
8394 4 : .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
8395 4 : .await
8396 4 : .unwrap()
8397 4 : .into_iter()
8398 36 : .filter(|(k, _)| k.is_metadata_key())
8399 4 : .collect::<Vec<_>>();
8400 4 : assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
8401 4 : }
8402 :
8403 : #[tokio::test]
8404 4 : async fn test_metadata_tombstone_empty_image_creation() {
8405 4 : let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
8406 4 : .await
8407 4 : .unwrap();
8408 4 : let (tenant, ctx) = harness.load().await;
8409 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8410 4 :
8411 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8412 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8413 4 :
8414 4 : let tline = tenant
8415 4 : .create_test_timeline_with_layers(
8416 4 : TIMELINE_ID,
8417 4 : Lsn(0x10),
8418 4 : DEFAULT_PG_VERSION,
8419 4 : &ctx,
8420 4 : Vec::new(), // in-memory layers
8421 4 : // delta layers
8422 4 : vec![
8423 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8424 4 : Lsn(0x10)..Lsn(0x20),
8425 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8426 4 : ),
8427 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8428 4 : Lsn(0x20)..Lsn(0x30),
8429 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8430 4 : ),
8431 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8432 4 : Lsn(0x20)..Lsn(0x30),
8433 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8434 4 : ),
8435 4 : ],
8436 4 : // image layers
8437 4 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
8438 4 : Lsn(0x30),
8439 4 : )
8440 4 : .await
8441 4 : .unwrap();
8442 4 :
8443 4 : let cancel = CancellationToken::new();
8444 4 :
8445 4 : tline
8446 4 : .compact(
8447 4 : &cancel,
8448 4 : {
8449 4 : let mut flags = EnumSet::new();
8450 4 : flags.insert(CompactFlags::ForceImageLayerCreation);
8451 4 : flags.insert(CompactFlags::ForceRepartition);
8452 4 : flags
8453 4 : },
8454 4 : &ctx,
8455 4 : )
8456 4 : .await
8457 4 : .unwrap();
8458 4 :
8459 4 : // Image layers are created at last_record_lsn
8460 4 : let images = tline
8461 4 : .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
8462 4 : .await
8463 4 : .unwrap()
8464 4 : .into_iter()
8465 28 : .filter(|(k, _)| k.is_metadata_key())
8466 4 : .collect::<Vec<_>>();
8467 4 : assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
8468 4 : }
8469 :
8470 : #[tokio::test]
8471 4 : async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
8472 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
8473 4 : let (tenant, ctx) = harness.load().await;
8474 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8475 4 :
8476 204 : fn get_key(id: u32) -> Key {
8477 204 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8478 204 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8479 204 : key.field6 = id;
8480 204 : key
8481 204 : }
8482 4 :
8483 4 : // We create
8484 4 : // - one bottom-most image layer,
8485 4 : // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
8486 4 : // - a delta layer D2 crossing the GC horizon with data only below the horizon,
8487 4 : // - a delta layer D3 above the horizon.
8488 4 : //
8489 4 : // | D3 |
8490 4 : // | D1 |
8491 4 : // -| |-- gc horizon -----------------
8492 4 : // | | | D2 |
8493 4 : // --------- img layer ------------------
8494 4 : //
8495 4 : // What we should expact from this compaction is:
8496 4 : // | D3 |
8497 4 : // | Part of D1 |
8498 4 : // --------- img layer with D1+D2 at GC horizon------------------
8499 4 :
8500 4 : // img layer at 0x10
8501 4 : let img_layer = (0..10)
8502 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
8503 4 : .collect_vec();
8504 4 :
8505 4 : let delta1 = vec![
8506 4 : (
8507 4 : get_key(1),
8508 4 : Lsn(0x20),
8509 4 : Value::Image(Bytes::from("value 1@0x20")),
8510 4 : ),
8511 4 : (
8512 4 : get_key(2),
8513 4 : Lsn(0x30),
8514 4 : Value::Image(Bytes::from("value 2@0x30")),
8515 4 : ),
8516 4 : (
8517 4 : get_key(3),
8518 4 : Lsn(0x40),
8519 4 : Value::Image(Bytes::from("value 3@0x40")),
8520 4 : ),
8521 4 : ];
8522 4 : let delta2 = vec![
8523 4 : (
8524 4 : get_key(5),
8525 4 : Lsn(0x20),
8526 4 : Value::Image(Bytes::from("value 5@0x20")),
8527 4 : ),
8528 4 : (
8529 4 : get_key(6),
8530 4 : Lsn(0x20),
8531 4 : Value::Image(Bytes::from("value 6@0x20")),
8532 4 : ),
8533 4 : ];
8534 4 : let delta3 = vec![
8535 4 : (
8536 4 : get_key(8),
8537 4 : Lsn(0x48),
8538 4 : Value::Image(Bytes::from("value 8@0x48")),
8539 4 : ),
8540 4 : (
8541 4 : get_key(9),
8542 4 : Lsn(0x48),
8543 4 : Value::Image(Bytes::from("value 9@0x48")),
8544 4 : ),
8545 4 : ];
8546 4 :
8547 4 : let tline = tenant
8548 4 : .create_test_timeline_with_layers(
8549 4 : TIMELINE_ID,
8550 4 : Lsn(0x10),
8551 4 : DEFAULT_PG_VERSION,
8552 4 : &ctx,
8553 4 : Vec::new(), // in-memory layers
8554 4 : vec![
8555 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
8556 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
8557 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
8558 4 : ], // delta layers
8559 4 : vec![(Lsn(0x10), img_layer)], // image layers
8560 4 : Lsn(0x50),
8561 4 : )
8562 4 : .await?;
8563 4 : {
8564 4 : tline
8565 4 : .applied_gc_cutoff_lsn
8566 4 : .lock_for_write()
8567 4 : .store_and_unlock(Lsn(0x30))
8568 4 : .wait()
8569 4 : .await;
8570 4 : // Update GC info
8571 4 : let mut guard = tline.gc_info.write().unwrap();
8572 4 : guard.cutoffs.time = Lsn(0x30);
8573 4 : guard.cutoffs.space = Lsn(0x30);
8574 4 : }
8575 4 :
8576 4 : let expected_result = [
8577 4 : Bytes::from_static(b"value 0@0x10"),
8578 4 : Bytes::from_static(b"value 1@0x20"),
8579 4 : Bytes::from_static(b"value 2@0x30"),
8580 4 : Bytes::from_static(b"value 3@0x40"),
8581 4 : Bytes::from_static(b"value 4@0x10"),
8582 4 : Bytes::from_static(b"value 5@0x20"),
8583 4 : Bytes::from_static(b"value 6@0x20"),
8584 4 : Bytes::from_static(b"value 7@0x10"),
8585 4 : Bytes::from_static(b"value 8@0x48"),
8586 4 : Bytes::from_static(b"value 9@0x48"),
8587 4 : ];
8588 4 :
8589 40 : for (idx, expected) in expected_result.iter().enumerate() {
8590 40 : assert_eq!(
8591 40 : tline
8592 40 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8593 40 : .await
8594 40 : .unwrap(),
8595 4 : expected
8596 4 : );
8597 4 : }
8598 4 :
8599 4 : let cancel = CancellationToken::new();
8600 4 : tline
8601 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8602 4 : .await
8603 4 : .unwrap();
8604 4 :
8605 40 : for (idx, expected) in expected_result.iter().enumerate() {
8606 40 : assert_eq!(
8607 40 : tline
8608 40 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8609 40 : .await
8610 40 : .unwrap(),
8611 4 : expected
8612 4 : );
8613 4 : }
8614 4 :
8615 4 : // Check if the image layer at the GC horizon contains exactly what we want
8616 4 : let image_at_gc_horizon = tline
8617 4 : .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
8618 4 : .await
8619 4 : .unwrap()
8620 4 : .into_iter()
8621 68 : .filter(|(k, _)| k.is_metadata_key())
8622 4 : .collect::<Vec<_>>();
8623 4 :
8624 4 : assert_eq!(image_at_gc_horizon.len(), 10);
8625 4 : let expected_result = [
8626 4 : Bytes::from_static(b"value 0@0x10"),
8627 4 : Bytes::from_static(b"value 1@0x20"),
8628 4 : Bytes::from_static(b"value 2@0x30"),
8629 4 : Bytes::from_static(b"value 3@0x10"),
8630 4 : Bytes::from_static(b"value 4@0x10"),
8631 4 : Bytes::from_static(b"value 5@0x20"),
8632 4 : Bytes::from_static(b"value 6@0x20"),
8633 4 : Bytes::from_static(b"value 7@0x10"),
8634 4 : Bytes::from_static(b"value 8@0x10"),
8635 4 : Bytes::from_static(b"value 9@0x10"),
8636 4 : ];
8637 44 : for idx in 0..10 {
8638 40 : assert_eq!(
8639 40 : image_at_gc_horizon[idx],
8640 40 : (get_key(idx as u32), expected_result[idx].clone())
8641 40 : );
8642 4 : }
8643 4 :
8644 4 : // Check if old layers are removed / new layers have the expected LSN
8645 4 : let all_layers = inspect_and_sort(&tline, None).await;
8646 4 : assert_eq!(
8647 4 : all_layers,
8648 4 : vec![
8649 4 : // Image layer at GC horizon
8650 4 : PersistentLayerKey {
8651 4 : key_range: Key::MIN..Key::MAX,
8652 4 : lsn_range: Lsn(0x30)..Lsn(0x31),
8653 4 : is_delta: false
8654 4 : },
8655 4 : // The delta layer below the horizon
8656 4 : PersistentLayerKey {
8657 4 : key_range: get_key(3)..get_key(4),
8658 4 : lsn_range: Lsn(0x30)..Lsn(0x48),
8659 4 : is_delta: true
8660 4 : },
8661 4 : // The delta3 layer that should not be picked for the compaction
8662 4 : PersistentLayerKey {
8663 4 : key_range: get_key(8)..get_key(10),
8664 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
8665 4 : is_delta: true
8666 4 : }
8667 4 : ]
8668 4 : );
8669 4 :
8670 4 : // increase GC horizon and compact again
8671 4 : {
8672 4 : tline
8673 4 : .applied_gc_cutoff_lsn
8674 4 : .lock_for_write()
8675 4 : .store_and_unlock(Lsn(0x40))
8676 4 : .wait()
8677 4 : .await;
8678 4 : // Update GC info
8679 4 : let mut guard = tline.gc_info.write().unwrap();
8680 4 : guard.cutoffs.time = Lsn(0x40);
8681 4 : guard.cutoffs.space = Lsn(0x40);
8682 4 : }
8683 4 : tline
8684 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8685 4 : .await
8686 4 : .unwrap();
8687 4 :
8688 4 : Ok(())
8689 4 : }
8690 :
8691 : #[cfg(feature = "testing")]
8692 : #[tokio::test]
8693 4 : async fn test_neon_test_record() -> anyhow::Result<()> {
8694 4 : let harness = TenantHarness::create("test_neon_test_record").await?;
8695 4 : let (tenant, ctx) = harness.load().await;
8696 4 :
8697 68 : fn get_key(id: u32) -> Key {
8698 68 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8699 68 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8700 68 : key.field6 = id;
8701 68 : key
8702 68 : }
8703 4 :
8704 4 : let delta1 = vec![
8705 4 : (
8706 4 : get_key(1),
8707 4 : Lsn(0x20),
8708 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
8709 4 : ),
8710 4 : (
8711 4 : get_key(1),
8712 4 : Lsn(0x30),
8713 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
8714 4 : ),
8715 4 : (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
8716 4 : (
8717 4 : get_key(2),
8718 4 : Lsn(0x20),
8719 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
8720 4 : ),
8721 4 : (
8722 4 : get_key(2),
8723 4 : Lsn(0x30),
8724 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
8725 4 : ),
8726 4 : (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
8727 4 : (
8728 4 : get_key(3),
8729 4 : Lsn(0x20),
8730 4 : Value::WalRecord(NeonWalRecord::wal_clear("c")),
8731 4 : ),
8732 4 : (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
8733 4 : (
8734 4 : get_key(4),
8735 4 : Lsn(0x20),
8736 4 : Value::WalRecord(NeonWalRecord::wal_init("i")),
8737 4 : ),
8738 4 : (
8739 4 : get_key(4),
8740 4 : Lsn(0x30),
8741 4 : Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "i")),
8742 4 : ),
8743 4 : (
8744 4 : get_key(5),
8745 4 : Lsn(0x20),
8746 4 : Value::WalRecord(NeonWalRecord::wal_init("1")),
8747 4 : ),
8748 4 : (
8749 4 : get_key(5),
8750 4 : Lsn(0x30),
8751 4 : Value::WalRecord(NeonWalRecord::wal_append_conditional("j", "2")),
8752 4 : ),
8753 4 : ];
8754 4 : let image1 = vec![(get_key(1), "0x10".into())];
8755 4 :
8756 4 : let tline = tenant
8757 4 : .create_test_timeline_with_layers(
8758 4 : TIMELINE_ID,
8759 4 : Lsn(0x10),
8760 4 : DEFAULT_PG_VERSION,
8761 4 : &ctx,
8762 4 : Vec::new(), // in-memory layers
8763 4 : vec![DeltaLayerTestDesc::new_with_inferred_key_range(
8764 4 : Lsn(0x10)..Lsn(0x40),
8765 4 : delta1,
8766 4 : )], // delta layers
8767 4 : vec![(Lsn(0x10), image1)], // image layers
8768 4 : Lsn(0x50),
8769 4 : )
8770 4 : .await?;
8771 4 :
8772 4 : assert_eq!(
8773 4 : tline.get(get_key(1), Lsn(0x50), &ctx).await?,
8774 4 : Bytes::from_static(b"0x10,0x20,0x30")
8775 4 : );
8776 4 : assert_eq!(
8777 4 : tline.get(get_key(2), Lsn(0x50), &ctx).await?,
8778 4 : Bytes::from_static(b"0x10,0x20,0x30")
8779 4 : );
8780 4 :
8781 4 : // Need to remove the limit of "Neon WAL redo requires base image".
8782 4 :
8783 4 : assert_eq!(
8784 4 : tline.get(get_key(3), Lsn(0x50), &ctx).await?,
8785 4 : Bytes::from_static(b"c")
8786 4 : );
8787 4 : assert_eq!(
8788 4 : tline.get(get_key(4), Lsn(0x50), &ctx).await?,
8789 4 : Bytes::from_static(b"ij")
8790 4 : );
8791 4 :
8792 4 : // Manual testing required: currently, read errors will panic the process in debug mode. So we
8793 4 : // cannot enable this assertion in the unit test.
8794 4 : // assert!(tline.get(get_key(5), Lsn(0x50), &ctx).await.is_err());
8795 4 :
8796 4 : Ok(())
8797 4 : }
8798 :
8799 : #[tokio::test(start_paused = true)]
8800 4 : async fn test_lsn_lease() -> anyhow::Result<()> {
8801 4 : let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
8802 4 : .await
8803 4 : .unwrap()
8804 4 : .load()
8805 4 : .await;
8806 4 : // Advance to the lsn lease deadline so that GC is not blocked by
8807 4 : // initial transition into AttachedSingle.
8808 4 : tokio::time::advance(tenant.get_lsn_lease_length()).await;
8809 4 : tokio::time::resume();
8810 4 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
8811 4 :
8812 4 : let end_lsn = Lsn(0x100);
8813 4 : let image_layers = (0x20..=0x90)
8814 4 : .step_by(0x10)
8815 32 : .map(|n| {
8816 32 : (
8817 32 : Lsn(n),
8818 32 : vec![(key, test_img(&format!("data key at {:x}", n)))],
8819 32 : )
8820 32 : })
8821 4 : .collect();
8822 4 :
8823 4 : let timeline = tenant
8824 4 : .create_test_timeline_with_layers(
8825 4 : TIMELINE_ID,
8826 4 : Lsn(0x10),
8827 4 : DEFAULT_PG_VERSION,
8828 4 : &ctx,
8829 4 : Vec::new(), // in-memory layers
8830 4 : Vec::new(),
8831 4 : image_layers,
8832 4 : end_lsn,
8833 4 : )
8834 4 : .await?;
8835 4 :
8836 4 : let leased_lsns = [0x30, 0x50, 0x70];
8837 4 : let mut leases = Vec::new();
8838 12 : leased_lsns.iter().for_each(|n| {
8839 12 : leases.push(
8840 12 : timeline
8841 12 : .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
8842 12 : .expect("lease request should succeed"),
8843 12 : );
8844 12 : });
8845 4 :
8846 4 : let updated_lease_0 = timeline
8847 4 : .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
8848 4 : .expect("lease renewal should succeed");
8849 4 : assert_eq!(
8850 4 : updated_lease_0.valid_until, leases[0].valid_until,
8851 4 : " Renewing with shorter lease should not change the lease."
8852 4 : );
8853 4 :
8854 4 : let updated_lease_1 = timeline
8855 4 : .renew_lsn_lease(
8856 4 : Lsn(leased_lsns[1]),
8857 4 : timeline.get_lsn_lease_length() * 2,
8858 4 : &ctx,
8859 4 : )
8860 4 : .expect("lease renewal should succeed");
8861 4 : assert!(
8862 4 : updated_lease_1.valid_until > leases[1].valid_until,
8863 4 : "Renewing with a long lease should renew lease with later expiration time."
8864 4 : );
8865 4 :
8866 4 : // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
8867 4 : info!(
8868 4 : "applied_gc_cutoff_lsn: {}",
8869 0 : *timeline.get_applied_gc_cutoff_lsn()
8870 4 : );
8871 4 : timeline.force_set_disk_consistent_lsn(end_lsn);
8872 4 :
8873 4 : let res = tenant
8874 4 : .gc_iteration(
8875 4 : Some(TIMELINE_ID),
8876 4 : 0,
8877 4 : Duration::ZERO,
8878 4 : &CancellationToken::new(),
8879 4 : &ctx,
8880 4 : )
8881 4 : .await
8882 4 : .unwrap();
8883 4 :
8884 4 : // Keeping everything <= Lsn(0x80) b/c leases:
8885 4 : // 0/10: initdb layer
8886 4 : // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
8887 4 : assert_eq!(res.layers_needed_by_leases, 7);
8888 4 : // Keeping 0/90 b/c it is the latest layer.
8889 4 : assert_eq!(res.layers_not_updated, 1);
8890 4 : // Removed 0/80.
8891 4 : assert_eq!(res.layers_removed, 1);
8892 4 :
8893 4 : // Make lease on a already GC-ed LSN.
8894 4 : // 0/80 does not have a valid lease + is below latest_gc_cutoff
8895 4 : assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
8896 4 : timeline
8897 4 : .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
8898 4 : .expect_err("lease request on GC-ed LSN should fail");
8899 4 :
8900 4 : // Should still be able to renew a currently valid lease
8901 4 : // Assumption: original lease to is still valid for 0/50.
8902 4 : // (use `Timeline::init_lsn_lease` for testing so it always does validation)
8903 4 : timeline
8904 4 : .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
8905 4 : .expect("lease renewal with validation should succeed");
8906 4 :
8907 4 : Ok(())
8908 4 : }
8909 :
8910 : #[cfg(feature = "testing")]
8911 : #[tokio::test]
8912 4 : async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
8913 4 : test_simple_bottom_most_compaction_deltas_helper(
8914 4 : "test_simple_bottom_most_compaction_deltas_1",
8915 4 : false,
8916 4 : )
8917 4 : .await
8918 4 : }
8919 :
8920 : #[cfg(feature = "testing")]
8921 : #[tokio::test]
8922 4 : async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
8923 4 : test_simple_bottom_most_compaction_deltas_helper(
8924 4 : "test_simple_bottom_most_compaction_deltas_2",
8925 4 : true,
8926 4 : )
8927 4 : .await
8928 4 : }
8929 :
8930 : #[cfg(feature = "testing")]
8931 8 : async fn test_simple_bottom_most_compaction_deltas_helper(
8932 8 : test_name: &'static str,
8933 8 : use_delta_bottom_layer: bool,
8934 8 : ) -> anyhow::Result<()> {
8935 8 : let harness = TenantHarness::create(test_name).await?;
8936 8 : let (tenant, ctx) = harness.load().await;
8937 :
8938 552 : fn get_key(id: u32) -> Key {
8939 552 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8940 552 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8941 552 : key.field6 = id;
8942 552 : key
8943 552 : }
8944 :
8945 : // We create
8946 : // - one bottom-most image layer,
8947 : // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
8948 : // - a delta layer D2 crossing the GC horizon with data only below the horizon,
8949 : // - a delta layer D3 above the horizon.
8950 : //
8951 : // | D3 |
8952 : // | D1 |
8953 : // -| |-- gc horizon -----------------
8954 : // | | | D2 |
8955 : // --------- img layer ------------------
8956 : //
8957 : // What we should expact from this compaction is:
8958 : // | D3 |
8959 : // | Part of D1 |
8960 : // --------- img layer with D1+D2 at GC horizon------------------
8961 :
8962 : // img layer at 0x10
8963 8 : let img_layer = (0..10)
8964 80 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
8965 8 : .collect_vec();
8966 8 : // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
8967 8 : let delta4 = (0..10)
8968 80 : .map(|id| {
8969 80 : (
8970 80 : get_key(id),
8971 80 : Lsn(0x08),
8972 80 : Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
8973 80 : )
8974 80 : })
8975 8 : .collect_vec();
8976 8 :
8977 8 : let delta1 = vec![
8978 8 : (
8979 8 : get_key(1),
8980 8 : Lsn(0x20),
8981 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8982 8 : ),
8983 8 : (
8984 8 : get_key(2),
8985 8 : Lsn(0x30),
8986 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
8987 8 : ),
8988 8 : (
8989 8 : get_key(3),
8990 8 : Lsn(0x28),
8991 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
8992 8 : ),
8993 8 : (
8994 8 : get_key(3),
8995 8 : Lsn(0x30),
8996 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
8997 8 : ),
8998 8 : (
8999 8 : get_key(3),
9000 8 : Lsn(0x40),
9001 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
9002 8 : ),
9003 8 : ];
9004 8 : let delta2 = vec![
9005 8 : (
9006 8 : get_key(5),
9007 8 : Lsn(0x20),
9008 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9009 8 : ),
9010 8 : (
9011 8 : get_key(6),
9012 8 : Lsn(0x20),
9013 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9014 8 : ),
9015 8 : ];
9016 8 : let delta3 = vec![
9017 8 : (
9018 8 : get_key(8),
9019 8 : Lsn(0x48),
9020 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9021 8 : ),
9022 8 : (
9023 8 : get_key(9),
9024 8 : Lsn(0x48),
9025 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9026 8 : ),
9027 8 : ];
9028 :
9029 8 : let tline = if use_delta_bottom_layer {
9030 4 : tenant
9031 4 : .create_test_timeline_with_layers(
9032 4 : TIMELINE_ID,
9033 4 : Lsn(0x08),
9034 4 : DEFAULT_PG_VERSION,
9035 4 : &ctx,
9036 4 : Vec::new(), // in-memory layers
9037 4 : vec![
9038 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9039 4 : Lsn(0x08)..Lsn(0x10),
9040 4 : delta4,
9041 4 : ),
9042 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9043 4 : Lsn(0x20)..Lsn(0x48),
9044 4 : delta1,
9045 4 : ),
9046 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9047 4 : Lsn(0x20)..Lsn(0x48),
9048 4 : delta2,
9049 4 : ),
9050 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9051 4 : Lsn(0x48)..Lsn(0x50),
9052 4 : delta3,
9053 4 : ),
9054 4 : ], // delta layers
9055 4 : vec![], // image layers
9056 4 : Lsn(0x50),
9057 4 : )
9058 4 : .await?
9059 : } else {
9060 4 : tenant
9061 4 : .create_test_timeline_with_layers(
9062 4 : TIMELINE_ID,
9063 4 : Lsn(0x10),
9064 4 : DEFAULT_PG_VERSION,
9065 4 : &ctx,
9066 4 : Vec::new(), // in-memory layers
9067 4 : vec![
9068 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9069 4 : Lsn(0x10)..Lsn(0x48),
9070 4 : delta1,
9071 4 : ),
9072 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9073 4 : Lsn(0x10)..Lsn(0x48),
9074 4 : delta2,
9075 4 : ),
9076 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9077 4 : Lsn(0x48)..Lsn(0x50),
9078 4 : delta3,
9079 4 : ),
9080 4 : ], // delta layers
9081 4 : vec![(Lsn(0x10), img_layer)], // image layers
9082 4 : Lsn(0x50),
9083 4 : )
9084 4 : .await?
9085 : };
9086 : {
9087 8 : tline
9088 8 : .applied_gc_cutoff_lsn
9089 8 : .lock_for_write()
9090 8 : .store_and_unlock(Lsn(0x30))
9091 8 : .wait()
9092 8 : .await;
9093 : // Update GC info
9094 8 : let mut guard = tline.gc_info.write().unwrap();
9095 8 : *guard = GcInfo {
9096 8 : retain_lsns: vec![],
9097 8 : cutoffs: GcCutoffs {
9098 8 : time: Lsn(0x30),
9099 8 : space: Lsn(0x30),
9100 8 : },
9101 8 : leases: Default::default(),
9102 8 : within_ancestor_pitr: false,
9103 8 : };
9104 8 : }
9105 8 :
9106 8 : let expected_result = [
9107 8 : Bytes::from_static(b"value 0@0x10"),
9108 8 : Bytes::from_static(b"value 1@0x10@0x20"),
9109 8 : Bytes::from_static(b"value 2@0x10@0x30"),
9110 8 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
9111 8 : Bytes::from_static(b"value 4@0x10"),
9112 8 : Bytes::from_static(b"value 5@0x10@0x20"),
9113 8 : Bytes::from_static(b"value 6@0x10@0x20"),
9114 8 : Bytes::from_static(b"value 7@0x10"),
9115 8 : Bytes::from_static(b"value 8@0x10@0x48"),
9116 8 : Bytes::from_static(b"value 9@0x10@0x48"),
9117 8 : ];
9118 8 :
9119 8 : let expected_result_at_gc_horizon = [
9120 8 : Bytes::from_static(b"value 0@0x10"),
9121 8 : Bytes::from_static(b"value 1@0x10@0x20"),
9122 8 : Bytes::from_static(b"value 2@0x10@0x30"),
9123 8 : Bytes::from_static(b"value 3@0x10@0x28@0x30"),
9124 8 : Bytes::from_static(b"value 4@0x10"),
9125 8 : Bytes::from_static(b"value 5@0x10@0x20"),
9126 8 : Bytes::from_static(b"value 6@0x10@0x20"),
9127 8 : Bytes::from_static(b"value 7@0x10"),
9128 8 : Bytes::from_static(b"value 8@0x10"),
9129 8 : Bytes::from_static(b"value 9@0x10"),
9130 8 : ];
9131 :
9132 88 : for idx in 0..10 {
9133 80 : assert_eq!(
9134 80 : tline
9135 80 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9136 80 : .await
9137 80 : .unwrap(),
9138 80 : &expected_result[idx]
9139 : );
9140 80 : assert_eq!(
9141 80 : tline
9142 80 : .get(get_key(idx as u32), Lsn(0x30), &ctx)
9143 80 : .await
9144 80 : .unwrap(),
9145 80 : &expected_result_at_gc_horizon[idx]
9146 : );
9147 : }
9148 :
9149 8 : let cancel = CancellationToken::new();
9150 8 : tline
9151 8 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9152 8 : .await
9153 8 : .unwrap();
9154 :
9155 88 : for idx in 0..10 {
9156 80 : assert_eq!(
9157 80 : tline
9158 80 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9159 80 : .await
9160 80 : .unwrap(),
9161 80 : &expected_result[idx]
9162 : );
9163 80 : assert_eq!(
9164 80 : tline
9165 80 : .get(get_key(idx as u32), Lsn(0x30), &ctx)
9166 80 : .await
9167 80 : .unwrap(),
9168 80 : &expected_result_at_gc_horizon[idx]
9169 : );
9170 : }
9171 :
9172 : // increase GC horizon and compact again
9173 : {
9174 8 : tline
9175 8 : .applied_gc_cutoff_lsn
9176 8 : .lock_for_write()
9177 8 : .store_and_unlock(Lsn(0x40))
9178 8 : .wait()
9179 8 : .await;
9180 : // Update GC info
9181 8 : let mut guard = tline.gc_info.write().unwrap();
9182 8 : guard.cutoffs.time = Lsn(0x40);
9183 8 : guard.cutoffs.space = Lsn(0x40);
9184 8 : }
9185 8 : tline
9186 8 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9187 8 : .await
9188 8 : .unwrap();
9189 8 :
9190 8 : Ok(())
9191 8 : }
9192 :
9193 : #[cfg(feature = "testing")]
9194 : #[tokio::test]
9195 4 : async fn test_generate_key_retention() -> anyhow::Result<()> {
9196 4 : let harness = TenantHarness::create("test_generate_key_retention").await?;
9197 4 : let (tenant, ctx) = harness.load().await;
9198 4 : let tline = tenant
9199 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
9200 4 : .await?;
9201 4 : tline.force_advance_lsn(Lsn(0x70));
9202 4 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
9203 4 : let history = vec![
9204 4 : (
9205 4 : key,
9206 4 : Lsn(0x10),
9207 4 : Value::WalRecord(NeonWalRecord::wal_init("0x10")),
9208 4 : ),
9209 4 : (
9210 4 : key,
9211 4 : Lsn(0x20),
9212 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9213 4 : ),
9214 4 : (
9215 4 : key,
9216 4 : Lsn(0x30),
9217 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9218 4 : ),
9219 4 : (
9220 4 : key,
9221 4 : Lsn(0x40),
9222 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9223 4 : ),
9224 4 : (
9225 4 : key,
9226 4 : Lsn(0x50),
9227 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9228 4 : ),
9229 4 : (
9230 4 : key,
9231 4 : Lsn(0x60),
9232 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9233 4 : ),
9234 4 : (
9235 4 : key,
9236 4 : Lsn(0x70),
9237 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9238 4 : ),
9239 4 : (
9240 4 : key,
9241 4 : Lsn(0x80),
9242 4 : Value::Image(Bytes::copy_from_slice(
9243 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9244 4 : )),
9245 4 : ),
9246 4 : (
9247 4 : key,
9248 4 : Lsn(0x90),
9249 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9250 4 : ),
9251 4 : ];
9252 4 : let res = tline
9253 4 : .generate_key_retention(
9254 4 : key,
9255 4 : &history,
9256 4 : Lsn(0x60),
9257 4 : &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
9258 4 : 3,
9259 4 : None,
9260 4 : true,
9261 4 : )
9262 4 : .await
9263 4 : .unwrap();
9264 4 : let expected_res = KeyHistoryRetention {
9265 4 : below_horizon: vec![
9266 4 : (
9267 4 : Lsn(0x20),
9268 4 : KeyLogAtLsn(vec![(
9269 4 : Lsn(0x20),
9270 4 : Value::Image(Bytes::from_static(b"0x10;0x20")),
9271 4 : )]),
9272 4 : ),
9273 4 : (
9274 4 : Lsn(0x40),
9275 4 : KeyLogAtLsn(vec![
9276 4 : (
9277 4 : Lsn(0x30),
9278 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9279 4 : ),
9280 4 : (
9281 4 : Lsn(0x40),
9282 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9283 4 : ),
9284 4 : ]),
9285 4 : ),
9286 4 : (
9287 4 : Lsn(0x50),
9288 4 : KeyLogAtLsn(vec![(
9289 4 : Lsn(0x50),
9290 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
9291 4 : )]),
9292 4 : ),
9293 4 : (
9294 4 : Lsn(0x60),
9295 4 : KeyLogAtLsn(vec![(
9296 4 : Lsn(0x60),
9297 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9298 4 : )]),
9299 4 : ),
9300 4 : ],
9301 4 : above_horizon: KeyLogAtLsn(vec![
9302 4 : (
9303 4 : Lsn(0x70),
9304 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9305 4 : ),
9306 4 : (
9307 4 : Lsn(0x80),
9308 4 : Value::Image(Bytes::copy_from_slice(
9309 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9310 4 : )),
9311 4 : ),
9312 4 : (
9313 4 : Lsn(0x90),
9314 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9315 4 : ),
9316 4 : ]),
9317 4 : };
9318 4 : assert_eq!(res, expected_res);
9319 4 :
9320 4 : // We expect GC-compaction to run with the original GC. This would create a situation that
9321 4 : // the original GC algorithm removes some delta layers b/c there are full image coverage,
9322 4 : // therefore causing some keys to have an incomplete history below the lowest retain LSN.
9323 4 : // For example, we have
9324 4 : // ```plain
9325 4 : // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
9326 4 : // ```
9327 4 : // Now the GC horizon moves up, and we have
9328 4 : // ```plain
9329 4 : // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
9330 4 : // ```
9331 4 : // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
9332 4 : // We will end up with
9333 4 : // ```plain
9334 4 : // delta @ 0x30, image @ 0x40 (gc_horizon)
9335 4 : // ```
9336 4 : // Now we run the GC-compaction, and this key does not have a full history.
9337 4 : // We should be able to handle this partial history and drop everything before the
9338 4 : // gc_horizon image.
9339 4 :
9340 4 : let history = vec![
9341 4 : (
9342 4 : key,
9343 4 : Lsn(0x20),
9344 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9345 4 : ),
9346 4 : (
9347 4 : key,
9348 4 : Lsn(0x30),
9349 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9350 4 : ),
9351 4 : (
9352 4 : key,
9353 4 : Lsn(0x40),
9354 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
9355 4 : ),
9356 4 : (
9357 4 : key,
9358 4 : Lsn(0x50),
9359 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9360 4 : ),
9361 4 : (
9362 4 : key,
9363 4 : Lsn(0x60),
9364 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9365 4 : ),
9366 4 : (
9367 4 : key,
9368 4 : Lsn(0x70),
9369 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9370 4 : ),
9371 4 : (
9372 4 : key,
9373 4 : Lsn(0x80),
9374 4 : Value::Image(Bytes::copy_from_slice(
9375 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9376 4 : )),
9377 4 : ),
9378 4 : (
9379 4 : key,
9380 4 : Lsn(0x90),
9381 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9382 4 : ),
9383 4 : ];
9384 4 : let res = tline
9385 4 : .generate_key_retention(
9386 4 : key,
9387 4 : &history,
9388 4 : Lsn(0x60),
9389 4 : &[Lsn(0x40), Lsn(0x50)],
9390 4 : 3,
9391 4 : None,
9392 4 : true,
9393 4 : )
9394 4 : .await
9395 4 : .unwrap();
9396 4 : let expected_res = KeyHistoryRetention {
9397 4 : below_horizon: vec![
9398 4 : (
9399 4 : Lsn(0x40),
9400 4 : KeyLogAtLsn(vec![(
9401 4 : Lsn(0x40),
9402 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
9403 4 : )]),
9404 4 : ),
9405 4 : (
9406 4 : Lsn(0x50),
9407 4 : KeyLogAtLsn(vec![(
9408 4 : Lsn(0x50),
9409 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9410 4 : )]),
9411 4 : ),
9412 4 : (
9413 4 : Lsn(0x60),
9414 4 : KeyLogAtLsn(vec![(
9415 4 : Lsn(0x60),
9416 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9417 4 : )]),
9418 4 : ),
9419 4 : ],
9420 4 : above_horizon: KeyLogAtLsn(vec![
9421 4 : (
9422 4 : Lsn(0x70),
9423 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9424 4 : ),
9425 4 : (
9426 4 : Lsn(0x80),
9427 4 : Value::Image(Bytes::copy_from_slice(
9428 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9429 4 : )),
9430 4 : ),
9431 4 : (
9432 4 : Lsn(0x90),
9433 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9434 4 : ),
9435 4 : ]),
9436 4 : };
9437 4 : assert_eq!(res, expected_res);
9438 4 :
9439 4 : // In case of branch compaction, the branch itself does not have the full history, and we need to provide
9440 4 : // the ancestor image in the test case.
9441 4 :
9442 4 : let history = vec![
9443 4 : (
9444 4 : key,
9445 4 : Lsn(0x20),
9446 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9447 4 : ),
9448 4 : (
9449 4 : key,
9450 4 : Lsn(0x30),
9451 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9452 4 : ),
9453 4 : (
9454 4 : key,
9455 4 : Lsn(0x40),
9456 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9457 4 : ),
9458 4 : (
9459 4 : key,
9460 4 : Lsn(0x70),
9461 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9462 4 : ),
9463 4 : ];
9464 4 : let res = tline
9465 4 : .generate_key_retention(
9466 4 : key,
9467 4 : &history,
9468 4 : Lsn(0x60),
9469 4 : &[],
9470 4 : 3,
9471 4 : Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
9472 4 : true,
9473 4 : )
9474 4 : .await
9475 4 : .unwrap();
9476 4 : let expected_res = KeyHistoryRetention {
9477 4 : below_horizon: vec![(
9478 4 : Lsn(0x60),
9479 4 : KeyLogAtLsn(vec![(
9480 4 : Lsn(0x60),
9481 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
9482 4 : )]),
9483 4 : )],
9484 4 : above_horizon: KeyLogAtLsn(vec![(
9485 4 : Lsn(0x70),
9486 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9487 4 : )]),
9488 4 : };
9489 4 : assert_eq!(res, expected_res);
9490 4 :
9491 4 : let history = vec![
9492 4 : (
9493 4 : key,
9494 4 : Lsn(0x20),
9495 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9496 4 : ),
9497 4 : (
9498 4 : key,
9499 4 : Lsn(0x40),
9500 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9501 4 : ),
9502 4 : (
9503 4 : key,
9504 4 : Lsn(0x60),
9505 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9506 4 : ),
9507 4 : (
9508 4 : key,
9509 4 : Lsn(0x70),
9510 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9511 4 : ),
9512 4 : ];
9513 4 : let res = tline
9514 4 : .generate_key_retention(
9515 4 : key,
9516 4 : &history,
9517 4 : Lsn(0x60),
9518 4 : &[Lsn(0x30)],
9519 4 : 3,
9520 4 : Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
9521 4 : true,
9522 4 : )
9523 4 : .await
9524 4 : .unwrap();
9525 4 : let expected_res = KeyHistoryRetention {
9526 4 : below_horizon: vec![
9527 4 : (
9528 4 : Lsn(0x30),
9529 4 : KeyLogAtLsn(vec![(
9530 4 : Lsn(0x20),
9531 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9532 4 : )]),
9533 4 : ),
9534 4 : (
9535 4 : Lsn(0x60),
9536 4 : KeyLogAtLsn(vec![(
9537 4 : Lsn(0x60),
9538 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
9539 4 : )]),
9540 4 : ),
9541 4 : ],
9542 4 : above_horizon: KeyLogAtLsn(vec![(
9543 4 : Lsn(0x70),
9544 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9545 4 : )]),
9546 4 : };
9547 4 : assert_eq!(res, expected_res);
9548 4 :
9549 4 : Ok(())
9550 4 : }
9551 :
9552 : #[cfg(feature = "testing")]
9553 : #[tokio::test]
9554 4 : async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
9555 4 : let harness =
9556 4 : TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
9557 4 : let (tenant, ctx) = harness.load().await;
9558 4 :
9559 1036 : fn get_key(id: u32) -> Key {
9560 1036 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
9561 1036 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
9562 1036 : key.field6 = id;
9563 1036 : key
9564 1036 : }
9565 4 :
9566 4 : let img_layer = (0..10)
9567 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9568 4 : .collect_vec();
9569 4 :
9570 4 : let delta1 = vec![
9571 4 : (
9572 4 : get_key(1),
9573 4 : Lsn(0x20),
9574 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9575 4 : ),
9576 4 : (
9577 4 : get_key(2),
9578 4 : Lsn(0x30),
9579 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9580 4 : ),
9581 4 : (
9582 4 : get_key(3),
9583 4 : Lsn(0x28),
9584 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9585 4 : ),
9586 4 : (
9587 4 : get_key(3),
9588 4 : Lsn(0x30),
9589 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9590 4 : ),
9591 4 : (
9592 4 : get_key(3),
9593 4 : Lsn(0x40),
9594 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
9595 4 : ),
9596 4 : ];
9597 4 : let delta2 = vec![
9598 4 : (
9599 4 : get_key(5),
9600 4 : Lsn(0x20),
9601 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9602 4 : ),
9603 4 : (
9604 4 : get_key(6),
9605 4 : Lsn(0x20),
9606 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9607 4 : ),
9608 4 : ];
9609 4 : let delta3 = vec![
9610 4 : (
9611 4 : get_key(8),
9612 4 : Lsn(0x48),
9613 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9614 4 : ),
9615 4 : (
9616 4 : get_key(9),
9617 4 : Lsn(0x48),
9618 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9619 4 : ),
9620 4 : ];
9621 4 :
9622 4 : let tline = tenant
9623 4 : .create_test_timeline_with_layers(
9624 4 : TIMELINE_ID,
9625 4 : Lsn(0x10),
9626 4 : DEFAULT_PG_VERSION,
9627 4 : &ctx,
9628 4 : Vec::new(), // in-memory layers
9629 4 : vec![
9630 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
9631 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
9632 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
9633 4 : ], // delta layers
9634 4 : vec![(Lsn(0x10), img_layer)], // image layers
9635 4 : Lsn(0x50),
9636 4 : )
9637 4 : .await?;
9638 4 : {
9639 4 : tline
9640 4 : .applied_gc_cutoff_lsn
9641 4 : .lock_for_write()
9642 4 : .store_and_unlock(Lsn(0x30))
9643 4 : .wait()
9644 4 : .await;
9645 4 : // Update GC info
9646 4 : let mut guard = tline.gc_info.write().unwrap();
9647 4 : *guard = GcInfo {
9648 4 : retain_lsns: vec![
9649 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
9650 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
9651 4 : ],
9652 4 : cutoffs: GcCutoffs {
9653 4 : time: Lsn(0x30),
9654 4 : space: Lsn(0x30),
9655 4 : },
9656 4 : leases: Default::default(),
9657 4 : within_ancestor_pitr: false,
9658 4 : };
9659 4 : }
9660 4 :
9661 4 : let expected_result = [
9662 4 : Bytes::from_static(b"value 0@0x10"),
9663 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9664 4 : Bytes::from_static(b"value 2@0x10@0x30"),
9665 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
9666 4 : Bytes::from_static(b"value 4@0x10"),
9667 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9668 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9669 4 : Bytes::from_static(b"value 7@0x10"),
9670 4 : Bytes::from_static(b"value 8@0x10@0x48"),
9671 4 : Bytes::from_static(b"value 9@0x10@0x48"),
9672 4 : ];
9673 4 :
9674 4 : let expected_result_at_gc_horizon = [
9675 4 : Bytes::from_static(b"value 0@0x10"),
9676 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9677 4 : Bytes::from_static(b"value 2@0x10@0x30"),
9678 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30"),
9679 4 : Bytes::from_static(b"value 4@0x10"),
9680 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9681 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9682 4 : Bytes::from_static(b"value 7@0x10"),
9683 4 : Bytes::from_static(b"value 8@0x10"),
9684 4 : Bytes::from_static(b"value 9@0x10"),
9685 4 : ];
9686 4 :
9687 4 : let expected_result_at_lsn_20 = [
9688 4 : Bytes::from_static(b"value 0@0x10"),
9689 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9690 4 : Bytes::from_static(b"value 2@0x10"),
9691 4 : Bytes::from_static(b"value 3@0x10"),
9692 4 : Bytes::from_static(b"value 4@0x10"),
9693 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9694 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9695 4 : Bytes::from_static(b"value 7@0x10"),
9696 4 : Bytes::from_static(b"value 8@0x10"),
9697 4 : Bytes::from_static(b"value 9@0x10"),
9698 4 : ];
9699 4 :
9700 4 : let expected_result_at_lsn_10 = [
9701 4 : Bytes::from_static(b"value 0@0x10"),
9702 4 : Bytes::from_static(b"value 1@0x10"),
9703 4 : Bytes::from_static(b"value 2@0x10"),
9704 4 : Bytes::from_static(b"value 3@0x10"),
9705 4 : Bytes::from_static(b"value 4@0x10"),
9706 4 : Bytes::from_static(b"value 5@0x10"),
9707 4 : Bytes::from_static(b"value 6@0x10"),
9708 4 : Bytes::from_static(b"value 7@0x10"),
9709 4 : Bytes::from_static(b"value 8@0x10"),
9710 4 : Bytes::from_static(b"value 9@0x10"),
9711 4 : ];
9712 4 :
9713 24 : let verify_result = || async {
9714 24 : let gc_horizon = {
9715 24 : let gc_info = tline.gc_info.read().unwrap();
9716 24 : gc_info.cutoffs.time
9717 4 : };
9718 264 : for idx in 0..10 {
9719 240 : assert_eq!(
9720 240 : tline
9721 240 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9722 240 : .await
9723 240 : .unwrap(),
9724 240 : &expected_result[idx]
9725 4 : );
9726 240 : assert_eq!(
9727 240 : tline
9728 240 : .get(get_key(idx as u32), gc_horizon, &ctx)
9729 240 : .await
9730 240 : .unwrap(),
9731 240 : &expected_result_at_gc_horizon[idx]
9732 4 : );
9733 240 : assert_eq!(
9734 240 : tline
9735 240 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
9736 240 : .await
9737 240 : .unwrap(),
9738 240 : &expected_result_at_lsn_20[idx]
9739 4 : );
9740 240 : assert_eq!(
9741 240 : tline
9742 240 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
9743 240 : .await
9744 240 : .unwrap(),
9745 240 : &expected_result_at_lsn_10[idx]
9746 4 : );
9747 4 : }
9748 48 : };
9749 4 :
9750 4 : verify_result().await;
9751 4 :
9752 4 : let cancel = CancellationToken::new();
9753 4 : let mut dryrun_flags = EnumSet::new();
9754 4 : dryrun_flags.insert(CompactFlags::DryRun);
9755 4 :
9756 4 : tline
9757 4 : .compact_with_gc(
9758 4 : &cancel,
9759 4 : CompactOptions {
9760 4 : flags: dryrun_flags,
9761 4 : ..Default::default()
9762 4 : },
9763 4 : &ctx,
9764 4 : )
9765 4 : .await
9766 4 : .unwrap();
9767 4 : // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
9768 4 : // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
9769 4 : verify_result().await;
9770 4 :
9771 4 : tline
9772 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9773 4 : .await
9774 4 : .unwrap();
9775 4 : verify_result().await;
9776 4 :
9777 4 : // compact again
9778 4 : tline
9779 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9780 4 : .await
9781 4 : .unwrap();
9782 4 : verify_result().await;
9783 4 :
9784 4 : // increase GC horizon and compact again
9785 4 : {
9786 4 : tline
9787 4 : .applied_gc_cutoff_lsn
9788 4 : .lock_for_write()
9789 4 : .store_and_unlock(Lsn(0x38))
9790 4 : .wait()
9791 4 : .await;
9792 4 : // Update GC info
9793 4 : let mut guard = tline.gc_info.write().unwrap();
9794 4 : guard.cutoffs.time = Lsn(0x38);
9795 4 : guard.cutoffs.space = Lsn(0x38);
9796 4 : }
9797 4 : tline
9798 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9799 4 : .await
9800 4 : .unwrap();
9801 4 : verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
9802 4 :
9803 4 : // not increasing the GC horizon and compact again
9804 4 : tline
9805 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9806 4 : .await
9807 4 : .unwrap();
9808 4 : verify_result().await;
9809 4 :
9810 4 : Ok(())
9811 4 : }
9812 :
9813 : #[cfg(feature = "testing")]
9814 : #[tokio::test]
9815 4 : async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
9816 4 : {
9817 4 : let harness =
9818 4 : TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
9819 4 : .await?;
9820 4 : let (tenant, ctx) = harness.load().await;
9821 4 :
9822 704 : fn get_key(id: u32) -> Key {
9823 704 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
9824 704 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
9825 704 : key.field6 = id;
9826 704 : key
9827 704 : }
9828 4 :
9829 4 : let img_layer = (0..10)
9830 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9831 4 : .collect_vec();
9832 4 :
9833 4 : let delta1 = vec![
9834 4 : (
9835 4 : get_key(1),
9836 4 : Lsn(0x20),
9837 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9838 4 : ),
9839 4 : (
9840 4 : get_key(1),
9841 4 : Lsn(0x28),
9842 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9843 4 : ),
9844 4 : ];
9845 4 : let delta2 = vec![
9846 4 : (
9847 4 : get_key(1),
9848 4 : Lsn(0x30),
9849 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9850 4 : ),
9851 4 : (
9852 4 : get_key(1),
9853 4 : Lsn(0x38),
9854 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
9855 4 : ),
9856 4 : ];
9857 4 : let delta3 = vec![
9858 4 : (
9859 4 : get_key(8),
9860 4 : Lsn(0x48),
9861 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9862 4 : ),
9863 4 : (
9864 4 : get_key(9),
9865 4 : Lsn(0x48),
9866 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9867 4 : ),
9868 4 : ];
9869 4 :
9870 4 : let tline = tenant
9871 4 : .create_test_timeline_with_layers(
9872 4 : TIMELINE_ID,
9873 4 : Lsn(0x10),
9874 4 : DEFAULT_PG_VERSION,
9875 4 : &ctx,
9876 4 : Vec::new(), // in-memory layers
9877 4 : vec![
9878 4 : // delta1 and delta 2 only contain a single key but multiple updates
9879 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
9880 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
9881 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
9882 4 : ], // delta layers
9883 4 : vec![(Lsn(0x10), img_layer)], // image layers
9884 4 : Lsn(0x50),
9885 4 : )
9886 4 : .await?;
9887 4 : {
9888 4 : tline
9889 4 : .applied_gc_cutoff_lsn
9890 4 : .lock_for_write()
9891 4 : .store_and_unlock(Lsn(0x30))
9892 4 : .wait()
9893 4 : .await;
9894 4 : // Update GC info
9895 4 : let mut guard = tline.gc_info.write().unwrap();
9896 4 : *guard = GcInfo {
9897 4 : retain_lsns: vec![
9898 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
9899 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
9900 4 : ],
9901 4 : cutoffs: GcCutoffs {
9902 4 : time: Lsn(0x30),
9903 4 : space: Lsn(0x30),
9904 4 : },
9905 4 : leases: Default::default(),
9906 4 : within_ancestor_pitr: false,
9907 4 : };
9908 4 : }
9909 4 :
9910 4 : let expected_result = [
9911 4 : Bytes::from_static(b"value 0@0x10"),
9912 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
9913 4 : Bytes::from_static(b"value 2@0x10"),
9914 4 : Bytes::from_static(b"value 3@0x10"),
9915 4 : Bytes::from_static(b"value 4@0x10"),
9916 4 : Bytes::from_static(b"value 5@0x10"),
9917 4 : Bytes::from_static(b"value 6@0x10"),
9918 4 : Bytes::from_static(b"value 7@0x10"),
9919 4 : Bytes::from_static(b"value 8@0x10@0x48"),
9920 4 : Bytes::from_static(b"value 9@0x10@0x48"),
9921 4 : ];
9922 4 :
9923 4 : let expected_result_at_gc_horizon = [
9924 4 : Bytes::from_static(b"value 0@0x10"),
9925 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
9926 4 : Bytes::from_static(b"value 2@0x10"),
9927 4 : Bytes::from_static(b"value 3@0x10"),
9928 4 : Bytes::from_static(b"value 4@0x10"),
9929 4 : Bytes::from_static(b"value 5@0x10"),
9930 4 : Bytes::from_static(b"value 6@0x10"),
9931 4 : Bytes::from_static(b"value 7@0x10"),
9932 4 : Bytes::from_static(b"value 8@0x10"),
9933 4 : Bytes::from_static(b"value 9@0x10"),
9934 4 : ];
9935 4 :
9936 4 : let expected_result_at_lsn_20 = [
9937 4 : Bytes::from_static(b"value 0@0x10"),
9938 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9939 4 : Bytes::from_static(b"value 2@0x10"),
9940 4 : Bytes::from_static(b"value 3@0x10"),
9941 4 : Bytes::from_static(b"value 4@0x10"),
9942 4 : Bytes::from_static(b"value 5@0x10"),
9943 4 : Bytes::from_static(b"value 6@0x10"),
9944 4 : Bytes::from_static(b"value 7@0x10"),
9945 4 : Bytes::from_static(b"value 8@0x10"),
9946 4 : Bytes::from_static(b"value 9@0x10"),
9947 4 : ];
9948 4 :
9949 4 : let expected_result_at_lsn_10 = [
9950 4 : Bytes::from_static(b"value 0@0x10"),
9951 4 : Bytes::from_static(b"value 1@0x10"),
9952 4 : Bytes::from_static(b"value 2@0x10"),
9953 4 : Bytes::from_static(b"value 3@0x10"),
9954 4 : Bytes::from_static(b"value 4@0x10"),
9955 4 : Bytes::from_static(b"value 5@0x10"),
9956 4 : Bytes::from_static(b"value 6@0x10"),
9957 4 : Bytes::from_static(b"value 7@0x10"),
9958 4 : Bytes::from_static(b"value 8@0x10"),
9959 4 : Bytes::from_static(b"value 9@0x10"),
9960 4 : ];
9961 4 :
9962 16 : let verify_result = || async {
9963 16 : let gc_horizon = {
9964 16 : let gc_info = tline.gc_info.read().unwrap();
9965 16 : gc_info.cutoffs.time
9966 4 : };
9967 176 : for idx in 0..10 {
9968 160 : assert_eq!(
9969 160 : tline
9970 160 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9971 160 : .await
9972 160 : .unwrap(),
9973 160 : &expected_result[idx]
9974 4 : );
9975 160 : assert_eq!(
9976 160 : tline
9977 160 : .get(get_key(idx as u32), gc_horizon, &ctx)
9978 160 : .await
9979 160 : .unwrap(),
9980 160 : &expected_result_at_gc_horizon[idx]
9981 4 : );
9982 160 : assert_eq!(
9983 160 : tline
9984 160 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
9985 160 : .await
9986 160 : .unwrap(),
9987 160 : &expected_result_at_lsn_20[idx]
9988 4 : );
9989 160 : assert_eq!(
9990 160 : tline
9991 160 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
9992 160 : .await
9993 160 : .unwrap(),
9994 160 : &expected_result_at_lsn_10[idx]
9995 4 : );
9996 4 : }
9997 32 : };
9998 4 :
9999 4 : verify_result().await;
10000 4 :
10001 4 : let cancel = CancellationToken::new();
10002 4 : let mut dryrun_flags = EnumSet::new();
10003 4 : dryrun_flags.insert(CompactFlags::DryRun);
10004 4 :
10005 4 : tline
10006 4 : .compact_with_gc(
10007 4 : &cancel,
10008 4 : CompactOptions {
10009 4 : flags: dryrun_flags,
10010 4 : ..Default::default()
10011 4 : },
10012 4 : &ctx,
10013 4 : )
10014 4 : .await
10015 4 : .unwrap();
10016 4 : // We expect layer map to be the same b/c the dry run flag, but we don't know whether there will be other background jobs
10017 4 : // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
10018 4 : verify_result().await;
10019 4 :
10020 4 : tline
10021 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
10022 4 : .await
10023 4 : .unwrap();
10024 4 : verify_result().await;
10025 4 :
10026 4 : // compact again
10027 4 : tline
10028 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
10029 4 : .await
10030 4 : .unwrap();
10031 4 : verify_result().await;
10032 4 :
10033 4 : Ok(())
10034 4 : }
10035 :
10036 : #[cfg(feature = "testing")]
10037 : #[tokio::test]
10038 4 : async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
10039 4 : use models::CompactLsnRange;
10040 4 :
10041 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
10042 4 : let (tenant, ctx) = harness.load().await;
10043 4 :
10044 332 : fn get_key(id: u32) -> Key {
10045 332 : let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
10046 332 : key.field6 = id;
10047 332 : key
10048 332 : }
10049 4 :
10050 4 : let img_layer = (0..10)
10051 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10052 4 : .collect_vec();
10053 4 :
10054 4 : let delta1 = vec![
10055 4 : (
10056 4 : get_key(1),
10057 4 : Lsn(0x20),
10058 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10059 4 : ),
10060 4 : (
10061 4 : get_key(2),
10062 4 : Lsn(0x30),
10063 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
10064 4 : ),
10065 4 : (
10066 4 : get_key(3),
10067 4 : Lsn(0x28),
10068 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
10069 4 : ),
10070 4 : (
10071 4 : get_key(3),
10072 4 : Lsn(0x30),
10073 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
10074 4 : ),
10075 4 : (
10076 4 : get_key(3),
10077 4 : Lsn(0x40),
10078 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
10079 4 : ),
10080 4 : ];
10081 4 : let delta2 = vec![
10082 4 : (
10083 4 : get_key(5),
10084 4 : Lsn(0x20),
10085 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10086 4 : ),
10087 4 : (
10088 4 : get_key(6),
10089 4 : Lsn(0x20),
10090 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10091 4 : ),
10092 4 : ];
10093 4 : let delta3 = vec![
10094 4 : (
10095 4 : get_key(8),
10096 4 : Lsn(0x48),
10097 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10098 4 : ),
10099 4 : (
10100 4 : get_key(9),
10101 4 : Lsn(0x48),
10102 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10103 4 : ),
10104 4 : ];
10105 4 :
10106 4 : let parent_tline = tenant
10107 4 : .create_test_timeline_with_layers(
10108 4 : TIMELINE_ID,
10109 4 : Lsn(0x10),
10110 4 : DEFAULT_PG_VERSION,
10111 4 : &ctx,
10112 4 : vec![], // in-memory layers
10113 4 : vec![], // delta layers
10114 4 : vec![(Lsn(0x18), img_layer)], // image layers
10115 4 : Lsn(0x18),
10116 4 : )
10117 4 : .await?;
10118 4 :
10119 4 : parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
10120 4 :
10121 4 : let branch_tline = tenant
10122 4 : .branch_timeline_test_with_layers(
10123 4 : &parent_tline,
10124 4 : NEW_TIMELINE_ID,
10125 4 : Some(Lsn(0x18)),
10126 4 : &ctx,
10127 4 : vec![
10128 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
10129 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
10130 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
10131 4 : ], // delta layers
10132 4 : vec![], // image layers
10133 4 : Lsn(0x50),
10134 4 : )
10135 4 : .await?;
10136 4 :
10137 4 : branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
10138 4 :
10139 4 : {
10140 4 : parent_tline
10141 4 : .applied_gc_cutoff_lsn
10142 4 : .lock_for_write()
10143 4 : .store_and_unlock(Lsn(0x10))
10144 4 : .wait()
10145 4 : .await;
10146 4 : // Update GC info
10147 4 : let mut guard = parent_tline.gc_info.write().unwrap();
10148 4 : *guard = GcInfo {
10149 4 : retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
10150 4 : cutoffs: GcCutoffs {
10151 4 : time: Lsn(0x10),
10152 4 : space: Lsn(0x10),
10153 4 : },
10154 4 : leases: Default::default(),
10155 4 : within_ancestor_pitr: false,
10156 4 : };
10157 4 : }
10158 4 :
10159 4 : {
10160 4 : branch_tline
10161 4 : .applied_gc_cutoff_lsn
10162 4 : .lock_for_write()
10163 4 : .store_and_unlock(Lsn(0x50))
10164 4 : .wait()
10165 4 : .await;
10166 4 : // Update GC info
10167 4 : let mut guard = branch_tline.gc_info.write().unwrap();
10168 4 : *guard = GcInfo {
10169 4 : retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
10170 4 : cutoffs: GcCutoffs {
10171 4 : time: Lsn(0x50),
10172 4 : space: Lsn(0x50),
10173 4 : },
10174 4 : leases: Default::default(),
10175 4 : within_ancestor_pitr: false,
10176 4 : };
10177 4 : }
10178 4 :
10179 4 : let expected_result_at_gc_horizon = [
10180 4 : Bytes::from_static(b"value 0@0x10"),
10181 4 : Bytes::from_static(b"value 1@0x10@0x20"),
10182 4 : Bytes::from_static(b"value 2@0x10@0x30"),
10183 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
10184 4 : Bytes::from_static(b"value 4@0x10"),
10185 4 : Bytes::from_static(b"value 5@0x10@0x20"),
10186 4 : Bytes::from_static(b"value 6@0x10@0x20"),
10187 4 : Bytes::from_static(b"value 7@0x10"),
10188 4 : Bytes::from_static(b"value 8@0x10@0x48"),
10189 4 : Bytes::from_static(b"value 9@0x10@0x48"),
10190 4 : ];
10191 4 :
10192 4 : let expected_result_at_lsn_40 = [
10193 4 : Bytes::from_static(b"value 0@0x10"),
10194 4 : Bytes::from_static(b"value 1@0x10@0x20"),
10195 4 : Bytes::from_static(b"value 2@0x10@0x30"),
10196 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
10197 4 : Bytes::from_static(b"value 4@0x10"),
10198 4 : Bytes::from_static(b"value 5@0x10@0x20"),
10199 4 : Bytes::from_static(b"value 6@0x10@0x20"),
10200 4 : Bytes::from_static(b"value 7@0x10"),
10201 4 : Bytes::from_static(b"value 8@0x10"),
10202 4 : Bytes::from_static(b"value 9@0x10"),
10203 4 : ];
10204 4 :
10205 12 : let verify_result = || async {
10206 132 : for idx in 0..10 {
10207 120 : assert_eq!(
10208 120 : branch_tline
10209 120 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
10210 120 : .await
10211 120 : .unwrap(),
10212 120 : &expected_result_at_gc_horizon[idx]
10213 4 : );
10214 120 : assert_eq!(
10215 120 : branch_tline
10216 120 : .get(get_key(idx as u32), Lsn(0x40), &ctx)
10217 120 : .await
10218 120 : .unwrap(),
10219 120 : &expected_result_at_lsn_40[idx]
10220 4 : );
10221 4 : }
10222 24 : };
10223 4 :
10224 4 : verify_result().await;
10225 4 :
10226 4 : let cancel = CancellationToken::new();
10227 4 : branch_tline
10228 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
10229 4 : .await
10230 4 : .unwrap();
10231 4 :
10232 4 : verify_result().await;
10233 4 :
10234 4 : // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
10235 4 : // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
10236 4 : branch_tline
10237 4 : .compact_with_gc(
10238 4 : &cancel,
10239 4 : CompactOptions {
10240 4 : compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
10241 4 : ..Default::default()
10242 4 : },
10243 4 : &ctx,
10244 4 : )
10245 4 : .await
10246 4 : .unwrap();
10247 4 :
10248 4 : verify_result().await;
10249 4 :
10250 4 : Ok(())
10251 4 : }
10252 :
10253 : // Regression test for https://github.com/neondatabase/neon/issues/9012
10254 : // Create an image arrangement where we have to read at different LSN ranges
10255 : // from a delta layer. This is achieved by overlapping an image layer on top of
10256 : // a delta layer. Like so:
10257 : //
10258 : // A B
10259 : // +----------------+ -> delta_layer
10260 : // | | ^ lsn
10261 : // | =========|-> nested_image_layer |
10262 : // | C | |
10263 : // +----------------+ |
10264 : // ======== -> baseline_image_layer +-------> key
10265 : //
10266 : //
10267 : // When querying the key range [A, B) we need to read at different LSN ranges
10268 : // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
10269 : #[cfg(feature = "testing")]
10270 : #[tokio::test]
10271 4 : async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
10272 4 : let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
10273 4 : let (tenant, ctx) = harness.load().await;
10274 4 :
10275 4 : let will_init_keys = [2, 6];
10276 88 : fn get_key(id: u32) -> Key {
10277 88 : let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
10278 88 : key.field6 = id;
10279 88 : key
10280 88 : }
10281 4 :
10282 4 : let mut expected_key_values = HashMap::new();
10283 4 :
10284 4 : let baseline_image_layer_lsn = Lsn(0x10);
10285 4 : let mut baseline_img_layer = Vec::new();
10286 24 : for i in 0..5 {
10287 20 : let key = get_key(i);
10288 20 : let value = format!("value {i}@{baseline_image_layer_lsn}");
10289 20 :
10290 20 : let removed = expected_key_values.insert(key, value.clone());
10291 20 : assert!(removed.is_none());
10292 4 :
10293 20 : baseline_img_layer.push((key, Bytes::from(value)));
10294 4 : }
10295 4 :
10296 4 : let nested_image_layer_lsn = Lsn(0x50);
10297 4 : let mut nested_img_layer = Vec::new();
10298 24 : for i in 5..10 {
10299 20 : let key = get_key(i);
10300 20 : let value = format!("value {i}@{nested_image_layer_lsn}");
10301 20 :
10302 20 : let removed = expected_key_values.insert(key, value.clone());
10303 20 : assert!(removed.is_none());
10304 4 :
10305 20 : nested_img_layer.push((key, Bytes::from(value)));
10306 4 : }
10307 4 :
10308 4 : let mut delta_layer_spec = Vec::default();
10309 4 : let delta_layer_start_lsn = Lsn(0x20);
10310 4 : let mut delta_layer_end_lsn = delta_layer_start_lsn;
10311 4 :
10312 44 : for i in 0..10 {
10313 40 : let key = get_key(i);
10314 40 : let key_in_nested = nested_img_layer
10315 40 : .iter()
10316 160 : .any(|(key_with_img, _)| *key_with_img == key);
10317 40 : let lsn = {
10318 40 : if key_in_nested {
10319 20 : Lsn(nested_image_layer_lsn.0 + 0x10)
10320 4 : } else {
10321 20 : delta_layer_start_lsn
10322 4 : }
10323 4 : };
10324 4 :
10325 40 : let will_init = will_init_keys.contains(&i);
10326 40 : if will_init {
10327 8 : delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
10328 8 :
10329 8 : expected_key_values.insert(key, "".to_string());
10330 32 : } else {
10331 32 : let delta = format!("@{lsn}");
10332 32 : delta_layer_spec.push((
10333 32 : key,
10334 32 : lsn,
10335 32 : Value::WalRecord(NeonWalRecord::wal_append(&delta)),
10336 32 : ));
10337 32 :
10338 32 : expected_key_values
10339 32 : .get_mut(&key)
10340 32 : .expect("An image exists for each key")
10341 32 : .push_str(delta.as_str());
10342 32 : }
10343 40 : delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
10344 4 : }
10345 4 :
10346 4 : delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
10347 4 :
10348 4 : assert!(
10349 4 : nested_image_layer_lsn > delta_layer_start_lsn
10350 4 : && nested_image_layer_lsn < delta_layer_end_lsn
10351 4 : );
10352 4 :
10353 4 : let tline = tenant
10354 4 : .create_test_timeline_with_layers(
10355 4 : TIMELINE_ID,
10356 4 : baseline_image_layer_lsn,
10357 4 : DEFAULT_PG_VERSION,
10358 4 : &ctx,
10359 4 : vec![], // in-memory layers
10360 4 : vec![DeltaLayerTestDesc::new_with_inferred_key_range(
10361 4 : delta_layer_start_lsn..delta_layer_end_lsn,
10362 4 : delta_layer_spec,
10363 4 : )], // delta layers
10364 4 : vec![
10365 4 : (baseline_image_layer_lsn, baseline_img_layer),
10366 4 : (nested_image_layer_lsn, nested_img_layer),
10367 4 : ], // image layers
10368 4 : delta_layer_end_lsn,
10369 4 : )
10370 4 : .await?;
10371 4 :
10372 4 : let keyspace = KeySpace::single(get_key(0)..get_key(10));
10373 4 : let results = tline
10374 4 : .get_vectored(
10375 4 : keyspace,
10376 4 : delta_layer_end_lsn,
10377 4 : IoConcurrency::sequential(),
10378 4 : &ctx,
10379 4 : )
10380 4 : .await
10381 4 : .expect("No vectored errors");
10382 44 : for (key, res) in results {
10383 40 : let value = res.expect("No key errors");
10384 40 : let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
10385 40 : assert_eq!(value, Bytes::from(expected_value));
10386 4 : }
10387 4 :
10388 4 : Ok(())
10389 4 : }
10390 :
10391 : #[cfg(feature = "testing")]
10392 : #[tokio::test]
10393 4 : async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
10394 4 : let harness =
10395 4 : TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
10396 4 : let (tenant, ctx) = harness.load().await;
10397 4 :
10398 4 : let will_init_keys = [2, 6];
10399 128 : fn get_key(id: u32) -> Key {
10400 128 : let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
10401 128 : key.field6 = id;
10402 128 : key
10403 128 : }
10404 4 :
10405 4 : let mut expected_key_values = HashMap::new();
10406 4 :
10407 4 : let baseline_image_layer_lsn = Lsn(0x10);
10408 4 : let mut baseline_img_layer = Vec::new();
10409 24 : for i in 0..5 {
10410 20 : let key = get_key(i);
10411 20 : let value = format!("value {i}@{baseline_image_layer_lsn}");
10412 20 :
10413 20 : let removed = expected_key_values.insert(key, value.clone());
10414 20 : assert!(removed.is_none());
10415 4 :
10416 20 : baseline_img_layer.push((key, Bytes::from(value)));
10417 4 : }
10418 4 :
10419 4 : let nested_image_layer_lsn = Lsn(0x50);
10420 4 : let mut nested_img_layer = Vec::new();
10421 24 : for i in 5..10 {
10422 20 : let key = get_key(i);
10423 20 : let value = format!("value {i}@{nested_image_layer_lsn}");
10424 20 :
10425 20 : let removed = expected_key_values.insert(key, value.clone());
10426 20 : assert!(removed.is_none());
10427 4 :
10428 20 : nested_img_layer.push((key, Bytes::from(value)));
10429 4 : }
10430 4 :
10431 4 : let frozen_layer = {
10432 4 : let lsn_range = Lsn(0x40)..Lsn(0x60);
10433 4 : let mut data = Vec::new();
10434 44 : for i in 0..10 {
10435 40 : let key = get_key(i);
10436 40 : let key_in_nested = nested_img_layer
10437 40 : .iter()
10438 160 : .any(|(key_with_img, _)| *key_with_img == key);
10439 40 : let lsn = {
10440 40 : if key_in_nested {
10441 20 : Lsn(nested_image_layer_lsn.0 + 5)
10442 4 : } else {
10443 20 : lsn_range.start
10444 4 : }
10445 4 : };
10446 4 :
10447 40 : let will_init = will_init_keys.contains(&i);
10448 40 : if will_init {
10449 8 : data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
10450 8 :
10451 8 : expected_key_values.insert(key, "".to_string());
10452 32 : } else {
10453 32 : let delta = format!("@{lsn}");
10454 32 : data.push((
10455 32 : key,
10456 32 : lsn,
10457 32 : Value::WalRecord(NeonWalRecord::wal_append(&delta)),
10458 32 : ));
10459 32 :
10460 32 : expected_key_values
10461 32 : .get_mut(&key)
10462 32 : .expect("An image exists for each key")
10463 32 : .push_str(delta.as_str());
10464 32 : }
10465 4 : }
10466 4 :
10467 4 : InMemoryLayerTestDesc {
10468 4 : lsn_range,
10469 4 : is_open: false,
10470 4 : data,
10471 4 : }
10472 4 : };
10473 4 :
10474 4 : let (open_layer, last_record_lsn) = {
10475 4 : let start_lsn = Lsn(0x70);
10476 4 : let mut data = Vec::new();
10477 4 : let mut end_lsn = Lsn(0);
10478 44 : for i in 0..10 {
10479 40 : let key = get_key(i);
10480 40 : let lsn = Lsn(start_lsn.0 + i as u64);
10481 40 : let delta = format!("@{lsn}");
10482 40 : data.push((
10483 40 : key,
10484 40 : lsn,
10485 40 : Value::WalRecord(NeonWalRecord::wal_append(&delta)),
10486 40 : ));
10487 40 :
10488 40 : expected_key_values
10489 40 : .get_mut(&key)
10490 40 : .expect("An image exists for each key")
10491 40 : .push_str(delta.as_str());
10492 40 :
10493 40 : end_lsn = std::cmp::max(end_lsn, lsn);
10494 40 : }
10495 4 :
10496 4 : (
10497 4 : InMemoryLayerTestDesc {
10498 4 : lsn_range: start_lsn..Lsn::MAX,
10499 4 : is_open: true,
10500 4 : data,
10501 4 : },
10502 4 : end_lsn,
10503 4 : )
10504 4 : };
10505 4 :
10506 4 : assert!(
10507 4 : nested_image_layer_lsn > frozen_layer.lsn_range.start
10508 4 : && nested_image_layer_lsn < frozen_layer.lsn_range.end
10509 4 : );
10510 4 :
10511 4 : let tline = tenant
10512 4 : .create_test_timeline_with_layers(
10513 4 : TIMELINE_ID,
10514 4 : baseline_image_layer_lsn,
10515 4 : DEFAULT_PG_VERSION,
10516 4 : &ctx,
10517 4 : vec![open_layer, frozen_layer], // in-memory layers
10518 4 : Vec::new(), // delta layers
10519 4 : vec![
10520 4 : (baseline_image_layer_lsn, baseline_img_layer),
10521 4 : (nested_image_layer_lsn, nested_img_layer),
10522 4 : ], // image layers
10523 4 : last_record_lsn,
10524 4 : )
10525 4 : .await?;
10526 4 :
10527 4 : let keyspace = KeySpace::single(get_key(0)..get_key(10));
10528 4 : let results = tline
10529 4 : .get_vectored(keyspace, last_record_lsn, IoConcurrency::sequential(), &ctx)
10530 4 : .await
10531 4 : .expect("No vectored errors");
10532 44 : for (key, res) in results {
10533 40 : let value = res.expect("No key errors");
10534 40 : let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
10535 40 : assert_eq!(value, Bytes::from(expected_value.clone()));
10536 4 :
10537 40 : tracing::info!("key={key} value={expected_value}");
10538 4 : }
10539 4 :
10540 4 : Ok(())
10541 4 : }
10542 :
10543 428 : fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
10544 428 : (
10545 428 : k1.is_delta,
10546 428 : k1.key_range.start,
10547 428 : k1.key_range.end,
10548 428 : k1.lsn_range.start,
10549 428 : k1.lsn_range.end,
10550 428 : )
10551 428 : .cmp(&(
10552 428 : k2.is_delta,
10553 428 : k2.key_range.start,
10554 428 : k2.key_range.end,
10555 428 : k2.lsn_range.start,
10556 428 : k2.lsn_range.end,
10557 428 : ))
10558 428 : }
10559 :
10560 48 : async fn inspect_and_sort(
10561 48 : tline: &Arc<Timeline>,
10562 48 : filter: Option<std::ops::Range<Key>>,
10563 48 : ) -> Vec<PersistentLayerKey> {
10564 48 : let mut all_layers = tline.inspect_historic_layers().await.unwrap();
10565 48 : if let Some(filter) = filter {
10566 216 : all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
10567 44 : }
10568 48 : all_layers.sort_by(sort_layer_key);
10569 48 : all_layers
10570 48 : }
10571 :
10572 : #[cfg(feature = "testing")]
10573 44 : fn check_layer_map_key_eq(
10574 44 : mut left: Vec<PersistentLayerKey>,
10575 44 : mut right: Vec<PersistentLayerKey>,
10576 44 : ) {
10577 44 : left.sort_by(sort_layer_key);
10578 44 : right.sort_by(sort_layer_key);
10579 44 : if left != right {
10580 0 : eprintln!("---LEFT---");
10581 0 : for left in left.iter() {
10582 0 : eprintln!("{}", left);
10583 0 : }
10584 0 : eprintln!("---RIGHT---");
10585 0 : for right in right.iter() {
10586 0 : eprintln!("{}", right);
10587 0 : }
10588 0 : assert_eq!(left, right);
10589 44 : }
10590 44 : }
10591 :
10592 : #[cfg(feature = "testing")]
10593 : #[tokio::test]
10594 4 : async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
10595 4 : let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
10596 4 : let (tenant, ctx) = harness.load().await;
10597 4 :
10598 364 : fn get_key(id: u32) -> Key {
10599 364 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
10600 364 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
10601 364 : key.field6 = id;
10602 364 : key
10603 364 : }
10604 4 :
10605 4 : // img layer at 0x10
10606 4 : let img_layer = (0..10)
10607 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10608 4 : .collect_vec();
10609 4 :
10610 4 : let delta1 = vec![
10611 4 : (
10612 4 : get_key(1),
10613 4 : Lsn(0x20),
10614 4 : Value::Image(Bytes::from("value 1@0x20")),
10615 4 : ),
10616 4 : (
10617 4 : get_key(2),
10618 4 : Lsn(0x30),
10619 4 : Value::Image(Bytes::from("value 2@0x30")),
10620 4 : ),
10621 4 : (
10622 4 : get_key(3),
10623 4 : Lsn(0x40),
10624 4 : Value::Image(Bytes::from("value 3@0x40")),
10625 4 : ),
10626 4 : ];
10627 4 : let delta2 = vec![
10628 4 : (
10629 4 : get_key(5),
10630 4 : Lsn(0x20),
10631 4 : Value::Image(Bytes::from("value 5@0x20")),
10632 4 : ),
10633 4 : (
10634 4 : get_key(6),
10635 4 : Lsn(0x20),
10636 4 : Value::Image(Bytes::from("value 6@0x20")),
10637 4 : ),
10638 4 : ];
10639 4 : let delta3 = vec![
10640 4 : (
10641 4 : get_key(8),
10642 4 : Lsn(0x48),
10643 4 : Value::Image(Bytes::from("value 8@0x48")),
10644 4 : ),
10645 4 : (
10646 4 : get_key(9),
10647 4 : Lsn(0x48),
10648 4 : Value::Image(Bytes::from("value 9@0x48")),
10649 4 : ),
10650 4 : ];
10651 4 :
10652 4 : let tline = tenant
10653 4 : .create_test_timeline_with_layers(
10654 4 : TIMELINE_ID,
10655 4 : Lsn(0x10),
10656 4 : DEFAULT_PG_VERSION,
10657 4 : &ctx,
10658 4 : vec![], // in-memory layers
10659 4 : vec![
10660 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
10661 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
10662 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
10663 4 : ], // delta layers
10664 4 : vec![(Lsn(0x10), img_layer)], // image layers
10665 4 : Lsn(0x50),
10666 4 : )
10667 4 : .await?;
10668 4 :
10669 4 : {
10670 4 : tline
10671 4 : .applied_gc_cutoff_lsn
10672 4 : .lock_for_write()
10673 4 : .store_and_unlock(Lsn(0x30))
10674 4 : .wait()
10675 4 : .await;
10676 4 : // Update GC info
10677 4 : let mut guard = tline.gc_info.write().unwrap();
10678 4 : *guard = GcInfo {
10679 4 : retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
10680 4 : cutoffs: GcCutoffs {
10681 4 : time: Lsn(0x30),
10682 4 : space: Lsn(0x30),
10683 4 : },
10684 4 : leases: Default::default(),
10685 4 : within_ancestor_pitr: false,
10686 4 : };
10687 4 : }
10688 4 :
10689 4 : let cancel = CancellationToken::new();
10690 4 :
10691 4 : // Do a partial compaction on key range 0..2
10692 4 : tline
10693 4 : .compact_with_gc(
10694 4 : &cancel,
10695 4 : CompactOptions {
10696 4 : flags: EnumSet::new(),
10697 4 : compact_key_range: Some((get_key(0)..get_key(2)).into()),
10698 4 : ..Default::default()
10699 4 : },
10700 4 : &ctx,
10701 4 : )
10702 4 : .await
10703 4 : .unwrap();
10704 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10705 4 : check_layer_map_key_eq(
10706 4 : all_layers,
10707 4 : vec![
10708 4 : // newly-generated image layer for the partial compaction range 0-2
10709 4 : PersistentLayerKey {
10710 4 : key_range: get_key(0)..get_key(2),
10711 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10712 4 : is_delta: false,
10713 4 : },
10714 4 : PersistentLayerKey {
10715 4 : key_range: get_key(0)..get_key(10),
10716 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10717 4 : is_delta: false,
10718 4 : },
10719 4 : // delta1 is split and the second part is rewritten
10720 4 : PersistentLayerKey {
10721 4 : key_range: get_key(2)..get_key(4),
10722 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10723 4 : is_delta: true,
10724 4 : },
10725 4 : PersistentLayerKey {
10726 4 : key_range: get_key(5)..get_key(7),
10727 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10728 4 : is_delta: true,
10729 4 : },
10730 4 : PersistentLayerKey {
10731 4 : key_range: get_key(8)..get_key(10),
10732 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10733 4 : is_delta: true,
10734 4 : },
10735 4 : ],
10736 4 : );
10737 4 :
10738 4 : // Do a partial compaction on key range 2..4
10739 4 : tline
10740 4 : .compact_with_gc(
10741 4 : &cancel,
10742 4 : CompactOptions {
10743 4 : flags: EnumSet::new(),
10744 4 : compact_key_range: Some((get_key(2)..get_key(4)).into()),
10745 4 : ..Default::default()
10746 4 : },
10747 4 : &ctx,
10748 4 : )
10749 4 : .await
10750 4 : .unwrap();
10751 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10752 4 : check_layer_map_key_eq(
10753 4 : all_layers,
10754 4 : vec![
10755 4 : PersistentLayerKey {
10756 4 : key_range: get_key(0)..get_key(2),
10757 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10758 4 : is_delta: false,
10759 4 : },
10760 4 : PersistentLayerKey {
10761 4 : key_range: get_key(0)..get_key(10),
10762 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10763 4 : is_delta: false,
10764 4 : },
10765 4 : // image layer generated for the compaction range 2-4
10766 4 : PersistentLayerKey {
10767 4 : key_range: get_key(2)..get_key(4),
10768 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10769 4 : is_delta: false,
10770 4 : },
10771 4 : // we have key2/key3 above the retain_lsn, so we still need this delta layer
10772 4 : PersistentLayerKey {
10773 4 : key_range: get_key(2)..get_key(4),
10774 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10775 4 : is_delta: true,
10776 4 : },
10777 4 : PersistentLayerKey {
10778 4 : key_range: get_key(5)..get_key(7),
10779 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10780 4 : is_delta: true,
10781 4 : },
10782 4 : PersistentLayerKey {
10783 4 : key_range: get_key(8)..get_key(10),
10784 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10785 4 : is_delta: true,
10786 4 : },
10787 4 : ],
10788 4 : );
10789 4 :
10790 4 : // Do a partial compaction on key range 4..9
10791 4 : tline
10792 4 : .compact_with_gc(
10793 4 : &cancel,
10794 4 : CompactOptions {
10795 4 : flags: EnumSet::new(),
10796 4 : compact_key_range: Some((get_key(4)..get_key(9)).into()),
10797 4 : ..Default::default()
10798 4 : },
10799 4 : &ctx,
10800 4 : )
10801 4 : .await
10802 4 : .unwrap();
10803 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10804 4 : check_layer_map_key_eq(
10805 4 : all_layers,
10806 4 : vec![
10807 4 : PersistentLayerKey {
10808 4 : key_range: get_key(0)..get_key(2),
10809 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10810 4 : is_delta: false,
10811 4 : },
10812 4 : PersistentLayerKey {
10813 4 : key_range: get_key(0)..get_key(10),
10814 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10815 4 : is_delta: false,
10816 4 : },
10817 4 : PersistentLayerKey {
10818 4 : key_range: get_key(2)..get_key(4),
10819 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10820 4 : is_delta: false,
10821 4 : },
10822 4 : PersistentLayerKey {
10823 4 : key_range: get_key(2)..get_key(4),
10824 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10825 4 : is_delta: true,
10826 4 : },
10827 4 : // image layer generated for this compaction range
10828 4 : PersistentLayerKey {
10829 4 : key_range: get_key(4)..get_key(9),
10830 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10831 4 : is_delta: false,
10832 4 : },
10833 4 : PersistentLayerKey {
10834 4 : key_range: get_key(8)..get_key(10),
10835 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10836 4 : is_delta: true,
10837 4 : },
10838 4 : ],
10839 4 : );
10840 4 :
10841 4 : // Do a partial compaction on key range 9..10
10842 4 : tline
10843 4 : .compact_with_gc(
10844 4 : &cancel,
10845 4 : CompactOptions {
10846 4 : flags: EnumSet::new(),
10847 4 : compact_key_range: Some((get_key(9)..get_key(10)).into()),
10848 4 : ..Default::default()
10849 4 : },
10850 4 : &ctx,
10851 4 : )
10852 4 : .await
10853 4 : .unwrap();
10854 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10855 4 : check_layer_map_key_eq(
10856 4 : all_layers,
10857 4 : vec![
10858 4 : PersistentLayerKey {
10859 4 : key_range: get_key(0)..get_key(2),
10860 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10861 4 : is_delta: false,
10862 4 : },
10863 4 : PersistentLayerKey {
10864 4 : key_range: get_key(0)..get_key(10),
10865 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10866 4 : is_delta: false,
10867 4 : },
10868 4 : PersistentLayerKey {
10869 4 : key_range: get_key(2)..get_key(4),
10870 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10871 4 : is_delta: false,
10872 4 : },
10873 4 : PersistentLayerKey {
10874 4 : key_range: get_key(2)..get_key(4),
10875 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10876 4 : is_delta: true,
10877 4 : },
10878 4 : PersistentLayerKey {
10879 4 : key_range: get_key(4)..get_key(9),
10880 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10881 4 : is_delta: false,
10882 4 : },
10883 4 : // image layer generated for the compaction range
10884 4 : PersistentLayerKey {
10885 4 : key_range: get_key(9)..get_key(10),
10886 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10887 4 : is_delta: false,
10888 4 : },
10889 4 : PersistentLayerKey {
10890 4 : key_range: get_key(8)..get_key(10),
10891 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10892 4 : is_delta: true,
10893 4 : },
10894 4 : ],
10895 4 : );
10896 4 :
10897 4 : // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
10898 4 : tline
10899 4 : .compact_with_gc(
10900 4 : &cancel,
10901 4 : CompactOptions {
10902 4 : flags: EnumSet::new(),
10903 4 : compact_key_range: Some((get_key(0)..get_key(10)).into()),
10904 4 : ..Default::default()
10905 4 : },
10906 4 : &ctx,
10907 4 : )
10908 4 : .await
10909 4 : .unwrap();
10910 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10911 4 : check_layer_map_key_eq(
10912 4 : all_layers,
10913 4 : vec![
10914 4 : // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
10915 4 : PersistentLayerKey {
10916 4 : key_range: get_key(0)..get_key(10),
10917 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10918 4 : is_delta: false,
10919 4 : },
10920 4 : PersistentLayerKey {
10921 4 : key_range: get_key(2)..get_key(4),
10922 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10923 4 : is_delta: true,
10924 4 : },
10925 4 : PersistentLayerKey {
10926 4 : key_range: get_key(8)..get_key(10),
10927 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10928 4 : is_delta: true,
10929 4 : },
10930 4 : ],
10931 4 : );
10932 4 : Ok(())
10933 4 : }
10934 :
10935 : #[cfg(feature = "testing")]
10936 : #[tokio::test]
10937 4 : async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
10938 4 : let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
10939 4 : .await
10940 4 : .unwrap();
10941 4 : let (tenant, ctx) = harness.load().await;
10942 4 : let tline_parent = tenant
10943 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
10944 4 : .await
10945 4 : .unwrap();
10946 4 : let tline_child = tenant
10947 4 : .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
10948 4 : .await
10949 4 : .unwrap();
10950 4 : {
10951 4 : let gc_info_parent = tline_parent.gc_info.read().unwrap();
10952 4 : assert_eq!(
10953 4 : gc_info_parent.retain_lsns,
10954 4 : vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
10955 4 : );
10956 4 : }
10957 4 : // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
10958 4 : tline_child
10959 4 : .remote_client
10960 4 : .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
10961 4 : .unwrap();
10962 4 : tline_child.remote_client.wait_completion().await.unwrap();
10963 4 : offload_timeline(&tenant, &tline_child)
10964 4 : .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
10965 4 : .await.unwrap();
10966 4 : let child_timeline_id = tline_child.timeline_id;
10967 4 : Arc::try_unwrap(tline_child).unwrap();
10968 4 :
10969 4 : {
10970 4 : let gc_info_parent = tline_parent.gc_info.read().unwrap();
10971 4 : assert_eq!(
10972 4 : gc_info_parent.retain_lsns,
10973 4 : vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
10974 4 : );
10975 4 : }
10976 4 :
10977 4 : tenant
10978 4 : .get_offloaded_timeline(child_timeline_id)
10979 4 : .unwrap()
10980 4 : .defuse_for_tenant_drop();
10981 4 :
10982 4 : Ok(())
10983 4 : }
10984 :
10985 : #[cfg(feature = "testing")]
10986 : #[tokio::test]
10987 4 : async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
10988 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
10989 4 : let (tenant, ctx) = harness.load().await;
10990 4 :
10991 592 : fn get_key(id: u32) -> Key {
10992 592 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
10993 592 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
10994 592 : key.field6 = id;
10995 592 : key
10996 592 : }
10997 4 :
10998 4 : let img_layer = (0..10)
10999 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
11000 4 : .collect_vec();
11001 4 :
11002 4 : let delta1 = vec![(
11003 4 : get_key(1),
11004 4 : Lsn(0x20),
11005 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
11006 4 : )];
11007 4 : let delta4 = vec![(
11008 4 : get_key(1),
11009 4 : Lsn(0x28),
11010 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
11011 4 : )];
11012 4 : let delta2 = vec![
11013 4 : (
11014 4 : get_key(1),
11015 4 : Lsn(0x30),
11016 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
11017 4 : ),
11018 4 : (
11019 4 : get_key(1),
11020 4 : Lsn(0x38),
11021 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
11022 4 : ),
11023 4 : ];
11024 4 : let delta3 = vec![
11025 4 : (
11026 4 : get_key(8),
11027 4 : Lsn(0x48),
11028 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
11029 4 : ),
11030 4 : (
11031 4 : get_key(9),
11032 4 : Lsn(0x48),
11033 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
11034 4 : ),
11035 4 : ];
11036 4 :
11037 4 : let tline = tenant
11038 4 : .create_test_timeline_with_layers(
11039 4 : TIMELINE_ID,
11040 4 : Lsn(0x10),
11041 4 : DEFAULT_PG_VERSION,
11042 4 : &ctx,
11043 4 : vec![], // in-memory layers
11044 4 : vec![
11045 4 : // delta1/2/4 only contain a single key but multiple updates
11046 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
11047 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
11048 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
11049 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
11050 4 : ], // delta layers
11051 4 : vec![(Lsn(0x10), img_layer)], // image layers
11052 4 : Lsn(0x50),
11053 4 : )
11054 4 : .await?;
11055 4 : {
11056 4 : tline
11057 4 : .applied_gc_cutoff_lsn
11058 4 : .lock_for_write()
11059 4 : .store_and_unlock(Lsn(0x30))
11060 4 : .wait()
11061 4 : .await;
11062 4 : // Update GC info
11063 4 : let mut guard = tline.gc_info.write().unwrap();
11064 4 : *guard = GcInfo {
11065 4 : retain_lsns: vec![
11066 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
11067 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
11068 4 : ],
11069 4 : cutoffs: GcCutoffs {
11070 4 : time: Lsn(0x30),
11071 4 : space: Lsn(0x30),
11072 4 : },
11073 4 : leases: Default::default(),
11074 4 : within_ancestor_pitr: false,
11075 4 : };
11076 4 : }
11077 4 :
11078 4 : let expected_result = [
11079 4 : Bytes::from_static(b"value 0@0x10"),
11080 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
11081 4 : Bytes::from_static(b"value 2@0x10"),
11082 4 : Bytes::from_static(b"value 3@0x10"),
11083 4 : Bytes::from_static(b"value 4@0x10"),
11084 4 : Bytes::from_static(b"value 5@0x10"),
11085 4 : Bytes::from_static(b"value 6@0x10"),
11086 4 : Bytes::from_static(b"value 7@0x10"),
11087 4 : Bytes::from_static(b"value 8@0x10@0x48"),
11088 4 : Bytes::from_static(b"value 9@0x10@0x48"),
11089 4 : ];
11090 4 :
11091 4 : let expected_result_at_gc_horizon = [
11092 4 : Bytes::from_static(b"value 0@0x10"),
11093 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
11094 4 : Bytes::from_static(b"value 2@0x10"),
11095 4 : Bytes::from_static(b"value 3@0x10"),
11096 4 : Bytes::from_static(b"value 4@0x10"),
11097 4 : Bytes::from_static(b"value 5@0x10"),
11098 4 : Bytes::from_static(b"value 6@0x10"),
11099 4 : Bytes::from_static(b"value 7@0x10"),
11100 4 : Bytes::from_static(b"value 8@0x10"),
11101 4 : Bytes::from_static(b"value 9@0x10"),
11102 4 : ];
11103 4 :
11104 4 : let expected_result_at_lsn_20 = [
11105 4 : Bytes::from_static(b"value 0@0x10"),
11106 4 : Bytes::from_static(b"value 1@0x10@0x20"),
11107 4 : Bytes::from_static(b"value 2@0x10"),
11108 4 : Bytes::from_static(b"value 3@0x10"),
11109 4 : Bytes::from_static(b"value 4@0x10"),
11110 4 : Bytes::from_static(b"value 5@0x10"),
11111 4 : Bytes::from_static(b"value 6@0x10"),
11112 4 : Bytes::from_static(b"value 7@0x10"),
11113 4 : Bytes::from_static(b"value 8@0x10"),
11114 4 : Bytes::from_static(b"value 9@0x10"),
11115 4 : ];
11116 4 :
11117 4 : let expected_result_at_lsn_10 = [
11118 4 : Bytes::from_static(b"value 0@0x10"),
11119 4 : Bytes::from_static(b"value 1@0x10"),
11120 4 : Bytes::from_static(b"value 2@0x10"),
11121 4 : Bytes::from_static(b"value 3@0x10"),
11122 4 : Bytes::from_static(b"value 4@0x10"),
11123 4 : Bytes::from_static(b"value 5@0x10"),
11124 4 : Bytes::from_static(b"value 6@0x10"),
11125 4 : Bytes::from_static(b"value 7@0x10"),
11126 4 : Bytes::from_static(b"value 8@0x10"),
11127 4 : Bytes::from_static(b"value 9@0x10"),
11128 4 : ];
11129 4 :
11130 12 : let verify_result = || async {
11131 12 : let gc_horizon = {
11132 12 : let gc_info = tline.gc_info.read().unwrap();
11133 12 : gc_info.cutoffs.time
11134 4 : };
11135 132 : for idx in 0..10 {
11136 120 : assert_eq!(
11137 120 : tline
11138 120 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
11139 120 : .await
11140 120 : .unwrap(),
11141 120 : &expected_result[idx]
11142 4 : );
11143 120 : assert_eq!(
11144 120 : tline
11145 120 : .get(get_key(idx as u32), gc_horizon, &ctx)
11146 120 : .await
11147 120 : .unwrap(),
11148 120 : &expected_result_at_gc_horizon[idx]
11149 4 : );
11150 120 : assert_eq!(
11151 120 : tline
11152 120 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
11153 120 : .await
11154 120 : .unwrap(),
11155 120 : &expected_result_at_lsn_20[idx]
11156 4 : );
11157 120 : assert_eq!(
11158 120 : tline
11159 120 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
11160 120 : .await
11161 120 : .unwrap(),
11162 120 : &expected_result_at_lsn_10[idx]
11163 4 : );
11164 4 : }
11165 24 : };
11166 4 :
11167 4 : verify_result().await;
11168 4 :
11169 4 : let cancel = CancellationToken::new();
11170 4 : tline
11171 4 : .compact_with_gc(
11172 4 : &cancel,
11173 4 : CompactOptions {
11174 4 : compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
11175 4 : ..Default::default()
11176 4 : },
11177 4 : &ctx,
11178 4 : )
11179 4 : .await
11180 4 : .unwrap();
11181 4 : verify_result().await;
11182 4 :
11183 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11184 4 : check_layer_map_key_eq(
11185 4 : all_layers,
11186 4 : vec![
11187 4 : // The original image layer, not compacted
11188 4 : PersistentLayerKey {
11189 4 : key_range: get_key(0)..get_key(10),
11190 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11191 4 : is_delta: false,
11192 4 : },
11193 4 : // Delta layer below the specified above_lsn not compacted
11194 4 : PersistentLayerKey {
11195 4 : key_range: get_key(1)..get_key(2),
11196 4 : lsn_range: Lsn(0x20)..Lsn(0x28),
11197 4 : is_delta: true,
11198 4 : },
11199 4 : // Delta layer compacted above the LSN
11200 4 : PersistentLayerKey {
11201 4 : key_range: get_key(1)..get_key(10),
11202 4 : lsn_range: Lsn(0x28)..Lsn(0x50),
11203 4 : is_delta: true,
11204 4 : },
11205 4 : ],
11206 4 : );
11207 4 :
11208 4 : // compact again
11209 4 : tline
11210 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
11211 4 : .await
11212 4 : .unwrap();
11213 4 : verify_result().await;
11214 4 :
11215 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11216 4 : check_layer_map_key_eq(
11217 4 : all_layers,
11218 4 : vec![
11219 4 : // The compacted image layer (full key range)
11220 4 : PersistentLayerKey {
11221 4 : key_range: Key::MIN..Key::MAX,
11222 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11223 4 : is_delta: false,
11224 4 : },
11225 4 : // All other data in the delta layer
11226 4 : PersistentLayerKey {
11227 4 : key_range: get_key(1)..get_key(10),
11228 4 : lsn_range: Lsn(0x10)..Lsn(0x50),
11229 4 : is_delta: true,
11230 4 : },
11231 4 : ],
11232 4 : );
11233 4 :
11234 4 : Ok(())
11235 4 : }
11236 :
11237 : #[cfg(feature = "testing")]
11238 : #[tokio::test]
11239 4 : async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
11240 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
11241 4 : let (tenant, ctx) = harness.load().await;
11242 4 :
11243 1016 : fn get_key(id: u32) -> Key {
11244 1016 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
11245 1016 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
11246 1016 : key.field6 = id;
11247 1016 : key
11248 1016 : }
11249 4 :
11250 4 : let img_layer = (0..10)
11251 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
11252 4 : .collect_vec();
11253 4 :
11254 4 : let delta1 = vec![(
11255 4 : get_key(1),
11256 4 : Lsn(0x20),
11257 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
11258 4 : )];
11259 4 : let delta4 = vec![(
11260 4 : get_key(1),
11261 4 : Lsn(0x28),
11262 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
11263 4 : )];
11264 4 : let delta2 = vec![
11265 4 : (
11266 4 : get_key(1),
11267 4 : Lsn(0x30),
11268 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
11269 4 : ),
11270 4 : (
11271 4 : get_key(1),
11272 4 : Lsn(0x38),
11273 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
11274 4 : ),
11275 4 : ];
11276 4 : let delta3 = vec![
11277 4 : (
11278 4 : get_key(8),
11279 4 : Lsn(0x48),
11280 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
11281 4 : ),
11282 4 : (
11283 4 : get_key(9),
11284 4 : Lsn(0x48),
11285 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
11286 4 : ),
11287 4 : ];
11288 4 :
11289 4 : let tline = tenant
11290 4 : .create_test_timeline_with_layers(
11291 4 : TIMELINE_ID,
11292 4 : Lsn(0x10),
11293 4 : DEFAULT_PG_VERSION,
11294 4 : &ctx,
11295 4 : vec![], // in-memory layers
11296 4 : vec![
11297 4 : // delta1/2/4 only contain a single key but multiple updates
11298 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
11299 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
11300 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
11301 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
11302 4 : ], // delta layers
11303 4 : vec![(Lsn(0x10), img_layer)], // image layers
11304 4 : Lsn(0x50),
11305 4 : )
11306 4 : .await?;
11307 4 : {
11308 4 : tline
11309 4 : .applied_gc_cutoff_lsn
11310 4 : .lock_for_write()
11311 4 : .store_and_unlock(Lsn(0x30))
11312 4 : .wait()
11313 4 : .await;
11314 4 : // Update GC info
11315 4 : let mut guard = tline.gc_info.write().unwrap();
11316 4 : *guard = GcInfo {
11317 4 : retain_lsns: vec![
11318 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
11319 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
11320 4 : ],
11321 4 : cutoffs: GcCutoffs {
11322 4 : time: Lsn(0x30),
11323 4 : space: Lsn(0x30),
11324 4 : },
11325 4 : leases: Default::default(),
11326 4 : within_ancestor_pitr: false,
11327 4 : };
11328 4 : }
11329 4 :
11330 4 : let expected_result = [
11331 4 : Bytes::from_static(b"value 0@0x10"),
11332 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
11333 4 : Bytes::from_static(b"value 2@0x10"),
11334 4 : Bytes::from_static(b"value 3@0x10"),
11335 4 : Bytes::from_static(b"value 4@0x10"),
11336 4 : Bytes::from_static(b"value 5@0x10"),
11337 4 : Bytes::from_static(b"value 6@0x10"),
11338 4 : Bytes::from_static(b"value 7@0x10"),
11339 4 : Bytes::from_static(b"value 8@0x10@0x48"),
11340 4 : Bytes::from_static(b"value 9@0x10@0x48"),
11341 4 : ];
11342 4 :
11343 4 : let expected_result_at_gc_horizon = [
11344 4 : Bytes::from_static(b"value 0@0x10"),
11345 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
11346 4 : Bytes::from_static(b"value 2@0x10"),
11347 4 : Bytes::from_static(b"value 3@0x10"),
11348 4 : Bytes::from_static(b"value 4@0x10"),
11349 4 : Bytes::from_static(b"value 5@0x10"),
11350 4 : Bytes::from_static(b"value 6@0x10"),
11351 4 : Bytes::from_static(b"value 7@0x10"),
11352 4 : Bytes::from_static(b"value 8@0x10"),
11353 4 : Bytes::from_static(b"value 9@0x10"),
11354 4 : ];
11355 4 :
11356 4 : let expected_result_at_lsn_20 = [
11357 4 : Bytes::from_static(b"value 0@0x10"),
11358 4 : Bytes::from_static(b"value 1@0x10@0x20"),
11359 4 : Bytes::from_static(b"value 2@0x10"),
11360 4 : Bytes::from_static(b"value 3@0x10"),
11361 4 : Bytes::from_static(b"value 4@0x10"),
11362 4 : Bytes::from_static(b"value 5@0x10"),
11363 4 : Bytes::from_static(b"value 6@0x10"),
11364 4 : Bytes::from_static(b"value 7@0x10"),
11365 4 : Bytes::from_static(b"value 8@0x10"),
11366 4 : Bytes::from_static(b"value 9@0x10"),
11367 4 : ];
11368 4 :
11369 4 : let expected_result_at_lsn_10 = [
11370 4 : Bytes::from_static(b"value 0@0x10"),
11371 4 : Bytes::from_static(b"value 1@0x10"),
11372 4 : Bytes::from_static(b"value 2@0x10"),
11373 4 : Bytes::from_static(b"value 3@0x10"),
11374 4 : Bytes::from_static(b"value 4@0x10"),
11375 4 : Bytes::from_static(b"value 5@0x10"),
11376 4 : Bytes::from_static(b"value 6@0x10"),
11377 4 : Bytes::from_static(b"value 7@0x10"),
11378 4 : Bytes::from_static(b"value 8@0x10"),
11379 4 : Bytes::from_static(b"value 9@0x10"),
11380 4 : ];
11381 4 :
11382 20 : let verify_result = || async {
11383 20 : let gc_horizon = {
11384 20 : let gc_info = tline.gc_info.read().unwrap();
11385 20 : gc_info.cutoffs.time
11386 4 : };
11387 220 : for idx in 0..10 {
11388 200 : assert_eq!(
11389 200 : tline
11390 200 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
11391 200 : .await
11392 200 : .unwrap(),
11393 200 : &expected_result[idx]
11394 4 : );
11395 200 : assert_eq!(
11396 200 : tline
11397 200 : .get(get_key(idx as u32), gc_horizon, &ctx)
11398 200 : .await
11399 200 : .unwrap(),
11400 200 : &expected_result_at_gc_horizon[idx]
11401 4 : );
11402 200 : assert_eq!(
11403 200 : tline
11404 200 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
11405 200 : .await
11406 200 : .unwrap(),
11407 200 : &expected_result_at_lsn_20[idx]
11408 4 : );
11409 200 : assert_eq!(
11410 200 : tline
11411 200 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
11412 200 : .await
11413 200 : .unwrap(),
11414 200 : &expected_result_at_lsn_10[idx]
11415 4 : );
11416 4 : }
11417 40 : };
11418 4 :
11419 4 : verify_result().await;
11420 4 :
11421 4 : let cancel = CancellationToken::new();
11422 4 :
11423 4 : tline
11424 4 : .compact_with_gc(
11425 4 : &cancel,
11426 4 : CompactOptions {
11427 4 : compact_key_range: Some((get_key(0)..get_key(2)).into()),
11428 4 : compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
11429 4 : ..Default::default()
11430 4 : },
11431 4 : &ctx,
11432 4 : )
11433 4 : .await
11434 4 : .unwrap();
11435 4 : verify_result().await;
11436 4 :
11437 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11438 4 : check_layer_map_key_eq(
11439 4 : all_layers,
11440 4 : vec![
11441 4 : // The original image layer, not compacted
11442 4 : PersistentLayerKey {
11443 4 : key_range: get_key(0)..get_key(10),
11444 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11445 4 : is_delta: false,
11446 4 : },
11447 4 : // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
11448 4 : // the layer 0x28-0x30 into one.
11449 4 : PersistentLayerKey {
11450 4 : key_range: get_key(1)..get_key(2),
11451 4 : lsn_range: Lsn(0x20)..Lsn(0x30),
11452 4 : is_delta: true,
11453 4 : },
11454 4 : // Above the upper bound and untouched
11455 4 : PersistentLayerKey {
11456 4 : key_range: get_key(1)..get_key(2),
11457 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11458 4 : is_delta: true,
11459 4 : },
11460 4 : // This layer is untouched
11461 4 : PersistentLayerKey {
11462 4 : key_range: get_key(8)..get_key(10),
11463 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11464 4 : is_delta: true,
11465 4 : },
11466 4 : ],
11467 4 : );
11468 4 :
11469 4 : tline
11470 4 : .compact_with_gc(
11471 4 : &cancel,
11472 4 : CompactOptions {
11473 4 : compact_key_range: Some((get_key(3)..get_key(8)).into()),
11474 4 : compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
11475 4 : ..Default::default()
11476 4 : },
11477 4 : &ctx,
11478 4 : )
11479 4 : .await
11480 4 : .unwrap();
11481 4 : verify_result().await;
11482 4 :
11483 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11484 4 : check_layer_map_key_eq(
11485 4 : all_layers,
11486 4 : vec![
11487 4 : // The original image layer, not compacted
11488 4 : PersistentLayerKey {
11489 4 : key_range: get_key(0)..get_key(10),
11490 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11491 4 : is_delta: false,
11492 4 : },
11493 4 : // Not in the compaction key range, uncompacted
11494 4 : PersistentLayerKey {
11495 4 : key_range: get_key(1)..get_key(2),
11496 4 : lsn_range: Lsn(0x20)..Lsn(0x30),
11497 4 : is_delta: true,
11498 4 : },
11499 4 : // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
11500 4 : PersistentLayerKey {
11501 4 : key_range: get_key(1)..get_key(2),
11502 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11503 4 : is_delta: true,
11504 4 : },
11505 4 : // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
11506 4 : // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
11507 4 : // becomes 0x50.
11508 4 : PersistentLayerKey {
11509 4 : key_range: get_key(8)..get_key(10),
11510 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11511 4 : is_delta: true,
11512 4 : },
11513 4 : ],
11514 4 : );
11515 4 :
11516 4 : // compact again
11517 4 : tline
11518 4 : .compact_with_gc(
11519 4 : &cancel,
11520 4 : CompactOptions {
11521 4 : compact_key_range: Some((get_key(0)..get_key(5)).into()),
11522 4 : compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
11523 4 : ..Default::default()
11524 4 : },
11525 4 : &ctx,
11526 4 : )
11527 4 : .await
11528 4 : .unwrap();
11529 4 : verify_result().await;
11530 4 :
11531 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11532 4 : check_layer_map_key_eq(
11533 4 : all_layers,
11534 4 : vec![
11535 4 : // The original image layer, not compacted
11536 4 : PersistentLayerKey {
11537 4 : key_range: get_key(0)..get_key(10),
11538 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11539 4 : is_delta: false,
11540 4 : },
11541 4 : // The range gets compacted
11542 4 : PersistentLayerKey {
11543 4 : key_range: get_key(1)..get_key(2),
11544 4 : lsn_range: Lsn(0x20)..Lsn(0x50),
11545 4 : is_delta: true,
11546 4 : },
11547 4 : // Not touched during this iteration of compaction
11548 4 : PersistentLayerKey {
11549 4 : key_range: get_key(8)..get_key(10),
11550 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11551 4 : is_delta: true,
11552 4 : },
11553 4 : ],
11554 4 : );
11555 4 :
11556 4 : // final full compaction
11557 4 : tline
11558 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
11559 4 : .await
11560 4 : .unwrap();
11561 4 : verify_result().await;
11562 4 :
11563 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11564 4 : check_layer_map_key_eq(
11565 4 : all_layers,
11566 4 : vec![
11567 4 : // The compacted image layer (full key range)
11568 4 : PersistentLayerKey {
11569 4 : key_range: Key::MIN..Key::MAX,
11570 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11571 4 : is_delta: false,
11572 4 : },
11573 4 : // All other data in the delta layer
11574 4 : PersistentLayerKey {
11575 4 : key_range: get_key(1)..get_key(10),
11576 4 : lsn_range: Lsn(0x10)..Lsn(0x50),
11577 4 : is_delta: true,
11578 4 : },
11579 4 : ],
11580 4 : );
11581 4 :
11582 4 : Ok(())
11583 4 : }
11584 :
11585 : #[cfg(feature = "testing")]
11586 : #[tokio::test]
11587 4 : async fn test_bottom_most_compation_redo_failure() -> anyhow::Result<()> {
11588 4 : let harness = TenantHarness::create("test_bottom_most_compation_redo_failure").await?;
11589 4 : let (tenant, ctx) = harness.load().await;
11590 4 :
11591 52 : fn get_key(id: u32) -> Key {
11592 52 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
11593 52 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
11594 52 : key.field6 = id;
11595 52 : key
11596 52 : }
11597 4 :
11598 4 : let img_layer = (0..10)
11599 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
11600 4 : .collect_vec();
11601 4 :
11602 4 : let delta1 = vec![
11603 4 : (
11604 4 : get_key(1),
11605 4 : Lsn(0x20),
11606 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
11607 4 : ),
11608 4 : (
11609 4 : get_key(1),
11610 4 : Lsn(0x24),
11611 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x24")),
11612 4 : ),
11613 4 : (
11614 4 : get_key(1),
11615 4 : Lsn(0x28),
11616 4 : // This record will fail to redo
11617 4 : Value::WalRecord(NeonWalRecord::wal_append_conditional("@0x28", "???")),
11618 4 : ),
11619 4 : ];
11620 4 :
11621 4 : let tline = tenant
11622 4 : .create_test_timeline_with_layers(
11623 4 : TIMELINE_ID,
11624 4 : Lsn(0x10),
11625 4 : DEFAULT_PG_VERSION,
11626 4 : &ctx,
11627 4 : vec![], // in-memory layers
11628 4 : vec![DeltaLayerTestDesc::new_with_inferred_key_range(
11629 4 : Lsn(0x20)..Lsn(0x30),
11630 4 : delta1,
11631 4 : )], // delta layers
11632 4 : vec![(Lsn(0x10), img_layer)], // image layers
11633 4 : Lsn(0x50),
11634 4 : )
11635 4 : .await?;
11636 4 : {
11637 4 : tline
11638 4 : .applied_gc_cutoff_lsn
11639 4 : .lock_for_write()
11640 4 : .store_and_unlock(Lsn(0x30))
11641 4 : .wait()
11642 4 : .await;
11643 4 : // Update GC info
11644 4 : let mut guard = tline.gc_info.write().unwrap();
11645 4 : *guard = GcInfo {
11646 4 : retain_lsns: vec![],
11647 4 : cutoffs: GcCutoffs {
11648 4 : time: Lsn(0x30),
11649 4 : space: Lsn(0x30),
11650 4 : },
11651 4 : leases: Default::default(),
11652 4 : within_ancestor_pitr: false,
11653 4 : };
11654 4 : }
11655 4 :
11656 4 : let cancel = CancellationToken::new();
11657 4 :
11658 4 : // Compaction will fail, but should not fire any critical error.
11659 4 : // Gc-compaction currently cannot figure out what keys are not in the keyspace during the compaction
11660 4 : // process. It will always try to redo the logs it reads and if it doesn't work, fail the entire
11661 4 : // compaction job. Tracked in <https://github.com/neondatabase/neon/issues/10395>.
11662 4 : let res = tline
11663 4 : .compact_with_gc(
11664 4 : &cancel,
11665 4 : CompactOptions {
11666 4 : compact_key_range: None,
11667 4 : compact_lsn_range: None,
11668 4 : ..Default::default()
11669 4 : },
11670 4 : &ctx,
11671 4 : )
11672 4 : .await;
11673 4 : assert!(res.is_err());
11674 4 :
11675 4 : Ok(())
11676 4 : }
11677 :
11678 : #[cfg(feature = "testing")]
11679 : #[tokio::test]
11680 4 : async fn test_synthetic_size_calculation_with_invisible_branches() -> anyhow::Result<()> {
11681 4 : use pageserver_api::models::TimelineVisibilityState;
11682 4 :
11683 4 : use crate::tenant::size::gather_inputs;
11684 4 :
11685 4 : let tenant_conf = pageserver_api::models::TenantConfig {
11686 4 : // Ensure that we don't compute gc_cutoffs (which needs reading the layer files)
11687 4 : pitr_interval: Some(Duration::ZERO),
11688 4 : ..Default::default()
11689 4 : };
11690 4 : let harness = TenantHarness::create_custom(
11691 4 : "test_synthetic_size_calculation_with_invisible_branches",
11692 4 : tenant_conf,
11693 4 : TenantId::generate(),
11694 4 : ShardIdentity::unsharded(),
11695 4 : Generation::new(0xdeadbeef),
11696 4 : )
11697 4 : .await?;
11698 4 : let (tenant, ctx) = harness.load().await;
11699 4 : let main_tline = tenant
11700 4 : .create_test_timeline_with_layers(
11701 4 : TIMELINE_ID,
11702 4 : Lsn(0x10),
11703 4 : DEFAULT_PG_VERSION,
11704 4 : &ctx,
11705 4 : vec![],
11706 4 : vec![],
11707 4 : vec![],
11708 4 : Lsn(0x100),
11709 4 : )
11710 4 : .await?;
11711 4 :
11712 4 : let snapshot1 = TimelineId::from_array(hex!("11223344556677881122334455667790"));
11713 4 : tenant
11714 4 : .branch_timeline_test_with_layers(
11715 4 : &main_tline,
11716 4 : snapshot1,
11717 4 : Some(Lsn(0x20)),
11718 4 : &ctx,
11719 4 : vec![],
11720 4 : vec![],
11721 4 : Lsn(0x50),
11722 4 : )
11723 4 : .await?;
11724 4 : let snapshot2 = TimelineId::from_array(hex!("11223344556677881122334455667791"));
11725 4 : tenant
11726 4 : .branch_timeline_test_with_layers(
11727 4 : &main_tline,
11728 4 : snapshot2,
11729 4 : Some(Lsn(0x30)),
11730 4 : &ctx,
11731 4 : vec![],
11732 4 : vec![],
11733 4 : Lsn(0x50),
11734 4 : )
11735 4 : .await?;
11736 4 : let snapshot3 = TimelineId::from_array(hex!("11223344556677881122334455667792"));
11737 4 : tenant
11738 4 : .branch_timeline_test_with_layers(
11739 4 : &main_tline,
11740 4 : snapshot3,
11741 4 : Some(Lsn(0x40)),
11742 4 : &ctx,
11743 4 : vec![],
11744 4 : vec![],
11745 4 : Lsn(0x50),
11746 4 : )
11747 4 : .await?;
11748 4 : let limit = Arc::new(Semaphore::new(1));
11749 4 : let max_retention_period = None;
11750 4 : let mut logical_size_cache = HashMap::new();
11751 4 : let cause = LogicalSizeCalculationCause::EvictionTaskImitation;
11752 4 : let cancel = CancellationToken::new();
11753 4 :
11754 4 : let inputs = gather_inputs(
11755 4 : &tenant,
11756 4 : &limit,
11757 4 : max_retention_period,
11758 4 : &mut logical_size_cache,
11759 4 : cause,
11760 4 : &cancel,
11761 4 : &ctx,
11762 4 : )
11763 4 : .instrument(info_span!(
11764 4 : "gather_inputs",
11765 4 : tenant_id = "unknown",
11766 4 : shard_id = "unknown",
11767 4 : ))
11768 4 : .await?;
11769 4 : use crate::tenant::size::{LsnKind, ModelInputs, SegmentMeta};
11770 4 : use LsnKind::*;
11771 4 : use tenant_size_model::Segment;
11772 4 : let ModelInputs { mut segments, .. } = inputs;
11773 60 : segments.retain(|s| s.timeline_id == TIMELINE_ID);
11774 24 : for segment in segments.iter_mut() {
11775 24 : segment.segment.parent = None; // We don't care about the parent for the test
11776 24 : segment.segment.size = None; // We don't care about the size for the test
11777 24 : }
11778 4 : assert_eq!(
11779 4 : segments,
11780 4 : [
11781 4 : SegmentMeta {
11782 4 : segment: Segment {
11783 4 : parent: None,
11784 4 : lsn: 0x10,
11785 4 : size: None,
11786 4 : needed: false,
11787 4 : },
11788 4 : timeline_id: TIMELINE_ID,
11789 4 : kind: BranchStart,
11790 4 : },
11791 4 : SegmentMeta {
11792 4 : segment: Segment {
11793 4 : parent: None,
11794 4 : lsn: 0x20,
11795 4 : size: None,
11796 4 : needed: false,
11797 4 : },
11798 4 : timeline_id: TIMELINE_ID,
11799 4 : kind: BranchPoint,
11800 4 : },
11801 4 : SegmentMeta {
11802 4 : segment: Segment {
11803 4 : parent: None,
11804 4 : lsn: 0x30,
11805 4 : size: None,
11806 4 : needed: false,
11807 4 : },
11808 4 : timeline_id: TIMELINE_ID,
11809 4 : kind: BranchPoint,
11810 4 : },
11811 4 : SegmentMeta {
11812 4 : segment: Segment {
11813 4 : parent: None,
11814 4 : lsn: 0x40,
11815 4 : size: None,
11816 4 : needed: false,
11817 4 : },
11818 4 : timeline_id: TIMELINE_ID,
11819 4 : kind: BranchPoint,
11820 4 : },
11821 4 : SegmentMeta {
11822 4 : segment: Segment {
11823 4 : parent: None,
11824 4 : lsn: 0x100,
11825 4 : size: None,
11826 4 : needed: false,
11827 4 : },
11828 4 : timeline_id: TIMELINE_ID,
11829 4 : kind: GcCutOff,
11830 4 : }, // we need to retain everything above the last branch point
11831 4 : SegmentMeta {
11832 4 : segment: Segment {
11833 4 : parent: None,
11834 4 : lsn: 0x100,
11835 4 : size: None,
11836 4 : needed: true,
11837 4 : },
11838 4 : timeline_id: TIMELINE_ID,
11839 4 : kind: BranchEnd,
11840 4 : },
11841 4 : ]
11842 4 : );
11843 4 :
11844 4 : main_tline
11845 4 : .remote_client
11846 4 : .schedule_index_upload_for_timeline_invisible_state(
11847 4 : TimelineVisibilityState::Invisible,
11848 4 : )?;
11849 4 : main_tline.remote_client.wait_completion().await?;
11850 4 : let inputs = gather_inputs(
11851 4 : &tenant,
11852 4 : &limit,
11853 4 : max_retention_period,
11854 4 : &mut logical_size_cache,
11855 4 : cause,
11856 4 : &cancel,
11857 4 : &ctx,
11858 4 : )
11859 4 : .instrument(info_span!(
11860 4 : "gather_inputs",
11861 4 : tenant_id = "unknown",
11862 4 : shard_id = "unknown",
11863 4 : ))
11864 4 : .await?;
11865 4 : let ModelInputs { mut segments, .. } = inputs;
11866 56 : segments.retain(|s| s.timeline_id == TIMELINE_ID);
11867 20 : for segment in segments.iter_mut() {
11868 20 : segment.segment.parent = None; // We don't care about the parent for the test
11869 20 : segment.segment.size = None; // We don't care about the size for the test
11870 20 : }
11871 4 : assert_eq!(
11872 4 : segments,
11873 4 : [
11874 4 : SegmentMeta {
11875 4 : segment: Segment {
11876 4 : parent: None,
11877 4 : lsn: 0x10,
11878 4 : size: None,
11879 4 : needed: false,
11880 4 : },
11881 4 : timeline_id: TIMELINE_ID,
11882 4 : kind: BranchStart,
11883 4 : },
11884 4 : SegmentMeta {
11885 4 : segment: Segment {
11886 4 : parent: None,
11887 4 : lsn: 0x20,
11888 4 : size: None,
11889 4 : needed: false,
11890 4 : },
11891 4 : timeline_id: TIMELINE_ID,
11892 4 : kind: BranchPoint,
11893 4 : },
11894 4 : SegmentMeta {
11895 4 : segment: Segment {
11896 4 : parent: None,
11897 4 : lsn: 0x30,
11898 4 : size: None,
11899 4 : needed: false,
11900 4 : },
11901 4 : timeline_id: TIMELINE_ID,
11902 4 : kind: BranchPoint,
11903 4 : },
11904 4 : SegmentMeta {
11905 4 : segment: Segment {
11906 4 : parent: None,
11907 4 : lsn: 0x40,
11908 4 : size: None,
11909 4 : needed: false,
11910 4 : },
11911 4 : timeline_id: TIMELINE_ID,
11912 4 : kind: BranchPoint,
11913 4 : },
11914 4 : SegmentMeta {
11915 4 : segment: Segment {
11916 4 : parent: None,
11917 4 : lsn: 0x40, // Branch end LSN == last branch point LSN
11918 4 : size: None,
11919 4 : needed: true,
11920 4 : },
11921 4 : timeline_id: TIMELINE_ID,
11922 4 : kind: BranchEnd,
11923 4 : },
11924 4 : ]
11925 4 : );
11926 4 : Ok(())
11927 4 : }
11928 : }
|