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 : use pageserver_api::models;
35 : pub use pageserver_api::models::TenantState;
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 : };
49 : use secondary::heatmap::{HeatMapTenant, HeatMapTimeline};
50 : use storage_broker::BrokerClientChannel;
51 : use timeline::compaction::{CompactionOutcome, GcCompactionQueue};
52 : use timeline::offload::{OffloadError, offload_timeline};
53 : use timeline::{
54 : CompactFlags, CompactOptions, CompactionError, PreviousHeatmap, ShutdownMode, import_pgdata,
55 : };
56 : use tokio::io::BufReader;
57 : use tokio::sync::{Notify, Semaphore, watch};
58 : use tokio::task::JoinSet;
59 : use tokio_util::sync::CancellationToken;
60 : use tracing::*;
61 : use upload_queue::NotInitialized;
62 : use utils::circuit_breaker::CircuitBreaker;
63 : use utils::crashsafe::path_with_suffix_extension;
64 : use utils::sync::gate::{Gate, GateGuard};
65 : use utils::timeout::{TimeoutCancellableError, timeout_cancellable};
66 : use utils::try_rcu::ArcSwapExt;
67 : use utils::zstd::{create_zst_tarball, extract_zst_tarball};
68 : use utils::{backoff, completion, failpoint_support, fs_ext, pausable_failpoint};
69 :
70 : use self::config::{AttachedLocationConfig, AttachmentMode, LocationConf, TenantConf};
71 : use self::metadata::TimelineMetadata;
72 : use self::mgr::{GetActiveTenantError, GetTenantError};
73 : use self::remote_timeline_client::upload::{upload_index_part, upload_tenant_manifest};
74 : use self::remote_timeline_client::{RemoteTimelineClient, WaitCompletionError};
75 : use self::timeline::uninit::{TimelineCreateGuard, TimelineExclusionError, UninitializedTimeline};
76 : use self::timeline::{
77 : EvictionTaskTenantState, GcCutoffs, TimelineDeleteProgress, TimelineResources, WaitLsnError,
78 : };
79 : use crate::config::PageServerConf;
80 : use crate::context::{DownloadBehavior, RequestContext};
81 : use crate::deletion_queue::{DeletionQueueClient, DeletionQueueError};
82 : use crate::l0_flush::L0FlushGlobalState;
83 : use crate::metrics::{
84 : BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN, CONCURRENT_INITDBS,
85 : INITDB_RUN_TIME, INITDB_SEMAPHORE_ACQUISITION_TIME, TENANT, TENANT_STATE_METRIC,
86 : TENANT_SYNTHETIC_SIZE_METRIC, remove_tenant_metrics,
87 : };
88 : use crate::task_mgr::TaskKind;
89 : use crate::tenant::config::{LocationMode, TenantConfOpt};
90 : use crate::tenant::gc_result::GcResult;
91 : pub use crate::tenant::remote_timeline_client::index::IndexPart;
92 : use crate::tenant::remote_timeline_client::{
93 : INITDB_PATH, MaybeDeletedIndexPart, remote_initdb_archive_path,
94 : };
95 : use crate::tenant::storage_layer::{DeltaLayer, ImageLayer};
96 : use crate::tenant::timeline::delete::DeleteTimelineFlow;
97 : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
98 : use crate::virtual_file::VirtualFile;
99 : use crate::walingest::WalLagCooldown;
100 : use crate::walredo::PostgresRedoManager;
101 : use crate::{InitializationOrder, TEMP_FILE_SUFFIX, import_datadir, span, task_mgr, walredo};
102 :
103 0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
104 : use utils::crashsafe;
105 : use utils::generation::Generation;
106 : use utils::id::TimelineId;
107 : use utils::lsn::{Lsn, RecordLsn};
108 :
109 : pub mod blob_io;
110 : pub mod block_io;
111 : pub mod vectored_blob_io;
112 :
113 : pub mod disk_btree;
114 : pub(crate) mod ephemeral_file;
115 : pub mod layer_map;
116 :
117 : pub mod metadata;
118 : pub mod remote_timeline_client;
119 : pub mod storage_layer;
120 :
121 : pub mod checks;
122 : pub mod config;
123 : pub mod mgr;
124 : pub mod secondary;
125 : pub mod tasks;
126 : pub mod upload_queue;
127 :
128 : pub(crate) mod timeline;
129 :
130 : pub mod size;
131 :
132 : mod gc_block;
133 : mod gc_result;
134 : pub(crate) mod throttle;
135 :
136 : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
137 :
138 : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
139 : // re-export for use in walreceiver
140 : pub use crate::tenant::timeline::WalReceiverInfo;
141 :
142 : /// The "tenants" part of `tenants/<tenant>/timelines...`
143 : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
144 :
145 : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
146 : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
147 :
148 : /// References to shared objects that are passed into each tenant, such
149 : /// as the shared remote storage client and process initialization state.
150 : #[derive(Clone)]
151 : pub struct TenantSharedResources {
152 : pub broker_client: storage_broker::BrokerClientChannel,
153 : pub remote_storage: GenericRemoteStorage,
154 : pub deletion_queue_client: DeletionQueueClient,
155 : pub l0_flush_global_state: L0FlushGlobalState,
156 : }
157 :
158 : /// A [`Tenant`] is really an _attached_ tenant. The configuration
159 : /// for an attached tenant is a subset of the [`LocationConf`], represented
160 : /// in this struct.
161 : #[derive(Clone)]
162 : pub(super) struct AttachedTenantConf {
163 : tenant_conf: TenantConfOpt,
164 : location: AttachedLocationConfig,
165 : /// The deadline before which we are blocked from GC so that
166 : /// leases have a chance to be renewed.
167 : lsn_lease_deadline: Option<tokio::time::Instant>,
168 : }
169 :
170 : impl AttachedTenantConf {
171 454 : fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
172 : // Sets a deadline before which we cannot proceed to GC due to lsn lease.
173 : //
174 : // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
175 : // length, we guarantee that all the leases we granted before will have a chance to renew
176 : // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
177 454 : let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
178 454 : Some(
179 454 : tokio::time::Instant::now()
180 454 : + tenant_conf
181 454 : .lsn_lease_length
182 454 : .unwrap_or(LsnLease::DEFAULT_LENGTH),
183 454 : )
184 : } else {
185 : // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
186 : // because we don't do GC in these modes.
187 0 : None
188 : };
189 :
190 454 : Self {
191 454 : tenant_conf,
192 454 : location,
193 454 : lsn_lease_deadline,
194 454 : }
195 454 : }
196 :
197 454 : fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
198 454 : match &location_conf.mode {
199 454 : LocationMode::Attached(attach_conf) => {
200 454 : Ok(Self::new(location_conf.tenant_conf, *attach_conf))
201 : }
202 : LocationMode::Secondary(_) => {
203 0 : anyhow::bail!(
204 0 : "Attempted to construct AttachedTenantConf from a LocationConf in secondary mode"
205 0 : )
206 : }
207 : }
208 454 : }
209 :
210 1524 : fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
211 1524 : self.lsn_lease_deadline
212 1524 : .map(|d| tokio::time::Instant::now() < d)
213 1524 : .unwrap_or(false)
214 1524 : }
215 : }
216 : struct TimelinePreload {
217 : timeline_id: TimelineId,
218 : client: RemoteTimelineClient,
219 : index_part: Result<MaybeDeletedIndexPart, DownloadError>,
220 : previous_heatmap: Option<PreviousHeatmap>,
221 : }
222 :
223 : pub(crate) struct TenantPreload {
224 : tenant_manifest: TenantManifest,
225 : /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
226 : timelines: HashMap<TimelineId, Option<TimelinePreload>>,
227 : }
228 :
229 : /// When we spawn a tenant, there is a special mode for tenant creation that
230 : /// avoids trying to read anything from remote storage.
231 : pub(crate) enum SpawnMode {
232 : /// Activate as soon as possible
233 : Eager,
234 : /// Lazy activation in the background, with the option to skip the queue if the need comes up
235 : Lazy,
236 : }
237 :
238 : ///
239 : /// Tenant consists of multiple timelines. Keep them in a hash table.
240 : ///
241 : pub struct Tenant {
242 : // Global pageserver config parameters
243 : pub conf: &'static PageServerConf,
244 :
245 : /// The value creation timestamp, used to measure activation delay, see:
246 : /// <https://github.com/neondatabase/neon/issues/4025>
247 : constructed_at: Instant,
248 :
249 : state: watch::Sender<TenantState>,
250 :
251 : // Overridden tenant-specific config parameters.
252 : // We keep TenantConfOpt sturct here to preserve the information
253 : // about parameters that are not set.
254 : // This is necessary to allow global config updates.
255 : tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
256 :
257 : tenant_shard_id: TenantShardId,
258 :
259 : // The detailed sharding information, beyond the number/count in tenant_shard_id
260 : shard_identity: ShardIdentity,
261 :
262 : /// The remote storage generation, used to protect S3 objects from split-brain.
263 : /// Does not change over the lifetime of the [`Tenant`] object.
264 : ///
265 : /// This duplicates the generation stored in LocationConf, but that structure is mutable:
266 : /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
267 : generation: Generation,
268 :
269 : timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
270 :
271 : /// During timeline creation, we first insert the TimelineId to the
272 : /// creating map, then `timelines`, then remove it from the creating map.
273 : /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
274 : timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
275 :
276 : /// Possibly offloaded and archived timelines
277 : /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
278 : timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
279 :
280 : /// Serialize writes of the tenant manifest to remote storage. If there are concurrent operations
281 : /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
282 : /// each other (this could be optimized to coalesce writes if necessary).
283 : ///
284 : /// The contents of the Mutex are the last manifest we successfully uploaded
285 : tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
286 :
287 : // This mutex prevents creation of new timelines during GC.
288 : // Adding yet another mutex (in addition to `timelines`) is needed because holding
289 : // `timelines` mutex during all GC iteration
290 : // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
291 : // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
292 : // timeout...
293 : gc_cs: tokio::sync::Mutex<()>,
294 : walredo_mgr: Option<Arc<WalRedoManager>>,
295 :
296 : // provides access to timeline data sitting in the remote storage
297 : pub(crate) remote_storage: GenericRemoteStorage,
298 :
299 : // Access to global deletion queue for when this tenant wants to schedule a deletion
300 : deletion_queue_client: DeletionQueueClient,
301 :
302 : /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
303 : cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
304 : cached_synthetic_tenant_size: Arc<AtomicU64>,
305 :
306 : eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
307 :
308 : /// Track repeated failures to compact, so that we can back off.
309 : /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
310 : compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
311 :
312 : /// Signals the tenant compaction loop that there is L0 compaction work to be done.
313 : pub(crate) l0_compaction_trigger: Arc<Notify>,
314 :
315 : /// Scheduled gc-compaction tasks.
316 : scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
317 :
318 : /// If the tenant is in Activating state, notify this to encourage it
319 : /// to proceed to Active as soon as possible, rather than waiting for lazy
320 : /// background warmup.
321 : pub(crate) activate_now_sem: tokio::sync::Semaphore,
322 :
323 : /// Time it took for the tenant to activate. Zero if not active yet.
324 : attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
325 :
326 : // Cancellation token fires when we have entered shutdown(). This is a parent of
327 : // Timelines' cancellation token.
328 : pub(crate) cancel: CancellationToken,
329 :
330 : // Users of the Tenant such as the page service must take this Gate to avoid
331 : // trying to use a Tenant which is shutting down.
332 : pub(crate) gate: Gate,
333 :
334 : /// Throttle applied at the top of [`Timeline::get`].
335 : /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
336 : pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
337 :
338 : pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
339 :
340 : /// An ongoing timeline detach concurrency limiter.
341 : ///
342 : /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
343 : /// to have two running at the same time. A different one can be started if an earlier one
344 : /// has failed for whatever reason.
345 : ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
346 :
347 : /// `index_part.json` based gc blocking reason tracking.
348 : ///
349 : /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
350 : /// proceeding.
351 : pub(crate) gc_block: gc_block::GcBlock,
352 :
353 : l0_flush_global_state: L0FlushGlobalState,
354 : }
355 : impl std::fmt::Debug for Tenant {
356 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
357 0 : write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
358 0 : }
359 : }
360 :
361 : pub(crate) enum WalRedoManager {
362 : Prod(WalredoManagerId, PostgresRedoManager),
363 : #[cfg(test)]
364 : Test(harness::TestRedoManager),
365 : }
366 :
367 : #[derive(thiserror::Error, Debug)]
368 : #[error("pageserver is shutting down")]
369 : pub(crate) struct GlobalShutDown;
370 :
371 : impl WalRedoManager {
372 0 : pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
373 0 : let id = WalredoManagerId::next();
374 0 : let arc = Arc::new(Self::Prod(id, mgr));
375 0 : let mut guard = WALREDO_MANAGERS.lock().unwrap();
376 0 : match &mut *guard {
377 0 : Some(map) => {
378 0 : map.insert(id, Arc::downgrade(&arc));
379 0 : Ok(arc)
380 : }
381 0 : None => Err(GlobalShutDown),
382 : }
383 0 : }
384 : }
385 :
386 : impl Drop for WalRedoManager {
387 20 : fn drop(&mut self) {
388 20 : match self {
389 0 : Self::Prod(id, _) => {
390 0 : let mut guard = WALREDO_MANAGERS.lock().unwrap();
391 0 : if let Some(map) = &mut *guard {
392 0 : map.remove(id).expect("new() registers, drop() unregisters");
393 0 : }
394 : }
395 : #[cfg(test)]
396 20 : Self::Test(_) => {
397 20 : // Not applicable to test redo manager
398 20 : }
399 : }
400 20 : }
401 : }
402 :
403 : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
404 : /// the walredo processes outside of the regular order.
405 : ///
406 : /// This is necessary to work around a systemd bug where it freezes if there are
407 : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
408 : #[allow(clippy::type_complexity)]
409 : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
410 : Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
411 0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
412 : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
413 : pub(crate) struct WalredoManagerId(u64);
414 : impl WalredoManagerId {
415 0 : pub fn next() -> Self {
416 : static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
417 0 : let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
418 0 : if id == 0 {
419 0 : panic!(
420 0 : "WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique"
421 0 : );
422 0 : }
423 0 : Self(id)
424 0 : }
425 : }
426 :
427 : #[cfg(test)]
428 : impl From<harness::TestRedoManager> for WalRedoManager {
429 454 : fn from(mgr: harness::TestRedoManager) -> Self {
430 454 : Self::Test(mgr)
431 454 : }
432 : }
433 :
434 : impl WalRedoManager {
435 12 : pub(crate) async fn shutdown(&self) -> bool {
436 12 : match self {
437 0 : Self::Prod(_, mgr) => mgr.shutdown().await,
438 : #[cfg(test)]
439 : Self::Test(_) => {
440 : // Not applicable to test redo manager
441 12 : true
442 : }
443 : }
444 12 : }
445 :
446 0 : pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
447 0 : match self {
448 0 : Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
449 0 : #[cfg(test)]
450 0 : Self::Test(_) => {
451 0 : // Not applicable to test redo manager
452 0 : }
453 0 : }
454 0 : }
455 :
456 : /// # Cancel-Safety
457 : ///
458 : /// This method is cancellation-safe.
459 1676 : pub async fn request_redo(
460 1676 : &self,
461 1676 : key: pageserver_api::key::Key,
462 1676 : lsn: Lsn,
463 1676 : base_img: Option<(Lsn, bytes::Bytes)>,
464 1676 : records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
465 1676 : pg_version: u32,
466 1676 : ) -> Result<bytes::Bytes, walredo::Error> {
467 1676 : match self {
468 0 : Self::Prod(_, mgr) => {
469 0 : mgr.request_redo(key, lsn, base_img, records, pg_version)
470 0 : .await
471 : }
472 : #[cfg(test)]
473 1676 : Self::Test(mgr) => {
474 1676 : mgr.request_redo(key, lsn, base_img, records, pg_version)
475 1676 : .await
476 : }
477 : }
478 1676 : }
479 :
480 0 : pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
481 0 : match self {
482 0 : WalRedoManager::Prod(_, m) => Some(m.status()),
483 0 : #[cfg(test)]
484 0 : WalRedoManager::Test(_) => None,
485 0 : }
486 0 : }
487 : }
488 :
489 : /// A very lightweight memory representation of an offloaded timeline.
490 : ///
491 : /// We need to store the list of offloaded timelines so that we can perform operations on them,
492 : /// like unoffloading them, or (at a later date), decide to perform flattening.
493 : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
494 : /// more offloaded timelines than we can manage ones that aren't.
495 : pub struct OffloadedTimeline {
496 : pub tenant_shard_id: TenantShardId,
497 : pub timeline_id: TimelineId,
498 : pub ancestor_timeline_id: Option<TimelineId>,
499 : /// Whether to retain the branch lsn at the ancestor or not
500 : pub ancestor_retain_lsn: Option<Lsn>,
501 :
502 : /// When the timeline was archived.
503 : ///
504 : /// Present for future flattening deliberations.
505 : pub archived_at: NaiveDateTime,
506 :
507 : /// Prevent two tasks from deleting the timeline at the same time. If held, the
508 : /// timeline is being deleted. If 'true', the timeline has already been deleted.
509 : pub delete_progress: TimelineDeleteProgress,
510 :
511 : /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
512 : pub deleted_from_ancestor: AtomicBool,
513 : }
514 :
515 : impl OffloadedTimeline {
516 : /// Obtains an offloaded timeline from a given timeline object.
517 : ///
518 : /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
519 : /// the timeline is not in a stopped state.
520 : /// Panics if the timeline is not archived.
521 4 : fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
522 4 : let (ancestor_retain_lsn, ancestor_timeline_id) =
523 4 : if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
524 4 : let ancestor_lsn = timeline.get_ancestor_lsn();
525 4 : let ancestor_timeline_id = ancestor_timeline.timeline_id;
526 4 : let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
527 4 : gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
528 4 : (Some(ancestor_lsn), Some(ancestor_timeline_id))
529 : } else {
530 0 : (None, None)
531 : };
532 4 : let archived_at = timeline
533 4 : .remote_client
534 4 : .archived_at_stopped_queue()?
535 4 : .expect("must be called on an archived timeline");
536 4 : Ok(Self {
537 4 : tenant_shard_id: timeline.tenant_shard_id,
538 4 : timeline_id: timeline.timeline_id,
539 4 : ancestor_timeline_id,
540 4 : ancestor_retain_lsn,
541 4 : archived_at,
542 4 :
543 4 : delete_progress: timeline.delete_progress.clone(),
544 4 : deleted_from_ancestor: AtomicBool::new(false),
545 4 : })
546 4 : }
547 0 : fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
548 0 : // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
549 0 : // by the `initialize_gc_info` function.
550 0 : let OffloadedTimelineManifest {
551 0 : timeline_id,
552 0 : ancestor_timeline_id,
553 0 : ancestor_retain_lsn,
554 0 : archived_at,
555 0 : } = *manifest;
556 0 : Self {
557 0 : tenant_shard_id,
558 0 : timeline_id,
559 0 : ancestor_timeline_id,
560 0 : ancestor_retain_lsn,
561 0 : archived_at,
562 0 : delete_progress: TimelineDeleteProgress::default(),
563 0 : deleted_from_ancestor: AtomicBool::new(false),
564 0 : }
565 0 : }
566 4 : fn manifest(&self) -> OffloadedTimelineManifest {
567 4 : let Self {
568 4 : timeline_id,
569 4 : ancestor_timeline_id,
570 4 : ancestor_retain_lsn,
571 4 : archived_at,
572 4 : ..
573 4 : } = self;
574 4 : OffloadedTimelineManifest {
575 4 : timeline_id: *timeline_id,
576 4 : ancestor_timeline_id: *ancestor_timeline_id,
577 4 : ancestor_retain_lsn: *ancestor_retain_lsn,
578 4 : archived_at: *archived_at,
579 4 : }
580 4 : }
581 : /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
582 0 : fn delete_from_ancestor_with_timelines(
583 0 : &self,
584 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
585 0 : ) {
586 0 : if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
587 0 : (self.ancestor_retain_lsn, self.ancestor_timeline_id)
588 : {
589 0 : if let Some((_, ancestor_timeline)) = timelines
590 0 : .iter()
591 0 : .find(|(tid, _tl)| **tid == ancestor_timeline_id)
592 : {
593 0 : let removal_happened = ancestor_timeline
594 0 : .gc_info
595 0 : .write()
596 0 : .unwrap()
597 0 : .remove_child_offloaded(self.timeline_id);
598 0 : if !removal_happened {
599 0 : tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
600 0 : "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
601 0 : }
602 0 : }
603 0 : }
604 0 : self.deleted_from_ancestor.store(true, Ordering::Release);
605 0 : }
606 : /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
607 : ///
608 : /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
609 4 : fn defuse_for_tenant_drop(&self) {
610 4 : self.deleted_from_ancestor.store(true, Ordering::Release);
611 4 : }
612 : }
613 :
614 : impl fmt::Debug for OffloadedTimeline {
615 0 : fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
616 0 : write!(f, "OffloadedTimeline<{}>", self.timeline_id)
617 0 : }
618 : }
619 :
620 : impl Drop for OffloadedTimeline {
621 4 : fn drop(&mut self) {
622 4 : if !self.deleted_from_ancestor.load(Ordering::Acquire) {
623 0 : tracing::warn!(
624 0 : "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
625 : self.timeline_id
626 : );
627 4 : }
628 4 : }
629 : }
630 :
631 : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
632 : pub enum MaybeOffloaded {
633 : Yes,
634 : No,
635 : }
636 :
637 : #[derive(Clone, Debug)]
638 : pub enum TimelineOrOffloaded {
639 : Timeline(Arc<Timeline>),
640 : Offloaded(Arc<OffloadedTimeline>),
641 : }
642 :
643 : impl TimelineOrOffloaded {
644 0 : pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
645 0 : match self {
646 0 : TimelineOrOffloaded::Timeline(timeline) => {
647 0 : TimelineOrOffloadedArcRef::Timeline(timeline)
648 : }
649 0 : TimelineOrOffloaded::Offloaded(offloaded) => {
650 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded)
651 : }
652 : }
653 0 : }
654 0 : pub fn tenant_shard_id(&self) -> TenantShardId {
655 0 : self.arc_ref().tenant_shard_id()
656 0 : }
657 0 : pub fn timeline_id(&self) -> TimelineId {
658 0 : self.arc_ref().timeline_id()
659 0 : }
660 4 : pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
661 4 : match self {
662 4 : TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
663 0 : TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
664 : }
665 4 : }
666 0 : fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
667 0 : match self {
668 0 : TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
669 0 : TimelineOrOffloaded::Offloaded(_offloaded) => None,
670 : }
671 0 : }
672 : }
673 :
674 : pub enum TimelineOrOffloadedArcRef<'a> {
675 : Timeline(&'a Arc<Timeline>),
676 : Offloaded(&'a Arc<OffloadedTimeline>),
677 : }
678 :
679 : impl TimelineOrOffloadedArcRef<'_> {
680 0 : pub fn tenant_shard_id(&self) -> TenantShardId {
681 0 : match self {
682 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
683 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
684 : }
685 0 : }
686 0 : pub fn timeline_id(&self) -> TimelineId {
687 0 : match self {
688 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
689 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
690 : }
691 0 : }
692 : }
693 :
694 : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
695 0 : fn from(timeline: &'a Arc<Timeline>) -> Self {
696 0 : Self::Timeline(timeline)
697 0 : }
698 : }
699 :
700 : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
701 0 : fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
702 0 : Self::Offloaded(timeline)
703 0 : }
704 : }
705 :
706 : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
707 : pub enum GetTimelineError {
708 : #[error("Timeline is shutting down")]
709 : ShuttingDown,
710 : #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
711 : NotActive {
712 : tenant_id: TenantShardId,
713 : timeline_id: TimelineId,
714 : state: TimelineState,
715 : },
716 : #[error("Timeline {tenant_id}/{timeline_id} was not found")]
717 : NotFound {
718 : tenant_id: TenantShardId,
719 : timeline_id: TimelineId,
720 : },
721 : }
722 :
723 : #[derive(Debug, thiserror::Error)]
724 : pub enum LoadLocalTimelineError {
725 : #[error("FailedToLoad")]
726 : Load(#[source] anyhow::Error),
727 : #[error("FailedToResumeDeletion")]
728 : ResumeDeletion(#[source] anyhow::Error),
729 : }
730 :
731 : #[derive(thiserror::Error)]
732 : pub enum DeleteTimelineError {
733 : #[error("NotFound")]
734 : NotFound,
735 :
736 : #[error("HasChildren")]
737 : HasChildren(Vec<TimelineId>),
738 :
739 : #[error("Timeline deletion is already in progress")]
740 : AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
741 :
742 : #[error("Cancelled")]
743 : Cancelled,
744 :
745 : #[error(transparent)]
746 : Other(#[from] anyhow::Error),
747 : }
748 :
749 : impl Debug for DeleteTimelineError {
750 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
751 0 : match self {
752 0 : Self::NotFound => write!(f, "NotFound"),
753 0 : Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
754 0 : Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
755 0 : Self::Cancelled => f.debug_tuple("Cancelled").finish(),
756 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
757 : }
758 0 : }
759 : }
760 :
761 : #[derive(thiserror::Error)]
762 : pub enum TimelineArchivalError {
763 : #[error("NotFound")]
764 : NotFound,
765 :
766 : #[error("Timeout")]
767 : Timeout,
768 :
769 : #[error("Cancelled")]
770 : Cancelled,
771 :
772 : #[error("ancestor is archived: {}", .0)]
773 : HasArchivedParent(TimelineId),
774 :
775 : #[error("HasUnarchivedChildren")]
776 : HasUnarchivedChildren(Vec<TimelineId>),
777 :
778 : #[error("Timeline archival is already in progress")]
779 : AlreadyInProgress,
780 :
781 : #[error(transparent)]
782 : Other(anyhow::Error),
783 : }
784 :
785 : #[derive(thiserror::Error, Debug)]
786 : pub(crate) enum TenantManifestError {
787 : #[error("Remote storage error: {0}")]
788 : RemoteStorage(anyhow::Error),
789 :
790 : #[error("Cancelled")]
791 : Cancelled,
792 : }
793 :
794 : impl From<TenantManifestError> for TimelineArchivalError {
795 0 : fn from(e: TenantManifestError) -> Self {
796 0 : match e {
797 0 : TenantManifestError::RemoteStorage(e) => Self::Other(e),
798 0 : TenantManifestError::Cancelled => Self::Cancelled,
799 : }
800 0 : }
801 : }
802 :
803 : impl Debug for TimelineArchivalError {
804 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
805 0 : match self {
806 0 : Self::NotFound => write!(f, "NotFound"),
807 0 : Self::Timeout => write!(f, "Timeout"),
808 0 : Self::Cancelled => write!(f, "Cancelled"),
809 0 : Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
810 0 : Self::HasUnarchivedChildren(c) => {
811 0 : f.debug_tuple("HasUnarchivedChildren").field(c).finish()
812 : }
813 0 : Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
814 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
815 : }
816 0 : }
817 : }
818 :
819 : pub enum SetStoppingError {
820 : AlreadyStopping(completion::Barrier),
821 : Broken,
822 : }
823 :
824 : impl Debug for SetStoppingError {
825 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
826 0 : match self {
827 0 : Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
828 0 : Self::Broken => write!(f, "Broken"),
829 : }
830 0 : }
831 : }
832 :
833 : /// Arguments to [`Tenant::create_timeline`].
834 : ///
835 : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
836 : /// is `None`, the result of the timeline create call is not deterministic.
837 : ///
838 : /// See [`CreateTimelineIdempotency`] for an idempotency key.
839 : #[derive(Debug)]
840 : pub(crate) enum CreateTimelineParams {
841 : Bootstrap(CreateTimelineParamsBootstrap),
842 : Branch(CreateTimelineParamsBranch),
843 : ImportPgdata(CreateTimelineParamsImportPgdata),
844 : }
845 :
846 : #[derive(Debug)]
847 : pub(crate) struct CreateTimelineParamsBootstrap {
848 : pub(crate) new_timeline_id: TimelineId,
849 : pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
850 : pub(crate) pg_version: u32,
851 : }
852 :
853 : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
854 : #[derive(Debug)]
855 : pub(crate) struct CreateTimelineParamsBranch {
856 : pub(crate) new_timeline_id: TimelineId,
857 : pub(crate) ancestor_timeline_id: TimelineId,
858 : pub(crate) ancestor_start_lsn: Option<Lsn>,
859 : }
860 :
861 : #[derive(Debug)]
862 : pub(crate) struct CreateTimelineParamsImportPgdata {
863 : pub(crate) new_timeline_id: TimelineId,
864 : pub(crate) location: import_pgdata::index_part_format::Location,
865 : pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
866 : }
867 :
868 : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in [`Tenant::start_creating_timeline`] in [`Tenant::start_creating_timeline`].
869 : ///
870 : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
871 : ///
872 : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
873 : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
874 : ///
875 : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
876 : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
877 : ///
878 : /// Notes:
879 : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
880 : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
881 : /// is not considered for idempotency. We can improve on this over time if we deem it necessary.
882 : ///
883 : #[derive(Debug, Clone, PartialEq, Eq)]
884 : pub(crate) enum CreateTimelineIdempotency {
885 : /// NB: special treatment, see comment in [`Self`].
886 : FailWithConflict,
887 : Bootstrap {
888 : pg_version: u32,
889 : },
890 : /// NB: branches always have the same `pg_version` as their ancestor.
891 : /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
892 : /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
893 : /// determining the child branch pg_version.
894 : Branch {
895 : ancestor_timeline_id: TimelineId,
896 : ancestor_start_lsn: Lsn,
897 : },
898 : ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
899 : }
900 :
901 : #[derive(Debug, Clone, PartialEq, Eq)]
902 : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
903 : idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
904 : }
905 :
906 : /// What is returned by [`Tenant::start_creating_timeline`].
907 : #[must_use]
908 : enum StartCreatingTimelineResult {
909 : CreateGuard(TimelineCreateGuard),
910 : Idempotent(Arc<Timeline>),
911 : }
912 :
913 : enum TimelineInitAndSyncResult {
914 : ReadyToActivate(Arc<Timeline>),
915 : NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
916 : }
917 :
918 : impl TimelineInitAndSyncResult {
919 0 : fn ready_to_activate(self) -> Option<Arc<Timeline>> {
920 0 : match self {
921 0 : Self::ReadyToActivate(timeline) => Some(timeline),
922 0 : _ => None,
923 : }
924 0 : }
925 : }
926 :
927 : #[must_use]
928 : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
929 : timeline: Arc<Timeline>,
930 : import_pgdata: import_pgdata::index_part_format::Root,
931 : guard: TimelineCreateGuard,
932 : }
933 :
934 : /// What is returned by [`Tenant::create_timeline`].
935 : enum CreateTimelineResult {
936 : Created(Arc<Timeline>),
937 : Idempotent(Arc<Timeline>),
938 : /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
939 : /// we return this result, nor will this concrete object ever be added there.
940 : /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
941 : ImportSpawned(Arc<Timeline>),
942 : }
943 :
944 : impl CreateTimelineResult {
945 0 : fn discriminant(&self) -> &'static str {
946 0 : match self {
947 0 : Self::Created(_) => "Created",
948 0 : Self::Idempotent(_) => "Idempotent",
949 0 : Self::ImportSpawned(_) => "ImportSpawned",
950 : }
951 0 : }
952 0 : fn timeline(&self) -> &Arc<Timeline> {
953 0 : match self {
954 0 : Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
955 0 : }
956 0 : }
957 : /// Unit test timelines aren't activated, test has to do it if it needs to.
958 : #[cfg(test)]
959 460 : fn into_timeline_for_test(self) -> Arc<Timeline> {
960 460 : match self {
961 460 : Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
962 460 : }
963 460 : }
964 : }
965 :
966 : #[derive(thiserror::Error, Debug)]
967 : pub enum CreateTimelineError {
968 : #[error("creation of timeline with the given ID is in progress")]
969 : AlreadyCreating,
970 : #[error("timeline already exists with different parameters")]
971 : Conflict,
972 : #[error(transparent)]
973 : AncestorLsn(anyhow::Error),
974 : #[error("ancestor timeline is not active")]
975 : AncestorNotActive,
976 : #[error("ancestor timeline is archived")]
977 : AncestorArchived,
978 : #[error("tenant shutting down")]
979 : ShuttingDown,
980 : #[error(transparent)]
981 : Other(#[from] anyhow::Error),
982 : }
983 :
984 : #[derive(thiserror::Error, Debug)]
985 : pub enum InitdbError {
986 : #[error("Operation was cancelled")]
987 : Cancelled,
988 : #[error(transparent)]
989 : Other(anyhow::Error),
990 : #[error(transparent)]
991 : Inner(postgres_initdb::Error),
992 : }
993 :
994 : enum CreateTimelineCause {
995 : Load,
996 : Delete,
997 : }
998 :
999 : enum LoadTimelineCause {
1000 : Attach,
1001 : Unoffload,
1002 : ImportPgdata {
1003 : create_guard: TimelineCreateGuard,
1004 : activate: ActivateTimelineArgs,
1005 : },
1006 : }
1007 :
1008 : #[derive(thiserror::Error, Debug)]
1009 : pub(crate) enum GcError {
1010 : // The tenant is shutting down
1011 : #[error("tenant shutting down")]
1012 : TenantCancelled,
1013 :
1014 : // The tenant is shutting down
1015 : #[error("timeline shutting down")]
1016 : TimelineCancelled,
1017 :
1018 : // The tenant is in a state inelegible to run GC
1019 : #[error("not active")]
1020 : NotActive,
1021 :
1022 : // A requested GC cutoff LSN was invalid, for example it tried to move backwards
1023 : #[error("not active")]
1024 : BadLsn { why: String },
1025 :
1026 : // A remote storage error while scheduling updates after compaction
1027 : #[error(transparent)]
1028 : Remote(anyhow::Error),
1029 :
1030 : // An error reading while calculating GC cutoffs
1031 : #[error(transparent)]
1032 : GcCutoffs(PageReconstructError),
1033 :
1034 : // If GC was invoked for a particular timeline, this error means it didn't exist
1035 : #[error("timeline not found")]
1036 : TimelineNotFound,
1037 : }
1038 :
1039 : impl From<PageReconstructError> for GcError {
1040 0 : fn from(value: PageReconstructError) -> Self {
1041 0 : match value {
1042 0 : PageReconstructError::Cancelled => Self::TimelineCancelled,
1043 0 : other => Self::GcCutoffs(other),
1044 : }
1045 0 : }
1046 : }
1047 :
1048 : impl From<NotInitialized> for GcError {
1049 0 : fn from(value: NotInitialized) -> Self {
1050 0 : match value {
1051 0 : NotInitialized::Uninitialized => GcError::Remote(value.into()),
1052 0 : NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
1053 : }
1054 0 : }
1055 : }
1056 :
1057 : impl From<timeline::layer_manager::Shutdown> for GcError {
1058 0 : fn from(_: timeline::layer_manager::Shutdown) -> Self {
1059 0 : GcError::TimelineCancelled
1060 0 : }
1061 : }
1062 :
1063 : #[derive(thiserror::Error, Debug)]
1064 : pub(crate) enum LoadConfigError {
1065 : #[error("TOML deserialization error: '{0}'")]
1066 : DeserializeToml(#[from] toml_edit::de::Error),
1067 :
1068 : #[error("Config not found at {0}")]
1069 : NotFound(Utf8PathBuf),
1070 : }
1071 :
1072 : impl Tenant {
1073 : /// Yet another helper for timeline initialization.
1074 : ///
1075 : /// - Initializes the Timeline struct and inserts it into the tenant's hash map
1076 : /// - Scans the local timeline directory for layer files and builds the layer map
1077 : /// - Downloads remote index file and adds remote files to the layer map
1078 : /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
1079 : ///
1080 : /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
1081 : /// it is marked as Active.
1082 : #[allow(clippy::too_many_arguments)]
1083 12 : async fn timeline_init_and_sync(
1084 12 : self: &Arc<Self>,
1085 12 : timeline_id: TimelineId,
1086 12 : resources: TimelineResources,
1087 12 : mut index_part: IndexPart,
1088 12 : metadata: TimelineMetadata,
1089 12 : previous_heatmap: Option<PreviousHeatmap>,
1090 12 : ancestor: Option<Arc<Timeline>>,
1091 12 : cause: LoadTimelineCause,
1092 12 : ctx: &RequestContext,
1093 12 : ) -> anyhow::Result<TimelineInitAndSyncResult> {
1094 12 : let tenant_id = self.tenant_shard_id;
1095 12 :
1096 12 : let import_pgdata = index_part.import_pgdata.take();
1097 12 : let idempotency = match &import_pgdata {
1098 0 : Some(import_pgdata) => {
1099 0 : CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
1100 0 : idempotency_key: import_pgdata.idempotency_key().clone(),
1101 0 : })
1102 : }
1103 : None => {
1104 12 : if metadata.ancestor_timeline().is_none() {
1105 8 : CreateTimelineIdempotency::Bootstrap {
1106 8 : pg_version: metadata.pg_version(),
1107 8 : }
1108 : } else {
1109 4 : CreateTimelineIdempotency::Branch {
1110 4 : ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
1111 4 : ancestor_start_lsn: metadata.ancestor_lsn(),
1112 4 : }
1113 : }
1114 : }
1115 : };
1116 :
1117 12 : let timeline = self.create_timeline_struct(
1118 12 : timeline_id,
1119 12 : &metadata,
1120 12 : previous_heatmap,
1121 12 : ancestor.clone(),
1122 12 : resources,
1123 12 : CreateTimelineCause::Load,
1124 12 : idempotency.clone(),
1125 12 : index_part.gc_compaction.clone(),
1126 12 : )?;
1127 12 : let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
1128 12 : anyhow::ensure!(
1129 12 : disk_consistent_lsn.is_valid(),
1130 0 : "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
1131 : );
1132 12 : assert_eq!(
1133 12 : disk_consistent_lsn,
1134 12 : metadata.disk_consistent_lsn(),
1135 0 : "these are used interchangeably"
1136 : );
1137 :
1138 12 : timeline.remote_client.init_upload_queue(&index_part)?;
1139 :
1140 12 : timeline
1141 12 : .load_layer_map(disk_consistent_lsn, index_part)
1142 12 : .await
1143 12 : .with_context(|| {
1144 0 : format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
1145 12 : })?;
1146 :
1147 : // When unarchiving, we've mostly likely lost the heatmap generated prior
1148 : // to the archival operation. To allow warming this timeline up, generate
1149 : // a previous heatmap which contains all visible layers in the layer map.
1150 : // This previous heatmap will be used whenever a fresh heatmap is generated
1151 : // for the timeline.
1152 12 : if matches!(cause, LoadTimelineCause::Unoffload) {
1153 0 : let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
1154 0 : while let Some((tline, end_lsn)) = tline_ending_at {
1155 0 : let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
1156 : // Another unearchived timeline might have generated a heatmap for this ancestor.
1157 : // If the current branch point greater than the previous one use the the heatmap
1158 : // we just generated - it should include more layers.
1159 0 : if !tline.should_keep_previous_heatmap(end_lsn) {
1160 0 : tline
1161 0 : .previous_heatmap
1162 0 : .store(Some(Arc::new(unarchival_heatmap)));
1163 0 : } else {
1164 0 : tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
1165 : }
1166 :
1167 0 : match tline.ancestor_timeline() {
1168 0 : Some(ancestor) => {
1169 0 : if ancestor.update_layer_visibility().await.is_err() {
1170 : // Ancestor timeline is shutting down.
1171 0 : break;
1172 0 : }
1173 0 :
1174 0 : tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
1175 : }
1176 0 : None => {
1177 0 : tline_ending_at = None;
1178 0 : }
1179 : }
1180 : }
1181 12 : }
1182 :
1183 0 : match import_pgdata {
1184 0 : Some(import_pgdata) if !import_pgdata.is_done() => {
1185 0 : match cause {
1186 0 : LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
1187 : LoadTimelineCause::ImportPgdata { .. } => {
1188 0 : unreachable!(
1189 0 : "ImportPgdata should not be reloading timeline import is done and persisted as such in s3"
1190 0 : )
1191 : }
1192 : }
1193 0 : let mut guard = self.timelines_creating.lock().unwrap();
1194 0 : if !guard.insert(timeline_id) {
1195 : // We should never try and load the same timeline twice during startup
1196 0 : unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
1197 0 : }
1198 0 : let timeline_create_guard = TimelineCreateGuard {
1199 0 : _tenant_gate_guard: self.gate.enter()?,
1200 0 : owning_tenant: self.clone(),
1201 0 : timeline_id,
1202 0 : idempotency,
1203 0 : // The users of this specific return value don't need the timline_path in there.
1204 0 : timeline_path: timeline
1205 0 : .conf
1206 0 : .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
1207 0 : };
1208 0 : Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
1209 0 : TimelineInitAndSyncNeedsSpawnImportPgdata {
1210 0 : timeline,
1211 0 : import_pgdata,
1212 0 : guard: timeline_create_guard,
1213 0 : },
1214 0 : ))
1215 : }
1216 : Some(_) | None => {
1217 : {
1218 12 : let mut timelines_accessor = self.timelines.lock().unwrap();
1219 12 : match timelines_accessor.entry(timeline_id) {
1220 : // We should never try and load the same timeline twice during startup
1221 : Entry::Occupied(_) => {
1222 0 : unreachable!(
1223 0 : "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
1224 0 : );
1225 : }
1226 12 : Entry::Vacant(v) => {
1227 12 : v.insert(Arc::clone(&timeline));
1228 12 : timeline.maybe_spawn_flush_loop();
1229 12 : }
1230 : }
1231 : }
1232 :
1233 : // Sanity check: a timeline should have some content.
1234 12 : anyhow::ensure!(
1235 12 : ancestor.is_some()
1236 8 : || timeline
1237 8 : .layers
1238 8 : .read()
1239 8 : .await
1240 8 : .layer_map()
1241 8 : .expect("currently loading, layer manager cannot be shutdown already")
1242 8 : .iter_historic_layers()
1243 8 : .next()
1244 8 : .is_some(),
1245 0 : "Timeline has no ancestor and no layer files"
1246 : );
1247 :
1248 12 : match cause {
1249 12 : LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
1250 : LoadTimelineCause::ImportPgdata {
1251 0 : create_guard,
1252 0 : activate,
1253 0 : } => {
1254 0 : // TODO: see the comment in the task code above how I'm not so certain
1255 0 : // it is safe to activate here because of concurrent shutdowns.
1256 0 : match activate {
1257 0 : ActivateTimelineArgs::Yes { broker_client } => {
1258 0 : info!("activating timeline after reload from pgdata import task");
1259 0 : timeline.activate(self.clone(), broker_client, None, ctx);
1260 : }
1261 0 : ActivateTimelineArgs::No => (),
1262 : }
1263 0 : drop(create_guard);
1264 : }
1265 : }
1266 :
1267 12 : Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
1268 : }
1269 : }
1270 12 : }
1271 :
1272 : /// Attach a tenant that's available in cloud storage.
1273 : ///
1274 : /// This returns quickly, after just creating the in-memory object
1275 : /// Tenant struct and launching a background task to download
1276 : /// the remote index files. On return, the tenant is most likely still in
1277 : /// Attaching state, and it will become Active once the background task
1278 : /// finishes. You can use wait_until_active() to wait for the task to
1279 : /// complete.
1280 : ///
1281 : #[allow(clippy::too_many_arguments)]
1282 0 : pub(crate) fn spawn(
1283 0 : conf: &'static PageServerConf,
1284 0 : tenant_shard_id: TenantShardId,
1285 0 : resources: TenantSharedResources,
1286 0 : attached_conf: AttachedTenantConf,
1287 0 : shard_identity: ShardIdentity,
1288 0 : init_order: Option<InitializationOrder>,
1289 0 : mode: SpawnMode,
1290 0 : ctx: &RequestContext,
1291 0 : ) -> Result<Arc<Tenant>, GlobalShutDown> {
1292 0 : let wal_redo_manager =
1293 0 : WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
1294 :
1295 : let TenantSharedResources {
1296 0 : broker_client,
1297 0 : remote_storage,
1298 0 : deletion_queue_client,
1299 0 : l0_flush_global_state,
1300 0 : } = resources;
1301 0 :
1302 0 : let attach_mode = attached_conf.location.attach_mode;
1303 0 : let generation = attached_conf.location.generation;
1304 0 :
1305 0 : let tenant = Arc::new(Tenant::new(
1306 0 : TenantState::Attaching,
1307 0 : conf,
1308 0 : attached_conf,
1309 0 : shard_identity,
1310 0 : Some(wal_redo_manager),
1311 0 : tenant_shard_id,
1312 0 : remote_storage.clone(),
1313 0 : deletion_queue_client,
1314 0 : l0_flush_global_state,
1315 0 : ));
1316 0 :
1317 0 : // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
1318 0 : // we shut down while attaching.
1319 0 : let attach_gate_guard = tenant
1320 0 : .gate
1321 0 : .enter()
1322 0 : .expect("We just created the Tenant: nothing else can have shut it down yet");
1323 0 :
1324 0 : // Do all the hard work in the background
1325 0 : let tenant_clone = Arc::clone(&tenant);
1326 0 : let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
1327 0 : task_mgr::spawn(
1328 0 : &tokio::runtime::Handle::current(),
1329 0 : TaskKind::Attach,
1330 0 : tenant_shard_id,
1331 0 : None,
1332 0 : "attach tenant",
1333 0 : async move {
1334 0 :
1335 0 : info!(
1336 : ?attach_mode,
1337 0 : "Attaching tenant"
1338 : );
1339 :
1340 0 : let _gate_guard = attach_gate_guard;
1341 0 :
1342 0 : // Is this tenant being spawned as part of process startup?
1343 0 : let starting_up = init_order.is_some();
1344 0 : scopeguard::defer! {
1345 0 : if starting_up {
1346 0 : TENANT.startup_complete.inc();
1347 0 : }
1348 0 : }
1349 :
1350 : // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
1351 : enum BrokenVerbosity {
1352 : Error,
1353 : Info
1354 : }
1355 0 : let make_broken =
1356 0 : |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
1357 0 : match verbosity {
1358 : BrokenVerbosity::Info => {
1359 0 : info!("attach cancelled, setting tenant state to Broken: {err}");
1360 : },
1361 : BrokenVerbosity::Error => {
1362 0 : error!("attach failed, setting tenant state to Broken: {err:?}");
1363 : }
1364 : }
1365 0 : t.state.send_modify(|state| {
1366 0 : // The Stopping case is for when we have passed control on to DeleteTenantFlow:
1367 0 : // if it errors, we will call make_broken when tenant is already in Stopping.
1368 0 : assert!(
1369 0 : matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
1370 0 : "the attach task owns the tenant state until activation is complete"
1371 : );
1372 :
1373 0 : *state = TenantState::broken_from_reason(err.to_string());
1374 0 : });
1375 0 : };
1376 :
1377 : // TODO: should also be rejecting tenant conf changes that violate this check.
1378 0 : if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
1379 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1380 0 : return Ok(());
1381 0 : }
1382 0 :
1383 0 : let mut init_order = init_order;
1384 0 : // take the completion because initial tenant loading will complete when all of
1385 0 : // these tasks complete.
1386 0 : let _completion = init_order
1387 0 : .as_mut()
1388 0 : .and_then(|x| x.initial_tenant_load.take());
1389 0 : let remote_load_completion = init_order
1390 0 : .as_mut()
1391 0 : .and_then(|x| x.initial_tenant_load_remote.take());
1392 :
1393 : enum AttachType<'a> {
1394 : /// We are attaching this tenant lazily in the background.
1395 : Warmup {
1396 : _permit: tokio::sync::SemaphorePermit<'a>,
1397 : during_startup: bool
1398 : },
1399 : /// We are attaching this tenant as soon as we can, because for example an
1400 : /// endpoint tried to access it.
1401 : OnDemand,
1402 : /// During normal operations after startup, we are attaching a tenant, and
1403 : /// eager attach was requested.
1404 : Normal,
1405 : }
1406 :
1407 0 : let attach_type = if matches!(mode, SpawnMode::Lazy) {
1408 : // Before doing any I/O, wait for at least one of:
1409 : // - A client attempting to access to this tenant (on-demand loading)
1410 : // - A permit becoming available in the warmup semaphore (background warmup)
1411 :
1412 0 : tokio::select!(
1413 0 : permit = tenant_clone.activate_now_sem.acquire() => {
1414 0 : let _ = permit.expect("activate_now_sem is never closed");
1415 0 : tracing::info!("Activating tenant (on-demand)");
1416 0 : AttachType::OnDemand
1417 : },
1418 0 : permit = conf.concurrent_tenant_warmup.inner().acquire() => {
1419 0 : let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
1420 0 : tracing::info!("Activating tenant (warmup)");
1421 0 : AttachType::Warmup {
1422 0 : _permit,
1423 0 : during_startup: init_order.is_some()
1424 0 : }
1425 : }
1426 0 : _ = tenant_clone.cancel.cancelled() => {
1427 : // This is safe, but should be pretty rare: it is interesting if a tenant
1428 : // stayed in Activating for such a long time that shutdown found it in
1429 : // that state.
1430 0 : tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
1431 : // Make the tenant broken so that set_stopping will not hang waiting for it to leave
1432 : // the Attaching state. This is an over-reaction (nothing really broke, the tenant is
1433 : // just shutting down), but ensures progress.
1434 0 : make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
1435 0 : return Ok(());
1436 : },
1437 : )
1438 : } else {
1439 : // SpawnMode::{Create,Eager} always cause jumping ahead of the
1440 : // concurrent_tenant_warmup queue
1441 0 : AttachType::Normal
1442 : };
1443 :
1444 0 : let preload = match &mode {
1445 : SpawnMode::Eager | SpawnMode::Lazy => {
1446 0 : let _preload_timer = TENANT.preload.start_timer();
1447 0 : let res = tenant_clone
1448 0 : .preload(&remote_storage, task_mgr::shutdown_token())
1449 0 : .await;
1450 0 : match res {
1451 0 : Ok(p) => Some(p),
1452 0 : Err(e) => {
1453 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1454 0 : return Ok(());
1455 : }
1456 : }
1457 : }
1458 :
1459 : };
1460 :
1461 : // Remote preload is complete.
1462 0 : drop(remote_load_completion);
1463 0 :
1464 0 :
1465 0 : // We will time the duration of the attach phase unless this is a creation (attach will do no work)
1466 0 : let attach_start = std::time::Instant::now();
1467 0 : let attached = {
1468 0 : let _attach_timer = Some(TENANT.attach.start_timer());
1469 0 : tenant_clone.attach(preload, &ctx).await
1470 : };
1471 0 : let attach_duration = attach_start.elapsed();
1472 0 : _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
1473 0 :
1474 0 : match attached {
1475 : Ok(()) => {
1476 0 : info!("attach finished, activating");
1477 0 : tenant_clone.activate(broker_client, None, &ctx);
1478 : }
1479 0 : Err(e) => {
1480 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1481 0 : }
1482 : }
1483 :
1484 : // If we are doing an opportunistic warmup attachment at startup, initialize
1485 : // logical size at the same time. This is better than starting a bunch of idle tenants
1486 : // with cold caches and then coming back later to initialize their logical sizes.
1487 : //
1488 : // It also prevents the warmup proccess competing with the concurrency limit on
1489 : // logical size calculations: if logical size calculation semaphore is saturated,
1490 : // then warmup will wait for that before proceeding to the next tenant.
1491 0 : if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
1492 0 : let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
1493 0 : tracing::info!("Waiting for initial logical sizes while warming up...");
1494 0 : while futs.next().await.is_some() {}
1495 0 : tracing::info!("Warm-up complete");
1496 0 : }
1497 :
1498 0 : Ok(())
1499 0 : }
1500 0 : .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
1501 : );
1502 0 : Ok(tenant)
1503 0 : }
1504 :
1505 : #[instrument(skip_all)]
1506 : pub(crate) async fn preload(
1507 : self: &Arc<Self>,
1508 : remote_storage: &GenericRemoteStorage,
1509 : cancel: CancellationToken,
1510 : ) -> anyhow::Result<TenantPreload> {
1511 : span::debug_assert_current_span_has_tenant_id();
1512 : // Get list of remote timelines
1513 : // download index files for every tenant timeline
1514 : info!("listing remote timelines");
1515 : let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
1516 : remote_storage,
1517 : self.tenant_shard_id,
1518 : cancel.clone(),
1519 : )
1520 : .await?;
1521 : let (offloaded_add, tenant_manifest) =
1522 : match remote_timeline_client::download_tenant_manifest(
1523 : remote_storage,
1524 : &self.tenant_shard_id,
1525 : self.generation,
1526 : &cancel,
1527 : )
1528 : .await
1529 : {
1530 : Ok((tenant_manifest, _generation, _manifest_mtime)) => (
1531 : format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
1532 : tenant_manifest,
1533 : ),
1534 : Err(DownloadError::NotFound) => {
1535 : ("no manifest".to_string(), TenantManifest::empty())
1536 : }
1537 : Err(e) => Err(e)?,
1538 : };
1539 :
1540 : info!(
1541 : "found {} timelines, and {offloaded_add}",
1542 : remote_timeline_ids.len()
1543 : );
1544 :
1545 : for k in other_keys {
1546 : warn!("Unexpected non timeline key {k}");
1547 : }
1548 :
1549 : // Avoid downloading IndexPart of offloaded timelines.
1550 : let mut offloaded_with_prefix = HashSet::new();
1551 : for offloaded in tenant_manifest.offloaded_timelines.iter() {
1552 : if remote_timeline_ids.remove(&offloaded.timeline_id) {
1553 : offloaded_with_prefix.insert(offloaded.timeline_id);
1554 : } else {
1555 : // We'll take care later of timelines in the manifest without a prefix
1556 : }
1557 : }
1558 :
1559 : // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
1560 : // pulled the first heatmap. Not entirely necessary since the storage controller
1561 : // will kick the secondary in any case and cause a download.
1562 : let maybe_heatmap_at = self.read_on_disk_heatmap().await;
1563 :
1564 : let timelines = self
1565 : .load_timelines_metadata(
1566 : remote_timeline_ids,
1567 : remote_storage,
1568 : maybe_heatmap_at,
1569 : cancel,
1570 : )
1571 : .await?;
1572 :
1573 : Ok(TenantPreload {
1574 : tenant_manifest,
1575 : timelines: timelines
1576 : .into_iter()
1577 12 : .map(|(id, tl)| (id, Some(tl)))
1578 0 : .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
1579 : .collect(),
1580 : })
1581 : }
1582 :
1583 454 : async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
1584 454 : let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
1585 454 : match tokio::fs::read_to_string(on_disk_heatmap_path).await {
1586 0 : Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
1587 0 : Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
1588 0 : Err(err) => {
1589 0 : error!("Failed to deserialize old heatmap: {err}");
1590 0 : None
1591 : }
1592 : },
1593 454 : Err(err) => match err.kind() {
1594 454 : std::io::ErrorKind::NotFound => None,
1595 : _ => {
1596 0 : error!("Unexpected IO error reading old heatmap: {err}");
1597 0 : None
1598 : }
1599 : },
1600 : }
1601 454 : }
1602 :
1603 : ///
1604 : /// Background task that downloads all data for a tenant and brings it to Active state.
1605 : ///
1606 : /// No background tasks are started as part of this routine.
1607 : ///
1608 454 : async fn attach(
1609 454 : self: &Arc<Tenant>,
1610 454 : preload: Option<TenantPreload>,
1611 454 : ctx: &RequestContext,
1612 454 : ) -> anyhow::Result<()> {
1613 454 : span::debug_assert_current_span_has_tenant_id();
1614 454 :
1615 454 : failpoint_support::sleep_millis_async!("before-attaching-tenant");
1616 :
1617 454 : let Some(preload) = preload else {
1618 0 : anyhow::bail!(
1619 0 : "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
1620 0 : );
1621 : };
1622 :
1623 454 : let mut offloaded_timeline_ids = HashSet::new();
1624 454 : let mut offloaded_timelines_list = Vec::new();
1625 454 : for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
1626 0 : let timeline_id = timeline_manifest.timeline_id;
1627 0 : let offloaded_timeline =
1628 0 : OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
1629 0 : offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
1630 0 : offloaded_timeline_ids.insert(timeline_id);
1631 0 : }
1632 : // Complete deletions for offloaded timeline id's from manifest.
1633 : // The manifest will be uploaded later in this function.
1634 454 : offloaded_timelines_list
1635 454 : .retain(|(offloaded_id, offloaded)| {
1636 0 : // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
1637 0 : // If there is dangling references in another location, they need to be cleaned up.
1638 0 : let delete = !preload.timelines.contains_key(offloaded_id);
1639 0 : if delete {
1640 0 : tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
1641 0 : offloaded.defuse_for_tenant_drop();
1642 0 : }
1643 0 : !delete
1644 454 : });
1645 454 :
1646 454 : let mut timelines_to_resume_deletions = vec![];
1647 454 :
1648 454 : let mut remote_index_and_client = HashMap::new();
1649 454 : let mut timeline_ancestors = HashMap::new();
1650 454 : let mut existent_timelines = HashSet::new();
1651 466 : for (timeline_id, preload) in preload.timelines {
1652 12 : let Some(preload) = preload else { continue };
1653 : // This is an invariant of the `preload` function's API
1654 12 : assert!(!offloaded_timeline_ids.contains(&timeline_id));
1655 12 : let index_part = match preload.index_part {
1656 12 : Ok(i) => {
1657 12 : debug!("remote index part exists for timeline {timeline_id}");
1658 : // We found index_part on the remote, this is the standard case.
1659 12 : existent_timelines.insert(timeline_id);
1660 12 : i
1661 : }
1662 : Err(DownloadError::NotFound) => {
1663 : // There is no index_part on the remote. We only get here
1664 : // if there is some prefix for the timeline in the remote storage.
1665 : // This can e.g. be the initdb.tar.zst archive, maybe a
1666 : // remnant from a prior incomplete creation or deletion attempt.
1667 : // Delete the local directory as the deciding criterion for a
1668 : // timeline's existence is presence of index_part.
1669 0 : info!(%timeline_id, "index_part not found on remote");
1670 0 : continue;
1671 : }
1672 0 : Err(DownloadError::Fatal(why)) => {
1673 0 : // If, while loading one remote timeline, we saw an indication that our generation
1674 0 : // number is likely invalid, then we should not load the whole tenant.
1675 0 : error!(%timeline_id, "Fatal error loading timeline: {why}");
1676 0 : anyhow::bail!(why.to_string());
1677 : }
1678 0 : Err(e) => {
1679 0 : // Some (possibly ephemeral) error happened during index_part download.
1680 0 : // Pretend the timeline exists to not delete the timeline directory,
1681 0 : // as it might be a temporary issue and we don't want to re-download
1682 0 : // everything after it resolves.
1683 0 : warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
1684 :
1685 0 : existent_timelines.insert(timeline_id);
1686 0 : continue;
1687 : }
1688 : };
1689 12 : match index_part {
1690 12 : MaybeDeletedIndexPart::IndexPart(index_part) => {
1691 12 : timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
1692 12 : remote_index_and_client.insert(
1693 12 : timeline_id,
1694 12 : (index_part, preload.client, preload.previous_heatmap),
1695 12 : );
1696 12 : }
1697 0 : MaybeDeletedIndexPart::Deleted(index_part) => {
1698 0 : info!(
1699 0 : "timeline {} is deleted, picking to resume deletion",
1700 : timeline_id
1701 : );
1702 0 : timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
1703 : }
1704 : }
1705 : }
1706 :
1707 454 : let mut gc_blocks = HashMap::new();
1708 :
1709 : // For every timeline, download the metadata file, scan the local directory,
1710 : // and build a layer map that contains an entry for each remote and local
1711 : // layer file.
1712 454 : let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
1713 466 : for (timeline_id, remote_metadata) in sorted_timelines {
1714 12 : let (index_part, remote_client, previous_heatmap) = remote_index_and_client
1715 12 : .remove(&timeline_id)
1716 12 : .expect("just put it in above");
1717 :
1718 12 : if let Some(blocking) = index_part.gc_blocking.as_ref() {
1719 : // could just filter these away, but it helps while testing
1720 0 : anyhow::ensure!(
1721 0 : !blocking.reasons.is_empty(),
1722 0 : "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
1723 : );
1724 0 : let prev = gc_blocks.insert(timeline_id, blocking.reasons);
1725 0 : assert!(prev.is_none());
1726 12 : }
1727 :
1728 : // TODO again handle early failure
1729 12 : let effect = self
1730 12 : .load_remote_timeline(
1731 12 : timeline_id,
1732 12 : index_part,
1733 12 : remote_metadata,
1734 12 : previous_heatmap,
1735 12 : self.get_timeline_resources_for(remote_client),
1736 12 : LoadTimelineCause::Attach,
1737 12 : ctx,
1738 12 : )
1739 12 : .await
1740 12 : .with_context(|| {
1741 0 : format!(
1742 0 : "failed to load remote timeline {} for tenant {}",
1743 0 : timeline_id, self.tenant_shard_id
1744 0 : )
1745 12 : })?;
1746 :
1747 12 : match effect {
1748 12 : TimelineInitAndSyncResult::ReadyToActivate(_) => {
1749 12 : // activation happens later, on Tenant::activate
1750 12 : }
1751 : TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
1752 : TimelineInitAndSyncNeedsSpawnImportPgdata {
1753 0 : timeline,
1754 0 : import_pgdata,
1755 0 : guard,
1756 0 : },
1757 0 : ) => {
1758 0 : tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
1759 0 : timeline,
1760 0 : import_pgdata,
1761 0 : ActivateTimelineArgs::No,
1762 0 : guard,
1763 0 : ));
1764 0 : }
1765 : }
1766 : }
1767 :
1768 : // Walk through deleted timelines, resume deletion
1769 454 : for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
1770 0 : remote_timeline_client
1771 0 : .init_upload_queue_stopped_to_continue_deletion(&index_part)
1772 0 : .context("init queue stopped")
1773 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1774 :
1775 0 : DeleteTimelineFlow::resume_deletion(
1776 0 : Arc::clone(self),
1777 0 : timeline_id,
1778 0 : &index_part.metadata,
1779 0 : remote_timeline_client,
1780 0 : )
1781 0 : .instrument(tracing::info_span!("timeline_delete", %timeline_id))
1782 0 : .await
1783 0 : .context("resume_deletion")
1784 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1785 : }
1786 454 : let needs_manifest_upload =
1787 454 : offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
1788 454 : {
1789 454 : let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
1790 454 : offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
1791 454 : }
1792 454 : if needs_manifest_upload {
1793 0 : self.store_tenant_manifest().await?;
1794 454 : }
1795 :
1796 : // The local filesystem contents are a cache of what's in the remote IndexPart;
1797 : // IndexPart is the source of truth.
1798 454 : self.clean_up_timelines(&existent_timelines)?;
1799 :
1800 454 : self.gc_block.set_scanned(gc_blocks);
1801 454 :
1802 454 : fail::fail_point!("attach-before-activate", |_| {
1803 0 : anyhow::bail!("attach-before-activate");
1804 454 : });
1805 454 : failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
1806 :
1807 454 : info!("Done");
1808 :
1809 454 : Ok(())
1810 454 : }
1811 :
1812 : /// Check for any local timeline directories that are temporary, or do not correspond to a
1813 : /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
1814 : /// if a timeline was deleted while the tenant was attached to a different pageserver.
1815 454 : fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
1816 454 : let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
1817 :
1818 454 : let entries = match timelines_dir.read_dir_utf8() {
1819 454 : Ok(d) => d,
1820 0 : Err(e) => {
1821 0 : if e.kind() == std::io::ErrorKind::NotFound {
1822 0 : return Ok(());
1823 : } else {
1824 0 : return Err(e).context("list timelines directory for tenant");
1825 : }
1826 : }
1827 : };
1828 :
1829 470 : for entry in entries {
1830 16 : let entry = entry.context("read timeline dir entry")?;
1831 16 : let entry_path = entry.path();
1832 :
1833 16 : let purge = if crate::is_temporary(entry_path) {
1834 0 : true
1835 : } else {
1836 16 : match TimelineId::try_from(entry_path.file_name()) {
1837 16 : Ok(i) => {
1838 16 : // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
1839 16 : !existent_timelines.contains(&i)
1840 : }
1841 0 : Err(e) => {
1842 0 : tracing::warn!(
1843 0 : "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
1844 : );
1845 : // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
1846 0 : false
1847 : }
1848 : }
1849 : };
1850 :
1851 16 : if purge {
1852 4 : tracing::info!("Purging stale timeline dentry {entry_path}");
1853 4 : if let Err(e) = match entry.file_type() {
1854 4 : Ok(t) => if t.is_dir() {
1855 4 : std::fs::remove_dir_all(entry_path)
1856 : } else {
1857 0 : std::fs::remove_file(entry_path)
1858 : }
1859 4 : .or_else(fs_ext::ignore_not_found),
1860 0 : Err(e) => Err(e),
1861 : } {
1862 0 : tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
1863 4 : }
1864 12 : }
1865 : }
1866 :
1867 454 : Ok(())
1868 454 : }
1869 :
1870 : /// Get sum of all remote timelines sizes
1871 : ///
1872 : /// This function relies on the index_part instead of listing the remote storage
1873 0 : pub fn remote_size(&self) -> u64 {
1874 0 : let mut size = 0;
1875 :
1876 0 : for timeline in self.list_timelines() {
1877 0 : size += timeline.remote_client.get_remote_physical_size();
1878 0 : }
1879 :
1880 0 : size
1881 0 : }
1882 :
1883 : #[instrument(skip_all, fields(timeline_id=%timeline_id))]
1884 : #[allow(clippy::too_many_arguments)]
1885 : async fn load_remote_timeline(
1886 : self: &Arc<Self>,
1887 : timeline_id: TimelineId,
1888 : index_part: IndexPart,
1889 : remote_metadata: TimelineMetadata,
1890 : previous_heatmap: Option<PreviousHeatmap>,
1891 : resources: TimelineResources,
1892 : cause: LoadTimelineCause,
1893 : ctx: &RequestContext,
1894 : ) -> anyhow::Result<TimelineInitAndSyncResult> {
1895 : span::debug_assert_current_span_has_tenant_id();
1896 :
1897 : info!("downloading index file for timeline {}", timeline_id);
1898 : tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
1899 : .await
1900 : .context("Failed to create new timeline directory")?;
1901 :
1902 : let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
1903 : let timelines = self.timelines.lock().unwrap();
1904 : Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
1905 0 : || {
1906 0 : anyhow::anyhow!(
1907 0 : "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
1908 0 : )
1909 0 : },
1910 : )?))
1911 : } else {
1912 : None
1913 : };
1914 :
1915 : self.timeline_init_and_sync(
1916 : timeline_id,
1917 : resources,
1918 : index_part,
1919 : remote_metadata,
1920 : previous_heatmap,
1921 : ancestor,
1922 : cause,
1923 : ctx,
1924 : )
1925 : .await
1926 : }
1927 :
1928 454 : async fn load_timelines_metadata(
1929 454 : self: &Arc<Tenant>,
1930 454 : timeline_ids: HashSet<TimelineId>,
1931 454 : remote_storage: &GenericRemoteStorage,
1932 454 : heatmap: Option<(HeatMapTenant, std::time::Instant)>,
1933 454 : cancel: CancellationToken,
1934 454 : ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
1935 454 : let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
1936 454 :
1937 454 : let mut part_downloads = JoinSet::new();
1938 466 : for timeline_id in timeline_ids {
1939 12 : let cancel_clone = cancel.clone();
1940 12 :
1941 12 : let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
1942 0 : hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
1943 0 : heatmap: h,
1944 0 : read_at: hs.1,
1945 0 : end_lsn: None,
1946 0 : })
1947 12 : });
1948 12 : part_downloads.spawn(
1949 12 : self.load_timeline_metadata(
1950 12 : timeline_id,
1951 12 : remote_storage.clone(),
1952 12 : previous_timeline_heatmap,
1953 12 : cancel_clone,
1954 12 : )
1955 12 : .instrument(info_span!("download_index_part", %timeline_id)),
1956 : );
1957 : }
1958 :
1959 454 : let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
1960 :
1961 : loop {
1962 466 : tokio::select!(
1963 466 : next = part_downloads.join_next() => {
1964 466 : match next {
1965 12 : Some(result) => {
1966 12 : let preload = result.context("join preload task")?;
1967 12 : timeline_preloads.insert(preload.timeline_id, preload);
1968 : },
1969 : None => {
1970 454 : break;
1971 : }
1972 : }
1973 : },
1974 466 : _ = cancel.cancelled() => {
1975 0 : anyhow::bail!("Cancelled while waiting for remote index download")
1976 : }
1977 : )
1978 : }
1979 :
1980 454 : Ok(timeline_preloads)
1981 454 : }
1982 :
1983 12 : fn build_timeline_client(
1984 12 : &self,
1985 12 : timeline_id: TimelineId,
1986 12 : remote_storage: GenericRemoteStorage,
1987 12 : ) -> RemoteTimelineClient {
1988 12 : RemoteTimelineClient::new(
1989 12 : remote_storage.clone(),
1990 12 : self.deletion_queue_client.clone(),
1991 12 : self.conf,
1992 12 : self.tenant_shard_id,
1993 12 : timeline_id,
1994 12 : self.generation,
1995 12 : &self.tenant_conf.load().location,
1996 12 : )
1997 12 : }
1998 :
1999 12 : fn load_timeline_metadata(
2000 12 : self: &Arc<Tenant>,
2001 12 : timeline_id: TimelineId,
2002 12 : remote_storage: GenericRemoteStorage,
2003 12 : previous_heatmap: Option<PreviousHeatmap>,
2004 12 : cancel: CancellationToken,
2005 12 : ) -> impl Future<Output = TimelinePreload> + use<> {
2006 12 : let client = self.build_timeline_client(timeline_id, remote_storage);
2007 12 : async move {
2008 12 : debug_assert_current_span_has_tenant_and_timeline_id();
2009 12 : debug!("starting index part download");
2010 :
2011 12 : let index_part = client.download_index_file(&cancel).await;
2012 :
2013 12 : debug!("finished index part download");
2014 :
2015 12 : TimelinePreload {
2016 12 : client,
2017 12 : timeline_id,
2018 12 : index_part,
2019 12 : previous_heatmap,
2020 12 : }
2021 12 : }
2022 12 : }
2023 :
2024 0 : fn check_to_be_archived_has_no_unarchived_children(
2025 0 : timeline_id: TimelineId,
2026 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
2027 0 : ) -> Result<(), TimelineArchivalError> {
2028 0 : let children: Vec<TimelineId> = timelines
2029 0 : .iter()
2030 0 : .filter_map(|(id, entry)| {
2031 0 : if entry.get_ancestor_timeline_id() != Some(timeline_id) {
2032 0 : return None;
2033 0 : }
2034 0 : if entry.is_archived() == Some(true) {
2035 0 : return None;
2036 0 : }
2037 0 : Some(*id)
2038 0 : })
2039 0 : .collect();
2040 0 :
2041 0 : if !children.is_empty() {
2042 0 : return Err(TimelineArchivalError::HasUnarchivedChildren(children));
2043 0 : }
2044 0 : Ok(())
2045 0 : }
2046 :
2047 0 : fn check_ancestor_of_to_be_unarchived_is_not_archived(
2048 0 : ancestor_timeline_id: TimelineId,
2049 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
2050 0 : offloaded_timelines: &std::sync::MutexGuard<
2051 0 : '_,
2052 0 : HashMap<TimelineId, Arc<OffloadedTimeline>>,
2053 0 : >,
2054 0 : ) -> Result<(), TimelineArchivalError> {
2055 0 : let has_archived_parent =
2056 0 : if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
2057 0 : ancestor_timeline.is_archived() == Some(true)
2058 0 : } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
2059 0 : true
2060 : } else {
2061 0 : error!("ancestor timeline {ancestor_timeline_id} not found");
2062 0 : if cfg!(debug_assertions) {
2063 0 : panic!("ancestor timeline {ancestor_timeline_id} not found");
2064 0 : }
2065 0 : return Err(TimelineArchivalError::NotFound);
2066 : };
2067 0 : if has_archived_parent {
2068 0 : return Err(TimelineArchivalError::HasArchivedParent(
2069 0 : ancestor_timeline_id,
2070 0 : ));
2071 0 : }
2072 0 : Ok(())
2073 0 : }
2074 :
2075 0 : fn check_to_be_unarchived_timeline_has_no_archived_parent(
2076 0 : timeline: &Arc<Timeline>,
2077 0 : ) -> Result<(), TimelineArchivalError> {
2078 0 : if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
2079 0 : if ancestor_timeline.is_archived() == Some(true) {
2080 0 : return Err(TimelineArchivalError::HasArchivedParent(
2081 0 : ancestor_timeline.timeline_id,
2082 0 : ));
2083 0 : }
2084 0 : }
2085 0 : Ok(())
2086 0 : }
2087 :
2088 : /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
2089 : ///
2090 : /// Counterpart to [`offload_timeline`].
2091 0 : async fn unoffload_timeline(
2092 0 : self: &Arc<Self>,
2093 0 : timeline_id: TimelineId,
2094 0 : broker_client: storage_broker::BrokerClientChannel,
2095 0 : ctx: RequestContext,
2096 0 : ) -> Result<Arc<Timeline>, TimelineArchivalError> {
2097 0 : info!("unoffloading timeline");
2098 :
2099 : // We activate the timeline below manually, so this must be called on an active tenant.
2100 : // We expect callers of this function to ensure this.
2101 0 : match self.current_state() {
2102 : TenantState::Activating { .. }
2103 : | TenantState::Attaching
2104 : | TenantState::Broken { .. } => {
2105 0 : panic!("Timeline expected to be active")
2106 : }
2107 0 : TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
2108 0 : TenantState::Active => {}
2109 0 : }
2110 0 : let cancel = self.cancel.clone();
2111 0 :
2112 0 : // Protect against concurrent attempts to use this TimelineId
2113 0 : // We don't care much about idempotency, as it's ensured a layer above.
2114 0 : let allow_offloaded = true;
2115 0 : let _create_guard = self
2116 0 : .create_timeline_create_guard(
2117 0 : timeline_id,
2118 0 : CreateTimelineIdempotency::FailWithConflict,
2119 0 : allow_offloaded,
2120 0 : )
2121 0 : .map_err(|err| match err {
2122 0 : TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
2123 : TimelineExclusionError::AlreadyExists { .. } => {
2124 0 : TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
2125 : }
2126 0 : TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
2127 0 : TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
2128 0 : })?;
2129 :
2130 0 : let timeline_preload = self
2131 0 : .load_timeline_metadata(
2132 0 : timeline_id,
2133 0 : self.remote_storage.clone(),
2134 0 : None,
2135 0 : cancel.clone(),
2136 0 : )
2137 0 : .await;
2138 :
2139 0 : let index_part = match timeline_preload.index_part {
2140 0 : Ok(index_part) => {
2141 0 : debug!("remote index part exists for timeline {timeline_id}");
2142 0 : index_part
2143 : }
2144 : Err(DownloadError::NotFound) => {
2145 0 : error!(%timeline_id, "index_part not found on remote");
2146 0 : return Err(TimelineArchivalError::NotFound);
2147 : }
2148 0 : Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
2149 0 : Err(e) => {
2150 0 : // Some (possibly ephemeral) error happened during index_part download.
2151 0 : warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
2152 0 : return Err(TimelineArchivalError::Other(
2153 0 : anyhow::Error::new(e).context("downloading index_part from remote storage"),
2154 0 : ));
2155 : }
2156 : };
2157 0 : let index_part = match index_part {
2158 0 : MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
2159 0 : MaybeDeletedIndexPart::Deleted(_index_part) => {
2160 0 : info!("timeline is deleted according to index_part.json");
2161 0 : return Err(TimelineArchivalError::NotFound);
2162 : }
2163 : };
2164 0 : let remote_metadata = index_part.metadata.clone();
2165 0 : let timeline_resources = self.build_timeline_resources(timeline_id);
2166 0 : self.load_remote_timeline(
2167 0 : timeline_id,
2168 0 : index_part,
2169 0 : remote_metadata,
2170 0 : None,
2171 0 : timeline_resources,
2172 0 : LoadTimelineCause::Unoffload,
2173 0 : &ctx,
2174 0 : )
2175 0 : .await
2176 0 : .with_context(|| {
2177 0 : format!(
2178 0 : "failed to load remote timeline {} for tenant {}",
2179 0 : timeline_id, self.tenant_shard_id
2180 0 : )
2181 0 : })
2182 0 : .map_err(TimelineArchivalError::Other)?;
2183 :
2184 0 : let timeline = {
2185 0 : let timelines = self.timelines.lock().unwrap();
2186 0 : let Some(timeline) = timelines.get(&timeline_id) else {
2187 0 : warn!("timeline not available directly after attach");
2188 : // This is not a panic because no locks are held between `load_remote_timeline`
2189 : // which puts the timeline into timelines, and our look into the timeline map.
2190 0 : return Err(TimelineArchivalError::Other(anyhow::anyhow!(
2191 0 : "timeline not available directly after attach"
2192 0 : )));
2193 : };
2194 0 : let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
2195 0 : match offloaded_timelines.remove(&timeline_id) {
2196 0 : Some(offloaded) => {
2197 0 : offloaded.delete_from_ancestor_with_timelines(&timelines);
2198 0 : }
2199 0 : None => warn!("timeline already removed from offloaded timelines"),
2200 : }
2201 :
2202 0 : self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
2203 0 :
2204 0 : Arc::clone(timeline)
2205 0 : };
2206 0 :
2207 0 : // Upload new list of offloaded timelines to S3
2208 0 : self.store_tenant_manifest().await?;
2209 :
2210 : // Activate the timeline (if it makes sense)
2211 0 : if !(timeline.is_broken() || timeline.is_stopping()) {
2212 0 : let background_jobs_can_start = None;
2213 0 : timeline.activate(
2214 0 : self.clone(),
2215 0 : broker_client.clone(),
2216 0 : background_jobs_can_start,
2217 0 : &ctx,
2218 0 : );
2219 0 : }
2220 :
2221 0 : info!("timeline unoffloading complete");
2222 0 : Ok(timeline)
2223 0 : }
2224 :
2225 0 : pub(crate) async fn apply_timeline_archival_config(
2226 0 : self: &Arc<Self>,
2227 0 : timeline_id: TimelineId,
2228 0 : new_state: TimelineArchivalState,
2229 0 : broker_client: storage_broker::BrokerClientChannel,
2230 0 : ctx: RequestContext,
2231 0 : ) -> Result<(), TimelineArchivalError> {
2232 0 : info!("setting timeline archival config");
2233 : // First part: figure out what is needed to do, and do validation
2234 0 : let timeline_or_unarchive_offloaded = 'outer: {
2235 0 : let timelines = self.timelines.lock().unwrap();
2236 :
2237 0 : let Some(timeline) = timelines.get(&timeline_id) else {
2238 0 : let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
2239 0 : let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
2240 0 : return Err(TimelineArchivalError::NotFound);
2241 : };
2242 0 : if new_state == TimelineArchivalState::Archived {
2243 : // It's offloaded already, so nothing to do
2244 0 : return Ok(());
2245 0 : }
2246 0 : if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
2247 0 : Self::check_ancestor_of_to_be_unarchived_is_not_archived(
2248 0 : ancestor_timeline_id,
2249 0 : &timelines,
2250 0 : &offloaded_timelines,
2251 0 : )?;
2252 0 : }
2253 0 : break 'outer None;
2254 : };
2255 :
2256 : // Do some validation. We release the timelines lock below, so there is potential
2257 : // for race conditions: these checks are more present to prevent misunderstandings of
2258 : // the API's capabilities, instead of serving as the sole way to defend their invariants.
2259 0 : match new_state {
2260 : TimelineArchivalState::Unarchived => {
2261 0 : Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
2262 : }
2263 : TimelineArchivalState::Archived => {
2264 0 : Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
2265 : }
2266 : }
2267 0 : Some(Arc::clone(timeline))
2268 : };
2269 :
2270 : // Second part: unoffload timeline (if needed)
2271 0 : let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
2272 0 : timeline
2273 : } else {
2274 : // Turn offloaded timeline into a non-offloaded one
2275 0 : self.unoffload_timeline(timeline_id, broker_client, ctx)
2276 0 : .await?
2277 : };
2278 :
2279 : // Third part: upload new timeline archival state and block until it is present in S3
2280 0 : let upload_needed = match timeline
2281 0 : .remote_client
2282 0 : .schedule_index_upload_for_timeline_archival_state(new_state)
2283 : {
2284 0 : Ok(upload_needed) => upload_needed,
2285 0 : Err(e) => {
2286 0 : if timeline.cancel.is_cancelled() {
2287 0 : return Err(TimelineArchivalError::Cancelled);
2288 : } else {
2289 0 : return Err(TimelineArchivalError::Other(e));
2290 : }
2291 : }
2292 : };
2293 :
2294 0 : if upload_needed {
2295 0 : info!("Uploading new state");
2296 : const MAX_WAIT: Duration = Duration::from_secs(10);
2297 0 : let Ok(v) =
2298 0 : tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
2299 : else {
2300 0 : tracing::warn!("reached timeout for waiting on upload queue");
2301 0 : return Err(TimelineArchivalError::Timeout);
2302 : };
2303 0 : v.map_err(|e| match e {
2304 0 : WaitCompletionError::NotInitialized(e) => {
2305 0 : TimelineArchivalError::Other(anyhow::anyhow!(e))
2306 : }
2307 : WaitCompletionError::UploadQueueShutDownOrStopped => {
2308 0 : TimelineArchivalError::Cancelled
2309 : }
2310 0 : })?;
2311 0 : }
2312 0 : Ok(())
2313 0 : }
2314 :
2315 4 : pub fn get_offloaded_timeline(
2316 4 : &self,
2317 4 : timeline_id: TimelineId,
2318 4 : ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
2319 4 : self.timelines_offloaded
2320 4 : .lock()
2321 4 : .unwrap()
2322 4 : .get(&timeline_id)
2323 4 : .map(Arc::clone)
2324 4 : .ok_or(GetTimelineError::NotFound {
2325 4 : tenant_id: self.tenant_shard_id,
2326 4 : timeline_id,
2327 4 : })
2328 4 : }
2329 :
2330 8 : pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
2331 8 : self.tenant_shard_id
2332 8 : }
2333 :
2334 : /// Get Timeline handle for given Neon timeline ID.
2335 : /// This function is idempotent. It doesn't change internal state in any way.
2336 444 : pub fn get_timeline(
2337 444 : &self,
2338 444 : timeline_id: TimelineId,
2339 444 : active_only: bool,
2340 444 : ) -> Result<Arc<Timeline>, GetTimelineError> {
2341 444 : let timelines_accessor = self.timelines.lock().unwrap();
2342 444 : let timeline = timelines_accessor
2343 444 : .get(&timeline_id)
2344 444 : .ok_or(GetTimelineError::NotFound {
2345 444 : tenant_id: self.tenant_shard_id,
2346 444 : timeline_id,
2347 444 : })?;
2348 :
2349 440 : if active_only && !timeline.is_active() {
2350 0 : Err(GetTimelineError::NotActive {
2351 0 : tenant_id: self.tenant_shard_id,
2352 0 : timeline_id,
2353 0 : state: timeline.current_state(),
2354 0 : })
2355 : } else {
2356 440 : Ok(Arc::clone(timeline))
2357 : }
2358 444 : }
2359 :
2360 : /// Lists timelines the tenant contains.
2361 : /// It's up to callers to omit certain timelines that are not considered ready for use.
2362 0 : pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
2363 0 : self.timelines
2364 0 : .lock()
2365 0 : .unwrap()
2366 0 : .values()
2367 0 : .map(Arc::clone)
2368 0 : .collect()
2369 0 : }
2370 :
2371 : /// Lists timelines the tenant manages, including offloaded ones.
2372 : ///
2373 : /// It's up to callers to omit certain timelines that are not considered ready for use.
2374 0 : pub fn list_timelines_and_offloaded(
2375 0 : &self,
2376 0 : ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
2377 0 : let timelines = self
2378 0 : .timelines
2379 0 : .lock()
2380 0 : .unwrap()
2381 0 : .values()
2382 0 : .map(Arc::clone)
2383 0 : .collect();
2384 0 : let offloaded = self
2385 0 : .timelines_offloaded
2386 0 : .lock()
2387 0 : .unwrap()
2388 0 : .values()
2389 0 : .map(Arc::clone)
2390 0 : .collect();
2391 0 : (timelines, offloaded)
2392 0 : }
2393 :
2394 0 : pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
2395 0 : self.timelines.lock().unwrap().keys().cloned().collect()
2396 0 : }
2397 :
2398 : /// This is used by tests & import-from-basebackup.
2399 : ///
2400 : /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
2401 : /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
2402 : ///
2403 : /// The caller is responsible for getting the timeline into a state that will be accepted
2404 : /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
2405 : /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
2406 : /// to the [`Tenant::timelines`].
2407 : ///
2408 : /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
2409 438 : pub(crate) async fn create_empty_timeline(
2410 438 : self: &Arc<Self>,
2411 438 : new_timeline_id: TimelineId,
2412 438 : initdb_lsn: Lsn,
2413 438 : pg_version: u32,
2414 438 : _ctx: &RequestContext,
2415 438 : ) -> anyhow::Result<UninitializedTimeline> {
2416 438 : anyhow::ensure!(
2417 438 : self.is_active(),
2418 0 : "Cannot create empty timelines on inactive tenant"
2419 : );
2420 :
2421 : // Protect against concurrent attempts to use this TimelineId
2422 438 : let create_guard = match self
2423 438 : .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
2424 438 : .await?
2425 : {
2426 434 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
2427 : StartCreatingTimelineResult::Idempotent(_) => {
2428 0 : unreachable!("FailWithConflict implies we get an error instead")
2429 : }
2430 : };
2431 :
2432 434 : let new_metadata = TimelineMetadata::new(
2433 434 : // Initialize disk_consistent LSN to 0, The caller must import some data to
2434 434 : // make it valid, before calling finish_creation()
2435 434 : Lsn(0),
2436 434 : None,
2437 434 : None,
2438 434 : Lsn(0),
2439 434 : initdb_lsn,
2440 434 : initdb_lsn,
2441 434 : pg_version,
2442 434 : );
2443 434 : self.prepare_new_timeline(
2444 434 : new_timeline_id,
2445 434 : &new_metadata,
2446 434 : create_guard,
2447 434 : initdb_lsn,
2448 434 : None,
2449 434 : )
2450 434 : .await
2451 438 : }
2452 :
2453 : /// Helper for unit tests to create an empty timeline.
2454 : ///
2455 : /// The timeline is has state value `Active` but its background loops are not running.
2456 : // This makes the various functions which anyhow::ensure! for Active state work in tests.
2457 : // Our current tests don't need the background loops.
2458 : #[cfg(test)]
2459 418 : pub async fn create_test_timeline(
2460 418 : self: &Arc<Self>,
2461 418 : new_timeline_id: TimelineId,
2462 418 : initdb_lsn: Lsn,
2463 418 : pg_version: u32,
2464 418 : ctx: &RequestContext,
2465 418 : ) -> anyhow::Result<Arc<Timeline>> {
2466 418 : let uninit_tl = self
2467 418 : .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
2468 418 : .await?;
2469 418 : let tline = uninit_tl.raw_timeline().expect("we just created it");
2470 418 : assert_eq!(tline.get_last_record_lsn(), Lsn(0));
2471 :
2472 : // Setup minimum keys required for the timeline to be usable.
2473 418 : let mut modification = tline.begin_modification(initdb_lsn);
2474 418 : modification
2475 418 : .init_empty_test_timeline()
2476 418 : .context("init_empty_test_timeline")?;
2477 418 : modification
2478 418 : .commit(ctx)
2479 418 : .await
2480 418 : .context("commit init_empty_test_timeline modification")?;
2481 :
2482 : // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
2483 418 : tline.maybe_spawn_flush_loop();
2484 418 : tline.freeze_and_flush().await.context("freeze_and_flush")?;
2485 :
2486 : // Make sure the freeze_and_flush reaches remote storage.
2487 418 : tline.remote_client.wait_completion().await.unwrap();
2488 :
2489 418 : let tl = uninit_tl.finish_creation().await?;
2490 : // The non-test code would call tl.activate() here.
2491 418 : tl.set_state(TimelineState::Active);
2492 418 : Ok(tl)
2493 418 : }
2494 :
2495 : /// Helper for unit tests to create a timeline with some pre-loaded states.
2496 : #[cfg(test)]
2497 : #[allow(clippy::too_many_arguments)]
2498 86 : pub async fn create_test_timeline_with_layers(
2499 86 : self: &Arc<Self>,
2500 86 : new_timeline_id: TimelineId,
2501 86 : initdb_lsn: Lsn,
2502 86 : pg_version: u32,
2503 86 : ctx: &RequestContext,
2504 86 : in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
2505 86 : delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
2506 86 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
2507 86 : end_lsn: Lsn,
2508 86 : ) -> anyhow::Result<Arc<Timeline>> {
2509 : use checks::check_valid_layermap;
2510 : use itertools::Itertools;
2511 :
2512 86 : let tline = self
2513 86 : .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
2514 86 : .await?;
2515 86 : tline.force_advance_lsn(end_lsn);
2516 260 : for deltas in delta_layer_desc {
2517 174 : tline
2518 174 : .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
2519 174 : .await?;
2520 : }
2521 208 : for (lsn, images) in image_layer_desc {
2522 122 : tline
2523 122 : .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
2524 122 : .await?;
2525 : }
2526 94 : for in_memory in in_memory_layer_desc {
2527 8 : tline
2528 8 : .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
2529 8 : .await?;
2530 : }
2531 86 : let layer_names = tline
2532 86 : .layers
2533 86 : .read()
2534 86 : .await
2535 86 : .layer_map()
2536 86 : .unwrap()
2537 86 : .iter_historic_layers()
2538 382 : .map(|layer| layer.layer_name())
2539 86 : .collect_vec();
2540 86 : if let Some(err) = check_valid_layermap(&layer_names) {
2541 0 : bail!("invalid layermap: {err}");
2542 86 : }
2543 86 : Ok(tline)
2544 86 : }
2545 :
2546 : /// Create a new timeline.
2547 : ///
2548 : /// Returns the new timeline ID and reference to its Timeline object.
2549 : ///
2550 : /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
2551 : /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
2552 : #[allow(clippy::too_many_arguments)]
2553 0 : pub(crate) async fn create_timeline(
2554 0 : self: &Arc<Tenant>,
2555 0 : params: CreateTimelineParams,
2556 0 : broker_client: storage_broker::BrokerClientChannel,
2557 0 : ctx: &RequestContext,
2558 0 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
2559 0 : if !self.is_active() {
2560 0 : if matches!(self.current_state(), TenantState::Stopping { .. }) {
2561 0 : return Err(CreateTimelineError::ShuttingDown);
2562 : } else {
2563 0 : return Err(CreateTimelineError::Other(anyhow::anyhow!(
2564 0 : "Cannot create timelines on inactive tenant"
2565 0 : )));
2566 : }
2567 0 : }
2568 :
2569 0 : let _gate = self
2570 0 : .gate
2571 0 : .enter()
2572 0 : .map_err(|_| CreateTimelineError::ShuttingDown)?;
2573 :
2574 0 : let result: CreateTimelineResult = match params {
2575 : CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
2576 0 : new_timeline_id,
2577 0 : existing_initdb_timeline_id,
2578 0 : pg_version,
2579 0 : }) => {
2580 0 : self.bootstrap_timeline(
2581 0 : new_timeline_id,
2582 0 : pg_version,
2583 0 : existing_initdb_timeline_id,
2584 0 : ctx,
2585 0 : )
2586 0 : .await?
2587 : }
2588 : CreateTimelineParams::Branch(CreateTimelineParamsBranch {
2589 0 : new_timeline_id,
2590 0 : ancestor_timeline_id,
2591 0 : mut ancestor_start_lsn,
2592 : }) => {
2593 0 : let ancestor_timeline = self
2594 0 : .get_timeline(ancestor_timeline_id, false)
2595 0 : .context("Cannot branch off the timeline that's not present in pageserver")?;
2596 :
2597 : // instead of waiting around, just deny the request because ancestor is not yet
2598 : // ready for other purposes either.
2599 0 : if !ancestor_timeline.is_active() {
2600 0 : return Err(CreateTimelineError::AncestorNotActive);
2601 0 : }
2602 0 :
2603 0 : if ancestor_timeline.is_archived() == Some(true) {
2604 0 : info!("tried to branch archived timeline");
2605 0 : return Err(CreateTimelineError::AncestorArchived);
2606 0 : }
2607 :
2608 0 : if let Some(lsn) = ancestor_start_lsn.as_mut() {
2609 0 : *lsn = lsn.align();
2610 0 :
2611 0 : let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
2612 0 : if ancestor_ancestor_lsn > *lsn {
2613 : // can we safely just branch from the ancestor instead?
2614 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
2615 0 : "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
2616 0 : lsn,
2617 0 : ancestor_timeline_id,
2618 0 : ancestor_ancestor_lsn,
2619 0 : )));
2620 0 : }
2621 0 :
2622 0 : // Wait for the WAL to arrive and be processed on the parent branch up
2623 0 : // to the requested branch point. The repository code itself doesn't
2624 0 : // require it, but if we start to receive WAL on the new timeline,
2625 0 : // decoding the new WAL might need to look up previous pages, relation
2626 0 : // sizes etc. and that would get confused if the previous page versions
2627 0 : // are not in the repository yet.
2628 0 : ancestor_timeline
2629 0 : .wait_lsn(
2630 0 : *lsn,
2631 0 : timeline::WaitLsnWaiter::Tenant,
2632 0 : timeline::WaitLsnTimeout::Default,
2633 0 : ctx,
2634 0 : )
2635 0 : .await
2636 0 : .map_err(|e| match e {
2637 0 : e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
2638 0 : CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
2639 : }
2640 0 : WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
2641 0 : })?;
2642 0 : }
2643 :
2644 0 : self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
2645 0 : .await?
2646 : }
2647 0 : CreateTimelineParams::ImportPgdata(params) => {
2648 0 : self.create_timeline_import_pgdata(
2649 0 : params,
2650 0 : ActivateTimelineArgs::Yes {
2651 0 : broker_client: broker_client.clone(),
2652 0 : },
2653 0 : ctx,
2654 0 : )
2655 0 : .await?
2656 : }
2657 : };
2658 :
2659 : // At this point we have dropped our guard on [`Self::timelines_creating`], and
2660 : // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet. We must
2661 : // not send a success to the caller until it is. The same applies to idempotent retries.
2662 : //
2663 : // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
2664 : // assume that, because they can see the timeline via API, that the creation is done and
2665 : // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
2666 : // until it is durable, e.g., by extending the time we hold the creation guard. This also
2667 : // interacts with UninitializedTimeline and is generally a bit tricky.
2668 : //
2669 : // To re-emphasize: the only correct way to create a timeline is to repeat calling the
2670 : // creation API until it returns success. Only then is durability guaranteed.
2671 0 : info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
2672 0 : result
2673 0 : .timeline()
2674 0 : .remote_client
2675 0 : .wait_completion()
2676 0 : .await
2677 0 : .map_err(|e| match e {
2678 : WaitCompletionError::NotInitialized(
2679 0 : e, // If the queue is already stopped, it's a shutdown error.
2680 0 : ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
2681 : WaitCompletionError::NotInitialized(_) => {
2682 : // This is a bug: we should never try to wait for uploads before initializing the timeline
2683 0 : debug_assert!(false);
2684 0 : CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
2685 : }
2686 : WaitCompletionError::UploadQueueShutDownOrStopped => {
2687 0 : CreateTimelineError::ShuttingDown
2688 : }
2689 0 : })?;
2690 :
2691 : // The creating task is responsible for activating the timeline.
2692 : // We do this after `wait_completion()` so that we don't spin up tasks that start
2693 : // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
2694 0 : let activated_timeline = match result {
2695 0 : CreateTimelineResult::Created(timeline) => {
2696 0 : timeline.activate(self.clone(), broker_client, None, ctx);
2697 0 : timeline
2698 : }
2699 0 : CreateTimelineResult::Idempotent(timeline) => {
2700 0 : info!(
2701 0 : "request was deemed idempotent, activation will be done by the creating task"
2702 : );
2703 0 : timeline
2704 : }
2705 0 : CreateTimelineResult::ImportSpawned(timeline) => {
2706 0 : info!(
2707 0 : "import task spawned, timeline will become visible and activated once the import is done"
2708 : );
2709 0 : timeline
2710 : }
2711 : };
2712 :
2713 0 : Ok(activated_timeline)
2714 0 : }
2715 :
2716 : /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
2717 : /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
2718 : /// [`Tenant::timelines`] map when the import completes.
2719 : /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
2720 : /// for the response.
2721 0 : async fn create_timeline_import_pgdata(
2722 0 : self: &Arc<Tenant>,
2723 0 : params: CreateTimelineParamsImportPgdata,
2724 0 : activate: ActivateTimelineArgs,
2725 0 : ctx: &RequestContext,
2726 0 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
2727 0 : let CreateTimelineParamsImportPgdata {
2728 0 : new_timeline_id,
2729 0 : location,
2730 0 : idempotency_key,
2731 0 : } = params;
2732 0 :
2733 0 : let started_at = chrono::Utc::now().naive_utc();
2734 :
2735 : //
2736 : // There's probably a simpler way to upload an index part, but, remote_timeline_client
2737 : // is the canonical way we do it.
2738 : // - create an empty timeline in-memory
2739 : // - use its remote_timeline_client to do the upload
2740 : // - dispose of the uninit timeline
2741 : // - keep the creation guard alive
2742 :
2743 0 : let timeline_create_guard = match self
2744 0 : .start_creating_timeline(
2745 0 : new_timeline_id,
2746 0 : CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
2747 0 : idempotency_key: idempotency_key.clone(),
2748 0 : }),
2749 0 : )
2750 0 : .await?
2751 : {
2752 0 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
2753 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
2754 0 : return Ok(CreateTimelineResult::Idempotent(timeline));
2755 : }
2756 : };
2757 :
2758 0 : let mut uninit_timeline = {
2759 0 : let this = &self;
2760 0 : let initdb_lsn = Lsn(0);
2761 0 : let _ctx = ctx;
2762 0 : async move {
2763 0 : let new_metadata = TimelineMetadata::new(
2764 0 : // Initialize disk_consistent LSN to 0, The caller must import some data to
2765 0 : // make it valid, before calling finish_creation()
2766 0 : Lsn(0),
2767 0 : None,
2768 0 : None,
2769 0 : Lsn(0),
2770 0 : initdb_lsn,
2771 0 : initdb_lsn,
2772 0 : 15,
2773 0 : );
2774 0 : this.prepare_new_timeline(
2775 0 : new_timeline_id,
2776 0 : &new_metadata,
2777 0 : timeline_create_guard,
2778 0 : initdb_lsn,
2779 0 : None,
2780 0 : )
2781 0 : .await
2782 0 : }
2783 0 : }
2784 0 : .await?;
2785 :
2786 0 : let in_progress = import_pgdata::index_part_format::InProgress {
2787 0 : idempotency_key,
2788 0 : location,
2789 0 : started_at,
2790 0 : };
2791 0 : let index_part = import_pgdata::index_part_format::Root::V1(
2792 0 : import_pgdata::index_part_format::V1::InProgress(in_progress),
2793 0 : );
2794 0 : uninit_timeline
2795 0 : .raw_timeline()
2796 0 : .unwrap()
2797 0 : .remote_client
2798 0 : .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
2799 :
2800 : // wait_completion happens in caller
2801 :
2802 0 : let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
2803 0 :
2804 0 : tokio::spawn(self.clone().create_timeline_import_pgdata_task(
2805 0 : timeline.clone(),
2806 0 : index_part,
2807 0 : activate,
2808 0 : timeline_create_guard,
2809 0 : ));
2810 0 :
2811 0 : // NB: the timeline doesn't exist in self.timelines at this point
2812 0 : Ok(CreateTimelineResult::ImportSpawned(timeline))
2813 0 : }
2814 :
2815 : #[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))]
2816 : async fn create_timeline_import_pgdata_task(
2817 : self: Arc<Tenant>,
2818 : timeline: Arc<Timeline>,
2819 : index_part: import_pgdata::index_part_format::Root,
2820 : activate: ActivateTimelineArgs,
2821 : timeline_create_guard: TimelineCreateGuard,
2822 : ) {
2823 : debug_assert_current_span_has_tenant_and_timeline_id();
2824 : info!("starting");
2825 : scopeguard::defer! {info!("exiting")};
2826 :
2827 : let res = self
2828 : .create_timeline_import_pgdata_task_impl(
2829 : timeline,
2830 : index_part,
2831 : activate,
2832 : timeline_create_guard,
2833 : )
2834 : .await;
2835 : if let Err(err) = &res {
2836 : error!(?err, "task failed");
2837 : // TODO sleep & retry, sensitive to tenant shutdown
2838 : // TODO: allow timeline deletion requests => should cancel the task
2839 : }
2840 : }
2841 :
2842 0 : async fn create_timeline_import_pgdata_task_impl(
2843 0 : self: Arc<Tenant>,
2844 0 : timeline: Arc<Timeline>,
2845 0 : index_part: import_pgdata::index_part_format::Root,
2846 0 : activate: ActivateTimelineArgs,
2847 0 : timeline_create_guard: TimelineCreateGuard,
2848 0 : ) -> Result<(), anyhow::Error> {
2849 0 : let ctx = RequestContext::new(TaskKind::ImportPgdata, DownloadBehavior::Warn);
2850 0 :
2851 0 : info!("importing pgdata");
2852 0 : import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
2853 0 : .await
2854 0 : .context("import")?;
2855 0 : info!("import done");
2856 :
2857 : //
2858 : // Reload timeline from remote.
2859 : // This proves that the remote state is attachable, and it reuses the code.
2860 : //
2861 : // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
2862 : // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
2863 : // But our activate() call might launch new background tasks after Tenant::shutdown
2864 : // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
2865 : // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
2866 : // down while bootstrapping/branching + activating), but, the race condition is much more likely
2867 : // to manifest because of the long runtime of this import task.
2868 :
2869 : // in theory this shouldn't even .await anything except for coop yield
2870 0 : info!("shutting down timeline");
2871 0 : timeline.shutdown(ShutdownMode::Hard).await;
2872 0 : info!("timeline shut down, reloading from remote");
2873 : // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
2874 : // let Some(timeline) = Arc::into_inner(timeline) else {
2875 : // anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
2876 : // };
2877 0 : let timeline_id = timeline.timeline_id;
2878 0 :
2879 0 : // load from object storage like Tenant::attach does
2880 0 : let resources = self.build_timeline_resources(timeline_id);
2881 0 : let index_part = resources
2882 0 : .remote_client
2883 0 : .download_index_file(&self.cancel)
2884 0 : .await?;
2885 0 : let index_part = match index_part {
2886 : MaybeDeletedIndexPart::Deleted(_) => {
2887 : // likely concurrent delete call, cplane should prevent this
2888 0 : anyhow::bail!(
2889 0 : "index part says deleted but we are not done creating yet, this should not happen but"
2890 0 : )
2891 : }
2892 0 : MaybeDeletedIndexPart::IndexPart(p) => p,
2893 0 : };
2894 0 : let metadata = index_part.metadata.clone();
2895 0 : self
2896 0 : .load_remote_timeline(timeline_id, index_part, metadata, None, resources, LoadTimelineCause::ImportPgdata{
2897 0 : create_guard: timeline_create_guard, activate, }, &ctx)
2898 0 : .await?
2899 0 : .ready_to_activate()
2900 0 : .context("implementation error: reloaded timeline still needs import after import reported success")?;
2901 :
2902 0 : anyhow::Ok(())
2903 0 : }
2904 :
2905 0 : pub(crate) async fn delete_timeline(
2906 0 : self: Arc<Self>,
2907 0 : timeline_id: TimelineId,
2908 0 : ) -> Result<(), DeleteTimelineError> {
2909 0 : DeleteTimelineFlow::run(&self, timeline_id).await?;
2910 :
2911 0 : Ok(())
2912 0 : }
2913 :
2914 : /// perform one garbage collection iteration, removing old data files from disk.
2915 : /// this function is periodically called by gc task.
2916 : /// also it can be explicitly requested through page server api 'do_gc' command.
2917 : ///
2918 : /// `target_timeline_id` specifies the timeline to GC, or None for all.
2919 : ///
2920 : /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
2921 : /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
2922 : /// the amount of history, as LSN difference from current latest LSN on each timeline.
2923 : /// `pitr` specifies the same as a time difference from the current time. The effective
2924 : /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
2925 : /// requires more history to be retained.
2926 : //
2927 1508 : pub(crate) async fn gc_iteration(
2928 1508 : &self,
2929 1508 : target_timeline_id: Option<TimelineId>,
2930 1508 : horizon: u64,
2931 1508 : pitr: Duration,
2932 1508 : cancel: &CancellationToken,
2933 1508 : ctx: &RequestContext,
2934 1508 : ) -> Result<GcResult, GcError> {
2935 1508 : // Don't start doing work during shutdown
2936 1508 : if let TenantState::Stopping { .. } = self.current_state() {
2937 0 : return Ok(GcResult::default());
2938 1508 : }
2939 1508 :
2940 1508 : // there is a global allowed_error for this
2941 1508 : if !self.is_active() {
2942 0 : return Err(GcError::NotActive);
2943 1508 : }
2944 1508 :
2945 1508 : {
2946 1508 : let conf = self.tenant_conf.load();
2947 1508 :
2948 1508 : // If we may not delete layers, then simply skip GC. Even though a tenant
2949 1508 : // in AttachedMulti state could do GC and just enqueue the blocked deletions,
2950 1508 : // the only advantage to doing it is to perhaps shrink the LayerMap metadata
2951 1508 : // a bit sooner than we would achieve by waiting for AttachedSingle status.
2952 1508 : if !conf.location.may_delete_layers_hint() {
2953 0 : info!("Skipping GC in location state {:?}", conf.location);
2954 0 : return Ok(GcResult::default());
2955 1508 : }
2956 1508 :
2957 1508 : if conf.is_gc_blocked_by_lsn_lease_deadline() {
2958 1500 : info!("Skipping GC because lsn lease deadline is not reached");
2959 1500 : return Ok(GcResult::default());
2960 8 : }
2961 : }
2962 :
2963 8 : let _guard = match self.gc_block.start().await {
2964 8 : Ok(guard) => guard,
2965 0 : Err(reasons) => {
2966 0 : info!("Skipping GC: {reasons}");
2967 0 : return Ok(GcResult::default());
2968 : }
2969 : };
2970 :
2971 8 : self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
2972 8 : .await
2973 1508 : }
2974 :
2975 : /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
2976 : /// whether another compaction is needed, if we still have pending work or if we yield for
2977 : /// immediate L0 compaction.
2978 : ///
2979 : /// Compaction can also be explicitly requested for a timeline via the HTTP API.
2980 0 : async fn compaction_iteration(
2981 0 : self: &Arc<Self>,
2982 0 : cancel: &CancellationToken,
2983 0 : ctx: &RequestContext,
2984 0 : ) -> Result<CompactionOutcome, CompactionError> {
2985 0 : // Don't compact inactive tenants.
2986 0 : if !self.is_active() {
2987 0 : return Ok(CompactionOutcome::Skipped);
2988 0 : }
2989 0 :
2990 0 : // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
2991 0 : // since we need to compact L0 even in AttachedMulti to bound read amplification.
2992 0 : let location = self.tenant_conf.load().location;
2993 0 : if !location.may_upload_layers_hint() {
2994 0 : info!("skipping compaction in location state {location:?}");
2995 0 : return Ok(CompactionOutcome::Skipped);
2996 0 : }
2997 0 :
2998 0 : // Don't compact if the circuit breaker is tripped.
2999 0 : if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
3000 0 : info!("skipping compaction due to previous failures");
3001 0 : return Ok(CompactionOutcome::Skipped);
3002 0 : }
3003 0 :
3004 0 : // Collect all timelines to compact, along with offload instructions and L0 counts.
3005 0 : let mut compact: Vec<Arc<Timeline>> = Vec::new();
3006 0 : let mut offload: HashSet<TimelineId> = HashSet::new();
3007 0 : let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
3008 0 :
3009 0 : {
3010 0 : let offload_enabled = self.get_timeline_offloading_enabled();
3011 0 : let timelines = self.timelines.lock().unwrap();
3012 0 : for (&timeline_id, timeline) in timelines.iter() {
3013 : // Skip inactive timelines.
3014 0 : if !timeline.is_active() {
3015 0 : continue;
3016 0 : }
3017 0 :
3018 0 : // Schedule the timeline for compaction.
3019 0 : compact.push(timeline.clone());
3020 :
3021 : // Schedule the timeline for offloading if eligible.
3022 0 : let can_offload = offload_enabled
3023 0 : && timeline.can_offload().0
3024 0 : && !timelines
3025 0 : .iter()
3026 0 : .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
3027 0 : if can_offload {
3028 0 : offload.insert(timeline_id);
3029 0 : }
3030 : }
3031 : } // release timelines lock
3032 :
3033 0 : for timeline in &compact {
3034 : // Collect L0 counts. Can't await while holding lock above.
3035 0 : if let Ok(lm) = timeline.layers.read().await.layer_map() {
3036 0 : l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
3037 0 : }
3038 : }
3039 :
3040 : // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
3041 : // bound read amplification.
3042 : //
3043 : // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
3044 : // compaction and offloading. We leave that as a potential problem to solve later. Consider
3045 : // splitting L0 and image/GC compaction to separate background jobs.
3046 0 : if self.get_compaction_l0_first() {
3047 0 : let compaction_threshold = self.get_compaction_threshold();
3048 0 : let compact_l0 = compact
3049 0 : .iter()
3050 0 : .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
3051 0 : .filter(|&(_, l0)| l0 >= compaction_threshold)
3052 0 : .sorted_by_key(|&(_, l0)| l0)
3053 0 : .rev()
3054 0 : .map(|(tli, _)| tli.clone())
3055 0 : .collect_vec();
3056 0 :
3057 0 : let mut has_pending_l0 = false;
3058 0 : for timeline in compact_l0 {
3059 0 : let outcome = timeline
3060 0 : .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
3061 0 : .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
3062 0 : .await
3063 0 : .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
3064 0 : match outcome {
3065 0 : CompactionOutcome::Done => {}
3066 0 : CompactionOutcome::Skipped => {}
3067 0 : CompactionOutcome::Pending => has_pending_l0 = true,
3068 0 : CompactionOutcome::YieldForL0 => has_pending_l0 = true,
3069 : }
3070 : }
3071 0 : if has_pending_l0 {
3072 0 : return Ok(CompactionOutcome::YieldForL0); // do another pass
3073 0 : }
3074 0 : }
3075 :
3076 : // Pass 2: image compaction and timeline offloading. If any timelines have accumulated
3077 : // more L0 layers, they may also be compacted here.
3078 : //
3079 : // NB: image compaction may yield if there is pending L0 compaction.
3080 : //
3081 : // TODO: it will only yield if there is pending L0 compaction on the same timeline. If a
3082 : // different timeline needs compaction, it won't. It should check `l0_compaction_trigger`.
3083 : // We leave this for a later PR.
3084 : //
3085 : // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
3086 : // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
3087 0 : let mut has_pending = false;
3088 0 : for timeline in compact {
3089 0 : if !timeline.is_active() {
3090 0 : continue;
3091 0 : }
3092 :
3093 0 : let mut outcome = timeline
3094 0 : .compact(cancel, EnumSet::default(), ctx)
3095 0 : .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
3096 0 : .await
3097 0 : .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
3098 :
3099 : // If we're done compacting, check the scheduled GC compaction queue for more work.
3100 0 : if outcome == CompactionOutcome::Done {
3101 0 : let queue = {
3102 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3103 0 : guard
3104 0 : .entry(timeline.timeline_id)
3105 0 : .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
3106 0 : .clone()
3107 0 : };
3108 0 : outcome = queue
3109 0 : .iteration(cancel, ctx, &self.gc_block, &timeline)
3110 0 : .instrument(
3111 0 : info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id),
3112 : )
3113 0 : .await?;
3114 0 : }
3115 :
3116 : // If we're done compacting, offload the timeline if requested.
3117 0 : if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
3118 0 : pausable_failpoint!("before-timeline-auto-offload");
3119 0 : offload_timeline(self, &timeline)
3120 0 : .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
3121 0 : .await
3122 0 : .or_else(|err| match err {
3123 : // Ignore this, we likely raced with unarchival.
3124 0 : OffloadError::NotArchived => Ok(()),
3125 0 : err => Err(err),
3126 0 : })?;
3127 0 : }
3128 :
3129 0 : match outcome {
3130 0 : CompactionOutcome::Done => {}
3131 0 : CompactionOutcome::Skipped => {}
3132 0 : CompactionOutcome::Pending => has_pending = true,
3133 : // This mostly makes sense when the L0-only pass above is enabled, since there's
3134 : // otherwise no guarantee that we'll start with the timeline that has high L0.
3135 0 : CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
3136 : }
3137 : }
3138 :
3139 : // Success! Untrip the breaker if necessary.
3140 0 : self.compaction_circuit_breaker
3141 0 : .lock()
3142 0 : .unwrap()
3143 0 : .success(&CIRCUIT_BREAKERS_UNBROKEN);
3144 0 :
3145 0 : match has_pending {
3146 0 : true => Ok(CompactionOutcome::Pending),
3147 0 : false => Ok(CompactionOutcome::Done),
3148 : }
3149 0 : }
3150 :
3151 : /// Trips the compaction circuit breaker if appropriate.
3152 0 : pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
3153 0 : match err {
3154 0 : err if err.is_cancel() => {}
3155 0 : CompactionError::ShuttingDown => (),
3156 : // Offload failures don't trip the circuit breaker, since they're cheap to retry and
3157 : // shouldn't block compaction.
3158 0 : CompactionError::Offload(_) => {}
3159 0 : CompactionError::CollectKeySpaceError(err) => {
3160 0 : // CollectKeySpaceError::Cancelled and PageRead::Cancelled are handled in `err.is_cancel` branch.
3161 0 : self.compaction_circuit_breaker
3162 0 : .lock()
3163 0 : .unwrap()
3164 0 : .fail(&CIRCUIT_BREAKERS_BROKEN, err);
3165 0 : }
3166 0 : CompactionError::Other(err) => {
3167 0 : self.compaction_circuit_breaker
3168 0 : .lock()
3169 0 : .unwrap()
3170 0 : .fail(&CIRCUIT_BREAKERS_BROKEN, err);
3171 0 : }
3172 0 : CompactionError::AlreadyRunning(_) => {}
3173 : }
3174 0 : }
3175 :
3176 : /// Cancel scheduled compaction tasks
3177 0 : pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
3178 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3179 0 : if let Some(q) = guard.get_mut(&timeline_id) {
3180 0 : q.cancel_scheduled();
3181 0 : }
3182 0 : }
3183 :
3184 0 : pub(crate) fn get_scheduled_compaction_tasks(
3185 0 : &self,
3186 0 : timeline_id: TimelineId,
3187 0 : ) -> Vec<CompactInfoResponse> {
3188 0 : let res = {
3189 0 : let guard = self.scheduled_compaction_tasks.lock().unwrap();
3190 0 : guard.get(&timeline_id).map(|q| q.remaining_jobs())
3191 : };
3192 0 : let Some((running, remaining)) = res else {
3193 0 : return Vec::new();
3194 : };
3195 0 : let mut result = Vec::new();
3196 0 : if let Some((id, running)) = running {
3197 0 : result.extend(running.into_compact_info_resp(id, true));
3198 0 : }
3199 0 : for (id, job) in remaining {
3200 0 : result.extend(job.into_compact_info_resp(id, false));
3201 0 : }
3202 0 : result
3203 0 : }
3204 :
3205 : /// Schedule a compaction task for a timeline.
3206 0 : pub(crate) async fn schedule_compaction(
3207 0 : &self,
3208 0 : timeline_id: TimelineId,
3209 0 : options: CompactOptions,
3210 0 : ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
3211 0 : let (tx, rx) = tokio::sync::oneshot::channel();
3212 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3213 0 : let q = guard
3214 0 : .entry(timeline_id)
3215 0 : .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
3216 0 : q.schedule_manual_compaction(options, Some(tx));
3217 0 : Ok(rx)
3218 0 : }
3219 :
3220 : /// Performs periodic housekeeping, via the tenant housekeeping background task.
3221 0 : async fn housekeeping(&self) {
3222 0 : // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
3223 0 : // during ingest, but we don't want idle timelines to hold open layers for too long.
3224 0 : let timelines = self
3225 0 : .timelines
3226 0 : .lock()
3227 0 : .unwrap()
3228 0 : .values()
3229 0 : .filter(|tli| tli.is_active())
3230 0 : .cloned()
3231 0 : .collect_vec();
3232 :
3233 0 : for timeline in timelines {
3234 0 : timeline.maybe_freeze_ephemeral_layer().await;
3235 : }
3236 :
3237 : // Shut down walredo if idle.
3238 : const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
3239 0 : if let Some(ref walredo_mgr) = self.walredo_mgr {
3240 0 : walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
3241 0 : }
3242 0 : }
3243 :
3244 0 : pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
3245 0 : let timelines = self.timelines.lock().unwrap();
3246 0 : !timelines
3247 0 : .iter()
3248 0 : .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
3249 0 : }
3250 :
3251 3478 : pub fn current_state(&self) -> TenantState {
3252 3478 : self.state.borrow().clone()
3253 3478 : }
3254 :
3255 1954 : pub fn is_active(&self) -> bool {
3256 1954 : self.current_state() == TenantState::Active
3257 1954 : }
3258 :
3259 0 : pub fn generation(&self) -> Generation {
3260 0 : self.generation
3261 0 : }
3262 :
3263 0 : pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
3264 0 : self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
3265 0 : }
3266 :
3267 : /// Changes tenant status to active, unless shutdown was already requested.
3268 : ///
3269 : /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
3270 : /// to delay background jobs. Background jobs can be started right away when None is given.
3271 0 : fn activate(
3272 0 : self: &Arc<Self>,
3273 0 : broker_client: BrokerClientChannel,
3274 0 : background_jobs_can_start: Option<&completion::Barrier>,
3275 0 : ctx: &RequestContext,
3276 0 : ) {
3277 0 : span::debug_assert_current_span_has_tenant_id();
3278 0 :
3279 0 : let mut activating = false;
3280 0 : self.state.send_modify(|current_state| {
3281 : use pageserver_api::models::ActivatingFrom;
3282 0 : match &*current_state {
3283 : TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
3284 0 : panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
3285 : }
3286 0 : TenantState::Attaching => {
3287 0 : *current_state = TenantState::Activating(ActivatingFrom::Attaching);
3288 0 : }
3289 0 : }
3290 0 : debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
3291 0 : activating = true;
3292 0 : // Continue outside the closure. We need to grab timelines.lock()
3293 0 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
3294 0 : });
3295 0 :
3296 0 : if activating {
3297 0 : let timelines_accessor = self.timelines.lock().unwrap();
3298 0 : let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
3299 0 : let timelines_to_activate = timelines_accessor
3300 0 : .values()
3301 0 : .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
3302 0 :
3303 0 : // Before activation, populate each Timeline's GcInfo with information about its children
3304 0 : self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
3305 0 :
3306 0 : // Spawn gc and compaction loops. The loops will shut themselves
3307 0 : // down when they notice that the tenant is inactive.
3308 0 : tasks::start_background_loops(self, background_jobs_can_start);
3309 0 :
3310 0 : let mut activated_timelines = 0;
3311 :
3312 0 : for timeline in timelines_to_activate {
3313 0 : timeline.activate(
3314 0 : self.clone(),
3315 0 : broker_client.clone(),
3316 0 : background_jobs_can_start,
3317 0 : ctx,
3318 0 : );
3319 0 : activated_timelines += 1;
3320 0 : }
3321 :
3322 0 : self.state.send_modify(move |current_state| {
3323 0 : assert!(
3324 0 : matches!(current_state, TenantState::Activating(_)),
3325 0 : "set_stopping and set_broken wait for us to leave Activating state",
3326 : );
3327 0 : *current_state = TenantState::Active;
3328 0 :
3329 0 : let elapsed = self.constructed_at.elapsed();
3330 0 : let total_timelines = timelines_accessor.len();
3331 0 :
3332 0 : // log a lot of stuff, because some tenants sometimes suffer from user-visible
3333 0 : // times to activate. see https://github.com/neondatabase/neon/issues/4025
3334 0 : info!(
3335 0 : since_creation_millis = elapsed.as_millis(),
3336 0 : tenant_id = %self.tenant_shard_id.tenant_id,
3337 0 : shard_id = %self.tenant_shard_id.shard_slug(),
3338 0 : activated_timelines,
3339 0 : total_timelines,
3340 0 : post_state = <&'static str>::from(&*current_state),
3341 0 : "activation attempt finished"
3342 : );
3343 :
3344 0 : TENANT.activation.observe(elapsed.as_secs_f64());
3345 0 : });
3346 0 : }
3347 0 : }
3348 :
3349 : /// Shutdown the tenant and join all of the spawned tasks.
3350 : ///
3351 : /// The method caters for all use-cases:
3352 : /// - pageserver shutdown (freeze_and_flush == true)
3353 : /// - detach + ignore (freeze_and_flush == false)
3354 : ///
3355 : /// This will attempt to shutdown even if tenant is broken.
3356 : ///
3357 : /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
3358 : /// If the tenant is already shutting down, we return a clone of the first shutdown call's
3359 : /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
3360 : /// the ongoing shutdown.
3361 12 : async fn shutdown(
3362 12 : &self,
3363 12 : shutdown_progress: completion::Barrier,
3364 12 : shutdown_mode: timeline::ShutdownMode,
3365 12 : ) -> Result<(), completion::Barrier> {
3366 12 : span::debug_assert_current_span_has_tenant_id();
3367 :
3368 : // Set tenant (and its timlines) to Stoppping state.
3369 : //
3370 : // Since we can only transition into Stopping state after activation is complete,
3371 : // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
3372 : //
3373 : // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
3374 : // 1. Lock out any new requests to the tenants.
3375 : // 2. Signal cancellation to WAL receivers (we wait on it below).
3376 : // 3. Signal cancellation for other tenant background loops.
3377 : // 4. ???
3378 : //
3379 : // The waiting for the cancellation is not done uniformly.
3380 : // We certainly wait for WAL receivers to shut down.
3381 : // That is necessary so that no new data comes in before the freeze_and_flush.
3382 : // But the tenant background loops are joined-on in our caller.
3383 : // It's mesed up.
3384 : // we just ignore the failure to stop
3385 :
3386 : // If we're still attaching, fire the cancellation token early to drop out: this
3387 : // will prevent us flushing, but ensures timely shutdown if some I/O during attach
3388 : // is very slow.
3389 12 : let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
3390 0 : self.cancel.cancel();
3391 0 :
3392 0 : // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
3393 0 : // are children of ours, so their flush loops will have shut down already
3394 0 : timeline::ShutdownMode::Hard
3395 : } else {
3396 12 : shutdown_mode
3397 : };
3398 :
3399 12 : match self.set_stopping(shutdown_progress, false, false).await {
3400 12 : Ok(()) => {}
3401 0 : Err(SetStoppingError::Broken) => {
3402 0 : // assume that this is acceptable
3403 0 : }
3404 0 : Err(SetStoppingError::AlreadyStopping(other)) => {
3405 0 : // give caller the option to wait for this this shutdown
3406 0 : info!("Tenant::shutdown: AlreadyStopping");
3407 0 : return Err(other);
3408 : }
3409 : };
3410 :
3411 12 : let mut js = tokio::task::JoinSet::new();
3412 12 : {
3413 12 : let timelines = self.timelines.lock().unwrap();
3414 12 : timelines.values().for_each(|timeline| {
3415 12 : let timeline = Arc::clone(timeline);
3416 12 : let timeline_id = timeline.timeline_id;
3417 12 : let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
3418 12 : js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
3419 12 : });
3420 12 : }
3421 12 : {
3422 12 : let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
3423 12 : timelines_offloaded.values().for_each(|timeline| {
3424 0 : timeline.defuse_for_tenant_drop();
3425 12 : });
3426 12 : }
3427 12 : // test_long_timeline_create_then_tenant_delete is leaning on this message
3428 12 : tracing::info!("Waiting for timelines...");
3429 24 : while let Some(res) = js.join_next().await {
3430 0 : match res {
3431 12 : Ok(()) => {}
3432 0 : Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
3433 0 : Err(je) if je.is_panic() => { /* logged already */ }
3434 0 : Err(je) => warn!("unexpected JoinError: {je:?}"),
3435 : }
3436 : }
3437 :
3438 12 : if let ShutdownMode::Reload = shutdown_mode {
3439 0 : tracing::info!("Flushing deletion queue");
3440 0 : if let Err(e) = self.deletion_queue_client.flush().await {
3441 0 : match e {
3442 0 : DeletionQueueError::ShuttingDown => {
3443 0 : // This is the only error we expect for now. In the future, if more error
3444 0 : // variants are added, we should handle them here.
3445 0 : }
3446 : }
3447 0 : }
3448 12 : }
3449 :
3450 : // We cancel the Tenant's cancellation token _after_ the timelines have all shut down. This permits
3451 : // them to continue to do work during their shutdown methods, e.g. flushing data.
3452 12 : tracing::debug!("Cancelling CancellationToken");
3453 12 : self.cancel.cancel();
3454 12 :
3455 12 : // shutdown all tenant and timeline tasks: gc, compaction, page service
3456 12 : // No new tasks will be started for this tenant because it's in `Stopping` state.
3457 12 : //
3458 12 : // this will additionally shutdown and await all timeline tasks.
3459 12 : tracing::debug!("Waiting for tasks...");
3460 12 : task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
3461 :
3462 12 : if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
3463 12 : walredo_mgr.shutdown().await;
3464 0 : }
3465 :
3466 : // Wait for any in-flight operations to complete
3467 12 : self.gate.close().await;
3468 :
3469 12 : remove_tenant_metrics(&self.tenant_shard_id);
3470 12 :
3471 12 : Ok(())
3472 12 : }
3473 :
3474 : /// Change tenant status to Stopping, to mark that it is being shut down.
3475 : ///
3476 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
3477 : ///
3478 : /// This function is not cancel-safe!
3479 : ///
3480 : /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
3481 : /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
3482 12 : async fn set_stopping(
3483 12 : &self,
3484 12 : progress: completion::Barrier,
3485 12 : _allow_transition_from_loading: bool,
3486 12 : allow_transition_from_attaching: bool,
3487 12 : ) -> Result<(), SetStoppingError> {
3488 12 : let mut rx = self.state.subscribe();
3489 12 :
3490 12 : // cannot stop before we're done activating, so wait out until we're done activating
3491 12 : rx.wait_for(|state| match state {
3492 0 : TenantState::Attaching if allow_transition_from_attaching => true,
3493 : TenantState::Activating(_) | TenantState::Attaching => {
3494 0 : info!(
3495 0 : "waiting for {} to turn Active|Broken|Stopping",
3496 0 : <&'static str>::from(state)
3497 : );
3498 0 : false
3499 : }
3500 12 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
3501 12 : })
3502 12 : .await
3503 12 : .expect("cannot drop self.state while on a &self method");
3504 12 :
3505 12 : // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
3506 12 : let mut err = None;
3507 12 : let stopping = self.state.send_if_modified(|current_state| match current_state {
3508 : TenantState::Activating(_) => {
3509 0 : unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
3510 : }
3511 : TenantState::Attaching => {
3512 0 : if !allow_transition_from_attaching {
3513 0 : unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
3514 0 : };
3515 0 : *current_state = TenantState::Stopping { progress };
3516 0 : true
3517 : }
3518 : TenantState::Active => {
3519 : // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
3520 : // are created after the transition to Stopping. That's harmless, as the Timelines
3521 : // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
3522 12 : *current_state = TenantState::Stopping { progress };
3523 12 : // Continue stopping outside the closure. We need to grab timelines.lock()
3524 12 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
3525 12 : true
3526 : }
3527 0 : TenantState::Broken { reason, .. } => {
3528 0 : info!(
3529 0 : "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
3530 : );
3531 0 : err = Some(SetStoppingError::Broken);
3532 0 : false
3533 : }
3534 0 : TenantState::Stopping { progress } => {
3535 0 : info!("Tenant is already in Stopping state");
3536 0 : err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
3537 0 : false
3538 : }
3539 12 : });
3540 12 : match (stopping, err) {
3541 12 : (true, None) => {} // continue
3542 0 : (false, Some(err)) => return Err(err),
3543 0 : (true, Some(_)) => unreachable!(
3544 0 : "send_if_modified closure must error out if not transitioning to Stopping"
3545 0 : ),
3546 0 : (false, None) => unreachable!(
3547 0 : "send_if_modified closure must return true if transitioning to Stopping"
3548 0 : ),
3549 : }
3550 :
3551 12 : let timelines_accessor = self.timelines.lock().unwrap();
3552 12 : let not_broken_timelines = timelines_accessor
3553 12 : .values()
3554 12 : .filter(|timeline| !timeline.is_broken());
3555 24 : for timeline in not_broken_timelines {
3556 12 : timeline.set_state(TimelineState::Stopping);
3557 12 : }
3558 12 : Ok(())
3559 12 : }
3560 :
3561 : /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
3562 : /// `remove_tenant_from_memory`
3563 : ///
3564 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
3565 : ///
3566 : /// In tests, we also use this to set tenants to Broken state on purpose.
3567 0 : pub(crate) async fn set_broken(&self, reason: String) {
3568 0 : let mut rx = self.state.subscribe();
3569 0 :
3570 0 : // The load & attach routines own the tenant state until it has reached `Active`.
3571 0 : // So, wait until it's done.
3572 0 : rx.wait_for(|state| match state {
3573 : TenantState::Activating(_) | TenantState::Attaching => {
3574 0 : info!(
3575 0 : "waiting for {} to turn Active|Broken|Stopping",
3576 0 : <&'static str>::from(state)
3577 : );
3578 0 : false
3579 : }
3580 0 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
3581 0 : })
3582 0 : .await
3583 0 : .expect("cannot drop self.state while on a &self method");
3584 0 :
3585 0 : // we now know we're done activating, let's see whether this task is the winner to transition into Broken
3586 0 : self.set_broken_no_wait(reason)
3587 0 : }
3588 :
3589 0 : pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
3590 0 : let reason = reason.to_string();
3591 0 : self.state.send_modify(|current_state| {
3592 0 : match *current_state {
3593 : TenantState::Activating(_) | TenantState::Attaching => {
3594 0 : unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
3595 : }
3596 : TenantState::Active => {
3597 0 : if cfg!(feature = "testing") {
3598 0 : warn!("Changing Active tenant to Broken state, reason: {}", reason);
3599 0 : *current_state = TenantState::broken_from_reason(reason);
3600 : } else {
3601 0 : unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
3602 : }
3603 : }
3604 : TenantState::Broken { .. } => {
3605 0 : warn!("Tenant is already in Broken state");
3606 : }
3607 : // This is the only "expected" path, any other path is a bug.
3608 : TenantState::Stopping { .. } => {
3609 0 : warn!(
3610 0 : "Marking Stopping tenant as Broken state, reason: {}",
3611 : reason
3612 : );
3613 0 : *current_state = TenantState::broken_from_reason(reason);
3614 : }
3615 : }
3616 0 : });
3617 0 : }
3618 :
3619 0 : pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
3620 0 : self.state.subscribe()
3621 0 : }
3622 :
3623 : /// The activate_now semaphore is initialized with zero units. As soon as
3624 : /// we add a unit, waiters will be able to acquire a unit and proceed.
3625 0 : pub(crate) fn activate_now(&self) {
3626 0 : self.activate_now_sem.add_permits(1);
3627 0 : }
3628 :
3629 0 : pub(crate) async fn wait_to_become_active(
3630 0 : &self,
3631 0 : timeout: Duration,
3632 0 : ) -> Result<(), GetActiveTenantError> {
3633 0 : let mut receiver = self.state.subscribe();
3634 : loop {
3635 0 : let current_state = receiver.borrow_and_update().clone();
3636 0 : match current_state {
3637 : TenantState::Attaching | TenantState::Activating(_) => {
3638 : // in these states, there's a chance that we can reach ::Active
3639 0 : self.activate_now();
3640 0 : match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
3641 0 : Ok(r) => {
3642 0 : r.map_err(
3643 0 : |_e: tokio::sync::watch::error::RecvError|
3644 : // Tenant existed but was dropped: report it as non-existent
3645 0 : GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
3646 0 : )?
3647 : }
3648 : Err(TimeoutCancellableError::Cancelled) => {
3649 0 : return Err(GetActiveTenantError::Cancelled);
3650 : }
3651 : Err(TimeoutCancellableError::Timeout) => {
3652 0 : return Err(GetActiveTenantError::WaitForActiveTimeout {
3653 0 : latest_state: Some(self.current_state()),
3654 0 : wait_time: timeout,
3655 0 : });
3656 : }
3657 : }
3658 : }
3659 : TenantState::Active { .. } => {
3660 0 : return Ok(());
3661 : }
3662 0 : TenantState::Broken { reason, .. } => {
3663 0 : // This is fatal, and reported distinctly from the general case of "will never be active" because
3664 0 : // it's logically a 500 to external API users (broken is always a bug).
3665 0 : return Err(GetActiveTenantError::Broken(reason));
3666 : }
3667 : TenantState::Stopping { .. } => {
3668 : // There's no chance the tenant can transition back into ::Active
3669 0 : return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
3670 : }
3671 : }
3672 : }
3673 0 : }
3674 :
3675 0 : pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
3676 0 : self.tenant_conf.load().location.attach_mode
3677 0 : }
3678 :
3679 : /// For API access: generate a LocationConfig equivalent to the one that would be used to
3680 : /// create a Tenant in the same state. Do not use this in hot paths: it's for relatively
3681 : /// rare external API calls, like a reconciliation at startup.
3682 0 : pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
3683 0 : let conf = self.tenant_conf.load();
3684 :
3685 0 : let location_config_mode = match conf.location.attach_mode {
3686 0 : AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
3687 0 : AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
3688 0 : AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
3689 : };
3690 :
3691 : // We have a pageserver TenantConf, we need the API-facing TenantConfig.
3692 0 : let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
3693 0 :
3694 0 : models::LocationConfig {
3695 0 : mode: location_config_mode,
3696 0 : generation: self.generation.into(),
3697 0 : secondary_conf: None,
3698 0 : shard_number: self.shard_identity.number.0,
3699 0 : shard_count: self.shard_identity.count.literal(),
3700 0 : shard_stripe_size: self.shard_identity.stripe_size.0,
3701 0 : tenant_conf: tenant_config,
3702 0 : }
3703 0 : }
3704 :
3705 0 : pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
3706 0 : &self.tenant_shard_id
3707 0 : }
3708 :
3709 0 : pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
3710 0 : self.shard_identity.stripe_size
3711 0 : }
3712 :
3713 0 : pub(crate) fn get_generation(&self) -> Generation {
3714 0 : self.generation
3715 0 : }
3716 :
3717 : /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
3718 : /// and can leave the tenant in a bad state if it fails. The caller is responsible for
3719 : /// resetting this tenant to a valid state if we fail.
3720 0 : pub(crate) async fn split_prepare(
3721 0 : &self,
3722 0 : child_shards: &Vec<TenantShardId>,
3723 0 : ) -> anyhow::Result<()> {
3724 0 : let (timelines, offloaded) = {
3725 0 : let timelines = self.timelines.lock().unwrap();
3726 0 : let offloaded = self.timelines_offloaded.lock().unwrap();
3727 0 : (timelines.clone(), offloaded.clone())
3728 0 : };
3729 0 : let timelines_iter = timelines
3730 0 : .values()
3731 0 : .map(TimelineOrOffloadedArcRef::<'_>::from)
3732 0 : .chain(
3733 0 : offloaded
3734 0 : .values()
3735 0 : .map(TimelineOrOffloadedArcRef::<'_>::from),
3736 0 : );
3737 0 : for timeline in timelines_iter {
3738 : // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
3739 : // to ensure that they do not start a split if currently in the process of doing these.
3740 :
3741 0 : let timeline_id = timeline.timeline_id();
3742 :
3743 0 : if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
3744 : // Upload an index from the parent: this is partly to provide freshness for the
3745 : // child tenants that will copy it, and partly for general ease-of-debugging: there will
3746 : // always be a parent shard index in the same generation as we wrote the child shard index.
3747 0 : tracing::info!(%timeline_id, "Uploading index");
3748 0 : timeline
3749 0 : .remote_client
3750 0 : .schedule_index_upload_for_file_changes()?;
3751 0 : timeline.remote_client.wait_completion().await?;
3752 0 : }
3753 :
3754 0 : let remote_client = match timeline {
3755 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
3756 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
3757 0 : let remote_client = self
3758 0 : .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
3759 0 : Arc::new(remote_client)
3760 : }
3761 : };
3762 :
3763 : // Shut down the timeline's remote client: this means that the indices we write
3764 : // for child shards will not be invalidated by the parent shard deleting layers.
3765 0 : tracing::info!(%timeline_id, "Shutting down remote storage client");
3766 0 : remote_client.shutdown().await;
3767 :
3768 : // Download methods can still be used after shutdown, as they don't flow through the remote client's
3769 : // queue. In principal the RemoteTimelineClient could provide this without downloading it, but this
3770 : // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
3771 : // we use here really is the remotely persistent one).
3772 0 : tracing::info!(%timeline_id, "Downloading index_part from parent");
3773 0 : let result = remote_client
3774 0 : .download_index_file(&self.cancel)
3775 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))
3776 0 : .await?;
3777 0 : let index_part = match result {
3778 : MaybeDeletedIndexPart::Deleted(_) => {
3779 0 : anyhow::bail!("Timeline deletion happened concurrently with split")
3780 : }
3781 0 : MaybeDeletedIndexPart::IndexPart(p) => p,
3782 : };
3783 :
3784 0 : for child_shard in child_shards {
3785 0 : tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
3786 0 : upload_index_part(
3787 0 : &self.remote_storage,
3788 0 : child_shard,
3789 0 : &timeline_id,
3790 0 : self.generation,
3791 0 : &index_part,
3792 0 : &self.cancel,
3793 0 : )
3794 0 : .await?;
3795 : }
3796 : }
3797 :
3798 0 : let tenant_manifest = self.build_tenant_manifest();
3799 0 : for child_shard in child_shards {
3800 0 : tracing::info!(
3801 0 : "Uploading tenant manifest for child {}",
3802 0 : child_shard.to_index()
3803 : );
3804 0 : upload_tenant_manifest(
3805 0 : &self.remote_storage,
3806 0 : child_shard,
3807 0 : self.generation,
3808 0 : &tenant_manifest,
3809 0 : &self.cancel,
3810 0 : )
3811 0 : .await?;
3812 : }
3813 :
3814 0 : Ok(())
3815 0 : }
3816 :
3817 0 : pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
3818 0 : let mut result = TopTenantShardItem {
3819 0 : id: self.tenant_shard_id,
3820 0 : resident_size: 0,
3821 0 : physical_size: 0,
3822 0 : max_logical_size: 0,
3823 0 : };
3824 :
3825 0 : for timeline in self.timelines.lock().unwrap().values() {
3826 0 : result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
3827 0 :
3828 0 : result.physical_size += timeline
3829 0 : .remote_client
3830 0 : .metrics
3831 0 : .remote_physical_size_gauge
3832 0 : .get();
3833 0 : result.max_logical_size = std::cmp::max(
3834 0 : result.max_logical_size,
3835 0 : timeline.metrics.current_logical_size_gauge.get(),
3836 0 : );
3837 0 : }
3838 :
3839 0 : result
3840 0 : }
3841 : }
3842 :
3843 : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
3844 : /// perform a topological sort, so that the parent of each timeline comes
3845 : /// before the children.
3846 : /// E extracts the ancestor from T
3847 : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
3848 454 : fn tree_sort_timelines<T, E>(
3849 454 : timelines: HashMap<TimelineId, T>,
3850 454 : extractor: E,
3851 454 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
3852 454 : where
3853 454 : E: Fn(&T) -> Option<TimelineId>,
3854 454 : {
3855 454 : let mut result = Vec::with_capacity(timelines.len());
3856 454 :
3857 454 : let mut now = Vec::with_capacity(timelines.len());
3858 454 : // (ancestor, children)
3859 454 : let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
3860 454 : HashMap::with_capacity(timelines.len());
3861 :
3862 466 : for (timeline_id, value) in timelines {
3863 12 : if let Some(ancestor_id) = extractor(&value) {
3864 4 : let children = later.entry(ancestor_id).or_default();
3865 4 : children.push((timeline_id, value));
3866 8 : } else {
3867 8 : now.push((timeline_id, value));
3868 8 : }
3869 : }
3870 :
3871 466 : while let Some((timeline_id, metadata)) = now.pop() {
3872 12 : result.push((timeline_id, metadata));
3873 : // All children of this can be loaded now
3874 12 : if let Some(mut children) = later.remove(&timeline_id) {
3875 4 : now.append(&mut children);
3876 8 : }
3877 : }
3878 :
3879 : // All timelines should be visited now. Unless there were timelines with missing ancestors.
3880 454 : if !later.is_empty() {
3881 0 : for (missing_id, orphan_ids) in later {
3882 0 : for (orphan_id, _) in orphan_ids {
3883 0 : error!(
3884 0 : "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
3885 : );
3886 : }
3887 : }
3888 0 : bail!("could not load tenant because some timelines are missing ancestors");
3889 454 : }
3890 454 :
3891 454 : Ok(result)
3892 454 : }
3893 :
3894 : enum ActivateTimelineArgs {
3895 : Yes {
3896 : broker_client: storage_broker::BrokerClientChannel,
3897 : },
3898 : No,
3899 : }
3900 :
3901 : impl Tenant {
3902 0 : pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
3903 0 : self.tenant_conf.load().tenant_conf.clone()
3904 0 : }
3905 :
3906 0 : pub fn effective_config(&self) -> TenantConf {
3907 0 : self.tenant_specific_overrides()
3908 0 : .merge(self.conf.default_tenant_conf.clone())
3909 0 : }
3910 :
3911 0 : pub fn get_checkpoint_distance(&self) -> u64 {
3912 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3913 0 : tenant_conf
3914 0 : .checkpoint_distance
3915 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
3916 0 : }
3917 :
3918 0 : pub fn get_checkpoint_timeout(&self) -> Duration {
3919 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3920 0 : tenant_conf
3921 0 : .checkpoint_timeout
3922 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
3923 0 : }
3924 :
3925 0 : pub fn get_compaction_target_size(&self) -> u64 {
3926 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3927 0 : tenant_conf
3928 0 : .compaction_target_size
3929 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
3930 0 : }
3931 :
3932 0 : pub fn get_compaction_period(&self) -> Duration {
3933 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3934 0 : tenant_conf
3935 0 : .compaction_period
3936 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_period)
3937 0 : }
3938 :
3939 0 : pub fn get_compaction_threshold(&self) -> usize {
3940 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3941 0 : tenant_conf
3942 0 : .compaction_threshold
3943 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
3944 0 : }
3945 :
3946 0 : pub fn get_rel_size_v2_enabled(&self) -> bool {
3947 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3948 0 : tenant_conf
3949 0 : .rel_size_v2_enabled
3950 0 : .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
3951 0 : }
3952 :
3953 0 : pub fn get_compaction_upper_limit(&self) -> usize {
3954 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3955 0 : tenant_conf
3956 0 : .compaction_upper_limit
3957 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
3958 0 : }
3959 :
3960 0 : pub fn get_compaction_l0_first(&self) -> bool {
3961 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3962 0 : tenant_conf
3963 0 : .compaction_l0_first
3964 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
3965 0 : }
3966 :
3967 0 : pub fn get_gc_horizon(&self) -> u64 {
3968 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3969 0 : tenant_conf
3970 0 : .gc_horizon
3971 0 : .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
3972 0 : }
3973 :
3974 0 : pub fn get_gc_period(&self) -> Duration {
3975 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3976 0 : tenant_conf
3977 0 : .gc_period
3978 0 : .unwrap_or(self.conf.default_tenant_conf.gc_period)
3979 0 : }
3980 :
3981 0 : pub fn get_image_creation_threshold(&self) -> usize {
3982 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3983 0 : tenant_conf
3984 0 : .image_creation_threshold
3985 0 : .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
3986 0 : }
3987 :
3988 0 : pub fn get_pitr_interval(&self) -> Duration {
3989 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3990 0 : tenant_conf
3991 0 : .pitr_interval
3992 0 : .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
3993 0 : }
3994 :
3995 0 : pub fn get_min_resident_size_override(&self) -> Option<u64> {
3996 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3997 0 : tenant_conf
3998 0 : .min_resident_size_override
3999 0 : .or(self.conf.default_tenant_conf.min_resident_size_override)
4000 0 : }
4001 :
4002 0 : pub fn get_heatmap_period(&self) -> Option<Duration> {
4003 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4004 0 : let heatmap_period = tenant_conf
4005 0 : .heatmap_period
4006 0 : .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
4007 0 : if heatmap_period.is_zero() {
4008 0 : None
4009 : } else {
4010 0 : Some(heatmap_period)
4011 : }
4012 0 : }
4013 :
4014 8 : pub fn get_lsn_lease_length(&self) -> Duration {
4015 8 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4016 8 : tenant_conf
4017 8 : .lsn_lease_length
4018 8 : .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
4019 8 : }
4020 :
4021 0 : pub fn get_timeline_offloading_enabled(&self) -> bool {
4022 0 : if self.conf.timeline_offloading {
4023 0 : return true;
4024 0 : }
4025 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4026 0 : tenant_conf
4027 0 : .timeline_offloading
4028 0 : .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
4029 0 : }
4030 :
4031 : /// Generate an up-to-date TenantManifest based on the state of this Tenant.
4032 4 : fn build_tenant_manifest(&self) -> TenantManifest {
4033 4 : let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
4034 4 :
4035 4 : let mut timeline_manifests = timelines_offloaded
4036 4 : .iter()
4037 4 : .map(|(_timeline_id, offloaded)| offloaded.manifest())
4038 4 : .collect::<Vec<_>>();
4039 4 : // Sort the manifests so that our output is deterministic
4040 4 : timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
4041 4 :
4042 4 : TenantManifest {
4043 4 : version: LATEST_TENANT_MANIFEST_VERSION,
4044 4 : offloaded_timelines: timeline_manifests,
4045 4 : }
4046 4 : }
4047 :
4048 0 : pub fn update_tenant_config<F: Fn(TenantConfOpt) -> anyhow::Result<TenantConfOpt>>(
4049 0 : &self,
4050 0 : update: F,
4051 0 : ) -> anyhow::Result<TenantConfOpt> {
4052 0 : // Use read-copy-update in order to avoid overwriting the location config
4053 0 : // state if this races with [`Tenant::set_new_location_config`]. Note that
4054 0 : // this race is not possible if both request types come from the storage
4055 0 : // controller (as they should!) because an exclusive op lock is required
4056 0 : // on the storage controller side.
4057 0 :
4058 0 : self.tenant_conf
4059 0 : .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
4060 0 : Ok(Arc::new(AttachedTenantConf {
4061 0 : tenant_conf: update(attached_conf.tenant_conf.clone())?,
4062 0 : location: attached_conf.location,
4063 0 : lsn_lease_deadline: attached_conf.lsn_lease_deadline,
4064 : }))
4065 0 : })?;
4066 :
4067 0 : let updated = self.tenant_conf.load();
4068 0 :
4069 0 : self.tenant_conf_updated(&updated.tenant_conf);
4070 0 : // Don't hold self.timelines.lock() during the notifies.
4071 0 : // There's no risk of deadlock right now, but there could be if we consolidate
4072 0 : // mutexes in struct Timeline in the future.
4073 0 : let timelines = self.list_timelines();
4074 0 : for timeline in timelines {
4075 0 : timeline.tenant_conf_updated(&updated);
4076 0 : }
4077 :
4078 0 : Ok(updated.tenant_conf.clone())
4079 0 : }
4080 :
4081 0 : pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
4082 0 : let new_tenant_conf = new_conf.tenant_conf.clone();
4083 0 :
4084 0 : self.tenant_conf.store(Arc::new(new_conf.clone()));
4085 0 :
4086 0 : self.tenant_conf_updated(&new_tenant_conf);
4087 0 : // Don't hold self.timelines.lock() during the notifies.
4088 0 : // There's no risk of deadlock right now, but there could be if we consolidate
4089 0 : // mutexes in struct Timeline in the future.
4090 0 : let timelines = self.list_timelines();
4091 0 : for timeline in timelines {
4092 0 : timeline.tenant_conf_updated(&new_conf);
4093 0 : }
4094 0 : }
4095 :
4096 454 : fn get_pagestream_throttle_config(
4097 454 : psconf: &'static PageServerConf,
4098 454 : overrides: &TenantConfOpt,
4099 454 : ) -> throttle::Config {
4100 454 : overrides
4101 454 : .timeline_get_throttle
4102 454 : .clone()
4103 454 : .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
4104 454 : }
4105 :
4106 0 : pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
4107 0 : let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
4108 0 : self.pagestream_throttle.reconfigure(conf)
4109 0 : }
4110 :
4111 : /// Helper function to create a new Timeline struct.
4112 : ///
4113 : /// The returned Timeline is in Loading state. The caller is responsible for
4114 : /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
4115 : /// map.
4116 : ///
4117 : /// `validate_ancestor == false` is used when a timeline is created for deletion
4118 : /// and we might not have the ancestor present anymore which is fine for to be
4119 : /// deleted timelines.
4120 : #[allow(clippy::too_many_arguments)]
4121 906 : fn create_timeline_struct(
4122 906 : &self,
4123 906 : new_timeline_id: TimelineId,
4124 906 : new_metadata: &TimelineMetadata,
4125 906 : previous_heatmap: Option<PreviousHeatmap>,
4126 906 : ancestor: Option<Arc<Timeline>>,
4127 906 : resources: TimelineResources,
4128 906 : cause: CreateTimelineCause,
4129 906 : create_idempotency: CreateTimelineIdempotency,
4130 906 : gc_compaction_state: Option<GcCompactionState>,
4131 906 : ) -> anyhow::Result<Arc<Timeline>> {
4132 906 : let state = match cause {
4133 : CreateTimelineCause::Load => {
4134 906 : let ancestor_id = new_metadata.ancestor_timeline();
4135 906 : anyhow::ensure!(
4136 906 : ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
4137 0 : "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
4138 : );
4139 906 : TimelineState::Loading
4140 : }
4141 0 : CreateTimelineCause::Delete => TimelineState::Stopping,
4142 : };
4143 :
4144 906 : let pg_version = new_metadata.pg_version();
4145 906 :
4146 906 : let timeline = Timeline::new(
4147 906 : self.conf,
4148 906 : Arc::clone(&self.tenant_conf),
4149 906 : new_metadata,
4150 906 : previous_heatmap,
4151 906 : ancestor,
4152 906 : new_timeline_id,
4153 906 : self.tenant_shard_id,
4154 906 : self.generation,
4155 906 : self.shard_identity,
4156 906 : self.walredo_mgr.clone(),
4157 906 : resources,
4158 906 : pg_version,
4159 906 : state,
4160 906 : self.attach_wal_lag_cooldown.clone(),
4161 906 : create_idempotency,
4162 906 : gc_compaction_state,
4163 906 : self.cancel.child_token(),
4164 906 : );
4165 906 :
4166 906 : Ok(timeline)
4167 906 : }
4168 :
4169 : /// [`Tenant::shutdown`] must be called before dropping the returned [`Tenant`] object
4170 : /// to ensure proper cleanup of background tasks and metrics.
4171 : //
4172 : // Allow too_many_arguments because a constructor's argument list naturally grows with the
4173 : // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
4174 : #[allow(clippy::too_many_arguments)]
4175 454 : fn new(
4176 454 : state: TenantState,
4177 454 : conf: &'static PageServerConf,
4178 454 : attached_conf: AttachedTenantConf,
4179 454 : shard_identity: ShardIdentity,
4180 454 : walredo_mgr: Option<Arc<WalRedoManager>>,
4181 454 : tenant_shard_id: TenantShardId,
4182 454 : remote_storage: GenericRemoteStorage,
4183 454 : deletion_queue_client: DeletionQueueClient,
4184 454 : l0_flush_global_state: L0FlushGlobalState,
4185 454 : ) -> Tenant {
4186 454 : debug_assert!(
4187 454 : !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
4188 : );
4189 :
4190 454 : let (state, mut rx) = watch::channel(state);
4191 454 :
4192 454 : tokio::spawn(async move {
4193 454 : // reflect tenant state in metrics:
4194 454 : // - global per tenant state: TENANT_STATE_METRIC
4195 454 : // - "set" of broken tenants: BROKEN_TENANTS_SET
4196 454 : //
4197 454 : // set of broken tenants should not have zero counts so that it remains accessible for
4198 454 : // alerting.
4199 454 :
4200 454 : let tid = tenant_shard_id.to_string();
4201 454 : let shard_id = tenant_shard_id.shard_slug().to_string();
4202 454 : let set_key = &[tid.as_str(), shard_id.as_str()][..];
4203 :
4204 908 : fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
4205 908 : ([state.into()], matches!(state, TenantState::Broken { .. }))
4206 908 : }
4207 :
4208 454 : let mut tuple = inspect_state(&rx.borrow_and_update());
4209 454 :
4210 454 : let is_broken = tuple.1;
4211 454 : let mut counted_broken = if is_broken {
4212 : // add the id to the set right away, there should not be any updates on the channel
4213 : // after before tenant is removed, if ever
4214 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
4215 0 : true
4216 : } else {
4217 454 : false
4218 : };
4219 :
4220 : loop {
4221 908 : let labels = &tuple.0;
4222 908 : let current = TENANT_STATE_METRIC.with_label_values(labels);
4223 908 : current.inc();
4224 908 :
4225 908 : if rx.changed().await.is_err() {
4226 : // tenant has been dropped
4227 28 : current.dec();
4228 28 : drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
4229 28 : break;
4230 454 : }
4231 454 :
4232 454 : current.dec();
4233 454 : tuple = inspect_state(&rx.borrow_and_update());
4234 454 :
4235 454 : let is_broken = tuple.1;
4236 454 : if is_broken && !counted_broken {
4237 0 : counted_broken = true;
4238 0 : // insert the tenant_id (back) into the set while avoiding needless counter
4239 0 : // access
4240 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
4241 454 : }
4242 : }
4243 454 : });
4244 454 :
4245 454 : Tenant {
4246 454 : tenant_shard_id,
4247 454 : shard_identity,
4248 454 : generation: attached_conf.location.generation,
4249 454 : conf,
4250 454 : // using now here is good enough approximation to catch tenants with really long
4251 454 : // activation times.
4252 454 : constructed_at: Instant::now(),
4253 454 : timelines: Mutex::new(HashMap::new()),
4254 454 : timelines_creating: Mutex::new(HashSet::new()),
4255 454 : timelines_offloaded: Mutex::new(HashMap::new()),
4256 454 : tenant_manifest_upload: Default::default(),
4257 454 : gc_cs: tokio::sync::Mutex::new(()),
4258 454 : walredo_mgr,
4259 454 : remote_storage,
4260 454 : deletion_queue_client,
4261 454 : state,
4262 454 : cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
4263 454 : cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
4264 454 : eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
4265 454 : compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
4266 454 : format!("compaction-{tenant_shard_id}"),
4267 454 : 5,
4268 454 : // Compaction can be a very expensive operation, and might leak disk space. It also ought
4269 454 : // to be infallible, as long as remote storage is available. So if it repeatedly fails,
4270 454 : // use an extremely long backoff.
4271 454 : Some(Duration::from_secs(3600 * 24)),
4272 454 : )),
4273 454 : l0_compaction_trigger: Arc::new(Notify::new()),
4274 454 : scheduled_compaction_tasks: Mutex::new(Default::default()),
4275 454 : activate_now_sem: tokio::sync::Semaphore::new(0),
4276 454 : attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
4277 454 : cancel: CancellationToken::default(),
4278 454 : gate: Gate::default(),
4279 454 : pagestream_throttle: Arc::new(throttle::Throttle::new(
4280 454 : Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
4281 454 : )),
4282 454 : pagestream_throttle_metrics: Arc::new(
4283 454 : crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
4284 454 : ),
4285 454 : tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
4286 454 : ongoing_timeline_detach: std::sync::Mutex::default(),
4287 454 : gc_block: Default::default(),
4288 454 : l0_flush_global_state,
4289 454 : }
4290 454 : }
4291 :
4292 : /// Locate and load config
4293 0 : pub(super) fn load_tenant_config(
4294 0 : conf: &'static PageServerConf,
4295 0 : tenant_shard_id: &TenantShardId,
4296 0 : ) -> Result<LocationConf, LoadConfigError> {
4297 0 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
4298 0 :
4299 0 : info!("loading tenant configuration from {config_path}");
4300 :
4301 : // load and parse file
4302 0 : let config = fs::read_to_string(&config_path).map_err(|e| {
4303 0 : match e.kind() {
4304 : std::io::ErrorKind::NotFound => {
4305 : // The config should almost always exist for a tenant directory:
4306 : // - When attaching a tenant, the config is the first thing we write
4307 : // - When detaching a tenant, we atomically move the directory to a tmp location
4308 : // before deleting contents.
4309 : //
4310 : // The very rare edge case that can result in a missing config is if we crash during attach
4311 : // between creating directory and writing config. Callers should handle that as if the
4312 : // directory didn't exist.
4313 :
4314 0 : LoadConfigError::NotFound(config_path)
4315 : }
4316 : _ => {
4317 : // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
4318 : // that we cannot cleanly recover
4319 0 : crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
4320 : }
4321 : }
4322 0 : })?;
4323 :
4324 0 : Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
4325 0 : }
4326 :
4327 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
4328 : pub(super) async fn persist_tenant_config(
4329 : conf: &'static PageServerConf,
4330 : tenant_shard_id: &TenantShardId,
4331 : location_conf: &LocationConf,
4332 : ) -> std::io::Result<()> {
4333 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
4334 :
4335 : Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
4336 : }
4337 :
4338 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
4339 : pub(super) async fn persist_tenant_config_at(
4340 : tenant_shard_id: &TenantShardId,
4341 : config_path: &Utf8Path,
4342 : location_conf: &LocationConf,
4343 : ) -> std::io::Result<()> {
4344 : debug!("persisting tenantconf to {config_path}");
4345 :
4346 : let mut conf_content = r#"# This file contains a specific per-tenant's config.
4347 : # It is read in case of pageserver restart.
4348 : "#
4349 : .to_string();
4350 :
4351 0 : fail::fail_point!("tenant-config-before-write", |_| {
4352 0 : Err(std::io::Error::new(
4353 0 : std::io::ErrorKind::Other,
4354 0 : "tenant-config-before-write",
4355 0 : ))
4356 0 : });
4357 :
4358 : // Convert the config to a toml file.
4359 : conf_content +=
4360 : &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
4361 :
4362 : let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
4363 :
4364 : let conf_content = conf_content.into_bytes();
4365 : VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
4366 : }
4367 :
4368 : //
4369 : // How garbage collection works:
4370 : //
4371 : // +--bar------------->
4372 : // /
4373 : // +----+-----foo---------------->
4374 : // /
4375 : // ----main--+-------------------------->
4376 : // \
4377 : // +-----baz-------->
4378 : //
4379 : //
4380 : // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
4381 : // `gc_infos` are being refreshed
4382 : // 2. Scan collected timelines, and on each timeline, make note of the
4383 : // all the points where other timelines have been branched off.
4384 : // We will refrain from removing page versions at those LSNs.
4385 : // 3. For each timeline, scan all layer files on the timeline.
4386 : // Remove all files for which a newer file exists and which
4387 : // don't cover any branch point LSNs.
4388 : //
4389 : // TODO:
4390 : // - if a relation has a non-incremental persistent layer on a child branch, then we
4391 : // don't need to keep that in the parent anymore. But currently
4392 : // we do.
4393 8 : async fn gc_iteration_internal(
4394 8 : &self,
4395 8 : target_timeline_id: Option<TimelineId>,
4396 8 : horizon: u64,
4397 8 : pitr: Duration,
4398 8 : cancel: &CancellationToken,
4399 8 : ctx: &RequestContext,
4400 8 : ) -> Result<GcResult, GcError> {
4401 8 : let mut totals: GcResult = Default::default();
4402 8 : let now = Instant::now();
4403 :
4404 8 : let gc_timelines = self
4405 8 : .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
4406 8 : .await?;
4407 :
4408 8 : failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
4409 :
4410 : // If there is nothing to GC, we don't want any messages in the INFO log.
4411 8 : if !gc_timelines.is_empty() {
4412 8 : info!("{} timelines need GC", gc_timelines.len());
4413 : } else {
4414 0 : debug!("{} timelines need GC", gc_timelines.len());
4415 : }
4416 :
4417 : // Perform GC for each timeline.
4418 : //
4419 : // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
4420 : // branch creation task, which requires the GC lock. A GC iteration can run concurrently
4421 : // with branch creation.
4422 : //
4423 : // See comments in [`Tenant::branch_timeline`] for more information about why branch
4424 : // creation task can run concurrently with timeline's GC iteration.
4425 16 : for timeline in gc_timelines {
4426 8 : if cancel.is_cancelled() {
4427 : // We were requested to shut down. Stop and return with the progress we
4428 : // made.
4429 0 : break;
4430 8 : }
4431 8 : let result = match timeline.gc().await {
4432 : Err(GcError::TimelineCancelled) => {
4433 0 : if target_timeline_id.is_some() {
4434 : // If we were targetting this specific timeline, surface cancellation to caller
4435 0 : return Err(GcError::TimelineCancelled);
4436 : } else {
4437 : // A timeline may be shutting down independently of the tenant's lifecycle: we should
4438 : // skip past this and proceed to try GC on other timelines.
4439 0 : continue;
4440 : }
4441 : }
4442 8 : r => r?,
4443 : };
4444 8 : totals += result;
4445 : }
4446 :
4447 8 : totals.elapsed = now.elapsed();
4448 8 : Ok(totals)
4449 8 : }
4450 :
4451 : /// Refreshes the Timeline::gc_info for all timelines, returning the
4452 : /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
4453 : /// [`Tenant::get_gc_horizon`].
4454 : ///
4455 : /// This is usually executed as part of periodic gc, but can now be triggered more often.
4456 0 : pub(crate) async fn refresh_gc_info(
4457 0 : &self,
4458 0 : cancel: &CancellationToken,
4459 0 : ctx: &RequestContext,
4460 0 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
4461 0 : // since this method can now be called at different rates than the configured gc loop, it
4462 0 : // might be that these configuration values get applied faster than what it was previously,
4463 0 : // since these were only read from the gc task.
4464 0 : let horizon = self.get_gc_horizon();
4465 0 : let pitr = self.get_pitr_interval();
4466 0 :
4467 0 : // refresh all timelines
4468 0 : let target_timeline_id = None;
4469 0 :
4470 0 : self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
4471 0 : .await
4472 0 : }
4473 :
4474 : /// Populate all Timelines' `GcInfo` with information about their children. We do not set the
4475 : /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
4476 : ///
4477 : /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
4478 0 : fn initialize_gc_info(
4479 0 : &self,
4480 0 : timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
4481 0 : timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
4482 0 : restrict_to_timeline: Option<TimelineId>,
4483 0 : ) {
4484 0 : if restrict_to_timeline.is_none() {
4485 : // This function must be called before activation: after activation timeline create/delete operations
4486 : // might happen, and this function is not safe to run concurrently with those.
4487 0 : assert!(!self.is_active());
4488 0 : }
4489 :
4490 : // Scan all timelines. For each timeline, remember the timeline ID and
4491 : // the branch point where it was created.
4492 0 : let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
4493 0 : BTreeMap::new();
4494 0 : timelines.iter().for_each(|(timeline_id, timeline_entry)| {
4495 0 : if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
4496 0 : let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
4497 0 : ancestor_children.push((
4498 0 : timeline_entry.get_ancestor_lsn(),
4499 0 : *timeline_id,
4500 0 : MaybeOffloaded::No,
4501 0 : ));
4502 0 : }
4503 0 : });
4504 0 : timelines_offloaded
4505 0 : .iter()
4506 0 : .for_each(|(timeline_id, timeline_entry)| {
4507 0 : let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
4508 0 : return;
4509 : };
4510 0 : let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
4511 0 : return;
4512 : };
4513 0 : let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
4514 0 : ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
4515 0 : });
4516 0 :
4517 0 : // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
4518 0 : let horizon = self.get_gc_horizon();
4519 :
4520 : // Populate each timeline's GcInfo with information about its child branches
4521 0 : let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
4522 0 : itertools::Either::Left(timelines.get(&timeline_id).into_iter())
4523 : } else {
4524 0 : itertools::Either::Right(timelines.values())
4525 : };
4526 0 : for timeline in timelines_to_write {
4527 0 : let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
4528 0 : .remove(&timeline.timeline_id)
4529 0 : .unwrap_or_default();
4530 0 :
4531 0 : branchpoints.sort_by_key(|b| b.0);
4532 0 :
4533 0 : let mut target = timeline.gc_info.write().unwrap();
4534 0 :
4535 0 : target.retain_lsns = branchpoints;
4536 0 :
4537 0 : let space_cutoff = timeline
4538 0 : .get_last_record_lsn()
4539 0 : .checked_sub(horizon)
4540 0 : .unwrap_or(Lsn(0));
4541 0 :
4542 0 : target.cutoffs = GcCutoffs {
4543 0 : space: space_cutoff,
4544 0 : time: Lsn::INVALID,
4545 0 : };
4546 0 : }
4547 0 : }
4548 :
4549 8 : async fn refresh_gc_info_internal(
4550 8 : &self,
4551 8 : target_timeline_id: Option<TimelineId>,
4552 8 : horizon: u64,
4553 8 : pitr: Duration,
4554 8 : cancel: &CancellationToken,
4555 8 : ctx: &RequestContext,
4556 8 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
4557 8 : // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
4558 8 : // currently visible timelines.
4559 8 : let timelines = self
4560 8 : .timelines
4561 8 : .lock()
4562 8 : .unwrap()
4563 8 : .values()
4564 8 : .filter(|tl| match target_timeline_id.as_ref() {
4565 8 : Some(target) => &tl.timeline_id == target,
4566 0 : None => true,
4567 8 : })
4568 8 : .cloned()
4569 8 : .collect::<Vec<_>>();
4570 8 :
4571 8 : if target_timeline_id.is_some() && timelines.is_empty() {
4572 : // We were to act on a particular timeline and it wasn't found
4573 0 : return Err(GcError::TimelineNotFound);
4574 8 : }
4575 8 :
4576 8 : let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
4577 8 : HashMap::with_capacity(timelines.len());
4578 8 :
4579 8 : // Ensures all timelines use the same start time when computing the time cutoff.
4580 8 : let now_ts_for_pitr_calc = SystemTime::now();
4581 8 : for timeline in timelines.iter() {
4582 8 : let cutoff = timeline
4583 8 : .get_last_record_lsn()
4584 8 : .checked_sub(horizon)
4585 8 : .unwrap_or(Lsn(0));
4586 :
4587 8 : let cutoffs = timeline
4588 8 : .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
4589 8 : .await?;
4590 8 : let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
4591 8 : assert!(old.is_none());
4592 : }
4593 :
4594 8 : if !self.is_active() || self.cancel.is_cancelled() {
4595 0 : return Err(GcError::TenantCancelled);
4596 8 : }
4597 :
4598 : // grab mutex to prevent new timelines from being created here; avoid doing long operations
4599 : // because that will stall branch creation.
4600 8 : let gc_cs = self.gc_cs.lock().await;
4601 :
4602 : // Ok, we now know all the branch points.
4603 : // Update the GC information for each timeline.
4604 8 : let mut gc_timelines = Vec::with_capacity(timelines.len());
4605 16 : for timeline in timelines {
4606 : // We filtered the timeline list above
4607 8 : if let Some(target_timeline_id) = target_timeline_id {
4608 8 : assert_eq!(target_timeline_id, timeline.timeline_id);
4609 0 : }
4610 :
4611 : {
4612 8 : let mut target = timeline.gc_info.write().unwrap();
4613 8 :
4614 8 : // Cull any expired leases
4615 8 : let now = SystemTime::now();
4616 12 : target.leases.retain(|_, lease| !lease.is_expired(&now));
4617 8 :
4618 8 : timeline
4619 8 : .metrics
4620 8 : .valid_lsn_lease_count_gauge
4621 8 : .set(target.leases.len() as u64);
4622 :
4623 : // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
4624 8 : if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
4625 0 : if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
4626 0 : target.within_ancestor_pitr =
4627 0 : timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
4628 0 : }
4629 8 : }
4630 :
4631 : // Update metrics that depend on GC state
4632 8 : timeline
4633 8 : .metrics
4634 8 : .archival_size
4635 8 : .set(if target.within_ancestor_pitr {
4636 0 : timeline.metrics.current_logical_size_gauge.get()
4637 : } else {
4638 8 : 0
4639 : });
4640 8 : timeline.metrics.pitr_history_size.set(
4641 8 : timeline
4642 8 : .get_last_record_lsn()
4643 8 : .checked_sub(target.cutoffs.time)
4644 8 : .unwrap_or(Lsn(0))
4645 8 : .0,
4646 8 : );
4647 :
4648 : // Apply the cutoffs we found to the Timeline's GcInfo. Why might we _not_ have cutoffs for a timeline?
4649 : // - this timeline was created while we were finding cutoffs
4650 : // - lsn for timestamp search fails for this timeline repeatedly
4651 8 : if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
4652 8 : let original_cutoffs = target.cutoffs.clone();
4653 8 : // GC cutoffs should never go back
4654 8 : target.cutoffs = GcCutoffs {
4655 8 : space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
4656 8 : time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
4657 8 : }
4658 0 : }
4659 : }
4660 :
4661 8 : gc_timelines.push(timeline);
4662 : }
4663 8 : drop(gc_cs);
4664 8 : Ok(gc_timelines)
4665 8 : }
4666 :
4667 : /// A substitute for `branch_timeline` for use in unit tests.
4668 : /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
4669 : /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
4670 : /// timeline background tasks are launched, except the flush loop.
4671 : #[cfg(test)]
4672 464 : async fn branch_timeline_test(
4673 464 : self: &Arc<Self>,
4674 464 : src_timeline: &Arc<Timeline>,
4675 464 : dst_id: TimelineId,
4676 464 : ancestor_lsn: Option<Lsn>,
4677 464 : ctx: &RequestContext,
4678 464 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
4679 464 : let tl = self
4680 464 : .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
4681 464 : .await?
4682 456 : .into_timeline_for_test();
4683 456 : tl.set_state(TimelineState::Active);
4684 456 : Ok(tl)
4685 464 : }
4686 :
4687 : /// Helper for unit tests to branch a timeline with some pre-loaded states.
4688 : #[cfg(test)]
4689 : #[allow(clippy::too_many_arguments)]
4690 12 : pub async fn branch_timeline_test_with_layers(
4691 12 : self: &Arc<Self>,
4692 12 : src_timeline: &Arc<Timeline>,
4693 12 : dst_id: TimelineId,
4694 12 : ancestor_lsn: Option<Lsn>,
4695 12 : ctx: &RequestContext,
4696 12 : delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
4697 12 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
4698 12 : end_lsn: Lsn,
4699 12 : ) -> anyhow::Result<Arc<Timeline>> {
4700 : use checks::check_valid_layermap;
4701 : use itertools::Itertools;
4702 :
4703 12 : let tline = self
4704 12 : .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
4705 12 : .await?;
4706 12 : let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
4707 12 : ancestor_lsn
4708 : } else {
4709 0 : tline.get_last_record_lsn()
4710 : };
4711 12 : assert!(end_lsn >= ancestor_lsn);
4712 12 : tline.force_advance_lsn(end_lsn);
4713 24 : for deltas in delta_layer_desc {
4714 12 : tline
4715 12 : .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
4716 12 : .await?;
4717 : }
4718 20 : for (lsn, images) in image_layer_desc {
4719 8 : tline
4720 8 : .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
4721 8 : .await?;
4722 : }
4723 12 : let layer_names = tline
4724 12 : .layers
4725 12 : .read()
4726 12 : .await
4727 12 : .layer_map()
4728 12 : .unwrap()
4729 12 : .iter_historic_layers()
4730 20 : .map(|layer| layer.layer_name())
4731 12 : .collect_vec();
4732 12 : if let Some(err) = check_valid_layermap(&layer_names) {
4733 0 : bail!("invalid layermap: {err}");
4734 12 : }
4735 12 : Ok(tline)
4736 12 : }
4737 :
4738 : /// Branch an existing timeline.
4739 0 : async fn branch_timeline(
4740 0 : self: &Arc<Self>,
4741 0 : src_timeline: &Arc<Timeline>,
4742 0 : dst_id: TimelineId,
4743 0 : start_lsn: Option<Lsn>,
4744 0 : ctx: &RequestContext,
4745 0 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
4746 0 : self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
4747 0 : .await
4748 0 : }
4749 :
4750 464 : async fn branch_timeline_impl(
4751 464 : self: &Arc<Self>,
4752 464 : src_timeline: &Arc<Timeline>,
4753 464 : dst_id: TimelineId,
4754 464 : start_lsn: Option<Lsn>,
4755 464 : _ctx: &RequestContext,
4756 464 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
4757 464 : let src_id = src_timeline.timeline_id;
4758 :
4759 : // We will validate our ancestor LSN in this function. Acquire the GC lock so that
4760 : // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
4761 : // valid while we are creating the branch.
4762 464 : let _gc_cs = self.gc_cs.lock().await;
4763 :
4764 : // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
4765 464 : let start_lsn = start_lsn.unwrap_or_else(|| {
4766 4 : let lsn = src_timeline.get_last_record_lsn();
4767 4 : info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
4768 4 : lsn
4769 464 : });
4770 :
4771 : // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
4772 464 : let timeline_create_guard = match self
4773 464 : .start_creating_timeline(
4774 464 : dst_id,
4775 464 : CreateTimelineIdempotency::Branch {
4776 464 : ancestor_timeline_id: src_timeline.timeline_id,
4777 464 : ancestor_start_lsn: start_lsn,
4778 464 : },
4779 464 : )
4780 464 : .await?
4781 : {
4782 464 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
4783 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
4784 0 : return Ok(CreateTimelineResult::Idempotent(timeline));
4785 : }
4786 : };
4787 :
4788 : // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
4789 : // horizon on the source timeline
4790 : //
4791 : // We check it against both the planned GC cutoff stored in 'gc_info',
4792 : // and the 'latest_gc_cutoff' of the last GC that was performed. The
4793 : // planned GC cutoff in 'gc_info' is normally larger than
4794 : // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
4795 : // changed the GC settings for the tenant to make the PITR window
4796 : // larger, but some of the data was already removed by an earlier GC
4797 : // iteration.
4798 :
4799 : // check against last actual 'latest_gc_cutoff' first
4800 464 : let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
4801 464 : {
4802 464 : let gc_info = src_timeline.gc_info.read().unwrap();
4803 464 : let planned_cutoff = gc_info.min_cutoff();
4804 464 : if gc_info.lsn_covered_by_lease(start_lsn) {
4805 0 : tracing::info!(
4806 0 : "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
4807 0 : *applied_gc_cutoff_lsn
4808 : );
4809 : } else {
4810 464 : src_timeline
4811 464 : .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
4812 464 : .context(format!(
4813 464 : "invalid branch start lsn: less than latest GC cutoff {}",
4814 464 : *applied_gc_cutoff_lsn,
4815 464 : ))
4816 464 : .map_err(CreateTimelineError::AncestorLsn)?;
4817 :
4818 : // and then the planned GC cutoff
4819 456 : if start_lsn < planned_cutoff {
4820 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
4821 0 : "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
4822 0 : )));
4823 456 : }
4824 : }
4825 : }
4826 :
4827 : //
4828 : // The branch point is valid, and we are still holding the 'gc_cs' lock
4829 : // so that GC cannot advance the GC cutoff until we are finished.
4830 : // Proceed with the branch creation.
4831 : //
4832 :
4833 : // Determine prev-LSN for the new timeline. We can only determine it if
4834 : // the timeline was branched at the current end of the source timeline.
4835 : let RecordLsn {
4836 456 : last: src_last,
4837 456 : prev: src_prev,
4838 456 : } = src_timeline.get_last_record_rlsn();
4839 456 : let dst_prev = if src_last == start_lsn {
4840 432 : Some(src_prev)
4841 : } else {
4842 24 : None
4843 : };
4844 :
4845 : // Create the metadata file, noting the ancestor of the new timeline.
4846 : // There is initially no data in it, but all the read-calls know to look
4847 : // into the ancestor.
4848 456 : let metadata = TimelineMetadata::new(
4849 456 : start_lsn,
4850 456 : dst_prev,
4851 456 : Some(src_id),
4852 456 : start_lsn,
4853 456 : *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
4854 456 : src_timeline.initdb_lsn,
4855 456 : src_timeline.pg_version,
4856 456 : );
4857 :
4858 456 : let uninitialized_timeline = self
4859 456 : .prepare_new_timeline(
4860 456 : dst_id,
4861 456 : &metadata,
4862 456 : timeline_create_guard,
4863 456 : start_lsn + 1,
4864 456 : Some(Arc::clone(src_timeline)),
4865 456 : )
4866 456 : .await?;
4867 :
4868 456 : let new_timeline = uninitialized_timeline.finish_creation().await?;
4869 :
4870 : // Root timeline gets its layers during creation and uploads them along with the metadata.
4871 : // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
4872 : // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
4873 : // could get incorrect information and remove more layers, than needed.
4874 : // See also https://github.com/neondatabase/neon/issues/3865
4875 456 : new_timeline
4876 456 : .remote_client
4877 456 : .schedule_index_upload_for_full_metadata_update(&metadata)
4878 456 : .context("branch initial metadata upload")?;
4879 :
4880 : // Callers are responsible to wait for uploads to complete and for activating the timeline.
4881 :
4882 456 : Ok(CreateTimelineResult::Created(new_timeline))
4883 464 : }
4884 :
4885 : /// For unit tests, make this visible so that other modules can directly create timelines
4886 : #[cfg(test)]
4887 : #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
4888 : pub(crate) async fn bootstrap_timeline_test(
4889 : self: &Arc<Self>,
4890 : timeline_id: TimelineId,
4891 : pg_version: u32,
4892 : load_existing_initdb: Option<TimelineId>,
4893 : ctx: &RequestContext,
4894 : ) -> anyhow::Result<Arc<Timeline>> {
4895 : self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
4896 : .await
4897 : .map_err(anyhow::Error::new)
4898 4 : .map(|r| r.into_timeline_for_test())
4899 : }
4900 :
4901 : /// Get exclusive access to the timeline ID for creation.
4902 : ///
4903 : /// Timeline-creating code paths must use this function before making changes
4904 : /// to in-memory or persistent state.
4905 : ///
4906 : /// The `state` parameter is a description of the timeline creation operation
4907 : /// we intend to perform.
4908 : /// If the timeline was already created in the meantime, we check whether this
4909 : /// request conflicts or is idempotent , based on `state`.
4910 906 : async fn start_creating_timeline(
4911 906 : self: &Arc<Self>,
4912 906 : new_timeline_id: TimelineId,
4913 906 : idempotency: CreateTimelineIdempotency,
4914 906 : ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
4915 906 : let allow_offloaded = false;
4916 906 : match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
4917 902 : Ok(create_guard) => {
4918 902 : pausable_failpoint!("timeline-creation-after-uninit");
4919 902 : Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
4920 : }
4921 0 : Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
4922 : Err(TimelineExclusionError::AlreadyCreating) => {
4923 : // Creation is in progress, we cannot create it again, and we cannot
4924 : // check if this request matches the existing one, so caller must try
4925 : // again later.
4926 0 : Err(CreateTimelineError::AlreadyCreating)
4927 : }
4928 0 : Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
4929 : Err(TimelineExclusionError::AlreadyExists {
4930 0 : existing: TimelineOrOffloaded::Offloaded(_existing),
4931 0 : ..
4932 0 : }) => {
4933 0 : info!("timeline already exists but is offloaded");
4934 0 : Err(CreateTimelineError::Conflict)
4935 : }
4936 : Err(TimelineExclusionError::AlreadyExists {
4937 4 : existing: TimelineOrOffloaded::Timeline(existing),
4938 4 : arg,
4939 4 : }) => {
4940 4 : {
4941 4 : let existing = &existing.create_idempotency;
4942 4 : let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
4943 4 : debug!("timeline already exists");
4944 :
4945 4 : match (existing, &arg) {
4946 : // FailWithConflict => no idempotency check
4947 : (CreateTimelineIdempotency::FailWithConflict, _)
4948 : | (_, CreateTimelineIdempotency::FailWithConflict) => {
4949 4 : warn!("timeline already exists, failing request");
4950 4 : return Err(CreateTimelineError::Conflict);
4951 : }
4952 : // Idempotent <=> CreateTimelineIdempotency is identical
4953 0 : (x, y) if x == y => {
4954 0 : info!(
4955 0 : "timeline already exists and idempotency matches, succeeding request"
4956 : );
4957 : // fallthrough
4958 : }
4959 : (_, _) => {
4960 0 : warn!("idempotency conflict, failing request");
4961 0 : return Err(CreateTimelineError::Conflict);
4962 : }
4963 : }
4964 : }
4965 :
4966 0 : Ok(StartCreatingTimelineResult::Idempotent(existing))
4967 : }
4968 : }
4969 906 : }
4970 :
4971 0 : async fn upload_initdb(
4972 0 : &self,
4973 0 : timelines_path: &Utf8PathBuf,
4974 0 : pgdata_path: &Utf8PathBuf,
4975 0 : timeline_id: &TimelineId,
4976 0 : ) -> anyhow::Result<()> {
4977 0 : let temp_path = timelines_path.join(format!(
4978 0 : "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
4979 0 : ));
4980 0 :
4981 0 : scopeguard::defer! {
4982 0 : if let Err(e) = fs::remove_file(&temp_path) {
4983 0 : error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
4984 0 : }
4985 0 : }
4986 :
4987 0 : let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
4988 : const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
4989 0 : if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
4990 0 : warn!(
4991 0 : "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
4992 : );
4993 0 : }
4994 :
4995 0 : pausable_failpoint!("before-initdb-upload");
4996 :
4997 0 : backoff::retry(
4998 0 : || async {
4999 0 : self::remote_timeline_client::upload_initdb_dir(
5000 0 : &self.remote_storage,
5001 0 : &self.tenant_shard_id.tenant_id,
5002 0 : timeline_id,
5003 0 : pgdata_zstd.try_clone().await?,
5004 0 : tar_zst_size,
5005 0 : &self.cancel,
5006 0 : )
5007 0 : .await
5008 0 : },
5009 0 : |_| false,
5010 0 : 3,
5011 0 : u32::MAX,
5012 0 : "persist_initdb_tar_zst",
5013 0 : &self.cancel,
5014 0 : )
5015 0 : .await
5016 0 : .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
5017 0 : .and_then(|x| x)
5018 0 : }
5019 :
5020 : /// - run initdb to init temporary instance and get bootstrap data
5021 : /// - after initialization completes, tar up the temp dir and upload it to S3.
5022 4 : async fn bootstrap_timeline(
5023 4 : self: &Arc<Self>,
5024 4 : timeline_id: TimelineId,
5025 4 : pg_version: u32,
5026 4 : load_existing_initdb: Option<TimelineId>,
5027 4 : ctx: &RequestContext,
5028 4 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
5029 4 : let timeline_create_guard = match self
5030 4 : .start_creating_timeline(
5031 4 : timeline_id,
5032 4 : CreateTimelineIdempotency::Bootstrap { pg_version },
5033 4 : )
5034 4 : .await?
5035 : {
5036 4 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
5037 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
5038 0 : return Ok(CreateTimelineResult::Idempotent(timeline));
5039 : }
5040 : };
5041 :
5042 : // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
5043 : // temporary directory for basebackup files for the given timeline.
5044 :
5045 4 : let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
5046 4 : let pgdata_path = path_with_suffix_extension(
5047 4 : timelines_path.join(format!("basebackup-{timeline_id}")),
5048 4 : TEMP_FILE_SUFFIX,
5049 4 : );
5050 4 :
5051 4 : // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
5052 4 : // we won't race with other creations or existent timelines with the same path.
5053 4 : if pgdata_path.exists() {
5054 0 : fs::remove_dir_all(&pgdata_path).with_context(|| {
5055 0 : format!("Failed to remove already existing initdb directory: {pgdata_path}")
5056 0 : })?;
5057 4 : }
5058 :
5059 : // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
5060 4 : let pgdata_path_deferred = pgdata_path.clone();
5061 4 : scopeguard::defer! {
5062 4 : if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred) {
5063 4 : // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
5064 4 : error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
5065 4 : }
5066 4 : }
5067 4 : if let Some(existing_initdb_timeline_id) = load_existing_initdb {
5068 4 : if existing_initdb_timeline_id != timeline_id {
5069 0 : let source_path = &remote_initdb_archive_path(
5070 0 : &self.tenant_shard_id.tenant_id,
5071 0 : &existing_initdb_timeline_id,
5072 0 : );
5073 0 : let dest_path =
5074 0 : &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
5075 0 :
5076 0 : // if this fails, it will get retried by retried control plane requests
5077 0 : self.remote_storage
5078 0 : .copy_object(source_path, dest_path, &self.cancel)
5079 0 : .await
5080 0 : .context("copy initdb tar")?;
5081 4 : }
5082 4 : let (initdb_tar_zst_path, initdb_tar_zst) =
5083 4 : self::remote_timeline_client::download_initdb_tar_zst(
5084 4 : self.conf,
5085 4 : &self.remote_storage,
5086 4 : &self.tenant_shard_id,
5087 4 : &existing_initdb_timeline_id,
5088 4 : &self.cancel,
5089 4 : )
5090 4 : .await
5091 4 : .context("download initdb tar")?;
5092 :
5093 4 : scopeguard::defer! {
5094 4 : if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
5095 4 : error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
5096 4 : }
5097 4 : }
5098 4 :
5099 4 : let buf_read =
5100 4 : BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
5101 4 : extract_zst_tarball(&pgdata_path, buf_read)
5102 4 : .await
5103 4 : .context("extract initdb tar")?;
5104 : } else {
5105 : // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
5106 0 : run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
5107 0 : .await
5108 0 : .context("run initdb")?;
5109 :
5110 : // Upload the created data dir to S3
5111 0 : if self.tenant_shard_id().is_shard_zero() {
5112 0 : self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
5113 0 : .await?;
5114 0 : }
5115 : }
5116 4 : let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
5117 4 :
5118 4 : // Import the contents of the data directory at the initial checkpoint
5119 4 : // LSN, and any WAL after that.
5120 4 : // Initdb lsn will be equal to last_record_lsn which will be set after import.
5121 4 : // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
5122 4 : let new_metadata = TimelineMetadata::new(
5123 4 : Lsn(0),
5124 4 : None,
5125 4 : None,
5126 4 : Lsn(0),
5127 4 : pgdata_lsn,
5128 4 : pgdata_lsn,
5129 4 : pg_version,
5130 4 : );
5131 4 : let mut raw_timeline = self
5132 4 : .prepare_new_timeline(
5133 4 : timeline_id,
5134 4 : &new_metadata,
5135 4 : timeline_create_guard,
5136 4 : pgdata_lsn,
5137 4 : None,
5138 4 : )
5139 4 : .await?;
5140 :
5141 4 : let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
5142 4 : raw_timeline
5143 4 : .write(|unfinished_timeline| async move {
5144 4 : import_datadir::import_timeline_from_postgres_datadir(
5145 4 : &unfinished_timeline,
5146 4 : &pgdata_path,
5147 4 : pgdata_lsn,
5148 4 : ctx,
5149 4 : )
5150 4 : .await
5151 4 : .with_context(|| {
5152 0 : format!(
5153 0 : "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
5154 0 : )
5155 4 : })?;
5156 :
5157 4 : fail::fail_point!("before-checkpoint-new-timeline", |_| {
5158 0 : Err(CreateTimelineError::Other(anyhow::anyhow!(
5159 0 : "failpoint before-checkpoint-new-timeline"
5160 0 : )))
5161 4 : });
5162 :
5163 4 : Ok(())
5164 8 : })
5165 4 : .await?;
5166 :
5167 : // All done!
5168 4 : let timeline = raw_timeline.finish_creation().await?;
5169 :
5170 : // Callers are responsible to wait for uploads to complete and for activating the timeline.
5171 :
5172 4 : Ok(CreateTimelineResult::Created(timeline))
5173 4 : }
5174 :
5175 894 : fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
5176 894 : RemoteTimelineClient::new(
5177 894 : self.remote_storage.clone(),
5178 894 : self.deletion_queue_client.clone(),
5179 894 : self.conf,
5180 894 : self.tenant_shard_id,
5181 894 : timeline_id,
5182 894 : self.generation,
5183 894 : &self.tenant_conf.load().location,
5184 894 : )
5185 894 : }
5186 :
5187 : /// Builds required resources for a new timeline.
5188 894 : fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
5189 894 : let remote_client = self.build_timeline_remote_client(timeline_id);
5190 894 : self.get_timeline_resources_for(remote_client)
5191 894 : }
5192 :
5193 : /// Builds timeline resources for the given remote client.
5194 906 : fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
5195 906 : TimelineResources {
5196 906 : remote_client,
5197 906 : pagestream_throttle: self.pagestream_throttle.clone(),
5198 906 : pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
5199 906 : l0_compaction_trigger: self.l0_compaction_trigger.clone(),
5200 906 : l0_flush_global_state: self.l0_flush_global_state.clone(),
5201 906 : }
5202 906 : }
5203 :
5204 : /// Creates intermediate timeline structure and its files.
5205 : ///
5206 : /// An empty layer map is initialized, and new data and WAL can be imported starting
5207 : /// at 'disk_consistent_lsn'. After any initial data has been imported, call
5208 : /// `finish_creation` to insert the Timeline into the timelines map.
5209 894 : async fn prepare_new_timeline<'a>(
5210 894 : &'a self,
5211 894 : new_timeline_id: TimelineId,
5212 894 : new_metadata: &TimelineMetadata,
5213 894 : create_guard: TimelineCreateGuard,
5214 894 : start_lsn: Lsn,
5215 894 : ancestor: Option<Arc<Timeline>>,
5216 894 : ) -> anyhow::Result<UninitializedTimeline<'a>> {
5217 894 : let tenant_shard_id = self.tenant_shard_id;
5218 894 :
5219 894 : let resources = self.build_timeline_resources(new_timeline_id);
5220 894 : resources
5221 894 : .remote_client
5222 894 : .init_upload_queue_for_empty_remote(new_metadata)?;
5223 :
5224 894 : let timeline_struct = self
5225 894 : .create_timeline_struct(
5226 894 : new_timeline_id,
5227 894 : new_metadata,
5228 894 : None,
5229 894 : ancestor,
5230 894 : resources,
5231 894 : CreateTimelineCause::Load,
5232 894 : create_guard.idempotency.clone(),
5233 894 : None,
5234 894 : )
5235 894 : .context("Failed to create timeline data structure")?;
5236 :
5237 894 : timeline_struct.init_empty_layer_map(start_lsn);
5238 :
5239 894 : if let Err(e) = self
5240 894 : .create_timeline_files(&create_guard.timeline_path)
5241 894 : .await
5242 : {
5243 0 : error!(
5244 0 : "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
5245 : );
5246 0 : cleanup_timeline_directory(create_guard);
5247 0 : return Err(e);
5248 894 : }
5249 894 :
5250 894 : debug!(
5251 0 : "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
5252 : );
5253 :
5254 894 : Ok(UninitializedTimeline::new(
5255 894 : self,
5256 894 : new_timeline_id,
5257 894 : Some((timeline_struct, create_guard)),
5258 894 : ))
5259 894 : }
5260 :
5261 894 : async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
5262 894 : crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
5263 :
5264 894 : fail::fail_point!("after-timeline-dir-creation", |_| {
5265 0 : anyhow::bail!("failpoint after-timeline-dir-creation");
5266 894 : });
5267 :
5268 894 : Ok(())
5269 894 : }
5270 :
5271 : /// Get a guard that provides exclusive access to the timeline directory, preventing
5272 : /// concurrent attempts to create the same timeline.
5273 : ///
5274 : /// The `allow_offloaded` parameter controls whether to tolerate the existence of
5275 : /// offloaded timelines or not.
5276 906 : fn create_timeline_create_guard(
5277 906 : self: &Arc<Self>,
5278 906 : timeline_id: TimelineId,
5279 906 : idempotency: CreateTimelineIdempotency,
5280 906 : allow_offloaded: bool,
5281 906 : ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
5282 906 : let tenant_shard_id = self.tenant_shard_id;
5283 906 :
5284 906 : let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
5285 :
5286 906 : let create_guard = TimelineCreateGuard::new(
5287 906 : self,
5288 906 : timeline_id,
5289 906 : timeline_path.clone(),
5290 906 : idempotency,
5291 906 : allow_offloaded,
5292 906 : )?;
5293 :
5294 : // At this stage, we have got exclusive access to in-memory state for this timeline ID
5295 : // for creation.
5296 : // A timeline directory should never exist on disk already:
5297 : // - a previous failed creation would have cleaned up after itself
5298 : // - a pageserver restart would clean up timeline directories that don't have valid remote state
5299 : //
5300 : // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
5301 : // this error may indicate a bug in cleanup on failed creations.
5302 902 : if timeline_path.exists() {
5303 0 : return Err(TimelineExclusionError::Other(anyhow::anyhow!(
5304 0 : "Timeline directory already exists! This is a bug."
5305 0 : )));
5306 902 : }
5307 902 :
5308 902 : Ok(create_guard)
5309 906 : }
5310 :
5311 : /// Gathers inputs from all of the timelines to produce a sizing model input.
5312 : ///
5313 : /// Future is cancellation safe. Only one calculation can be running at once per tenant.
5314 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5315 : pub async fn gather_size_inputs(
5316 : &self,
5317 : // `max_retention_period` overrides the cutoff that is used to calculate the size
5318 : // (only if it is shorter than the real cutoff).
5319 : max_retention_period: Option<u64>,
5320 : cause: LogicalSizeCalculationCause,
5321 : cancel: &CancellationToken,
5322 : ctx: &RequestContext,
5323 : ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
5324 : let logical_sizes_at_once = self
5325 : .conf
5326 : .concurrent_tenant_size_logical_size_queries
5327 : .inner();
5328 :
5329 : // TODO: Having a single mutex block concurrent reads is not great for performance.
5330 : //
5331 : // But the only case where we need to run multiple of these at once is when we
5332 : // request a size for a tenant manually via API, while another background calculation
5333 : // is in progress (which is not a common case).
5334 : //
5335 : // See more for on the issue #2748 condenced out of the initial PR review.
5336 : let mut shared_cache = tokio::select! {
5337 : locked = self.cached_logical_sizes.lock() => locked,
5338 : _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
5339 : _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
5340 : };
5341 :
5342 : size::gather_inputs(
5343 : self,
5344 : logical_sizes_at_once,
5345 : max_retention_period,
5346 : &mut shared_cache,
5347 : cause,
5348 : cancel,
5349 : ctx,
5350 : )
5351 : .await
5352 : }
5353 :
5354 : /// Calculate synthetic tenant size and cache the result.
5355 : /// This is periodically called by background worker.
5356 : /// result is cached in tenant struct
5357 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5358 : pub async fn calculate_synthetic_size(
5359 : &self,
5360 : cause: LogicalSizeCalculationCause,
5361 : cancel: &CancellationToken,
5362 : ctx: &RequestContext,
5363 : ) -> Result<u64, size::CalculateSyntheticSizeError> {
5364 : let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
5365 :
5366 : let size = inputs.calculate();
5367 :
5368 : self.set_cached_synthetic_size(size);
5369 :
5370 : Ok(size)
5371 : }
5372 :
5373 : /// Cache given synthetic size and update the metric value
5374 0 : pub fn set_cached_synthetic_size(&self, size: u64) {
5375 0 : self.cached_synthetic_tenant_size
5376 0 : .store(size, Ordering::Relaxed);
5377 0 :
5378 0 : // Only shard zero should be calculating synthetic sizes
5379 0 : debug_assert!(self.shard_identity.is_shard_zero());
5380 :
5381 0 : TENANT_SYNTHETIC_SIZE_METRIC
5382 0 : .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
5383 0 : .unwrap()
5384 0 : .set(size);
5385 0 : }
5386 :
5387 0 : pub fn cached_synthetic_size(&self) -> u64 {
5388 0 : self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
5389 0 : }
5390 :
5391 : /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
5392 : ///
5393 : /// This function can take a long time: callers should wrap it in a timeout if calling
5394 : /// from an external API handler.
5395 : ///
5396 : /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
5397 : /// still bounded by tenant/timeline shutdown.
5398 : #[tracing::instrument(skip_all)]
5399 : pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
5400 : let timelines = self.timelines.lock().unwrap().clone();
5401 :
5402 0 : async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
5403 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
5404 0 : timeline.freeze_and_flush().await?;
5405 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
5406 0 : timeline.remote_client.wait_completion().await?;
5407 :
5408 0 : Ok(())
5409 0 : }
5410 :
5411 : // We do not use a JoinSet for these tasks, because we don't want them to be
5412 : // aborted when this function's future is cancelled: they should stay alive
5413 : // holding their GateGuard until they complete, to ensure their I/Os complete
5414 : // before Timeline shutdown completes.
5415 : let mut results = FuturesUnordered::new();
5416 :
5417 : for (_timeline_id, timeline) in timelines {
5418 : // Run each timeline's flush in a task holding the timeline's gate: this
5419 : // means that if this function's future is cancelled, the Timeline shutdown
5420 : // will still wait for any I/O in here to complete.
5421 : let Ok(gate) = timeline.gate.enter() else {
5422 : continue;
5423 : };
5424 0 : let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
5425 : results.push(jh);
5426 : }
5427 :
5428 : while let Some(r) = results.next().await {
5429 : if let Err(e) = r {
5430 : if !e.is_cancelled() && !e.is_panic() {
5431 : tracing::error!("unexpected join error: {e:?}");
5432 : }
5433 : }
5434 : }
5435 :
5436 : // The flushes we did above were just writes, but the Tenant might have had
5437 : // pending deletions as well from recent compaction/gc: we want to flush those
5438 : // as well. This requires flushing the global delete queue. This is cheap
5439 : // because it's typically a no-op.
5440 : match self.deletion_queue_client.flush_execute().await {
5441 : Ok(_) => {}
5442 : Err(DeletionQueueError::ShuttingDown) => {}
5443 : }
5444 :
5445 : Ok(())
5446 : }
5447 :
5448 0 : pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
5449 0 : self.tenant_conf.load().tenant_conf.clone()
5450 0 : }
5451 :
5452 : /// How much local storage would this tenant like to have? It can cope with
5453 : /// less than this (via eviction and on-demand downloads), but this function enables
5454 : /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
5455 : /// by keeping important things on local disk.
5456 : ///
5457 : /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
5458 : /// than they report here, due to layer eviction. Tenants with many active branches may
5459 : /// actually use more than they report here.
5460 0 : pub(crate) fn local_storage_wanted(&self) -> u64 {
5461 0 : let timelines = self.timelines.lock().unwrap();
5462 0 :
5463 0 : // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum. This
5464 0 : // reflects the observation that on tenants with multiple large branches, typically only one
5465 0 : // of them is used actively enough to occupy space on disk.
5466 0 : timelines
5467 0 : .values()
5468 0 : .map(|t| t.metrics.visible_physical_size_gauge.get())
5469 0 : .max()
5470 0 : .unwrap_or(0)
5471 0 : }
5472 :
5473 : /// Serialize and write the latest TenantManifest to remote storage.
5474 4 : pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
5475 : // Only one manifest write may be done at at time, and the contents of the manifest
5476 : // must be loaded while holding this lock. This makes it safe to call this function
5477 : // from anywhere without worrying about colliding updates.
5478 4 : let mut guard = tokio::select! {
5479 4 : g = self.tenant_manifest_upload.lock() => {
5480 4 : g
5481 : },
5482 4 : _ = self.cancel.cancelled() => {
5483 0 : return Err(TenantManifestError::Cancelled);
5484 : }
5485 : };
5486 :
5487 4 : let manifest = self.build_tenant_manifest();
5488 4 : if Some(&manifest) == (*guard).as_ref() {
5489 : // Optimisation: skip uploads that don't change anything.
5490 0 : return Ok(());
5491 4 : }
5492 4 :
5493 4 : // Remote storage does no retries internally, so wrap it
5494 4 : match backoff::retry(
5495 4 : || async {
5496 4 : upload_tenant_manifest(
5497 4 : &self.remote_storage,
5498 4 : &self.tenant_shard_id,
5499 4 : self.generation,
5500 4 : &manifest,
5501 4 : &self.cancel,
5502 4 : )
5503 4 : .await
5504 8 : },
5505 4 : |_e| self.cancel.is_cancelled(),
5506 4 : FAILED_UPLOAD_WARN_THRESHOLD,
5507 4 : FAILED_REMOTE_OP_RETRIES,
5508 4 : "uploading tenant manifest",
5509 4 : &self.cancel,
5510 4 : )
5511 4 : .await
5512 : {
5513 0 : None => Err(TenantManifestError::Cancelled),
5514 0 : Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
5515 0 : Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
5516 : Some(Ok(_)) => {
5517 : // Store the successfully uploaded manifest, so that future callers can avoid
5518 : // re-uploading the same thing.
5519 4 : *guard = Some(manifest);
5520 4 :
5521 4 : Ok(())
5522 : }
5523 : }
5524 4 : }
5525 : }
5526 :
5527 : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
5528 : /// to get bootstrap data for timeline initialization.
5529 0 : async fn run_initdb(
5530 0 : conf: &'static PageServerConf,
5531 0 : initdb_target_dir: &Utf8Path,
5532 0 : pg_version: u32,
5533 0 : cancel: &CancellationToken,
5534 0 : ) -> Result<(), InitdbError> {
5535 0 : let initdb_bin_path = conf
5536 0 : .pg_bin_dir(pg_version)
5537 0 : .map_err(InitdbError::Other)?
5538 0 : .join("initdb");
5539 0 : let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
5540 0 : info!(
5541 0 : "running {} in {}, libdir: {}",
5542 : initdb_bin_path, initdb_target_dir, initdb_lib_dir,
5543 : );
5544 :
5545 0 : let _permit = {
5546 0 : let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
5547 0 : INIT_DB_SEMAPHORE.acquire().await
5548 : };
5549 :
5550 0 : CONCURRENT_INITDBS.inc();
5551 0 : scopeguard::defer! {
5552 0 : CONCURRENT_INITDBS.dec();
5553 0 : }
5554 0 :
5555 0 : let _timer = INITDB_RUN_TIME.start_timer();
5556 0 : let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
5557 0 : superuser: &conf.superuser,
5558 0 : locale: &conf.locale,
5559 0 : initdb_bin: &initdb_bin_path,
5560 0 : pg_version,
5561 0 : library_search_path: &initdb_lib_dir,
5562 0 : pgdata: initdb_target_dir,
5563 0 : })
5564 0 : .await
5565 0 : .map_err(InitdbError::Inner);
5566 0 :
5567 0 : // This isn't true cancellation support, see above. Still return an error to
5568 0 : // excercise the cancellation code path.
5569 0 : if cancel.is_cancelled() {
5570 0 : return Err(InitdbError::Cancelled);
5571 0 : }
5572 0 :
5573 0 : res
5574 0 : }
5575 :
5576 : /// Dump contents of a layer file to stdout.
5577 0 : pub async fn dump_layerfile_from_path(
5578 0 : path: &Utf8Path,
5579 0 : verbose: bool,
5580 0 : ctx: &RequestContext,
5581 0 : ) -> anyhow::Result<()> {
5582 : use std::os::unix::fs::FileExt;
5583 :
5584 : // All layer files start with a two-byte "magic" value, to identify the kind of
5585 : // file.
5586 0 : let file = File::open(path)?;
5587 0 : let mut header_buf = [0u8; 2];
5588 0 : file.read_exact_at(&mut header_buf, 0)?;
5589 :
5590 0 : match u16::from_be_bytes(header_buf) {
5591 : crate::IMAGE_FILE_MAGIC => {
5592 0 : ImageLayer::new_for_path(path, file)?
5593 0 : .dump(verbose, ctx)
5594 0 : .await?
5595 : }
5596 : crate::DELTA_FILE_MAGIC => {
5597 0 : DeltaLayer::new_for_path(path, file)?
5598 0 : .dump(verbose, ctx)
5599 0 : .await?
5600 : }
5601 0 : magic => bail!("unrecognized magic identifier: {:?}", magic),
5602 : }
5603 :
5604 0 : Ok(())
5605 0 : }
5606 :
5607 : #[cfg(test)]
5608 : pub(crate) mod harness {
5609 : use bytes::{Bytes, BytesMut};
5610 : use hex_literal::hex;
5611 : use once_cell::sync::OnceCell;
5612 : use pageserver_api::key::Key;
5613 : use pageserver_api::models::ShardParameters;
5614 : use pageserver_api::record::NeonWalRecord;
5615 : use pageserver_api::shard::ShardIndex;
5616 : use utils::id::TenantId;
5617 : use utils::logging;
5618 :
5619 : use super::*;
5620 : use crate::deletion_queue::mock::MockDeletionQueue;
5621 : use crate::l0_flush::L0FlushConfig;
5622 : use crate::walredo::apply_neon;
5623 :
5624 : pub const TIMELINE_ID: TimelineId =
5625 : TimelineId::from_array(hex!("11223344556677881122334455667788"));
5626 : pub const NEW_TIMELINE_ID: TimelineId =
5627 : TimelineId::from_array(hex!("AA223344556677881122334455667788"));
5628 :
5629 : /// Convenience function to create a page image with given string as the only content
5630 10057502 : pub fn test_img(s: &str) -> Bytes {
5631 10057502 : let mut buf = BytesMut::new();
5632 10057502 : buf.extend_from_slice(s.as_bytes());
5633 10057502 : buf.resize(64, 0);
5634 10057502 :
5635 10057502 : buf.freeze()
5636 10057502 : }
5637 :
5638 : impl From<TenantConf> for TenantConfOpt {
5639 454 : fn from(tenant_conf: TenantConf) -> Self {
5640 454 : Self {
5641 454 : checkpoint_distance: Some(tenant_conf.checkpoint_distance),
5642 454 : checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
5643 454 : compaction_target_size: Some(tenant_conf.compaction_target_size),
5644 454 : compaction_period: Some(tenant_conf.compaction_period),
5645 454 : compaction_threshold: Some(tenant_conf.compaction_threshold),
5646 454 : compaction_upper_limit: Some(tenant_conf.compaction_upper_limit),
5647 454 : compaction_algorithm: Some(tenant_conf.compaction_algorithm),
5648 454 : compaction_l0_first: Some(tenant_conf.compaction_l0_first),
5649 454 : compaction_l0_semaphore: Some(tenant_conf.compaction_l0_semaphore),
5650 454 : l0_flush_delay_threshold: tenant_conf.l0_flush_delay_threshold,
5651 454 : l0_flush_stall_threshold: tenant_conf.l0_flush_stall_threshold,
5652 454 : l0_flush_wait_upload: Some(tenant_conf.l0_flush_wait_upload),
5653 454 : gc_horizon: Some(tenant_conf.gc_horizon),
5654 454 : gc_period: Some(tenant_conf.gc_period),
5655 454 : image_creation_threshold: Some(tenant_conf.image_creation_threshold),
5656 454 : pitr_interval: Some(tenant_conf.pitr_interval),
5657 454 : walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
5658 454 : lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
5659 454 : max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
5660 454 : eviction_policy: Some(tenant_conf.eviction_policy),
5661 454 : min_resident_size_override: tenant_conf.min_resident_size_override,
5662 454 : evictions_low_residence_duration_metric_threshold: Some(
5663 454 : tenant_conf.evictions_low_residence_duration_metric_threshold,
5664 454 : ),
5665 454 : heatmap_period: Some(tenant_conf.heatmap_period),
5666 454 : lazy_slru_download: Some(tenant_conf.lazy_slru_download),
5667 454 : timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
5668 454 : image_layer_creation_check_threshold: Some(
5669 454 : tenant_conf.image_layer_creation_check_threshold,
5670 454 : ),
5671 454 : image_creation_preempt_threshold: Some(
5672 454 : tenant_conf.image_creation_preempt_threshold,
5673 454 : ),
5674 454 : lsn_lease_length: Some(tenant_conf.lsn_lease_length),
5675 454 : lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
5676 454 : timeline_offloading: Some(tenant_conf.timeline_offloading),
5677 454 : wal_receiver_protocol_override: tenant_conf.wal_receiver_protocol_override,
5678 454 : rel_size_v2_enabled: Some(tenant_conf.rel_size_v2_enabled),
5679 454 : gc_compaction_enabled: Some(tenant_conf.gc_compaction_enabled),
5680 454 : gc_compaction_initial_threshold_kb: Some(
5681 454 : tenant_conf.gc_compaction_initial_threshold_kb,
5682 454 : ),
5683 454 : gc_compaction_ratio_percent: Some(tenant_conf.gc_compaction_ratio_percent),
5684 454 : }
5685 454 : }
5686 : }
5687 :
5688 : pub struct TenantHarness {
5689 : pub conf: &'static PageServerConf,
5690 : pub tenant_conf: TenantConf,
5691 : pub tenant_shard_id: TenantShardId,
5692 : pub generation: Generation,
5693 : pub shard: ShardIndex,
5694 : pub remote_storage: GenericRemoteStorage,
5695 : pub remote_fs_dir: Utf8PathBuf,
5696 : pub deletion_queue: MockDeletionQueue,
5697 : }
5698 :
5699 : static LOG_HANDLE: OnceCell<()> = OnceCell::new();
5700 :
5701 502 : pub(crate) fn setup_logging() {
5702 502 : LOG_HANDLE.get_or_init(|| {
5703 478 : logging::init(
5704 478 : logging::LogFormat::Test,
5705 478 : // enable it in case the tests exercise code paths that use
5706 478 : // debug_assert_current_span_has_tenant_and_timeline_id
5707 478 : logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
5708 478 : logging::Output::Stdout,
5709 478 : )
5710 478 : .expect("Failed to init test logging")
5711 502 : });
5712 502 : }
5713 :
5714 : impl TenantHarness {
5715 454 : pub async fn create_custom(
5716 454 : test_name: &'static str,
5717 454 : tenant_conf: TenantConf,
5718 454 : tenant_id: TenantId,
5719 454 : shard_identity: ShardIdentity,
5720 454 : generation: Generation,
5721 454 : ) -> anyhow::Result<Self> {
5722 454 : setup_logging();
5723 454 :
5724 454 : let repo_dir = PageServerConf::test_repo_dir(test_name);
5725 454 : let _ = fs::remove_dir_all(&repo_dir);
5726 454 : fs::create_dir_all(&repo_dir)?;
5727 :
5728 454 : let conf = PageServerConf::dummy_conf(repo_dir);
5729 454 : // Make a static copy of the config. This can never be free'd, but that's
5730 454 : // OK in a test.
5731 454 : let conf: &'static PageServerConf = Box::leak(Box::new(conf));
5732 454 :
5733 454 : let shard = shard_identity.shard_index();
5734 454 : let tenant_shard_id = TenantShardId {
5735 454 : tenant_id,
5736 454 : shard_number: shard.shard_number,
5737 454 : shard_count: shard.shard_count,
5738 454 : };
5739 454 : fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
5740 454 : fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
5741 :
5742 : use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
5743 454 : let remote_fs_dir = conf.workdir.join("localfs");
5744 454 : std::fs::create_dir_all(&remote_fs_dir).unwrap();
5745 454 : let config = RemoteStorageConfig {
5746 454 : storage: RemoteStorageKind::LocalFs {
5747 454 : local_path: remote_fs_dir.clone(),
5748 454 : },
5749 454 : timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
5750 454 : small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
5751 454 : };
5752 454 : let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
5753 454 : let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
5754 454 :
5755 454 : Ok(Self {
5756 454 : conf,
5757 454 : tenant_conf,
5758 454 : tenant_shard_id,
5759 454 : generation,
5760 454 : shard,
5761 454 : remote_storage,
5762 454 : remote_fs_dir,
5763 454 : deletion_queue,
5764 454 : })
5765 454 : }
5766 :
5767 430 : pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
5768 430 : // Disable automatic GC and compaction to make the unit tests more deterministic.
5769 430 : // The tests perform them manually if needed.
5770 430 : let tenant_conf = TenantConf {
5771 430 : gc_period: Duration::ZERO,
5772 430 : compaction_period: Duration::ZERO,
5773 430 : ..TenantConf::default()
5774 430 : };
5775 430 : let tenant_id = TenantId::generate();
5776 430 : let shard = ShardIdentity::unsharded();
5777 430 : Self::create_custom(
5778 430 : test_name,
5779 430 : tenant_conf,
5780 430 : tenant_id,
5781 430 : shard,
5782 430 : Generation::new(0xdeadbeef),
5783 430 : )
5784 430 : .await
5785 430 : }
5786 :
5787 40 : pub fn span(&self) -> tracing::Span {
5788 40 : info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
5789 40 : }
5790 :
5791 454 : pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
5792 454 : let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error);
5793 454 : (
5794 454 : self.do_try_load(&ctx)
5795 454 : .await
5796 454 : .expect("failed to load test tenant"),
5797 454 : ctx,
5798 454 : )
5799 454 : }
5800 :
5801 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5802 : pub(crate) async fn do_try_load(
5803 : &self,
5804 : ctx: &RequestContext,
5805 : ) -> anyhow::Result<Arc<Tenant>> {
5806 : let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
5807 :
5808 : let tenant = Arc::new(Tenant::new(
5809 : TenantState::Attaching,
5810 : self.conf,
5811 : AttachedTenantConf::try_from(LocationConf::attached_single(
5812 : TenantConfOpt::from(self.tenant_conf.clone()),
5813 : self.generation,
5814 : &ShardParameters::default(),
5815 : ))
5816 : .unwrap(),
5817 : // This is a legacy/test code path: sharding isn't supported here.
5818 : ShardIdentity::unsharded(),
5819 : Some(walredo_mgr),
5820 : self.tenant_shard_id,
5821 : self.remote_storage.clone(),
5822 : self.deletion_queue.new_client(),
5823 : // TODO: ideally we should run all unit tests with both configs
5824 : L0FlushGlobalState::new(L0FlushConfig::default()),
5825 : ));
5826 :
5827 : let preload = tenant
5828 : .preload(&self.remote_storage, CancellationToken::new())
5829 : .await?;
5830 : tenant.attach(Some(preload), ctx).await?;
5831 :
5832 : tenant.state.send_replace(TenantState::Active);
5833 : for timeline in tenant.timelines.lock().unwrap().values() {
5834 : timeline.set_state(TimelineState::Active);
5835 : }
5836 : Ok(tenant)
5837 : }
5838 :
5839 4 : pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
5840 4 : self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
5841 4 : }
5842 : }
5843 :
5844 : // Mock WAL redo manager that doesn't do much
5845 : pub(crate) struct TestRedoManager;
5846 :
5847 : impl TestRedoManager {
5848 : /// # Cancel-Safety
5849 : ///
5850 : /// This method is cancellation-safe.
5851 1676 : pub async fn request_redo(
5852 1676 : &self,
5853 1676 : key: Key,
5854 1676 : lsn: Lsn,
5855 1676 : base_img: Option<(Lsn, Bytes)>,
5856 1676 : records: Vec<(Lsn, NeonWalRecord)>,
5857 1676 : _pg_version: u32,
5858 1676 : ) -> Result<Bytes, walredo::Error> {
5859 2472 : let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
5860 1676 : if records_neon {
5861 : // For Neon wal records, we can decode without spawning postgres, so do so.
5862 1676 : let mut page = match (base_img, records.first()) {
5863 1536 : (Some((_lsn, img)), _) => {
5864 1536 : let mut page = BytesMut::new();
5865 1536 : page.extend_from_slice(&img);
5866 1536 : page
5867 : }
5868 140 : (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
5869 : _ => {
5870 0 : panic!("Neon WAL redo requires base image or will init record");
5871 : }
5872 : };
5873 :
5874 4148 : for (record_lsn, record) in records {
5875 2472 : apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
5876 : }
5877 1676 : Ok(page.freeze())
5878 : } else {
5879 : // We never spawn a postgres walredo process in unit tests: just log what we might have done.
5880 0 : let s = format!(
5881 0 : "redo for {} to get to {}, with {} and {} records",
5882 0 : key,
5883 0 : lsn,
5884 0 : if base_img.is_some() {
5885 0 : "base image"
5886 : } else {
5887 0 : "no base image"
5888 : },
5889 0 : records.len()
5890 0 : );
5891 0 : println!("{s}");
5892 0 :
5893 0 : Ok(test_img(&s))
5894 : }
5895 1676 : }
5896 : }
5897 : }
5898 :
5899 : #[cfg(test)]
5900 : mod tests {
5901 : use std::collections::{BTreeMap, BTreeSet};
5902 :
5903 : use bytes::{Bytes, BytesMut};
5904 : use hex_literal::hex;
5905 : use itertools::Itertools;
5906 : #[cfg(feature = "testing")]
5907 : use models::CompactLsnRange;
5908 : use pageserver_api::key::{AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX};
5909 : use pageserver_api::keyspace::KeySpace;
5910 : use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
5911 : #[cfg(feature = "testing")]
5912 : use pageserver_api::record::NeonWalRecord;
5913 : use pageserver_api::value::Value;
5914 : use pageserver_compaction::helpers::overlaps_with;
5915 : use rand::{Rng, thread_rng};
5916 : use storage_layer::{IoConcurrency, PersistentLayerKey};
5917 : use tests::storage_layer::ValuesReconstructState;
5918 : use tests::timeline::{GetVectoredError, ShutdownMode};
5919 : #[cfg(feature = "testing")]
5920 : use timeline::GcInfo;
5921 : #[cfg(feature = "testing")]
5922 : use timeline::InMemoryLayerTestDesc;
5923 : #[cfg(feature = "testing")]
5924 : use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
5925 : use timeline::{CompactOptions, DeltaLayerTestDesc};
5926 : use utils::id::TenantId;
5927 :
5928 : use super::*;
5929 : use crate::DEFAULT_PG_VERSION;
5930 : use crate::keyspace::KeySpaceAccum;
5931 : use crate::tenant::harness::*;
5932 : use crate::tenant::timeline::CompactFlags;
5933 :
5934 : static TEST_KEY: Lazy<Key> =
5935 36 : Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
5936 :
5937 : #[tokio::test]
5938 4 : async fn test_basic() -> anyhow::Result<()> {
5939 4 : let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
5940 4 : let tline = tenant
5941 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
5942 4 : .await?;
5943 4 :
5944 4 : let mut writer = tline.writer().await;
5945 4 : writer
5946 4 : .put(
5947 4 : *TEST_KEY,
5948 4 : Lsn(0x10),
5949 4 : &Value::Image(test_img("foo at 0x10")),
5950 4 : &ctx,
5951 4 : )
5952 4 : .await?;
5953 4 : writer.finish_write(Lsn(0x10));
5954 4 : drop(writer);
5955 4 :
5956 4 : let mut writer = tline.writer().await;
5957 4 : writer
5958 4 : .put(
5959 4 : *TEST_KEY,
5960 4 : Lsn(0x20),
5961 4 : &Value::Image(test_img("foo at 0x20")),
5962 4 : &ctx,
5963 4 : )
5964 4 : .await?;
5965 4 : writer.finish_write(Lsn(0x20));
5966 4 : drop(writer);
5967 4 :
5968 4 : assert_eq!(
5969 4 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
5970 4 : test_img("foo at 0x10")
5971 4 : );
5972 4 : assert_eq!(
5973 4 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
5974 4 : test_img("foo at 0x10")
5975 4 : );
5976 4 : assert_eq!(
5977 4 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
5978 4 : test_img("foo at 0x20")
5979 4 : );
5980 4 :
5981 4 : Ok(())
5982 4 : }
5983 :
5984 : #[tokio::test]
5985 4 : async fn no_duplicate_timelines() -> anyhow::Result<()> {
5986 4 : let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
5987 4 : .await?
5988 4 : .load()
5989 4 : .await;
5990 4 : let _ = tenant
5991 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5992 4 : .await?;
5993 4 :
5994 4 : match tenant
5995 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5996 4 : .await
5997 4 : {
5998 4 : Ok(_) => panic!("duplicate timeline creation should fail"),
5999 4 : Err(e) => assert_eq!(
6000 4 : e.to_string(),
6001 4 : "timeline already exists with different parameters".to_string()
6002 4 : ),
6003 4 : }
6004 4 :
6005 4 : Ok(())
6006 4 : }
6007 :
6008 : /// Convenience function to create a page image with given string as the only content
6009 20 : pub fn test_value(s: &str) -> Value {
6010 20 : let mut buf = BytesMut::new();
6011 20 : buf.extend_from_slice(s.as_bytes());
6012 20 : Value::Image(buf.freeze())
6013 20 : }
6014 :
6015 : ///
6016 : /// Test branch creation
6017 : ///
6018 : #[tokio::test]
6019 4 : async fn test_branch() -> anyhow::Result<()> {
6020 4 : use std::str::from_utf8;
6021 4 :
6022 4 : let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
6023 4 : let tline = tenant
6024 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6025 4 : .await?;
6026 4 : let mut writer = tline.writer().await;
6027 4 :
6028 4 : #[allow(non_snake_case)]
6029 4 : let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
6030 4 : #[allow(non_snake_case)]
6031 4 : let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
6032 4 :
6033 4 : // Insert a value on the timeline
6034 4 : writer
6035 4 : .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
6036 4 : .await?;
6037 4 : writer
6038 4 : .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
6039 4 : .await?;
6040 4 : writer.finish_write(Lsn(0x20));
6041 4 :
6042 4 : writer
6043 4 : .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
6044 4 : .await?;
6045 4 : writer.finish_write(Lsn(0x30));
6046 4 : writer
6047 4 : .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
6048 4 : .await?;
6049 4 : writer.finish_write(Lsn(0x40));
6050 4 :
6051 4 : //assert_current_logical_size(&tline, Lsn(0x40));
6052 4 :
6053 4 : // Branch the history, modify relation differently on the new timeline
6054 4 : tenant
6055 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
6056 4 : .await?;
6057 4 : let newtline = tenant
6058 4 : .get_timeline(NEW_TIMELINE_ID, true)
6059 4 : .expect("Should have a local timeline");
6060 4 : let mut new_writer = newtline.writer().await;
6061 4 : new_writer
6062 4 : .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
6063 4 : .await?;
6064 4 : new_writer.finish_write(Lsn(0x40));
6065 4 :
6066 4 : // Check page contents on both branches
6067 4 : assert_eq!(
6068 4 : from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
6069 4 : "foo at 0x40"
6070 4 : );
6071 4 : assert_eq!(
6072 4 : from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
6073 4 : "bar at 0x40"
6074 4 : );
6075 4 : assert_eq!(
6076 4 : from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
6077 4 : "foobar at 0x20"
6078 4 : );
6079 4 :
6080 4 : //assert_current_logical_size(&tline, Lsn(0x40));
6081 4 :
6082 4 : Ok(())
6083 4 : }
6084 :
6085 40 : async fn make_some_layers(
6086 40 : tline: &Timeline,
6087 40 : start_lsn: Lsn,
6088 40 : ctx: &RequestContext,
6089 40 : ) -> anyhow::Result<()> {
6090 40 : let mut lsn = start_lsn;
6091 : {
6092 40 : let mut writer = tline.writer().await;
6093 : // Create a relation on the timeline
6094 40 : writer
6095 40 : .put(
6096 40 : *TEST_KEY,
6097 40 : lsn,
6098 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6099 40 : ctx,
6100 40 : )
6101 40 : .await?;
6102 40 : writer.finish_write(lsn);
6103 40 : lsn += 0x10;
6104 40 : writer
6105 40 : .put(
6106 40 : *TEST_KEY,
6107 40 : lsn,
6108 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6109 40 : ctx,
6110 40 : )
6111 40 : .await?;
6112 40 : writer.finish_write(lsn);
6113 40 : lsn += 0x10;
6114 40 : }
6115 40 : tline.freeze_and_flush().await?;
6116 : {
6117 40 : let mut writer = tline.writer().await;
6118 40 : writer
6119 40 : .put(
6120 40 : *TEST_KEY,
6121 40 : lsn,
6122 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6123 40 : ctx,
6124 40 : )
6125 40 : .await?;
6126 40 : writer.finish_write(lsn);
6127 40 : lsn += 0x10;
6128 40 : writer
6129 40 : .put(
6130 40 : *TEST_KEY,
6131 40 : lsn,
6132 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6133 40 : ctx,
6134 40 : )
6135 40 : .await?;
6136 40 : writer.finish_write(lsn);
6137 40 : }
6138 40 : tline.freeze_and_flush().await.map_err(|e| e.into())
6139 40 : }
6140 :
6141 : #[tokio::test(start_paused = true)]
6142 4 : async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
6143 4 : let (tenant, ctx) =
6144 4 : TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
6145 4 : .await?
6146 4 : .load()
6147 4 : .await;
6148 4 : // Advance to the lsn lease deadline so that GC is not blocked by
6149 4 : // initial transition into AttachedSingle.
6150 4 : tokio::time::advance(tenant.get_lsn_lease_length()).await;
6151 4 : tokio::time::resume();
6152 4 : let tline = tenant
6153 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6154 4 : .await?;
6155 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6156 4 :
6157 4 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
6158 4 : // FIXME: this doesn't actually remove any layer currently, given how the flushing
6159 4 : // and compaction works. But it does set the 'cutoff' point so that the cross check
6160 4 : // below should fail.
6161 4 : tenant
6162 4 : .gc_iteration(
6163 4 : Some(TIMELINE_ID),
6164 4 : 0x10,
6165 4 : Duration::ZERO,
6166 4 : &CancellationToken::new(),
6167 4 : &ctx,
6168 4 : )
6169 4 : .await?;
6170 4 :
6171 4 : // try to branch at lsn 25, should fail because we already garbage collected the data
6172 4 : match tenant
6173 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
6174 4 : .await
6175 4 : {
6176 4 : Ok(_) => panic!("branching should have failed"),
6177 4 : Err(err) => {
6178 4 : let CreateTimelineError::AncestorLsn(err) = err else {
6179 4 : panic!("wrong error type")
6180 4 : };
6181 4 : assert!(err.to_string().contains("invalid branch start lsn"));
6182 4 : assert!(
6183 4 : err.source()
6184 4 : .unwrap()
6185 4 : .to_string()
6186 4 : .contains("we might've already garbage collected needed data")
6187 4 : )
6188 4 : }
6189 4 : }
6190 4 :
6191 4 : Ok(())
6192 4 : }
6193 :
6194 : #[tokio::test]
6195 4 : async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
6196 4 : let (tenant, ctx) =
6197 4 : TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
6198 4 : .await?
6199 4 : .load()
6200 4 : .await;
6201 4 :
6202 4 : let tline = tenant
6203 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
6204 4 : .await?;
6205 4 : // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
6206 4 : match tenant
6207 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
6208 4 : .await
6209 4 : {
6210 4 : Ok(_) => panic!("branching should have failed"),
6211 4 : Err(err) => {
6212 4 : let CreateTimelineError::AncestorLsn(err) = err else {
6213 4 : panic!("wrong error type");
6214 4 : };
6215 4 : assert!(&err.to_string().contains("invalid branch start lsn"));
6216 4 : assert!(
6217 4 : &err.source()
6218 4 : .unwrap()
6219 4 : .to_string()
6220 4 : .contains("is earlier than latest GC cutoff")
6221 4 : );
6222 4 : }
6223 4 : }
6224 4 :
6225 4 : Ok(())
6226 4 : }
6227 :
6228 : /*
6229 : // FIXME: This currently fails to error out. Calling GC doesn't currently
6230 : // remove the old value, we'd need to work a little harder
6231 : #[tokio::test]
6232 : async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
6233 : let repo =
6234 : RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
6235 : .load();
6236 :
6237 : let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
6238 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6239 :
6240 : repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
6241 : let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
6242 : assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
6243 : match tline.get(*TEST_KEY, Lsn(0x25)) {
6244 : Ok(_) => panic!("request for page should have failed"),
6245 : Err(err) => assert!(err.to_string().contains("not found at")),
6246 : }
6247 : Ok(())
6248 : }
6249 : */
6250 :
6251 : #[tokio::test]
6252 4 : async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
6253 4 : let (tenant, ctx) =
6254 4 : TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
6255 4 : .await?
6256 4 : .load()
6257 4 : .await;
6258 4 : let tline = tenant
6259 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6260 4 : .await?;
6261 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6262 4 :
6263 4 : tenant
6264 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6265 4 : .await?;
6266 4 : let newtline = tenant
6267 4 : .get_timeline(NEW_TIMELINE_ID, true)
6268 4 : .expect("Should have a local timeline");
6269 4 :
6270 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6271 4 :
6272 4 : tline.set_broken("test".to_owned());
6273 4 :
6274 4 : tenant
6275 4 : .gc_iteration(
6276 4 : Some(TIMELINE_ID),
6277 4 : 0x10,
6278 4 : Duration::ZERO,
6279 4 : &CancellationToken::new(),
6280 4 : &ctx,
6281 4 : )
6282 4 : .await?;
6283 4 :
6284 4 : // The branchpoints should contain all timelines, even ones marked
6285 4 : // as Broken.
6286 4 : {
6287 4 : let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
6288 4 : assert_eq!(branchpoints.len(), 1);
6289 4 : assert_eq!(
6290 4 : branchpoints[0],
6291 4 : (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
6292 4 : );
6293 4 : }
6294 4 :
6295 4 : // You can read the key from the child branch even though the parent is
6296 4 : // Broken, as long as you don't need to access data from the parent.
6297 4 : assert_eq!(
6298 4 : newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
6299 4 : test_img(&format!("foo at {}", Lsn(0x70)))
6300 4 : );
6301 4 :
6302 4 : // This needs to traverse to the parent, and fails.
6303 4 : let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
6304 4 : assert!(
6305 4 : err.to_string().starts_with(&format!(
6306 4 : "bad state on timeline {}: Broken",
6307 4 : tline.timeline_id
6308 4 : )),
6309 4 : "{err}"
6310 4 : );
6311 4 :
6312 4 : Ok(())
6313 4 : }
6314 :
6315 : #[tokio::test]
6316 4 : async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
6317 4 : let (tenant, ctx) =
6318 4 : TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
6319 4 : .await?
6320 4 : .load()
6321 4 : .await;
6322 4 : let tline = tenant
6323 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6324 4 : .await?;
6325 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6326 4 :
6327 4 : tenant
6328 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6329 4 : .await?;
6330 4 : let newtline = tenant
6331 4 : .get_timeline(NEW_TIMELINE_ID, true)
6332 4 : .expect("Should have a local timeline");
6333 4 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
6334 4 : tenant
6335 4 : .gc_iteration(
6336 4 : Some(TIMELINE_ID),
6337 4 : 0x10,
6338 4 : Duration::ZERO,
6339 4 : &CancellationToken::new(),
6340 4 : &ctx,
6341 4 : )
6342 4 : .await?;
6343 4 : assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
6344 4 :
6345 4 : Ok(())
6346 4 : }
6347 : #[tokio::test]
6348 4 : async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
6349 4 : let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
6350 4 : .await?
6351 4 : .load()
6352 4 : .await;
6353 4 : let tline = tenant
6354 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6355 4 : .await?;
6356 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6357 4 :
6358 4 : tenant
6359 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6360 4 : .await?;
6361 4 : let newtline = tenant
6362 4 : .get_timeline(NEW_TIMELINE_ID, true)
6363 4 : .expect("Should have a local timeline");
6364 4 :
6365 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6366 4 :
6367 4 : // run gc on parent
6368 4 : tenant
6369 4 : .gc_iteration(
6370 4 : Some(TIMELINE_ID),
6371 4 : 0x10,
6372 4 : Duration::ZERO,
6373 4 : &CancellationToken::new(),
6374 4 : &ctx,
6375 4 : )
6376 4 : .await?;
6377 4 :
6378 4 : // Check that the data is still accessible on the branch.
6379 4 : assert_eq!(
6380 4 : newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
6381 4 : test_img(&format!("foo at {}", Lsn(0x40)))
6382 4 : );
6383 4 :
6384 4 : Ok(())
6385 4 : }
6386 :
6387 : #[tokio::test]
6388 4 : async fn timeline_load() -> anyhow::Result<()> {
6389 4 : const TEST_NAME: &str = "timeline_load";
6390 4 : let harness = TenantHarness::create(TEST_NAME).await?;
6391 4 : {
6392 4 : let (tenant, ctx) = harness.load().await;
6393 4 : let tline = tenant
6394 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
6395 4 : .await?;
6396 4 : make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
6397 4 : // so that all uploads finish & we can call harness.load() below again
6398 4 : tenant
6399 4 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
6400 4 : .instrument(harness.span())
6401 4 : .await
6402 4 : .ok()
6403 4 : .unwrap();
6404 4 : }
6405 4 :
6406 4 : let (tenant, _ctx) = harness.load().await;
6407 4 : tenant
6408 4 : .get_timeline(TIMELINE_ID, true)
6409 4 : .expect("cannot load timeline");
6410 4 :
6411 4 : Ok(())
6412 4 : }
6413 :
6414 : #[tokio::test]
6415 4 : async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
6416 4 : const TEST_NAME: &str = "timeline_load_with_ancestor";
6417 4 : let harness = TenantHarness::create(TEST_NAME).await?;
6418 4 : // create two timelines
6419 4 : {
6420 4 : let (tenant, ctx) = harness.load().await;
6421 4 : let tline = tenant
6422 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6423 4 : .await?;
6424 4 :
6425 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6426 4 :
6427 4 : let child_tline = tenant
6428 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6429 4 : .await?;
6430 4 : child_tline.set_state(TimelineState::Active);
6431 4 :
6432 4 : let newtline = tenant
6433 4 : .get_timeline(NEW_TIMELINE_ID, true)
6434 4 : .expect("Should have a local timeline");
6435 4 :
6436 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6437 4 :
6438 4 : // so that all uploads finish & we can call harness.load() below again
6439 4 : tenant
6440 4 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
6441 4 : .instrument(harness.span())
6442 4 : .await
6443 4 : .ok()
6444 4 : .unwrap();
6445 4 : }
6446 4 :
6447 4 : // check that both of them are initially unloaded
6448 4 : let (tenant, _ctx) = harness.load().await;
6449 4 :
6450 4 : // check that both, child and ancestor are loaded
6451 4 : let _child_tline = tenant
6452 4 : .get_timeline(NEW_TIMELINE_ID, true)
6453 4 : .expect("cannot get child timeline loaded");
6454 4 :
6455 4 : let _ancestor_tline = tenant
6456 4 : .get_timeline(TIMELINE_ID, true)
6457 4 : .expect("cannot get ancestor timeline loaded");
6458 4 :
6459 4 : Ok(())
6460 4 : }
6461 :
6462 : #[tokio::test]
6463 4 : async fn delta_layer_dumping() -> anyhow::Result<()> {
6464 4 : use storage_layer::AsLayerDesc;
6465 4 : let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
6466 4 : .await?
6467 4 : .load()
6468 4 : .await;
6469 4 : let tline = tenant
6470 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6471 4 : .await?;
6472 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6473 4 :
6474 4 : let layer_map = tline.layers.read().await;
6475 4 : let level0_deltas = layer_map
6476 4 : .layer_map()?
6477 4 : .level0_deltas()
6478 4 : .iter()
6479 8 : .map(|desc| layer_map.get_from_desc(desc))
6480 4 : .collect::<Vec<_>>();
6481 4 :
6482 4 : assert!(!level0_deltas.is_empty());
6483 4 :
6484 12 : for delta in level0_deltas {
6485 4 : // Ensure we are dumping a delta layer here
6486 8 : assert!(delta.layer_desc().is_delta);
6487 8 : delta.dump(true, &ctx).await.unwrap();
6488 4 : }
6489 4 :
6490 4 : Ok(())
6491 4 : }
6492 :
6493 : #[tokio::test]
6494 4 : async fn test_images() -> anyhow::Result<()> {
6495 4 : let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
6496 4 : let tline = tenant
6497 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6498 4 : .await?;
6499 4 :
6500 4 : let mut writer = tline.writer().await;
6501 4 : writer
6502 4 : .put(
6503 4 : *TEST_KEY,
6504 4 : Lsn(0x10),
6505 4 : &Value::Image(test_img("foo at 0x10")),
6506 4 : &ctx,
6507 4 : )
6508 4 : .await?;
6509 4 : writer.finish_write(Lsn(0x10));
6510 4 : drop(writer);
6511 4 :
6512 4 : tline.freeze_and_flush().await?;
6513 4 : tline
6514 4 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
6515 4 : .await?;
6516 4 :
6517 4 : let mut writer = tline.writer().await;
6518 4 : writer
6519 4 : .put(
6520 4 : *TEST_KEY,
6521 4 : Lsn(0x20),
6522 4 : &Value::Image(test_img("foo at 0x20")),
6523 4 : &ctx,
6524 4 : )
6525 4 : .await?;
6526 4 : writer.finish_write(Lsn(0x20));
6527 4 : drop(writer);
6528 4 :
6529 4 : tline.freeze_and_flush().await?;
6530 4 : tline
6531 4 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
6532 4 : .await?;
6533 4 :
6534 4 : let mut writer = tline.writer().await;
6535 4 : writer
6536 4 : .put(
6537 4 : *TEST_KEY,
6538 4 : Lsn(0x30),
6539 4 : &Value::Image(test_img("foo at 0x30")),
6540 4 : &ctx,
6541 4 : )
6542 4 : .await?;
6543 4 : writer.finish_write(Lsn(0x30));
6544 4 : drop(writer);
6545 4 :
6546 4 : tline.freeze_and_flush().await?;
6547 4 : tline
6548 4 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
6549 4 : .await?;
6550 4 :
6551 4 : let mut writer = tline.writer().await;
6552 4 : writer
6553 4 : .put(
6554 4 : *TEST_KEY,
6555 4 : Lsn(0x40),
6556 4 : &Value::Image(test_img("foo at 0x40")),
6557 4 : &ctx,
6558 4 : )
6559 4 : .await?;
6560 4 : writer.finish_write(Lsn(0x40));
6561 4 : drop(writer);
6562 4 :
6563 4 : tline.freeze_and_flush().await?;
6564 4 : tline
6565 4 : .compact(&CancellationToken::new(), EnumSet::empty(), &ctx)
6566 4 : .await?;
6567 4 :
6568 4 : assert_eq!(
6569 4 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
6570 4 : test_img("foo at 0x10")
6571 4 : );
6572 4 : assert_eq!(
6573 4 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
6574 4 : test_img("foo at 0x10")
6575 4 : );
6576 4 : assert_eq!(
6577 4 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
6578 4 : test_img("foo at 0x20")
6579 4 : );
6580 4 : assert_eq!(
6581 4 : tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
6582 4 : test_img("foo at 0x30")
6583 4 : );
6584 4 : assert_eq!(
6585 4 : tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
6586 4 : test_img("foo at 0x40")
6587 4 : );
6588 4 :
6589 4 : Ok(())
6590 4 : }
6591 :
6592 8 : async fn bulk_insert_compact_gc(
6593 8 : tenant: &Tenant,
6594 8 : timeline: &Arc<Timeline>,
6595 8 : ctx: &RequestContext,
6596 8 : lsn: Lsn,
6597 8 : repeat: usize,
6598 8 : key_count: usize,
6599 8 : ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
6600 8 : let compact = true;
6601 8 : bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
6602 8 : }
6603 :
6604 16 : async fn bulk_insert_maybe_compact_gc(
6605 16 : tenant: &Tenant,
6606 16 : timeline: &Arc<Timeline>,
6607 16 : ctx: &RequestContext,
6608 16 : mut lsn: Lsn,
6609 16 : repeat: usize,
6610 16 : key_count: usize,
6611 16 : compact: bool,
6612 16 : ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
6613 16 : let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
6614 16 :
6615 16 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6616 16 : let mut blknum = 0;
6617 16 :
6618 16 : // Enforce that key range is monotonously increasing
6619 16 : let mut keyspace = KeySpaceAccum::new();
6620 16 :
6621 16 : let cancel = CancellationToken::new();
6622 16 :
6623 16 : for _ in 0..repeat {
6624 800 : for _ in 0..key_count {
6625 8000000 : test_key.field6 = blknum;
6626 8000000 : let mut writer = timeline.writer().await;
6627 8000000 : writer
6628 8000000 : .put(
6629 8000000 : test_key,
6630 8000000 : lsn,
6631 8000000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
6632 8000000 : ctx,
6633 8000000 : )
6634 8000000 : .await?;
6635 8000000 : inserted.entry(test_key).or_default().insert(lsn);
6636 8000000 : writer.finish_write(lsn);
6637 8000000 : drop(writer);
6638 8000000 :
6639 8000000 : keyspace.add_key(test_key);
6640 8000000 :
6641 8000000 : lsn = Lsn(lsn.0 + 0x10);
6642 8000000 : blknum += 1;
6643 : }
6644 :
6645 800 : timeline.freeze_and_flush().await?;
6646 800 : if compact {
6647 : // this requires timeline to be &Arc<Timeline>
6648 400 : timeline.compact(&cancel, EnumSet::empty(), ctx).await?;
6649 400 : }
6650 :
6651 : // this doesn't really need to use the timeline_id target, but it is closer to what it
6652 : // originally was.
6653 800 : let res = tenant
6654 800 : .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
6655 800 : .await?;
6656 :
6657 800 : assert_eq!(res.layers_removed, 0, "this never removes anything");
6658 : }
6659 :
6660 16 : Ok(inserted)
6661 16 : }
6662 :
6663 : //
6664 : // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
6665 : // Repeat 50 times.
6666 : //
6667 : #[tokio::test]
6668 4 : async fn test_bulk_insert() -> anyhow::Result<()> {
6669 4 : let harness = TenantHarness::create("test_bulk_insert").await?;
6670 4 : let (tenant, ctx) = harness.load().await;
6671 4 : let tline = tenant
6672 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6673 4 : .await?;
6674 4 :
6675 4 : let lsn = Lsn(0x10);
6676 4 : bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
6677 4 :
6678 4 : Ok(())
6679 4 : }
6680 :
6681 : // Test the vectored get real implementation against a simple sequential implementation.
6682 : //
6683 : // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
6684 : // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
6685 : // grow to the right on the X axis.
6686 : // [Delta]
6687 : // [Delta]
6688 : // [Delta]
6689 : // [Delta]
6690 : // ------------ Image ---------------
6691 : //
6692 : // After layer generation we pick the ranges to query as follows:
6693 : // 1. The beginning of each delta layer
6694 : // 2. At the seam between two adjacent delta layers
6695 : //
6696 : // There's one major downside to this test: delta layers only contains images,
6697 : // so the search can stop at the first delta layer and doesn't traverse any deeper.
6698 : #[tokio::test]
6699 4 : async fn test_get_vectored() -> anyhow::Result<()> {
6700 4 : let harness = TenantHarness::create("test_get_vectored").await?;
6701 4 : let (tenant, ctx) = harness.load().await;
6702 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6703 4 : let tline = tenant
6704 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6705 4 : .await?;
6706 4 :
6707 4 : let lsn = Lsn(0x10);
6708 4 : let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
6709 4 :
6710 4 : let guard = tline.layers.read().await;
6711 4 : let lm = guard.layer_map()?;
6712 4 :
6713 4 : lm.dump(true, &ctx).await?;
6714 4 :
6715 4 : let mut reads = Vec::new();
6716 4 : let mut prev = None;
6717 24 : lm.iter_historic_layers().for_each(|desc| {
6718 24 : if !desc.is_delta() {
6719 4 : prev = Some(desc.clone());
6720 4 : return;
6721 20 : }
6722 20 :
6723 20 : let start = desc.key_range.start;
6724 20 : let end = desc
6725 20 : .key_range
6726 20 : .start
6727 20 : .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
6728 20 : reads.push(KeySpace {
6729 20 : ranges: vec![start..end],
6730 20 : });
6731 4 :
6732 20 : if let Some(prev) = &prev {
6733 20 : if !prev.is_delta() {
6734 20 : return;
6735 4 : }
6736 0 :
6737 0 : let first_range = Key {
6738 0 : field6: prev.key_range.end.field6 - 4,
6739 0 : ..prev.key_range.end
6740 0 : }..prev.key_range.end;
6741 0 :
6742 0 : let second_range = desc.key_range.start..Key {
6743 0 : field6: desc.key_range.start.field6 + 4,
6744 0 : ..desc.key_range.start
6745 0 : };
6746 0 :
6747 0 : reads.push(KeySpace {
6748 0 : ranges: vec![first_range, second_range],
6749 0 : });
6750 4 : };
6751 4 :
6752 4 : prev = Some(desc.clone());
6753 24 : });
6754 4 :
6755 4 : drop(guard);
6756 4 :
6757 4 : // Pick a big LSN such that we query over all the changes.
6758 4 : let reads_lsn = Lsn(u64::MAX - 1);
6759 4 :
6760 24 : for read in reads {
6761 20 : info!("Doing vectored read on {:?}", read);
6762 4 :
6763 20 : let vectored_res = tline
6764 20 : .get_vectored_impl(
6765 20 : read.clone(),
6766 20 : reads_lsn,
6767 20 : &mut ValuesReconstructState::new(io_concurrency.clone()),
6768 20 : &ctx,
6769 20 : )
6770 20 : .await;
6771 4 :
6772 20 : let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
6773 20 : let mut expect_missing = false;
6774 20 : let mut key = read.start().unwrap();
6775 660 : while key != read.end().unwrap() {
6776 640 : if let Some(lsns) = inserted.get(&key) {
6777 640 : let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
6778 640 : match expected_lsn {
6779 640 : Some(lsn) => {
6780 640 : expected_lsns.insert(key, *lsn);
6781 640 : }
6782 4 : None => {
6783 4 : expect_missing = true;
6784 0 : break;
6785 4 : }
6786 4 : }
6787 4 : } else {
6788 4 : expect_missing = true;
6789 0 : break;
6790 4 : }
6791 4 :
6792 640 : key = key.next();
6793 4 : }
6794 4 :
6795 20 : if expect_missing {
6796 4 : assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
6797 4 : } else {
6798 640 : for (key, image) in vectored_res? {
6799 640 : let expected_lsn = expected_lsns.get(&key).expect("determined above");
6800 640 : let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
6801 640 : assert_eq!(image?, expected_image);
6802 4 : }
6803 4 : }
6804 4 : }
6805 4 :
6806 4 : Ok(())
6807 4 : }
6808 :
6809 : #[tokio::test]
6810 4 : async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
6811 4 : let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
6812 4 :
6813 4 : let (tenant, ctx) = harness.load().await;
6814 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6815 4 : let tline = tenant
6816 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
6817 4 : .await?;
6818 4 : let tline = tline.raw_timeline().unwrap();
6819 4 :
6820 4 : let mut modification = tline.begin_modification(Lsn(0x1000));
6821 4 : modification.put_file("foo/bar1", b"content1", &ctx).await?;
6822 4 : modification.set_lsn(Lsn(0x1008))?;
6823 4 : modification.put_file("foo/bar2", b"content2", &ctx).await?;
6824 4 : modification.commit(&ctx).await?;
6825 4 :
6826 4 : let child_timeline_id = TimelineId::generate();
6827 4 : tenant
6828 4 : .branch_timeline_test(
6829 4 : tline,
6830 4 : child_timeline_id,
6831 4 : Some(tline.get_last_record_lsn()),
6832 4 : &ctx,
6833 4 : )
6834 4 : .await?;
6835 4 :
6836 4 : let child_timeline = tenant
6837 4 : .get_timeline(child_timeline_id, true)
6838 4 : .expect("Should have the branched timeline");
6839 4 :
6840 4 : let aux_keyspace = KeySpace {
6841 4 : ranges: vec![NON_INHERITED_RANGE],
6842 4 : };
6843 4 : let read_lsn = child_timeline.get_last_record_lsn();
6844 4 :
6845 4 : let vectored_res = child_timeline
6846 4 : .get_vectored_impl(
6847 4 : aux_keyspace.clone(),
6848 4 : read_lsn,
6849 4 : &mut ValuesReconstructState::new(io_concurrency.clone()),
6850 4 : &ctx,
6851 4 : )
6852 4 : .await;
6853 4 :
6854 4 : let images = vectored_res?;
6855 4 : assert!(images.is_empty());
6856 4 : Ok(())
6857 4 : }
6858 :
6859 : // Test that vectored get handles layer gaps correctly
6860 : // by advancing into the next ancestor timeline if required.
6861 : //
6862 : // The test generates timelines that look like the diagram below.
6863 : // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
6864 : // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
6865 : //
6866 : // ```
6867 : //-------------------------------+
6868 : // ... |
6869 : // [ L1 ] |
6870 : // [ / L1 ] | Child Timeline
6871 : // ... |
6872 : // ------------------------------+
6873 : // [ X L1 ] | Parent Timeline
6874 : // ------------------------------+
6875 : // ```
6876 : #[tokio::test]
6877 4 : async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
6878 4 : let tenant_conf = TenantConf {
6879 4 : // Make compaction deterministic
6880 4 : gc_period: Duration::ZERO,
6881 4 : compaction_period: Duration::ZERO,
6882 4 : // Encourage creation of L1 layers
6883 4 : checkpoint_distance: 16 * 1024,
6884 4 : compaction_target_size: 8 * 1024,
6885 4 : ..TenantConf::default()
6886 4 : };
6887 4 :
6888 4 : let harness = TenantHarness::create_custom(
6889 4 : "test_get_vectored_key_gap",
6890 4 : tenant_conf,
6891 4 : TenantId::generate(),
6892 4 : ShardIdentity::unsharded(),
6893 4 : Generation::new(0xdeadbeef),
6894 4 : )
6895 4 : .await?;
6896 4 : let (tenant, ctx) = harness.load().await;
6897 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6898 4 :
6899 4 : let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6900 4 : let gap_at_key = current_key.add(100);
6901 4 : let mut current_lsn = Lsn(0x10);
6902 4 :
6903 4 : const KEY_COUNT: usize = 10_000;
6904 4 :
6905 4 : let timeline_id = TimelineId::generate();
6906 4 : let current_timeline = tenant
6907 4 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
6908 4 : .await?;
6909 4 :
6910 4 : current_lsn += 0x100;
6911 4 :
6912 4 : let mut writer = current_timeline.writer().await;
6913 4 : writer
6914 4 : .put(
6915 4 : gap_at_key,
6916 4 : current_lsn,
6917 4 : &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
6918 4 : &ctx,
6919 4 : )
6920 4 : .await?;
6921 4 : writer.finish_write(current_lsn);
6922 4 : drop(writer);
6923 4 :
6924 4 : let mut latest_lsns = HashMap::new();
6925 4 : latest_lsns.insert(gap_at_key, current_lsn);
6926 4 :
6927 4 : current_timeline.freeze_and_flush().await?;
6928 4 :
6929 4 : let child_timeline_id = TimelineId::generate();
6930 4 :
6931 4 : tenant
6932 4 : .branch_timeline_test(
6933 4 : ¤t_timeline,
6934 4 : child_timeline_id,
6935 4 : Some(current_lsn),
6936 4 : &ctx,
6937 4 : )
6938 4 : .await?;
6939 4 : let child_timeline = tenant
6940 4 : .get_timeline(child_timeline_id, true)
6941 4 : .expect("Should have the branched timeline");
6942 4 :
6943 40004 : for i in 0..KEY_COUNT {
6944 40000 : if current_key == gap_at_key {
6945 4 : current_key = current_key.next();
6946 4 : continue;
6947 39996 : }
6948 39996 :
6949 39996 : current_lsn += 0x10;
6950 4 :
6951 39996 : let mut writer = child_timeline.writer().await;
6952 39996 : writer
6953 39996 : .put(
6954 39996 : current_key,
6955 39996 : current_lsn,
6956 39996 : &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
6957 39996 : &ctx,
6958 39996 : )
6959 39996 : .await?;
6960 39996 : writer.finish_write(current_lsn);
6961 39996 : drop(writer);
6962 39996 :
6963 39996 : latest_lsns.insert(current_key, current_lsn);
6964 39996 : current_key = current_key.next();
6965 39996 :
6966 39996 : // Flush every now and then to encourage layer file creation.
6967 39996 : if i % 500 == 0 {
6968 80 : child_timeline.freeze_and_flush().await?;
6969 39916 : }
6970 4 : }
6971 4 :
6972 4 : child_timeline.freeze_and_flush().await?;
6973 4 : let mut flags = EnumSet::new();
6974 4 : flags.insert(CompactFlags::ForceRepartition);
6975 4 : child_timeline
6976 4 : .compact(&CancellationToken::new(), flags, &ctx)
6977 4 : .await?;
6978 4 :
6979 4 : let key_near_end = {
6980 4 : let mut tmp = current_key;
6981 4 : tmp.field6 -= 10;
6982 4 : tmp
6983 4 : };
6984 4 :
6985 4 : let key_near_gap = {
6986 4 : let mut tmp = gap_at_key;
6987 4 : tmp.field6 -= 10;
6988 4 : tmp
6989 4 : };
6990 4 :
6991 4 : let read = KeySpace {
6992 4 : ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
6993 4 : };
6994 4 : let results = child_timeline
6995 4 : .get_vectored_impl(
6996 4 : read.clone(),
6997 4 : current_lsn,
6998 4 : &mut ValuesReconstructState::new(io_concurrency.clone()),
6999 4 : &ctx,
7000 4 : )
7001 4 : .await?;
7002 4 :
7003 88 : for (key, img_res) in results {
7004 84 : let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
7005 84 : assert_eq!(img_res?, expected);
7006 4 : }
7007 4 :
7008 4 : Ok(())
7009 4 : }
7010 :
7011 : // Test that vectored get descends into ancestor timelines correctly and
7012 : // does not return an image that's newer than requested.
7013 : //
7014 : // The diagram below ilustrates an interesting case. We have a parent timeline
7015 : // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
7016 : // from the child timeline, so the parent timeline must be visited. When advacing into
7017 : // the child timeline, the read path needs to remember what the requested Lsn was in
7018 : // order to avoid returning an image that's too new. The test below constructs such
7019 : // a timeline setup and does a few queries around the Lsn of each page image.
7020 : // ```
7021 : // LSN
7022 : // ^
7023 : // |
7024 : // |
7025 : // 500 | --------------------------------------> branch point
7026 : // 400 | X
7027 : // 300 | X
7028 : // 200 | --------------------------------------> requested lsn
7029 : // 100 | X
7030 : // |---------------------------------------> Key
7031 : // |
7032 : // ------> requested key
7033 : //
7034 : // Legend:
7035 : // * X - page images
7036 : // ```
7037 : #[tokio::test]
7038 4 : async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
7039 4 : let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
7040 4 : let (tenant, ctx) = harness.load().await;
7041 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7042 4 :
7043 4 : let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7044 4 : let end_key = start_key.add(1000);
7045 4 : let child_gap_at_key = start_key.add(500);
7046 4 : let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
7047 4 :
7048 4 : let mut current_lsn = Lsn(0x10);
7049 4 :
7050 4 : let timeline_id = TimelineId::generate();
7051 4 : let parent_timeline = tenant
7052 4 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
7053 4 : .await?;
7054 4 :
7055 4 : current_lsn += 0x100;
7056 4 :
7057 16 : for _ in 0..3 {
7058 12 : let mut key = start_key;
7059 12012 : while key < end_key {
7060 12000 : current_lsn += 0x10;
7061 12000 :
7062 12000 : let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
7063 4 :
7064 12000 : let mut writer = parent_timeline.writer().await;
7065 12000 : writer
7066 12000 : .put(
7067 12000 : key,
7068 12000 : current_lsn,
7069 12000 : &Value::Image(test_img(&image_value)),
7070 12000 : &ctx,
7071 12000 : )
7072 12000 : .await?;
7073 12000 : writer.finish_write(current_lsn);
7074 12000 :
7075 12000 : if key == child_gap_at_key {
7076 12 : parent_gap_lsns.insert(current_lsn, image_value);
7077 11988 : }
7078 4 :
7079 12000 : key = key.next();
7080 4 : }
7081 4 :
7082 12 : parent_timeline.freeze_and_flush().await?;
7083 4 : }
7084 4 :
7085 4 : let child_timeline_id = TimelineId::generate();
7086 4 :
7087 4 : let child_timeline = tenant
7088 4 : .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
7089 4 : .await?;
7090 4 :
7091 4 : let mut key = start_key;
7092 4004 : while key < end_key {
7093 4000 : if key == child_gap_at_key {
7094 4 : key = key.next();
7095 4 : continue;
7096 3996 : }
7097 3996 :
7098 3996 : current_lsn += 0x10;
7099 4 :
7100 3996 : let mut writer = child_timeline.writer().await;
7101 3996 : writer
7102 3996 : .put(
7103 3996 : key,
7104 3996 : current_lsn,
7105 3996 : &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
7106 3996 : &ctx,
7107 3996 : )
7108 3996 : .await?;
7109 3996 : writer.finish_write(current_lsn);
7110 3996 :
7111 3996 : key = key.next();
7112 4 : }
7113 4 :
7114 4 : child_timeline.freeze_and_flush().await?;
7115 4 :
7116 4 : let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
7117 4 : let mut query_lsns = Vec::new();
7118 12 : for image_lsn in parent_gap_lsns.keys().rev() {
7119 72 : for offset in lsn_offsets {
7120 60 : query_lsns.push(Lsn(image_lsn
7121 60 : .0
7122 60 : .checked_add_signed(offset)
7123 60 : .expect("Shouldn't overflow")));
7124 60 : }
7125 4 : }
7126 4 :
7127 64 : for query_lsn in query_lsns {
7128 60 : let results = child_timeline
7129 60 : .get_vectored_impl(
7130 60 : KeySpace {
7131 60 : ranges: vec![child_gap_at_key..child_gap_at_key.next()],
7132 60 : },
7133 60 : query_lsn,
7134 60 : &mut ValuesReconstructState::new(io_concurrency.clone()),
7135 60 : &ctx,
7136 60 : )
7137 60 : .await;
7138 4 :
7139 60 : let expected_item = parent_gap_lsns
7140 60 : .iter()
7141 60 : .rev()
7142 136 : .find(|(lsn, _)| **lsn <= query_lsn);
7143 60 :
7144 60 : info!(
7145 4 : "Doing vectored read at LSN {}. Expecting image to be: {:?}",
7146 4 : query_lsn, expected_item
7147 4 : );
7148 4 :
7149 60 : match expected_item {
7150 52 : Some((_, img_value)) => {
7151 52 : let key_results = results.expect("No vectored get error expected");
7152 52 : let key_result = &key_results[&child_gap_at_key];
7153 52 : let returned_img = key_result
7154 52 : .as_ref()
7155 52 : .expect("No page reconstruct error expected");
7156 52 :
7157 52 : info!(
7158 4 : "Vectored read at LSN {} returned image {}",
7159 0 : query_lsn,
7160 0 : std::str::from_utf8(returned_img)?
7161 4 : );
7162 52 : assert_eq!(*returned_img, test_img(img_value));
7163 4 : }
7164 4 : None => {
7165 8 : assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
7166 4 : }
7167 4 : }
7168 4 : }
7169 4 :
7170 4 : Ok(())
7171 4 : }
7172 :
7173 : #[tokio::test]
7174 4 : async fn test_random_updates() -> anyhow::Result<()> {
7175 4 : let names_algorithms = [
7176 4 : ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
7177 4 : ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
7178 4 : ];
7179 12 : for (name, algorithm) in names_algorithms {
7180 8 : test_random_updates_algorithm(name, algorithm).await?;
7181 4 : }
7182 4 : Ok(())
7183 4 : }
7184 :
7185 8 : async fn test_random_updates_algorithm(
7186 8 : name: &'static str,
7187 8 : compaction_algorithm: CompactionAlgorithm,
7188 8 : ) -> anyhow::Result<()> {
7189 8 : let mut harness = TenantHarness::create(name).await?;
7190 8 : harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
7191 8 : kind: compaction_algorithm,
7192 8 : };
7193 8 : let (tenant, ctx) = harness.load().await;
7194 8 : let tline = tenant
7195 8 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7196 8 : .await?;
7197 :
7198 : const NUM_KEYS: usize = 1000;
7199 8 : let cancel = CancellationToken::new();
7200 8 :
7201 8 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7202 8 : let mut test_key_end = test_key;
7203 8 : test_key_end.field6 = NUM_KEYS as u32;
7204 8 : tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
7205 8 :
7206 8 : let mut keyspace = KeySpaceAccum::new();
7207 8 :
7208 8 : // Track when each page was last modified. Used to assert that
7209 8 : // a read sees the latest page version.
7210 8 : let mut updated = [Lsn(0); NUM_KEYS];
7211 8 :
7212 8 : let mut lsn = Lsn(0x10);
7213 : #[allow(clippy::needless_range_loop)]
7214 8008 : for blknum in 0..NUM_KEYS {
7215 8000 : lsn = Lsn(lsn.0 + 0x10);
7216 8000 : test_key.field6 = blknum as u32;
7217 8000 : let mut writer = tline.writer().await;
7218 8000 : writer
7219 8000 : .put(
7220 8000 : test_key,
7221 8000 : lsn,
7222 8000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7223 8000 : &ctx,
7224 8000 : )
7225 8000 : .await?;
7226 8000 : writer.finish_write(lsn);
7227 8000 : updated[blknum] = lsn;
7228 8000 : drop(writer);
7229 8000 :
7230 8000 : keyspace.add_key(test_key);
7231 : }
7232 :
7233 408 : for _ in 0..50 {
7234 400400 : for _ in 0..NUM_KEYS {
7235 400000 : lsn = Lsn(lsn.0 + 0x10);
7236 400000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7237 400000 : test_key.field6 = blknum as u32;
7238 400000 : let mut writer = tline.writer().await;
7239 400000 : writer
7240 400000 : .put(
7241 400000 : test_key,
7242 400000 : lsn,
7243 400000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7244 400000 : &ctx,
7245 400000 : )
7246 400000 : .await?;
7247 400000 : writer.finish_write(lsn);
7248 400000 : drop(writer);
7249 400000 : updated[blknum] = lsn;
7250 : }
7251 :
7252 : // Read all the blocks
7253 400000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7254 400000 : test_key.field6 = blknum as u32;
7255 400000 : assert_eq!(
7256 400000 : tline.get(test_key, lsn, &ctx).await?,
7257 400000 : test_img(&format!("{} at {}", blknum, last_lsn))
7258 : );
7259 : }
7260 :
7261 : // Perform a cycle of flush, and GC
7262 400 : tline.freeze_and_flush().await?;
7263 400 : tenant
7264 400 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7265 400 : .await?;
7266 : }
7267 :
7268 8 : Ok(())
7269 8 : }
7270 :
7271 : #[tokio::test]
7272 4 : async fn test_traverse_branches() -> anyhow::Result<()> {
7273 4 : let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
7274 4 : .await?
7275 4 : .load()
7276 4 : .await;
7277 4 : let mut tline = tenant
7278 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7279 4 : .await?;
7280 4 :
7281 4 : const NUM_KEYS: usize = 1000;
7282 4 :
7283 4 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7284 4 :
7285 4 : let mut keyspace = KeySpaceAccum::new();
7286 4 :
7287 4 : let cancel = CancellationToken::new();
7288 4 :
7289 4 : // Track when each page was last modified. Used to assert that
7290 4 : // a read sees the latest page version.
7291 4 : let mut updated = [Lsn(0); NUM_KEYS];
7292 4 :
7293 4 : let mut lsn = Lsn(0x10);
7294 4 : #[allow(clippy::needless_range_loop)]
7295 4004 : for blknum in 0..NUM_KEYS {
7296 4000 : lsn = Lsn(lsn.0 + 0x10);
7297 4000 : test_key.field6 = blknum as u32;
7298 4000 : let mut writer = tline.writer().await;
7299 4000 : writer
7300 4000 : .put(
7301 4000 : test_key,
7302 4000 : lsn,
7303 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7304 4000 : &ctx,
7305 4000 : )
7306 4000 : .await?;
7307 4000 : writer.finish_write(lsn);
7308 4000 : updated[blknum] = lsn;
7309 4000 : drop(writer);
7310 4000 :
7311 4000 : keyspace.add_key(test_key);
7312 4 : }
7313 4 :
7314 204 : for _ in 0..50 {
7315 200 : let new_tline_id = TimelineId::generate();
7316 200 : tenant
7317 200 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
7318 200 : .await?;
7319 200 : tline = tenant
7320 200 : .get_timeline(new_tline_id, true)
7321 200 : .expect("Should have the branched timeline");
7322 4 :
7323 200200 : for _ in 0..NUM_KEYS {
7324 200000 : lsn = Lsn(lsn.0 + 0x10);
7325 200000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7326 200000 : test_key.field6 = blknum as u32;
7327 200000 : let mut writer = tline.writer().await;
7328 200000 : writer
7329 200000 : .put(
7330 200000 : test_key,
7331 200000 : lsn,
7332 200000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7333 200000 : &ctx,
7334 200000 : )
7335 200000 : .await?;
7336 200000 : println!("updating {} at {}", blknum, lsn);
7337 200000 : writer.finish_write(lsn);
7338 200000 : drop(writer);
7339 200000 : updated[blknum] = lsn;
7340 4 : }
7341 4 :
7342 4 : // Read all the blocks
7343 200000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7344 200000 : test_key.field6 = blknum as u32;
7345 200000 : assert_eq!(
7346 200000 : tline.get(test_key, lsn, &ctx).await?,
7347 200000 : test_img(&format!("{} at {}", blknum, last_lsn))
7348 4 : );
7349 4 : }
7350 4 :
7351 4 : // Perform a cycle of flush, compact, and GC
7352 200 : tline.freeze_and_flush().await?;
7353 200 : tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
7354 200 : tenant
7355 200 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7356 200 : .await?;
7357 4 : }
7358 4 :
7359 4 : Ok(())
7360 4 : }
7361 :
7362 : #[tokio::test]
7363 4 : async fn test_traverse_ancestors() -> anyhow::Result<()> {
7364 4 : let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
7365 4 : .await?
7366 4 : .load()
7367 4 : .await;
7368 4 : let mut tline = tenant
7369 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7370 4 : .await?;
7371 4 :
7372 4 : const NUM_KEYS: usize = 100;
7373 4 : const NUM_TLINES: usize = 50;
7374 4 :
7375 4 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7376 4 : // Track page mutation lsns across different timelines.
7377 4 : let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
7378 4 :
7379 4 : let mut lsn = Lsn(0x10);
7380 4 :
7381 4 : #[allow(clippy::needless_range_loop)]
7382 204 : for idx in 0..NUM_TLINES {
7383 200 : let new_tline_id = TimelineId::generate();
7384 200 : tenant
7385 200 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
7386 200 : .await?;
7387 200 : tline = tenant
7388 200 : .get_timeline(new_tline_id, true)
7389 200 : .expect("Should have the branched timeline");
7390 4 :
7391 20200 : for _ in 0..NUM_KEYS {
7392 20000 : lsn = Lsn(lsn.0 + 0x10);
7393 20000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7394 20000 : test_key.field6 = blknum as u32;
7395 20000 : let mut writer = tline.writer().await;
7396 20000 : writer
7397 20000 : .put(
7398 20000 : test_key,
7399 20000 : lsn,
7400 20000 : &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
7401 20000 : &ctx,
7402 20000 : )
7403 20000 : .await?;
7404 20000 : println!("updating [{}][{}] at {}", idx, blknum, lsn);
7405 20000 : writer.finish_write(lsn);
7406 20000 : drop(writer);
7407 20000 : updated[idx][blknum] = lsn;
7408 4 : }
7409 4 : }
7410 4 :
7411 4 : // Read pages from leaf timeline across all ancestors.
7412 200 : for (idx, lsns) in updated.iter().enumerate() {
7413 20000 : for (blknum, lsn) in lsns.iter().enumerate() {
7414 4 : // Skip empty mutations.
7415 20000 : if lsn.0 == 0 {
7416 7390 : continue;
7417 12610 : }
7418 12610 : println!("checking [{idx}][{blknum}] at {lsn}");
7419 12610 : test_key.field6 = blknum as u32;
7420 12610 : assert_eq!(
7421 12610 : tline.get(test_key, *lsn, &ctx).await?,
7422 12610 : test_img(&format!("{idx} {blknum} at {lsn}"))
7423 4 : );
7424 4 : }
7425 4 : }
7426 4 : Ok(())
7427 4 : }
7428 :
7429 : #[tokio::test]
7430 4 : async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
7431 4 : let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
7432 4 : .await?
7433 4 : .load()
7434 4 : .await;
7435 4 :
7436 4 : let initdb_lsn = Lsn(0x20);
7437 4 : let utline = tenant
7438 4 : .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
7439 4 : .await?;
7440 4 : let tline = utline.raw_timeline().unwrap();
7441 4 :
7442 4 : // Spawn flush loop now so that we can set the `expect_initdb_optimization`
7443 4 : tline.maybe_spawn_flush_loop();
7444 4 :
7445 4 : // Make sure the timeline has the minimum set of required keys for operation.
7446 4 : // The only operation you can always do on an empty timeline is to `put` new data.
7447 4 : // Except if you `put` at `initdb_lsn`.
7448 4 : // In that case, there's an optimization to directly create image layers instead of delta layers.
7449 4 : // It uses `repartition()`, which assumes some keys to be present.
7450 4 : // Let's make sure the test timeline can handle that case.
7451 4 : {
7452 4 : let mut state = tline.flush_loop_state.lock().unwrap();
7453 4 : assert_eq!(
7454 4 : timeline::FlushLoopState::Running {
7455 4 : expect_initdb_optimization: false,
7456 4 : initdb_optimization_count: 0,
7457 4 : },
7458 4 : *state
7459 4 : );
7460 4 : *state = timeline::FlushLoopState::Running {
7461 4 : expect_initdb_optimization: true,
7462 4 : initdb_optimization_count: 0,
7463 4 : };
7464 4 : }
7465 4 :
7466 4 : // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
7467 4 : // As explained above, the optimization requires some keys to be present.
7468 4 : // As per `create_empty_timeline` documentation, use init_empty to set them.
7469 4 : // This is what `create_test_timeline` does, by the way.
7470 4 : let mut modification = tline.begin_modification(initdb_lsn);
7471 4 : modification
7472 4 : .init_empty_test_timeline()
7473 4 : .context("init_empty_test_timeline")?;
7474 4 : modification
7475 4 : .commit(&ctx)
7476 4 : .await
7477 4 : .context("commit init_empty_test_timeline modification")?;
7478 4 :
7479 4 : // Do the flush. The flush code will check the expectations that we set above.
7480 4 : tline.freeze_and_flush().await?;
7481 4 :
7482 4 : // assert freeze_and_flush exercised the initdb optimization
7483 4 : {
7484 4 : let state = tline.flush_loop_state.lock().unwrap();
7485 4 : let timeline::FlushLoopState::Running {
7486 4 : expect_initdb_optimization,
7487 4 : initdb_optimization_count,
7488 4 : } = *state
7489 4 : else {
7490 4 : panic!("unexpected state: {:?}", *state);
7491 4 : };
7492 4 : assert!(expect_initdb_optimization);
7493 4 : assert!(initdb_optimization_count > 0);
7494 4 : }
7495 4 : Ok(())
7496 4 : }
7497 :
7498 : #[tokio::test]
7499 4 : async fn test_create_guard_crash() -> anyhow::Result<()> {
7500 4 : let name = "test_create_guard_crash";
7501 4 : let harness = TenantHarness::create(name).await?;
7502 4 : {
7503 4 : let (tenant, ctx) = harness.load().await;
7504 4 : let tline = tenant
7505 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
7506 4 : .await?;
7507 4 : // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
7508 4 : let raw_tline = tline.raw_timeline().unwrap();
7509 4 : raw_tline
7510 4 : .shutdown(super::timeline::ShutdownMode::Hard)
7511 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))
7512 4 : .await;
7513 4 : std::mem::forget(tline);
7514 4 : }
7515 4 :
7516 4 : let (tenant, _) = harness.load().await;
7517 4 : match tenant.get_timeline(TIMELINE_ID, false) {
7518 4 : Ok(_) => panic!("timeline should've been removed during load"),
7519 4 : Err(e) => {
7520 4 : assert_eq!(
7521 4 : e,
7522 4 : GetTimelineError::NotFound {
7523 4 : tenant_id: tenant.tenant_shard_id,
7524 4 : timeline_id: TIMELINE_ID,
7525 4 : }
7526 4 : )
7527 4 : }
7528 4 : }
7529 4 :
7530 4 : assert!(
7531 4 : !harness
7532 4 : .conf
7533 4 : .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
7534 4 : .exists()
7535 4 : );
7536 4 :
7537 4 : Ok(())
7538 4 : }
7539 :
7540 : #[tokio::test]
7541 4 : async fn test_read_at_max_lsn() -> anyhow::Result<()> {
7542 4 : let names_algorithms = [
7543 4 : ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
7544 4 : ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
7545 4 : ];
7546 12 : for (name, algorithm) in names_algorithms {
7547 8 : test_read_at_max_lsn_algorithm(name, algorithm).await?;
7548 4 : }
7549 4 : Ok(())
7550 4 : }
7551 :
7552 8 : async fn test_read_at_max_lsn_algorithm(
7553 8 : name: &'static str,
7554 8 : compaction_algorithm: CompactionAlgorithm,
7555 8 : ) -> anyhow::Result<()> {
7556 8 : let mut harness = TenantHarness::create(name).await?;
7557 8 : harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
7558 8 : kind: compaction_algorithm,
7559 8 : };
7560 8 : let (tenant, ctx) = harness.load().await;
7561 8 : let tline = tenant
7562 8 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
7563 8 : .await?;
7564 :
7565 8 : let lsn = Lsn(0x10);
7566 8 : let compact = false;
7567 8 : bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
7568 :
7569 8 : let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7570 8 : let read_lsn = Lsn(u64::MAX - 1);
7571 :
7572 8 : let result = tline.get(test_key, read_lsn, &ctx).await;
7573 8 : assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
7574 :
7575 8 : Ok(())
7576 8 : }
7577 :
7578 : #[tokio::test]
7579 4 : async fn test_metadata_scan() -> anyhow::Result<()> {
7580 4 : let harness = TenantHarness::create("test_metadata_scan").await?;
7581 4 : let (tenant, ctx) = harness.load().await;
7582 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7583 4 : let tline = tenant
7584 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7585 4 : .await?;
7586 4 :
7587 4 : const NUM_KEYS: usize = 1000;
7588 4 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
7589 4 :
7590 4 : let cancel = CancellationToken::new();
7591 4 :
7592 4 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7593 4 : base_key.field1 = AUX_KEY_PREFIX;
7594 4 : let mut test_key = base_key;
7595 4 :
7596 4 : // Track when each page was last modified. Used to assert that
7597 4 : // a read sees the latest page version.
7598 4 : let mut updated = [Lsn(0); NUM_KEYS];
7599 4 :
7600 4 : let mut lsn = Lsn(0x10);
7601 4 : #[allow(clippy::needless_range_loop)]
7602 4004 : for blknum in 0..NUM_KEYS {
7603 4000 : lsn = Lsn(lsn.0 + 0x10);
7604 4000 : test_key.field6 = (blknum * STEP) as u32;
7605 4000 : let mut writer = tline.writer().await;
7606 4000 : writer
7607 4000 : .put(
7608 4000 : test_key,
7609 4000 : lsn,
7610 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7611 4000 : &ctx,
7612 4000 : )
7613 4000 : .await?;
7614 4000 : writer.finish_write(lsn);
7615 4000 : updated[blknum] = lsn;
7616 4000 : drop(writer);
7617 4 : }
7618 4 :
7619 4 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
7620 4 :
7621 48 : for iter in 0..=10 {
7622 4 : // Read all the blocks
7623 44000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7624 44000 : test_key.field6 = (blknum * STEP) as u32;
7625 44000 : assert_eq!(
7626 44000 : tline.get(test_key, lsn, &ctx).await?,
7627 44000 : test_img(&format!("{} at {}", blknum, last_lsn))
7628 4 : );
7629 4 : }
7630 4 :
7631 44 : let mut cnt = 0;
7632 44000 : for (key, value) in tline
7633 44 : .get_vectored_impl(
7634 44 : keyspace.clone(),
7635 44 : lsn,
7636 44 : &mut ValuesReconstructState::new(io_concurrency.clone()),
7637 44 : &ctx,
7638 44 : )
7639 44 : .await?
7640 4 : {
7641 44000 : let blknum = key.field6 as usize;
7642 44000 : let value = value?;
7643 44000 : assert!(blknum % STEP == 0);
7644 44000 : let blknum = blknum / STEP;
7645 44000 : assert_eq!(
7646 44000 : value,
7647 44000 : test_img(&format!("{} at {}", blknum, updated[blknum]))
7648 44000 : );
7649 44000 : cnt += 1;
7650 4 : }
7651 4 :
7652 44 : assert_eq!(cnt, NUM_KEYS);
7653 4 :
7654 44044 : for _ in 0..NUM_KEYS {
7655 44000 : lsn = Lsn(lsn.0 + 0x10);
7656 44000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7657 44000 : test_key.field6 = (blknum * STEP) as u32;
7658 44000 : let mut writer = tline.writer().await;
7659 44000 : writer
7660 44000 : .put(
7661 44000 : test_key,
7662 44000 : lsn,
7663 44000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7664 44000 : &ctx,
7665 44000 : )
7666 44000 : .await?;
7667 44000 : writer.finish_write(lsn);
7668 44000 : drop(writer);
7669 44000 : updated[blknum] = lsn;
7670 4 : }
7671 4 :
7672 4 : // Perform two cycles of flush, compact, and GC
7673 132 : for round in 0..2 {
7674 88 : tline.freeze_and_flush().await?;
7675 88 : tline
7676 88 : .compact(
7677 88 : &cancel,
7678 88 : if iter % 5 == 0 && round == 0 {
7679 12 : let mut flags = EnumSet::new();
7680 12 : flags.insert(CompactFlags::ForceImageLayerCreation);
7681 12 : flags.insert(CompactFlags::ForceRepartition);
7682 12 : flags
7683 4 : } else {
7684 76 : EnumSet::empty()
7685 4 : },
7686 88 : &ctx,
7687 88 : )
7688 88 : .await?;
7689 88 : tenant
7690 88 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7691 88 : .await?;
7692 4 : }
7693 4 : }
7694 4 :
7695 4 : Ok(())
7696 4 : }
7697 :
7698 : #[tokio::test]
7699 4 : async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
7700 4 : let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
7701 4 : let (tenant, ctx) = harness.load().await;
7702 4 : let tline = tenant
7703 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7704 4 : .await?;
7705 4 :
7706 4 : let cancel = CancellationToken::new();
7707 4 :
7708 4 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7709 4 : base_key.field1 = AUX_KEY_PREFIX;
7710 4 : let test_key = base_key;
7711 4 : let mut lsn = Lsn(0x10);
7712 4 :
7713 84 : for _ in 0..20 {
7714 80 : lsn = Lsn(lsn.0 + 0x10);
7715 80 : let mut writer = tline.writer().await;
7716 80 : writer
7717 80 : .put(
7718 80 : test_key,
7719 80 : lsn,
7720 80 : &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
7721 80 : &ctx,
7722 80 : )
7723 80 : .await?;
7724 80 : writer.finish_write(lsn);
7725 80 : drop(writer);
7726 80 : tline.freeze_and_flush().await?; // force create a delta layer
7727 4 : }
7728 4 :
7729 4 : let before_num_l0_delta_files =
7730 4 : tline.layers.read().await.layer_map()?.level0_deltas().len();
7731 4 :
7732 4 : tline.compact(&cancel, EnumSet::empty(), &ctx).await?;
7733 4 :
7734 4 : let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
7735 4 :
7736 4 : assert!(
7737 4 : after_num_l0_delta_files < before_num_l0_delta_files,
7738 4 : "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
7739 4 : );
7740 4 :
7741 4 : assert_eq!(
7742 4 : tline.get(test_key, lsn, &ctx).await?,
7743 4 : test_img(&format!("{} at {}", 0, lsn))
7744 4 : );
7745 4 :
7746 4 : Ok(())
7747 4 : }
7748 :
7749 : #[tokio::test]
7750 4 : async fn test_aux_file_e2e() {
7751 4 : let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
7752 4 :
7753 4 : let (tenant, ctx) = harness.load().await;
7754 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7755 4 :
7756 4 : let mut lsn = Lsn(0x08);
7757 4 :
7758 4 : let tline: Arc<Timeline> = tenant
7759 4 : .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
7760 4 : .await
7761 4 : .unwrap();
7762 4 :
7763 4 : {
7764 4 : lsn += 8;
7765 4 : let mut modification = tline.begin_modification(lsn);
7766 4 : modification
7767 4 : .put_file("pg_logical/mappings/test1", b"first", &ctx)
7768 4 : .await
7769 4 : .unwrap();
7770 4 : modification.commit(&ctx).await.unwrap();
7771 4 : }
7772 4 :
7773 4 : // we can read everything from the storage
7774 4 : let files = tline
7775 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7776 4 : .await
7777 4 : .unwrap();
7778 4 : assert_eq!(
7779 4 : files.get("pg_logical/mappings/test1"),
7780 4 : Some(&bytes::Bytes::from_static(b"first"))
7781 4 : );
7782 4 :
7783 4 : {
7784 4 : lsn += 8;
7785 4 : let mut modification = tline.begin_modification(lsn);
7786 4 : modification
7787 4 : .put_file("pg_logical/mappings/test2", b"second", &ctx)
7788 4 : .await
7789 4 : .unwrap();
7790 4 : modification.commit(&ctx).await.unwrap();
7791 4 : }
7792 4 :
7793 4 : let files = tline
7794 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7795 4 : .await
7796 4 : .unwrap();
7797 4 : assert_eq!(
7798 4 : files.get("pg_logical/mappings/test2"),
7799 4 : Some(&bytes::Bytes::from_static(b"second"))
7800 4 : );
7801 4 :
7802 4 : let child = tenant
7803 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
7804 4 : .await
7805 4 : .unwrap();
7806 4 :
7807 4 : let files = child
7808 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7809 4 : .await
7810 4 : .unwrap();
7811 4 : assert_eq!(files.get("pg_logical/mappings/test1"), None);
7812 4 : assert_eq!(files.get("pg_logical/mappings/test2"), None);
7813 4 : }
7814 :
7815 : #[tokio::test]
7816 4 : async fn test_metadata_image_creation() -> anyhow::Result<()> {
7817 4 : let harness = TenantHarness::create("test_metadata_image_creation").await?;
7818 4 : let (tenant, ctx) = harness.load().await;
7819 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7820 4 : let tline = tenant
7821 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7822 4 : .await?;
7823 4 :
7824 4 : const NUM_KEYS: usize = 1000;
7825 4 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
7826 4 :
7827 4 : let cancel = CancellationToken::new();
7828 4 :
7829 4 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
7830 4 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
7831 4 : let mut test_key = base_key;
7832 4 : let mut lsn = Lsn(0x10);
7833 4 :
7834 16 : async fn scan_with_statistics(
7835 16 : tline: &Timeline,
7836 16 : keyspace: &KeySpace,
7837 16 : lsn: Lsn,
7838 16 : ctx: &RequestContext,
7839 16 : io_concurrency: IoConcurrency,
7840 16 : ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
7841 16 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
7842 16 : let res = tline
7843 16 : .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
7844 16 : .await?;
7845 16 : Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
7846 16 : }
7847 4 :
7848 4 : #[allow(clippy::needless_range_loop)]
7849 4004 : for blknum in 0..NUM_KEYS {
7850 4000 : lsn = Lsn(lsn.0 + 0x10);
7851 4000 : test_key.field6 = (blknum * STEP) as u32;
7852 4000 : let mut writer = tline.writer().await;
7853 4000 : writer
7854 4000 : .put(
7855 4000 : test_key,
7856 4000 : lsn,
7857 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7858 4000 : &ctx,
7859 4000 : )
7860 4000 : .await?;
7861 4000 : writer.finish_write(lsn);
7862 4000 : drop(writer);
7863 4 : }
7864 4 :
7865 4 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
7866 4 :
7867 44 : for iter in 1..=10 {
7868 40040 : for _ in 0..NUM_KEYS {
7869 40000 : lsn = Lsn(lsn.0 + 0x10);
7870 40000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7871 40000 : test_key.field6 = (blknum * STEP) as u32;
7872 40000 : let mut writer = tline.writer().await;
7873 40000 : writer
7874 40000 : .put(
7875 40000 : test_key,
7876 40000 : lsn,
7877 40000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7878 40000 : &ctx,
7879 40000 : )
7880 40000 : .await?;
7881 40000 : writer.finish_write(lsn);
7882 40000 : drop(writer);
7883 4 : }
7884 4 :
7885 40 : tline.freeze_and_flush().await?;
7886 4 :
7887 40 : if iter % 5 == 0 {
7888 8 : let (_, before_delta_file_accessed) =
7889 8 : scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
7890 8 : .await?;
7891 8 : tline
7892 8 : .compact(
7893 8 : &cancel,
7894 8 : {
7895 8 : let mut flags = EnumSet::new();
7896 8 : flags.insert(CompactFlags::ForceImageLayerCreation);
7897 8 : flags.insert(CompactFlags::ForceRepartition);
7898 8 : flags
7899 8 : },
7900 8 : &ctx,
7901 8 : )
7902 8 : .await?;
7903 8 : let (_, after_delta_file_accessed) =
7904 8 : scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
7905 8 : .await?;
7906 8 : assert!(
7907 8 : after_delta_file_accessed < before_delta_file_accessed,
7908 4 : "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
7909 4 : );
7910 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.
7911 8 : assert!(
7912 8 : after_delta_file_accessed <= 2,
7913 4 : "after_delta_file_accessed={after_delta_file_accessed}"
7914 4 : );
7915 32 : }
7916 4 : }
7917 4 :
7918 4 : Ok(())
7919 4 : }
7920 :
7921 : #[tokio::test]
7922 4 : async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
7923 4 : let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
7924 4 : let (tenant, ctx) = harness.load().await;
7925 4 :
7926 4 : let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7927 4 : let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
7928 4 : let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
7929 4 :
7930 4 : let tline = tenant
7931 4 : .create_test_timeline_with_layers(
7932 4 : TIMELINE_ID,
7933 4 : Lsn(0x10),
7934 4 : DEFAULT_PG_VERSION,
7935 4 : &ctx,
7936 4 : Vec::new(), // in-memory layers
7937 4 : Vec::new(), // delta layers
7938 4 : vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
7939 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
7940 4 : )
7941 4 : .await?;
7942 4 : tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
7943 4 :
7944 4 : let child = tenant
7945 4 : .branch_timeline_test_with_layers(
7946 4 : &tline,
7947 4 : NEW_TIMELINE_ID,
7948 4 : Some(Lsn(0x20)),
7949 4 : &ctx,
7950 4 : Vec::new(), // delta layers
7951 4 : vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
7952 4 : Lsn(0x30),
7953 4 : )
7954 4 : .await
7955 4 : .unwrap();
7956 4 :
7957 4 : let lsn = Lsn(0x30);
7958 4 :
7959 4 : // test vectored get on parent timeline
7960 4 : assert_eq!(
7961 4 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
7962 4 : Some(test_img("data key 1"))
7963 4 : );
7964 4 : assert!(
7965 4 : get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
7966 4 : .await
7967 4 : .unwrap_err()
7968 4 : .is_missing_key_error()
7969 4 : );
7970 4 : assert!(
7971 4 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
7972 4 : .await
7973 4 : .unwrap_err()
7974 4 : .is_missing_key_error()
7975 4 : );
7976 4 :
7977 4 : // test vectored get on child timeline
7978 4 : assert_eq!(
7979 4 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
7980 4 : Some(test_img("data key 1"))
7981 4 : );
7982 4 : assert_eq!(
7983 4 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
7984 4 : Some(test_img("data key 2"))
7985 4 : );
7986 4 : assert!(
7987 4 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
7988 4 : .await
7989 4 : .unwrap_err()
7990 4 : .is_missing_key_error()
7991 4 : );
7992 4 :
7993 4 : Ok(())
7994 4 : }
7995 :
7996 : #[tokio::test]
7997 4 : async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
7998 4 : let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
7999 4 : let (tenant, ctx) = harness.load().await;
8000 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8001 4 :
8002 4 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8003 4 : let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
8004 4 : let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
8005 4 : let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
8006 4 :
8007 4 : let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
8008 4 : let base_inherited_key_child =
8009 4 : Key::from_hex("610000000033333333444444445500000001").unwrap();
8010 4 : let base_inherited_key_nonexist =
8011 4 : Key::from_hex("610000000033333333444444445500000002").unwrap();
8012 4 : let base_inherited_key_overwrite =
8013 4 : Key::from_hex("610000000033333333444444445500000003").unwrap();
8014 4 :
8015 4 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
8016 4 : assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
8017 4 :
8018 4 : let tline = tenant
8019 4 : .create_test_timeline_with_layers(
8020 4 : TIMELINE_ID,
8021 4 : Lsn(0x10),
8022 4 : DEFAULT_PG_VERSION,
8023 4 : &ctx,
8024 4 : Vec::new(), // in-memory layers
8025 4 : Vec::new(), // delta layers
8026 4 : vec![(
8027 4 : Lsn(0x20),
8028 4 : vec![
8029 4 : (base_inherited_key, test_img("metadata inherited key 1")),
8030 4 : (
8031 4 : base_inherited_key_overwrite,
8032 4 : test_img("metadata key overwrite 1a"),
8033 4 : ),
8034 4 : (base_key, test_img("metadata key 1")),
8035 4 : (base_key_overwrite, test_img("metadata key overwrite 1b")),
8036 4 : ],
8037 4 : )], // image layers
8038 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
8039 4 : )
8040 4 : .await?;
8041 4 :
8042 4 : let child = tenant
8043 4 : .branch_timeline_test_with_layers(
8044 4 : &tline,
8045 4 : NEW_TIMELINE_ID,
8046 4 : Some(Lsn(0x20)),
8047 4 : &ctx,
8048 4 : Vec::new(), // delta layers
8049 4 : vec![(
8050 4 : Lsn(0x30),
8051 4 : vec![
8052 4 : (
8053 4 : base_inherited_key_child,
8054 4 : test_img("metadata inherited key 2"),
8055 4 : ),
8056 4 : (
8057 4 : base_inherited_key_overwrite,
8058 4 : test_img("metadata key overwrite 2a"),
8059 4 : ),
8060 4 : (base_key_child, test_img("metadata key 2")),
8061 4 : (base_key_overwrite, test_img("metadata key overwrite 2b")),
8062 4 : ],
8063 4 : )], // image layers
8064 4 : Lsn(0x30),
8065 4 : )
8066 4 : .await
8067 4 : .unwrap();
8068 4 :
8069 4 : let lsn = Lsn(0x30);
8070 4 :
8071 4 : // test vectored get on parent timeline
8072 4 : assert_eq!(
8073 4 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
8074 4 : Some(test_img("metadata key 1"))
8075 4 : );
8076 4 : assert_eq!(
8077 4 : get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
8078 4 : None
8079 4 : );
8080 4 : assert_eq!(
8081 4 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
8082 4 : None
8083 4 : );
8084 4 : assert_eq!(
8085 4 : get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
8086 4 : Some(test_img("metadata key overwrite 1b"))
8087 4 : );
8088 4 : assert_eq!(
8089 4 : get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
8090 4 : Some(test_img("metadata inherited key 1"))
8091 4 : );
8092 4 : assert_eq!(
8093 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
8094 4 : None
8095 4 : );
8096 4 : assert_eq!(
8097 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
8098 4 : None
8099 4 : );
8100 4 : assert_eq!(
8101 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
8102 4 : Some(test_img("metadata key overwrite 1a"))
8103 4 : );
8104 4 :
8105 4 : // test vectored get on child timeline
8106 4 : assert_eq!(
8107 4 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
8108 4 : None
8109 4 : );
8110 4 : assert_eq!(
8111 4 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
8112 4 : Some(test_img("metadata key 2"))
8113 4 : );
8114 4 : assert_eq!(
8115 4 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
8116 4 : None
8117 4 : );
8118 4 : assert_eq!(
8119 4 : get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
8120 4 : Some(test_img("metadata inherited key 1"))
8121 4 : );
8122 4 : assert_eq!(
8123 4 : get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
8124 4 : Some(test_img("metadata inherited key 2"))
8125 4 : );
8126 4 : assert_eq!(
8127 4 : get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
8128 4 : None
8129 4 : );
8130 4 : assert_eq!(
8131 4 : get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
8132 4 : Some(test_img("metadata key overwrite 2b"))
8133 4 : );
8134 4 : assert_eq!(
8135 4 : get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
8136 4 : Some(test_img("metadata key overwrite 2a"))
8137 4 : );
8138 4 :
8139 4 : // test vectored scan on parent timeline
8140 4 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
8141 4 : let res = tline
8142 4 : .get_vectored_impl(
8143 4 : KeySpace::single(Key::metadata_key_range()),
8144 4 : lsn,
8145 4 : &mut reconstruct_state,
8146 4 : &ctx,
8147 4 : )
8148 4 : .await?;
8149 4 :
8150 4 : assert_eq!(
8151 4 : res.into_iter()
8152 16 : .map(|(k, v)| (k, v.unwrap()))
8153 4 : .collect::<Vec<_>>(),
8154 4 : vec![
8155 4 : (base_inherited_key, test_img("metadata inherited key 1")),
8156 4 : (
8157 4 : base_inherited_key_overwrite,
8158 4 : test_img("metadata key overwrite 1a")
8159 4 : ),
8160 4 : (base_key, test_img("metadata key 1")),
8161 4 : (base_key_overwrite, test_img("metadata key overwrite 1b")),
8162 4 : ]
8163 4 : );
8164 4 :
8165 4 : // test vectored scan on child timeline
8166 4 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
8167 4 : let res = child
8168 4 : .get_vectored_impl(
8169 4 : KeySpace::single(Key::metadata_key_range()),
8170 4 : lsn,
8171 4 : &mut reconstruct_state,
8172 4 : &ctx,
8173 4 : )
8174 4 : .await?;
8175 4 :
8176 4 : assert_eq!(
8177 4 : res.into_iter()
8178 20 : .map(|(k, v)| (k, v.unwrap()))
8179 4 : .collect::<Vec<_>>(),
8180 4 : vec![
8181 4 : (base_inherited_key, test_img("metadata inherited key 1")),
8182 4 : (
8183 4 : base_inherited_key_child,
8184 4 : test_img("metadata inherited key 2")
8185 4 : ),
8186 4 : (
8187 4 : base_inherited_key_overwrite,
8188 4 : test_img("metadata key overwrite 2a")
8189 4 : ),
8190 4 : (base_key_child, test_img("metadata key 2")),
8191 4 : (base_key_overwrite, test_img("metadata key overwrite 2b")),
8192 4 : ]
8193 4 : );
8194 4 :
8195 4 : Ok(())
8196 4 : }
8197 :
8198 112 : async fn get_vectored_impl_wrapper(
8199 112 : tline: &Arc<Timeline>,
8200 112 : key: Key,
8201 112 : lsn: Lsn,
8202 112 : ctx: &RequestContext,
8203 112 : ) -> Result<Option<Bytes>, GetVectoredError> {
8204 112 : let io_concurrency =
8205 112 : IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
8206 112 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
8207 112 : let mut res = tline
8208 112 : .get_vectored_impl(
8209 112 : KeySpace::single(key..key.next()),
8210 112 : lsn,
8211 112 : &mut reconstruct_state,
8212 112 : ctx,
8213 112 : )
8214 112 : .await?;
8215 100 : Ok(res.pop_last().map(|(k, v)| {
8216 64 : assert_eq!(k, key);
8217 64 : v.unwrap()
8218 100 : }))
8219 112 : }
8220 :
8221 : #[tokio::test]
8222 4 : async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
8223 4 : let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
8224 4 : let (tenant, ctx) = harness.load().await;
8225 4 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
8226 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8227 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8228 4 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
8229 4 :
8230 4 : // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
8231 4 : // Lsn 0x30 key0, key3, no key1+key2
8232 4 : // Lsn 0x20 key1+key2 tomestones
8233 4 : // Lsn 0x10 key1 in image, key2 in delta
8234 4 : let tline = tenant
8235 4 : .create_test_timeline_with_layers(
8236 4 : TIMELINE_ID,
8237 4 : Lsn(0x10),
8238 4 : DEFAULT_PG_VERSION,
8239 4 : &ctx,
8240 4 : Vec::new(), // in-memory layers
8241 4 : // delta layers
8242 4 : vec![
8243 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8244 4 : Lsn(0x10)..Lsn(0x20),
8245 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8246 4 : ),
8247 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8248 4 : Lsn(0x20)..Lsn(0x30),
8249 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8250 4 : ),
8251 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8252 4 : Lsn(0x20)..Lsn(0x30),
8253 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8254 4 : ),
8255 4 : ],
8256 4 : // image layers
8257 4 : vec![
8258 4 : (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
8259 4 : (
8260 4 : Lsn(0x30),
8261 4 : vec![
8262 4 : (key0, test_img("metadata key 0")),
8263 4 : (key3, test_img("metadata key 3")),
8264 4 : ],
8265 4 : ),
8266 4 : ],
8267 4 : Lsn(0x30),
8268 4 : )
8269 4 : .await?;
8270 4 :
8271 4 : let lsn = Lsn(0x30);
8272 4 : let old_lsn = Lsn(0x20);
8273 4 :
8274 4 : assert_eq!(
8275 4 : get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
8276 4 : Some(test_img("metadata key 0"))
8277 4 : );
8278 4 : assert_eq!(
8279 4 : get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
8280 4 : None,
8281 4 : );
8282 4 : assert_eq!(
8283 4 : get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
8284 4 : None,
8285 4 : );
8286 4 : assert_eq!(
8287 4 : get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
8288 4 : Some(Bytes::new()),
8289 4 : );
8290 4 : assert_eq!(
8291 4 : get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
8292 4 : Some(Bytes::new()),
8293 4 : );
8294 4 : assert_eq!(
8295 4 : get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
8296 4 : Some(test_img("metadata key 3"))
8297 4 : );
8298 4 :
8299 4 : Ok(())
8300 4 : }
8301 :
8302 : #[tokio::test]
8303 4 : async fn test_metadata_tombstone_image_creation() {
8304 4 : let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
8305 4 : .await
8306 4 : .unwrap();
8307 4 : let (tenant, ctx) = harness.load().await;
8308 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8309 4 :
8310 4 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
8311 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8312 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8313 4 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
8314 4 :
8315 4 : let tline = tenant
8316 4 : .create_test_timeline_with_layers(
8317 4 : TIMELINE_ID,
8318 4 : Lsn(0x10),
8319 4 : DEFAULT_PG_VERSION,
8320 4 : &ctx,
8321 4 : Vec::new(), // in-memory layers
8322 4 : // delta layers
8323 4 : vec![
8324 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8325 4 : Lsn(0x10)..Lsn(0x20),
8326 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8327 4 : ),
8328 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8329 4 : Lsn(0x20)..Lsn(0x30),
8330 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8331 4 : ),
8332 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8333 4 : Lsn(0x20)..Lsn(0x30),
8334 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8335 4 : ),
8336 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8337 4 : Lsn(0x30)..Lsn(0x40),
8338 4 : vec![
8339 4 : (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
8340 4 : (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
8341 4 : ],
8342 4 : ),
8343 4 : ],
8344 4 : // image layers
8345 4 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
8346 4 : Lsn(0x40),
8347 4 : )
8348 4 : .await
8349 4 : .unwrap();
8350 4 :
8351 4 : let cancel = CancellationToken::new();
8352 4 :
8353 4 : tline
8354 4 : .compact(
8355 4 : &cancel,
8356 4 : {
8357 4 : let mut flags = EnumSet::new();
8358 4 : flags.insert(CompactFlags::ForceImageLayerCreation);
8359 4 : flags.insert(CompactFlags::ForceRepartition);
8360 4 : flags
8361 4 : },
8362 4 : &ctx,
8363 4 : )
8364 4 : .await
8365 4 : .unwrap();
8366 4 :
8367 4 : // Image layers are created at last_record_lsn
8368 4 : let images = tline
8369 4 : .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
8370 4 : .await
8371 4 : .unwrap()
8372 4 : .into_iter()
8373 36 : .filter(|(k, _)| k.is_metadata_key())
8374 4 : .collect::<Vec<_>>();
8375 4 : assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
8376 4 : }
8377 :
8378 : #[tokio::test]
8379 4 : async fn test_metadata_tombstone_empty_image_creation() {
8380 4 : let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
8381 4 : .await
8382 4 : .unwrap();
8383 4 : let (tenant, ctx) = harness.load().await;
8384 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8385 4 :
8386 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8387 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8388 4 :
8389 4 : let tline = tenant
8390 4 : .create_test_timeline_with_layers(
8391 4 : TIMELINE_ID,
8392 4 : Lsn(0x10),
8393 4 : DEFAULT_PG_VERSION,
8394 4 : &ctx,
8395 4 : Vec::new(), // in-memory layers
8396 4 : // delta layers
8397 4 : vec![
8398 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8399 4 : Lsn(0x10)..Lsn(0x20),
8400 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8401 4 : ),
8402 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8403 4 : Lsn(0x20)..Lsn(0x30),
8404 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8405 4 : ),
8406 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8407 4 : Lsn(0x20)..Lsn(0x30),
8408 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8409 4 : ),
8410 4 : ],
8411 4 : // image layers
8412 4 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
8413 4 : Lsn(0x30),
8414 4 : )
8415 4 : .await
8416 4 : .unwrap();
8417 4 :
8418 4 : let cancel = CancellationToken::new();
8419 4 :
8420 4 : tline
8421 4 : .compact(
8422 4 : &cancel,
8423 4 : {
8424 4 : let mut flags = EnumSet::new();
8425 4 : flags.insert(CompactFlags::ForceImageLayerCreation);
8426 4 : flags.insert(CompactFlags::ForceRepartition);
8427 4 : flags
8428 4 : },
8429 4 : &ctx,
8430 4 : )
8431 4 : .await
8432 4 : .unwrap();
8433 4 :
8434 4 : // Image layers are created at last_record_lsn
8435 4 : let images = tline
8436 4 : .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
8437 4 : .await
8438 4 : .unwrap()
8439 4 : .into_iter()
8440 28 : .filter(|(k, _)| k.is_metadata_key())
8441 4 : .collect::<Vec<_>>();
8442 4 : assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
8443 4 : }
8444 :
8445 : #[tokio::test]
8446 4 : async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
8447 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
8448 4 : let (tenant, ctx) = harness.load().await;
8449 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8450 4 :
8451 204 : fn get_key(id: u32) -> Key {
8452 204 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8453 204 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8454 204 : key.field6 = id;
8455 204 : key
8456 204 : }
8457 4 :
8458 4 : // We create
8459 4 : // - one bottom-most image layer,
8460 4 : // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
8461 4 : // - a delta layer D2 crossing the GC horizon with data only below the horizon,
8462 4 : // - a delta layer D3 above the horizon.
8463 4 : //
8464 4 : // | D3 |
8465 4 : // | D1 |
8466 4 : // -| |-- gc horizon -----------------
8467 4 : // | | | D2 |
8468 4 : // --------- img layer ------------------
8469 4 : //
8470 4 : // What we should expact from this compaction is:
8471 4 : // | D3 |
8472 4 : // | Part of D1 |
8473 4 : // --------- img layer with D1+D2 at GC horizon------------------
8474 4 :
8475 4 : // img layer at 0x10
8476 4 : let img_layer = (0..10)
8477 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
8478 4 : .collect_vec();
8479 4 :
8480 4 : let delta1 = vec![
8481 4 : (
8482 4 : get_key(1),
8483 4 : Lsn(0x20),
8484 4 : Value::Image(Bytes::from("value 1@0x20")),
8485 4 : ),
8486 4 : (
8487 4 : get_key(2),
8488 4 : Lsn(0x30),
8489 4 : Value::Image(Bytes::from("value 2@0x30")),
8490 4 : ),
8491 4 : (
8492 4 : get_key(3),
8493 4 : Lsn(0x40),
8494 4 : Value::Image(Bytes::from("value 3@0x40")),
8495 4 : ),
8496 4 : ];
8497 4 : let delta2 = vec![
8498 4 : (
8499 4 : get_key(5),
8500 4 : Lsn(0x20),
8501 4 : Value::Image(Bytes::from("value 5@0x20")),
8502 4 : ),
8503 4 : (
8504 4 : get_key(6),
8505 4 : Lsn(0x20),
8506 4 : Value::Image(Bytes::from("value 6@0x20")),
8507 4 : ),
8508 4 : ];
8509 4 : let delta3 = vec![
8510 4 : (
8511 4 : get_key(8),
8512 4 : Lsn(0x48),
8513 4 : Value::Image(Bytes::from("value 8@0x48")),
8514 4 : ),
8515 4 : (
8516 4 : get_key(9),
8517 4 : Lsn(0x48),
8518 4 : Value::Image(Bytes::from("value 9@0x48")),
8519 4 : ),
8520 4 : ];
8521 4 :
8522 4 : let tline = tenant
8523 4 : .create_test_timeline_with_layers(
8524 4 : TIMELINE_ID,
8525 4 : Lsn(0x10),
8526 4 : DEFAULT_PG_VERSION,
8527 4 : &ctx,
8528 4 : Vec::new(), // in-memory layers
8529 4 : vec![
8530 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
8531 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
8532 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
8533 4 : ], // delta layers
8534 4 : vec![(Lsn(0x10), img_layer)], // image layers
8535 4 : Lsn(0x50),
8536 4 : )
8537 4 : .await?;
8538 4 : {
8539 4 : tline
8540 4 : .applied_gc_cutoff_lsn
8541 4 : .lock_for_write()
8542 4 : .store_and_unlock(Lsn(0x30))
8543 4 : .wait()
8544 4 : .await;
8545 4 : // Update GC info
8546 4 : let mut guard = tline.gc_info.write().unwrap();
8547 4 : guard.cutoffs.time = Lsn(0x30);
8548 4 : guard.cutoffs.space = Lsn(0x30);
8549 4 : }
8550 4 :
8551 4 : let expected_result = [
8552 4 : Bytes::from_static(b"value 0@0x10"),
8553 4 : Bytes::from_static(b"value 1@0x20"),
8554 4 : Bytes::from_static(b"value 2@0x30"),
8555 4 : Bytes::from_static(b"value 3@0x40"),
8556 4 : Bytes::from_static(b"value 4@0x10"),
8557 4 : Bytes::from_static(b"value 5@0x20"),
8558 4 : Bytes::from_static(b"value 6@0x20"),
8559 4 : Bytes::from_static(b"value 7@0x10"),
8560 4 : Bytes::from_static(b"value 8@0x48"),
8561 4 : Bytes::from_static(b"value 9@0x48"),
8562 4 : ];
8563 4 :
8564 40 : for (idx, expected) in expected_result.iter().enumerate() {
8565 40 : assert_eq!(
8566 40 : tline
8567 40 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8568 40 : .await
8569 40 : .unwrap(),
8570 4 : expected
8571 4 : );
8572 4 : }
8573 4 :
8574 4 : let cancel = CancellationToken::new();
8575 4 : tline
8576 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8577 4 : .await
8578 4 : .unwrap();
8579 4 :
8580 40 : for (idx, expected) in expected_result.iter().enumerate() {
8581 40 : assert_eq!(
8582 40 : tline
8583 40 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8584 40 : .await
8585 40 : .unwrap(),
8586 4 : expected
8587 4 : );
8588 4 : }
8589 4 :
8590 4 : // Check if the image layer at the GC horizon contains exactly what we want
8591 4 : let image_at_gc_horizon = tline
8592 4 : .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
8593 4 : .await
8594 4 : .unwrap()
8595 4 : .into_iter()
8596 68 : .filter(|(k, _)| k.is_metadata_key())
8597 4 : .collect::<Vec<_>>();
8598 4 :
8599 4 : assert_eq!(image_at_gc_horizon.len(), 10);
8600 4 : let expected_result = [
8601 4 : Bytes::from_static(b"value 0@0x10"),
8602 4 : Bytes::from_static(b"value 1@0x20"),
8603 4 : Bytes::from_static(b"value 2@0x30"),
8604 4 : Bytes::from_static(b"value 3@0x10"),
8605 4 : Bytes::from_static(b"value 4@0x10"),
8606 4 : Bytes::from_static(b"value 5@0x20"),
8607 4 : Bytes::from_static(b"value 6@0x20"),
8608 4 : Bytes::from_static(b"value 7@0x10"),
8609 4 : Bytes::from_static(b"value 8@0x10"),
8610 4 : Bytes::from_static(b"value 9@0x10"),
8611 4 : ];
8612 44 : for idx in 0..10 {
8613 40 : assert_eq!(
8614 40 : image_at_gc_horizon[idx],
8615 40 : (get_key(idx as u32), expected_result[idx].clone())
8616 40 : );
8617 4 : }
8618 4 :
8619 4 : // Check if old layers are removed / new layers have the expected LSN
8620 4 : let all_layers = inspect_and_sort(&tline, None).await;
8621 4 : assert_eq!(
8622 4 : all_layers,
8623 4 : vec![
8624 4 : // Image layer at GC horizon
8625 4 : PersistentLayerKey {
8626 4 : key_range: Key::MIN..Key::MAX,
8627 4 : lsn_range: Lsn(0x30)..Lsn(0x31),
8628 4 : is_delta: false
8629 4 : },
8630 4 : // The delta layer below the horizon
8631 4 : PersistentLayerKey {
8632 4 : key_range: get_key(3)..get_key(4),
8633 4 : lsn_range: Lsn(0x30)..Lsn(0x48),
8634 4 : is_delta: true
8635 4 : },
8636 4 : // The delta3 layer that should not be picked for the compaction
8637 4 : PersistentLayerKey {
8638 4 : key_range: get_key(8)..get_key(10),
8639 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
8640 4 : is_delta: true
8641 4 : }
8642 4 : ]
8643 4 : );
8644 4 :
8645 4 : // increase GC horizon and compact again
8646 4 : {
8647 4 : tline
8648 4 : .applied_gc_cutoff_lsn
8649 4 : .lock_for_write()
8650 4 : .store_and_unlock(Lsn(0x40))
8651 4 : .wait()
8652 4 : .await;
8653 4 : // Update GC info
8654 4 : let mut guard = tline.gc_info.write().unwrap();
8655 4 : guard.cutoffs.time = Lsn(0x40);
8656 4 : guard.cutoffs.space = Lsn(0x40);
8657 4 : }
8658 4 : tline
8659 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8660 4 : .await
8661 4 : .unwrap();
8662 4 :
8663 4 : Ok(())
8664 4 : }
8665 :
8666 : #[cfg(feature = "testing")]
8667 : #[tokio::test]
8668 4 : async fn test_neon_test_record() -> anyhow::Result<()> {
8669 4 : let harness = TenantHarness::create("test_neon_test_record").await?;
8670 4 : let (tenant, ctx) = harness.load().await;
8671 4 :
8672 48 : fn get_key(id: u32) -> Key {
8673 48 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8674 48 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8675 48 : key.field6 = id;
8676 48 : key
8677 48 : }
8678 4 :
8679 4 : let delta1 = vec![
8680 4 : (
8681 4 : get_key(1),
8682 4 : Lsn(0x20),
8683 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
8684 4 : ),
8685 4 : (
8686 4 : get_key(1),
8687 4 : Lsn(0x30),
8688 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
8689 4 : ),
8690 4 : (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
8691 4 : (
8692 4 : get_key(2),
8693 4 : Lsn(0x20),
8694 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
8695 4 : ),
8696 4 : (
8697 4 : get_key(2),
8698 4 : Lsn(0x30),
8699 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
8700 4 : ),
8701 4 : (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
8702 4 : (
8703 4 : get_key(3),
8704 4 : Lsn(0x20),
8705 4 : Value::WalRecord(NeonWalRecord::wal_clear("c")),
8706 4 : ),
8707 4 : (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
8708 4 : (
8709 4 : get_key(4),
8710 4 : Lsn(0x20),
8711 4 : Value::WalRecord(NeonWalRecord::wal_init("i")),
8712 4 : ),
8713 4 : ];
8714 4 : let image1 = vec![(get_key(1), "0x10".into())];
8715 4 :
8716 4 : let tline = tenant
8717 4 : .create_test_timeline_with_layers(
8718 4 : TIMELINE_ID,
8719 4 : Lsn(0x10),
8720 4 : DEFAULT_PG_VERSION,
8721 4 : &ctx,
8722 4 : Vec::new(), // in-memory layers
8723 4 : vec![DeltaLayerTestDesc::new_with_inferred_key_range(
8724 4 : Lsn(0x10)..Lsn(0x40),
8725 4 : delta1,
8726 4 : )], // delta layers
8727 4 : vec![(Lsn(0x10), image1)], // image layers
8728 4 : Lsn(0x50),
8729 4 : )
8730 4 : .await?;
8731 4 :
8732 4 : assert_eq!(
8733 4 : tline.get(get_key(1), Lsn(0x50), &ctx).await?,
8734 4 : Bytes::from_static(b"0x10,0x20,0x30")
8735 4 : );
8736 4 : assert_eq!(
8737 4 : tline.get(get_key(2), Lsn(0x50), &ctx).await?,
8738 4 : Bytes::from_static(b"0x10,0x20,0x30")
8739 4 : );
8740 4 :
8741 4 : // Need to remove the limit of "Neon WAL redo requires base image".
8742 4 :
8743 4 : // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
8744 4 : // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
8745 4 :
8746 4 : Ok(())
8747 4 : }
8748 :
8749 : #[tokio::test(start_paused = true)]
8750 4 : async fn test_lsn_lease() -> anyhow::Result<()> {
8751 4 : let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
8752 4 : .await
8753 4 : .unwrap()
8754 4 : .load()
8755 4 : .await;
8756 4 : // Advance to the lsn lease deadline so that GC is not blocked by
8757 4 : // initial transition into AttachedSingle.
8758 4 : tokio::time::advance(tenant.get_lsn_lease_length()).await;
8759 4 : tokio::time::resume();
8760 4 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
8761 4 :
8762 4 : let end_lsn = Lsn(0x100);
8763 4 : let image_layers = (0x20..=0x90)
8764 4 : .step_by(0x10)
8765 32 : .map(|n| {
8766 32 : (
8767 32 : Lsn(n),
8768 32 : vec![(key, test_img(&format!("data key at {:x}", n)))],
8769 32 : )
8770 32 : })
8771 4 : .collect();
8772 4 :
8773 4 : let timeline = tenant
8774 4 : .create_test_timeline_with_layers(
8775 4 : TIMELINE_ID,
8776 4 : Lsn(0x10),
8777 4 : DEFAULT_PG_VERSION,
8778 4 : &ctx,
8779 4 : Vec::new(), // in-memory layers
8780 4 : Vec::new(),
8781 4 : image_layers,
8782 4 : end_lsn,
8783 4 : )
8784 4 : .await?;
8785 4 :
8786 4 : let leased_lsns = [0x30, 0x50, 0x70];
8787 4 : let mut leases = Vec::new();
8788 12 : leased_lsns.iter().for_each(|n| {
8789 12 : leases.push(
8790 12 : timeline
8791 12 : .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
8792 12 : .expect("lease request should succeed"),
8793 12 : );
8794 12 : });
8795 4 :
8796 4 : let updated_lease_0 = timeline
8797 4 : .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
8798 4 : .expect("lease renewal should succeed");
8799 4 : assert_eq!(
8800 4 : updated_lease_0.valid_until, leases[0].valid_until,
8801 4 : " Renewing with shorter lease should not change the lease."
8802 4 : );
8803 4 :
8804 4 : let updated_lease_1 = timeline
8805 4 : .renew_lsn_lease(
8806 4 : Lsn(leased_lsns[1]),
8807 4 : timeline.get_lsn_lease_length() * 2,
8808 4 : &ctx,
8809 4 : )
8810 4 : .expect("lease renewal should succeed");
8811 4 : assert!(
8812 4 : updated_lease_1.valid_until > leases[1].valid_until,
8813 4 : "Renewing with a long lease should renew lease with later expiration time."
8814 4 : );
8815 4 :
8816 4 : // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
8817 4 : info!(
8818 4 : "applied_gc_cutoff_lsn: {}",
8819 0 : *timeline.get_applied_gc_cutoff_lsn()
8820 4 : );
8821 4 : timeline.force_set_disk_consistent_lsn(end_lsn);
8822 4 :
8823 4 : let res = tenant
8824 4 : .gc_iteration(
8825 4 : Some(TIMELINE_ID),
8826 4 : 0,
8827 4 : Duration::ZERO,
8828 4 : &CancellationToken::new(),
8829 4 : &ctx,
8830 4 : )
8831 4 : .await
8832 4 : .unwrap();
8833 4 :
8834 4 : // Keeping everything <= Lsn(0x80) b/c leases:
8835 4 : // 0/10: initdb layer
8836 4 : // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
8837 4 : assert_eq!(res.layers_needed_by_leases, 7);
8838 4 : // Keeping 0/90 b/c it is the latest layer.
8839 4 : assert_eq!(res.layers_not_updated, 1);
8840 4 : // Removed 0/80.
8841 4 : assert_eq!(res.layers_removed, 1);
8842 4 :
8843 4 : // Make lease on a already GC-ed LSN.
8844 4 : // 0/80 does not have a valid lease + is below latest_gc_cutoff
8845 4 : assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
8846 4 : timeline
8847 4 : .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
8848 4 : .expect_err("lease request on GC-ed LSN should fail");
8849 4 :
8850 4 : // Should still be able to renew a currently valid lease
8851 4 : // Assumption: original lease to is still valid for 0/50.
8852 4 : // (use `Timeline::init_lsn_lease` for testing so it always does validation)
8853 4 : timeline
8854 4 : .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
8855 4 : .expect("lease renewal with validation should succeed");
8856 4 :
8857 4 : Ok(())
8858 4 : }
8859 :
8860 : #[cfg(feature = "testing")]
8861 : #[tokio::test]
8862 4 : async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
8863 4 : test_simple_bottom_most_compaction_deltas_helper(
8864 4 : "test_simple_bottom_most_compaction_deltas_1",
8865 4 : false,
8866 4 : )
8867 4 : .await
8868 4 : }
8869 :
8870 : #[cfg(feature = "testing")]
8871 : #[tokio::test]
8872 4 : async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
8873 4 : test_simple_bottom_most_compaction_deltas_helper(
8874 4 : "test_simple_bottom_most_compaction_deltas_2",
8875 4 : true,
8876 4 : )
8877 4 : .await
8878 4 : }
8879 :
8880 : #[cfg(feature = "testing")]
8881 8 : async fn test_simple_bottom_most_compaction_deltas_helper(
8882 8 : test_name: &'static str,
8883 8 : use_delta_bottom_layer: bool,
8884 8 : ) -> anyhow::Result<()> {
8885 8 : let harness = TenantHarness::create(test_name).await?;
8886 8 : let (tenant, ctx) = harness.load().await;
8887 :
8888 552 : fn get_key(id: u32) -> Key {
8889 552 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8890 552 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8891 552 : key.field6 = id;
8892 552 : key
8893 552 : }
8894 :
8895 : // We create
8896 : // - one bottom-most image layer,
8897 : // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
8898 : // - a delta layer D2 crossing the GC horizon with data only below the horizon,
8899 : // - a delta layer D3 above the horizon.
8900 : //
8901 : // | D3 |
8902 : // | D1 |
8903 : // -| |-- gc horizon -----------------
8904 : // | | | D2 |
8905 : // --------- img layer ------------------
8906 : //
8907 : // What we should expact from this compaction is:
8908 : // | D3 |
8909 : // | Part of D1 |
8910 : // --------- img layer with D1+D2 at GC horizon------------------
8911 :
8912 : // img layer at 0x10
8913 8 : let img_layer = (0..10)
8914 80 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
8915 8 : .collect_vec();
8916 8 : // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
8917 8 : let delta4 = (0..10)
8918 80 : .map(|id| {
8919 80 : (
8920 80 : get_key(id),
8921 80 : Lsn(0x08),
8922 80 : Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
8923 80 : )
8924 80 : })
8925 8 : .collect_vec();
8926 8 :
8927 8 : let delta1 = vec![
8928 8 : (
8929 8 : get_key(1),
8930 8 : Lsn(0x20),
8931 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8932 8 : ),
8933 8 : (
8934 8 : get_key(2),
8935 8 : Lsn(0x30),
8936 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
8937 8 : ),
8938 8 : (
8939 8 : get_key(3),
8940 8 : Lsn(0x28),
8941 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
8942 8 : ),
8943 8 : (
8944 8 : get_key(3),
8945 8 : Lsn(0x30),
8946 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
8947 8 : ),
8948 8 : (
8949 8 : get_key(3),
8950 8 : Lsn(0x40),
8951 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
8952 8 : ),
8953 8 : ];
8954 8 : let delta2 = vec![
8955 8 : (
8956 8 : get_key(5),
8957 8 : Lsn(0x20),
8958 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8959 8 : ),
8960 8 : (
8961 8 : get_key(6),
8962 8 : Lsn(0x20),
8963 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8964 8 : ),
8965 8 : ];
8966 8 : let delta3 = vec![
8967 8 : (
8968 8 : get_key(8),
8969 8 : Lsn(0x48),
8970 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
8971 8 : ),
8972 8 : (
8973 8 : get_key(9),
8974 8 : Lsn(0x48),
8975 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
8976 8 : ),
8977 8 : ];
8978 :
8979 8 : let tline = if use_delta_bottom_layer {
8980 4 : tenant
8981 4 : .create_test_timeline_with_layers(
8982 4 : TIMELINE_ID,
8983 4 : Lsn(0x08),
8984 4 : DEFAULT_PG_VERSION,
8985 4 : &ctx,
8986 4 : Vec::new(), // in-memory layers
8987 4 : vec![
8988 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8989 4 : Lsn(0x08)..Lsn(0x10),
8990 4 : delta4,
8991 4 : ),
8992 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8993 4 : Lsn(0x20)..Lsn(0x48),
8994 4 : delta1,
8995 4 : ),
8996 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8997 4 : Lsn(0x20)..Lsn(0x48),
8998 4 : delta2,
8999 4 : ),
9000 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9001 4 : Lsn(0x48)..Lsn(0x50),
9002 4 : delta3,
9003 4 : ),
9004 4 : ], // delta layers
9005 4 : vec![], // image layers
9006 4 : Lsn(0x50),
9007 4 : )
9008 4 : .await?
9009 : } else {
9010 4 : tenant
9011 4 : .create_test_timeline_with_layers(
9012 4 : TIMELINE_ID,
9013 4 : Lsn(0x10),
9014 4 : DEFAULT_PG_VERSION,
9015 4 : &ctx,
9016 4 : Vec::new(), // in-memory layers
9017 4 : vec![
9018 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9019 4 : Lsn(0x10)..Lsn(0x48),
9020 4 : delta1,
9021 4 : ),
9022 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9023 4 : Lsn(0x10)..Lsn(0x48),
9024 4 : delta2,
9025 4 : ),
9026 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9027 4 : Lsn(0x48)..Lsn(0x50),
9028 4 : delta3,
9029 4 : ),
9030 4 : ], // delta layers
9031 4 : vec![(Lsn(0x10), img_layer)], // image layers
9032 4 : Lsn(0x50),
9033 4 : )
9034 4 : .await?
9035 : };
9036 : {
9037 8 : tline
9038 8 : .applied_gc_cutoff_lsn
9039 8 : .lock_for_write()
9040 8 : .store_and_unlock(Lsn(0x30))
9041 8 : .wait()
9042 8 : .await;
9043 : // Update GC info
9044 8 : let mut guard = tline.gc_info.write().unwrap();
9045 8 : *guard = GcInfo {
9046 8 : retain_lsns: vec![],
9047 8 : cutoffs: GcCutoffs {
9048 8 : time: Lsn(0x30),
9049 8 : space: Lsn(0x30),
9050 8 : },
9051 8 : leases: Default::default(),
9052 8 : within_ancestor_pitr: false,
9053 8 : };
9054 8 : }
9055 8 :
9056 8 : let expected_result = [
9057 8 : Bytes::from_static(b"value 0@0x10"),
9058 8 : Bytes::from_static(b"value 1@0x10@0x20"),
9059 8 : Bytes::from_static(b"value 2@0x10@0x30"),
9060 8 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
9061 8 : Bytes::from_static(b"value 4@0x10"),
9062 8 : Bytes::from_static(b"value 5@0x10@0x20"),
9063 8 : Bytes::from_static(b"value 6@0x10@0x20"),
9064 8 : Bytes::from_static(b"value 7@0x10"),
9065 8 : Bytes::from_static(b"value 8@0x10@0x48"),
9066 8 : Bytes::from_static(b"value 9@0x10@0x48"),
9067 8 : ];
9068 8 :
9069 8 : let expected_result_at_gc_horizon = [
9070 8 : Bytes::from_static(b"value 0@0x10"),
9071 8 : Bytes::from_static(b"value 1@0x10@0x20"),
9072 8 : Bytes::from_static(b"value 2@0x10@0x30"),
9073 8 : Bytes::from_static(b"value 3@0x10@0x28@0x30"),
9074 8 : Bytes::from_static(b"value 4@0x10"),
9075 8 : Bytes::from_static(b"value 5@0x10@0x20"),
9076 8 : Bytes::from_static(b"value 6@0x10@0x20"),
9077 8 : Bytes::from_static(b"value 7@0x10"),
9078 8 : Bytes::from_static(b"value 8@0x10"),
9079 8 : Bytes::from_static(b"value 9@0x10"),
9080 8 : ];
9081 :
9082 88 : for idx in 0..10 {
9083 80 : assert_eq!(
9084 80 : tline
9085 80 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9086 80 : .await
9087 80 : .unwrap(),
9088 80 : &expected_result[idx]
9089 : );
9090 80 : assert_eq!(
9091 80 : tline
9092 80 : .get(get_key(idx as u32), Lsn(0x30), &ctx)
9093 80 : .await
9094 80 : .unwrap(),
9095 80 : &expected_result_at_gc_horizon[idx]
9096 : );
9097 : }
9098 :
9099 8 : let cancel = CancellationToken::new();
9100 8 : tline
9101 8 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9102 8 : .await
9103 8 : .unwrap();
9104 :
9105 88 : for idx in 0..10 {
9106 80 : assert_eq!(
9107 80 : tline
9108 80 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9109 80 : .await
9110 80 : .unwrap(),
9111 80 : &expected_result[idx]
9112 : );
9113 80 : assert_eq!(
9114 80 : tline
9115 80 : .get(get_key(idx as u32), Lsn(0x30), &ctx)
9116 80 : .await
9117 80 : .unwrap(),
9118 80 : &expected_result_at_gc_horizon[idx]
9119 : );
9120 : }
9121 :
9122 : // increase GC horizon and compact again
9123 : {
9124 8 : tline
9125 8 : .applied_gc_cutoff_lsn
9126 8 : .lock_for_write()
9127 8 : .store_and_unlock(Lsn(0x40))
9128 8 : .wait()
9129 8 : .await;
9130 : // Update GC info
9131 8 : let mut guard = tline.gc_info.write().unwrap();
9132 8 : guard.cutoffs.time = Lsn(0x40);
9133 8 : guard.cutoffs.space = Lsn(0x40);
9134 8 : }
9135 8 : tline
9136 8 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9137 8 : .await
9138 8 : .unwrap();
9139 8 :
9140 8 : Ok(())
9141 8 : }
9142 :
9143 : #[cfg(feature = "testing")]
9144 : #[tokio::test]
9145 4 : async fn test_generate_key_retention() -> anyhow::Result<()> {
9146 4 : let harness = TenantHarness::create("test_generate_key_retention").await?;
9147 4 : let (tenant, ctx) = harness.load().await;
9148 4 : let tline = tenant
9149 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
9150 4 : .await?;
9151 4 : tline.force_advance_lsn(Lsn(0x70));
9152 4 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
9153 4 : let history = vec![
9154 4 : (
9155 4 : key,
9156 4 : Lsn(0x10),
9157 4 : Value::WalRecord(NeonWalRecord::wal_init("0x10")),
9158 4 : ),
9159 4 : (
9160 4 : key,
9161 4 : Lsn(0x20),
9162 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9163 4 : ),
9164 4 : (
9165 4 : key,
9166 4 : Lsn(0x30),
9167 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9168 4 : ),
9169 4 : (
9170 4 : key,
9171 4 : Lsn(0x40),
9172 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9173 4 : ),
9174 4 : (
9175 4 : key,
9176 4 : Lsn(0x50),
9177 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9178 4 : ),
9179 4 : (
9180 4 : key,
9181 4 : Lsn(0x60),
9182 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9183 4 : ),
9184 4 : (
9185 4 : key,
9186 4 : Lsn(0x70),
9187 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9188 4 : ),
9189 4 : (
9190 4 : key,
9191 4 : Lsn(0x80),
9192 4 : Value::Image(Bytes::copy_from_slice(
9193 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9194 4 : )),
9195 4 : ),
9196 4 : (
9197 4 : key,
9198 4 : Lsn(0x90),
9199 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9200 4 : ),
9201 4 : ];
9202 4 : let res = tline
9203 4 : .generate_key_retention(
9204 4 : key,
9205 4 : &history,
9206 4 : Lsn(0x60),
9207 4 : &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
9208 4 : 3,
9209 4 : None,
9210 4 : )
9211 4 : .await
9212 4 : .unwrap();
9213 4 : let expected_res = KeyHistoryRetention {
9214 4 : below_horizon: vec![
9215 4 : (
9216 4 : Lsn(0x20),
9217 4 : KeyLogAtLsn(vec![(
9218 4 : Lsn(0x20),
9219 4 : Value::Image(Bytes::from_static(b"0x10;0x20")),
9220 4 : )]),
9221 4 : ),
9222 4 : (
9223 4 : Lsn(0x40),
9224 4 : KeyLogAtLsn(vec![
9225 4 : (
9226 4 : Lsn(0x30),
9227 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9228 4 : ),
9229 4 : (
9230 4 : Lsn(0x40),
9231 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9232 4 : ),
9233 4 : ]),
9234 4 : ),
9235 4 : (
9236 4 : Lsn(0x50),
9237 4 : KeyLogAtLsn(vec![(
9238 4 : Lsn(0x50),
9239 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
9240 4 : )]),
9241 4 : ),
9242 4 : (
9243 4 : Lsn(0x60),
9244 4 : KeyLogAtLsn(vec![(
9245 4 : Lsn(0x60),
9246 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9247 4 : )]),
9248 4 : ),
9249 4 : ],
9250 4 : above_horizon: KeyLogAtLsn(vec![
9251 4 : (
9252 4 : Lsn(0x70),
9253 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9254 4 : ),
9255 4 : (
9256 4 : Lsn(0x80),
9257 4 : Value::Image(Bytes::copy_from_slice(
9258 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9259 4 : )),
9260 4 : ),
9261 4 : (
9262 4 : Lsn(0x90),
9263 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9264 4 : ),
9265 4 : ]),
9266 4 : };
9267 4 : assert_eq!(res, expected_res);
9268 4 :
9269 4 : // We expect GC-compaction to run with the original GC. This would create a situation that
9270 4 : // the original GC algorithm removes some delta layers b/c there are full image coverage,
9271 4 : // therefore causing some keys to have an incomplete history below the lowest retain LSN.
9272 4 : // For example, we have
9273 4 : // ```plain
9274 4 : // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
9275 4 : // ```
9276 4 : // Now the GC horizon moves up, and we have
9277 4 : // ```plain
9278 4 : // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
9279 4 : // ```
9280 4 : // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
9281 4 : // We will end up with
9282 4 : // ```plain
9283 4 : // delta @ 0x30, image @ 0x40 (gc_horizon)
9284 4 : // ```
9285 4 : // Now we run the GC-compaction, and this key does not have a full history.
9286 4 : // We should be able to handle this partial history and drop everything before the
9287 4 : // gc_horizon image.
9288 4 :
9289 4 : let history = vec![
9290 4 : (
9291 4 : key,
9292 4 : Lsn(0x20),
9293 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9294 4 : ),
9295 4 : (
9296 4 : key,
9297 4 : Lsn(0x30),
9298 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9299 4 : ),
9300 4 : (
9301 4 : key,
9302 4 : Lsn(0x40),
9303 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
9304 4 : ),
9305 4 : (
9306 4 : key,
9307 4 : Lsn(0x50),
9308 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9309 4 : ),
9310 4 : (
9311 4 : key,
9312 4 : Lsn(0x60),
9313 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9314 4 : ),
9315 4 : (
9316 4 : key,
9317 4 : Lsn(0x70),
9318 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9319 4 : ),
9320 4 : (
9321 4 : key,
9322 4 : Lsn(0x80),
9323 4 : Value::Image(Bytes::copy_from_slice(
9324 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9325 4 : )),
9326 4 : ),
9327 4 : (
9328 4 : key,
9329 4 : Lsn(0x90),
9330 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9331 4 : ),
9332 4 : ];
9333 4 : let res = tline
9334 4 : .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
9335 4 : .await
9336 4 : .unwrap();
9337 4 : let expected_res = KeyHistoryRetention {
9338 4 : below_horizon: vec![
9339 4 : (
9340 4 : Lsn(0x40),
9341 4 : KeyLogAtLsn(vec![(
9342 4 : Lsn(0x40),
9343 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
9344 4 : )]),
9345 4 : ),
9346 4 : (
9347 4 : Lsn(0x50),
9348 4 : KeyLogAtLsn(vec![(
9349 4 : Lsn(0x50),
9350 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9351 4 : )]),
9352 4 : ),
9353 4 : (
9354 4 : Lsn(0x60),
9355 4 : KeyLogAtLsn(vec![(
9356 4 : Lsn(0x60),
9357 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9358 4 : )]),
9359 4 : ),
9360 4 : ],
9361 4 : above_horizon: KeyLogAtLsn(vec![
9362 4 : (
9363 4 : Lsn(0x70),
9364 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9365 4 : ),
9366 4 : (
9367 4 : Lsn(0x80),
9368 4 : Value::Image(Bytes::copy_from_slice(
9369 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9370 4 : )),
9371 4 : ),
9372 4 : (
9373 4 : Lsn(0x90),
9374 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9375 4 : ),
9376 4 : ]),
9377 4 : };
9378 4 : assert_eq!(res, expected_res);
9379 4 :
9380 4 : // In case of branch compaction, the branch itself does not have the full history, and we need to provide
9381 4 : // the ancestor image in the test case.
9382 4 :
9383 4 : let history = vec![
9384 4 : (
9385 4 : key,
9386 4 : Lsn(0x20),
9387 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9388 4 : ),
9389 4 : (
9390 4 : key,
9391 4 : Lsn(0x30),
9392 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9393 4 : ),
9394 4 : (
9395 4 : key,
9396 4 : Lsn(0x40),
9397 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9398 4 : ),
9399 4 : (
9400 4 : key,
9401 4 : Lsn(0x70),
9402 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9403 4 : ),
9404 4 : ];
9405 4 : let res = tline
9406 4 : .generate_key_retention(
9407 4 : key,
9408 4 : &history,
9409 4 : Lsn(0x60),
9410 4 : &[],
9411 4 : 3,
9412 4 : Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
9413 4 : )
9414 4 : .await
9415 4 : .unwrap();
9416 4 : let expected_res = KeyHistoryRetention {
9417 4 : below_horizon: vec![(
9418 4 : Lsn(0x60),
9419 4 : KeyLogAtLsn(vec![(
9420 4 : Lsn(0x60),
9421 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
9422 4 : )]),
9423 4 : )],
9424 4 : above_horizon: KeyLogAtLsn(vec![(
9425 4 : Lsn(0x70),
9426 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9427 4 : )]),
9428 4 : };
9429 4 : assert_eq!(res, expected_res);
9430 4 :
9431 4 : let history = vec![
9432 4 : (
9433 4 : key,
9434 4 : Lsn(0x20),
9435 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9436 4 : ),
9437 4 : (
9438 4 : key,
9439 4 : Lsn(0x40),
9440 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9441 4 : ),
9442 4 : (
9443 4 : key,
9444 4 : Lsn(0x60),
9445 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9446 4 : ),
9447 4 : (
9448 4 : key,
9449 4 : Lsn(0x70),
9450 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9451 4 : ),
9452 4 : ];
9453 4 : let res = tline
9454 4 : .generate_key_retention(
9455 4 : key,
9456 4 : &history,
9457 4 : Lsn(0x60),
9458 4 : &[Lsn(0x30)],
9459 4 : 3,
9460 4 : Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
9461 4 : )
9462 4 : .await
9463 4 : .unwrap();
9464 4 : let expected_res = KeyHistoryRetention {
9465 4 : below_horizon: vec![
9466 4 : (
9467 4 : Lsn(0x30),
9468 4 : KeyLogAtLsn(vec![(
9469 4 : Lsn(0x20),
9470 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9471 4 : )]),
9472 4 : ),
9473 4 : (
9474 4 : Lsn(0x60),
9475 4 : KeyLogAtLsn(vec![(
9476 4 : Lsn(0x60),
9477 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
9478 4 : )]),
9479 4 : ),
9480 4 : ],
9481 4 : above_horizon: KeyLogAtLsn(vec![(
9482 4 : Lsn(0x70),
9483 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9484 4 : )]),
9485 4 : };
9486 4 : assert_eq!(res, expected_res);
9487 4 :
9488 4 : Ok(())
9489 4 : }
9490 :
9491 : #[cfg(feature = "testing")]
9492 : #[tokio::test]
9493 4 : async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
9494 4 : let harness =
9495 4 : TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
9496 4 : let (tenant, ctx) = harness.load().await;
9497 4 :
9498 1036 : fn get_key(id: u32) -> Key {
9499 1036 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
9500 1036 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
9501 1036 : key.field6 = id;
9502 1036 : key
9503 1036 : }
9504 4 :
9505 4 : let img_layer = (0..10)
9506 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9507 4 : .collect_vec();
9508 4 :
9509 4 : let delta1 = vec![
9510 4 : (
9511 4 : get_key(1),
9512 4 : Lsn(0x20),
9513 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9514 4 : ),
9515 4 : (
9516 4 : get_key(2),
9517 4 : Lsn(0x30),
9518 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9519 4 : ),
9520 4 : (
9521 4 : get_key(3),
9522 4 : Lsn(0x28),
9523 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9524 4 : ),
9525 4 : (
9526 4 : get_key(3),
9527 4 : Lsn(0x30),
9528 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9529 4 : ),
9530 4 : (
9531 4 : get_key(3),
9532 4 : Lsn(0x40),
9533 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
9534 4 : ),
9535 4 : ];
9536 4 : let delta2 = vec![
9537 4 : (
9538 4 : get_key(5),
9539 4 : Lsn(0x20),
9540 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9541 4 : ),
9542 4 : (
9543 4 : get_key(6),
9544 4 : Lsn(0x20),
9545 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9546 4 : ),
9547 4 : ];
9548 4 : let delta3 = vec![
9549 4 : (
9550 4 : get_key(8),
9551 4 : Lsn(0x48),
9552 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9553 4 : ),
9554 4 : (
9555 4 : get_key(9),
9556 4 : Lsn(0x48),
9557 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9558 4 : ),
9559 4 : ];
9560 4 :
9561 4 : let tline = tenant
9562 4 : .create_test_timeline_with_layers(
9563 4 : TIMELINE_ID,
9564 4 : Lsn(0x10),
9565 4 : DEFAULT_PG_VERSION,
9566 4 : &ctx,
9567 4 : Vec::new(), // in-memory layers
9568 4 : vec![
9569 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
9570 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
9571 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
9572 4 : ], // delta layers
9573 4 : vec![(Lsn(0x10), img_layer)], // image layers
9574 4 : Lsn(0x50),
9575 4 : )
9576 4 : .await?;
9577 4 : {
9578 4 : tline
9579 4 : .applied_gc_cutoff_lsn
9580 4 : .lock_for_write()
9581 4 : .store_and_unlock(Lsn(0x30))
9582 4 : .wait()
9583 4 : .await;
9584 4 : // Update GC info
9585 4 : let mut guard = tline.gc_info.write().unwrap();
9586 4 : *guard = GcInfo {
9587 4 : retain_lsns: vec![
9588 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
9589 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
9590 4 : ],
9591 4 : cutoffs: GcCutoffs {
9592 4 : time: Lsn(0x30),
9593 4 : space: Lsn(0x30),
9594 4 : },
9595 4 : leases: Default::default(),
9596 4 : within_ancestor_pitr: false,
9597 4 : };
9598 4 : }
9599 4 :
9600 4 : let expected_result = [
9601 4 : Bytes::from_static(b"value 0@0x10"),
9602 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9603 4 : Bytes::from_static(b"value 2@0x10@0x30"),
9604 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
9605 4 : Bytes::from_static(b"value 4@0x10"),
9606 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9607 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9608 4 : Bytes::from_static(b"value 7@0x10"),
9609 4 : Bytes::from_static(b"value 8@0x10@0x48"),
9610 4 : Bytes::from_static(b"value 9@0x10@0x48"),
9611 4 : ];
9612 4 :
9613 4 : let expected_result_at_gc_horizon = [
9614 4 : Bytes::from_static(b"value 0@0x10"),
9615 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9616 4 : Bytes::from_static(b"value 2@0x10@0x30"),
9617 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30"),
9618 4 : Bytes::from_static(b"value 4@0x10"),
9619 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9620 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9621 4 : Bytes::from_static(b"value 7@0x10"),
9622 4 : Bytes::from_static(b"value 8@0x10"),
9623 4 : Bytes::from_static(b"value 9@0x10"),
9624 4 : ];
9625 4 :
9626 4 : let expected_result_at_lsn_20 = [
9627 4 : Bytes::from_static(b"value 0@0x10"),
9628 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9629 4 : Bytes::from_static(b"value 2@0x10"),
9630 4 : Bytes::from_static(b"value 3@0x10"),
9631 4 : Bytes::from_static(b"value 4@0x10"),
9632 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9633 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9634 4 : Bytes::from_static(b"value 7@0x10"),
9635 4 : Bytes::from_static(b"value 8@0x10"),
9636 4 : Bytes::from_static(b"value 9@0x10"),
9637 4 : ];
9638 4 :
9639 4 : let expected_result_at_lsn_10 = [
9640 4 : Bytes::from_static(b"value 0@0x10"),
9641 4 : Bytes::from_static(b"value 1@0x10"),
9642 4 : Bytes::from_static(b"value 2@0x10"),
9643 4 : Bytes::from_static(b"value 3@0x10"),
9644 4 : Bytes::from_static(b"value 4@0x10"),
9645 4 : Bytes::from_static(b"value 5@0x10"),
9646 4 : Bytes::from_static(b"value 6@0x10"),
9647 4 : Bytes::from_static(b"value 7@0x10"),
9648 4 : Bytes::from_static(b"value 8@0x10"),
9649 4 : Bytes::from_static(b"value 9@0x10"),
9650 4 : ];
9651 4 :
9652 24 : let verify_result = || async {
9653 24 : let gc_horizon = {
9654 24 : let gc_info = tline.gc_info.read().unwrap();
9655 24 : gc_info.cutoffs.time
9656 4 : };
9657 264 : for idx in 0..10 {
9658 240 : assert_eq!(
9659 240 : tline
9660 240 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9661 240 : .await
9662 240 : .unwrap(),
9663 240 : &expected_result[idx]
9664 4 : );
9665 240 : assert_eq!(
9666 240 : tline
9667 240 : .get(get_key(idx as u32), gc_horizon, &ctx)
9668 240 : .await
9669 240 : .unwrap(),
9670 240 : &expected_result_at_gc_horizon[idx]
9671 4 : );
9672 240 : assert_eq!(
9673 240 : tline
9674 240 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
9675 240 : .await
9676 240 : .unwrap(),
9677 240 : &expected_result_at_lsn_20[idx]
9678 4 : );
9679 240 : assert_eq!(
9680 240 : tline
9681 240 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
9682 240 : .await
9683 240 : .unwrap(),
9684 240 : &expected_result_at_lsn_10[idx]
9685 4 : );
9686 4 : }
9687 48 : };
9688 4 :
9689 4 : verify_result().await;
9690 4 :
9691 4 : let cancel = CancellationToken::new();
9692 4 : let mut dryrun_flags = EnumSet::new();
9693 4 : dryrun_flags.insert(CompactFlags::DryRun);
9694 4 :
9695 4 : tline
9696 4 : .compact_with_gc(
9697 4 : &cancel,
9698 4 : CompactOptions {
9699 4 : flags: dryrun_flags,
9700 4 : ..Default::default()
9701 4 : },
9702 4 : &ctx,
9703 4 : )
9704 4 : .await
9705 4 : .unwrap();
9706 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
9707 4 : // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
9708 4 : verify_result().await;
9709 4 :
9710 4 : tline
9711 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9712 4 : .await
9713 4 : .unwrap();
9714 4 : verify_result().await;
9715 4 :
9716 4 : // compact again
9717 4 : tline
9718 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9719 4 : .await
9720 4 : .unwrap();
9721 4 : verify_result().await;
9722 4 :
9723 4 : // increase GC horizon and compact again
9724 4 : {
9725 4 : tline
9726 4 : .applied_gc_cutoff_lsn
9727 4 : .lock_for_write()
9728 4 : .store_and_unlock(Lsn(0x38))
9729 4 : .wait()
9730 4 : .await;
9731 4 : // Update GC info
9732 4 : let mut guard = tline.gc_info.write().unwrap();
9733 4 : guard.cutoffs.time = Lsn(0x38);
9734 4 : guard.cutoffs.space = Lsn(0x38);
9735 4 : }
9736 4 : tline
9737 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9738 4 : .await
9739 4 : .unwrap();
9740 4 : verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
9741 4 :
9742 4 : // not increasing the GC horizon and compact again
9743 4 : tline
9744 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9745 4 : .await
9746 4 : .unwrap();
9747 4 : verify_result().await;
9748 4 :
9749 4 : Ok(())
9750 4 : }
9751 :
9752 : #[cfg(feature = "testing")]
9753 : #[tokio::test]
9754 4 : async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
9755 4 : {
9756 4 : let harness =
9757 4 : TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
9758 4 : .await?;
9759 4 : let (tenant, ctx) = harness.load().await;
9760 4 :
9761 704 : fn get_key(id: u32) -> Key {
9762 704 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
9763 704 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
9764 704 : key.field6 = id;
9765 704 : key
9766 704 : }
9767 4 :
9768 4 : let img_layer = (0..10)
9769 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9770 4 : .collect_vec();
9771 4 :
9772 4 : let delta1 = vec![
9773 4 : (
9774 4 : get_key(1),
9775 4 : Lsn(0x20),
9776 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9777 4 : ),
9778 4 : (
9779 4 : get_key(1),
9780 4 : Lsn(0x28),
9781 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9782 4 : ),
9783 4 : ];
9784 4 : let delta2 = vec![
9785 4 : (
9786 4 : get_key(1),
9787 4 : Lsn(0x30),
9788 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9789 4 : ),
9790 4 : (
9791 4 : get_key(1),
9792 4 : Lsn(0x38),
9793 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
9794 4 : ),
9795 4 : ];
9796 4 : let delta3 = vec![
9797 4 : (
9798 4 : get_key(8),
9799 4 : Lsn(0x48),
9800 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9801 4 : ),
9802 4 : (
9803 4 : get_key(9),
9804 4 : Lsn(0x48),
9805 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9806 4 : ),
9807 4 : ];
9808 4 :
9809 4 : let tline = tenant
9810 4 : .create_test_timeline_with_layers(
9811 4 : TIMELINE_ID,
9812 4 : Lsn(0x10),
9813 4 : DEFAULT_PG_VERSION,
9814 4 : &ctx,
9815 4 : Vec::new(), // in-memory layers
9816 4 : vec![
9817 4 : // delta1 and delta 2 only contain a single key but multiple updates
9818 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
9819 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
9820 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
9821 4 : ], // delta layers
9822 4 : vec![(Lsn(0x10), img_layer)], // image layers
9823 4 : Lsn(0x50),
9824 4 : )
9825 4 : .await?;
9826 4 : {
9827 4 : tline
9828 4 : .applied_gc_cutoff_lsn
9829 4 : .lock_for_write()
9830 4 : .store_and_unlock(Lsn(0x30))
9831 4 : .wait()
9832 4 : .await;
9833 4 : // Update GC info
9834 4 : let mut guard = tline.gc_info.write().unwrap();
9835 4 : *guard = GcInfo {
9836 4 : retain_lsns: vec![
9837 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
9838 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
9839 4 : ],
9840 4 : cutoffs: GcCutoffs {
9841 4 : time: Lsn(0x30),
9842 4 : space: Lsn(0x30),
9843 4 : },
9844 4 : leases: Default::default(),
9845 4 : within_ancestor_pitr: false,
9846 4 : };
9847 4 : }
9848 4 :
9849 4 : let expected_result = [
9850 4 : Bytes::from_static(b"value 0@0x10"),
9851 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
9852 4 : Bytes::from_static(b"value 2@0x10"),
9853 4 : Bytes::from_static(b"value 3@0x10"),
9854 4 : Bytes::from_static(b"value 4@0x10"),
9855 4 : Bytes::from_static(b"value 5@0x10"),
9856 4 : Bytes::from_static(b"value 6@0x10"),
9857 4 : Bytes::from_static(b"value 7@0x10"),
9858 4 : Bytes::from_static(b"value 8@0x10@0x48"),
9859 4 : Bytes::from_static(b"value 9@0x10@0x48"),
9860 4 : ];
9861 4 :
9862 4 : let expected_result_at_gc_horizon = [
9863 4 : Bytes::from_static(b"value 0@0x10"),
9864 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
9865 4 : Bytes::from_static(b"value 2@0x10"),
9866 4 : Bytes::from_static(b"value 3@0x10"),
9867 4 : Bytes::from_static(b"value 4@0x10"),
9868 4 : Bytes::from_static(b"value 5@0x10"),
9869 4 : Bytes::from_static(b"value 6@0x10"),
9870 4 : Bytes::from_static(b"value 7@0x10"),
9871 4 : Bytes::from_static(b"value 8@0x10"),
9872 4 : Bytes::from_static(b"value 9@0x10"),
9873 4 : ];
9874 4 :
9875 4 : let expected_result_at_lsn_20 = [
9876 4 : Bytes::from_static(b"value 0@0x10"),
9877 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9878 4 : Bytes::from_static(b"value 2@0x10"),
9879 4 : Bytes::from_static(b"value 3@0x10"),
9880 4 : Bytes::from_static(b"value 4@0x10"),
9881 4 : Bytes::from_static(b"value 5@0x10"),
9882 4 : Bytes::from_static(b"value 6@0x10"),
9883 4 : Bytes::from_static(b"value 7@0x10"),
9884 4 : Bytes::from_static(b"value 8@0x10"),
9885 4 : Bytes::from_static(b"value 9@0x10"),
9886 4 : ];
9887 4 :
9888 4 : let expected_result_at_lsn_10 = [
9889 4 : Bytes::from_static(b"value 0@0x10"),
9890 4 : Bytes::from_static(b"value 1@0x10"),
9891 4 : Bytes::from_static(b"value 2@0x10"),
9892 4 : Bytes::from_static(b"value 3@0x10"),
9893 4 : Bytes::from_static(b"value 4@0x10"),
9894 4 : Bytes::from_static(b"value 5@0x10"),
9895 4 : Bytes::from_static(b"value 6@0x10"),
9896 4 : Bytes::from_static(b"value 7@0x10"),
9897 4 : Bytes::from_static(b"value 8@0x10"),
9898 4 : Bytes::from_static(b"value 9@0x10"),
9899 4 : ];
9900 4 :
9901 16 : let verify_result = || async {
9902 16 : let gc_horizon = {
9903 16 : let gc_info = tline.gc_info.read().unwrap();
9904 16 : gc_info.cutoffs.time
9905 4 : };
9906 176 : for idx in 0..10 {
9907 160 : assert_eq!(
9908 160 : tline
9909 160 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9910 160 : .await
9911 160 : .unwrap(),
9912 160 : &expected_result[idx]
9913 4 : );
9914 160 : assert_eq!(
9915 160 : tline
9916 160 : .get(get_key(idx as u32), gc_horizon, &ctx)
9917 160 : .await
9918 160 : .unwrap(),
9919 160 : &expected_result_at_gc_horizon[idx]
9920 4 : );
9921 160 : assert_eq!(
9922 160 : tline
9923 160 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
9924 160 : .await
9925 160 : .unwrap(),
9926 160 : &expected_result_at_lsn_20[idx]
9927 4 : );
9928 160 : assert_eq!(
9929 160 : tline
9930 160 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
9931 160 : .await
9932 160 : .unwrap(),
9933 160 : &expected_result_at_lsn_10[idx]
9934 4 : );
9935 4 : }
9936 32 : };
9937 4 :
9938 4 : verify_result().await;
9939 4 :
9940 4 : let cancel = CancellationToken::new();
9941 4 : let mut dryrun_flags = EnumSet::new();
9942 4 : dryrun_flags.insert(CompactFlags::DryRun);
9943 4 :
9944 4 : tline
9945 4 : .compact_with_gc(
9946 4 : &cancel,
9947 4 : CompactOptions {
9948 4 : flags: dryrun_flags,
9949 4 : ..Default::default()
9950 4 : },
9951 4 : &ctx,
9952 4 : )
9953 4 : .await
9954 4 : .unwrap();
9955 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
9956 4 : // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
9957 4 : verify_result().await;
9958 4 :
9959 4 : tline
9960 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9961 4 : .await
9962 4 : .unwrap();
9963 4 : verify_result().await;
9964 4 :
9965 4 : // compact again
9966 4 : tline
9967 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9968 4 : .await
9969 4 : .unwrap();
9970 4 : verify_result().await;
9971 4 :
9972 4 : Ok(())
9973 4 : }
9974 :
9975 : #[cfg(feature = "testing")]
9976 : #[tokio::test]
9977 4 : async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
9978 4 : use models::CompactLsnRange;
9979 4 :
9980 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
9981 4 : let (tenant, ctx) = harness.load().await;
9982 4 :
9983 332 : fn get_key(id: u32) -> Key {
9984 332 : let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
9985 332 : key.field6 = id;
9986 332 : key
9987 332 : }
9988 4 :
9989 4 : let img_layer = (0..10)
9990 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9991 4 : .collect_vec();
9992 4 :
9993 4 : let delta1 = vec![
9994 4 : (
9995 4 : get_key(1),
9996 4 : Lsn(0x20),
9997 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9998 4 : ),
9999 4 : (
10000 4 : get_key(2),
10001 4 : Lsn(0x30),
10002 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
10003 4 : ),
10004 4 : (
10005 4 : get_key(3),
10006 4 : Lsn(0x28),
10007 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
10008 4 : ),
10009 4 : (
10010 4 : get_key(3),
10011 4 : Lsn(0x30),
10012 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
10013 4 : ),
10014 4 : (
10015 4 : get_key(3),
10016 4 : Lsn(0x40),
10017 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
10018 4 : ),
10019 4 : ];
10020 4 : let delta2 = vec![
10021 4 : (
10022 4 : get_key(5),
10023 4 : Lsn(0x20),
10024 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10025 4 : ),
10026 4 : (
10027 4 : get_key(6),
10028 4 : Lsn(0x20),
10029 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10030 4 : ),
10031 4 : ];
10032 4 : let delta3 = vec![
10033 4 : (
10034 4 : get_key(8),
10035 4 : Lsn(0x48),
10036 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10037 4 : ),
10038 4 : (
10039 4 : get_key(9),
10040 4 : Lsn(0x48),
10041 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10042 4 : ),
10043 4 : ];
10044 4 :
10045 4 : let parent_tline = tenant
10046 4 : .create_test_timeline_with_layers(
10047 4 : TIMELINE_ID,
10048 4 : Lsn(0x10),
10049 4 : DEFAULT_PG_VERSION,
10050 4 : &ctx,
10051 4 : vec![], // in-memory layers
10052 4 : vec![], // delta layers
10053 4 : vec![(Lsn(0x18), img_layer)], // image layers
10054 4 : Lsn(0x18),
10055 4 : )
10056 4 : .await?;
10057 4 :
10058 4 : parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
10059 4 :
10060 4 : let branch_tline = tenant
10061 4 : .branch_timeline_test_with_layers(
10062 4 : &parent_tline,
10063 4 : NEW_TIMELINE_ID,
10064 4 : Some(Lsn(0x18)),
10065 4 : &ctx,
10066 4 : vec![
10067 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
10068 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
10069 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
10070 4 : ], // delta layers
10071 4 : vec![], // image layers
10072 4 : Lsn(0x50),
10073 4 : )
10074 4 : .await?;
10075 4 :
10076 4 : branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
10077 4 :
10078 4 : {
10079 4 : parent_tline
10080 4 : .applied_gc_cutoff_lsn
10081 4 : .lock_for_write()
10082 4 : .store_and_unlock(Lsn(0x10))
10083 4 : .wait()
10084 4 : .await;
10085 4 : // Update GC info
10086 4 : let mut guard = parent_tline.gc_info.write().unwrap();
10087 4 : *guard = GcInfo {
10088 4 : retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
10089 4 : cutoffs: GcCutoffs {
10090 4 : time: Lsn(0x10),
10091 4 : space: Lsn(0x10),
10092 4 : },
10093 4 : leases: Default::default(),
10094 4 : within_ancestor_pitr: false,
10095 4 : };
10096 4 : }
10097 4 :
10098 4 : {
10099 4 : branch_tline
10100 4 : .applied_gc_cutoff_lsn
10101 4 : .lock_for_write()
10102 4 : .store_and_unlock(Lsn(0x50))
10103 4 : .wait()
10104 4 : .await;
10105 4 : // Update GC info
10106 4 : let mut guard = branch_tline.gc_info.write().unwrap();
10107 4 : *guard = GcInfo {
10108 4 : retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
10109 4 : cutoffs: GcCutoffs {
10110 4 : time: Lsn(0x50),
10111 4 : space: Lsn(0x50),
10112 4 : },
10113 4 : leases: Default::default(),
10114 4 : within_ancestor_pitr: false,
10115 4 : };
10116 4 : }
10117 4 :
10118 4 : let expected_result_at_gc_horizon = [
10119 4 : Bytes::from_static(b"value 0@0x10"),
10120 4 : Bytes::from_static(b"value 1@0x10@0x20"),
10121 4 : Bytes::from_static(b"value 2@0x10@0x30"),
10122 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
10123 4 : Bytes::from_static(b"value 4@0x10"),
10124 4 : Bytes::from_static(b"value 5@0x10@0x20"),
10125 4 : Bytes::from_static(b"value 6@0x10@0x20"),
10126 4 : Bytes::from_static(b"value 7@0x10"),
10127 4 : Bytes::from_static(b"value 8@0x10@0x48"),
10128 4 : Bytes::from_static(b"value 9@0x10@0x48"),
10129 4 : ];
10130 4 :
10131 4 : let expected_result_at_lsn_40 = [
10132 4 : Bytes::from_static(b"value 0@0x10"),
10133 4 : Bytes::from_static(b"value 1@0x10@0x20"),
10134 4 : Bytes::from_static(b"value 2@0x10@0x30"),
10135 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
10136 4 : Bytes::from_static(b"value 4@0x10"),
10137 4 : Bytes::from_static(b"value 5@0x10@0x20"),
10138 4 : Bytes::from_static(b"value 6@0x10@0x20"),
10139 4 : Bytes::from_static(b"value 7@0x10"),
10140 4 : Bytes::from_static(b"value 8@0x10"),
10141 4 : Bytes::from_static(b"value 9@0x10"),
10142 4 : ];
10143 4 :
10144 12 : let verify_result = || async {
10145 132 : for idx in 0..10 {
10146 120 : assert_eq!(
10147 120 : branch_tline
10148 120 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
10149 120 : .await
10150 120 : .unwrap(),
10151 120 : &expected_result_at_gc_horizon[idx]
10152 4 : );
10153 120 : assert_eq!(
10154 120 : branch_tline
10155 120 : .get(get_key(idx as u32), Lsn(0x40), &ctx)
10156 120 : .await
10157 120 : .unwrap(),
10158 120 : &expected_result_at_lsn_40[idx]
10159 4 : );
10160 4 : }
10161 24 : };
10162 4 :
10163 4 : verify_result().await;
10164 4 :
10165 4 : let cancel = CancellationToken::new();
10166 4 : branch_tline
10167 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
10168 4 : .await
10169 4 : .unwrap();
10170 4 :
10171 4 : verify_result().await;
10172 4 :
10173 4 : // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
10174 4 : // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
10175 4 : branch_tline
10176 4 : .compact_with_gc(
10177 4 : &cancel,
10178 4 : CompactOptions {
10179 4 : compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
10180 4 : ..Default::default()
10181 4 : },
10182 4 : &ctx,
10183 4 : )
10184 4 : .await
10185 4 : .unwrap();
10186 4 :
10187 4 : verify_result().await;
10188 4 :
10189 4 : Ok(())
10190 4 : }
10191 :
10192 : // Regression test for https://github.com/neondatabase/neon/issues/9012
10193 : // Create an image arrangement where we have to read at different LSN ranges
10194 : // from a delta layer. This is achieved by overlapping an image layer on top of
10195 : // a delta layer. Like so:
10196 : //
10197 : // A B
10198 : // +----------------+ -> delta_layer
10199 : // | | ^ lsn
10200 : // | =========|-> nested_image_layer |
10201 : // | C | |
10202 : // +----------------+ |
10203 : // ======== -> baseline_image_layer +-------> key
10204 : //
10205 : //
10206 : // When querying the key range [A, B) we need to read at different LSN ranges
10207 : // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
10208 : #[cfg(feature = "testing")]
10209 : #[tokio::test]
10210 4 : async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
10211 4 : let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
10212 4 : let (tenant, ctx) = harness.load().await;
10213 4 :
10214 4 : let will_init_keys = [2, 6];
10215 88 : fn get_key(id: u32) -> Key {
10216 88 : let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
10217 88 : key.field6 = id;
10218 88 : key
10219 88 : }
10220 4 :
10221 4 : let mut expected_key_values = HashMap::new();
10222 4 :
10223 4 : let baseline_image_layer_lsn = Lsn(0x10);
10224 4 : let mut baseline_img_layer = Vec::new();
10225 24 : for i in 0..5 {
10226 20 : let key = get_key(i);
10227 20 : let value = format!("value {i}@{baseline_image_layer_lsn}");
10228 20 :
10229 20 : let removed = expected_key_values.insert(key, value.clone());
10230 20 : assert!(removed.is_none());
10231 4 :
10232 20 : baseline_img_layer.push((key, Bytes::from(value)));
10233 4 : }
10234 4 :
10235 4 : let nested_image_layer_lsn = Lsn(0x50);
10236 4 : let mut nested_img_layer = Vec::new();
10237 24 : for i in 5..10 {
10238 20 : let key = get_key(i);
10239 20 : let value = format!("value {i}@{nested_image_layer_lsn}");
10240 20 :
10241 20 : let removed = expected_key_values.insert(key, value.clone());
10242 20 : assert!(removed.is_none());
10243 4 :
10244 20 : nested_img_layer.push((key, Bytes::from(value)));
10245 4 : }
10246 4 :
10247 4 : let mut delta_layer_spec = Vec::default();
10248 4 : let delta_layer_start_lsn = Lsn(0x20);
10249 4 : let mut delta_layer_end_lsn = delta_layer_start_lsn;
10250 4 :
10251 44 : for i in 0..10 {
10252 40 : let key = get_key(i);
10253 40 : let key_in_nested = nested_img_layer
10254 40 : .iter()
10255 160 : .any(|(key_with_img, _)| *key_with_img == key);
10256 40 : let lsn = {
10257 40 : if key_in_nested {
10258 20 : Lsn(nested_image_layer_lsn.0 + 0x10)
10259 4 : } else {
10260 20 : delta_layer_start_lsn
10261 4 : }
10262 4 : };
10263 4 :
10264 40 : let will_init = will_init_keys.contains(&i);
10265 40 : if will_init {
10266 8 : delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
10267 8 :
10268 8 : expected_key_values.insert(key, "".to_string());
10269 32 : } else {
10270 32 : let delta = format!("@{lsn}");
10271 32 : delta_layer_spec.push((
10272 32 : key,
10273 32 : lsn,
10274 32 : Value::WalRecord(NeonWalRecord::wal_append(&delta)),
10275 32 : ));
10276 32 :
10277 32 : expected_key_values
10278 32 : .get_mut(&key)
10279 32 : .expect("An image exists for each key")
10280 32 : .push_str(delta.as_str());
10281 32 : }
10282 40 : delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
10283 4 : }
10284 4 :
10285 4 : delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
10286 4 :
10287 4 : assert!(
10288 4 : nested_image_layer_lsn > delta_layer_start_lsn
10289 4 : && nested_image_layer_lsn < delta_layer_end_lsn
10290 4 : );
10291 4 :
10292 4 : let tline = tenant
10293 4 : .create_test_timeline_with_layers(
10294 4 : TIMELINE_ID,
10295 4 : baseline_image_layer_lsn,
10296 4 : DEFAULT_PG_VERSION,
10297 4 : &ctx,
10298 4 : vec![], // in-memory layers
10299 4 : vec![DeltaLayerTestDesc::new_with_inferred_key_range(
10300 4 : delta_layer_start_lsn..delta_layer_end_lsn,
10301 4 : delta_layer_spec,
10302 4 : )], // delta layers
10303 4 : vec![
10304 4 : (baseline_image_layer_lsn, baseline_img_layer),
10305 4 : (nested_image_layer_lsn, nested_img_layer),
10306 4 : ], // image layers
10307 4 : delta_layer_end_lsn,
10308 4 : )
10309 4 : .await?;
10310 4 :
10311 4 : let keyspace = KeySpace::single(get_key(0)..get_key(10));
10312 4 : let results = tline
10313 4 : .get_vectored(
10314 4 : keyspace,
10315 4 : delta_layer_end_lsn,
10316 4 : IoConcurrency::sequential(),
10317 4 : &ctx,
10318 4 : )
10319 4 : .await
10320 4 : .expect("No vectored errors");
10321 44 : for (key, res) in results {
10322 40 : let value = res.expect("No key errors");
10323 40 : let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
10324 40 : assert_eq!(value, Bytes::from(expected_value));
10325 4 : }
10326 4 :
10327 4 : Ok(())
10328 4 : }
10329 :
10330 : #[cfg(feature = "testing")]
10331 : #[tokio::test]
10332 4 : async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
10333 4 : let harness =
10334 4 : TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
10335 4 : let (tenant, ctx) = harness.load().await;
10336 4 :
10337 4 : let will_init_keys = [2, 6];
10338 128 : fn get_key(id: u32) -> Key {
10339 128 : let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
10340 128 : key.field6 = id;
10341 128 : key
10342 128 : }
10343 4 :
10344 4 : let mut expected_key_values = HashMap::new();
10345 4 :
10346 4 : let baseline_image_layer_lsn = Lsn(0x10);
10347 4 : let mut baseline_img_layer = Vec::new();
10348 24 : for i in 0..5 {
10349 20 : let key = get_key(i);
10350 20 : let value = format!("value {i}@{baseline_image_layer_lsn}");
10351 20 :
10352 20 : let removed = expected_key_values.insert(key, value.clone());
10353 20 : assert!(removed.is_none());
10354 4 :
10355 20 : baseline_img_layer.push((key, Bytes::from(value)));
10356 4 : }
10357 4 :
10358 4 : let nested_image_layer_lsn = Lsn(0x50);
10359 4 : let mut nested_img_layer = Vec::new();
10360 24 : for i in 5..10 {
10361 20 : let key = get_key(i);
10362 20 : let value = format!("value {i}@{nested_image_layer_lsn}");
10363 20 :
10364 20 : let removed = expected_key_values.insert(key, value.clone());
10365 20 : assert!(removed.is_none());
10366 4 :
10367 20 : nested_img_layer.push((key, Bytes::from(value)));
10368 4 : }
10369 4 :
10370 4 : let frozen_layer = {
10371 4 : let lsn_range = Lsn(0x40)..Lsn(0x60);
10372 4 : let mut data = Vec::new();
10373 44 : for i in 0..10 {
10374 40 : let key = get_key(i);
10375 40 : let key_in_nested = nested_img_layer
10376 40 : .iter()
10377 160 : .any(|(key_with_img, _)| *key_with_img == key);
10378 40 : let lsn = {
10379 40 : if key_in_nested {
10380 20 : Lsn(nested_image_layer_lsn.0 + 5)
10381 4 : } else {
10382 20 : lsn_range.start
10383 4 : }
10384 4 : };
10385 4 :
10386 40 : let will_init = will_init_keys.contains(&i);
10387 40 : if will_init {
10388 8 : data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
10389 8 :
10390 8 : expected_key_values.insert(key, "".to_string());
10391 32 : } else {
10392 32 : let delta = format!("@{lsn}");
10393 32 : data.push((
10394 32 : key,
10395 32 : lsn,
10396 32 : Value::WalRecord(NeonWalRecord::wal_append(&delta)),
10397 32 : ));
10398 32 :
10399 32 : expected_key_values
10400 32 : .get_mut(&key)
10401 32 : .expect("An image exists for each key")
10402 32 : .push_str(delta.as_str());
10403 32 : }
10404 4 : }
10405 4 :
10406 4 : InMemoryLayerTestDesc {
10407 4 : lsn_range,
10408 4 : is_open: false,
10409 4 : data,
10410 4 : }
10411 4 : };
10412 4 :
10413 4 : let (open_layer, last_record_lsn) = {
10414 4 : let start_lsn = Lsn(0x70);
10415 4 : let mut data = Vec::new();
10416 4 : let mut end_lsn = Lsn(0);
10417 44 : for i in 0..10 {
10418 40 : let key = get_key(i);
10419 40 : let lsn = Lsn(start_lsn.0 + i as u64);
10420 40 : let delta = format!("@{lsn}");
10421 40 : data.push((
10422 40 : key,
10423 40 : lsn,
10424 40 : Value::WalRecord(NeonWalRecord::wal_append(&delta)),
10425 40 : ));
10426 40 :
10427 40 : expected_key_values
10428 40 : .get_mut(&key)
10429 40 : .expect("An image exists for each key")
10430 40 : .push_str(delta.as_str());
10431 40 :
10432 40 : end_lsn = std::cmp::max(end_lsn, lsn);
10433 40 : }
10434 4 :
10435 4 : (
10436 4 : InMemoryLayerTestDesc {
10437 4 : lsn_range: start_lsn..Lsn::MAX,
10438 4 : is_open: true,
10439 4 : data,
10440 4 : },
10441 4 : end_lsn,
10442 4 : )
10443 4 : };
10444 4 :
10445 4 : assert!(
10446 4 : nested_image_layer_lsn > frozen_layer.lsn_range.start
10447 4 : && nested_image_layer_lsn < frozen_layer.lsn_range.end
10448 4 : );
10449 4 :
10450 4 : let tline = tenant
10451 4 : .create_test_timeline_with_layers(
10452 4 : TIMELINE_ID,
10453 4 : baseline_image_layer_lsn,
10454 4 : DEFAULT_PG_VERSION,
10455 4 : &ctx,
10456 4 : vec![open_layer, frozen_layer], // in-memory layers
10457 4 : Vec::new(), // delta layers
10458 4 : vec![
10459 4 : (baseline_image_layer_lsn, baseline_img_layer),
10460 4 : (nested_image_layer_lsn, nested_img_layer),
10461 4 : ], // image layers
10462 4 : last_record_lsn,
10463 4 : )
10464 4 : .await?;
10465 4 :
10466 4 : let keyspace = KeySpace::single(get_key(0)..get_key(10));
10467 4 : let results = tline
10468 4 : .get_vectored(keyspace, last_record_lsn, IoConcurrency::sequential(), &ctx)
10469 4 : .await
10470 4 : .expect("No vectored errors");
10471 44 : for (key, res) in results {
10472 40 : let value = res.expect("No key errors");
10473 40 : let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
10474 40 : assert_eq!(value, Bytes::from(expected_value.clone()));
10475 4 :
10476 40 : tracing::info!("key={key} value={expected_value}");
10477 4 : }
10478 4 :
10479 4 : Ok(())
10480 4 : }
10481 :
10482 428 : fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
10483 428 : (
10484 428 : k1.is_delta,
10485 428 : k1.key_range.start,
10486 428 : k1.key_range.end,
10487 428 : k1.lsn_range.start,
10488 428 : k1.lsn_range.end,
10489 428 : )
10490 428 : .cmp(&(
10491 428 : k2.is_delta,
10492 428 : k2.key_range.start,
10493 428 : k2.key_range.end,
10494 428 : k2.lsn_range.start,
10495 428 : k2.lsn_range.end,
10496 428 : ))
10497 428 : }
10498 :
10499 48 : async fn inspect_and_sort(
10500 48 : tline: &Arc<Timeline>,
10501 48 : filter: Option<std::ops::Range<Key>>,
10502 48 : ) -> Vec<PersistentLayerKey> {
10503 48 : let mut all_layers = tline.inspect_historic_layers().await.unwrap();
10504 48 : if let Some(filter) = filter {
10505 216 : all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
10506 44 : }
10507 48 : all_layers.sort_by(sort_layer_key);
10508 48 : all_layers
10509 48 : }
10510 :
10511 : #[cfg(feature = "testing")]
10512 44 : fn check_layer_map_key_eq(
10513 44 : mut left: Vec<PersistentLayerKey>,
10514 44 : mut right: Vec<PersistentLayerKey>,
10515 44 : ) {
10516 44 : left.sort_by(sort_layer_key);
10517 44 : right.sort_by(sort_layer_key);
10518 44 : if left != right {
10519 0 : eprintln!("---LEFT---");
10520 0 : for left in left.iter() {
10521 0 : eprintln!("{}", left);
10522 0 : }
10523 0 : eprintln!("---RIGHT---");
10524 0 : for right in right.iter() {
10525 0 : eprintln!("{}", right);
10526 0 : }
10527 0 : assert_eq!(left, right);
10528 44 : }
10529 44 : }
10530 :
10531 : #[cfg(feature = "testing")]
10532 : #[tokio::test]
10533 4 : async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
10534 4 : let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
10535 4 : let (tenant, ctx) = harness.load().await;
10536 4 :
10537 364 : fn get_key(id: u32) -> Key {
10538 364 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
10539 364 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
10540 364 : key.field6 = id;
10541 364 : key
10542 364 : }
10543 4 :
10544 4 : // img layer at 0x10
10545 4 : let img_layer = (0..10)
10546 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10547 4 : .collect_vec();
10548 4 :
10549 4 : let delta1 = vec![
10550 4 : (
10551 4 : get_key(1),
10552 4 : Lsn(0x20),
10553 4 : Value::Image(Bytes::from("value 1@0x20")),
10554 4 : ),
10555 4 : (
10556 4 : get_key(2),
10557 4 : Lsn(0x30),
10558 4 : Value::Image(Bytes::from("value 2@0x30")),
10559 4 : ),
10560 4 : (
10561 4 : get_key(3),
10562 4 : Lsn(0x40),
10563 4 : Value::Image(Bytes::from("value 3@0x40")),
10564 4 : ),
10565 4 : ];
10566 4 : let delta2 = vec![
10567 4 : (
10568 4 : get_key(5),
10569 4 : Lsn(0x20),
10570 4 : Value::Image(Bytes::from("value 5@0x20")),
10571 4 : ),
10572 4 : (
10573 4 : get_key(6),
10574 4 : Lsn(0x20),
10575 4 : Value::Image(Bytes::from("value 6@0x20")),
10576 4 : ),
10577 4 : ];
10578 4 : let delta3 = vec![
10579 4 : (
10580 4 : get_key(8),
10581 4 : Lsn(0x48),
10582 4 : Value::Image(Bytes::from("value 8@0x48")),
10583 4 : ),
10584 4 : (
10585 4 : get_key(9),
10586 4 : Lsn(0x48),
10587 4 : Value::Image(Bytes::from("value 9@0x48")),
10588 4 : ),
10589 4 : ];
10590 4 :
10591 4 : let tline = tenant
10592 4 : .create_test_timeline_with_layers(
10593 4 : TIMELINE_ID,
10594 4 : Lsn(0x10),
10595 4 : DEFAULT_PG_VERSION,
10596 4 : &ctx,
10597 4 : vec![], // in-memory layers
10598 4 : vec![
10599 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
10600 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
10601 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
10602 4 : ], // delta layers
10603 4 : vec![(Lsn(0x10), img_layer)], // image layers
10604 4 : Lsn(0x50),
10605 4 : )
10606 4 : .await?;
10607 4 :
10608 4 : {
10609 4 : tline
10610 4 : .applied_gc_cutoff_lsn
10611 4 : .lock_for_write()
10612 4 : .store_and_unlock(Lsn(0x30))
10613 4 : .wait()
10614 4 : .await;
10615 4 : // Update GC info
10616 4 : let mut guard = tline.gc_info.write().unwrap();
10617 4 : *guard = GcInfo {
10618 4 : retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
10619 4 : cutoffs: GcCutoffs {
10620 4 : time: Lsn(0x30),
10621 4 : space: Lsn(0x30),
10622 4 : },
10623 4 : leases: Default::default(),
10624 4 : within_ancestor_pitr: false,
10625 4 : };
10626 4 : }
10627 4 :
10628 4 : let cancel = CancellationToken::new();
10629 4 :
10630 4 : // Do a partial compaction on key range 0..2
10631 4 : tline
10632 4 : .compact_with_gc(
10633 4 : &cancel,
10634 4 : CompactOptions {
10635 4 : flags: EnumSet::new(),
10636 4 : compact_key_range: Some((get_key(0)..get_key(2)).into()),
10637 4 : ..Default::default()
10638 4 : },
10639 4 : &ctx,
10640 4 : )
10641 4 : .await
10642 4 : .unwrap();
10643 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10644 4 : check_layer_map_key_eq(
10645 4 : all_layers,
10646 4 : vec![
10647 4 : // newly-generated image layer for the partial compaction range 0-2
10648 4 : PersistentLayerKey {
10649 4 : key_range: get_key(0)..get_key(2),
10650 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10651 4 : is_delta: false,
10652 4 : },
10653 4 : PersistentLayerKey {
10654 4 : key_range: get_key(0)..get_key(10),
10655 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10656 4 : is_delta: false,
10657 4 : },
10658 4 : // delta1 is split and the second part is rewritten
10659 4 : PersistentLayerKey {
10660 4 : key_range: get_key(2)..get_key(4),
10661 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10662 4 : is_delta: true,
10663 4 : },
10664 4 : PersistentLayerKey {
10665 4 : key_range: get_key(5)..get_key(7),
10666 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10667 4 : is_delta: true,
10668 4 : },
10669 4 : PersistentLayerKey {
10670 4 : key_range: get_key(8)..get_key(10),
10671 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10672 4 : is_delta: true,
10673 4 : },
10674 4 : ],
10675 4 : );
10676 4 :
10677 4 : // Do a partial compaction on key range 2..4
10678 4 : tline
10679 4 : .compact_with_gc(
10680 4 : &cancel,
10681 4 : CompactOptions {
10682 4 : flags: EnumSet::new(),
10683 4 : compact_key_range: Some((get_key(2)..get_key(4)).into()),
10684 4 : ..Default::default()
10685 4 : },
10686 4 : &ctx,
10687 4 : )
10688 4 : .await
10689 4 : .unwrap();
10690 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10691 4 : check_layer_map_key_eq(
10692 4 : all_layers,
10693 4 : vec![
10694 4 : PersistentLayerKey {
10695 4 : key_range: get_key(0)..get_key(2),
10696 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10697 4 : is_delta: false,
10698 4 : },
10699 4 : PersistentLayerKey {
10700 4 : key_range: get_key(0)..get_key(10),
10701 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10702 4 : is_delta: false,
10703 4 : },
10704 4 : // image layer generated for the compaction range 2-4
10705 4 : PersistentLayerKey {
10706 4 : key_range: get_key(2)..get_key(4),
10707 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10708 4 : is_delta: false,
10709 4 : },
10710 4 : // we have key2/key3 above the retain_lsn, so we still need this delta layer
10711 4 : PersistentLayerKey {
10712 4 : key_range: get_key(2)..get_key(4),
10713 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10714 4 : is_delta: true,
10715 4 : },
10716 4 : PersistentLayerKey {
10717 4 : key_range: get_key(5)..get_key(7),
10718 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10719 4 : is_delta: true,
10720 4 : },
10721 4 : PersistentLayerKey {
10722 4 : key_range: get_key(8)..get_key(10),
10723 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10724 4 : is_delta: true,
10725 4 : },
10726 4 : ],
10727 4 : );
10728 4 :
10729 4 : // Do a partial compaction on key range 4..9
10730 4 : tline
10731 4 : .compact_with_gc(
10732 4 : &cancel,
10733 4 : CompactOptions {
10734 4 : flags: EnumSet::new(),
10735 4 : compact_key_range: Some((get_key(4)..get_key(9)).into()),
10736 4 : ..Default::default()
10737 4 : },
10738 4 : &ctx,
10739 4 : )
10740 4 : .await
10741 4 : .unwrap();
10742 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10743 4 : check_layer_map_key_eq(
10744 4 : all_layers,
10745 4 : vec![
10746 4 : PersistentLayerKey {
10747 4 : key_range: get_key(0)..get_key(2),
10748 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10749 4 : is_delta: false,
10750 4 : },
10751 4 : PersistentLayerKey {
10752 4 : key_range: get_key(0)..get_key(10),
10753 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10754 4 : is_delta: false,
10755 4 : },
10756 4 : PersistentLayerKey {
10757 4 : key_range: get_key(2)..get_key(4),
10758 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10759 4 : is_delta: false,
10760 4 : },
10761 4 : PersistentLayerKey {
10762 4 : key_range: get_key(2)..get_key(4),
10763 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10764 4 : is_delta: true,
10765 4 : },
10766 4 : // image layer generated for this compaction range
10767 4 : PersistentLayerKey {
10768 4 : key_range: get_key(4)..get_key(9),
10769 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10770 4 : is_delta: false,
10771 4 : },
10772 4 : PersistentLayerKey {
10773 4 : key_range: get_key(8)..get_key(10),
10774 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10775 4 : is_delta: true,
10776 4 : },
10777 4 : ],
10778 4 : );
10779 4 :
10780 4 : // Do a partial compaction on key range 9..10
10781 4 : tline
10782 4 : .compact_with_gc(
10783 4 : &cancel,
10784 4 : CompactOptions {
10785 4 : flags: EnumSet::new(),
10786 4 : compact_key_range: Some((get_key(9)..get_key(10)).into()),
10787 4 : ..Default::default()
10788 4 : },
10789 4 : &ctx,
10790 4 : )
10791 4 : .await
10792 4 : .unwrap();
10793 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10794 4 : check_layer_map_key_eq(
10795 4 : all_layers,
10796 4 : vec![
10797 4 : PersistentLayerKey {
10798 4 : key_range: get_key(0)..get_key(2),
10799 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10800 4 : is_delta: false,
10801 4 : },
10802 4 : PersistentLayerKey {
10803 4 : key_range: get_key(0)..get_key(10),
10804 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10805 4 : is_delta: false,
10806 4 : },
10807 4 : PersistentLayerKey {
10808 4 : key_range: get_key(2)..get_key(4),
10809 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10810 4 : is_delta: false,
10811 4 : },
10812 4 : PersistentLayerKey {
10813 4 : key_range: get_key(2)..get_key(4),
10814 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10815 4 : is_delta: true,
10816 4 : },
10817 4 : PersistentLayerKey {
10818 4 : key_range: get_key(4)..get_key(9),
10819 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10820 4 : is_delta: false,
10821 4 : },
10822 4 : // image layer generated for the compaction range
10823 4 : PersistentLayerKey {
10824 4 : key_range: get_key(9)..get_key(10),
10825 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10826 4 : is_delta: false,
10827 4 : },
10828 4 : PersistentLayerKey {
10829 4 : key_range: get_key(8)..get_key(10),
10830 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10831 4 : is_delta: true,
10832 4 : },
10833 4 : ],
10834 4 : );
10835 4 :
10836 4 : // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
10837 4 : tline
10838 4 : .compact_with_gc(
10839 4 : &cancel,
10840 4 : CompactOptions {
10841 4 : flags: EnumSet::new(),
10842 4 : compact_key_range: Some((get_key(0)..get_key(10)).into()),
10843 4 : ..Default::default()
10844 4 : },
10845 4 : &ctx,
10846 4 : )
10847 4 : .await
10848 4 : .unwrap();
10849 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10850 4 : check_layer_map_key_eq(
10851 4 : all_layers,
10852 4 : vec![
10853 4 : // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
10854 4 : PersistentLayerKey {
10855 4 : key_range: get_key(0)..get_key(10),
10856 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10857 4 : is_delta: false,
10858 4 : },
10859 4 : PersistentLayerKey {
10860 4 : key_range: get_key(2)..get_key(4),
10861 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10862 4 : is_delta: true,
10863 4 : },
10864 4 : PersistentLayerKey {
10865 4 : key_range: get_key(8)..get_key(10),
10866 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10867 4 : is_delta: true,
10868 4 : },
10869 4 : ],
10870 4 : );
10871 4 : Ok(())
10872 4 : }
10873 :
10874 : #[cfg(feature = "testing")]
10875 : #[tokio::test]
10876 4 : async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
10877 4 : let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
10878 4 : .await
10879 4 : .unwrap();
10880 4 : let (tenant, ctx) = harness.load().await;
10881 4 : let tline_parent = tenant
10882 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
10883 4 : .await
10884 4 : .unwrap();
10885 4 : let tline_child = tenant
10886 4 : .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
10887 4 : .await
10888 4 : .unwrap();
10889 4 : {
10890 4 : let gc_info_parent = tline_parent.gc_info.read().unwrap();
10891 4 : assert_eq!(
10892 4 : gc_info_parent.retain_lsns,
10893 4 : vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
10894 4 : );
10895 4 : }
10896 4 : // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
10897 4 : tline_child
10898 4 : .remote_client
10899 4 : .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
10900 4 : .unwrap();
10901 4 : tline_child.remote_client.wait_completion().await.unwrap();
10902 4 : offload_timeline(&tenant, &tline_child)
10903 4 : .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
10904 4 : .await.unwrap();
10905 4 : let child_timeline_id = tline_child.timeline_id;
10906 4 : Arc::try_unwrap(tline_child).unwrap();
10907 4 :
10908 4 : {
10909 4 : let gc_info_parent = tline_parent.gc_info.read().unwrap();
10910 4 : assert_eq!(
10911 4 : gc_info_parent.retain_lsns,
10912 4 : vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
10913 4 : );
10914 4 : }
10915 4 :
10916 4 : tenant
10917 4 : .get_offloaded_timeline(child_timeline_id)
10918 4 : .unwrap()
10919 4 : .defuse_for_tenant_drop();
10920 4 :
10921 4 : Ok(())
10922 4 : }
10923 :
10924 : #[cfg(feature = "testing")]
10925 : #[tokio::test]
10926 4 : async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
10927 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
10928 4 : let (tenant, ctx) = harness.load().await;
10929 4 :
10930 592 : fn get_key(id: u32) -> Key {
10931 592 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
10932 592 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
10933 592 : key.field6 = id;
10934 592 : key
10935 592 : }
10936 4 :
10937 4 : let img_layer = (0..10)
10938 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10939 4 : .collect_vec();
10940 4 :
10941 4 : let delta1 = vec![(
10942 4 : get_key(1),
10943 4 : Lsn(0x20),
10944 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10945 4 : )];
10946 4 : let delta4 = vec![(
10947 4 : get_key(1),
10948 4 : Lsn(0x28),
10949 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
10950 4 : )];
10951 4 : let delta2 = vec![
10952 4 : (
10953 4 : get_key(1),
10954 4 : Lsn(0x30),
10955 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
10956 4 : ),
10957 4 : (
10958 4 : get_key(1),
10959 4 : Lsn(0x38),
10960 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
10961 4 : ),
10962 4 : ];
10963 4 : let delta3 = vec![
10964 4 : (
10965 4 : get_key(8),
10966 4 : Lsn(0x48),
10967 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10968 4 : ),
10969 4 : (
10970 4 : get_key(9),
10971 4 : Lsn(0x48),
10972 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10973 4 : ),
10974 4 : ];
10975 4 :
10976 4 : let tline = tenant
10977 4 : .create_test_timeline_with_layers(
10978 4 : TIMELINE_ID,
10979 4 : Lsn(0x10),
10980 4 : DEFAULT_PG_VERSION,
10981 4 : &ctx,
10982 4 : vec![], // in-memory layers
10983 4 : vec![
10984 4 : // delta1/2/4 only contain a single key but multiple updates
10985 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
10986 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
10987 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
10988 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
10989 4 : ], // delta layers
10990 4 : vec![(Lsn(0x10), img_layer)], // image layers
10991 4 : Lsn(0x50),
10992 4 : )
10993 4 : .await?;
10994 4 : {
10995 4 : tline
10996 4 : .applied_gc_cutoff_lsn
10997 4 : .lock_for_write()
10998 4 : .store_and_unlock(Lsn(0x30))
10999 4 : .wait()
11000 4 : .await;
11001 4 : // Update GC info
11002 4 : let mut guard = tline.gc_info.write().unwrap();
11003 4 : *guard = GcInfo {
11004 4 : retain_lsns: vec![
11005 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
11006 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
11007 4 : ],
11008 4 : cutoffs: GcCutoffs {
11009 4 : time: Lsn(0x30),
11010 4 : space: Lsn(0x30),
11011 4 : },
11012 4 : leases: Default::default(),
11013 4 : within_ancestor_pitr: false,
11014 4 : };
11015 4 : }
11016 4 :
11017 4 : let expected_result = [
11018 4 : Bytes::from_static(b"value 0@0x10"),
11019 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
11020 4 : Bytes::from_static(b"value 2@0x10"),
11021 4 : Bytes::from_static(b"value 3@0x10"),
11022 4 : Bytes::from_static(b"value 4@0x10"),
11023 4 : Bytes::from_static(b"value 5@0x10"),
11024 4 : Bytes::from_static(b"value 6@0x10"),
11025 4 : Bytes::from_static(b"value 7@0x10"),
11026 4 : Bytes::from_static(b"value 8@0x10@0x48"),
11027 4 : Bytes::from_static(b"value 9@0x10@0x48"),
11028 4 : ];
11029 4 :
11030 4 : let expected_result_at_gc_horizon = [
11031 4 : Bytes::from_static(b"value 0@0x10"),
11032 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
11033 4 : Bytes::from_static(b"value 2@0x10"),
11034 4 : Bytes::from_static(b"value 3@0x10"),
11035 4 : Bytes::from_static(b"value 4@0x10"),
11036 4 : Bytes::from_static(b"value 5@0x10"),
11037 4 : Bytes::from_static(b"value 6@0x10"),
11038 4 : Bytes::from_static(b"value 7@0x10"),
11039 4 : Bytes::from_static(b"value 8@0x10"),
11040 4 : Bytes::from_static(b"value 9@0x10"),
11041 4 : ];
11042 4 :
11043 4 : let expected_result_at_lsn_20 = [
11044 4 : Bytes::from_static(b"value 0@0x10"),
11045 4 : Bytes::from_static(b"value 1@0x10@0x20"),
11046 4 : Bytes::from_static(b"value 2@0x10"),
11047 4 : Bytes::from_static(b"value 3@0x10"),
11048 4 : Bytes::from_static(b"value 4@0x10"),
11049 4 : Bytes::from_static(b"value 5@0x10"),
11050 4 : Bytes::from_static(b"value 6@0x10"),
11051 4 : Bytes::from_static(b"value 7@0x10"),
11052 4 : Bytes::from_static(b"value 8@0x10"),
11053 4 : Bytes::from_static(b"value 9@0x10"),
11054 4 : ];
11055 4 :
11056 4 : let expected_result_at_lsn_10 = [
11057 4 : Bytes::from_static(b"value 0@0x10"),
11058 4 : Bytes::from_static(b"value 1@0x10"),
11059 4 : Bytes::from_static(b"value 2@0x10"),
11060 4 : Bytes::from_static(b"value 3@0x10"),
11061 4 : Bytes::from_static(b"value 4@0x10"),
11062 4 : Bytes::from_static(b"value 5@0x10"),
11063 4 : Bytes::from_static(b"value 6@0x10"),
11064 4 : Bytes::from_static(b"value 7@0x10"),
11065 4 : Bytes::from_static(b"value 8@0x10"),
11066 4 : Bytes::from_static(b"value 9@0x10"),
11067 4 : ];
11068 4 :
11069 12 : let verify_result = || async {
11070 12 : let gc_horizon = {
11071 12 : let gc_info = tline.gc_info.read().unwrap();
11072 12 : gc_info.cutoffs.time
11073 4 : };
11074 132 : for idx in 0..10 {
11075 120 : assert_eq!(
11076 120 : tline
11077 120 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
11078 120 : .await
11079 120 : .unwrap(),
11080 120 : &expected_result[idx]
11081 4 : );
11082 120 : assert_eq!(
11083 120 : tline
11084 120 : .get(get_key(idx as u32), gc_horizon, &ctx)
11085 120 : .await
11086 120 : .unwrap(),
11087 120 : &expected_result_at_gc_horizon[idx]
11088 4 : );
11089 120 : assert_eq!(
11090 120 : tline
11091 120 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
11092 120 : .await
11093 120 : .unwrap(),
11094 120 : &expected_result_at_lsn_20[idx]
11095 4 : );
11096 120 : assert_eq!(
11097 120 : tline
11098 120 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
11099 120 : .await
11100 120 : .unwrap(),
11101 120 : &expected_result_at_lsn_10[idx]
11102 4 : );
11103 4 : }
11104 24 : };
11105 4 :
11106 4 : verify_result().await;
11107 4 :
11108 4 : let cancel = CancellationToken::new();
11109 4 : tline
11110 4 : .compact_with_gc(
11111 4 : &cancel,
11112 4 : CompactOptions {
11113 4 : compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
11114 4 : ..Default::default()
11115 4 : },
11116 4 : &ctx,
11117 4 : )
11118 4 : .await
11119 4 : .unwrap();
11120 4 : verify_result().await;
11121 4 :
11122 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11123 4 : check_layer_map_key_eq(
11124 4 : all_layers,
11125 4 : vec![
11126 4 : // The original image layer, not compacted
11127 4 : PersistentLayerKey {
11128 4 : key_range: get_key(0)..get_key(10),
11129 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11130 4 : is_delta: false,
11131 4 : },
11132 4 : // Delta layer below the specified above_lsn not compacted
11133 4 : PersistentLayerKey {
11134 4 : key_range: get_key(1)..get_key(2),
11135 4 : lsn_range: Lsn(0x20)..Lsn(0x28),
11136 4 : is_delta: true,
11137 4 : },
11138 4 : // Delta layer compacted above the LSN
11139 4 : PersistentLayerKey {
11140 4 : key_range: get_key(1)..get_key(10),
11141 4 : lsn_range: Lsn(0x28)..Lsn(0x50),
11142 4 : is_delta: true,
11143 4 : },
11144 4 : ],
11145 4 : );
11146 4 :
11147 4 : // compact again
11148 4 : tline
11149 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
11150 4 : .await
11151 4 : .unwrap();
11152 4 : verify_result().await;
11153 4 :
11154 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11155 4 : check_layer_map_key_eq(
11156 4 : all_layers,
11157 4 : vec![
11158 4 : // The compacted image layer (full key range)
11159 4 : PersistentLayerKey {
11160 4 : key_range: Key::MIN..Key::MAX,
11161 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11162 4 : is_delta: false,
11163 4 : },
11164 4 : // All other data in the delta layer
11165 4 : PersistentLayerKey {
11166 4 : key_range: get_key(1)..get_key(10),
11167 4 : lsn_range: Lsn(0x10)..Lsn(0x50),
11168 4 : is_delta: true,
11169 4 : },
11170 4 : ],
11171 4 : );
11172 4 :
11173 4 : Ok(())
11174 4 : }
11175 :
11176 : #[cfg(feature = "testing")]
11177 : #[tokio::test]
11178 4 : async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
11179 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
11180 4 : let (tenant, ctx) = harness.load().await;
11181 4 :
11182 1016 : fn get_key(id: u32) -> Key {
11183 1016 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
11184 1016 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
11185 1016 : key.field6 = id;
11186 1016 : key
11187 1016 : }
11188 4 :
11189 4 : let img_layer = (0..10)
11190 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
11191 4 : .collect_vec();
11192 4 :
11193 4 : let delta1 = vec![(
11194 4 : get_key(1),
11195 4 : Lsn(0x20),
11196 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
11197 4 : )];
11198 4 : let delta4 = vec![(
11199 4 : get_key(1),
11200 4 : Lsn(0x28),
11201 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
11202 4 : )];
11203 4 : let delta2 = vec![
11204 4 : (
11205 4 : get_key(1),
11206 4 : Lsn(0x30),
11207 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
11208 4 : ),
11209 4 : (
11210 4 : get_key(1),
11211 4 : Lsn(0x38),
11212 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
11213 4 : ),
11214 4 : ];
11215 4 : let delta3 = vec![
11216 4 : (
11217 4 : get_key(8),
11218 4 : Lsn(0x48),
11219 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
11220 4 : ),
11221 4 : (
11222 4 : get_key(9),
11223 4 : Lsn(0x48),
11224 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
11225 4 : ),
11226 4 : ];
11227 4 :
11228 4 : let tline = tenant
11229 4 : .create_test_timeline_with_layers(
11230 4 : TIMELINE_ID,
11231 4 : Lsn(0x10),
11232 4 : DEFAULT_PG_VERSION,
11233 4 : &ctx,
11234 4 : vec![], // in-memory layers
11235 4 : vec![
11236 4 : // delta1/2/4 only contain a single key but multiple updates
11237 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
11238 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
11239 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
11240 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
11241 4 : ], // delta layers
11242 4 : vec![(Lsn(0x10), img_layer)], // image layers
11243 4 : Lsn(0x50),
11244 4 : )
11245 4 : .await?;
11246 4 : {
11247 4 : tline
11248 4 : .applied_gc_cutoff_lsn
11249 4 : .lock_for_write()
11250 4 : .store_and_unlock(Lsn(0x30))
11251 4 : .wait()
11252 4 : .await;
11253 4 : // Update GC info
11254 4 : let mut guard = tline.gc_info.write().unwrap();
11255 4 : *guard = GcInfo {
11256 4 : retain_lsns: vec![
11257 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
11258 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
11259 4 : ],
11260 4 : cutoffs: GcCutoffs {
11261 4 : time: Lsn(0x30),
11262 4 : space: Lsn(0x30),
11263 4 : },
11264 4 : leases: Default::default(),
11265 4 : within_ancestor_pitr: false,
11266 4 : };
11267 4 : }
11268 4 :
11269 4 : let expected_result = [
11270 4 : Bytes::from_static(b"value 0@0x10"),
11271 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
11272 4 : Bytes::from_static(b"value 2@0x10"),
11273 4 : Bytes::from_static(b"value 3@0x10"),
11274 4 : Bytes::from_static(b"value 4@0x10"),
11275 4 : Bytes::from_static(b"value 5@0x10"),
11276 4 : Bytes::from_static(b"value 6@0x10"),
11277 4 : Bytes::from_static(b"value 7@0x10"),
11278 4 : Bytes::from_static(b"value 8@0x10@0x48"),
11279 4 : Bytes::from_static(b"value 9@0x10@0x48"),
11280 4 : ];
11281 4 :
11282 4 : let expected_result_at_gc_horizon = [
11283 4 : Bytes::from_static(b"value 0@0x10"),
11284 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
11285 4 : Bytes::from_static(b"value 2@0x10"),
11286 4 : Bytes::from_static(b"value 3@0x10"),
11287 4 : Bytes::from_static(b"value 4@0x10"),
11288 4 : Bytes::from_static(b"value 5@0x10"),
11289 4 : Bytes::from_static(b"value 6@0x10"),
11290 4 : Bytes::from_static(b"value 7@0x10"),
11291 4 : Bytes::from_static(b"value 8@0x10"),
11292 4 : Bytes::from_static(b"value 9@0x10"),
11293 4 : ];
11294 4 :
11295 4 : let expected_result_at_lsn_20 = [
11296 4 : Bytes::from_static(b"value 0@0x10"),
11297 4 : Bytes::from_static(b"value 1@0x10@0x20"),
11298 4 : Bytes::from_static(b"value 2@0x10"),
11299 4 : Bytes::from_static(b"value 3@0x10"),
11300 4 : Bytes::from_static(b"value 4@0x10"),
11301 4 : Bytes::from_static(b"value 5@0x10"),
11302 4 : Bytes::from_static(b"value 6@0x10"),
11303 4 : Bytes::from_static(b"value 7@0x10"),
11304 4 : Bytes::from_static(b"value 8@0x10"),
11305 4 : Bytes::from_static(b"value 9@0x10"),
11306 4 : ];
11307 4 :
11308 4 : let expected_result_at_lsn_10 = [
11309 4 : Bytes::from_static(b"value 0@0x10"),
11310 4 : Bytes::from_static(b"value 1@0x10"),
11311 4 : Bytes::from_static(b"value 2@0x10"),
11312 4 : Bytes::from_static(b"value 3@0x10"),
11313 4 : Bytes::from_static(b"value 4@0x10"),
11314 4 : Bytes::from_static(b"value 5@0x10"),
11315 4 : Bytes::from_static(b"value 6@0x10"),
11316 4 : Bytes::from_static(b"value 7@0x10"),
11317 4 : Bytes::from_static(b"value 8@0x10"),
11318 4 : Bytes::from_static(b"value 9@0x10"),
11319 4 : ];
11320 4 :
11321 20 : let verify_result = || async {
11322 20 : let gc_horizon = {
11323 20 : let gc_info = tline.gc_info.read().unwrap();
11324 20 : gc_info.cutoffs.time
11325 4 : };
11326 220 : for idx in 0..10 {
11327 200 : assert_eq!(
11328 200 : tline
11329 200 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
11330 200 : .await
11331 200 : .unwrap(),
11332 200 : &expected_result[idx]
11333 4 : );
11334 200 : assert_eq!(
11335 200 : tline
11336 200 : .get(get_key(idx as u32), gc_horizon, &ctx)
11337 200 : .await
11338 200 : .unwrap(),
11339 200 : &expected_result_at_gc_horizon[idx]
11340 4 : );
11341 200 : assert_eq!(
11342 200 : tline
11343 200 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
11344 200 : .await
11345 200 : .unwrap(),
11346 200 : &expected_result_at_lsn_20[idx]
11347 4 : );
11348 200 : assert_eq!(
11349 200 : tline
11350 200 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
11351 200 : .await
11352 200 : .unwrap(),
11353 200 : &expected_result_at_lsn_10[idx]
11354 4 : );
11355 4 : }
11356 40 : };
11357 4 :
11358 4 : verify_result().await;
11359 4 :
11360 4 : let cancel = CancellationToken::new();
11361 4 :
11362 4 : tline
11363 4 : .compact_with_gc(
11364 4 : &cancel,
11365 4 : CompactOptions {
11366 4 : compact_key_range: Some((get_key(0)..get_key(2)).into()),
11367 4 : compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
11368 4 : ..Default::default()
11369 4 : },
11370 4 : &ctx,
11371 4 : )
11372 4 : .await
11373 4 : .unwrap();
11374 4 : verify_result().await;
11375 4 :
11376 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11377 4 : check_layer_map_key_eq(
11378 4 : all_layers,
11379 4 : vec![
11380 4 : // The original image layer, not compacted
11381 4 : PersistentLayerKey {
11382 4 : key_range: get_key(0)..get_key(10),
11383 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11384 4 : is_delta: false,
11385 4 : },
11386 4 : // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
11387 4 : // the layer 0x28-0x30 into one.
11388 4 : PersistentLayerKey {
11389 4 : key_range: get_key(1)..get_key(2),
11390 4 : lsn_range: Lsn(0x20)..Lsn(0x30),
11391 4 : is_delta: true,
11392 4 : },
11393 4 : // Above the upper bound and untouched
11394 4 : PersistentLayerKey {
11395 4 : key_range: get_key(1)..get_key(2),
11396 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11397 4 : is_delta: true,
11398 4 : },
11399 4 : // This layer is untouched
11400 4 : PersistentLayerKey {
11401 4 : key_range: get_key(8)..get_key(10),
11402 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11403 4 : is_delta: true,
11404 4 : },
11405 4 : ],
11406 4 : );
11407 4 :
11408 4 : tline
11409 4 : .compact_with_gc(
11410 4 : &cancel,
11411 4 : CompactOptions {
11412 4 : compact_key_range: Some((get_key(3)..get_key(8)).into()),
11413 4 : compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
11414 4 : ..Default::default()
11415 4 : },
11416 4 : &ctx,
11417 4 : )
11418 4 : .await
11419 4 : .unwrap();
11420 4 : verify_result().await;
11421 4 :
11422 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11423 4 : check_layer_map_key_eq(
11424 4 : all_layers,
11425 4 : vec![
11426 4 : // The original image layer, not compacted
11427 4 : PersistentLayerKey {
11428 4 : key_range: get_key(0)..get_key(10),
11429 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11430 4 : is_delta: false,
11431 4 : },
11432 4 : // Not in the compaction key range, uncompacted
11433 4 : PersistentLayerKey {
11434 4 : key_range: get_key(1)..get_key(2),
11435 4 : lsn_range: Lsn(0x20)..Lsn(0x30),
11436 4 : is_delta: true,
11437 4 : },
11438 4 : // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
11439 4 : PersistentLayerKey {
11440 4 : key_range: get_key(1)..get_key(2),
11441 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11442 4 : is_delta: true,
11443 4 : },
11444 4 : // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
11445 4 : // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
11446 4 : // becomes 0x50.
11447 4 : PersistentLayerKey {
11448 4 : key_range: get_key(8)..get_key(10),
11449 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11450 4 : is_delta: true,
11451 4 : },
11452 4 : ],
11453 4 : );
11454 4 :
11455 4 : // compact again
11456 4 : tline
11457 4 : .compact_with_gc(
11458 4 : &cancel,
11459 4 : CompactOptions {
11460 4 : compact_key_range: Some((get_key(0)..get_key(5)).into()),
11461 4 : compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
11462 4 : ..Default::default()
11463 4 : },
11464 4 : &ctx,
11465 4 : )
11466 4 : .await
11467 4 : .unwrap();
11468 4 : verify_result().await;
11469 4 :
11470 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11471 4 : check_layer_map_key_eq(
11472 4 : all_layers,
11473 4 : vec![
11474 4 : // The original image layer, not compacted
11475 4 : PersistentLayerKey {
11476 4 : key_range: get_key(0)..get_key(10),
11477 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11478 4 : is_delta: false,
11479 4 : },
11480 4 : // The range gets compacted
11481 4 : PersistentLayerKey {
11482 4 : key_range: get_key(1)..get_key(2),
11483 4 : lsn_range: Lsn(0x20)..Lsn(0x50),
11484 4 : is_delta: true,
11485 4 : },
11486 4 : // Not touched during this iteration of compaction
11487 4 : PersistentLayerKey {
11488 4 : key_range: get_key(8)..get_key(10),
11489 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11490 4 : is_delta: true,
11491 4 : },
11492 4 : ],
11493 4 : );
11494 4 :
11495 4 : // final full compaction
11496 4 : tline
11497 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
11498 4 : .await
11499 4 : .unwrap();
11500 4 : verify_result().await;
11501 4 :
11502 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11503 4 : check_layer_map_key_eq(
11504 4 : all_layers,
11505 4 : vec![
11506 4 : // The compacted image layer (full key range)
11507 4 : PersistentLayerKey {
11508 4 : key_range: Key::MIN..Key::MAX,
11509 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11510 4 : is_delta: false,
11511 4 : },
11512 4 : // All other data in the delta layer
11513 4 : PersistentLayerKey {
11514 4 : key_range: get_key(1)..get_key(10),
11515 4 : lsn_range: Lsn(0x10)..Lsn(0x50),
11516 4 : is_delta: true,
11517 4 : },
11518 4 : ],
11519 4 : );
11520 4 :
11521 4 : Ok(())
11522 4 : }
11523 : }
|