Line data Source code
1 : //! Timeline repository implementation that keeps old data in layer files, and
2 : //! the recent changes in ephemeral files.
3 : //!
4 : //! See tenant/*_layer.rs files. The functions here are responsible for locating
5 : //! the correct layer for the get/put call, walking back the timeline branching
6 : //! history as needed.
7 : //!
8 : //! The files are stored in the .neon/tenants/<tenant_id>/timelines/<timeline_id>
9 : //! directory. See docs/pageserver-storage.md for how the files are managed.
10 : //! In addition to the layer files, there is a metadata file in the same
11 : //! directory that contains information about the timeline, in particular its
12 : //! parent timeline, and the last LSN that has been written to disk.
13 : //!
14 :
15 : use std::collections::hash_map::Entry;
16 : use std::collections::{BTreeMap, HashMap, HashSet};
17 : use std::fmt::{Debug, Display};
18 : use std::fs::File;
19 : use std::future::Future;
20 : use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
21 : use std::sync::{Arc, Mutex, Weak};
22 : use std::time::{Duration, Instant, SystemTime};
23 : use std::{fmt, fs};
24 :
25 : use anyhow::{Context, bail};
26 : use arc_swap::ArcSwap;
27 : use camino::{Utf8Path, Utf8PathBuf};
28 : use chrono::NaiveDateTime;
29 : use enumset::EnumSet;
30 : use futures::StreamExt;
31 : use futures::stream::FuturesUnordered;
32 : use itertools::Itertools as _;
33 : use once_cell::sync::Lazy;
34 : pub use pageserver_api::models::TenantState;
35 : use pageserver_api::models::{self, RelSizeMigration};
36 : use pageserver_api::models::{
37 : CompactInfoResponse, LsnLease, TimelineArchivalState, TimelineState, TopTenantShardItem,
38 : WalRedoManagerStatus,
39 : };
40 : use pageserver_api::shard::{ShardIdentity, ShardStripeSize, TenantShardId};
41 : use remote_storage::{DownloadError, GenericRemoteStorage, TimeoutOrCancel};
42 : use remote_timeline_client::index::GcCompactionState;
43 : use remote_timeline_client::manifest::{
44 : LATEST_TENANT_MANIFEST_VERSION, OffloadedTimelineManifest, TenantManifest,
45 : };
46 : use remote_timeline_client::{
47 : FAILED_REMOTE_OP_RETRIES, FAILED_UPLOAD_WARN_THRESHOLD, UploadQueueNotReadyError,
48 : };
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;
81 : use crate::context::RequestContextBuilder;
82 : use crate::context::{DownloadBehavior, RequestContext};
83 : use crate::deletion_queue::{DeletionQueueClient, DeletionQueueError};
84 : use crate::l0_flush::L0FlushGlobalState;
85 : use crate::metrics::{
86 : BROKEN_TENANTS_SET, CIRCUIT_BREAKERS_BROKEN, CIRCUIT_BREAKERS_UNBROKEN, CONCURRENT_INITDBS,
87 : INITDB_RUN_TIME, INITDB_SEMAPHORE_ACQUISITION_TIME, TENANT, TENANT_STATE_METRIC,
88 : TENANT_SYNTHETIC_SIZE_METRIC, remove_tenant_metrics,
89 : };
90 : use crate::task_mgr::TaskKind;
91 : use crate::tenant::config::{LocationMode, TenantConfOpt};
92 : use crate::tenant::gc_result::GcResult;
93 : pub use crate::tenant::remote_timeline_client::index::IndexPart;
94 : use crate::tenant::remote_timeline_client::{
95 : INITDB_PATH, MaybeDeletedIndexPart, remote_initdb_archive_path,
96 : };
97 : use crate::tenant::storage_layer::{DeltaLayer, ImageLayer};
98 : use crate::tenant::timeline::delete::DeleteTimelineFlow;
99 : use crate::tenant::timeline::uninit::cleanup_timeline_directory;
100 : use crate::virtual_file::VirtualFile;
101 : use crate::walingest::WalLagCooldown;
102 : use crate::walredo::PostgresRedoManager;
103 : use crate::{InitializationOrder, TEMP_FILE_SUFFIX, import_datadir, span, task_mgr, walredo};
104 :
105 0 : static INIT_DB_SEMAPHORE: Lazy<Semaphore> = Lazy::new(|| Semaphore::new(8));
106 : use utils::crashsafe;
107 : use utils::generation::Generation;
108 : use utils::id::TimelineId;
109 : use utils::lsn::{Lsn, RecordLsn};
110 :
111 : pub mod blob_io;
112 : pub mod block_io;
113 : pub mod vectored_blob_io;
114 :
115 : pub mod disk_btree;
116 : pub(crate) mod ephemeral_file;
117 : pub mod layer_map;
118 :
119 : pub mod metadata;
120 : pub mod remote_timeline_client;
121 : pub mod storage_layer;
122 :
123 : pub mod checks;
124 : pub mod config;
125 : pub mod mgr;
126 : pub mod secondary;
127 : pub mod tasks;
128 : pub mod upload_queue;
129 :
130 : pub(crate) mod timeline;
131 :
132 : pub mod size;
133 :
134 : mod gc_block;
135 : mod gc_result;
136 : pub(crate) mod throttle;
137 :
138 : pub(crate) use timeline::{LogicalSizeCalculationCause, PageReconstructError, Timeline};
139 :
140 : pub(crate) use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
141 : // re-export for use in walreceiver
142 : pub use crate::tenant::timeline::WalReceiverInfo;
143 :
144 : /// The "tenants" part of `tenants/<tenant>/timelines...`
145 : pub const TENANTS_SEGMENT_NAME: &str = "tenants";
146 :
147 : /// Parts of the `.neon/tenants/<tenant_id>/timelines/<timeline_id>` directory prefix.
148 : pub const TIMELINES_SEGMENT_NAME: &str = "timelines";
149 :
150 : /// References to shared objects that are passed into each tenant, such
151 : /// as the shared remote storage client and process initialization state.
152 : #[derive(Clone)]
153 : pub struct TenantSharedResources {
154 : pub broker_client: storage_broker::BrokerClientChannel,
155 : pub remote_storage: GenericRemoteStorage,
156 : pub deletion_queue_client: DeletionQueueClient,
157 : pub l0_flush_global_state: L0FlushGlobalState,
158 : }
159 :
160 : /// A [`Tenant`] is really an _attached_ tenant. The configuration
161 : /// for an attached tenant is a subset of the [`LocationConf`], represented
162 : /// in this struct.
163 : #[derive(Clone)]
164 : pub(super) struct AttachedTenantConf {
165 : tenant_conf: TenantConfOpt,
166 : location: AttachedLocationConfig,
167 : /// The deadline before which we are blocked from GC so that
168 : /// leases have a chance to be renewed.
169 : lsn_lease_deadline: Option<tokio::time::Instant>,
170 : }
171 :
172 : impl AttachedTenantConf {
173 452 : fn new(tenant_conf: TenantConfOpt, location: AttachedLocationConfig) -> Self {
174 : // Sets a deadline before which we cannot proceed to GC due to lsn lease.
175 : //
176 : // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
177 : // length, we guarantee that all the leases we granted before will have a chance to renew
178 : // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
179 452 : let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
180 452 : Some(
181 452 : tokio::time::Instant::now()
182 452 : + tenant_conf
183 452 : .lsn_lease_length
184 452 : .unwrap_or(LsnLease::DEFAULT_LENGTH),
185 452 : )
186 : } else {
187 : // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
188 : // because we don't do GC in these modes.
189 0 : None
190 : };
191 :
192 452 : Self {
193 452 : tenant_conf,
194 452 : location,
195 452 : lsn_lease_deadline,
196 452 : }
197 452 : }
198 :
199 452 : fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
200 452 : match &location_conf.mode {
201 452 : LocationMode::Attached(attach_conf) => {
202 452 : Ok(Self::new(location_conf.tenant_conf, *attach_conf))
203 : }
204 : LocationMode::Secondary(_) => {
205 0 : anyhow::bail!(
206 0 : "Attempted to construct AttachedTenantConf from a LocationConf in secondary mode"
207 0 : )
208 : }
209 : }
210 452 : }
211 :
212 1524 : fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
213 1524 : self.lsn_lease_deadline
214 1524 : .map(|d| tokio::time::Instant::now() < d)
215 1524 : .unwrap_or(false)
216 1524 : }
217 : }
218 : struct TimelinePreload {
219 : timeline_id: TimelineId,
220 : client: RemoteTimelineClient,
221 : index_part: Result<MaybeDeletedIndexPart, DownloadError>,
222 : previous_heatmap: Option<PreviousHeatmap>,
223 : }
224 :
225 : pub(crate) struct TenantPreload {
226 : tenant_manifest: TenantManifest,
227 : /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
228 : timelines: HashMap<TimelineId, Option<TimelinePreload>>,
229 : }
230 :
231 : /// When we spawn a tenant, there is a special mode for tenant creation that
232 : /// avoids trying to read anything from remote storage.
233 : pub(crate) enum SpawnMode {
234 : /// Activate as soon as possible
235 : Eager,
236 : /// Lazy activation in the background, with the option to skip the queue if the need comes up
237 : Lazy,
238 : }
239 :
240 : ///
241 : /// Tenant consists of multiple timelines. Keep them in a hash table.
242 : ///
243 : pub struct Tenant {
244 : // Global pageserver config parameters
245 : pub conf: &'static PageServerConf,
246 :
247 : /// The value creation timestamp, used to measure activation delay, see:
248 : /// <https://github.com/neondatabase/neon/issues/4025>
249 : constructed_at: Instant,
250 :
251 : state: watch::Sender<TenantState>,
252 :
253 : // Overridden tenant-specific config parameters.
254 : // We keep TenantConfOpt sturct here to preserve the information
255 : // about parameters that are not set.
256 : // This is necessary to allow global config updates.
257 : tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
258 :
259 : tenant_shard_id: TenantShardId,
260 :
261 : // The detailed sharding information, beyond the number/count in tenant_shard_id
262 : shard_identity: ShardIdentity,
263 :
264 : /// The remote storage generation, used to protect S3 objects from split-brain.
265 : /// Does not change over the lifetime of the [`Tenant`] object.
266 : ///
267 : /// This duplicates the generation stored in LocationConf, but that structure is mutable:
268 : /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
269 : generation: Generation,
270 :
271 : timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
272 :
273 : /// During timeline creation, we first insert the TimelineId to the
274 : /// creating map, then `timelines`, then remove it from the creating map.
275 : /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
276 : timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
277 :
278 : /// Possibly offloaded and archived timelines
279 : /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
280 : timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
281 :
282 : /// Serialize writes of the tenant manifest to remote storage. If there are concurrent operations
283 : /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
284 : /// each other (this could be optimized to coalesce writes if necessary).
285 : ///
286 : /// The contents of the Mutex are the last manifest we successfully uploaded
287 : tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
288 :
289 : // This mutex prevents creation of new timelines during GC.
290 : // Adding yet another mutex (in addition to `timelines`) is needed because holding
291 : // `timelines` mutex during all GC iteration
292 : // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
293 : // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
294 : // timeout...
295 : gc_cs: tokio::sync::Mutex<()>,
296 : walredo_mgr: Option<Arc<WalRedoManager>>,
297 :
298 : // provides access to timeline data sitting in the remote storage
299 : pub(crate) remote_storage: GenericRemoteStorage,
300 :
301 : // Access to global deletion queue for when this tenant wants to schedule a deletion
302 : deletion_queue_client: DeletionQueueClient,
303 :
304 : /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
305 : cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
306 : cached_synthetic_tenant_size: Arc<AtomicU64>,
307 :
308 : eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
309 :
310 : /// Track repeated failures to compact, so that we can back off.
311 : /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
312 : compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
313 :
314 : /// Signals the tenant compaction loop that there is L0 compaction work to be done.
315 : pub(crate) l0_compaction_trigger: Arc<Notify>,
316 :
317 : /// Scheduled gc-compaction tasks.
318 : scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
319 :
320 : /// If the tenant is in Activating state, notify this to encourage it
321 : /// to proceed to Active as soon as possible, rather than waiting for lazy
322 : /// background warmup.
323 : pub(crate) activate_now_sem: tokio::sync::Semaphore,
324 :
325 : /// Time it took for the tenant to activate. Zero if not active yet.
326 : attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
327 :
328 : // Cancellation token fires when we have entered shutdown(). This is a parent of
329 : // Timelines' cancellation token.
330 : pub(crate) cancel: CancellationToken,
331 :
332 : // Users of the Tenant such as the page service must take this Gate to avoid
333 : // trying to use a Tenant which is shutting down.
334 : pub(crate) gate: Gate,
335 :
336 : /// Throttle applied at the top of [`Timeline::get`].
337 : /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
338 : pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
339 :
340 : pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
341 :
342 : /// An ongoing timeline detach concurrency limiter.
343 : ///
344 : /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
345 : /// to have two running at the same time. A different one can be started if an earlier one
346 : /// has failed for whatever reason.
347 : ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
348 :
349 : /// `index_part.json` based gc blocking reason tracking.
350 : ///
351 : /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
352 : /// proceeding.
353 : pub(crate) gc_block: gc_block::GcBlock,
354 :
355 : l0_flush_global_state: L0FlushGlobalState,
356 : }
357 : impl std::fmt::Debug for Tenant {
358 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
359 0 : write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
360 0 : }
361 : }
362 :
363 : pub(crate) enum WalRedoManager {
364 : Prod(WalredoManagerId, PostgresRedoManager),
365 : #[cfg(test)]
366 : Test(harness::TestRedoManager),
367 : }
368 :
369 : #[derive(thiserror::Error, Debug)]
370 : #[error("pageserver is shutting down")]
371 : pub(crate) struct GlobalShutDown;
372 :
373 : impl WalRedoManager {
374 0 : pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
375 0 : let id = WalredoManagerId::next();
376 0 : let arc = Arc::new(Self::Prod(id, mgr));
377 0 : let mut guard = WALREDO_MANAGERS.lock().unwrap();
378 0 : match &mut *guard {
379 0 : Some(map) => {
380 0 : map.insert(id, Arc::downgrade(&arc));
381 0 : Ok(arc)
382 : }
383 0 : None => Err(GlobalShutDown),
384 : }
385 0 : }
386 : }
387 :
388 : impl Drop for WalRedoManager {
389 20 : fn drop(&mut self) {
390 20 : match self {
391 0 : Self::Prod(id, _) => {
392 0 : let mut guard = WALREDO_MANAGERS.lock().unwrap();
393 0 : if let Some(map) = &mut *guard {
394 0 : map.remove(id).expect("new() registers, drop() unregisters");
395 0 : }
396 : }
397 : #[cfg(test)]
398 20 : Self::Test(_) => {
399 20 : // Not applicable to test redo manager
400 20 : }
401 : }
402 20 : }
403 : }
404 :
405 : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
406 : /// the walredo processes outside of the regular order.
407 : ///
408 : /// This is necessary to work around a systemd bug where it freezes if there are
409 : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
410 : #[allow(clippy::type_complexity)]
411 : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
412 : Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
413 0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
414 : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
415 : pub(crate) struct WalredoManagerId(u64);
416 : impl WalredoManagerId {
417 0 : pub fn next() -> Self {
418 : static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
419 0 : let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
420 0 : if id == 0 {
421 0 : panic!(
422 0 : "WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique"
423 0 : );
424 0 : }
425 0 : Self(id)
426 0 : }
427 : }
428 :
429 : #[cfg(test)]
430 : impl From<harness::TestRedoManager> for WalRedoManager {
431 452 : fn from(mgr: harness::TestRedoManager) -> Self {
432 452 : Self::Test(mgr)
433 452 : }
434 : }
435 :
436 : impl WalRedoManager {
437 12 : pub(crate) async fn shutdown(&self) -> bool {
438 12 : match self {
439 0 : Self::Prod(_, mgr) => mgr.shutdown().await,
440 : #[cfg(test)]
441 : Self::Test(_) => {
442 : // Not applicable to test redo manager
443 12 : true
444 : }
445 : }
446 12 : }
447 :
448 0 : pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
449 0 : match self {
450 0 : Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
451 0 : #[cfg(test)]
452 0 : Self::Test(_) => {
453 0 : // Not applicable to test redo manager
454 0 : }
455 0 : }
456 0 : }
457 :
458 : /// # Cancel-Safety
459 : ///
460 : /// This method is cancellation-safe.
461 1676 : pub async fn request_redo(
462 1676 : &self,
463 1676 : key: pageserver_api::key::Key,
464 1676 : lsn: Lsn,
465 1676 : base_img: Option<(Lsn, bytes::Bytes)>,
466 1676 : records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
467 1676 : pg_version: u32,
468 1676 : ) -> Result<bytes::Bytes, walredo::Error> {
469 1676 : match self {
470 0 : Self::Prod(_, mgr) => {
471 0 : mgr.request_redo(key, lsn, base_img, records, pg_version)
472 0 : .await
473 : }
474 : #[cfg(test)]
475 1676 : Self::Test(mgr) => {
476 1676 : mgr.request_redo(key, lsn, base_img, records, pg_version)
477 1676 : .await
478 : }
479 : }
480 1676 : }
481 :
482 0 : pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
483 0 : match self {
484 0 : WalRedoManager::Prod(_, m) => Some(m.status()),
485 0 : #[cfg(test)]
486 0 : WalRedoManager::Test(_) => None,
487 0 : }
488 0 : }
489 : }
490 :
491 : /// A very lightweight memory representation of an offloaded timeline.
492 : ///
493 : /// We need to store the list of offloaded timelines so that we can perform operations on them,
494 : /// like unoffloading them, or (at a later date), decide to perform flattening.
495 : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
496 : /// more offloaded timelines than we can manage ones that aren't.
497 : pub struct OffloadedTimeline {
498 : pub tenant_shard_id: TenantShardId,
499 : pub timeline_id: TimelineId,
500 : pub ancestor_timeline_id: Option<TimelineId>,
501 : /// Whether to retain the branch lsn at the ancestor or not
502 : pub ancestor_retain_lsn: Option<Lsn>,
503 :
504 : /// When the timeline was archived.
505 : ///
506 : /// Present for future flattening deliberations.
507 : pub archived_at: NaiveDateTime,
508 :
509 : /// Prevent two tasks from deleting the timeline at the same time. If held, the
510 : /// timeline is being deleted. If 'true', the timeline has already been deleted.
511 : pub delete_progress: TimelineDeleteProgress,
512 :
513 : /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
514 : pub deleted_from_ancestor: AtomicBool,
515 : }
516 :
517 : impl OffloadedTimeline {
518 : /// Obtains an offloaded timeline from a given timeline object.
519 : ///
520 : /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
521 : /// the timeline is not in a stopped state.
522 : /// Panics if the timeline is not archived.
523 4 : fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
524 4 : let (ancestor_retain_lsn, ancestor_timeline_id) =
525 4 : if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
526 4 : let ancestor_lsn = timeline.get_ancestor_lsn();
527 4 : let ancestor_timeline_id = ancestor_timeline.timeline_id;
528 4 : let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
529 4 : gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
530 4 : (Some(ancestor_lsn), Some(ancestor_timeline_id))
531 : } else {
532 0 : (None, None)
533 : };
534 4 : let archived_at = timeline
535 4 : .remote_client
536 4 : .archived_at_stopped_queue()?
537 4 : .expect("must be called on an archived timeline");
538 4 : Ok(Self {
539 4 : tenant_shard_id: timeline.tenant_shard_id,
540 4 : timeline_id: timeline.timeline_id,
541 4 : ancestor_timeline_id,
542 4 : ancestor_retain_lsn,
543 4 : archived_at,
544 4 :
545 4 : delete_progress: timeline.delete_progress.clone(),
546 4 : deleted_from_ancestor: AtomicBool::new(false),
547 4 : })
548 4 : }
549 0 : fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
550 0 : // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
551 0 : // by the `initialize_gc_info` function.
552 0 : let OffloadedTimelineManifest {
553 0 : timeline_id,
554 0 : ancestor_timeline_id,
555 0 : ancestor_retain_lsn,
556 0 : archived_at,
557 0 : } = *manifest;
558 0 : Self {
559 0 : tenant_shard_id,
560 0 : timeline_id,
561 0 : ancestor_timeline_id,
562 0 : ancestor_retain_lsn,
563 0 : archived_at,
564 0 : delete_progress: TimelineDeleteProgress::default(),
565 0 : deleted_from_ancestor: AtomicBool::new(false),
566 0 : }
567 0 : }
568 4 : fn manifest(&self) -> OffloadedTimelineManifest {
569 4 : let Self {
570 4 : timeline_id,
571 4 : ancestor_timeline_id,
572 4 : ancestor_retain_lsn,
573 4 : archived_at,
574 4 : ..
575 4 : } = self;
576 4 : OffloadedTimelineManifest {
577 4 : timeline_id: *timeline_id,
578 4 : ancestor_timeline_id: *ancestor_timeline_id,
579 4 : ancestor_retain_lsn: *ancestor_retain_lsn,
580 4 : archived_at: *archived_at,
581 4 : }
582 4 : }
583 : /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
584 0 : fn delete_from_ancestor_with_timelines(
585 0 : &self,
586 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
587 0 : ) {
588 0 : if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
589 0 : (self.ancestor_retain_lsn, self.ancestor_timeline_id)
590 : {
591 0 : if let Some((_, ancestor_timeline)) = timelines
592 0 : .iter()
593 0 : .find(|(tid, _tl)| **tid == ancestor_timeline_id)
594 : {
595 0 : let removal_happened = ancestor_timeline
596 0 : .gc_info
597 0 : .write()
598 0 : .unwrap()
599 0 : .remove_child_offloaded(self.timeline_id);
600 0 : if !removal_happened {
601 0 : tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
602 0 : "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
603 0 : }
604 0 : }
605 0 : }
606 0 : self.deleted_from_ancestor.store(true, Ordering::Release);
607 0 : }
608 : /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
609 : ///
610 : /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
611 4 : fn defuse_for_tenant_drop(&self) {
612 4 : self.deleted_from_ancestor.store(true, Ordering::Release);
613 4 : }
614 : }
615 :
616 : impl fmt::Debug for OffloadedTimeline {
617 0 : fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618 0 : write!(f, "OffloadedTimeline<{}>", self.timeline_id)
619 0 : }
620 : }
621 :
622 : impl Drop for OffloadedTimeline {
623 4 : fn drop(&mut self) {
624 4 : if !self.deleted_from_ancestor.load(Ordering::Acquire) {
625 0 : tracing::warn!(
626 0 : "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
627 : self.timeline_id
628 : );
629 4 : }
630 4 : }
631 : }
632 :
633 : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
634 : pub enum MaybeOffloaded {
635 : Yes,
636 : No,
637 : }
638 :
639 : #[derive(Clone, Debug)]
640 : pub enum TimelineOrOffloaded {
641 : Timeline(Arc<Timeline>),
642 : Offloaded(Arc<OffloadedTimeline>),
643 : }
644 :
645 : impl TimelineOrOffloaded {
646 0 : pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
647 0 : match self {
648 0 : TimelineOrOffloaded::Timeline(timeline) => {
649 0 : TimelineOrOffloadedArcRef::Timeline(timeline)
650 : }
651 0 : TimelineOrOffloaded::Offloaded(offloaded) => {
652 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded)
653 : }
654 : }
655 0 : }
656 0 : pub fn tenant_shard_id(&self) -> TenantShardId {
657 0 : self.arc_ref().tenant_shard_id()
658 0 : }
659 0 : pub fn timeline_id(&self) -> TimelineId {
660 0 : self.arc_ref().timeline_id()
661 0 : }
662 4 : pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
663 4 : match self {
664 4 : TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
665 0 : TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
666 : }
667 4 : }
668 0 : fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
669 0 : match self {
670 0 : TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
671 0 : TimelineOrOffloaded::Offloaded(_offloaded) => None,
672 : }
673 0 : }
674 : }
675 :
676 : pub enum TimelineOrOffloadedArcRef<'a> {
677 : Timeline(&'a Arc<Timeline>),
678 : Offloaded(&'a Arc<OffloadedTimeline>),
679 : }
680 :
681 : impl TimelineOrOffloadedArcRef<'_> {
682 0 : pub fn tenant_shard_id(&self) -> TenantShardId {
683 0 : match self {
684 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
685 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
686 : }
687 0 : }
688 0 : pub fn timeline_id(&self) -> TimelineId {
689 0 : match self {
690 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
691 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
692 : }
693 0 : }
694 : }
695 :
696 : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
697 0 : fn from(timeline: &'a Arc<Timeline>) -> Self {
698 0 : Self::Timeline(timeline)
699 0 : }
700 : }
701 :
702 : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
703 0 : fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
704 0 : Self::Offloaded(timeline)
705 0 : }
706 : }
707 :
708 : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
709 : pub enum GetTimelineError {
710 : #[error("Timeline is shutting down")]
711 : ShuttingDown,
712 : #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
713 : NotActive {
714 : tenant_id: TenantShardId,
715 : timeline_id: TimelineId,
716 : state: TimelineState,
717 : },
718 : #[error("Timeline {tenant_id}/{timeline_id} was not found")]
719 : NotFound {
720 : tenant_id: TenantShardId,
721 : timeline_id: TimelineId,
722 : },
723 : }
724 :
725 : #[derive(Debug, thiserror::Error)]
726 : pub enum LoadLocalTimelineError {
727 : #[error("FailedToLoad")]
728 : Load(#[source] anyhow::Error),
729 : #[error("FailedToResumeDeletion")]
730 : ResumeDeletion(#[source] anyhow::Error),
731 : }
732 :
733 : #[derive(thiserror::Error)]
734 : pub enum DeleteTimelineError {
735 : #[error("NotFound")]
736 : NotFound,
737 :
738 : #[error("HasChildren")]
739 : HasChildren(Vec<TimelineId>),
740 :
741 : #[error("Timeline deletion is already in progress")]
742 : AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
743 :
744 : #[error("Cancelled")]
745 : Cancelled,
746 :
747 : #[error(transparent)]
748 : Other(#[from] anyhow::Error),
749 : }
750 :
751 : impl Debug for DeleteTimelineError {
752 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
753 0 : match self {
754 0 : Self::NotFound => write!(f, "NotFound"),
755 0 : Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
756 0 : Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
757 0 : Self::Cancelled => f.debug_tuple("Cancelled").finish(),
758 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
759 : }
760 0 : }
761 : }
762 :
763 : #[derive(thiserror::Error)]
764 : pub enum TimelineArchivalError {
765 : #[error("NotFound")]
766 : NotFound,
767 :
768 : #[error("Timeout")]
769 : Timeout,
770 :
771 : #[error("Cancelled")]
772 : Cancelled,
773 :
774 : #[error("ancestor is archived: {}", .0)]
775 : HasArchivedParent(TimelineId),
776 :
777 : #[error("HasUnarchivedChildren")]
778 : HasUnarchivedChildren(Vec<TimelineId>),
779 :
780 : #[error("Timeline archival is already in progress")]
781 : AlreadyInProgress,
782 :
783 : #[error(transparent)]
784 : Other(anyhow::Error),
785 : }
786 :
787 : #[derive(thiserror::Error, Debug)]
788 : pub(crate) enum TenantManifestError {
789 : #[error("Remote storage error: {0}")]
790 : RemoteStorage(anyhow::Error),
791 :
792 : #[error("Cancelled")]
793 : Cancelled,
794 : }
795 :
796 : impl From<TenantManifestError> for TimelineArchivalError {
797 0 : fn from(e: TenantManifestError) -> Self {
798 0 : match e {
799 0 : TenantManifestError::RemoteStorage(e) => Self::Other(e),
800 0 : TenantManifestError::Cancelled => Self::Cancelled,
801 : }
802 0 : }
803 : }
804 :
805 : impl Debug for TimelineArchivalError {
806 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
807 0 : match self {
808 0 : Self::NotFound => write!(f, "NotFound"),
809 0 : Self::Timeout => write!(f, "Timeout"),
810 0 : Self::Cancelled => write!(f, "Cancelled"),
811 0 : Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
812 0 : Self::HasUnarchivedChildren(c) => {
813 0 : f.debug_tuple("HasUnarchivedChildren").field(c).finish()
814 : }
815 0 : Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
816 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
817 : }
818 0 : }
819 : }
820 :
821 : pub enum SetStoppingError {
822 : AlreadyStopping(completion::Barrier),
823 : Broken,
824 : }
825 :
826 : impl Debug for SetStoppingError {
827 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
828 0 : match self {
829 0 : Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
830 0 : Self::Broken => write!(f, "Broken"),
831 : }
832 0 : }
833 : }
834 :
835 : /// Arguments to [`Tenant::create_timeline`].
836 : ///
837 : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
838 : /// is `None`, the result of the timeline create call is not deterministic.
839 : ///
840 : /// See [`CreateTimelineIdempotency`] for an idempotency key.
841 : #[derive(Debug)]
842 : pub(crate) enum CreateTimelineParams {
843 : Bootstrap(CreateTimelineParamsBootstrap),
844 : Branch(CreateTimelineParamsBranch),
845 : ImportPgdata(CreateTimelineParamsImportPgdata),
846 : }
847 :
848 : #[derive(Debug)]
849 : pub(crate) struct CreateTimelineParamsBootstrap {
850 : pub(crate) new_timeline_id: TimelineId,
851 : pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
852 : pub(crate) pg_version: u32,
853 : }
854 :
855 : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
856 : #[derive(Debug)]
857 : pub(crate) struct CreateTimelineParamsBranch {
858 : pub(crate) new_timeline_id: TimelineId,
859 : pub(crate) ancestor_timeline_id: TimelineId,
860 : pub(crate) ancestor_start_lsn: Option<Lsn>,
861 : }
862 :
863 : #[derive(Debug)]
864 : pub(crate) struct CreateTimelineParamsImportPgdata {
865 : pub(crate) new_timeline_id: TimelineId,
866 : pub(crate) location: import_pgdata::index_part_format::Location,
867 : pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
868 : }
869 :
870 : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in [`Tenant::start_creating_timeline`] in [`Tenant::start_creating_timeline`].
871 : ///
872 : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
873 : ///
874 : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
875 : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
876 : ///
877 : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
878 : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
879 : ///
880 : /// Notes:
881 : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
882 : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
883 : /// is not considered for idempotency. We can improve on this over time if we deem it necessary.
884 : ///
885 : #[derive(Debug, Clone, PartialEq, Eq)]
886 : pub(crate) enum CreateTimelineIdempotency {
887 : /// NB: special treatment, see comment in [`Self`].
888 : FailWithConflict,
889 : Bootstrap {
890 : pg_version: u32,
891 : },
892 : /// NB: branches always have the same `pg_version` as their ancestor.
893 : /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
894 : /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
895 : /// determining the child branch pg_version.
896 : Branch {
897 : ancestor_timeline_id: TimelineId,
898 : ancestor_start_lsn: Lsn,
899 : },
900 : ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
901 : }
902 :
903 : #[derive(Debug, Clone, PartialEq, Eq)]
904 : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
905 : idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
906 : }
907 :
908 : /// What is returned by [`Tenant::start_creating_timeline`].
909 : #[must_use]
910 : enum StartCreatingTimelineResult {
911 : CreateGuard(TimelineCreateGuard),
912 : Idempotent(Arc<Timeline>),
913 : }
914 :
915 : #[allow(clippy::large_enum_variant, reason = "TODO")]
916 : enum TimelineInitAndSyncResult {
917 : ReadyToActivate(Arc<Timeline>),
918 : NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
919 : }
920 :
921 : impl TimelineInitAndSyncResult {
922 0 : fn ready_to_activate(self) -> Option<Arc<Timeline>> {
923 0 : match self {
924 0 : Self::ReadyToActivate(timeline) => Some(timeline),
925 0 : _ => None,
926 : }
927 0 : }
928 : }
929 :
930 : #[must_use]
931 : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
932 : timeline: Arc<Timeline>,
933 : import_pgdata: import_pgdata::index_part_format::Root,
934 : guard: TimelineCreateGuard,
935 : }
936 :
937 : /// What is returned by [`Tenant::create_timeline`].
938 : enum CreateTimelineResult {
939 : Created(Arc<Timeline>),
940 : Idempotent(Arc<Timeline>),
941 : /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
942 : /// we return this result, nor will this concrete object ever be added there.
943 : /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
944 : ImportSpawned(Arc<Timeline>),
945 : }
946 :
947 : impl CreateTimelineResult {
948 0 : fn discriminant(&self) -> &'static str {
949 0 : match self {
950 0 : Self::Created(_) => "Created",
951 0 : Self::Idempotent(_) => "Idempotent",
952 0 : Self::ImportSpawned(_) => "ImportSpawned",
953 : }
954 0 : }
955 0 : fn timeline(&self) -> &Arc<Timeline> {
956 0 : match self {
957 0 : Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
958 0 : }
959 0 : }
960 : /// Unit test timelines aren't activated, test has to do it if it needs to.
961 : #[cfg(test)]
962 460 : fn into_timeline_for_test(self) -> Arc<Timeline> {
963 460 : match self {
964 460 : Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
965 460 : }
966 460 : }
967 : }
968 :
969 : #[derive(thiserror::Error, Debug)]
970 : pub enum CreateTimelineError {
971 : #[error("creation of timeline with the given ID is in progress")]
972 : AlreadyCreating,
973 : #[error("timeline already exists with different parameters")]
974 : Conflict,
975 : #[error(transparent)]
976 : AncestorLsn(anyhow::Error),
977 : #[error("ancestor timeline is not active")]
978 : AncestorNotActive,
979 : #[error("ancestor timeline is archived")]
980 : AncestorArchived,
981 : #[error("tenant shutting down")]
982 : ShuttingDown,
983 : #[error(transparent)]
984 : Other(#[from] anyhow::Error),
985 : }
986 :
987 : #[derive(thiserror::Error, Debug)]
988 : pub enum InitdbError {
989 : #[error("Operation was cancelled")]
990 : Cancelled,
991 : #[error(transparent)]
992 : Other(anyhow::Error),
993 : #[error(transparent)]
994 : Inner(postgres_initdb::Error),
995 : }
996 :
997 : enum CreateTimelineCause {
998 : Load,
999 : Delete,
1000 : }
1001 :
1002 : #[allow(clippy::large_enum_variant, reason = "TODO")]
1003 : enum LoadTimelineCause {
1004 : Attach,
1005 : Unoffload,
1006 : ImportPgdata {
1007 : create_guard: TimelineCreateGuard,
1008 : activate: ActivateTimelineArgs,
1009 : },
1010 : }
1011 :
1012 : #[derive(thiserror::Error, Debug)]
1013 : pub(crate) enum GcError {
1014 : // The tenant is shutting down
1015 : #[error("tenant shutting down")]
1016 : TenantCancelled,
1017 :
1018 : // The tenant is shutting down
1019 : #[error("timeline shutting down")]
1020 : TimelineCancelled,
1021 :
1022 : // The tenant is in a state inelegible to run GC
1023 : #[error("not active")]
1024 : NotActive,
1025 :
1026 : // A requested GC cutoff LSN was invalid, for example it tried to move backwards
1027 : #[error("not active")]
1028 : BadLsn { why: String },
1029 :
1030 : // A remote storage error while scheduling updates after compaction
1031 : #[error(transparent)]
1032 : Remote(anyhow::Error),
1033 :
1034 : // An error reading while calculating GC cutoffs
1035 : #[error(transparent)]
1036 : GcCutoffs(PageReconstructError),
1037 :
1038 : // If GC was invoked for a particular timeline, this error means it didn't exist
1039 : #[error("timeline not found")]
1040 : TimelineNotFound,
1041 : }
1042 :
1043 : impl From<PageReconstructError> for GcError {
1044 0 : fn from(value: PageReconstructError) -> Self {
1045 0 : match value {
1046 0 : PageReconstructError::Cancelled => Self::TimelineCancelled,
1047 0 : other => Self::GcCutoffs(other),
1048 : }
1049 0 : }
1050 : }
1051 :
1052 : impl From<NotInitialized> for GcError {
1053 0 : fn from(value: NotInitialized) -> Self {
1054 0 : match value {
1055 0 : NotInitialized::Uninitialized => GcError::Remote(value.into()),
1056 0 : NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
1057 : }
1058 0 : }
1059 : }
1060 :
1061 : impl From<timeline::layer_manager::Shutdown> for GcError {
1062 0 : fn from(_: timeline::layer_manager::Shutdown) -> Self {
1063 0 : GcError::TimelineCancelled
1064 0 : }
1065 : }
1066 :
1067 : #[derive(thiserror::Error, Debug)]
1068 : pub(crate) enum LoadConfigError {
1069 : #[error("TOML deserialization error: '{0}'")]
1070 : DeserializeToml(#[from] toml_edit::de::Error),
1071 :
1072 : #[error("Config not found at {0}")]
1073 : NotFound(Utf8PathBuf),
1074 : }
1075 :
1076 : impl Tenant {
1077 : /// Yet another helper for timeline initialization.
1078 : ///
1079 : /// - Initializes the Timeline struct and inserts it into the tenant's hash map
1080 : /// - Scans the local timeline directory for layer files and builds the layer map
1081 : /// - Downloads remote index file and adds remote files to the layer map
1082 : /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
1083 : ///
1084 : /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
1085 : /// it is marked as Active.
1086 : #[allow(clippy::too_many_arguments)]
1087 12 : async fn timeline_init_and_sync(
1088 12 : self: &Arc<Self>,
1089 12 : timeline_id: TimelineId,
1090 12 : resources: TimelineResources,
1091 12 : mut index_part: IndexPart,
1092 12 : metadata: TimelineMetadata,
1093 12 : previous_heatmap: Option<PreviousHeatmap>,
1094 12 : ancestor: Option<Arc<Timeline>>,
1095 12 : cause: LoadTimelineCause,
1096 12 : ctx: &RequestContext,
1097 12 : ) -> anyhow::Result<TimelineInitAndSyncResult> {
1098 12 : let tenant_id = self.tenant_shard_id;
1099 12 :
1100 12 : let import_pgdata = index_part.import_pgdata.take();
1101 12 : let idempotency = match &import_pgdata {
1102 0 : Some(import_pgdata) => {
1103 0 : CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
1104 0 : idempotency_key: import_pgdata.idempotency_key().clone(),
1105 0 : })
1106 : }
1107 : None => {
1108 12 : if metadata.ancestor_timeline().is_none() {
1109 8 : CreateTimelineIdempotency::Bootstrap {
1110 8 : pg_version: metadata.pg_version(),
1111 8 : }
1112 : } else {
1113 4 : CreateTimelineIdempotency::Branch {
1114 4 : ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
1115 4 : ancestor_start_lsn: metadata.ancestor_lsn(),
1116 4 : }
1117 : }
1118 : }
1119 : };
1120 :
1121 12 : let (timeline, timeline_ctx) = self.create_timeline_struct(
1122 12 : timeline_id,
1123 12 : &metadata,
1124 12 : previous_heatmap,
1125 12 : ancestor.clone(),
1126 12 : resources,
1127 12 : CreateTimelineCause::Load,
1128 12 : idempotency.clone(),
1129 12 : index_part.gc_compaction.clone(),
1130 12 : index_part.rel_size_migration.clone(),
1131 12 : ctx,
1132 12 : )?;
1133 12 : let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
1134 12 : anyhow::ensure!(
1135 12 : disk_consistent_lsn.is_valid(),
1136 0 : "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
1137 : );
1138 12 : assert_eq!(
1139 12 : disk_consistent_lsn,
1140 12 : metadata.disk_consistent_lsn(),
1141 0 : "these are used interchangeably"
1142 : );
1143 :
1144 12 : timeline.remote_client.init_upload_queue(&index_part)?;
1145 :
1146 12 : timeline
1147 12 : .load_layer_map(disk_consistent_lsn, index_part)
1148 12 : .await
1149 12 : .with_context(|| {
1150 0 : format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
1151 12 : })?;
1152 :
1153 : // When unarchiving, we've mostly likely lost the heatmap generated prior
1154 : // to the archival operation. To allow warming this timeline up, generate
1155 : // a previous heatmap which contains all visible layers in the layer map.
1156 : // This previous heatmap will be used whenever a fresh heatmap is generated
1157 : // for the timeline.
1158 12 : if self.conf.generate_unarchival_heatmap && matches!(cause, LoadTimelineCause::Unoffload) {
1159 0 : let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
1160 0 : while let Some((tline, end_lsn)) = tline_ending_at {
1161 0 : let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
1162 : // Another unearchived timeline might have generated a heatmap for this ancestor.
1163 : // If the current branch point greater than the previous one use the the heatmap
1164 : // we just generated - it should include more layers.
1165 0 : if !tline.should_keep_previous_heatmap(end_lsn) {
1166 0 : tline
1167 0 : .previous_heatmap
1168 0 : .store(Some(Arc::new(unarchival_heatmap)));
1169 0 : } else {
1170 0 : tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
1171 : }
1172 :
1173 0 : match tline.ancestor_timeline() {
1174 0 : Some(ancestor) => {
1175 0 : if ancestor.update_layer_visibility().await.is_err() {
1176 : // Ancestor timeline is shutting down.
1177 0 : break;
1178 0 : }
1179 0 :
1180 0 : tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
1181 : }
1182 0 : None => {
1183 0 : tline_ending_at = None;
1184 0 : }
1185 : }
1186 : }
1187 12 : }
1188 :
1189 0 : match import_pgdata {
1190 0 : Some(import_pgdata) if !import_pgdata.is_done() => {
1191 0 : match cause {
1192 0 : LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
1193 : LoadTimelineCause::ImportPgdata { .. } => {
1194 0 : unreachable!(
1195 0 : "ImportPgdata should not be reloading timeline import is done and persisted as such in s3"
1196 0 : )
1197 : }
1198 : }
1199 0 : let mut guard = self.timelines_creating.lock().unwrap();
1200 0 : if !guard.insert(timeline_id) {
1201 : // We should never try and load the same timeline twice during startup
1202 0 : unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
1203 0 : }
1204 0 : let timeline_create_guard = TimelineCreateGuard {
1205 0 : _tenant_gate_guard: self.gate.enter()?,
1206 0 : owning_tenant: self.clone(),
1207 0 : timeline_id,
1208 0 : idempotency,
1209 0 : // The users of this specific return value don't need the timline_path in there.
1210 0 : timeline_path: timeline
1211 0 : .conf
1212 0 : .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
1213 0 : };
1214 0 : Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
1215 0 : TimelineInitAndSyncNeedsSpawnImportPgdata {
1216 0 : timeline,
1217 0 : import_pgdata,
1218 0 : guard: timeline_create_guard,
1219 0 : },
1220 0 : ))
1221 : }
1222 : Some(_) | None => {
1223 : {
1224 12 : let mut timelines_accessor = self.timelines.lock().unwrap();
1225 12 : match timelines_accessor.entry(timeline_id) {
1226 : // We should never try and load the same timeline twice during startup
1227 : Entry::Occupied(_) => {
1228 0 : unreachable!(
1229 0 : "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
1230 0 : );
1231 : }
1232 12 : Entry::Vacant(v) => {
1233 12 : v.insert(Arc::clone(&timeline));
1234 12 : timeline.maybe_spawn_flush_loop();
1235 12 : }
1236 : }
1237 : }
1238 :
1239 : // Sanity check: a timeline should have some content.
1240 12 : anyhow::ensure!(
1241 12 : ancestor.is_some()
1242 8 : || timeline
1243 8 : .layers
1244 8 : .read()
1245 8 : .await
1246 8 : .layer_map()
1247 8 : .expect("currently loading, layer manager cannot be shutdown already")
1248 8 : .iter_historic_layers()
1249 8 : .next()
1250 8 : .is_some(),
1251 0 : "Timeline has no ancestor and no layer files"
1252 : );
1253 :
1254 12 : match cause {
1255 12 : LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
1256 : LoadTimelineCause::ImportPgdata {
1257 0 : create_guard,
1258 0 : activate,
1259 0 : } => {
1260 0 : // TODO: see the comment in the task code above how I'm not so certain
1261 0 : // it is safe to activate here because of concurrent shutdowns.
1262 0 : match activate {
1263 0 : ActivateTimelineArgs::Yes { broker_client } => {
1264 0 : info!("activating timeline after reload from pgdata import task");
1265 0 : timeline.activate(self.clone(), broker_client, None, &timeline_ctx);
1266 : }
1267 0 : ActivateTimelineArgs::No => (),
1268 : }
1269 0 : drop(create_guard);
1270 : }
1271 : }
1272 :
1273 12 : Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
1274 : }
1275 : }
1276 12 : }
1277 :
1278 : /// Attach a tenant that's available in cloud storage.
1279 : ///
1280 : /// This returns quickly, after just creating the in-memory object
1281 : /// Tenant struct and launching a background task to download
1282 : /// the remote index files. On return, the tenant is most likely still in
1283 : /// Attaching state, and it will become Active once the background task
1284 : /// finishes. You can use wait_until_active() to wait for the task to
1285 : /// complete.
1286 : ///
1287 : #[allow(clippy::too_many_arguments)]
1288 0 : pub(crate) fn spawn(
1289 0 : conf: &'static PageServerConf,
1290 0 : tenant_shard_id: TenantShardId,
1291 0 : resources: TenantSharedResources,
1292 0 : attached_conf: AttachedTenantConf,
1293 0 : shard_identity: ShardIdentity,
1294 0 : init_order: Option<InitializationOrder>,
1295 0 : mode: SpawnMode,
1296 0 : ctx: &RequestContext,
1297 0 : ) -> Result<Arc<Tenant>, GlobalShutDown> {
1298 0 : let wal_redo_manager =
1299 0 : WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
1300 :
1301 : let TenantSharedResources {
1302 0 : broker_client,
1303 0 : remote_storage,
1304 0 : deletion_queue_client,
1305 0 : l0_flush_global_state,
1306 0 : } = resources;
1307 0 :
1308 0 : let attach_mode = attached_conf.location.attach_mode;
1309 0 : let generation = attached_conf.location.generation;
1310 0 :
1311 0 : let tenant = Arc::new(Tenant::new(
1312 0 : TenantState::Attaching,
1313 0 : conf,
1314 0 : attached_conf,
1315 0 : shard_identity,
1316 0 : Some(wal_redo_manager),
1317 0 : tenant_shard_id,
1318 0 : remote_storage.clone(),
1319 0 : deletion_queue_client,
1320 0 : l0_flush_global_state,
1321 0 : ));
1322 0 :
1323 0 : // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
1324 0 : // we shut down while attaching.
1325 0 : let attach_gate_guard = tenant
1326 0 : .gate
1327 0 : .enter()
1328 0 : .expect("We just created the Tenant: nothing else can have shut it down yet");
1329 0 :
1330 0 : // Do all the hard work in the background
1331 0 : let tenant_clone = Arc::clone(&tenant);
1332 0 : let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
1333 0 : task_mgr::spawn(
1334 0 : &tokio::runtime::Handle::current(),
1335 0 : TaskKind::Attach,
1336 0 : tenant_shard_id,
1337 0 : None,
1338 0 : "attach tenant",
1339 0 : async move {
1340 0 :
1341 0 : info!(
1342 : ?attach_mode,
1343 0 : "Attaching tenant"
1344 : );
1345 :
1346 0 : let _gate_guard = attach_gate_guard;
1347 0 :
1348 0 : // Is this tenant being spawned as part of process startup?
1349 0 : let starting_up = init_order.is_some();
1350 0 : scopeguard::defer! {
1351 0 : if starting_up {
1352 0 : TENANT.startup_complete.inc();
1353 0 : }
1354 0 : }
1355 :
1356 : // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
1357 : enum BrokenVerbosity {
1358 : Error,
1359 : Info
1360 : }
1361 0 : let make_broken =
1362 0 : |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
1363 0 : match verbosity {
1364 : BrokenVerbosity::Info => {
1365 0 : info!("attach cancelled, setting tenant state to Broken: {err}");
1366 : },
1367 : BrokenVerbosity::Error => {
1368 0 : error!("attach failed, setting tenant state to Broken: {err:?}");
1369 : }
1370 : }
1371 0 : t.state.send_modify(|state| {
1372 0 : // The Stopping case is for when we have passed control on to DeleteTenantFlow:
1373 0 : // if it errors, we will call make_broken when tenant is already in Stopping.
1374 0 : assert!(
1375 0 : matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
1376 0 : "the attach task owns the tenant state until activation is complete"
1377 : );
1378 :
1379 0 : *state = TenantState::broken_from_reason(err.to_string());
1380 0 : });
1381 0 : };
1382 :
1383 : // TODO: should also be rejecting tenant conf changes that violate this check.
1384 0 : if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
1385 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1386 0 : return Ok(());
1387 0 : }
1388 0 :
1389 0 : let mut init_order = init_order;
1390 0 : // take the completion because initial tenant loading will complete when all of
1391 0 : // these tasks complete.
1392 0 : let _completion = init_order
1393 0 : .as_mut()
1394 0 : .and_then(|x| x.initial_tenant_load.take());
1395 0 : let remote_load_completion = init_order
1396 0 : .as_mut()
1397 0 : .and_then(|x| x.initial_tenant_load_remote.take());
1398 :
1399 : enum AttachType<'a> {
1400 : /// We are attaching this tenant lazily in the background.
1401 : Warmup {
1402 : _permit: tokio::sync::SemaphorePermit<'a>,
1403 : during_startup: bool
1404 : },
1405 : /// We are attaching this tenant as soon as we can, because for example an
1406 : /// endpoint tried to access it.
1407 : OnDemand,
1408 : /// During normal operations after startup, we are attaching a tenant, and
1409 : /// eager attach was requested.
1410 : Normal,
1411 : }
1412 :
1413 0 : let attach_type = if matches!(mode, SpawnMode::Lazy) {
1414 : // Before doing any I/O, wait for at least one of:
1415 : // - A client attempting to access to this tenant (on-demand loading)
1416 : // - A permit becoming available in the warmup semaphore (background warmup)
1417 :
1418 0 : tokio::select!(
1419 0 : permit = tenant_clone.activate_now_sem.acquire() => {
1420 0 : let _ = permit.expect("activate_now_sem is never closed");
1421 0 : tracing::info!("Activating tenant (on-demand)");
1422 0 : AttachType::OnDemand
1423 : },
1424 0 : permit = conf.concurrent_tenant_warmup.inner().acquire() => {
1425 0 : let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
1426 0 : tracing::info!("Activating tenant (warmup)");
1427 0 : AttachType::Warmup {
1428 0 : _permit,
1429 0 : during_startup: init_order.is_some()
1430 0 : }
1431 : }
1432 0 : _ = tenant_clone.cancel.cancelled() => {
1433 : // This is safe, but should be pretty rare: it is interesting if a tenant
1434 : // stayed in Activating for such a long time that shutdown found it in
1435 : // that state.
1436 0 : tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
1437 : // Make the tenant broken so that set_stopping will not hang waiting for it to leave
1438 : // the Attaching state. This is an over-reaction (nothing really broke, the tenant is
1439 : // just shutting down), but ensures progress.
1440 0 : make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
1441 0 : return Ok(());
1442 : },
1443 : )
1444 : } else {
1445 : // SpawnMode::{Create,Eager} always cause jumping ahead of the
1446 : // concurrent_tenant_warmup queue
1447 0 : AttachType::Normal
1448 : };
1449 :
1450 0 : let preload = match &mode {
1451 : SpawnMode::Eager | SpawnMode::Lazy => {
1452 0 : let _preload_timer = TENANT.preload.start_timer();
1453 0 : let res = tenant_clone
1454 0 : .preload(&remote_storage, task_mgr::shutdown_token())
1455 0 : .await;
1456 0 : match res {
1457 0 : Ok(p) => Some(p),
1458 0 : Err(e) => {
1459 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1460 0 : return Ok(());
1461 : }
1462 : }
1463 : }
1464 :
1465 : };
1466 :
1467 : // Remote preload is complete.
1468 0 : drop(remote_load_completion);
1469 0 :
1470 0 :
1471 0 : // We will time the duration of the attach phase unless this is a creation (attach will do no work)
1472 0 : let attach_start = std::time::Instant::now();
1473 0 : let attached = {
1474 0 : let _attach_timer = Some(TENANT.attach.start_timer());
1475 0 : tenant_clone.attach(preload, &ctx).await
1476 : };
1477 0 : let attach_duration = attach_start.elapsed();
1478 0 : _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
1479 0 :
1480 0 : match attached {
1481 : Ok(()) => {
1482 0 : info!("attach finished, activating");
1483 0 : tenant_clone.activate(broker_client, None, &ctx);
1484 : }
1485 0 : Err(e) => {
1486 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1487 0 : }
1488 : }
1489 :
1490 : // If we are doing an opportunistic warmup attachment at startup, initialize
1491 : // logical size at the same time. This is better than starting a bunch of idle tenants
1492 : // with cold caches and then coming back later to initialize their logical sizes.
1493 : //
1494 : // It also prevents the warmup proccess competing with the concurrency limit on
1495 : // logical size calculations: if logical size calculation semaphore is saturated,
1496 : // then warmup will wait for that before proceeding to the next tenant.
1497 0 : if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
1498 0 : let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
1499 0 : tracing::info!("Waiting for initial logical sizes while warming up...");
1500 0 : while futs.next().await.is_some() {}
1501 0 : tracing::info!("Warm-up complete");
1502 0 : }
1503 :
1504 0 : Ok(())
1505 0 : }
1506 0 : .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
1507 : );
1508 0 : Ok(tenant)
1509 0 : }
1510 :
1511 : #[instrument(skip_all)]
1512 : pub(crate) async fn preload(
1513 : self: &Arc<Self>,
1514 : remote_storage: &GenericRemoteStorage,
1515 : cancel: CancellationToken,
1516 : ) -> anyhow::Result<TenantPreload> {
1517 : span::debug_assert_current_span_has_tenant_id();
1518 : // Get list of remote timelines
1519 : // download index files for every tenant timeline
1520 : info!("listing remote timelines");
1521 : let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
1522 : remote_storage,
1523 : self.tenant_shard_id,
1524 : cancel.clone(),
1525 : )
1526 : .await?;
1527 : let (offloaded_add, tenant_manifest) =
1528 : match remote_timeline_client::download_tenant_manifest(
1529 : remote_storage,
1530 : &self.tenant_shard_id,
1531 : self.generation,
1532 : &cancel,
1533 : )
1534 : .await
1535 : {
1536 : Ok((tenant_manifest, _generation, _manifest_mtime)) => (
1537 : format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
1538 : tenant_manifest,
1539 : ),
1540 : Err(DownloadError::NotFound) => {
1541 : ("no manifest".to_string(), TenantManifest::empty())
1542 : }
1543 : Err(e) => Err(e)?,
1544 : };
1545 :
1546 : info!(
1547 : "found {} timelines, and {offloaded_add}",
1548 : remote_timeline_ids.len()
1549 : );
1550 :
1551 : for k in other_keys {
1552 : warn!("Unexpected non timeline key {k}");
1553 : }
1554 :
1555 : // Avoid downloading IndexPart of offloaded timelines.
1556 : let mut offloaded_with_prefix = HashSet::new();
1557 : for offloaded in tenant_manifest.offloaded_timelines.iter() {
1558 : if remote_timeline_ids.remove(&offloaded.timeline_id) {
1559 : offloaded_with_prefix.insert(offloaded.timeline_id);
1560 : } else {
1561 : // We'll take care later of timelines in the manifest without a prefix
1562 : }
1563 : }
1564 :
1565 : // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
1566 : // pulled the first heatmap. Not entirely necessary since the storage controller
1567 : // will kick the secondary in any case and cause a download.
1568 : let maybe_heatmap_at = self.read_on_disk_heatmap().await;
1569 :
1570 : let timelines = self
1571 : .load_timelines_metadata(
1572 : remote_timeline_ids,
1573 : remote_storage,
1574 : maybe_heatmap_at,
1575 : cancel,
1576 : )
1577 : .await?;
1578 :
1579 : Ok(TenantPreload {
1580 : tenant_manifest,
1581 : timelines: timelines
1582 : .into_iter()
1583 12 : .map(|(id, tl)| (id, Some(tl)))
1584 0 : .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
1585 : .collect(),
1586 : })
1587 : }
1588 :
1589 452 : async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
1590 452 : if !self.conf.load_previous_heatmap {
1591 0 : return None;
1592 452 : }
1593 452 :
1594 452 : let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
1595 452 : match tokio::fs::read_to_string(on_disk_heatmap_path).await {
1596 0 : Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
1597 0 : Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
1598 0 : Err(err) => {
1599 0 : error!("Failed to deserialize old heatmap: {err}");
1600 0 : None
1601 : }
1602 : },
1603 452 : Err(err) => match err.kind() {
1604 452 : std::io::ErrorKind::NotFound => None,
1605 : _ => {
1606 0 : error!("Unexpected IO error reading old heatmap: {err}");
1607 0 : None
1608 : }
1609 : },
1610 : }
1611 452 : }
1612 :
1613 : ///
1614 : /// Background task that downloads all data for a tenant and brings it to Active state.
1615 : ///
1616 : /// No background tasks are started as part of this routine.
1617 : ///
1618 452 : async fn attach(
1619 452 : self: &Arc<Tenant>,
1620 452 : preload: Option<TenantPreload>,
1621 452 : ctx: &RequestContext,
1622 452 : ) -> anyhow::Result<()> {
1623 452 : span::debug_assert_current_span_has_tenant_id();
1624 452 :
1625 452 : failpoint_support::sleep_millis_async!("before-attaching-tenant");
1626 :
1627 452 : let Some(preload) = preload else {
1628 0 : anyhow::bail!(
1629 0 : "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
1630 0 : );
1631 : };
1632 :
1633 452 : let mut offloaded_timeline_ids = HashSet::new();
1634 452 : let mut offloaded_timelines_list = Vec::new();
1635 452 : for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
1636 0 : let timeline_id = timeline_manifest.timeline_id;
1637 0 : let offloaded_timeline =
1638 0 : OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
1639 0 : offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
1640 0 : offloaded_timeline_ids.insert(timeline_id);
1641 0 : }
1642 : // Complete deletions for offloaded timeline id's from manifest.
1643 : // The manifest will be uploaded later in this function.
1644 452 : offloaded_timelines_list
1645 452 : .retain(|(offloaded_id, offloaded)| {
1646 0 : // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
1647 0 : // If there is dangling references in another location, they need to be cleaned up.
1648 0 : let delete = !preload.timelines.contains_key(offloaded_id);
1649 0 : if delete {
1650 0 : tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
1651 0 : offloaded.defuse_for_tenant_drop();
1652 0 : }
1653 0 : !delete
1654 452 : });
1655 452 :
1656 452 : let mut timelines_to_resume_deletions = vec![];
1657 452 :
1658 452 : let mut remote_index_and_client = HashMap::new();
1659 452 : let mut timeline_ancestors = HashMap::new();
1660 452 : let mut existent_timelines = HashSet::new();
1661 464 : for (timeline_id, preload) in preload.timelines {
1662 12 : let Some(preload) = preload else { continue };
1663 : // This is an invariant of the `preload` function's API
1664 12 : assert!(!offloaded_timeline_ids.contains(&timeline_id));
1665 12 : let index_part = match preload.index_part {
1666 12 : Ok(i) => {
1667 12 : debug!("remote index part exists for timeline {timeline_id}");
1668 : // We found index_part on the remote, this is the standard case.
1669 12 : existent_timelines.insert(timeline_id);
1670 12 : i
1671 : }
1672 : Err(DownloadError::NotFound) => {
1673 : // There is no index_part on the remote. We only get here
1674 : // if there is some prefix for the timeline in the remote storage.
1675 : // This can e.g. be the initdb.tar.zst archive, maybe a
1676 : // remnant from a prior incomplete creation or deletion attempt.
1677 : // Delete the local directory as the deciding criterion for a
1678 : // timeline's existence is presence of index_part.
1679 0 : info!(%timeline_id, "index_part not found on remote");
1680 0 : continue;
1681 : }
1682 0 : Err(DownloadError::Fatal(why)) => {
1683 0 : // If, while loading one remote timeline, we saw an indication that our generation
1684 0 : // number is likely invalid, then we should not load the whole tenant.
1685 0 : error!(%timeline_id, "Fatal error loading timeline: {why}");
1686 0 : anyhow::bail!(why.to_string());
1687 : }
1688 0 : Err(e) => {
1689 0 : // Some (possibly ephemeral) error happened during index_part download.
1690 0 : // Pretend the timeline exists to not delete the timeline directory,
1691 0 : // as it might be a temporary issue and we don't want to re-download
1692 0 : // everything after it resolves.
1693 0 : warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
1694 :
1695 0 : existent_timelines.insert(timeline_id);
1696 0 : continue;
1697 : }
1698 : };
1699 12 : match index_part {
1700 12 : MaybeDeletedIndexPart::IndexPart(index_part) => {
1701 12 : timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
1702 12 : remote_index_and_client.insert(
1703 12 : timeline_id,
1704 12 : (index_part, preload.client, preload.previous_heatmap),
1705 12 : );
1706 12 : }
1707 0 : MaybeDeletedIndexPart::Deleted(index_part) => {
1708 0 : info!(
1709 0 : "timeline {} is deleted, picking to resume deletion",
1710 : timeline_id
1711 : );
1712 0 : timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
1713 : }
1714 : }
1715 : }
1716 :
1717 452 : let mut gc_blocks = HashMap::new();
1718 :
1719 : // For every timeline, download the metadata file, scan the local directory,
1720 : // and build a layer map that contains an entry for each remote and local
1721 : // layer file.
1722 452 : let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
1723 464 : for (timeline_id, remote_metadata) in sorted_timelines {
1724 12 : let (index_part, remote_client, previous_heatmap) = remote_index_and_client
1725 12 : .remove(&timeline_id)
1726 12 : .expect("just put it in above");
1727 :
1728 12 : if let Some(blocking) = index_part.gc_blocking.as_ref() {
1729 : // could just filter these away, but it helps while testing
1730 0 : anyhow::ensure!(
1731 0 : !blocking.reasons.is_empty(),
1732 0 : "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
1733 : );
1734 0 : let prev = gc_blocks.insert(timeline_id, blocking.reasons);
1735 0 : assert!(prev.is_none());
1736 12 : }
1737 :
1738 : // TODO again handle early failure
1739 12 : let effect = self
1740 12 : .load_remote_timeline(
1741 12 : timeline_id,
1742 12 : index_part,
1743 12 : remote_metadata,
1744 12 : previous_heatmap,
1745 12 : self.get_timeline_resources_for(remote_client),
1746 12 : LoadTimelineCause::Attach,
1747 12 : ctx,
1748 12 : )
1749 12 : .await
1750 12 : .with_context(|| {
1751 0 : format!(
1752 0 : "failed to load remote timeline {} for tenant {}",
1753 0 : timeline_id, self.tenant_shard_id
1754 0 : )
1755 12 : })?;
1756 :
1757 12 : match effect {
1758 12 : TimelineInitAndSyncResult::ReadyToActivate(_) => {
1759 12 : // activation happens later, on Tenant::activate
1760 12 : }
1761 : TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
1762 : TimelineInitAndSyncNeedsSpawnImportPgdata {
1763 0 : timeline,
1764 0 : import_pgdata,
1765 0 : guard,
1766 0 : },
1767 0 : ) => {
1768 0 : tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
1769 0 : timeline,
1770 0 : import_pgdata,
1771 0 : ActivateTimelineArgs::No,
1772 0 : guard,
1773 0 : ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
1774 0 : ));
1775 0 : }
1776 : }
1777 : }
1778 :
1779 : // Walk through deleted timelines, resume deletion
1780 452 : for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
1781 0 : remote_timeline_client
1782 0 : .init_upload_queue_stopped_to_continue_deletion(&index_part)
1783 0 : .context("init queue stopped")
1784 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1785 :
1786 0 : DeleteTimelineFlow::resume_deletion(
1787 0 : Arc::clone(self),
1788 0 : timeline_id,
1789 0 : &index_part.metadata,
1790 0 : remote_timeline_client,
1791 0 : ctx,
1792 0 : )
1793 0 : .instrument(tracing::info_span!("timeline_delete", %timeline_id))
1794 0 : .await
1795 0 : .context("resume_deletion")
1796 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1797 : }
1798 452 : let needs_manifest_upload =
1799 452 : offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
1800 452 : {
1801 452 : let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
1802 452 : offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
1803 452 : }
1804 452 : if needs_manifest_upload {
1805 0 : self.store_tenant_manifest().await?;
1806 452 : }
1807 :
1808 : // The local filesystem contents are a cache of what's in the remote IndexPart;
1809 : // IndexPart is the source of truth.
1810 452 : self.clean_up_timelines(&existent_timelines)?;
1811 :
1812 452 : self.gc_block.set_scanned(gc_blocks);
1813 452 :
1814 452 : fail::fail_point!("attach-before-activate", |_| {
1815 0 : anyhow::bail!("attach-before-activate");
1816 452 : });
1817 452 : failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
1818 :
1819 452 : info!("Done");
1820 :
1821 452 : Ok(())
1822 452 : }
1823 :
1824 : /// Check for any local timeline directories that are temporary, or do not correspond to a
1825 : /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
1826 : /// if a timeline was deleted while the tenant was attached to a different pageserver.
1827 452 : fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
1828 452 : let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
1829 :
1830 452 : let entries = match timelines_dir.read_dir_utf8() {
1831 452 : Ok(d) => d,
1832 0 : Err(e) => {
1833 0 : if e.kind() == std::io::ErrorKind::NotFound {
1834 0 : return Ok(());
1835 : } else {
1836 0 : return Err(e).context("list timelines directory for tenant");
1837 : }
1838 : }
1839 : };
1840 :
1841 468 : for entry in entries {
1842 16 : let entry = entry.context("read timeline dir entry")?;
1843 16 : let entry_path = entry.path();
1844 :
1845 16 : let purge = if crate::is_temporary(entry_path) {
1846 0 : true
1847 : } else {
1848 16 : match TimelineId::try_from(entry_path.file_name()) {
1849 16 : Ok(i) => {
1850 16 : // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
1851 16 : !existent_timelines.contains(&i)
1852 : }
1853 0 : Err(e) => {
1854 0 : tracing::warn!(
1855 0 : "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
1856 : );
1857 : // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
1858 0 : false
1859 : }
1860 : }
1861 : };
1862 :
1863 16 : if purge {
1864 4 : tracing::info!("Purging stale timeline dentry {entry_path}");
1865 4 : if let Err(e) = match entry.file_type() {
1866 4 : Ok(t) => if t.is_dir() {
1867 4 : std::fs::remove_dir_all(entry_path)
1868 : } else {
1869 0 : std::fs::remove_file(entry_path)
1870 : }
1871 4 : .or_else(fs_ext::ignore_not_found),
1872 0 : Err(e) => Err(e),
1873 : } {
1874 0 : tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
1875 4 : }
1876 12 : }
1877 : }
1878 :
1879 452 : Ok(())
1880 452 : }
1881 :
1882 : /// Get sum of all remote timelines sizes
1883 : ///
1884 : /// This function relies on the index_part instead of listing the remote storage
1885 0 : pub fn remote_size(&self) -> u64 {
1886 0 : let mut size = 0;
1887 :
1888 0 : for timeline in self.list_timelines() {
1889 0 : size += timeline.remote_client.get_remote_physical_size();
1890 0 : }
1891 :
1892 0 : size
1893 0 : }
1894 :
1895 : #[instrument(skip_all, fields(timeline_id=%timeline_id))]
1896 : #[allow(clippy::too_many_arguments)]
1897 : async fn load_remote_timeline(
1898 : self: &Arc<Self>,
1899 : timeline_id: TimelineId,
1900 : index_part: IndexPart,
1901 : remote_metadata: TimelineMetadata,
1902 : previous_heatmap: Option<PreviousHeatmap>,
1903 : resources: TimelineResources,
1904 : cause: LoadTimelineCause,
1905 : ctx: &RequestContext,
1906 : ) -> anyhow::Result<TimelineInitAndSyncResult> {
1907 : span::debug_assert_current_span_has_tenant_id();
1908 :
1909 : info!("downloading index file for timeline {}", timeline_id);
1910 : tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
1911 : .await
1912 : .context("Failed to create new timeline directory")?;
1913 :
1914 : let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
1915 : let timelines = self.timelines.lock().unwrap();
1916 : Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
1917 0 : || {
1918 0 : anyhow::anyhow!(
1919 0 : "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
1920 0 : )
1921 0 : },
1922 : )?))
1923 : } else {
1924 : None
1925 : };
1926 :
1927 : self.timeline_init_and_sync(
1928 : timeline_id,
1929 : resources,
1930 : index_part,
1931 : remote_metadata,
1932 : previous_heatmap,
1933 : ancestor,
1934 : cause,
1935 : ctx,
1936 : )
1937 : .await
1938 : }
1939 :
1940 452 : async fn load_timelines_metadata(
1941 452 : self: &Arc<Tenant>,
1942 452 : timeline_ids: HashSet<TimelineId>,
1943 452 : remote_storage: &GenericRemoteStorage,
1944 452 : heatmap: Option<(HeatMapTenant, std::time::Instant)>,
1945 452 : cancel: CancellationToken,
1946 452 : ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
1947 452 : let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
1948 452 :
1949 452 : let mut part_downloads = JoinSet::new();
1950 464 : for timeline_id in timeline_ids {
1951 12 : let cancel_clone = cancel.clone();
1952 12 :
1953 12 : let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
1954 0 : hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
1955 0 : heatmap: h,
1956 0 : read_at: hs.1,
1957 0 : end_lsn: None,
1958 0 : })
1959 12 : });
1960 12 : part_downloads.spawn(
1961 12 : self.load_timeline_metadata(
1962 12 : timeline_id,
1963 12 : remote_storage.clone(),
1964 12 : previous_timeline_heatmap,
1965 12 : cancel_clone,
1966 12 : )
1967 12 : .instrument(info_span!("download_index_part", %timeline_id)),
1968 : );
1969 : }
1970 :
1971 452 : let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
1972 :
1973 : loop {
1974 464 : tokio::select!(
1975 464 : next = part_downloads.join_next() => {
1976 464 : match next {
1977 12 : Some(result) => {
1978 12 : let preload = result.context("join preload task")?;
1979 12 : timeline_preloads.insert(preload.timeline_id, preload);
1980 : },
1981 : None => {
1982 452 : break;
1983 : }
1984 : }
1985 : },
1986 464 : _ = cancel.cancelled() => {
1987 0 : anyhow::bail!("Cancelled while waiting for remote index download")
1988 : }
1989 : )
1990 : }
1991 :
1992 452 : Ok(timeline_preloads)
1993 452 : }
1994 :
1995 12 : fn build_timeline_client(
1996 12 : &self,
1997 12 : timeline_id: TimelineId,
1998 12 : remote_storage: GenericRemoteStorage,
1999 12 : ) -> RemoteTimelineClient {
2000 12 : RemoteTimelineClient::new(
2001 12 : remote_storage.clone(),
2002 12 : self.deletion_queue_client.clone(),
2003 12 : self.conf,
2004 12 : self.tenant_shard_id,
2005 12 : timeline_id,
2006 12 : self.generation,
2007 12 : &self.tenant_conf.load().location,
2008 12 : )
2009 12 : }
2010 :
2011 12 : fn load_timeline_metadata(
2012 12 : self: &Arc<Tenant>,
2013 12 : timeline_id: TimelineId,
2014 12 : remote_storage: GenericRemoteStorage,
2015 12 : previous_heatmap: Option<PreviousHeatmap>,
2016 12 : cancel: CancellationToken,
2017 12 : ) -> impl Future<Output = TimelinePreload> + use<> {
2018 12 : let client = self.build_timeline_client(timeline_id, remote_storage);
2019 12 : async move {
2020 12 : debug_assert_current_span_has_tenant_and_timeline_id();
2021 12 : debug!("starting index part download");
2022 :
2023 12 : let index_part = client.download_index_file(&cancel).await;
2024 :
2025 12 : debug!("finished index part download");
2026 :
2027 12 : TimelinePreload {
2028 12 : client,
2029 12 : timeline_id,
2030 12 : index_part,
2031 12 : previous_heatmap,
2032 12 : }
2033 12 : }
2034 12 : }
2035 :
2036 0 : fn check_to_be_archived_has_no_unarchived_children(
2037 0 : timeline_id: TimelineId,
2038 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
2039 0 : ) -> Result<(), TimelineArchivalError> {
2040 0 : let children: Vec<TimelineId> = timelines
2041 0 : .iter()
2042 0 : .filter_map(|(id, entry)| {
2043 0 : if entry.get_ancestor_timeline_id() != Some(timeline_id) {
2044 0 : return None;
2045 0 : }
2046 0 : if entry.is_archived() == Some(true) {
2047 0 : return None;
2048 0 : }
2049 0 : Some(*id)
2050 0 : })
2051 0 : .collect();
2052 0 :
2053 0 : if !children.is_empty() {
2054 0 : return Err(TimelineArchivalError::HasUnarchivedChildren(children));
2055 0 : }
2056 0 : Ok(())
2057 0 : }
2058 :
2059 0 : fn check_ancestor_of_to_be_unarchived_is_not_archived(
2060 0 : ancestor_timeline_id: TimelineId,
2061 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
2062 0 : offloaded_timelines: &std::sync::MutexGuard<
2063 0 : '_,
2064 0 : HashMap<TimelineId, Arc<OffloadedTimeline>>,
2065 0 : >,
2066 0 : ) -> Result<(), TimelineArchivalError> {
2067 0 : let has_archived_parent =
2068 0 : if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
2069 0 : ancestor_timeline.is_archived() == Some(true)
2070 0 : } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
2071 0 : true
2072 : } else {
2073 0 : error!("ancestor timeline {ancestor_timeline_id} not found");
2074 0 : if cfg!(debug_assertions) {
2075 0 : panic!("ancestor timeline {ancestor_timeline_id} not found");
2076 0 : }
2077 0 : return Err(TimelineArchivalError::NotFound);
2078 : };
2079 0 : if has_archived_parent {
2080 0 : return Err(TimelineArchivalError::HasArchivedParent(
2081 0 : ancestor_timeline_id,
2082 0 : ));
2083 0 : }
2084 0 : Ok(())
2085 0 : }
2086 :
2087 0 : fn check_to_be_unarchived_timeline_has_no_archived_parent(
2088 0 : timeline: &Arc<Timeline>,
2089 0 : ) -> Result<(), TimelineArchivalError> {
2090 0 : if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
2091 0 : if ancestor_timeline.is_archived() == Some(true) {
2092 0 : return Err(TimelineArchivalError::HasArchivedParent(
2093 0 : ancestor_timeline.timeline_id,
2094 0 : ));
2095 0 : }
2096 0 : }
2097 0 : Ok(())
2098 0 : }
2099 :
2100 : /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
2101 : ///
2102 : /// Counterpart to [`offload_timeline`].
2103 0 : async fn unoffload_timeline(
2104 0 : self: &Arc<Self>,
2105 0 : timeline_id: TimelineId,
2106 0 : broker_client: storage_broker::BrokerClientChannel,
2107 0 : ctx: RequestContext,
2108 0 : ) -> Result<Arc<Timeline>, TimelineArchivalError> {
2109 0 : info!("unoffloading timeline");
2110 :
2111 : // We activate the timeline below manually, so this must be called on an active tenant.
2112 : // We expect callers of this function to ensure this.
2113 0 : match self.current_state() {
2114 : TenantState::Activating { .. }
2115 : | TenantState::Attaching
2116 : | TenantState::Broken { .. } => {
2117 0 : panic!("Timeline expected to be active")
2118 : }
2119 0 : TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
2120 0 : TenantState::Active => {}
2121 0 : }
2122 0 : let cancel = self.cancel.clone();
2123 0 :
2124 0 : // Protect against concurrent attempts to use this TimelineId
2125 0 : // We don't care much about idempotency, as it's ensured a layer above.
2126 0 : let allow_offloaded = true;
2127 0 : let _create_guard = self
2128 0 : .create_timeline_create_guard(
2129 0 : timeline_id,
2130 0 : CreateTimelineIdempotency::FailWithConflict,
2131 0 : allow_offloaded,
2132 0 : )
2133 0 : .map_err(|err| match err {
2134 0 : TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
2135 : TimelineExclusionError::AlreadyExists { .. } => {
2136 0 : TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
2137 : }
2138 0 : TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
2139 0 : TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
2140 0 : })?;
2141 :
2142 0 : let timeline_preload = self
2143 0 : .load_timeline_metadata(
2144 0 : timeline_id,
2145 0 : self.remote_storage.clone(),
2146 0 : None,
2147 0 : cancel.clone(),
2148 0 : )
2149 0 : .await;
2150 :
2151 0 : let index_part = match timeline_preload.index_part {
2152 0 : Ok(index_part) => {
2153 0 : debug!("remote index part exists for timeline {timeline_id}");
2154 0 : index_part
2155 : }
2156 : Err(DownloadError::NotFound) => {
2157 0 : error!(%timeline_id, "index_part not found on remote");
2158 0 : return Err(TimelineArchivalError::NotFound);
2159 : }
2160 0 : Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
2161 0 : Err(e) => {
2162 0 : // Some (possibly ephemeral) error happened during index_part download.
2163 0 : warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
2164 0 : return Err(TimelineArchivalError::Other(
2165 0 : anyhow::Error::new(e).context("downloading index_part from remote storage"),
2166 0 : ));
2167 : }
2168 : };
2169 0 : let index_part = match index_part {
2170 0 : MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
2171 0 : MaybeDeletedIndexPart::Deleted(_index_part) => {
2172 0 : info!("timeline is deleted according to index_part.json");
2173 0 : return Err(TimelineArchivalError::NotFound);
2174 : }
2175 : };
2176 0 : let remote_metadata = index_part.metadata.clone();
2177 0 : let timeline_resources = self.build_timeline_resources(timeline_id);
2178 0 : self.load_remote_timeline(
2179 0 : timeline_id,
2180 0 : index_part,
2181 0 : remote_metadata,
2182 0 : None,
2183 0 : timeline_resources,
2184 0 : LoadTimelineCause::Unoffload,
2185 0 : &ctx,
2186 0 : )
2187 0 : .await
2188 0 : .with_context(|| {
2189 0 : format!(
2190 0 : "failed to load remote timeline {} for tenant {}",
2191 0 : timeline_id, self.tenant_shard_id
2192 0 : )
2193 0 : })
2194 0 : .map_err(TimelineArchivalError::Other)?;
2195 :
2196 0 : let timeline = {
2197 0 : let timelines = self.timelines.lock().unwrap();
2198 0 : let Some(timeline) = timelines.get(&timeline_id) else {
2199 0 : warn!("timeline not available directly after attach");
2200 : // This is not a panic because no locks are held between `load_remote_timeline`
2201 : // which puts the timeline into timelines, and our look into the timeline map.
2202 0 : return Err(TimelineArchivalError::Other(anyhow::anyhow!(
2203 0 : "timeline not available directly after attach"
2204 0 : )));
2205 : };
2206 0 : let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
2207 0 : match offloaded_timelines.remove(&timeline_id) {
2208 0 : Some(offloaded) => {
2209 0 : offloaded.delete_from_ancestor_with_timelines(&timelines);
2210 0 : }
2211 0 : None => warn!("timeline already removed from offloaded timelines"),
2212 : }
2213 :
2214 0 : self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
2215 0 :
2216 0 : Arc::clone(timeline)
2217 0 : };
2218 0 :
2219 0 : // Upload new list of offloaded timelines to S3
2220 0 : self.store_tenant_manifest().await?;
2221 :
2222 : // Activate the timeline (if it makes sense)
2223 0 : if !(timeline.is_broken() || timeline.is_stopping()) {
2224 0 : let background_jobs_can_start = None;
2225 0 : timeline.activate(
2226 0 : self.clone(),
2227 0 : broker_client.clone(),
2228 0 : background_jobs_can_start,
2229 0 : &ctx.with_scope_timeline(&timeline),
2230 0 : );
2231 0 : }
2232 :
2233 0 : info!("timeline unoffloading complete");
2234 0 : Ok(timeline)
2235 0 : }
2236 :
2237 0 : pub(crate) async fn apply_timeline_archival_config(
2238 0 : self: &Arc<Self>,
2239 0 : timeline_id: TimelineId,
2240 0 : new_state: TimelineArchivalState,
2241 0 : broker_client: storage_broker::BrokerClientChannel,
2242 0 : ctx: RequestContext,
2243 0 : ) -> Result<(), TimelineArchivalError> {
2244 0 : info!("setting timeline archival config");
2245 : // First part: figure out what is needed to do, and do validation
2246 0 : let timeline_or_unarchive_offloaded = 'outer: {
2247 0 : let timelines = self.timelines.lock().unwrap();
2248 :
2249 0 : let Some(timeline) = timelines.get(&timeline_id) else {
2250 0 : let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
2251 0 : let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
2252 0 : return Err(TimelineArchivalError::NotFound);
2253 : };
2254 0 : if new_state == TimelineArchivalState::Archived {
2255 : // It's offloaded already, so nothing to do
2256 0 : return Ok(());
2257 0 : }
2258 0 : if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
2259 0 : Self::check_ancestor_of_to_be_unarchived_is_not_archived(
2260 0 : ancestor_timeline_id,
2261 0 : &timelines,
2262 0 : &offloaded_timelines,
2263 0 : )?;
2264 0 : }
2265 0 : break 'outer None;
2266 : };
2267 :
2268 : // Do some validation. We release the timelines lock below, so there is potential
2269 : // for race conditions: these checks are more present to prevent misunderstandings of
2270 : // the API's capabilities, instead of serving as the sole way to defend their invariants.
2271 0 : match new_state {
2272 : TimelineArchivalState::Unarchived => {
2273 0 : Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
2274 : }
2275 : TimelineArchivalState::Archived => {
2276 0 : Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
2277 : }
2278 : }
2279 0 : Some(Arc::clone(timeline))
2280 : };
2281 :
2282 : // Second part: unoffload timeline (if needed)
2283 0 : let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
2284 0 : timeline
2285 : } else {
2286 : // Turn offloaded timeline into a non-offloaded one
2287 0 : self.unoffload_timeline(timeline_id, broker_client, ctx)
2288 0 : .await?
2289 : };
2290 :
2291 : // Third part: upload new timeline archival state and block until it is present in S3
2292 0 : let upload_needed = match timeline
2293 0 : .remote_client
2294 0 : .schedule_index_upload_for_timeline_archival_state(new_state)
2295 : {
2296 0 : Ok(upload_needed) => upload_needed,
2297 0 : Err(e) => {
2298 0 : if timeline.cancel.is_cancelled() {
2299 0 : return Err(TimelineArchivalError::Cancelled);
2300 : } else {
2301 0 : return Err(TimelineArchivalError::Other(e));
2302 : }
2303 : }
2304 : };
2305 :
2306 0 : if upload_needed {
2307 0 : info!("Uploading new state");
2308 : const MAX_WAIT: Duration = Duration::from_secs(10);
2309 0 : let Ok(v) =
2310 0 : tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
2311 : else {
2312 0 : tracing::warn!("reached timeout for waiting on upload queue");
2313 0 : return Err(TimelineArchivalError::Timeout);
2314 : };
2315 0 : v.map_err(|e| match e {
2316 0 : WaitCompletionError::NotInitialized(e) => {
2317 0 : TimelineArchivalError::Other(anyhow::anyhow!(e))
2318 : }
2319 : WaitCompletionError::UploadQueueShutDownOrStopped => {
2320 0 : TimelineArchivalError::Cancelled
2321 : }
2322 0 : })?;
2323 0 : }
2324 0 : Ok(())
2325 0 : }
2326 :
2327 4 : pub fn get_offloaded_timeline(
2328 4 : &self,
2329 4 : timeline_id: TimelineId,
2330 4 : ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
2331 4 : self.timelines_offloaded
2332 4 : .lock()
2333 4 : .unwrap()
2334 4 : .get(&timeline_id)
2335 4 : .map(Arc::clone)
2336 4 : .ok_or(GetTimelineError::NotFound {
2337 4 : tenant_id: self.tenant_shard_id,
2338 4 : timeline_id,
2339 4 : })
2340 4 : }
2341 :
2342 8 : pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
2343 8 : self.tenant_shard_id
2344 8 : }
2345 :
2346 : /// Get Timeline handle for given Neon timeline ID.
2347 : /// This function is idempotent. It doesn't change internal state in any way.
2348 444 : pub fn get_timeline(
2349 444 : &self,
2350 444 : timeline_id: TimelineId,
2351 444 : active_only: bool,
2352 444 : ) -> Result<Arc<Timeline>, GetTimelineError> {
2353 444 : let timelines_accessor = self.timelines.lock().unwrap();
2354 444 : let timeline = timelines_accessor
2355 444 : .get(&timeline_id)
2356 444 : .ok_or(GetTimelineError::NotFound {
2357 444 : tenant_id: self.tenant_shard_id,
2358 444 : timeline_id,
2359 444 : })?;
2360 :
2361 440 : if active_only && !timeline.is_active() {
2362 0 : Err(GetTimelineError::NotActive {
2363 0 : tenant_id: self.tenant_shard_id,
2364 0 : timeline_id,
2365 0 : state: timeline.current_state(),
2366 0 : })
2367 : } else {
2368 440 : Ok(Arc::clone(timeline))
2369 : }
2370 444 : }
2371 :
2372 : /// Lists timelines the tenant contains.
2373 : /// It's up to callers to omit certain timelines that are not considered ready for use.
2374 0 : pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
2375 0 : self.timelines
2376 0 : .lock()
2377 0 : .unwrap()
2378 0 : .values()
2379 0 : .map(Arc::clone)
2380 0 : .collect()
2381 0 : }
2382 :
2383 : /// Lists timelines the tenant manages, including offloaded ones.
2384 : ///
2385 : /// It's up to callers to omit certain timelines that are not considered ready for use.
2386 0 : pub fn list_timelines_and_offloaded(
2387 0 : &self,
2388 0 : ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
2389 0 : let timelines = self
2390 0 : .timelines
2391 0 : .lock()
2392 0 : .unwrap()
2393 0 : .values()
2394 0 : .map(Arc::clone)
2395 0 : .collect();
2396 0 : let offloaded = self
2397 0 : .timelines_offloaded
2398 0 : .lock()
2399 0 : .unwrap()
2400 0 : .values()
2401 0 : .map(Arc::clone)
2402 0 : .collect();
2403 0 : (timelines, offloaded)
2404 0 : }
2405 :
2406 0 : pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
2407 0 : self.timelines.lock().unwrap().keys().cloned().collect()
2408 0 : }
2409 :
2410 : /// This is used by tests & import-from-basebackup.
2411 : ///
2412 : /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
2413 : /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
2414 : ///
2415 : /// The caller is responsible for getting the timeline into a state that will be accepted
2416 : /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
2417 : /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
2418 : /// to the [`Tenant::timelines`].
2419 : ///
2420 : /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
2421 436 : pub(crate) async fn create_empty_timeline(
2422 436 : self: &Arc<Self>,
2423 436 : new_timeline_id: TimelineId,
2424 436 : initdb_lsn: Lsn,
2425 436 : pg_version: u32,
2426 436 : ctx: &RequestContext,
2427 436 : ) -> anyhow::Result<(UninitializedTimeline, RequestContext)> {
2428 436 : anyhow::ensure!(
2429 436 : self.is_active(),
2430 0 : "Cannot create empty timelines on inactive tenant"
2431 : );
2432 :
2433 : // Protect against concurrent attempts to use this TimelineId
2434 436 : let create_guard = match self
2435 436 : .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
2436 436 : .await?
2437 : {
2438 432 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
2439 : StartCreatingTimelineResult::Idempotent(_) => {
2440 0 : unreachable!("FailWithConflict implies we get an error instead")
2441 : }
2442 : };
2443 :
2444 432 : let new_metadata = TimelineMetadata::new(
2445 432 : // Initialize disk_consistent LSN to 0, The caller must import some data to
2446 432 : // make it valid, before calling finish_creation()
2447 432 : Lsn(0),
2448 432 : None,
2449 432 : None,
2450 432 : Lsn(0),
2451 432 : initdb_lsn,
2452 432 : initdb_lsn,
2453 432 : pg_version,
2454 432 : );
2455 432 : self.prepare_new_timeline(
2456 432 : new_timeline_id,
2457 432 : &new_metadata,
2458 432 : create_guard,
2459 432 : initdb_lsn,
2460 432 : None,
2461 432 : None,
2462 432 : ctx,
2463 432 : )
2464 432 : .await
2465 436 : }
2466 :
2467 : /// Helper for unit tests to create an empty timeline.
2468 : ///
2469 : /// The timeline is has state value `Active` but its background loops are not running.
2470 : // This makes the various functions which anyhow::ensure! for Active state work in tests.
2471 : // Our current tests don't need the background loops.
2472 : #[cfg(test)]
2473 416 : pub async fn create_test_timeline(
2474 416 : self: &Arc<Self>,
2475 416 : new_timeline_id: TimelineId,
2476 416 : initdb_lsn: Lsn,
2477 416 : pg_version: u32,
2478 416 : ctx: &RequestContext,
2479 416 : ) -> anyhow::Result<Arc<Timeline>> {
2480 416 : let (uninit_tl, ctx) = self
2481 416 : .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
2482 416 : .await?;
2483 416 : let tline = uninit_tl.raw_timeline().expect("we just created it");
2484 416 : assert_eq!(tline.get_last_record_lsn(), Lsn(0));
2485 :
2486 : // Setup minimum keys required for the timeline to be usable.
2487 416 : let mut modification = tline.begin_modification(initdb_lsn);
2488 416 : modification
2489 416 : .init_empty_test_timeline()
2490 416 : .context("init_empty_test_timeline")?;
2491 416 : modification
2492 416 : .commit(&ctx)
2493 416 : .await
2494 416 : .context("commit init_empty_test_timeline modification")?;
2495 :
2496 : // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
2497 416 : tline.maybe_spawn_flush_loop();
2498 416 : tline.freeze_and_flush().await.context("freeze_and_flush")?;
2499 :
2500 : // Make sure the freeze_and_flush reaches remote storage.
2501 416 : tline.remote_client.wait_completion().await.unwrap();
2502 :
2503 416 : let tl = uninit_tl.finish_creation().await?;
2504 : // The non-test code would call tl.activate() here.
2505 416 : tl.set_state(TimelineState::Active);
2506 416 : Ok(tl)
2507 416 : }
2508 :
2509 : /// Helper for unit tests to create a timeline with some pre-loaded states.
2510 : #[cfg(test)]
2511 : #[allow(clippy::too_many_arguments)]
2512 84 : pub async fn create_test_timeline_with_layers(
2513 84 : self: &Arc<Self>,
2514 84 : new_timeline_id: TimelineId,
2515 84 : initdb_lsn: Lsn,
2516 84 : pg_version: u32,
2517 84 : ctx: &RequestContext,
2518 84 : in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
2519 84 : delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
2520 84 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
2521 84 : end_lsn: Lsn,
2522 84 : ) -> anyhow::Result<Arc<Timeline>> {
2523 : use checks::check_valid_layermap;
2524 : use itertools::Itertools;
2525 :
2526 84 : let tline = self
2527 84 : .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
2528 84 : .await?;
2529 84 : tline.force_advance_lsn(end_lsn);
2530 256 : for deltas in delta_layer_desc {
2531 172 : tline
2532 172 : .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
2533 172 : .await?;
2534 : }
2535 204 : for (lsn, images) in image_layer_desc {
2536 120 : tline
2537 120 : .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
2538 120 : .await?;
2539 : }
2540 92 : for in_memory in in_memory_layer_desc {
2541 8 : tline
2542 8 : .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
2543 8 : .await?;
2544 : }
2545 84 : let layer_names = tline
2546 84 : .layers
2547 84 : .read()
2548 84 : .await
2549 84 : .layer_map()
2550 84 : .unwrap()
2551 84 : .iter_historic_layers()
2552 376 : .map(|layer| layer.layer_name())
2553 84 : .collect_vec();
2554 84 : if let Some(err) = check_valid_layermap(&layer_names) {
2555 0 : bail!("invalid layermap: {err}");
2556 84 : }
2557 84 : Ok(tline)
2558 84 : }
2559 :
2560 : /// Create a new timeline.
2561 : ///
2562 : /// Returns the new timeline ID and reference to its Timeline object.
2563 : ///
2564 : /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
2565 : /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
2566 : #[allow(clippy::too_many_arguments)]
2567 0 : pub(crate) async fn create_timeline(
2568 0 : self: &Arc<Tenant>,
2569 0 : params: CreateTimelineParams,
2570 0 : broker_client: storage_broker::BrokerClientChannel,
2571 0 : ctx: &RequestContext,
2572 0 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
2573 0 : if !self.is_active() {
2574 0 : if matches!(self.current_state(), TenantState::Stopping { .. }) {
2575 0 : return Err(CreateTimelineError::ShuttingDown);
2576 : } else {
2577 0 : return Err(CreateTimelineError::Other(anyhow::anyhow!(
2578 0 : "Cannot create timelines on inactive tenant"
2579 0 : )));
2580 : }
2581 0 : }
2582 :
2583 0 : let _gate = self
2584 0 : .gate
2585 0 : .enter()
2586 0 : .map_err(|_| CreateTimelineError::ShuttingDown)?;
2587 :
2588 0 : let result: CreateTimelineResult = match params {
2589 : CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
2590 0 : new_timeline_id,
2591 0 : existing_initdb_timeline_id,
2592 0 : pg_version,
2593 0 : }) => {
2594 0 : self.bootstrap_timeline(
2595 0 : new_timeline_id,
2596 0 : pg_version,
2597 0 : existing_initdb_timeline_id,
2598 0 : ctx,
2599 0 : )
2600 0 : .await?
2601 : }
2602 : CreateTimelineParams::Branch(CreateTimelineParamsBranch {
2603 0 : new_timeline_id,
2604 0 : ancestor_timeline_id,
2605 0 : mut ancestor_start_lsn,
2606 : }) => {
2607 0 : let ancestor_timeline = self
2608 0 : .get_timeline(ancestor_timeline_id, false)
2609 0 : .context("Cannot branch off the timeline that's not present in pageserver")?;
2610 :
2611 : // instead of waiting around, just deny the request because ancestor is not yet
2612 : // ready for other purposes either.
2613 0 : if !ancestor_timeline.is_active() {
2614 0 : return Err(CreateTimelineError::AncestorNotActive);
2615 0 : }
2616 0 :
2617 0 : if ancestor_timeline.is_archived() == Some(true) {
2618 0 : info!("tried to branch archived timeline");
2619 0 : return Err(CreateTimelineError::AncestorArchived);
2620 0 : }
2621 :
2622 0 : if let Some(lsn) = ancestor_start_lsn.as_mut() {
2623 0 : *lsn = lsn.align();
2624 0 :
2625 0 : let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
2626 0 : if ancestor_ancestor_lsn > *lsn {
2627 : // can we safely just branch from the ancestor instead?
2628 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
2629 0 : "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
2630 0 : lsn,
2631 0 : ancestor_timeline_id,
2632 0 : ancestor_ancestor_lsn,
2633 0 : )));
2634 0 : }
2635 0 :
2636 0 : // Wait for the WAL to arrive and be processed on the parent branch up
2637 0 : // to the requested branch point. The repository code itself doesn't
2638 0 : // require it, but if we start to receive WAL on the new timeline,
2639 0 : // decoding the new WAL might need to look up previous pages, relation
2640 0 : // sizes etc. and that would get confused if the previous page versions
2641 0 : // are not in the repository yet.
2642 0 : ancestor_timeline
2643 0 : .wait_lsn(
2644 0 : *lsn,
2645 0 : timeline::WaitLsnWaiter::Tenant,
2646 0 : timeline::WaitLsnTimeout::Default,
2647 0 : ctx,
2648 0 : )
2649 0 : .await
2650 0 : .map_err(|e| match e {
2651 0 : e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
2652 0 : CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
2653 : }
2654 0 : WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
2655 0 : })?;
2656 0 : }
2657 :
2658 0 : self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
2659 0 : .await?
2660 : }
2661 0 : CreateTimelineParams::ImportPgdata(params) => {
2662 0 : self.create_timeline_import_pgdata(
2663 0 : params,
2664 0 : ActivateTimelineArgs::Yes {
2665 0 : broker_client: broker_client.clone(),
2666 0 : },
2667 0 : ctx,
2668 0 : )
2669 0 : .await?
2670 : }
2671 : };
2672 :
2673 : // At this point we have dropped our guard on [`Self::timelines_creating`], and
2674 : // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet. We must
2675 : // not send a success to the caller until it is. The same applies to idempotent retries.
2676 : //
2677 : // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
2678 : // assume that, because they can see the timeline via API, that the creation is done and
2679 : // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
2680 : // until it is durable, e.g., by extending the time we hold the creation guard. This also
2681 : // interacts with UninitializedTimeline and is generally a bit tricky.
2682 : //
2683 : // To re-emphasize: the only correct way to create a timeline is to repeat calling the
2684 : // creation API until it returns success. Only then is durability guaranteed.
2685 0 : info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
2686 0 : result
2687 0 : .timeline()
2688 0 : .remote_client
2689 0 : .wait_completion()
2690 0 : .await
2691 0 : .map_err(|e| match e {
2692 : WaitCompletionError::NotInitialized(
2693 0 : e, // If the queue is already stopped, it's a shutdown error.
2694 0 : ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
2695 : WaitCompletionError::NotInitialized(_) => {
2696 : // This is a bug: we should never try to wait for uploads before initializing the timeline
2697 0 : debug_assert!(false);
2698 0 : CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
2699 : }
2700 : WaitCompletionError::UploadQueueShutDownOrStopped => {
2701 0 : CreateTimelineError::ShuttingDown
2702 : }
2703 0 : })?;
2704 :
2705 : // The creating task is responsible for activating the timeline.
2706 : // We do this after `wait_completion()` so that we don't spin up tasks that start
2707 : // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
2708 0 : let activated_timeline = match result {
2709 0 : CreateTimelineResult::Created(timeline) => {
2710 0 : timeline.activate(
2711 0 : self.clone(),
2712 0 : broker_client,
2713 0 : None,
2714 0 : &ctx.with_scope_timeline(&timeline),
2715 0 : );
2716 0 : timeline
2717 : }
2718 0 : CreateTimelineResult::Idempotent(timeline) => {
2719 0 : info!(
2720 0 : "request was deemed idempotent, activation will be done by the creating task"
2721 : );
2722 0 : timeline
2723 : }
2724 0 : CreateTimelineResult::ImportSpawned(timeline) => {
2725 0 : info!(
2726 0 : "import task spawned, timeline will become visible and activated once the import is done"
2727 : );
2728 0 : timeline
2729 : }
2730 : };
2731 :
2732 0 : Ok(activated_timeline)
2733 0 : }
2734 :
2735 : /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
2736 : /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
2737 : /// [`Tenant::timelines`] map when the import completes.
2738 : /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
2739 : /// for the response.
2740 0 : async fn create_timeline_import_pgdata(
2741 0 : self: &Arc<Tenant>,
2742 0 : params: CreateTimelineParamsImportPgdata,
2743 0 : activate: ActivateTimelineArgs,
2744 0 : ctx: &RequestContext,
2745 0 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
2746 0 : let CreateTimelineParamsImportPgdata {
2747 0 : new_timeline_id,
2748 0 : location,
2749 0 : idempotency_key,
2750 0 : } = params;
2751 0 :
2752 0 : let started_at = chrono::Utc::now().naive_utc();
2753 :
2754 : //
2755 : // There's probably a simpler way to upload an index part, but, remote_timeline_client
2756 : // is the canonical way we do it.
2757 : // - create an empty timeline in-memory
2758 : // - use its remote_timeline_client to do the upload
2759 : // - dispose of the uninit timeline
2760 : // - keep the creation guard alive
2761 :
2762 0 : let timeline_create_guard = match self
2763 0 : .start_creating_timeline(
2764 0 : new_timeline_id,
2765 0 : CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
2766 0 : idempotency_key: idempotency_key.clone(),
2767 0 : }),
2768 0 : )
2769 0 : .await?
2770 : {
2771 0 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
2772 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
2773 0 : return Ok(CreateTimelineResult::Idempotent(timeline));
2774 : }
2775 : };
2776 :
2777 0 : let (mut uninit_timeline, timeline_ctx) = {
2778 0 : let this = &self;
2779 0 : let initdb_lsn = Lsn(0);
2780 0 : async move {
2781 0 : let new_metadata = TimelineMetadata::new(
2782 0 : // Initialize disk_consistent LSN to 0, The caller must import some data to
2783 0 : // make it valid, before calling finish_creation()
2784 0 : Lsn(0),
2785 0 : None,
2786 0 : None,
2787 0 : Lsn(0),
2788 0 : initdb_lsn,
2789 0 : initdb_lsn,
2790 0 : 15,
2791 0 : );
2792 0 : this.prepare_new_timeline(
2793 0 : new_timeline_id,
2794 0 : &new_metadata,
2795 0 : timeline_create_guard,
2796 0 : initdb_lsn,
2797 0 : None,
2798 0 : None,
2799 0 : ctx,
2800 0 : )
2801 0 : .await
2802 0 : }
2803 0 : }
2804 0 : .await?;
2805 :
2806 0 : let in_progress = import_pgdata::index_part_format::InProgress {
2807 0 : idempotency_key,
2808 0 : location,
2809 0 : started_at,
2810 0 : };
2811 0 : let index_part = import_pgdata::index_part_format::Root::V1(
2812 0 : import_pgdata::index_part_format::V1::InProgress(in_progress),
2813 0 : );
2814 0 : uninit_timeline
2815 0 : .raw_timeline()
2816 0 : .unwrap()
2817 0 : .remote_client
2818 0 : .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
2819 :
2820 : // wait_completion happens in caller
2821 :
2822 0 : let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
2823 0 :
2824 0 : tokio::spawn(self.clone().create_timeline_import_pgdata_task(
2825 0 : timeline.clone(),
2826 0 : index_part,
2827 0 : activate,
2828 0 : timeline_create_guard,
2829 0 : timeline_ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
2830 0 : ));
2831 0 :
2832 0 : // NB: the timeline doesn't exist in self.timelines at this point
2833 0 : Ok(CreateTimelineResult::ImportSpawned(timeline))
2834 0 : }
2835 :
2836 : #[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))]
2837 : async fn create_timeline_import_pgdata_task(
2838 : self: Arc<Tenant>,
2839 : timeline: Arc<Timeline>,
2840 : index_part: import_pgdata::index_part_format::Root,
2841 : activate: ActivateTimelineArgs,
2842 : timeline_create_guard: TimelineCreateGuard,
2843 : ctx: RequestContext,
2844 : ) {
2845 : debug_assert_current_span_has_tenant_and_timeline_id();
2846 : info!("starting");
2847 : scopeguard::defer! {info!("exiting")};
2848 :
2849 : let res = self
2850 : .create_timeline_import_pgdata_task_impl(
2851 : timeline,
2852 : index_part,
2853 : activate,
2854 : timeline_create_guard,
2855 : ctx,
2856 : )
2857 : .await;
2858 : if let Err(err) = &res {
2859 : error!(?err, "task failed");
2860 : // TODO sleep & retry, sensitive to tenant shutdown
2861 : // TODO: allow timeline deletion requests => should cancel the task
2862 : }
2863 : }
2864 :
2865 0 : async fn create_timeline_import_pgdata_task_impl(
2866 0 : self: Arc<Tenant>,
2867 0 : timeline: Arc<Timeline>,
2868 0 : index_part: import_pgdata::index_part_format::Root,
2869 0 : activate: ActivateTimelineArgs,
2870 0 : timeline_create_guard: TimelineCreateGuard,
2871 0 : ctx: RequestContext,
2872 0 : ) -> Result<(), anyhow::Error> {
2873 0 : info!("importing pgdata");
2874 0 : import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
2875 0 : .await
2876 0 : .context("import")?;
2877 0 : info!("import done");
2878 :
2879 : //
2880 : // Reload timeline from remote.
2881 : // This proves that the remote state is attachable, and it reuses the code.
2882 : //
2883 : // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
2884 : // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
2885 : // But our activate() call might launch new background tasks after Tenant::shutdown
2886 : // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
2887 : // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
2888 : // down while bootstrapping/branching + activating), but, the race condition is much more likely
2889 : // to manifest because of the long runtime of this import task.
2890 :
2891 : // in theory this shouldn't even .await anything except for coop yield
2892 0 : info!("shutting down timeline");
2893 0 : timeline.shutdown(ShutdownMode::Hard).await;
2894 0 : info!("timeline shut down, reloading from remote");
2895 : // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
2896 : // let Some(timeline) = Arc::into_inner(timeline) else {
2897 : // anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
2898 : // };
2899 0 : let timeline_id = timeline.timeline_id;
2900 0 :
2901 0 : // load from object storage like Tenant::attach does
2902 0 : let resources = self.build_timeline_resources(timeline_id);
2903 0 : let index_part = resources
2904 0 : .remote_client
2905 0 : .download_index_file(&self.cancel)
2906 0 : .await?;
2907 0 : let index_part = match index_part {
2908 : MaybeDeletedIndexPart::Deleted(_) => {
2909 : // likely concurrent delete call, cplane should prevent this
2910 0 : anyhow::bail!(
2911 0 : "index part says deleted but we are not done creating yet, this should not happen but"
2912 0 : )
2913 : }
2914 0 : MaybeDeletedIndexPart::IndexPart(p) => p,
2915 0 : };
2916 0 : let metadata = index_part.metadata.clone();
2917 0 : self
2918 0 : .load_remote_timeline(timeline_id, index_part, metadata, None, resources, LoadTimelineCause::ImportPgdata{
2919 0 : create_guard: timeline_create_guard, activate, }, &ctx)
2920 0 : .await?
2921 0 : .ready_to_activate()
2922 0 : .context("implementation error: reloaded timeline still needs import after import reported success")?;
2923 :
2924 0 : anyhow::Ok(())
2925 0 : }
2926 :
2927 0 : pub(crate) async fn delete_timeline(
2928 0 : self: Arc<Self>,
2929 0 : timeline_id: TimelineId,
2930 0 : ) -> Result<(), DeleteTimelineError> {
2931 0 : DeleteTimelineFlow::run(&self, timeline_id).await?;
2932 :
2933 0 : Ok(())
2934 0 : }
2935 :
2936 : /// perform one garbage collection iteration, removing old data files from disk.
2937 : /// this function is periodically called by gc task.
2938 : /// also it can be explicitly requested through page server api 'do_gc' command.
2939 : ///
2940 : /// `target_timeline_id` specifies the timeline to GC, or None for all.
2941 : ///
2942 : /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
2943 : /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
2944 : /// the amount of history, as LSN difference from current latest LSN on each timeline.
2945 : /// `pitr` specifies the same as a time difference from the current time. The effective
2946 : /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
2947 : /// requires more history to be retained.
2948 : //
2949 1508 : pub(crate) async fn gc_iteration(
2950 1508 : &self,
2951 1508 : target_timeline_id: Option<TimelineId>,
2952 1508 : horizon: u64,
2953 1508 : pitr: Duration,
2954 1508 : cancel: &CancellationToken,
2955 1508 : ctx: &RequestContext,
2956 1508 : ) -> Result<GcResult, GcError> {
2957 1508 : // Don't start doing work during shutdown
2958 1508 : if let TenantState::Stopping { .. } = self.current_state() {
2959 0 : return Ok(GcResult::default());
2960 1508 : }
2961 1508 :
2962 1508 : // there is a global allowed_error for this
2963 1508 : if !self.is_active() {
2964 0 : return Err(GcError::NotActive);
2965 1508 : }
2966 1508 :
2967 1508 : {
2968 1508 : let conf = self.tenant_conf.load();
2969 1508 :
2970 1508 : // If we may not delete layers, then simply skip GC. Even though a tenant
2971 1508 : // in AttachedMulti state could do GC and just enqueue the blocked deletions,
2972 1508 : // the only advantage to doing it is to perhaps shrink the LayerMap metadata
2973 1508 : // a bit sooner than we would achieve by waiting for AttachedSingle status.
2974 1508 : if !conf.location.may_delete_layers_hint() {
2975 0 : info!("Skipping GC in location state {:?}", conf.location);
2976 0 : return Ok(GcResult::default());
2977 1508 : }
2978 1508 :
2979 1508 : if conf.is_gc_blocked_by_lsn_lease_deadline() {
2980 1500 : info!("Skipping GC because lsn lease deadline is not reached");
2981 1500 : return Ok(GcResult::default());
2982 8 : }
2983 : }
2984 :
2985 8 : let _guard = match self.gc_block.start().await {
2986 8 : Ok(guard) => guard,
2987 0 : Err(reasons) => {
2988 0 : info!("Skipping GC: {reasons}");
2989 0 : return Ok(GcResult::default());
2990 : }
2991 : };
2992 :
2993 8 : self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
2994 8 : .await
2995 1508 : }
2996 :
2997 : /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
2998 : /// whether another compaction is needed, if we still have pending work or if we yield for
2999 : /// immediate L0 compaction.
3000 : ///
3001 : /// Compaction can also be explicitly requested for a timeline via the HTTP API.
3002 0 : async fn compaction_iteration(
3003 0 : self: &Arc<Self>,
3004 0 : cancel: &CancellationToken,
3005 0 : ctx: &RequestContext,
3006 0 : ) -> Result<CompactionOutcome, CompactionError> {
3007 0 : // Don't compact inactive tenants.
3008 0 : if !self.is_active() {
3009 0 : return Ok(CompactionOutcome::Skipped);
3010 0 : }
3011 0 :
3012 0 : // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
3013 0 : // since we need to compact L0 even in AttachedMulti to bound read amplification.
3014 0 : let location = self.tenant_conf.load().location;
3015 0 : if !location.may_upload_layers_hint() {
3016 0 : info!("skipping compaction in location state {location:?}");
3017 0 : return Ok(CompactionOutcome::Skipped);
3018 0 : }
3019 0 :
3020 0 : // Don't compact if the circuit breaker is tripped.
3021 0 : if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
3022 0 : info!("skipping compaction due to previous failures");
3023 0 : return Ok(CompactionOutcome::Skipped);
3024 0 : }
3025 0 :
3026 0 : // Collect all timelines to compact, along with offload instructions and L0 counts.
3027 0 : let mut compact: Vec<Arc<Timeline>> = Vec::new();
3028 0 : let mut offload: HashSet<TimelineId> = HashSet::new();
3029 0 : let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
3030 0 :
3031 0 : {
3032 0 : let offload_enabled = self.get_timeline_offloading_enabled();
3033 0 : let timelines = self.timelines.lock().unwrap();
3034 0 : for (&timeline_id, timeline) in timelines.iter() {
3035 : // Skip inactive timelines.
3036 0 : if !timeline.is_active() {
3037 0 : continue;
3038 0 : }
3039 0 :
3040 0 : // Schedule the timeline for compaction.
3041 0 : compact.push(timeline.clone());
3042 :
3043 : // Schedule the timeline for offloading if eligible.
3044 0 : let can_offload = offload_enabled
3045 0 : && timeline.can_offload().0
3046 0 : && !timelines
3047 0 : .iter()
3048 0 : .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
3049 0 : if can_offload {
3050 0 : offload.insert(timeline_id);
3051 0 : }
3052 : }
3053 : } // release timelines lock
3054 :
3055 0 : for timeline in &compact {
3056 : // Collect L0 counts. Can't await while holding lock above.
3057 0 : if let Ok(lm) = timeline.layers.read().await.layer_map() {
3058 0 : l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
3059 0 : }
3060 : }
3061 :
3062 : // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
3063 : // bound read amplification.
3064 : //
3065 : // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
3066 : // compaction and offloading. We leave that as a potential problem to solve later. Consider
3067 : // splitting L0 and image/GC compaction to separate background jobs.
3068 0 : if self.get_compaction_l0_first() {
3069 0 : let compaction_threshold = self.get_compaction_threshold();
3070 0 : let compact_l0 = compact
3071 0 : .iter()
3072 0 : .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
3073 0 : .filter(|&(_, l0)| l0 >= compaction_threshold)
3074 0 : .sorted_by_key(|&(_, l0)| l0)
3075 0 : .rev()
3076 0 : .map(|(tli, _)| tli.clone())
3077 0 : .collect_vec();
3078 0 :
3079 0 : let mut has_pending_l0 = false;
3080 0 : for timeline in compact_l0 {
3081 0 : let ctx = &ctx.with_scope_timeline(&timeline);
3082 0 : let outcome = timeline
3083 0 : .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
3084 0 : .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
3085 0 : .await
3086 0 : .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
3087 0 : match outcome {
3088 0 : CompactionOutcome::Done => {}
3089 0 : CompactionOutcome::Skipped => {}
3090 0 : CompactionOutcome::Pending => has_pending_l0 = true,
3091 0 : CompactionOutcome::YieldForL0 => has_pending_l0 = true,
3092 : }
3093 : }
3094 0 : if has_pending_l0 {
3095 0 : return Ok(CompactionOutcome::YieldForL0); // do another pass
3096 0 : }
3097 0 : }
3098 :
3099 : // Pass 2: image compaction and timeline offloading. If any timelines have accumulated
3100 : // more L0 layers, they may also be compacted here.
3101 : //
3102 : // NB: image compaction may yield if there is pending L0 compaction.
3103 : //
3104 : // TODO: it will only yield if there is pending L0 compaction on the same timeline. If a
3105 : // different timeline needs compaction, it won't. It should check `l0_compaction_trigger`.
3106 : // We leave this for a later PR.
3107 : //
3108 : // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
3109 : // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
3110 0 : let mut has_pending = false;
3111 0 : for timeline in compact {
3112 0 : if !timeline.is_active() {
3113 0 : continue;
3114 0 : }
3115 0 : let ctx = &ctx.with_scope_timeline(&timeline);
3116 :
3117 0 : let mut outcome = timeline
3118 0 : .compact(cancel, EnumSet::default(), ctx)
3119 0 : .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
3120 0 : .await
3121 0 : .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
3122 :
3123 : // If we're done compacting, check the scheduled GC compaction queue for more work.
3124 0 : if outcome == CompactionOutcome::Done {
3125 0 : let queue = {
3126 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3127 0 : guard
3128 0 : .entry(timeline.timeline_id)
3129 0 : .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
3130 0 : .clone()
3131 0 : };
3132 0 : outcome = queue
3133 0 : .iteration(cancel, ctx, &self.gc_block, &timeline)
3134 0 : .instrument(
3135 0 : info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id),
3136 : )
3137 0 : .await?;
3138 0 : }
3139 :
3140 : // If we're done compacting, offload the timeline if requested.
3141 0 : if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
3142 0 : pausable_failpoint!("before-timeline-auto-offload");
3143 0 : offload_timeline(self, &timeline)
3144 0 : .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
3145 0 : .await
3146 0 : .or_else(|err| match err {
3147 : // Ignore this, we likely raced with unarchival.
3148 0 : OffloadError::NotArchived => Ok(()),
3149 0 : err => Err(err),
3150 0 : })?;
3151 0 : }
3152 :
3153 0 : match outcome {
3154 0 : CompactionOutcome::Done => {}
3155 0 : CompactionOutcome::Skipped => {}
3156 0 : CompactionOutcome::Pending => has_pending = true,
3157 : // This mostly makes sense when the L0-only pass above is enabled, since there's
3158 : // otherwise no guarantee that we'll start with the timeline that has high L0.
3159 0 : CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
3160 : }
3161 : }
3162 :
3163 : // Success! Untrip the breaker if necessary.
3164 0 : self.compaction_circuit_breaker
3165 0 : .lock()
3166 0 : .unwrap()
3167 0 : .success(&CIRCUIT_BREAKERS_UNBROKEN);
3168 0 :
3169 0 : match has_pending {
3170 0 : true => Ok(CompactionOutcome::Pending),
3171 0 : false => Ok(CompactionOutcome::Done),
3172 : }
3173 0 : }
3174 :
3175 : /// Trips the compaction circuit breaker if appropriate.
3176 0 : pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
3177 0 : match err {
3178 0 : err if err.is_cancel() => {}
3179 0 : CompactionError::ShuttingDown => (),
3180 : // Offload failures don't trip the circuit breaker, since they're cheap to retry and
3181 : // shouldn't block compaction.
3182 0 : CompactionError::Offload(_) => {}
3183 0 : CompactionError::CollectKeySpaceError(err) => {
3184 0 : // CollectKeySpaceError::Cancelled and PageRead::Cancelled are handled in `err.is_cancel` branch.
3185 0 : self.compaction_circuit_breaker
3186 0 : .lock()
3187 0 : .unwrap()
3188 0 : .fail(&CIRCUIT_BREAKERS_BROKEN, err);
3189 0 : }
3190 0 : CompactionError::Other(err) => {
3191 0 : self.compaction_circuit_breaker
3192 0 : .lock()
3193 0 : .unwrap()
3194 0 : .fail(&CIRCUIT_BREAKERS_BROKEN, err);
3195 0 : }
3196 0 : CompactionError::AlreadyRunning(_) => {}
3197 : }
3198 0 : }
3199 :
3200 : /// Cancel scheduled compaction tasks
3201 0 : pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
3202 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3203 0 : if let Some(q) = guard.get_mut(&timeline_id) {
3204 0 : q.cancel_scheduled();
3205 0 : }
3206 0 : }
3207 :
3208 0 : pub(crate) fn get_scheduled_compaction_tasks(
3209 0 : &self,
3210 0 : timeline_id: TimelineId,
3211 0 : ) -> Vec<CompactInfoResponse> {
3212 0 : let res = {
3213 0 : let guard = self.scheduled_compaction_tasks.lock().unwrap();
3214 0 : guard.get(&timeline_id).map(|q| q.remaining_jobs())
3215 : };
3216 0 : let Some((running, remaining)) = res else {
3217 0 : return Vec::new();
3218 : };
3219 0 : let mut result = Vec::new();
3220 0 : if let Some((id, running)) = running {
3221 0 : result.extend(running.into_compact_info_resp(id, true));
3222 0 : }
3223 0 : for (id, job) in remaining {
3224 0 : result.extend(job.into_compact_info_resp(id, false));
3225 0 : }
3226 0 : result
3227 0 : }
3228 :
3229 : /// Schedule a compaction task for a timeline.
3230 0 : pub(crate) async fn schedule_compaction(
3231 0 : &self,
3232 0 : timeline_id: TimelineId,
3233 0 : options: CompactOptions,
3234 0 : ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
3235 0 : let (tx, rx) = tokio::sync::oneshot::channel();
3236 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3237 0 : let q = guard
3238 0 : .entry(timeline_id)
3239 0 : .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
3240 0 : q.schedule_manual_compaction(options, Some(tx));
3241 0 : Ok(rx)
3242 0 : }
3243 :
3244 : /// Performs periodic housekeeping, via the tenant housekeeping background task.
3245 0 : async fn housekeeping(&self) {
3246 0 : // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
3247 0 : // during ingest, but we don't want idle timelines to hold open layers for too long.
3248 0 : let timelines = self
3249 0 : .timelines
3250 0 : .lock()
3251 0 : .unwrap()
3252 0 : .values()
3253 0 : .filter(|tli| tli.is_active())
3254 0 : .cloned()
3255 0 : .collect_vec();
3256 :
3257 0 : for timeline in timelines {
3258 0 : timeline.maybe_freeze_ephemeral_layer().await;
3259 : }
3260 :
3261 : // Shut down walredo if idle.
3262 : const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
3263 0 : if let Some(ref walredo_mgr) = self.walredo_mgr {
3264 0 : walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
3265 0 : }
3266 0 : }
3267 :
3268 0 : pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
3269 0 : let timelines = self.timelines.lock().unwrap();
3270 0 : !timelines
3271 0 : .iter()
3272 0 : .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
3273 0 : }
3274 :
3275 3476 : pub fn current_state(&self) -> TenantState {
3276 3476 : self.state.borrow().clone()
3277 3476 : }
3278 :
3279 1952 : pub fn is_active(&self) -> bool {
3280 1952 : self.current_state() == TenantState::Active
3281 1952 : }
3282 :
3283 0 : pub fn generation(&self) -> Generation {
3284 0 : self.generation
3285 0 : }
3286 :
3287 0 : pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
3288 0 : self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
3289 0 : }
3290 :
3291 : /// Changes tenant status to active, unless shutdown was already requested.
3292 : ///
3293 : /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
3294 : /// to delay background jobs. Background jobs can be started right away when None is given.
3295 0 : fn activate(
3296 0 : self: &Arc<Self>,
3297 0 : broker_client: BrokerClientChannel,
3298 0 : background_jobs_can_start: Option<&completion::Barrier>,
3299 0 : ctx: &RequestContext,
3300 0 : ) {
3301 0 : span::debug_assert_current_span_has_tenant_id();
3302 0 :
3303 0 : let mut activating = false;
3304 0 : self.state.send_modify(|current_state| {
3305 : use pageserver_api::models::ActivatingFrom;
3306 0 : match &*current_state {
3307 : TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
3308 0 : panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
3309 : }
3310 0 : TenantState::Attaching => {
3311 0 : *current_state = TenantState::Activating(ActivatingFrom::Attaching);
3312 0 : }
3313 0 : }
3314 0 : debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
3315 0 : activating = true;
3316 0 : // Continue outside the closure. We need to grab timelines.lock()
3317 0 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
3318 0 : });
3319 0 :
3320 0 : if activating {
3321 0 : let timelines_accessor = self.timelines.lock().unwrap();
3322 0 : let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
3323 0 : let timelines_to_activate = timelines_accessor
3324 0 : .values()
3325 0 : .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
3326 0 :
3327 0 : // Before activation, populate each Timeline's GcInfo with information about its children
3328 0 : self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
3329 0 :
3330 0 : // Spawn gc and compaction loops. The loops will shut themselves
3331 0 : // down when they notice that the tenant is inactive.
3332 0 : tasks::start_background_loops(self, background_jobs_can_start);
3333 0 :
3334 0 : let mut activated_timelines = 0;
3335 :
3336 0 : for timeline in timelines_to_activate {
3337 0 : timeline.activate(
3338 0 : self.clone(),
3339 0 : broker_client.clone(),
3340 0 : background_jobs_can_start,
3341 0 : &ctx.with_scope_timeline(timeline),
3342 0 : );
3343 0 : activated_timelines += 1;
3344 0 : }
3345 :
3346 0 : self.state.send_modify(move |current_state| {
3347 0 : assert!(
3348 0 : matches!(current_state, TenantState::Activating(_)),
3349 0 : "set_stopping and set_broken wait for us to leave Activating state",
3350 : );
3351 0 : *current_state = TenantState::Active;
3352 0 :
3353 0 : let elapsed = self.constructed_at.elapsed();
3354 0 : let total_timelines = timelines_accessor.len();
3355 0 :
3356 0 : // log a lot of stuff, because some tenants sometimes suffer from user-visible
3357 0 : // times to activate. see https://github.com/neondatabase/neon/issues/4025
3358 0 : info!(
3359 0 : since_creation_millis = elapsed.as_millis(),
3360 0 : tenant_id = %self.tenant_shard_id.tenant_id,
3361 0 : shard_id = %self.tenant_shard_id.shard_slug(),
3362 0 : activated_timelines,
3363 0 : total_timelines,
3364 0 : post_state = <&'static str>::from(&*current_state),
3365 0 : "activation attempt finished"
3366 : );
3367 :
3368 0 : TENANT.activation.observe(elapsed.as_secs_f64());
3369 0 : });
3370 0 : }
3371 0 : }
3372 :
3373 : /// Shutdown the tenant and join all of the spawned tasks.
3374 : ///
3375 : /// The method caters for all use-cases:
3376 : /// - pageserver shutdown (freeze_and_flush == true)
3377 : /// - detach + ignore (freeze_and_flush == false)
3378 : ///
3379 : /// This will attempt to shutdown even if tenant is broken.
3380 : ///
3381 : /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
3382 : /// If the tenant is already shutting down, we return a clone of the first shutdown call's
3383 : /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
3384 : /// the ongoing shutdown.
3385 12 : async fn shutdown(
3386 12 : &self,
3387 12 : shutdown_progress: completion::Barrier,
3388 12 : shutdown_mode: timeline::ShutdownMode,
3389 12 : ) -> Result<(), completion::Barrier> {
3390 12 : span::debug_assert_current_span_has_tenant_id();
3391 :
3392 : // Set tenant (and its timlines) to Stoppping state.
3393 : //
3394 : // Since we can only transition into Stopping state after activation is complete,
3395 : // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
3396 : //
3397 : // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
3398 : // 1. Lock out any new requests to the tenants.
3399 : // 2. Signal cancellation to WAL receivers (we wait on it below).
3400 : // 3. Signal cancellation for other tenant background loops.
3401 : // 4. ???
3402 : //
3403 : // The waiting for the cancellation is not done uniformly.
3404 : // We certainly wait for WAL receivers to shut down.
3405 : // That is necessary so that no new data comes in before the freeze_and_flush.
3406 : // But the tenant background loops are joined-on in our caller.
3407 : // It's mesed up.
3408 : // we just ignore the failure to stop
3409 :
3410 : // If we're still attaching, fire the cancellation token early to drop out: this
3411 : // will prevent us flushing, but ensures timely shutdown if some I/O during attach
3412 : // is very slow.
3413 12 : let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
3414 0 : self.cancel.cancel();
3415 0 :
3416 0 : // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
3417 0 : // are children of ours, so their flush loops will have shut down already
3418 0 : timeline::ShutdownMode::Hard
3419 : } else {
3420 12 : shutdown_mode
3421 : };
3422 :
3423 12 : match self.set_stopping(shutdown_progress, false, false).await {
3424 12 : Ok(()) => {}
3425 0 : Err(SetStoppingError::Broken) => {
3426 0 : // assume that this is acceptable
3427 0 : }
3428 0 : Err(SetStoppingError::AlreadyStopping(other)) => {
3429 0 : // give caller the option to wait for this this shutdown
3430 0 : info!("Tenant::shutdown: AlreadyStopping");
3431 0 : return Err(other);
3432 : }
3433 : };
3434 :
3435 12 : let mut js = tokio::task::JoinSet::new();
3436 12 : {
3437 12 : let timelines = self.timelines.lock().unwrap();
3438 12 : timelines.values().for_each(|timeline| {
3439 12 : let timeline = Arc::clone(timeline);
3440 12 : let timeline_id = timeline.timeline_id;
3441 12 : let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
3442 12 : js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
3443 12 : });
3444 12 : }
3445 12 : {
3446 12 : let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
3447 12 : timelines_offloaded.values().for_each(|timeline| {
3448 0 : timeline.defuse_for_tenant_drop();
3449 12 : });
3450 12 : }
3451 12 : // test_long_timeline_create_then_tenant_delete is leaning on this message
3452 12 : tracing::info!("Waiting for timelines...");
3453 24 : while let Some(res) = js.join_next().await {
3454 0 : match res {
3455 12 : Ok(()) => {}
3456 0 : Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
3457 0 : Err(je) if je.is_panic() => { /* logged already */ }
3458 0 : Err(je) => warn!("unexpected JoinError: {je:?}"),
3459 : }
3460 : }
3461 :
3462 12 : if let ShutdownMode::Reload = shutdown_mode {
3463 0 : tracing::info!("Flushing deletion queue");
3464 0 : if let Err(e) = self.deletion_queue_client.flush().await {
3465 0 : match e {
3466 0 : DeletionQueueError::ShuttingDown => {
3467 0 : // This is the only error we expect for now. In the future, if more error
3468 0 : // variants are added, we should handle them here.
3469 0 : }
3470 : }
3471 0 : }
3472 12 : }
3473 :
3474 : // We cancel the Tenant's cancellation token _after_ the timelines have all shut down. This permits
3475 : // them to continue to do work during their shutdown methods, e.g. flushing data.
3476 12 : tracing::debug!("Cancelling CancellationToken");
3477 12 : self.cancel.cancel();
3478 12 :
3479 12 : // shutdown all tenant and timeline tasks: gc, compaction, page service
3480 12 : // No new tasks will be started for this tenant because it's in `Stopping` state.
3481 12 : //
3482 12 : // this will additionally shutdown and await all timeline tasks.
3483 12 : tracing::debug!("Waiting for tasks...");
3484 12 : task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
3485 :
3486 12 : if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
3487 12 : walredo_mgr.shutdown().await;
3488 0 : }
3489 :
3490 : // Wait for any in-flight operations to complete
3491 12 : self.gate.close().await;
3492 :
3493 12 : remove_tenant_metrics(&self.tenant_shard_id);
3494 12 :
3495 12 : Ok(())
3496 12 : }
3497 :
3498 : /// Change tenant status to Stopping, to mark that it is being shut down.
3499 : ///
3500 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
3501 : ///
3502 : /// This function is not cancel-safe!
3503 : ///
3504 : /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
3505 : /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
3506 12 : async fn set_stopping(
3507 12 : &self,
3508 12 : progress: completion::Barrier,
3509 12 : _allow_transition_from_loading: bool,
3510 12 : allow_transition_from_attaching: bool,
3511 12 : ) -> Result<(), SetStoppingError> {
3512 12 : let mut rx = self.state.subscribe();
3513 12 :
3514 12 : // cannot stop before we're done activating, so wait out until we're done activating
3515 12 : rx.wait_for(|state| match state {
3516 0 : TenantState::Attaching if allow_transition_from_attaching => true,
3517 : TenantState::Activating(_) | TenantState::Attaching => {
3518 0 : info!(
3519 0 : "waiting for {} to turn Active|Broken|Stopping",
3520 0 : <&'static str>::from(state)
3521 : );
3522 0 : false
3523 : }
3524 12 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
3525 12 : })
3526 12 : .await
3527 12 : .expect("cannot drop self.state while on a &self method");
3528 12 :
3529 12 : // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
3530 12 : let mut err = None;
3531 12 : let stopping = self.state.send_if_modified(|current_state| match current_state {
3532 : TenantState::Activating(_) => {
3533 0 : unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
3534 : }
3535 : TenantState::Attaching => {
3536 0 : if !allow_transition_from_attaching {
3537 0 : unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
3538 0 : };
3539 0 : *current_state = TenantState::Stopping { progress };
3540 0 : true
3541 : }
3542 : TenantState::Active => {
3543 : // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
3544 : // are created after the transition to Stopping. That's harmless, as the Timelines
3545 : // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
3546 12 : *current_state = TenantState::Stopping { progress };
3547 12 : // Continue stopping outside the closure. We need to grab timelines.lock()
3548 12 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
3549 12 : true
3550 : }
3551 0 : TenantState::Broken { reason, .. } => {
3552 0 : info!(
3553 0 : "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
3554 : );
3555 0 : err = Some(SetStoppingError::Broken);
3556 0 : false
3557 : }
3558 0 : TenantState::Stopping { progress } => {
3559 0 : info!("Tenant is already in Stopping state");
3560 0 : err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
3561 0 : false
3562 : }
3563 12 : });
3564 12 : match (stopping, err) {
3565 12 : (true, None) => {} // continue
3566 0 : (false, Some(err)) => return Err(err),
3567 0 : (true, Some(_)) => unreachable!(
3568 0 : "send_if_modified closure must error out if not transitioning to Stopping"
3569 0 : ),
3570 0 : (false, None) => unreachable!(
3571 0 : "send_if_modified closure must return true if transitioning to Stopping"
3572 0 : ),
3573 : }
3574 :
3575 12 : let timelines_accessor = self.timelines.lock().unwrap();
3576 12 : let not_broken_timelines = timelines_accessor
3577 12 : .values()
3578 12 : .filter(|timeline| !timeline.is_broken());
3579 24 : for timeline in not_broken_timelines {
3580 12 : timeline.set_state(TimelineState::Stopping);
3581 12 : }
3582 12 : Ok(())
3583 12 : }
3584 :
3585 : /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
3586 : /// `remove_tenant_from_memory`
3587 : ///
3588 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
3589 : ///
3590 : /// In tests, we also use this to set tenants to Broken state on purpose.
3591 0 : pub(crate) async fn set_broken(&self, reason: String) {
3592 0 : let mut rx = self.state.subscribe();
3593 0 :
3594 0 : // The load & attach routines own the tenant state until it has reached `Active`.
3595 0 : // So, wait until it's done.
3596 0 : rx.wait_for(|state| match state {
3597 : TenantState::Activating(_) | TenantState::Attaching => {
3598 0 : info!(
3599 0 : "waiting for {} to turn Active|Broken|Stopping",
3600 0 : <&'static str>::from(state)
3601 : );
3602 0 : false
3603 : }
3604 0 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
3605 0 : })
3606 0 : .await
3607 0 : .expect("cannot drop self.state while on a &self method");
3608 0 :
3609 0 : // we now know we're done activating, let's see whether this task is the winner to transition into Broken
3610 0 : self.set_broken_no_wait(reason)
3611 0 : }
3612 :
3613 0 : pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
3614 0 : let reason = reason.to_string();
3615 0 : self.state.send_modify(|current_state| {
3616 0 : match *current_state {
3617 : TenantState::Activating(_) | TenantState::Attaching => {
3618 0 : unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
3619 : }
3620 : TenantState::Active => {
3621 0 : if cfg!(feature = "testing") {
3622 0 : warn!("Changing Active tenant to Broken state, reason: {}", reason);
3623 0 : *current_state = TenantState::broken_from_reason(reason);
3624 : } else {
3625 0 : unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
3626 : }
3627 : }
3628 : TenantState::Broken { .. } => {
3629 0 : warn!("Tenant is already in Broken state");
3630 : }
3631 : // This is the only "expected" path, any other path is a bug.
3632 : TenantState::Stopping { .. } => {
3633 0 : warn!(
3634 0 : "Marking Stopping tenant as Broken state, reason: {}",
3635 : reason
3636 : );
3637 0 : *current_state = TenantState::broken_from_reason(reason);
3638 : }
3639 : }
3640 0 : });
3641 0 : }
3642 :
3643 0 : pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
3644 0 : self.state.subscribe()
3645 0 : }
3646 :
3647 : /// The activate_now semaphore is initialized with zero units. As soon as
3648 : /// we add a unit, waiters will be able to acquire a unit and proceed.
3649 0 : pub(crate) fn activate_now(&self) {
3650 0 : self.activate_now_sem.add_permits(1);
3651 0 : }
3652 :
3653 0 : pub(crate) async fn wait_to_become_active(
3654 0 : &self,
3655 0 : timeout: Duration,
3656 0 : ) -> Result<(), GetActiveTenantError> {
3657 0 : let mut receiver = self.state.subscribe();
3658 : loop {
3659 0 : let current_state = receiver.borrow_and_update().clone();
3660 0 : match current_state {
3661 : TenantState::Attaching | TenantState::Activating(_) => {
3662 : // in these states, there's a chance that we can reach ::Active
3663 0 : self.activate_now();
3664 0 : match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
3665 0 : Ok(r) => {
3666 0 : r.map_err(
3667 0 : |_e: tokio::sync::watch::error::RecvError|
3668 : // Tenant existed but was dropped: report it as non-existent
3669 0 : GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
3670 0 : )?
3671 : }
3672 : Err(TimeoutCancellableError::Cancelled) => {
3673 0 : return Err(GetActiveTenantError::Cancelled);
3674 : }
3675 : Err(TimeoutCancellableError::Timeout) => {
3676 0 : return Err(GetActiveTenantError::WaitForActiveTimeout {
3677 0 : latest_state: Some(self.current_state()),
3678 0 : wait_time: timeout,
3679 0 : });
3680 : }
3681 : }
3682 : }
3683 : TenantState::Active => {
3684 0 : return Ok(());
3685 : }
3686 0 : TenantState::Broken { reason, .. } => {
3687 0 : // This is fatal, and reported distinctly from the general case of "will never be active" because
3688 0 : // it's logically a 500 to external API users (broken is always a bug).
3689 0 : return Err(GetActiveTenantError::Broken(reason));
3690 : }
3691 : TenantState::Stopping { .. } => {
3692 : // There's no chance the tenant can transition back into ::Active
3693 0 : return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
3694 : }
3695 : }
3696 : }
3697 0 : }
3698 :
3699 0 : pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
3700 0 : self.tenant_conf.load().location.attach_mode
3701 0 : }
3702 :
3703 : /// For API access: generate a LocationConfig equivalent to the one that would be used to
3704 : /// create a Tenant in the same state. Do not use this in hot paths: it's for relatively
3705 : /// rare external API calls, like a reconciliation at startup.
3706 0 : pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
3707 0 : let conf = self.tenant_conf.load();
3708 :
3709 0 : let location_config_mode = match conf.location.attach_mode {
3710 0 : AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
3711 0 : AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
3712 0 : AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
3713 : };
3714 :
3715 : // We have a pageserver TenantConf, we need the API-facing TenantConfig.
3716 0 : let tenant_config: models::TenantConfig = conf.tenant_conf.clone().into();
3717 0 :
3718 0 : models::LocationConfig {
3719 0 : mode: location_config_mode,
3720 0 : generation: self.generation.into(),
3721 0 : secondary_conf: None,
3722 0 : shard_number: self.shard_identity.number.0,
3723 0 : shard_count: self.shard_identity.count.literal(),
3724 0 : shard_stripe_size: self.shard_identity.stripe_size.0,
3725 0 : tenant_conf: tenant_config,
3726 0 : }
3727 0 : }
3728 :
3729 0 : pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
3730 0 : &self.tenant_shard_id
3731 0 : }
3732 :
3733 0 : pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
3734 0 : self.shard_identity.stripe_size
3735 0 : }
3736 :
3737 0 : pub(crate) fn get_generation(&self) -> Generation {
3738 0 : self.generation
3739 0 : }
3740 :
3741 : /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
3742 : /// and can leave the tenant in a bad state if it fails. The caller is responsible for
3743 : /// resetting this tenant to a valid state if we fail.
3744 0 : pub(crate) async fn split_prepare(
3745 0 : &self,
3746 0 : child_shards: &Vec<TenantShardId>,
3747 0 : ) -> anyhow::Result<()> {
3748 0 : let (timelines, offloaded) = {
3749 0 : let timelines = self.timelines.lock().unwrap();
3750 0 : let offloaded = self.timelines_offloaded.lock().unwrap();
3751 0 : (timelines.clone(), offloaded.clone())
3752 0 : };
3753 0 : let timelines_iter = timelines
3754 0 : .values()
3755 0 : .map(TimelineOrOffloadedArcRef::<'_>::from)
3756 0 : .chain(
3757 0 : offloaded
3758 0 : .values()
3759 0 : .map(TimelineOrOffloadedArcRef::<'_>::from),
3760 0 : );
3761 0 : for timeline in timelines_iter {
3762 : // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
3763 : // to ensure that they do not start a split if currently in the process of doing these.
3764 :
3765 0 : let timeline_id = timeline.timeline_id();
3766 :
3767 0 : if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
3768 : // Upload an index from the parent: this is partly to provide freshness for the
3769 : // child tenants that will copy it, and partly for general ease-of-debugging: there will
3770 : // always be a parent shard index in the same generation as we wrote the child shard index.
3771 0 : tracing::info!(%timeline_id, "Uploading index");
3772 0 : timeline
3773 0 : .remote_client
3774 0 : .schedule_index_upload_for_file_changes()?;
3775 0 : timeline.remote_client.wait_completion().await?;
3776 0 : }
3777 :
3778 0 : let remote_client = match timeline {
3779 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
3780 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
3781 0 : let remote_client = self
3782 0 : .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
3783 0 : Arc::new(remote_client)
3784 : }
3785 : };
3786 :
3787 : // Shut down the timeline's remote client: this means that the indices we write
3788 : // for child shards will not be invalidated by the parent shard deleting layers.
3789 0 : tracing::info!(%timeline_id, "Shutting down remote storage client");
3790 0 : remote_client.shutdown().await;
3791 :
3792 : // Download methods can still be used after shutdown, as they don't flow through the remote client's
3793 : // queue. In principal the RemoteTimelineClient could provide this without downloading it, but this
3794 : // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
3795 : // we use here really is the remotely persistent one).
3796 0 : tracing::info!(%timeline_id, "Downloading index_part from parent");
3797 0 : let result = remote_client
3798 0 : .download_index_file(&self.cancel)
3799 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))
3800 0 : .await?;
3801 0 : let index_part = match result {
3802 : MaybeDeletedIndexPart::Deleted(_) => {
3803 0 : anyhow::bail!("Timeline deletion happened concurrently with split")
3804 : }
3805 0 : MaybeDeletedIndexPart::IndexPart(p) => p,
3806 : };
3807 :
3808 0 : for child_shard in child_shards {
3809 0 : tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
3810 0 : upload_index_part(
3811 0 : &self.remote_storage,
3812 0 : child_shard,
3813 0 : &timeline_id,
3814 0 : self.generation,
3815 0 : &index_part,
3816 0 : &self.cancel,
3817 0 : )
3818 0 : .await?;
3819 : }
3820 : }
3821 :
3822 0 : let tenant_manifest = self.build_tenant_manifest();
3823 0 : for child_shard in child_shards {
3824 0 : tracing::info!(
3825 0 : "Uploading tenant manifest for child {}",
3826 0 : child_shard.to_index()
3827 : );
3828 0 : upload_tenant_manifest(
3829 0 : &self.remote_storage,
3830 0 : child_shard,
3831 0 : self.generation,
3832 0 : &tenant_manifest,
3833 0 : &self.cancel,
3834 0 : )
3835 0 : .await?;
3836 : }
3837 :
3838 0 : Ok(())
3839 0 : }
3840 :
3841 0 : pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
3842 0 : let mut result = TopTenantShardItem {
3843 0 : id: self.tenant_shard_id,
3844 0 : resident_size: 0,
3845 0 : physical_size: 0,
3846 0 : max_logical_size: 0,
3847 0 : max_logical_size_per_shard: 0,
3848 0 : };
3849 :
3850 0 : for timeline in self.timelines.lock().unwrap().values() {
3851 0 : result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
3852 0 :
3853 0 : result.physical_size += timeline
3854 0 : .remote_client
3855 0 : .metrics
3856 0 : .remote_physical_size_gauge
3857 0 : .get();
3858 0 : result.max_logical_size = std::cmp::max(
3859 0 : result.max_logical_size,
3860 0 : timeline.metrics.current_logical_size_gauge.get(),
3861 0 : );
3862 0 : }
3863 :
3864 0 : result.max_logical_size_per_shard = result
3865 0 : .max_logical_size
3866 0 : .div_ceil(self.tenant_shard_id.shard_count.count() as u64);
3867 0 :
3868 0 : result
3869 0 : }
3870 : }
3871 :
3872 : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
3873 : /// perform a topological sort, so that the parent of each timeline comes
3874 : /// before the children.
3875 : /// E extracts the ancestor from T
3876 : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
3877 452 : fn tree_sort_timelines<T, E>(
3878 452 : timelines: HashMap<TimelineId, T>,
3879 452 : extractor: E,
3880 452 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
3881 452 : where
3882 452 : E: Fn(&T) -> Option<TimelineId>,
3883 452 : {
3884 452 : let mut result = Vec::with_capacity(timelines.len());
3885 452 :
3886 452 : let mut now = Vec::with_capacity(timelines.len());
3887 452 : // (ancestor, children)
3888 452 : let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
3889 452 : HashMap::with_capacity(timelines.len());
3890 :
3891 464 : for (timeline_id, value) in timelines {
3892 12 : if let Some(ancestor_id) = extractor(&value) {
3893 4 : let children = later.entry(ancestor_id).or_default();
3894 4 : children.push((timeline_id, value));
3895 8 : } else {
3896 8 : now.push((timeline_id, value));
3897 8 : }
3898 : }
3899 :
3900 464 : while let Some((timeline_id, metadata)) = now.pop() {
3901 12 : result.push((timeline_id, metadata));
3902 : // All children of this can be loaded now
3903 12 : if let Some(mut children) = later.remove(&timeline_id) {
3904 4 : now.append(&mut children);
3905 8 : }
3906 : }
3907 :
3908 : // All timelines should be visited now. Unless there were timelines with missing ancestors.
3909 452 : if !later.is_empty() {
3910 0 : for (missing_id, orphan_ids) in later {
3911 0 : for (orphan_id, _) in orphan_ids {
3912 0 : error!(
3913 0 : "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
3914 : );
3915 : }
3916 : }
3917 0 : bail!("could not load tenant because some timelines are missing ancestors");
3918 452 : }
3919 452 :
3920 452 : Ok(result)
3921 452 : }
3922 :
3923 : enum ActivateTimelineArgs {
3924 : Yes {
3925 : broker_client: storage_broker::BrokerClientChannel,
3926 : },
3927 : No,
3928 : }
3929 :
3930 : impl Tenant {
3931 0 : pub fn tenant_specific_overrides(&self) -> TenantConfOpt {
3932 0 : self.tenant_conf.load().tenant_conf.clone()
3933 0 : }
3934 :
3935 0 : pub fn effective_config(&self) -> TenantConf {
3936 0 : self.tenant_specific_overrides()
3937 0 : .merge(self.conf.default_tenant_conf.clone())
3938 0 : }
3939 :
3940 0 : pub fn get_checkpoint_distance(&self) -> u64 {
3941 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3942 0 : tenant_conf
3943 0 : .checkpoint_distance
3944 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
3945 0 : }
3946 :
3947 0 : pub fn get_checkpoint_timeout(&self) -> Duration {
3948 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3949 0 : tenant_conf
3950 0 : .checkpoint_timeout
3951 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
3952 0 : }
3953 :
3954 0 : pub fn get_compaction_target_size(&self) -> u64 {
3955 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3956 0 : tenant_conf
3957 0 : .compaction_target_size
3958 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
3959 0 : }
3960 :
3961 0 : pub fn get_compaction_period(&self) -> Duration {
3962 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3963 0 : tenant_conf
3964 0 : .compaction_period
3965 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_period)
3966 0 : }
3967 :
3968 0 : pub fn get_compaction_threshold(&self) -> usize {
3969 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3970 0 : tenant_conf
3971 0 : .compaction_threshold
3972 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
3973 0 : }
3974 :
3975 0 : pub fn get_rel_size_v2_enabled(&self) -> bool {
3976 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3977 0 : tenant_conf
3978 0 : .rel_size_v2_enabled
3979 0 : .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
3980 0 : }
3981 :
3982 0 : pub fn get_compaction_upper_limit(&self) -> usize {
3983 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3984 0 : tenant_conf
3985 0 : .compaction_upper_limit
3986 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
3987 0 : }
3988 :
3989 0 : pub fn get_compaction_l0_first(&self) -> bool {
3990 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3991 0 : tenant_conf
3992 0 : .compaction_l0_first
3993 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
3994 0 : }
3995 :
3996 0 : pub fn get_gc_horizon(&self) -> u64 {
3997 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3998 0 : tenant_conf
3999 0 : .gc_horizon
4000 0 : .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
4001 0 : }
4002 :
4003 0 : pub fn get_gc_period(&self) -> Duration {
4004 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4005 0 : tenant_conf
4006 0 : .gc_period
4007 0 : .unwrap_or(self.conf.default_tenant_conf.gc_period)
4008 0 : }
4009 :
4010 0 : pub fn get_image_creation_threshold(&self) -> usize {
4011 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4012 0 : tenant_conf
4013 0 : .image_creation_threshold
4014 0 : .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
4015 0 : }
4016 :
4017 0 : pub fn get_pitr_interval(&self) -> Duration {
4018 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4019 0 : tenant_conf
4020 0 : .pitr_interval
4021 0 : .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
4022 0 : }
4023 :
4024 0 : pub fn get_min_resident_size_override(&self) -> Option<u64> {
4025 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4026 0 : tenant_conf
4027 0 : .min_resident_size_override
4028 0 : .or(self.conf.default_tenant_conf.min_resident_size_override)
4029 0 : }
4030 :
4031 0 : pub fn get_heatmap_period(&self) -> Option<Duration> {
4032 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4033 0 : let heatmap_period = tenant_conf
4034 0 : .heatmap_period
4035 0 : .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
4036 0 : if heatmap_period.is_zero() {
4037 0 : None
4038 : } else {
4039 0 : Some(heatmap_period)
4040 : }
4041 0 : }
4042 :
4043 8 : pub fn get_lsn_lease_length(&self) -> Duration {
4044 8 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4045 8 : tenant_conf
4046 8 : .lsn_lease_length
4047 8 : .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
4048 8 : }
4049 :
4050 0 : pub fn get_timeline_offloading_enabled(&self) -> bool {
4051 0 : if self.conf.timeline_offloading {
4052 0 : return true;
4053 0 : }
4054 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4055 0 : tenant_conf
4056 0 : .timeline_offloading
4057 0 : .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
4058 0 : }
4059 :
4060 : /// Generate an up-to-date TenantManifest based on the state of this Tenant.
4061 4 : fn build_tenant_manifest(&self) -> TenantManifest {
4062 4 : let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
4063 4 :
4064 4 : let mut timeline_manifests = timelines_offloaded
4065 4 : .iter()
4066 4 : .map(|(_timeline_id, offloaded)| offloaded.manifest())
4067 4 : .collect::<Vec<_>>();
4068 4 : // Sort the manifests so that our output is deterministic
4069 4 : timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
4070 4 :
4071 4 : TenantManifest {
4072 4 : version: LATEST_TENANT_MANIFEST_VERSION,
4073 4 : offloaded_timelines: timeline_manifests,
4074 4 : }
4075 4 : }
4076 :
4077 0 : pub fn update_tenant_config<F: Fn(TenantConfOpt) -> anyhow::Result<TenantConfOpt>>(
4078 0 : &self,
4079 0 : update: F,
4080 0 : ) -> anyhow::Result<TenantConfOpt> {
4081 0 : // Use read-copy-update in order to avoid overwriting the location config
4082 0 : // state if this races with [`Tenant::set_new_location_config`]. Note that
4083 0 : // this race is not possible if both request types come from the storage
4084 0 : // controller (as they should!) because an exclusive op lock is required
4085 0 : // on the storage controller side.
4086 0 :
4087 0 : self.tenant_conf
4088 0 : .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
4089 0 : Ok(Arc::new(AttachedTenantConf {
4090 0 : tenant_conf: update(attached_conf.tenant_conf.clone())?,
4091 0 : location: attached_conf.location,
4092 0 : lsn_lease_deadline: attached_conf.lsn_lease_deadline,
4093 : }))
4094 0 : })?;
4095 :
4096 0 : let updated = self.tenant_conf.load();
4097 0 :
4098 0 : self.tenant_conf_updated(&updated.tenant_conf);
4099 0 : // Don't hold self.timelines.lock() during the notifies.
4100 0 : // There's no risk of deadlock right now, but there could be if we consolidate
4101 0 : // mutexes in struct Timeline in the future.
4102 0 : let timelines = self.list_timelines();
4103 0 : for timeline in timelines {
4104 0 : timeline.tenant_conf_updated(&updated);
4105 0 : }
4106 :
4107 0 : Ok(updated.tenant_conf.clone())
4108 0 : }
4109 :
4110 0 : pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
4111 0 : let new_tenant_conf = new_conf.tenant_conf.clone();
4112 0 :
4113 0 : self.tenant_conf.store(Arc::new(new_conf.clone()));
4114 0 :
4115 0 : self.tenant_conf_updated(&new_tenant_conf);
4116 0 : // Don't hold self.timelines.lock() during the notifies.
4117 0 : // There's no risk of deadlock right now, but there could be if we consolidate
4118 0 : // mutexes in struct Timeline in the future.
4119 0 : let timelines = self.list_timelines();
4120 0 : for timeline in timelines {
4121 0 : timeline.tenant_conf_updated(&new_conf);
4122 0 : }
4123 0 : }
4124 :
4125 452 : fn get_pagestream_throttle_config(
4126 452 : psconf: &'static PageServerConf,
4127 452 : overrides: &TenantConfOpt,
4128 452 : ) -> throttle::Config {
4129 452 : overrides
4130 452 : .timeline_get_throttle
4131 452 : .clone()
4132 452 : .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
4133 452 : }
4134 :
4135 0 : pub(crate) fn tenant_conf_updated(&self, new_conf: &TenantConfOpt) {
4136 0 : let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
4137 0 : self.pagestream_throttle.reconfigure(conf)
4138 0 : }
4139 :
4140 : /// Helper function to create a new Timeline struct.
4141 : ///
4142 : /// The returned Timeline is in Loading state. The caller is responsible for
4143 : /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
4144 : /// map.
4145 : ///
4146 : /// `validate_ancestor == false` is used when a timeline is created for deletion
4147 : /// and we might not have the ancestor present anymore which is fine for to be
4148 : /// deleted timelines.
4149 : #[allow(clippy::too_many_arguments)]
4150 904 : fn create_timeline_struct(
4151 904 : &self,
4152 904 : new_timeline_id: TimelineId,
4153 904 : new_metadata: &TimelineMetadata,
4154 904 : previous_heatmap: Option<PreviousHeatmap>,
4155 904 : ancestor: Option<Arc<Timeline>>,
4156 904 : resources: TimelineResources,
4157 904 : cause: CreateTimelineCause,
4158 904 : create_idempotency: CreateTimelineIdempotency,
4159 904 : gc_compaction_state: Option<GcCompactionState>,
4160 904 : rel_size_v2_status: Option<RelSizeMigration>,
4161 904 : ctx: &RequestContext,
4162 904 : ) -> anyhow::Result<(Arc<Timeline>, RequestContext)> {
4163 904 : let state = match cause {
4164 : CreateTimelineCause::Load => {
4165 904 : let ancestor_id = new_metadata.ancestor_timeline();
4166 904 : anyhow::ensure!(
4167 904 : ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
4168 0 : "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
4169 : );
4170 904 : TimelineState::Loading
4171 : }
4172 0 : CreateTimelineCause::Delete => TimelineState::Stopping,
4173 : };
4174 :
4175 904 : let pg_version = new_metadata.pg_version();
4176 904 :
4177 904 : let timeline = Timeline::new(
4178 904 : self.conf,
4179 904 : Arc::clone(&self.tenant_conf),
4180 904 : new_metadata,
4181 904 : previous_heatmap,
4182 904 : ancestor,
4183 904 : new_timeline_id,
4184 904 : self.tenant_shard_id,
4185 904 : self.generation,
4186 904 : self.shard_identity,
4187 904 : self.walredo_mgr.clone(),
4188 904 : resources,
4189 904 : pg_version,
4190 904 : state,
4191 904 : self.attach_wal_lag_cooldown.clone(),
4192 904 : create_idempotency,
4193 904 : gc_compaction_state,
4194 904 : rel_size_v2_status,
4195 904 : self.cancel.child_token(),
4196 904 : );
4197 904 :
4198 904 : let timeline_ctx = RequestContextBuilder::extend(ctx)
4199 904 : .scope(context::Scope::new_timeline(&timeline))
4200 904 : .build();
4201 904 :
4202 904 : Ok((timeline, timeline_ctx))
4203 904 : }
4204 :
4205 : /// [`Tenant::shutdown`] must be called before dropping the returned [`Tenant`] object
4206 : /// to ensure proper cleanup of background tasks and metrics.
4207 : //
4208 : // Allow too_many_arguments because a constructor's argument list naturally grows with the
4209 : // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
4210 : #[allow(clippy::too_many_arguments)]
4211 452 : fn new(
4212 452 : state: TenantState,
4213 452 : conf: &'static PageServerConf,
4214 452 : attached_conf: AttachedTenantConf,
4215 452 : shard_identity: ShardIdentity,
4216 452 : walredo_mgr: Option<Arc<WalRedoManager>>,
4217 452 : tenant_shard_id: TenantShardId,
4218 452 : remote_storage: GenericRemoteStorage,
4219 452 : deletion_queue_client: DeletionQueueClient,
4220 452 : l0_flush_global_state: L0FlushGlobalState,
4221 452 : ) -> Tenant {
4222 452 : debug_assert!(
4223 452 : !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
4224 : );
4225 :
4226 452 : let (state, mut rx) = watch::channel(state);
4227 452 :
4228 452 : tokio::spawn(async move {
4229 451 : // reflect tenant state in metrics:
4230 451 : // - global per tenant state: TENANT_STATE_METRIC
4231 451 : // - "set" of broken tenants: BROKEN_TENANTS_SET
4232 451 : //
4233 451 : // set of broken tenants should not have zero counts so that it remains accessible for
4234 451 : // alerting.
4235 451 :
4236 451 : let tid = tenant_shard_id.to_string();
4237 451 : let shard_id = tenant_shard_id.shard_slug().to_string();
4238 451 : let set_key = &[tid.as_str(), shard_id.as_str()][..];
4239 :
4240 901 : fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
4241 901 : ([state.into()], matches!(state, TenantState::Broken { .. }))
4242 901 : }
4243 :
4244 451 : let mut tuple = inspect_state(&rx.borrow_and_update());
4245 451 :
4246 451 : let is_broken = tuple.1;
4247 451 : let mut counted_broken = if is_broken {
4248 : // add the id to the set right away, there should not be any updates on the channel
4249 : // after before tenant is removed, if ever
4250 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
4251 0 : true
4252 : } else {
4253 451 : false
4254 : };
4255 :
4256 : loop {
4257 901 : let labels = &tuple.0;
4258 901 : let current = TENANT_STATE_METRIC.with_label_values(labels);
4259 901 : current.inc();
4260 901 :
4261 901 : if rx.changed().await.is_err() {
4262 : // tenant has been dropped
4263 28 : current.dec();
4264 28 : drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
4265 28 : break;
4266 450 : }
4267 450 :
4268 450 : current.dec();
4269 450 : tuple = inspect_state(&rx.borrow_and_update());
4270 450 :
4271 450 : let is_broken = tuple.1;
4272 450 : if is_broken && !counted_broken {
4273 0 : counted_broken = true;
4274 0 : // insert the tenant_id (back) into the set while avoiding needless counter
4275 0 : // access
4276 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
4277 450 : }
4278 : }
4279 452 : });
4280 452 :
4281 452 : Tenant {
4282 452 : tenant_shard_id,
4283 452 : shard_identity,
4284 452 : generation: attached_conf.location.generation,
4285 452 : conf,
4286 452 : // using now here is good enough approximation to catch tenants with really long
4287 452 : // activation times.
4288 452 : constructed_at: Instant::now(),
4289 452 : timelines: Mutex::new(HashMap::new()),
4290 452 : timelines_creating: Mutex::new(HashSet::new()),
4291 452 : timelines_offloaded: Mutex::new(HashMap::new()),
4292 452 : tenant_manifest_upload: Default::default(),
4293 452 : gc_cs: tokio::sync::Mutex::new(()),
4294 452 : walredo_mgr,
4295 452 : remote_storage,
4296 452 : deletion_queue_client,
4297 452 : state,
4298 452 : cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
4299 452 : cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
4300 452 : eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
4301 452 : compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
4302 452 : format!("compaction-{tenant_shard_id}"),
4303 452 : 5,
4304 452 : // Compaction can be a very expensive operation, and might leak disk space. It also ought
4305 452 : // to be infallible, as long as remote storage is available. So if it repeatedly fails,
4306 452 : // use an extremely long backoff.
4307 452 : Some(Duration::from_secs(3600 * 24)),
4308 452 : )),
4309 452 : l0_compaction_trigger: Arc::new(Notify::new()),
4310 452 : scheduled_compaction_tasks: Mutex::new(Default::default()),
4311 452 : activate_now_sem: tokio::sync::Semaphore::new(0),
4312 452 : attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
4313 452 : cancel: CancellationToken::default(),
4314 452 : gate: Gate::default(),
4315 452 : pagestream_throttle: Arc::new(throttle::Throttle::new(
4316 452 : Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
4317 452 : )),
4318 452 : pagestream_throttle_metrics: Arc::new(
4319 452 : crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
4320 452 : ),
4321 452 : tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
4322 452 : ongoing_timeline_detach: std::sync::Mutex::default(),
4323 452 : gc_block: Default::default(),
4324 452 : l0_flush_global_state,
4325 452 : }
4326 452 : }
4327 :
4328 : /// Locate and load config
4329 0 : pub(super) fn load_tenant_config(
4330 0 : conf: &'static PageServerConf,
4331 0 : tenant_shard_id: &TenantShardId,
4332 0 : ) -> Result<LocationConf, LoadConfigError> {
4333 0 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
4334 0 :
4335 0 : info!("loading tenant configuration from {config_path}");
4336 :
4337 : // load and parse file
4338 0 : let config = fs::read_to_string(&config_path).map_err(|e| {
4339 0 : match e.kind() {
4340 : std::io::ErrorKind::NotFound => {
4341 : // The config should almost always exist for a tenant directory:
4342 : // - When attaching a tenant, the config is the first thing we write
4343 : // - When detaching a tenant, we atomically move the directory to a tmp location
4344 : // before deleting contents.
4345 : //
4346 : // The very rare edge case that can result in a missing config is if we crash during attach
4347 : // between creating directory and writing config. Callers should handle that as if the
4348 : // directory didn't exist.
4349 :
4350 0 : LoadConfigError::NotFound(config_path)
4351 : }
4352 : _ => {
4353 : // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
4354 : // that we cannot cleanly recover
4355 0 : crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
4356 : }
4357 : }
4358 0 : })?;
4359 :
4360 0 : Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
4361 0 : }
4362 :
4363 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
4364 : pub(super) async fn persist_tenant_config(
4365 : conf: &'static PageServerConf,
4366 : tenant_shard_id: &TenantShardId,
4367 : location_conf: &LocationConf,
4368 : ) -> std::io::Result<()> {
4369 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
4370 :
4371 : Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
4372 : }
4373 :
4374 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
4375 : pub(super) async fn persist_tenant_config_at(
4376 : tenant_shard_id: &TenantShardId,
4377 : config_path: &Utf8Path,
4378 : location_conf: &LocationConf,
4379 : ) -> std::io::Result<()> {
4380 : debug!("persisting tenantconf to {config_path}");
4381 :
4382 : let mut conf_content = r#"# This file contains a specific per-tenant's config.
4383 : # It is read in case of pageserver restart.
4384 : "#
4385 : .to_string();
4386 :
4387 0 : fail::fail_point!("tenant-config-before-write", |_| {
4388 0 : Err(std::io::Error::other("tenant-config-before-write"))
4389 0 : });
4390 :
4391 : // Convert the config to a toml file.
4392 : conf_content +=
4393 : &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
4394 :
4395 : let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
4396 :
4397 : let conf_content = conf_content.into_bytes();
4398 : VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
4399 : }
4400 :
4401 : //
4402 : // How garbage collection works:
4403 : //
4404 : // +--bar------------->
4405 : // /
4406 : // +----+-----foo---------------->
4407 : // /
4408 : // ----main--+-------------------------->
4409 : // \
4410 : // +-----baz-------->
4411 : //
4412 : //
4413 : // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
4414 : // `gc_infos` are being refreshed
4415 : // 2. Scan collected timelines, and on each timeline, make note of the
4416 : // all the points where other timelines have been branched off.
4417 : // We will refrain from removing page versions at those LSNs.
4418 : // 3. For each timeline, scan all layer files on the timeline.
4419 : // Remove all files for which a newer file exists and which
4420 : // don't cover any branch point LSNs.
4421 : //
4422 : // TODO:
4423 : // - if a relation has a non-incremental persistent layer on a child branch, then we
4424 : // don't need to keep that in the parent anymore. But currently
4425 : // we do.
4426 8 : async fn gc_iteration_internal(
4427 8 : &self,
4428 8 : target_timeline_id: Option<TimelineId>,
4429 8 : horizon: u64,
4430 8 : pitr: Duration,
4431 8 : cancel: &CancellationToken,
4432 8 : ctx: &RequestContext,
4433 8 : ) -> Result<GcResult, GcError> {
4434 8 : let mut totals: GcResult = Default::default();
4435 8 : let now = Instant::now();
4436 :
4437 8 : let gc_timelines = self
4438 8 : .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
4439 8 : .await?;
4440 :
4441 8 : failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
4442 :
4443 : // If there is nothing to GC, we don't want any messages in the INFO log.
4444 8 : if !gc_timelines.is_empty() {
4445 8 : info!("{} timelines need GC", gc_timelines.len());
4446 : } else {
4447 0 : debug!("{} timelines need GC", gc_timelines.len());
4448 : }
4449 :
4450 : // Perform GC for each timeline.
4451 : //
4452 : // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
4453 : // branch creation task, which requires the GC lock. A GC iteration can run concurrently
4454 : // with branch creation.
4455 : //
4456 : // See comments in [`Tenant::branch_timeline`] for more information about why branch
4457 : // creation task can run concurrently with timeline's GC iteration.
4458 16 : for timeline in gc_timelines {
4459 8 : if cancel.is_cancelled() {
4460 : // We were requested to shut down. Stop and return with the progress we
4461 : // made.
4462 0 : break;
4463 8 : }
4464 8 : let result = match timeline.gc().await {
4465 : Err(GcError::TimelineCancelled) => {
4466 0 : if target_timeline_id.is_some() {
4467 : // If we were targetting this specific timeline, surface cancellation to caller
4468 0 : return Err(GcError::TimelineCancelled);
4469 : } else {
4470 : // A timeline may be shutting down independently of the tenant's lifecycle: we should
4471 : // skip past this and proceed to try GC on other timelines.
4472 0 : continue;
4473 : }
4474 : }
4475 8 : r => r?,
4476 : };
4477 8 : totals += result;
4478 : }
4479 :
4480 8 : totals.elapsed = now.elapsed();
4481 8 : Ok(totals)
4482 8 : }
4483 :
4484 : /// Refreshes the Timeline::gc_info for all timelines, returning the
4485 : /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
4486 : /// [`Tenant::get_gc_horizon`].
4487 : ///
4488 : /// This is usually executed as part of periodic gc, but can now be triggered more often.
4489 0 : pub(crate) async fn refresh_gc_info(
4490 0 : &self,
4491 0 : cancel: &CancellationToken,
4492 0 : ctx: &RequestContext,
4493 0 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
4494 0 : // since this method can now be called at different rates than the configured gc loop, it
4495 0 : // might be that these configuration values get applied faster than what it was previously,
4496 0 : // since these were only read from the gc task.
4497 0 : let horizon = self.get_gc_horizon();
4498 0 : let pitr = self.get_pitr_interval();
4499 0 :
4500 0 : // refresh all timelines
4501 0 : let target_timeline_id = None;
4502 0 :
4503 0 : self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
4504 0 : .await
4505 0 : }
4506 :
4507 : /// Populate all Timelines' `GcInfo` with information about their children. We do not set the
4508 : /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
4509 : ///
4510 : /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
4511 0 : fn initialize_gc_info(
4512 0 : &self,
4513 0 : timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
4514 0 : timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
4515 0 : restrict_to_timeline: Option<TimelineId>,
4516 0 : ) {
4517 0 : if restrict_to_timeline.is_none() {
4518 : // This function must be called before activation: after activation timeline create/delete operations
4519 : // might happen, and this function is not safe to run concurrently with those.
4520 0 : assert!(!self.is_active());
4521 0 : }
4522 :
4523 : // Scan all timelines. For each timeline, remember the timeline ID and
4524 : // the branch point where it was created.
4525 0 : let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
4526 0 : BTreeMap::new();
4527 0 : timelines.iter().for_each(|(timeline_id, timeline_entry)| {
4528 0 : if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
4529 0 : let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
4530 0 : ancestor_children.push((
4531 0 : timeline_entry.get_ancestor_lsn(),
4532 0 : *timeline_id,
4533 0 : MaybeOffloaded::No,
4534 0 : ));
4535 0 : }
4536 0 : });
4537 0 : timelines_offloaded
4538 0 : .iter()
4539 0 : .for_each(|(timeline_id, timeline_entry)| {
4540 0 : let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
4541 0 : return;
4542 : };
4543 0 : let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
4544 0 : return;
4545 : };
4546 0 : let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
4547 0 : ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
4548 0 : });
4549 0 :
4550 0 : // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
4551 0 : let horizon = self.get_gc_horizon();
4552 :
4553 : // Populate each timeline's GcInfo with information about its child branches
4554 0 : let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
4555 0 : itertools::Either::Left(timelines.get(&timeline_id).into_iter())
4556 : } else {
4557 0 : itertools::Either::Right(timelines.values())
4558 : };
4559 0 : for timeline in timelines_to_write {
4560 0 : let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
4561 0 : .remove(&timeline.timeline_id)
4562 0 : .unwrap_or_default();
4563 0 :
4564 0 : branchpoints.sort_by_key(|b| b.0);
4565 0 :
4566 0 : let mut target = timeline.gc_info.write().unwrap();
4567 0 :
4568 0 : target.retain_lsns = branchpoints;
4569 0 :
4570 0 : let space_cutoff = timeline
4571 0 : .get_last_record_lsn()
4572 0 : .checked_sub(horizon)
4573 0 : .unwrap_or(Lsn(0));
4574 0 :
4575 0 : target.cutoffs = GcCutoffs {
4576 0 : space: space_cutoff,
4577 0 : time: Lsn::INVALID,
4578 0 : };
4579 0 : }
4580 0 : }
4581 :
4582 8 : async fn refresh_gc_info_internal(
4583 8 : &self,
4584 8 : target_timeline_id: Option<TimelineId>,
4585 8 : horizon: u64,
4586 8 : pitr: Duration,
4587 8 : cancel: &CancellationToken,
4588 8 : ctx: &RequestContext,
4589 8 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
4590 8 : // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
4591 8 : // currently visible timelines.
4592 8 : let timelines = self
4593 8 : .timelines
4594 8 : .lock()
4595 8 : .unwrap()
4596 8 : .values()
4597 8 : .filter(|tl| match target_timeline_id.as_ref() {
4598 8 : Some(target) => &tl.timeline_id == target,
4599 0 : None => true,
4600 8 : })
4601 8 : .cloned()
4602 8 : .collect::<Vec<_>>();
4603 8 :
4604 8 : if target_timeline_id.is_some() && timelines.is_empty() {
4605 : // We were to act on a particular timeline and it wasn't found
4606 0 : return Err(GcError::TimelineNotFound);
4607 8 : }
4608 8 :
4609 8 : let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
4610 8 : HashMap::with_capacity(timelines.len());
4611 8 :
4612 8 : // Ensures all timelines use the same start time when computing the time cutoff.
4613 8 : let now_ts_for_pitr_calc = SystemTime::now();
4614 8 : for timeline in timelines.iter() {
4615 8 : let ctx = &ctx.with_scope_timeline(timeline);
4616 8 : let cutoff = timeline
4617 8 : .get_last_record_lsn()
4618 8 : .checked_sub(horizon)
4619 8 : .unwrap_or(Lsn(0));
4620 :
4621 8 : let cutoffs = timeline
4622 8 : .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
4623 8 : .await?;
4624 8 : let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
4625 8 : assert!(old.is_none());
4626 : }
4627 :
4628 8 : if !self.is_active() || self.cancel.is_cancelled() {
4629 0 : return Err(GcError::TenantCancelled);
4630 8 : }
4631 :
4632 : // grab mutex to prevent new timelines from being created here; avoid doing long operations
4633 : // because that will stall branch creation.
4634 8 : let gc_cs = self.gc_cs.lock().await;
4635 :
4636 : // Ok, we now know all the branch points.
4637 : // Update the GC information for each timeline.
4638 8 : let mut gc_timelines = Vec::with_capacity(timelines.len());
4639 16 : for timeline in timelines {
4640 : // We filtered the timeline list above
4641 8 : if let Some(target_timeline_id) = target_timeline_id {
4642 8 : assert_eq!(target_timeline_id, timeline.timeline_id);
4643 0 : }
4644 :
4645 : {
4646 8 : let mut target = timeline.gc_info.write().unwrap();
4647 8 :
4648 8 : // Cull any expired leases
4649 8 : let now = SystemTime::now();
4650 12 : target.leases.retain(|_, lease| !lease.is_expired(&now));
4651 8 :
4652 8 : timeline
4653 8 : .metrics
4654 8 : .valid_lsn_lease_count_gauge
4655 8 : .set(target.leases.len() as u64);
4656 :
4657 : // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
4658 8 : if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
4659 0 : if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
4660 0 : target.within_ancestor_pitr =
4661 0 : timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
4662 0 : }
4663 8 : }
4664 :
4665 : // Update metrics that depend on GC state
4666 8 : timeline
4667 8 : .metrics
4668 8 : .archival_size
4669 8 : .set(if target.within_ancestor_pitr {
4670 0 : timeline.metrics.current_logical_size_gauge.get()
4671 : } else {
4672 8 : 0
4673 : });
4674 8 : timeline.metrics.pitr_history_size.set(
4675 8 : timeline
4676 8 : .get_last_record_lsn()
4677 8 : .checked_sub(target.cutoffs.time)
4678 8 : .unwrap_or(Lsn(0))
4679 8 : .0,
4680 8 : );
4681 :
4682 : // Apply the cutoffs we found to the Timeline's GcInfo. Why might we _not_ have cutoffs for a timeline?
4683 : // - this timeline was created while we were finding cutoffs
4684 : // - lsn for timestamp search fails for this timeline repeatedly
4685 8 : if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
4686 8 : let original_cutoffs = target.cutoffs.clone();
4687 8 : // GC cutoffs should never go back
4688 8 : target.cutoffs = GcCutoffs {
4689 8 : space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
4690 8 : time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
4691 8 : }
4692 0 : }
4693 : }
4694 :
4695 8 : gc_timelines.push(timeline);
4696 : }
4697 8 : drop(gc_cs);
4698 8 : Ok(gc_timelines)
4699 8 : }
4700 :
4701 : /// A substitute for `branch_timeline` for use in unit tests.
4702 : /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
4703 : /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
4704 : /// timeline background tasks are launched, except the flush loop.
4705 : #[cfg(test)]
4706 464 : async fn branch_timeline_test(
4707 464 : self: &Arc<Self>,
4708 464 : src_timeline: &Arc<Timeline>,
4709 464 : dst_id: TimelineId,
4710 464 : ancestor_lsn: Option<Lsn>,
4711 464 : ctx: &RequestContext,
4712 464 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
4713 464 : let tl = self
4714 464 : .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
4715 464 : .await?
4716 456 : .into_timeline_for_test();
4717 456 : tl.set_state(TimelineState::Active);
4718 456 : Ok(tl)
4719 464 : }
4720 :
4721 : /// Helper for unit tests to branch a timeline with some pre-loaded states.
4722 : #[cfg(test)]
4723 : #[allow(clippy::too_many_arguments)]
4724 12 : pub async fn branch_timeline_test_with_layers(
4725 12 : self: &Arc<Self>,
4726 12 : src_timeline: &Arc<Timeline>,
4727 12 : dst_id: TimelineId,
4728 12 : ancestor_lsn: Option<Lsn>,
4729 12 : ctx: &RequestContext,
4730 12 : delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
4731 12 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
4732 12 : end_lsn: Lsn,
4733 12 : ) -> anyhow::Result<Arc<Timeline>> {
4734 : use checks::check_valid_layermap;
4735 : use itertools::Itertools;
4736 :
4737 12 : let tline = self
4738 12 : .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
4739 12 : .await?;
4740 12 : let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
4741 12 : ancestor_lsn
4742 : } else {
4743 0 : tline.get_last_record_lsn()
4744 : };
4745 12 : assert!(end_lsn >= ancestor_lsn);
4746 12 : tline.force_advance_lsn(end_lsn);
4747 24 : for deltas in delta_layer_desc {
4748 12 : tline
4749 12 : .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
4750 12 : .await?;
4751 : }
4752 20 : for (lsn, images) in image_layer_desc {
4753 8 : tline
4754 8 : .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
4755 8 : .await?;
4756 : }
4757 12 : let layer_names = tline
4758 12 : .layers
4759 12 : .read()
4760 12 : .await
4761 12 : .layer_map()
4762 12 : .unwrap()
4763 12 : .iter_historic_layers()
4764 20 : .map(|layer| layer.layer_name())
4765 12 : .collect_vec();
4766 12 : if let Some(err) = check_valid_layermap(&layer_names) {
4767 0 : bail!("invalid layermap: {err}");
4768 12 : }
4769 12 : Ok(tline)
4770 12 : }
4771 :
4772 : /// Branch an existing timeline.
4773 0 : async fn branch_timeline(
4774 0 : self: &Arc<Self>,
4775 0 : src_timeline: &Arc<Timeline>,
4776 0 : dst_id: TimelineId,
4777 0 : start_lsn: Option<Lsn>,
4778 0 : ctx: &RequestContext,
4779 0 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
4780 0 : self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
4781 0 : .await
4782 0 : }
4783 :
4784 464 : async fn branch_timeline_impl(
4785 464 : self: &Arc<Self>,
4786 464 : src_timeline: &Arc<Timeline>,
4787 464 : dst_id: TimelineId,
4788 464 : start_lsn: Option<Lsn>,
4789 464 : ctx: &RequestContext,
4790 464 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
4791 464 : let src_id = src_timeline.timeline_id;
4792 :
4793 : // We will validate our ancestor LSN in this function. Acquire the GC lock so that
4794 : // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
4795 : // valid while we are creating the branch.
4796 464 : let _gc_cs = self.gc_cs.lock().await;
4797 :
4798 : // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
4799 464 : let start_lsn = start_lsn.unwrap_or_else(|| {
4800 4 : let lsn = src_timeline.get_last_record_lsn();
4801 4 : info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
4802 4 : lsn
4803 464 : });
4804 :
4805 : // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
4806 464 : let timeline_create_guard = match self
4807 464 : .start_creating_timeline(
4808 464 : dst_id,
4809 464 : CreateTimelineIdempotency::Branch {
4810 464 : ancestor_timeline_id: src_timeline.timeline_id,
4811 464 : ancestor_start_lsn: start_lsn,
4812 464 : },
4813 464 : )
4814 464 : .await?
4815 : {
4816 464 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
4817 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
4818 0 : return Ok(CreateTimelineResult::Idempotent(timeline));
4819 : }
4820 : };
4821 :
4822 : // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
4823 : // horizon on the source timeline
4824 : //
4825 : // We check it against both the planned GC cutoff stored in 'gc_info',
4826 : // and the 'latest_gc_cutoff' of the last GC that was performed. The
4827 : // planned GC cutoff in 'gc_info' is normally larger than
4828 : // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
4829 : // changed the GC settings for the tenant to make the PITR window
4830 : // larger, but some of the data was already removed by an earlier GC
4831 : // iteration.
4832 :
4833 : // check against last actual 'latest_gc_cutoff' first
4834 464 : let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
4835 464 : {
4836 464 : let gc_info = src_timeline.gc_info.read().unwrap();
4837 464 : let planned_cutoff = gc_info.min_cutoff();
4838 464 : if gc_info.lsn_covered_by_lease(start_lsn) {
4839 0 : tracing::info!(
4840 0 : "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
4841 0 : *applied_gc_cutoff_lsn
4842 : );
4843 : } else {
4844 464 : src_timeline
4845 464 : .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
4846 464 : .context(format!(
4847 464 : "invalid branch start lsn: less than latest GC cutoff {}",
4848 464 : *applied_gc_cutoff_lsn,
4849 464 : ))
4850 464 : .map_err(CreateTimelineError::AncestorLsn)?;
4851 :
4852 : // and then the planned GC cutoff
4853 456 : if start_lsn < planned_cutoff {
4854 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
4855 0 : "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
4856 0 : )));
4857 456 : }
4858 : }
4859 : }
4860 :
4861 : //
4862 : // The branch point is valid, and we are still holding the 'gc_cs' lock
4863 : // so that GC cannot advance the GC cutoff until we are finished.
4864 : // Proceed with the branch creation.
4865 : //
4866 :
4867 : // Determine prev-LSN for the new timeline. We can only determine it if
4868 : // the timeline was branched at the current end of the source timeline.
4869 : let RecordLsn {
4870 456 : last: src_last,
4871 456 : prev: src_prev,
4872 456 : } = src_timeline.get_last_record_rlsn();
4873 456 : let dst_prev = if src_last == start_lsn {
4874 432 : Some(src_prev)
4875 : } else {
4876 24 : None
4877 : };
4878 :
4879 : // Create the metadata file, noting the ancestor of the new timeline.
4880 : // There is initially no data in it, but all the read-calls know to look
4881 : // into the ancestor.
4882 456 : let metadata = TimelineMetadata::new(
4883 456 : start_lsn,
4884 456 : dst_prev,
4885 456 : Some(src_id),
4886 456 : start_lsn,
4887 456 : *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
4888 456 : src_timeline.initdb_lsn,
4889 456 : src_timeline.pg_version,
4890 456 : );
4891 :
4892 456 : let (uninitialized_timeline, _timeline_ctx) = self
4893 456 : .prepare_new_timeline(
4894 456 : dst_id,
4895 456 : &metadata,
4896 456 : timeline_create_guard,
4897 456 : start_lsn + 1,
4898 456 : Some(Arc::clone(src_timeline)),
4899 456 : Some(src_timeline.get_rel_size_v2_status()),
4900 456 : ctx,
4901 456 : )
4902 456 : .await?;
4903 :
4904 456 : let new_timeline = uninitialized_timeline.finish_creation().await?;
4905 :
4906 : // Root timeline gets its layers during creation and uploads them along with the metadata.
4907 : // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
4908 : // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
4909 : // could get incorrect information and remove more layers, than needed.
4910 : // See also https://github.com/neondatabase/neon/issues/3865
4911 456 : new_timeline
4912 456 : .remote_client
4913 456 : .schedule_index_upload_for_full_metadata_update(&metadata)
4914 456 : .context("branch initial metadata upload")?;
4915 :
4916 : // Callers are responsible to wait for uploads to complete and for activating the timeline.
4917 :
4918 456 : Ok(CreateTimelineResult::Created(new_timeline))
4919 464 : }
4920 :
4921 : /// For unit tests, make this visible so that other modules can directly create timelines
4922 : #[cfg(test)]
4923 : #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
4924 : pub(crate) async fn bootstrap_timeline_test(
4925 : self: &Arc<Self>,
4926 : timeline_id: TimelineId,
4927 : pg_version: u32,
4928 : load_existing_initdb: Option<TimelineId>,
4929 : ctx: &RequestContext,
4930 : ) -> anyhow::Result<Arc<Timeline>> {
4931 : self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
4932 : .await
4933 : .map_err(anyhow::Error::new)
4934 4 : .map(|r| r.into_timeline_for_test())
4935 : }
4936 :
4937 : /// Get exclusive access to the timeline ID for creation.
4938 : ///
4939 : /// Timeline-creating code paths must use this function before making changes
4940 : /// to in-memory or persistent state.
4941 : ///
4942 : /// The `state` parameter is a description of the timeline creation operation
4943 : /// we intend to perform.
4944 : /// If the timeline was already created in the meantime, we check whether this
4945 : /// request conflicts or is idempotent , based on `state`.
4946 904 : async fn start_creating_timeline(
4947 904 : self: &Arc<Self>,
4948 904 : new_timeline_id: TimelineId,
4949 904 : idempotency: CreateTimelineIdempotency,
4950 904 : ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
4951 904 : let allow_offloaded = false;
4952 904 : match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
4953 900 : Ok(create_guard) => {
4954 900 : pausable_failpoint!("timeline-creation-after-uninit");
4955 900 : Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
4956 : }
4957 0 : Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
4958 : Err(TimelineExclusionError::AlreadyCreating) => {
4959 : // Creation is in progress, we cannot create it again, and we cannot
4960 : // check if this request matches the existing one, so caller must try
4961 : // again later.
4962 0 : Err(CreateTimelineError::AlreadyCreating)
4963 : }
4964 0 : Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
4965 : Err(TimelineExclusionError::AlreadyExists {
4966 0 : existing: TimelineOrOffloaded::Offloaded(_existing),
4967 0 : ..
4968 0 : }) => {
4969 0 : info!("timeline already exists but is offloaded");
4970 0 : Err(CreateTimelineError::Conflict)
4971 : }
4972 : Err(TimelineExclusionError::AlreadyExists {
4973 4 : existing: TimelineOrOffloaded::Timeline(existing),
4974 4 : arg,
4975 4 : }) => {
4976 4 : {
4977 4 : let existing = &existing.create_idempotency;
4978 4 : let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
4979 4 : debug!("timeline already exists");
4980 :
4981 4 : match (existing, &arg) {
4982 : // FailWithConflict => no idempotency check
4983 : (CreateTimelineIdempotency::FailWithConflict, _)
4984 : | (_, CreateTimelineIdempotency::FailWithConflict) => {
4985 4 : warn!("timeline already exists, failing request");
4986 4 : return Err(CreateTimelineError::Conflict);
4987 : }
4988 : // Idempotent <=> CreateTimelineIdempotency is identical
4989 0 : (x, y) if x == y => {
4990 0 : info!(
4991 0 : "timeline already exists and idempotency matches, succeeding request"
4992 : );
4993 : // fallthrough
4994 : }
4995 : (_, _) => {
4996 0 : warn!("idempotency conflict, failing request");
4997 0 : return Err(CreateTimelineError::Conflict);
4998 : }
4999 : }
5000 : }
5001 :
5002 0 : Ok(StartCreatingTimelineResult::Idempotent(existing))
5003 : }
5004 : }
5005 904 : }
5006 :
5007 0 : async fn upload_initdb(
5008 0 : &self,
5009 0 : timelines_path: &Utf8PathBuf,
5010 0 : pgdata_path: &Utf8PathBuf,
5011 0 : timeline_id: &TimelineId,
5012 0 : ) -> anyhow::Result<()> {
5013 0 : let temp_path = timelines_path.join(format!(
5014 0 : "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
5015 0 : ));
5016 0 :
5017 0 : scopeguard::defer! {
5018 0 : if let Err(e) = fs::remove_file(&temp_path) {
5019 0 : error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
5020 0 : }
5021 0 : }
5022 :
5023 0 : let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
5024 : const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
5025 0 : if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
5026 0 : warn!(
5027 0 : "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
5028 : );
5029 0 : }
5030 :
5031 0 : pausable_failpoint!("before-initdb-upload");
5032 :
5033 0 : backoff::retry(
5034 0 : || async {
5035 0 : self::remote_timeline_client::upload_initdb_dir(
5036 0 : &self.remote_storage,
5037 0 : &self.tenant_shard_id.tenant_id,
5038 0 : timeline_id,
5039 0 : pgdata_zstd.try_clone().await?,
5040 0 : tar_zst_size,
5041 0 : &self.cancel,
5042 0 : )
5043 0 : .await
5044 0 : },
5045 0 : |_| false,
5046 0 : 3,
5047 0 : u32::MAX,
5048 0 : "persist_initdb_tar_zst",
5049 0 : &self.cancel,
5050 0 : )
5051 0 : .await
5052 0 : .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
5053 0 : .and_then(|x| x)
5054 0 : }
5055 :
5056 : /// - run initdb to init temporary instance and get bootstrap data
5057 : /// - after initialization completes, tar up the temp dir and upload it to S3.
5058 4 : async fn bootstrap_timeline(
5059 4 : self: &Arc<Self>,
5060 4 : timeline_id: TimelineId,
5061 4 : pg_version: u32,
5062 4 : load_existing_initdb: Option<TimelineId>,
5063 4 : ctx: &RequestContext,
5064 4 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
5065 4 : let timeline_create_guard = match self
5066 4 : .start_creating_timeline(
5067 4 : timeline_id,
5068 4 : CreateTimelineIdempotency::Bootstrap { pg_version },
5069 4 : )
5070 4 : .await?
5071 : {
5072 4 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
5073 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
5074 0 : return Ok(CreateTimelineResult::Idempotent(timeline));
5075 : }
5076 : };
5077 :
5078 : // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
5079 : // temporary directory for basebackup files for the given timeline.
5080 :
5081 4 : let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
5082 4 : let pgdata_path = path_with_suffix_extension(
5083 4 : timelines_path.join(format!("basebackup-{timeline_id}")),
5084 4 : TEMP_FILE_SUFFIX,
5085 4 : );
5086 4 :
5087 4 : // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
5088 4 : // we won't race with other creations or existent timelines with the same path.
5089 4 : if pgdata_path.exists() {
5090 0 : fs::remove_dir_all(&pgdata_path).with_context(|| {
5091 0 : format!("Failed to remove already existing initdb directory: {pgdata_path}")
5092 0 : })?;
5093 4 : }
5094 :
5095 : // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
5096 4 : let pgdata_path_deferred = pgdata_path.clone();
5097 4 : scopeguard::defer! {
5098 4 : if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred) {
5099 4 : // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
5100 4 : error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
5101 4 : }
5102 4 : }
5103 4 : if let Some(existing_initdb_timeline_id) = load_existing_initdb {
5104 4 : if existing_initdb_timeline_id != timeline_id {
5105 0 : let source_path = &remote_initdb_archive_path(
5106 0 : &self.tenant_shard_id.tenant_id,
5107 0 : &existing_initdb_timeline_id,
5108 0 : );
5109 0 : let dest_path =
5110 0 : &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
5111 0 :
5112 0 : // if this fails, it will get retried by retried control plane requests
5113 0 : self.remote_storage
5114 0 : .copy_object(source_path, dest_path, &self.cancel)
5115 0 : .await
5116 0 : .context("copy initdb tar")?;
5117 4 : }
5118 4 : let (initdb_tar_zst_path, initdb_tar_zst) =
5119 4 : self::remote_timeline_client::download_initdb_tar_zst(
5120 4 : self.conf,
5121 4 : &self.remote_storage,
5122 4 : &self.tenant_shard_id,
5123 4 : &existing_initdb_timeline_id,
5124 4 : &self.cancel,
5125 4 : )
5126 4 : .await
5127 4 : .context("download initdb tar")?;
5128 :
5129 4 : scopeguard::defer! {
5130 4 : if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
5131 4 : error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
5132 4 : }
5133 4 : }
5134 4 :
5135 4 : let buf_read =
5136 4 : BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
5137 4 : extract_zst_tarball(&pgdata_path, buf_read)
5138 4 : .await
5139 4 : .context("extract initdb tar")?;
5140 : } else {
5141 : // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
5142 0 : run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
5143 0 : .await
5144 0 : .context("run initdb")?;
5145 :
5146 : // Upload the created data dir to S3
5147 0 : if self.tenant_shard_id().is_shard_zero() {
5148 0 : self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
5149 0 : .await?;
5150 0 : }
5151 : }
5152 4 : let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
5153 4 :
5154 4 : // Import the contents of the data directory at the initial checkpoint
5155 4 : // LSN, and any WAL after that.
5156 4 : // Initdb lsn will be equal to last_record_lsn which will be set after import.
5157 4 : // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
5158 4 : let new_metadata = TimelineMetadata::new(
5159 4 : Lsn(0),
5160 4 : None,
5161 4 : None,
5162 4 : Lsn(0),
5163 4 : pgdata_lsn,
5164 4 : pgdata_lsn,
5165 4 : pg_version,
5166 4 : );
5167 4 : let (mut raw_timeline, timeline_ctx) = self
5168 4 : .prepare_new_timeline(
5169 4 : timeline_id,
5170 4 : &new_metadata,
5171 4 : timeline_create_guard,
5172 4 : pgdata_lsn,
5173 4 : None,
5174 4 : None,
5175 4 : ctx,
5176 4 : )
5177 4 : .await?;
5178 :
5179 4 : let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
5180 4 : raw_timeline
5181 4 : .write(|unfinished_timeline| async move {
5182 4 : import_datadir::import_timeline_from_postgres_datadir(
5183 4 : &unfinished_timeline,
5184 4 : &pgdata_path,
5185 4 : pgdata_lsn,
5186 4 : &timeline_ctx,
5187 4 : )
5188 4 : .await
5189 4 : .with_context(|| {
5190 0 : format!(
5191 0 : "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
5192 0 : )
5193 4 : })?;
5194 :
5195 4 : fail::fail_point!("before-checkpoint-new-timeline", |_| {
5196 0 : Err(CreateTimelineError::Other(anyhow::anyhow!(
5197 0 : "failpoint before-checkpoint-new-timeline"
5198 0 : )))
5199 4 : });
5200 :
5201 4 : Ok(())
5202 8 : })
5203 4 : .await?;
5204 :
5205 : // All done!
5206 4 : let timeline = raw_timeline.finish_creation().await?;
5207 :
5208 : // Callers are responsible to wait for uploads to complete and for activating the timeline.
5209 :
5210 4 : Ok(CreateTimelineResult::Created(timeline))
5211 4 : }
5212 :
5213 892 : fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
5214 892 : RemoteTimelineClient::new(
5215 892 : self.remote_storage.clone(),
5216 892 : self.deletion_queue_client.clone(),
5217 892 : self.conf,
5218 892 : self.tenant_shard_id,
5219 892 : timeline_id,
5220 892 : self.generation,
5221 892 : &self.tenant_conf.load().location,
5222 892 : )
5223 892 : }
5224 :
5225 : /// Builds required resources for a new timeline.
5226 892 : fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
5227 892 : let remote_client = self.build_timeline_remote_client(timeline_id);
5228 892 : self.get_timeline_resources_for(remote_client)
5229 892 : }
5230 :
5231 : /// Builds timeline resources for the given remote client.
5232 904 : fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
5233 904 : TimelineResources {
5234 904 : remote_client,
5235 904 : pagestream_throttle: self.pagestream_throttle.clone(),
5236 904 : pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
5237 904 : l0_compaction_trigger: self.l0_compaction_trigger.clone(),
5238 904 : l0_flush_global_state: self.l0_flush_global_state.clone(),
5239 904 : }
5240 904 : }
5241 :
5242 : /// Creates intermediate timeline structure and its files.
5243 : ///
5244 : /// An empty layer map is initialized, and new data and WAL can be imported starting
5245 : /// at 'disk_consistent_lsn'. After any initial data has been imported, call
5246 : /// `finish_creation` to insert the Timeline into the timelines map.
5247 : #[allow(clippy::too_many_arguments)]
5248 892 : async fn prepare_new_timeline<'a>(
5249 892 : &'a self,
5250 892 : new_timeline_id: TimelineId,
5251 892 : new_metadata: &TimelineMetadata,
5252 892 : create_guard: TimelineCreateGuard,
5253 892 : start_lsn: Lsn,
5254 892 : ancestor: Option<Arc<Timeline>>,
5255 892 : rel_size_v2_status: Option<RelSizeMigration>,
5256 892 : ctx: &RequestContext,
5257 892 : ) -> anyhow::Result<(UninitializedTimeline<'a>, RequestContext)> {
5258 892 : let tenant_shard_id = self.tenant_shard_id;
5259 892 :
5260 892 : let resources = self.build_timeline_resources(new_timeline_id);
5261 892 : resources
5262 892 : .remote_client
5263 892 : .init_upload_queue_for_empty_remote(new_metadata, rel_size_v2_status.clone())?;
5264 :
5265 892 : let (timeline_struct, timeline_ctx) = self
5266 892 : .create_timeline_struct(
5267 892 : new_timeline_id,
5268 892 : new_metadata,
5269 892 : None,
5270 892 : ancestor,
5271 892 : resources,
5272 892 : CreateTimelineCause::Load,
5273 892 : create_guard.idempotency.clone(),
5274 892 : None,
5275 892 : rel_size_v2_status,
5276 892 : ctx,
5277 892 : )
5278 892 : .context("Failed to create timeline data structure")?;
5279 :
5280 892 : timeline_struct.init_empty_layer_map(start_lsn);
5281 :
5282 892 : if let Err(e) = self
5283 892 : .create_timeline_files(&create_guard.timeline_path)
5284 892 : .await
5285 : {
5286 0 : error!(
5287 0 : "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
5288 : );
5289 0 : cleanup_timeline_directory(create_guard);
5290 0 : return Err(e);
5291 892 : }
5292 892 :
5293 892 : debug!(
5294 0 : "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
5295 : );
5296 :
5297 892 : Ok((
5298 892 : UninitializedTimeline::new(
5299 892 : self,
5300 892 : new_timeline_id,
5301 892 : Some((timeline_struct, create_guard)),
5302 892 : ),
5303 892 : timeline_ctx,
5304 892 : ))
5305 892 : }
5306 :
5307 892 : async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
5308 892 : crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
5309 :
5310 892 : fail::fail_point!("after-timeline-dir-creation", |_| {
5311 0 : anyhow::bail!("failpoint after-timeline-dir-creation");
5312 892 : });
5313 :
5314 892 : Ok(())
5315 892 : }
5316 :
5317 : /// Get a guard that provides exclusive access to the timeline directory, preventing
5318 : /// concurrent attempts to create the same timeline.
5319 : ///
5320 : /// The `allow_offloaded` parameter controls whether to tolerate the existence of
5321 : /// offloaded timelines or not.
5322 904 : fn create_timeline_create_guard(
5323 904 : self: &Arc<Self>,
5324 904 : timeline_id: TimelineId,
5325 904 : idempotency: CreateTimelineIdempotency,
5326 904 : allow_offloaded: bool,
5327 904 : ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
5328 904 : let tenant_shard_id = self.tenant_shard_id;
5329 904 :
5330 904 : let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
5331 :
5332 904 : let create_guard = TimelineCreateGuard::new(
5333 904 : self,
5334 904 : timeline_id,
5335 904 : timeline_path.clone(),
5336 904 : idempotency,
5337 904 : allow_offloaded,
5338 904 : )?;
5339 :
5340 : // At this stage, we have got exclusive access to in-memory state for this timeline ID
5341 : // for creation.
5342 : // A timeline directory should never exist on disk already:
5343 : // - a previous failed creation would have cleaned up after itself
5344 : // - a pageserver restart would clean up timeline directories that don't have valid remote state
5345 : //
5346 : // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
5347 : // this error may indicate a bug in cleanup on failed creations.
5348 900 : if timeline_path.exists() {
5349 0 : return Err(TimelineExclusionError::Other(anyhow::anyhow!(
5350 0 : "Timeline directory already exists! This is a bug."
5351 0 : )));
5352 900 : }
5353 900 :
5354 900 : Ok(create_guard)
5355 904 : }
5356 :
5357 : /// Gathers inputs from all of the timelines to produce a sizing model input.
5358 : ///
5359 : /// Future is cancellation safe. Only one calculation can be running at once per tenant.
5360 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5361 : pub async fn gather_size_inputs(
5362 : &self,
5363 : // `max_retention_period` overrides the cutoff that is used to calculate the size
5364 : // (only if it is shorter than the real cutoff).
5365 : max_retention_period: Option<u64>,
5366 : cause: LogicalSizeCalculationCause,
5367 : cancel: &CancellationToken,
5368 : ctx: &RequestContext,
5369 : ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
5370 : let logical_sizes_at_once = self
5371 : .conf
5372 : .concurrent_tenant_size_logical_size_queries
5373 : .inner();
5374 :
5375 : // TODO: Having a single mutex block concurrent reads is not great for performance.
5376 : //
5377 : // But the only case where we need to run multiple of these at once is when we
5378 : // request a size for a tenant manually via API, while another background calculation
5379 : // is in progress (which is not a common case).
5380 : //
5381 : // See more for on the issue #2748 condenced out of the initial PR review.
5382 : let mut shared_cache = tokio::select! {
5383 : locked = self.cached_logical_sizes.lock() => locked,
5384 : _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
5385 : _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
5386 : };
5387 :
5388 : size::gather_inputs(
5389 : self,
5390 : logical_sizes_at_once,
5391 : max_retention_period,
5392 : &mut shared_cache,
5393 : cause,
5394 : cancel,
5395 : ctx,
5396 : )
5397 : .await
5398 : }
5399 :
5400 : /// Calculate synthetic tenant size and cache the result.
5401 : /// This is periodically called by background worker.
5402 : /// result is cached in tenant struct
5403 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5404 : pub async fn calculate_synthetic_size(
5405 : &self,
5406 : cause: LogicalSizeCalculationCause,
5407 : cancel: &CancellationToken,
5408 : ctx: &RequestContext,
5409 : ) -> Result<u64, size::CalculateSyntheticSizeError> {
5410 : let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
5411 :
5412 : let size = inputs.calculate();
5413 :
5414 : self.set_cached_synthetic_size(size);
5415 :
5416 : Ok(size)
5417 : }
5418 :
5419 : /// Cache given synthetic size and update the metric value
5420 0 : pub fn set_cached_synthetic_size(&self, size: u64) {
5421 0 : self.cached_synthetic_tenant_size
5422 0 : .store(size, Ordering::Relaxed);
5423 0 :
5424 0 : // Only shard zero should be calculating synthetic sizes
5425 0 : debug_assert!(self.shard_identity.is_shard_zero());
5426 :
5427 0 : TENANT_SYNTHETIC_SIZE_METRIC
5428 0 : .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
5429 0 : .unwrap()
5430 0 : .set(size);
5431 0 : }
5432 :
5433 0 : pub fn cached_synthetic_size(&self) -> u64 {
5434 0 : self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
5435 0 : }
5436 :
5437 : /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
5438 : ///
5439 : /// This function can take a long time: callers should wrap it in a timeout if calling
5440 : /// from an external API handler.
5441 : ///
5442 : /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
5443 : /// still bounded by tenant/timeline shutdown.
5444 : #[tracing::instrument(skip_all)]
5445 : pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
5446 : let timelines = self.timelines.lock().unwrap().clone();
5447 :
5448 0 : async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
5449 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
5450 0 : timeline.freeze_and_flush().await?;
5451 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
5452 0 : timeline.remote_client.wait_completion().await?;
5453 :
5454 0 : Ok(())
5455 0 : }
5456 :
5457 : // We do not use a JoinSet for these tasks, because we don't want them to be
5458 : // aborted when this function's future is cancelled: they should stay alive
5459 : // holding their GateGuard until they complete, to ensure their I/Os complete
5460 : // before Timeline shutdown completes.
5461 : let mut results = FuturesUnordered::new();
5462 :
5463 : for (_timeline_id, timeline) in timelines {
5464 : // Run each timeline's flush in a task holding the timeline's gate: this
5465 : // means that if this function's future is cancelled, the Timeline shutdown
5466 : // will still wait for any I/O in here to complete.
5467 : let Ok(gate) = timeline.gate.enter() else {
5468 : continue;
5469 : };
5470 0 : let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
5471 : results.push(jh);
5472 : }
5473 :
5474 : while let Some(r) = results.next().await {
5475 : if let Err(e) = r {
5476 : if !e.is_cancelled() && !e.is_panic() {
5477 : tracing::error!("unexpected join error: {e:?}");
5478 : }
5479 : }
5480 : }
5481 :
5482 : // The flushes we did above were just writes, but the Tenant might have had
5483 : // pending deletions as well from recent compaction/gc: we want to flush those
5484 : // as well. This requires flushing the global delete queue. This is cheap
5485 : // because it's typically a no-op.
5486 : match self.deletion_queue_client.flush_execute().await {
5487 : Ok(_) => {}
5488 : Err(DeletionQueueError::ShuttingDown) => {}
5489 : }
5490 :
5491 : Ok(())
5492 : }
5493 :
5494 0 : pub(crate) fn get_tenant_conf(&self) -> TenantConfOpt {
5495 0 : self.tenant_conf.load().tenant_conf.clone()
5496 0 : }
5497 :
5498 : /// How much local storage would this tenant like to have? It can cope with
5499 : /// less than this (via eviction and on-demand downloads), but this function enables
5500 : /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
5501 : /// by keeping important things on local disk.
5502 : ///
5503 : /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
5504 : /// than they report here, due to layer eviction. Tenants with many active branches may
5505 : /// actually use more than they report here.
5506 0 : pub(crate) fn local_storage_wanted(&self) -> u64 {
5507 0 : let timelines = self.timelines.lock().unwrap();
5508 0 :
5509 0 : // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum. This
5510 0 : // reflects the observation that on tenants with multiple large branches, typically only one
5511 0 : // of them is used actively enough to occupy space on disk.
5512 0 : timelines
5513 0 : .values()
5514 0 : .map(|t| t.metrics.visible_physical_size_gauge.get())
5515 0 : .max()
5516 0 : .unwrap_or(0)
5517 0 : }
5518 :
5519 : /// Serialize and write the latest TenantManifest to remote storage.
5520 4 : pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
5521 : // Only one manifest write may be done at at time, and the contents of the manifest
5522 : // must be loaded while holding this lock. This makes it safe to call this function
5523 : // from anywhere without worrying about colliding updates.
5524 4 : let mut guard = tokio::select! {
5525 4 : g = self.tenant_manifest_upload.lock() => {
5526 4 : g
5527 : },
5528 4 : _ = self.cancel.cancelled() => {
5529 0 : return Err(TenantManifestError::Cancelled);
5530 : }
5531 : };
5532 :
5533 4 : let manifest = self.build_tenant_manifest();
5534 4 : if Some(&manifest) == (*guard).as_ref() {
5535 : // Optimisation: skip uploads that don't change anything.
5536 0 : return Ok(());
5537 4 : }
5538 4 :
5539 4 : // Remote storage does no retries internally, so wrap it
5540 4 : match backoff::retry(
5541 4 : || async {
5542 4 : upload_tenant_manifest(
5543 4 : &self.remote_storage,
5544 4 : &self.tenant_shard_id,
5545 4 : self.generation,
5546 4 : &manifest,
5547 4 : &self.cancel,
5548 4 : )
5549 4 : .await
5550 8 : },
5551 4 : |_e| self.cancel.is_cancelled(),
5552 4 : FAILED_UPLOAD_WARN_THRESHOLD,
5553 4 : FAILED_REMOTE_OP_RETRIES,
5554 4 : "uploading tenant manifest",
5555 4 : &self.cancel,
5556 4 : )
5557 4 : .await
5558 : {
5559 0 : None => Err(TenantManifestError::Cancelled),
5560 0 : Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
5561 0 : Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
5562 : Some(Ok(_)) => {
5563 : // Store the successfully uploaded manifest, so that future callers can avoid
5564 : // re-uploading the same thing.
5565 4 : *guard = Some(manifest);
5566 4 :
5567 4 : Ok(())
5568 : }
5569 : }
5570 4 : }
5571 : }
5572 :
5573 : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
5574 : /// to get bootstrap data for timeline initialization.
5575 0 : async fn run_initdb(
5576 0 : conf: &'static PageServerConf,
5577 0 : initdb_target_dir: &Utf8Path,
5578 0 : pg_version: u32,
5579 0 : cancel: &CancellationToken,
5580 0 : ) -> Result<(), InitdbError> {
5581 0 : let initdb_bin_path = conf
5582 0 : .pg_bin_dir(pg_version)
5583 0 : .map_err(InitdbError::Other)?
5584 0 : .join("initdb");
5585 0 : let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
5586 0 : info!(
5587 0 : "running {} in {}, libdir: {}",
5588 : initdb_bin_path, initdb_target_dir, initdb_lib_dir,
5589 : );
5590 :
5591 0 : let _permit = {
5592 0 : let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
5593 0 : INIT_DB_SEMAPHORE.acquire().await
5594 : };
5595 :
5596 0 : CONCURRENT_INITDBS.inc();
5597 0 : scopeguard::defer! {
5598 0 : CONCURRENT_INITDBS.dec();
5599 0 : }
5600 0 :
5601 0 : let _timer = INITDB_RUN_TIME.start_timer();
5602 0 : let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
5603 0 : superuser: &conf.superuser,
5604 0 : locale: &conf.locale,
5605 0 : initdb_bin: &initdb_bin_path,
5606 0 : pg_version,
5607 0 : library_search_path: &initdb_lib_dir,
5608 0 : pgdata: initdb_target_dir,
5609 0 : })
5610 0 : .await
5611 0 : .map_err(InitdbError::Inner);
5612 0 :
5613 0 : // This isn't true cancellation support, see above. Still return an error to
5614 0 : // excercise the cancellation code path.
5615 0 : if cancel.is_cancelled() {
5616 0 : return Err(InitdbError::Cancelled);
5617 0 : }
5618 0 :
5619 0 : res
5620 0 : }
5621 :
5622 : /// Dump contents of a layer file to stdout.
5623 0 : pub async fn dump_layerfile_from_path(
5624 0 : path: &Utf8Path,
5625 0 : verbose: bool,
5626 0 : ctx: &RequestContext,
5627 0 : ) -> anyhow::Result<()> {
5628 : use std::os::unix::fs::FileExt;
5629 :
5630 : // All layer files start with a two-byte "magic" value, to identify the kind of
5631 : // file.
5632 0 : let file = File::open(path)?;
5633 0 : let mut header_buf = [0u8; 2];
5634 0 : file.read_exact_at(&mut header_buf, 0)?;
5635 :
5636 0 : match u16::from_be_bytes(header_buf) {
5637 : crate::IMAGE_FILE_MAGIC => {
5638 0 : ImageLayer::new_for_path(path, file)?
5639 0 : .dump(verbose, ctx)
5640 0 : .await?
5641 : }
5642 : crate::DELTA_FILE_MAGIC => {
5643 0 : DeltaLayer::new_for_path(path, file)?
5644 0 : .dump(verbose, ctx)
5645 0 : .await?
5646 : }
5647 0 : magic => bail!("unrecognized magic identifier: {:?}", magic),
5648 : }
5649 :
5650 0 : Ok(())
5651 0 : }
5652 :
5653 : #[cfg(test)]
5654 : pub(crate) mod harness {
5655 : use bytes::{Bytes, BytesMut};
5656 : use hex_literal::hex;
5657 : use once_cell::sync::OnceCell;
5658 : use pageserver_api::key::Key;
5659 : use pageserver_api::models::ShardParameters;
5660 : use pageserver_api::record::NeonWalRecord;
5661 : use pageserver_api::shard::ShardIndex;
5662 : use utils::id::TenantId;
5663 : use utils::logging;
5664 :
5665 : use super::*;
5666 : use crate::deletion_queue::mock::MockDeletionQueue;
5667 : use crate::l0_flush::L0FlushConfig;
5668 : use crate::walredo::apply_neon;
5669 :
5670 : pub const TIMELINE_ID: TimelineId =
5671 : TimelineId::from_array(hex!("11223344556677881122334455667788"));
5672 : pub const NEW_TIMELINE_ID: TimelineId =
5673 : TimelineId::from_array(hex!("AA223344556677881122334455667788"));
5674 :
5675 : /// Convenience function to create a page image with given string as the only content
5676 10057570 : pub fn test_img(s: &str) -> Bytes {
5677 10057570 : let mut buf = BytesMut::new();
5678 10057570 : buf.extend_from_slice(s.as_bytes());
5679 10057570 : buf.resize(64, 0);
5680 10057570 :
5681 10057570 : buf.freeze()
5682 10057570 : }
5683 :
5684 : impl From<TenantConf> for TenantConfOpt {
5685 452 : fn from(tenant_conf: TenantConf) -> Self {
5686 452 : Self {
5687 452 : checkpoint_distance: Some(tenant_conf.checkpoint_distance),
5688 452 : checkpoint_timeout: Some(tenant_conf.checkpoint_timeout),
5689 452 : compaction_target_size: Some(tenant_conf.compaction_target_size),
5690 452 : compaction_period: Some(tenant_conf.compaction_period),
5691 452 : compaction_threshold: Some(tenant_conf.compaction_threshold),
5692 452 : compaction_upper_limit: Some(tenant_conf.compaction_upper_limit),
5693 452 : compaction_algorithm: Some(tenant_conf.compaction_algorithm),
5694 452 : compaction_l0_first: Some(tenant_conf.compaction_l0_first),
5695 452 : compaction_l0_semaphore: Some(tenant_conf.compaction_l0_semaphore),
5696 452 : l0_flush_delay_threshold: tenant_conf.l0_flush_delay_threshold,
5697 452 : l0_flush_stall_threshold: tenant_conf.l0_flush_stall_threshold,
5698 452 : l0_flush_wait_upload: Some(tenant_conf.l0_flush_wait_upload),
5699 452 : gc_horizon: Some(tenant_conf.gc_horizon),
5700 452 : gc_period: Some(tenant_conf.gc_period),
5701 452 : image_creation_threshold: Some(tenant_conf.image_creation_threshold),
5702 452 : pitr_interval: Some(tenant_conf.pitr_interval),
5703 452 : walreceiver_connect_timeout: Some(tenant_conf.walreceiver_connect_timeout),
5704 452 : lagging_wal_timeout: Some(tenant_conf.lagging_wal_timeout),
5705 452 : max_lsn_wal_lag: Some(tenant_conf.max_lsn_wal_lag),
5706 452 : eviction_policy: Some(tenant_conf.eviction_policy),
5707 452 : min_resident_size_override: tenant_conf.min_resident_size_override,
5708 452 : evictions_low_residence_duration_metric_threshold: Some(
5709 452 : tenant_conf.evictions_low_residence_duration_metric_threshold,
5710 452 : ),
5711 452 : heatmap_period: Some(tenant_conf.heatmap_period),
5712 452 : lazy_slru_download: Some(tenant_conf.lazy_slru_download),
5713 452 : timeline_get_throttle: Some(tenant_conf.timeline_get_throttle),
5714 452 : image_layer_creation_check_threshold: Some(
5715 452 : tenant_conf.image_layer_creation_check_threshold,
5716 452 : ),
5717 452 : image_creation_preempt_threshold: Some(
5718 452 : tenant_conf.image_creation_preempt_threshold,
5719 452 : ),
5720 452 : lsn_lease_length: Some(tenant_conf.lsn_lease_length),
5721 452 : lsn_lease_length_for_ts: Some(tenant_conf.lsn_lease_length_for_ts),
5722 452 : timeline_offloading: Some(tenant_conf.timeline_offloading),
5723 452 : wal_receiver_protocol_override: tenant_conf.wal_receiver_protocol_override,
5724 452 : rel_size_v2_enabled: Some(tenant_conf.rel_size_v2_enabled),
5725 452 : gc_compaction_enabled: Some(tenant_conf.gc_compaction_enabled),
5726 452 : gc_compaction_initial_threshold_kb: Some(
5727 452 : tenant_conf.gc_compaction_initial_threshold_kb,
5728 452 : ),
5729 452 : gc_compaction_ratio_percent: Some(tenant_conf.gc_compaction_ratio_percent),
5730 452 : }
5731 452 : }
5732 : }
5733 :
5734 : pub struct TenantHarness {
5735 : pub conf: &'static PageServerConf,
5736 : pub tenant_conf: TenantConf,
5737 : pub tenant_shard_id: TenantShardId,
5738 : pub generation: Generation,
5739 : pub shard: ShardIndex,
5740 : pub remote_storage: GenericRemoteStorage,
5741 : pub remote_fs_dir: Utf8PathBuf,
5742 : pub deletion_queue: MockDeletionQueue,
5743 : }
5744 :
5745 : static LOG_HANDLE: OnceCell<()> = OnceCell::new();
5746 :
5747 500 : pub(crate) fn setup_logging() {
5748 500 : LOG_HANDLE.get_or_init(|| {
5749 476 : logging::init(
5750 476 : logging::LogFormat::Test,
5751 476 : // enable it in case the tests exercise code paths that use
5752 476 : // debug_assert_current_span_has_tenant_and_timeline_id
5753 476 : logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
5754 476 : logging::Output::Stdout,
5755 476 : )
5756 476 : .expect("Failed to init test logging");
5757 500 : });
5758 500 : }
5759 :
5760 : impl TenantHarness {
5761 452 : pub async fn create_custom(
5762 452 : test_name: &'static str,
5763 452 : tenant_conf: TenantConf,
5764 452 : tenant_id: TenantId,
5765 452 : shard_identity: ShardIdentity,
5766 452 : generation: Generation,
5767 452 : ) -> anyhow::Result<Self> {
5768 452 : setup_logging();
5769 452 :
5770 452 : let repo_dir = PageServerConf::test_repo_dir(test_name);
5771 452 : let _ = fs::remove_dir_all(&repo_dir);
5772 452 : fs::create_dir_all(&repo_dir)?;
5773 :
5774 452 : let conf = PageServerConf::dummy_conf(repo_dir);
5775 452 : // Make a static copy of the config. This can never be free'd, but that's
5776 452 : // OK in a test.
5777 452 : let conf: &'static PageServerConf = Box::leak(Box::new(conf));
5778 452 :
5779 452 : let shard = shard_identity.shard_index();
5780 452 : let tenant_shard_id = TenantShardId {
5781 452 : tenant_id,
5782 452 : shard_number: shard.shard_number,
5783 452 : shard_count: shard.shard_count,
5784 452 : };
5785 452 : fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
5786 452 : fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
5787 :
5788 : use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
5789 452 : let remote_fs_dir = conf.workdir.join("localfs");
5790 452 : std::fs::create_dir_all(&remote_fs_dir).unwrap();
5791 452 : let config = RemoteStorageConfig {
5792 452 : storage: RemoteStorageKind::LocalFs {
5793 452 : local_path: remote_fs_dir.clone(),
5794 452 : },
5795 452 : timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
5796 452 : small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
5797 452 : };
5798 452 : let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
5799 452 : let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
5800 452 :
5801 452 : Ok(Self {
5802 452 : conf,
5803 452 : tenant_conf,
5804 452 : tenant_shard_id,
5805 452 : generation,
5806 452 : shard,
5807 452 : remote_storage,
5808 452 : remote_fs_dir,
5809 452 : deletion_queue,
5810 452 : })
5811 452 : }
5812 :
5813 428 : pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
5814 428 : // Disable automatic GC and compaction to make the unit tests more deterministic.
5815 428 : // The tests perform them manually if needed.
5816 428 : let tenant_conf = TenantConf {
5817 428 : gc_period: Duration::ZERO,
5818 428 : compaction_period: Duration::ZERO,
5819 428 : ..TenantConf::default()
5820 428 : };
5821 428 : let tenant_id = TenantId::generate();
5822 428 : let shard = ShardIdentity::unsharded();
5823 428 : Self::create_custom(
5824 428 : test_name,
5825 428 : tenant_conf,
5826 428 : tenant_id,
5827 428 : shard,
5828 428 : Generation::new(0xdeadbeef),
5829 428 : )
5830 428 : .await
5831 428 : }
5832 :
5833 40 : pub fn span(&self) -> tracing::Span {
5834 40 : info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
5835 40 : }
5836 :
5837 452 : pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
5838 452 : let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error)
5839 452 : .with_scope_unit_test();
5840 452 : (
5841 452 : self.do_try_load(&ctx)
5842 452 : .await
5843 452 : .expect("failed to load test tenant"),
5844 452 : ctx,
5845 452 : )
5846 452 : }
5847 :
5848 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5849 : pub(crate) async fn do_try_load(
5850 : &self,
5851 : ctx: &RequestContext,
5852 : ) -> anyhow::Result<Arc<Tenant>> {
5853 : let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
5854 :
5855 : let tenant = Arc::new(Tenant::new(
5856 : TenantState::Attaching,
5857 : self.conf,
5858 : AttachedTenantConf::try_from(LocationConf::attached_single(
5859 : TenantConfOpt::from(self.tenant_conf.clone()),
5860 : self.generation,
5861 : &ShardParameters::default(),
5862 : ))
5863 : .unwrap(),
5864 : // This is a legacy/test code path: sharding isn't supported here.
5865 : ShardIdentity::unsharded(),
5866 : Some(walredo_mgr),
5867 : self.tenant_shard_id,
5868 : self.remote_storage.clone(),
5869 : self.deletion_queue.new_client(),
5870 : // TODO: ideally we should run all unit tests with both configs
5871 : L0FlushGlobalState::new(L0FlushConfig::default()),
5872 : ));
5873 :
5874 : let preload = tenant
5875 : .preload(&self.remote_storage, CancellationToken::new())
5876 : .await?;
5877 : tenant.attach(Some(preload), ctx).await?;
5878 :
5879 : tenant.state.send_replace(TenantState::Active);
5880 : for timeline in tenant.timelines.lock().unwrap().values() {
5881 : timeline.set_state(TimelineState::Active);
5882 : }
5883 : Ok(tenant)
5884 : }
5885 :
5886 4 : pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
5887 4 : self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
5888 4 : }
5889 : }
5890 :
5891 : // Mock WAL redo manager that doesn't do much
5892 : pub(crate) struct TestRedoManager;
5893 :
5894 : impl TestRedoManager {
5895 : /// # Cancel-Safety
5896 : ///
5897 : /// This method is cancellation-safe.
5898 1676 : pub async fn request_redo(
5899 1676 : &self,
5900 1676 : key: Key,
5901 1676 : lsn: Lsn,
5902 1676 : base_img: Option<(Lsn, Bytes)>,
5903 1676 : records: Vec<(Lsn, NeonWalRecord)>,
5904 1676 : _pg_version: u32,
5905 1676 : ) -> Result<Bytes, walredo::Error> {
5906 2472 : let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
5907 1676 : if records_neon {
5908 : // For Neon wal records, we can decode without spawning postgres, so do so.
5909 1676 : let mut page = match (base_img, records.first()) {
5910 1536 : (Some((_lsn, img)), _) => {
5911 1536 : let mut page = BytesMut::new();
5912 1536 : page.extend_from_slice(&img);
5913 1536 : page
5914 : }
5915 140 : (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
5916 : _ => {
5917 0 : panic!("Neon WAL redo requires base image or will init record");
5918 : }
5919 : };
5920 :
5921 4148 : for (record_lsn, record) in records {
5922 2472 : apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
5923 : }
5924 1676 : Ok(page.freeze())
5925 : } else {
5926 : // We never spawn a postgres walredo process in unit tests: just log what we might have done.
5927 0 : let s = format!(
5928 0 : "redo for {} to get to {}, with {} and {} records",
5929 0 : key,
5930 0 : lsn,
5931 0 : if base_img.is_some() {
5932 0 : "base image"
5933 : } else {
5934 0 : "no base image"
5935 : },
5936 0 : records.len()
5937 0 : );
5938 0 : println!("{s}");
5939 0 :
5940 0 : Ok(test_img(&s))
5941 : }
5942 1676 : }
5943 : }
5944 : }
5945 :
5946 : #[cfg(test)]
5947 : mod tests {
5948 : use std::collections::{BTreeMap, BTreeSet};
5949 :
5950 : use bytes::{Bytes, BytesMut};
5951 : use hex_literal::hex;
5952 : use itertools::Itertools;
5953 : #[cfg(feature = "testing")]
5954 : use models::CompactLsnRange;
5955 : use pageserver_api::key::{AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX};
5956 : use pageserver_api::keyspace::KeySpace;
5957 : use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
5958 : #[cfg(feature = "testing")]
5959 : use pageserver_api::record::NeonWalRecord;
5960 : use pageserver_api::value::Value;
5961 : use pageserver_compaction::helpers::overlaps_with;
5962 : use rand::{Rng, thread_rng};
5963 : use storage_layer::{IoConcurrency, PersistentLayerKey};
5964 : use tests::storage_layer::ValuesReconstructState;
5965 : use tests::timeline::{GetVectoredError, ShutdownMode};
5966 : #[cfg(feature = "testing")]
5967 : use timeline::GcInfo;
5968 : #[cfg(feature = "testing")]
5969 : use timeline::InMemoryLayerTestDesc;
5970 : #[cfg(feature = "testing")]
5971 : use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
5972 : use timeline::{CompactOptions, DeltaLayerTestDesc};
5973 : use utils::id::TenantId;
5974 :
5975 : use super::*;
5976 : use crate::DEFAULT_PG_VERSION;
5977 : use crate::keyspace::KeySpaceAccum;
5978 : use crate::tenant::harness::*;
5979 : use crate::tenant::timeline::CompactFlags;
5980 :
5981 : static TEST_KEY: Lazy<Key> =
5982 36 : Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
5983 :
5984 : #[tokio::test]
5985 4 : async fn test_basic() -> anyhow::Result<()> {
5986 4 : let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
5987 4 : let tline = tenant
5988 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
5989 4 : .await?;
5990 4 :
5991 4 : let mut writer = tline.writer().await;
5992 4 : writer
5993 4 : .put(
5994 4 : *TEST_KEY,
5995 4 : Lsn(0x10),
5996 4 : &Value::Image(test_img("foo at 0x10")),
5997 4 : &ctx,
5998 4 : )
5999 4 : .await?;
6000 4 : writer.finish_write(Lsn(0x10));
6001 4 : drop(writer);
6002 4 :
6003 4 : let mut writer = tline.writer().await;
6004 4 : writer
6005 4 : .put(
6006 4 : *TEST_KEY,
6007 4 : Lsn(0x20),
6008 4 : &Value::Image(test_img("foo at 0x20")),
6009 4 : &ctx,
6010 4 : )
6011 4 : .await?;
6012 4 : writer.finish_write(Lsn(0x20));
6013 4 : drop(writer);
6014 4 :
6015 4 : assert_eq!(
6016 4 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
6017 4 : test_img("foo at 0x10")
6018 4 : );
6019 4 : assert_eq!(
6020 4 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
6021 4 : test_img("foo at 0x10")
6022 4 : );
6023 4 : assert_eq!(
6024 4 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
6025 4 : test_img("foo at 0x20")
6026 4 : );
6027 4 :
6028 4 : Ok(())
6029 4 : }
6030 :
6031 : #[tokio::test]
6032 4 : async fn no_duplicate_timelines() -> anyhow::Result<()> {
6033 4 : let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
6034 4 : .await?
6035 4 : .load()
6036 4 : .await;
6037 4 : let _ = tenant
6038 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6039 4 : .await?;
6040 4 :
6041 4 : match tenant
6042 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6043 4 : .await
6044 4 : {
6045 4 : Ok(_) => panic!("duplicate timeline creation should fail"),
6046 4 : Err(e) => assert_eq!(
6047 4 : e.to_string(),
6048 4 : "timeline already exists with different parameters".to_string()
6049 4 : ),
6050 4 : }
6051 4 :
6052 4 : Ok(())
6053 4 : }
6054 :
6055 : /// Convenience function to create a page image with given string as the only content
6056 20 : pub fn test_value(s: &str) -> Value {
6057 20 : let mut buf = BytesMut::new();
6058 20 : buf.extend_from_slice(s.as_bytes());
6059 20 : Value::Image(buf.freeze())
6060 20 : }
6061 :
6062 : ///
6063 : /// Test branch creation
6064 : ///
6065 : #[tokio::test]
6066 4 : async fn test_branch() -> anyhow::Result<()> {
6067 4 : use std::str::from_utf8;
6068 4 :
6069 4 : let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
6070 4 : let tline = tenant
6071 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6072 4 : .await?;
6073 4 : let mut writer = tline.writer().await;
6074 4 :
6075 4 : #[allow(non_snake_case)]
6076 4 : let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
6077 4 : #[allow(non_snake_case)]
6078 4 : let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
6079 4 :
6080 4 : // Insert a value on the timeline
6081 4 : writer
6082 4 : .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
6083 4 : .await?;
6084 4 : writer
6085 4 : .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
6086 4 : .await?;
6087 4 : writer.finish_write(Lsn(0x20));
6088 4 :
6089 4 : writer
6090 4 : .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
6091 4 : .await?;
6092 4 : writer.finish_write(Lsn(0x30));
6093 4 : writer
6094 4 : .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
6095 4 : .await?;
6096 4 : writer.finish_write(Lsn(0x40));
6097 4 :
6098 4 : //assert_current_logical_size(&tline, Lsn(0x40));
6099 4 :
6100 4 : // Branch the history, modify relation differently on the new timeline
6101 4 : tenant
6102 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
6103 4 : .await?;
6104 4 : let newtline = tenant
6105 4 : .get_timeline(NEW_TIMELINE_ID, true)
6106 4 : .expect("Should have a local timeline");
6107 4 : let mut new_writer = newtline.writer().await;
6108 4 : new_writer
6109 4 : .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
6110 4 : .await?;
6111 4 : new_writer.finish_write(Lsn(0x40));
6112 4 :
6113 4 : // Check page contents on both branches
6114 4 : assert_eq!(
6115 4 : from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
6116 4 : "foo at 0x40"
6117 4 : );
6118 4 : assert_eq!(
6119 4 : from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
6120 4 : "bar at 0x40"
6121 4 : );
6122 4 : assert_eq!(
6123 4 : from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
6124 4 : "foobar at 0x20"
6125 4 : );
6126 4 :
6127 4 : //assert_current_logical_size(&tline, Lsn(0x40));
6128 4 :
6129 4 : Ok(())
6130 4 : }
6131 :
6132 40 : async fn make_some_layers(
6133 40 : tline: &Timeline,
6134 40 : start_lsn: Lsn,
6135 40 : ctx: &RequestContext,
6136 40 : ) -> anyhow::Result<()> {
6137 40 : let mut lsn = start_lsn;
6138 : {
6139 40 : let mut writer = tline.writer().await;
6140 : // Create a relation on the timeline
6141 40 : writer
6142 40 : .put(
6143 40 : *TEST_KEY,
6144 40 : lsn,
6145 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6146 40 : ctx,
6147 40 : )
6148 40 : .await?;
6149 40 : writer.finish_write(lsn);
6150 40 : lsn += 0x10;
6151 40 : writer
6152 40 : .put(
6153 40 : *TEST_KEY,
6154 40 : lsn,
6155 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6156 40 : ctx,
6157 40 : )
6158 40 : .await?;
6159 40 : writer.finish_write(lsn);
6160 40 : lsn += 0x10;
6161 40 : }
6162 40 : tline.freeze_and_flush().await?;
6163 : {
6164 40 : let mut writer = tline.writer().await;
6165 40 : writer
6166 40 : .put(
6167 40 : *TEST_KEY,
6168 40 : lsn,
6169 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6170 40 : ctx,
6171 40 : )
6172 40 : .await?;
6173 40 : writer.finish_write(lsn);
6174 40 : lsn += 0x10;
6175 40 : writer
6176 40 : .put(
6177 40 : *TEST_KEY,
6178 40 : lsn,
6179 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6180 40 : ctx,
6181 40 : )
6182 40 : .await?;
6183 40 : writer.finish_write(lsn);
6184 40 : }
6185 40 : tline.freeze_and_flush().await.map_err(|e| e.into())
6186 40 : }
6187 :
6188 : #[tokio::test(start_paused = true)]
6189 4 : async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
6190 4 : let (tenant, ctx) =
6191 4 : TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
6192 4 : .await?
6193 4 : .load()
6194 4 : .await;
6195 4 : // Advance to the lsn lease deadline so that GC is not blocked by
6196 4 : // initial transition into AttachedSingle.
6197 4 : tokio::time::advance(tenant.get_lsn_lease_length()).await;
6198 4 : tokio::time::resume();
6199 4 : let tline = tenant
6200 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6201 4 : .await?;
6202 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6203 4 :
6204 4 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
6205 4 : // FIXME: this doesn't actually remove any layer currently, given how the flushing
6206 4 : // and compaction works. But it does set the 'cutoff' point so that the cross check
6207 4 : // below should fail.
6208 4 : tenant
6209 4 : .gc_iteration(
6210 4 : Some(TIMELINE_ID),
6211 4 : 0x10,
6212 4 : Duration::ZERO,
6213 4 : &CancellationToken::new(),
6214 4 : &ctx,
6215 4 : )
6216 4 : .await?;
6217 4 :
6218 4 : // try to branch at lsn 25, should fail because we already garbage collected the data
6219 4 : match tenant
6220 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
6221 4 : .await
6222 4 : {
6223 4 : Ok(_) => panic!("branching should have failed"),
6224 4 : Err(err) => {
6225 4 : let CreateTimelineError::AncestorLsn(err) = err else {
6226 4 : panic!("wrong error type")
6227 4 : };
6228 4 : assert!(err.to_string().contains("invalid branch start lsn"));
6229 4 : assert!(
6230 4 : err.source()
6231 4 : .unwrap()
6232 4 : .to_string()
6233 4 : .contains("we might've already garbage collected needed data")
6234 4 : )
6235 4 : }
6236 4 : }
6237 4 :
6238 4 : Ok(())
6239 4 : }
6240 :
6241 : #[tokio::test]
6242 4 : async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
6243 4 : let (tenant, ctx) =
6244 4 : TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
6245 4 : .await?
6246 4 : .load()
6247 4 : .await;
6248 4 :
6249 4 : let tline = tenant
6250 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
6251 4 : .await?;
6252 4 : // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
6253 4 : match tenant
6254 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
6255 4 : .await
6256 4 : {
6257 4 : Ok(_) => panic!("branching should have failed"),
6258 4 : Err(err) => {
6259 4 : let CreateTimelineError::AncestorLsn(err) = err else {
6260 4 : panic!("wrong error type");
6261 4 : };
6262 4 : assert!(&err.to_string().contains("invalid branch start lsn"));
6263 4 : assert!(
6264 4 : &err.source()
6265 4 : .unwrap()
6266 4 : .to_string()
6267 4 : .contains("is earlier than latest GC cutoff")
6268 4 : );
6269 4 : }
6270 4 : }
6271 4 :
6272 4 : Ok(())
6273 4 : }
6274 :
6275 : /*
6276 : // FIXME: This currently fails to error out. Calling GC doesn't currently
6277 : // remove the old value, we'd need to work a little harder
6278 : #[tokio::test]
6279 : async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
6280 : let repo =
6281 : RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
6282 : .load();
6283 :
6284 : let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
6285 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6286 :
6287 : repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
6288 : let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
6289 : assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
6290 : match tline.get(*TEST_KEY, Lsn(0x25)) {
6291 : Ok(_) => panic!("request for page should have failed"),
6292 : Err(err) => assert!(err.to_string().contains("not found at")),
6293 : }
6294 : Ok(())
6295 : }
6296 : */
6297 :
6298 : #[tokio::test]
6299 4 : async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
6300 4 : let (tenant, ctx) =
6301 4 : TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
6302 4 : .await?
6303 4 : .load()
6304 4 : .await;
6305 4 : let tline = tenant
6306 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6307 4 : .await?;
6308 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6309 4 :
6310 4 : tenant
6311 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6312 4 : .await?;
6313 4 : let newtline = tenant
6314 4 : .get_timeline(NEW_TIMELINE_ID, true)
6315 4 : .expect("Should have a local timeline");
6316 4 :
6317 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6318 4 :
6319 4 : tline.set_broken("test".to_owned());
6320 4 :
6321 4 : tenant
6322 4 : .gc_iteration(
6323 4 : Some(TIMELINE_ID),
6324 4 : 0x10,
6325 4 : Duration::ZERO,
6326 4 : &CancellationToken::new(),
6327 4 : &ctx,
6328 4 : )
6329 4 : .await?;
6330 4 :
6331 4 : // The branchpoints should contain all timelines, even ones marked
6332 4 : // as Broken.
6333 4 : {
6334 4 : let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
6335 4 : assert_eq!(branchpoints.len(), 1);
6336 4 : assert_eq!(
6337 4 : branchpoints[0],
6338 4 : (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
6339 4 : );
6340 4 : }
6341 4 :
6342 4 : // You can read the key from the child branch even though the parent is
6343 4 : // Broken, as long as you don't need to access data from the parent.
6344 4 : assert_eq!(
6345 4 : newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
6346 4 : test_img(&format!("foo at {}", Lsn(0x70)))
6347 4 : );
6348 4 :
6349 4 : // This needs to traverse to the parent, and fails.
6350 4 : let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
6351 4 : assert!(
6352 4 : err.to_string().starts_with(&format!(
6353 4 : "bad state on timeline {}: Broken",
6354 4 : tline.timeline_id
6355 4 : )),
6356 4 : "{err}"
6357 4 : );
6358 4 :
6359 4 : Ok(())
6360 4 : }
6361 :
6362 : #[tokio::test]
6363 4 : async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
6364 4 : let (tenant, ctx) =
6365 4 : TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
6366 4 : .await?
6367 4 : .load()
6368 4 : .await;
6369 4 : let tline = tenant
6370 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6371 4 : .await?;
6372 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6373 4 :
6374 4 : tenant
6375 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6376 4 : .await?;
6377 4 : let newtline = tenant
6378 4 : .get_timeline(NEW_TIMELINE_ID, true)
6379 4 : .expect("Should have a local timeline");
6380 4 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
6381 4 : tenant
6382 4 : .gc_iteration(
6383 4 : Some(TIMELINE_ID),
6384 4 : 0x10,
6385 4 : Duration::ZERO,
6386 4 : &CancellationToken::new(),
6387 4 : &ctx,
6388 4 : )
6389 4 : .await?;
6390 4 : assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
6391 4 :
6392 4 : Ok(())
6393 4 : }
6394 : #[tokio::test]
6395 4 : async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
6396 4 : let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
6397 4 : .await?
6398 4 : .load()
6399 4 : .await;
6400 4 : let tline = tenant
6401 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6402 4 : .await?;
6403 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6404 4 :
6405 4 : tenant
6406 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6407 4 : .await?;
6408 4 : let newtline = tenant
6409 4 : .get_timeline(NEW_TIMELINE_ID, true)
6410 4 : .expect("Should have a local timeline");
6411 4 :
6412 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6413 4 :
6414 4 : // run gc on parent
6415 4 : tenant
6416 4 : .gc_iteration(
6417 4 : Some(TIMELINE_ID),
6418 4 : 0x10,
6419 4 : Duration::ZERO,
6420 4 : &CancellationToken::new(),
6421 4 : &ctx,
6422 4 : )
6423 4 : .await?;
6424 4 :
6425 4 : // Check that the data is still accessible on the branch.
6426 4 : assert_eq!(
6427 4 : newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
6428 4 : test_img(&format!("foo at {}", Lsn(0x40)))
6429 4 : );
6430 4 :
6431 4 : Ok(())
6432 4 : }
6433 :
6434 : #[tokio::test]
6435 4 : async fn timeline_load() -> anyhow::Result<()> {
6436 4 : const TEST_NAME: &str = "timeline_load";
6437 4 : let harness = TenantHarness::create(TEST_NAME).await?;
6438 4 : {
6439 4 : let (tenant, ctx) = harness.load().await;
6440 4 : let tline = tenant
6441 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
6442 4 : .await?;
6443 4 : make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
6444 4 : // so that all uploads finish & we can call harness.load() below again
6445 4 : tenant
6446 4 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
6447 4 : .instrument(harness.span())
6448 4 : .await
6449 4 : .ok()
6450 4 : .unwrap();
6451 4 : }
6452 4 :
6453 4 : let (tenant, _ctx) = harness.load().await;
6454 4 : tenant
6455 4 : .get_timeline(TIMELINE_ID, true)
6456 4 : .expect("cannot load timeline");
6457 4 :
6458 4 : Ok(())
6459 4 : }
6460 :
6461 : #[tokio::test]
6462 4 : async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
6463 4 : const TEST_NAME: &str = "timeline_load_with_ancestor";
6464 4 : let harness = TenantHarness::create(TEST_NAME).await?;
6465 4 : // create two timelines
6466 4 : {
6467 4 : let (tenant, ctx) = harness.load().await;
6468 4 : let tline = tenant
6469 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6470 4 : .await?;
6471 4 :
6472 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6473 4 :
6474 4 : let child_tline = tenant
6475 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6476 4 : .await?;
6477 4 : child_tline.set_state(TimelineState::Active);
6478 4 :
6479 4 : let newtline = tenant
6480 4 : .get_timeline(NEW_TIMELINE_ID, true)
6481 4 : .expect("Should have a local timeline");
6482 4 :
6483 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6484 4 :
6485 4 : // so that all uploads finish & we can call harness.load() below again
6486 4 : tenant
6487 4 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
6488 4 : .instrument(harness.span())
6489 4 : .await
6490 4 : .ok()
6491 4 : .unwrap();
6492 4 : }
6493 4 :
6494 4 : // check that both of them are initially unloaded
6495 4 : let (tenant, _ctx) = harness.load().await;
6496 4 :
6497 4 : // check that both, child and ancestor are loaded
6498 4 : let _child_tline = tenant
6499 4 : .get_timeline(NEW_TIMELINE_ID, true)
6500 4 : .expect("cannot get child timeline loaded");
6501 4 :
6502 4 : let _ancestor_tline = tenant
6503 4 : .get_timeline(TIMELINE_ID, true)
6504 4 : .expect("cannot get ancestor timeline loaded");
6505 4 :
6506 4 : Ok(())
6507 4 : }
6508 :
6509 : #[tokio::test]
6510 4 : async fn delta_layer_dumping() -> anyhow::Result<()> {
6511 4 : use storage_layer::AsLayerDesc;
6512 4 : let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
6513 4 : .await?
6514 4 : .load()
6515 4 : .await;
6516 4 : let tline = tenant
6517 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6518 4 : .await?;
6519 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6520 4 :
6521 4 : let layer_map = tline.layers.read().await;
6522 4 : let level0_deltas = layer_map
6523 4 : .layer_map()?
6524 4 : .level0_deltas()
6525 4 : .iter()
6526 8 : .map(|desc| layer_map.get_from_desc(desc))
6527 4 : .collect::<Vec<_>>();
6528 4 :
6529 4 : assert!(!level0_deltas.is_empty());
6530 4 :
6531 12 : for delta in level0_deltas {
6532 4 : // Ensure we are dumping a delta layer here
6533 8 : assert!(delta.layer_desc().is_delta);
6534 8 : delta.dump(true, &ctx).await.unwrap();
6535 4 : }
6536 4 :
6537 4 : Ok(())
6538 4 : }
6539 :
6540 : #[tokio::test]
6541 4 : async fn test_images() -> anyhow::Result<()> {
6542 4 : let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
6543 4 : let tline = tenant
6544 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6545 4 : .await?;
6546 4 :
6547 4 : let mut writer = tline.writer().await;
6548 4 : writer
6549 4 : .put(
6550 4 : *TEST_KEY,
6551 4 : Lsn(0x10),
6552 4 : &Value::Image(test_img("foo at 0x10")),
6553 4 : &ctx,
6554 4 : )
6555 4 : .await?;
6556 4 : writer.finish_write(Lsn(0x10));
6557 4 : drop(writer);
6558 4 :
6559 4 : tline.freeze_and_flush().await?;
6560 4 : tline
6561 4 : .compact(
6562 4 : &CancellationToken::new(),
6563 4 : CompactFlags::NoYield.into(),
6564 4 : &ctx,
6565 4 : )
6566 4 : .await?;
6567 4 :
6568 4 : let mut writer = tline.writer().await;
6569 4 : writer
6570 4 : .put(
6571 4 : *TEST_KEY,
6572 4 : Lsn(0x20),
6573 4 : &Value::Image(test_img("foo at 0x20")),
6574 4 : &ctx,
6575 4 : )
6576 4 : .await?;
6577 4 : writer.finish_write(Lsn(0x20));
6578 4 : drop(writer);
6579 4 :
6580 4 : tline.freeze_and_flush().await?;
6581 4 : tline
6582 4 : .compact(
6583 4 : &CancellationToken::new(),
6584 4 : CompactFlags::NoYield.into(),
6585 4 : &ctx,
6586 4 : )
6587 4 : .await?;
6588 4 :
6589 4 : let mut writer = tline.writer().await;
6590 4 : writer
6591 4 : .put(
6592 4 : *TEST_KEY,
6593 4 : Lsn(0x30),
6594 4 : &Value::Image(test_img("foo at 0x30")),
6595 4 : &ctx,
6596 4 : )
6597 4 : .await?;
6598 4 : writer.finish_write(Lsn(0x30));
6599 4 : drop(writer);
6600 4 :
6601 4 : tline.freeze_and_flush().await?;
6602 4 : tline
6603 4 : .compact(
6604 4 : &CancellationToken::new(),
6605 4 : CompactFlags::NoYield.into(),
6606 4 : &ctx,
6607 4 : )
6608 4 : .await?;
6609 4 :
6610 4 : let mut writer = tline.writer().await;
6611 4 : writer
6612 4 : .put(
6613 4 : *TEST_KEY,
6614 4 : Lsn(0x40),
6615 4 : &Value::Image(test_img("foo at 0x40")),
6616 4 : &ctx,
6617 4 : )
6618 4 : .await?;
6619 4 : writer.finish_write(Lsn(0x40));
6620 4 : drop(writer);
6621 4 :
6622 4 : tline.freeze_and_flush().await?;
6623 4 : tline
6624 4 : .compact(
6625 4 : &CancellationToken::new(),
6626 4 : CompactFlags::NoYield.into(),
6627 4 : &ctx,
6628 4 : )
6629 4 : .await?;
6630 4 :
6631 4 : assert_eq!(
6632 4 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
6633 4 : test_img("foo at 0x10")
6634 4 : );
6635 4 : assert_eq!(
6636 4 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
6637 4 : test_img("foo at 0x10")
6638 4 : );
6639 4 : assert_eq!(
6640 4 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
6641 4 : test_img("foo at 0x20")
6642 4 : );
6643 4 : assert_eq!(
6644 4 : tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
6645 4 : test_img("foo at 0x30")
6646 4 : );
6647 4 : assert_eq!(
6648 4 : tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
6649 4 : test_img("foo at 0x40")
6650 4 : );
6651 4 :
6652 4 : Ok(())
6653 4 : }
6654 :
6655 8 : async fn bulk_insert_compact_gc(
6656 8 : tenant: &Tenant,
6657 8 : timeline: &Arc<Timeline>,
6658 8 : ctx: &RequestContext,
6659 8 : lsn: Lsn,
6660 8 : repeat: usize,
6661 8 : key_count: usize,
6662 8 : ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
6663 8 : let compact = true;
6664 8 : bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
6665 8 : }
6666 :
6667 16 : async fn bulk_insert_maybe_compact_gc(
6668 16 : tenant: &Tenant,
6669 16 : timeline: &Arc<Timeline>,
6670 16 : ctx: &RequestContext,
6671 16 : mut lsn: Lsn,
6672 16 : repeat: usize,
6673 16 : key_count: usize,
6674 16 : compact: bool,
6675 16 : ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
6676 16 : let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
6677 16 :
6678 16 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6679 16 : let mut blknum = 0;
6680 16 :
6681 16 : // Enforce that key range is monotonously increasing
6682 16 : let mut keyspace = KeySpaceAccum::new();
6683 16 :
6684 16 : let cancel = CancellationToken::new();
6685 16 :
6686 16 : for _ in 0..repeat {
6687 800 : for _ in 0..key_count {
6688 8000000 : test_key.field6 = blknum;
6689 8000000 : let mut writer = timeline.writer().await;
6690 8000000 : writer
6691 8000000 : .put(
6692 8000000 : test_key,
6693 8000000 : lsn,
6694 8000000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
6695 8000000 : ctx,
6696 8000000 : )
6697 8000000 : .await?;
6698 8000000 : inserted.entry(test_key).or_default().insert(lsn);
6699 8000000 : writer.finish_write(lsn);
6700 8000000 : drop(writer);
6701 8000000 :
6702 8000000 : keyspace.add_key(test_key);
6703 8000000 :
6704 8000000 : lsn = Lsn(lsn.0 + 0x10);
6705 8000000 : blknum += 1;
6706 : }
6707 :
6708 800 : timeline.freeze_and_flush().await?;
6709 800 : if compact {
6710 : // this requires timeline to be &Arc<Timeline>
6711 400 : timeline
6712 400 : .compact(&cancel, CompactFlags::NoYield.into(), ctx)
6713 400 : .await?;
6714 400 : }
6715 :
6716 : // this doesn't really need to use the timeline_id target, but it is closer to what it
6717 : // originally was.
6718 800 : let res = tenant
6719 800 : .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
6720 800 : .await?;
6721 :
6722 800 : assert_eq!(res.layers_removed, 0, "this never removes anything");
6723 : }
6724 :
6725 16 : Ok(inserted)
6726 16 : }
6727 :
6728 : //
6729 : // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
6730 : // Repeat 50 times.
6731 : //
6732 : #[tokio::test]
6733 4 : async fn test_bulk_insert() -> anyhow::Result<()> {
6734 4 : let harness = TenantHarness::create("test_bulk_insert").await?;
6735 4 : let (tenant, ctx) = harness.load().await;
6736 4 : let tline = tenant
6737 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6738 4 : .await?;
6739 4 :
6740 4 : let lsn = Lsn(0x10);
6741 4 : bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
6742 4 :
6743 4 : Ok(())
6744 4 : }
6745 :
6746 : // Test the vectored get real implementation against a simple sequential implementation.
6747 : //
6748 : // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
6749 : // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
6750 : // grow to the right on the X axis.
6751 : // [Delta]
6752 : // [Delta]
6753 : // [Delta]
6754 : // [Delta]
6755 : // ------------ Image ---------------
6756 : //
6757 : // After layer generation we pick the ranges to query as follows:
6758 : // 1. The beginning of each delta layer
6759 : // 2. At the seam between two adjacent delta layers
6760 : //
6761 : // There's one major downside to this test: delta layers only contains images,
6762 : // so the search can stop at the first delta layer and doesn't traverse any deeper.
6763 : #[tokio::test]
6764 4 : async fn test_get_vectored() -> anyhow::Result<()> {
6765 4 : let harness = TenantHarness::create("test_get_vectored").await?;
6766 4 : let (tenant, ctx) = harness.load().await;
6767 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6768 4 : let tline = tenant
6769 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6770 4 : .await?;
6771 4 :
6772 4 : let lsn = Lsn(0x10);
6773 4 : let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
6774 4 :
6775 4 : let guard = tline.layers.read().await;
6776 4 : let lm = guard.layer_map()?;
6777 4 :
6778 4 : lm.dump(true, &ctx).await?;
6779 4 :
6780 4 : let mut reads = Vec::new();
6781 4 : let mut prev = None;
6782 24 : lm.iter_historic_layers().for_each(|desc| {
6783 24 : if !desc.is_delta() {
6784 4 : prev = Some(desc.clone());
6785 4 : return;
6786 20 : }
6787 20 :
6788 20 : let start = desc.key_range.start;
6789 20 : let end = desc
6790 20 : .key_range
6791 20 : .start
6792 20 : .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
6793 20 : reads.push(KeySpace {
6794 20 : ranges: vec![start..end],
6795 20 : });
6796 4 :
6797 20 : if let Some(prev) = &prev {
6798 20 : if !prev.is_delta() {
6799 20 : return;
6800 4 : }
6801 0 :
6802 0 : let first_range = Key {
6803 0 : field6: prev.key_range.end.field6 - 4,
6804 0 : ..prev.key_range.end
6805 0 : }..prev.key_range.end;
6806 0 :
6807 0 : let second_range = desc.key_range.start..Key {
6808 0 : field6: desc.key_range.start.field6 + 4,
6809 0 : ..desc.key_range.start
6810 0 : };
6811 0 :
6812 0 : reads.push(KeySpace {
6813 0 : ranges: vec![first_range, second_range],
6814 0 : });
6815 4 : };
6816 4 :
6817 4 : prev = Some(desc.clone());
6818 24 : });
6819 4 :
6820 4 : drop(guard);
6821 4 :
6822 4 : // Pick a big LSN such that we query over all the changes.
6823 4 : let reads_lsn = Lsn(u64::MAX - 1);
6824 4 :
6825 24 : for read in reads {
6826 20 : info!("Doing vectored read on {:?}", read);
6827 4 :
6828 20 : let vectored_res = tline
6829 20 : .get_vectored_impl(
6830 20 : read.clone(),
6831 20 : reads_lsn,
6832 20 : &mut ValuesReconstructState::new(io_concurrency.clone()),
6833 20 : &ctx,
6834 20 : )
6835 20 : .await;
6836 4 :
6837 20 : let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
6838 20 : let mut expect_missing = false;
6839 20 : let mut key = read.start().unwrap();
6840 660 : while key != read.end().unwrap() {
6841 640 : if let Some(lsns) = inserted.get(&key) {
6842 640 : let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
6843 640 : match expected_lsn {
6844 640 : Some(lsn) => {
6845 640 : expected_lsns.insert(key, *lsn);
6846 640 : }
6847 4 : None => {
6848 4 : expect_missing = true;
6849 0 : break;
6850 4 : }
6851 4 : }
6852 4 : } else {
6853 4 : expect_missing = true;
6854 0 : break;
6855 4 : }
6856 4 :
6857 640 : key = key.next();
6858 4 : }
6859 4 :
6860 20 : if expect_missing {
6861 4 : assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
6862 4 : } else {
6863 640 : for (key, image) in vectored_res? {
6864 640 : let expected_lsn = expected_lsns.get(&key).expect("determined above");
6865 640 : let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
6866 640 : assert_eq!(image?, expected_image);
6867 4 : }
6868 4 : }
6869 4 : }
6870 4 :
6871 4 : Ok(())
6872 4 : }
6873 :
6874 : #[tokio::test]
6875 4 : async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
6876 4 : let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
6877 4 :
6878 4 : let (tenant, ctx) = harness.load().await;
6879 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6880 4 : let (tline, ctx) = tenant
6881 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
6882 4 : .await?;
6883 4 : let tline = tline.raw_timeline().unwrap();
6884 4 :
6885 4 : let mut modification = tline.begin_modification(Lsn(0x1000));
6886 4 : modification.put_file("foo/bar1", b"content1", &ctx).await?;
6887 4 : modification.set_lsn(Lsn(0x1008))?;
6888 4 : modification.put_file("foo/bar2", b"content2", &ctx).await?;
6889 4 : modification.commit(&ctx).await?;
6890 4 :
6891 4 : let child_timeline_id = TimelineId::generate();
6892 4 : tenant
6893 4 : .branch_timeline_test(
6894 4 : tline,
6895 4 : child_timeline_id,
6896 4 : Some(tline.get_last_record_lsn()),
6897 4 : &ctx,
6898 4 : )
6899 4 : .await?;
6900 4 :
6901 4 : let child_timeline = tenant
6902 4 : .get_timeline(child_timeline_id, true)
6903 4 : .expect("Should have the branched timeline");
6904 4 :
6905 4 : let aux_keyspace = KeySpace {
6906 4 : ranges: vec![NON_INHERITED_RANGE],
6907 4 : };
6908 4 : let read_lsn = child_timeline.get_last_record_lsn();
6909 4 :
6910 4 : let vectored_res = child_timeline
6911 4 : .get_vectored_impl(
6912 4 : aux_keyspace.clone(),
6913 4 : read_lsn,
6914 4 : &mut ValuesReconstructState::new(io_concurrency.clone()),
6915 4 : &ctx,
6916 4 : )
6917 4 : .await;
6918 4 :
6919 4 : let images = vectored_res?;
6920 4 : assert!(images.is_empty());
6921 4 : Ok(())
6922 4 : }
6923 :
6924 : // Test that vectored get handles layer gaps correctly
6925 : // by advancing into the next ancestor timeline if required.
6926 : //
6927 : // The test generates timelines that look like the diagram below.
6928 : // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
6929 : // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
6930 : //
6931 : // ```
6932 : //-------------------------------+
6933 : // ... |
6934 : // [ L1 ] |
6935 : // [ / L1 ] | Child Timeline
6936 : // ... |
6937 : // ------------------------------+
6938 : // [ X L1 ] | Parent Timeline
6939 : // ------------------------------+
6940 : // ```
6941 : #[tokio::test]
6942 4 : async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
6943 4 : let tenant_conf = TenantConf {
6944 4 : // Make compaction deterministic
6945 4 : gc_period: Duration::ZERO,
6946 4 : compaction_period: Duration::ZERO,
6947 4 : // Encourage creation of L1 layers
6948 4 : checkpoint_distance: 16 * 1024,
6949 4 : compaction_target_size: 8 * 1024,
6950 4 : ..TenantConf::default()
6951 4 : };
6952 4 :
6953 4 : let harness = TenantHarness::create_custom(
6954 4 : "test_get_vectored_key_gap",
6955 4 : tenant_conf,
6956 4 : TenantId::generate(),
6957 4 : ShardIdentity::unsharded(),
6958 4 : Generation::new(0xdeadbeef),
6959 4 : )
6960 4 : .await?;
6961 4 : let (tenant, ctx) = harness.load().await;
6962 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6963 4 :
6964 4 : let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6965 4 : let gap_at_key = current_key.add(100);
6966 4 : let mut current_lsn = Lsn(0x10);
6967 4 :
6968 4 : const KEY_COUNT: usize = 10_000;
6969 4 :
6970 4 : let timeline_id = TimelineId::generate();
6971 4 : let current_timeline = tenant
6972 4 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
6973 4 : .await?;
6974 4 :
6975 4 : current_lsn += 0x100;
6976 4 :
6977 4 : let mut writer = current_timeline.writer().await;
6978 4 : writer
6979 4 : .put(
6980 4 : gap_at_key,
6981 4 : current_lsn,
6982 4 : &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
6983 4 : &ctx,
6984 4 : )
6985 4 : .await?;
6986 4 : writer.finish_write(current_lsn);
6987 4 : drop(writer);
6988 4 :
6989 4 : let mut latest_lsns = HashMap::new();
6990 4 : latest_lsns.insert(gap_at_key, current_lsn);
6991 4 :
6992 4 : current_timeline.freeze_and_flush().await?;
6993 4 :
6994 4 : let child_timeline_id = TimelineId::generate();
6995 4 :
6996 4 : tenant
6997 4 : .branch_timeline_test(
6998 4 : ¤t_timeline,
6999 4 : child_timeline_id,
7000 4 : Some(current_lsn),
7001 4 : &ctx,
7002 4 : )
7003 4 : .await?;
7004 4 : let child_timeline = tenant
7005 4 : .get_timeline(child_timeline_id, true)
7006 4 : .expect("Should have the branched timeline");
7007 4 :
7008 40004 : for i in 0..KEY_COUNT {
7009 40000 : if current_key == gap_at_key {
7010 4 : current_key = current_key.next();
7011 4 : continue;
7012 39996 : }
7013 39996 :
7014 39996 : current_lsn += 0x10;
7015 4 :
7016 39996 : let mut writer = child_timeline.writer().await;
7017 39996 : writer
7018 39996 : .put(
7019 39996 : current_key,
7020 39996 : current_lsn,
7021 39996 : &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
7022 39996 : &ctx,
7023 39996 : )
7024 39996 : .await?;
7025 39996 : writer.finish_write(current_lsn);
7026 39996 : drop(writer);
7027 39996 :
7028 39996 : latest_lsns.insert(current_key, current_lsn);
7029 39996 : current_key = current_key.next();
7030 39996 :
7031 39996 : // Flush every now and then to encourage layer file creation.
7032 39996 : if i % 500 == 0 {
7033 80 : child_timeline.freeze_and_flush().await?;
7034 39916 : }
7035 4 : }
7036 4 :
7037 4 : child_timeline.freeze_and_flush().await?;
7038 4 : let mut flags = EnumSet::new();
7039 4 : flags.insert(CompactFlags::ForceRepartition);
7040 4 : flags.insert(CompactFlags::NoYield);
7041 4 : child_timeline
7042 4 : .compact(&CancellationToken::new(), flags, &ctx)
7043 4 : .await?;
7044 4 :
7045 4 : let key_near_end = {
7046 4 : let mut tmp = current_key;
7047 4 : tmp.field6 -= 10;
7048 4 : tmp
7049 4 : };
7050 4 :
7051 4 : let key_near_gap = {
7052 4 : let mut tmp = gap_at_key;
7053 4 : tmp.field6 -= 10;
7054 4 : tmp
7055 4 : };
7056 4 :
7057 4 : let read = KeySpace {
7058 4 : ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
7059 4 : };
7060 4 : let results = child_timeline
7061 4 : .get_vectored_impl(
7062 4 : read.clone(),
7063 4 : current_lsn,
7064 4 : &mut ValuesReconstructState::new(io_concurrency.clone()),
7065 4 : &ctx,
7066 4 : )
7067 4 : .await?;
7068 4 :
7069 88 : for (key, img_res) in results {
7070 84 : let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
7071 84 : assert_eq!(img_res?, expected);
7072 4 : }
7073 4 :
7074 4 : Ok(())
7075 4 : }
7076 :
7077 : // Test that vectored get descends into ancestor timelines correctly and
7078 : // does not return an image that's newer than requested.
7079 : //
7080 : // The diagram below ilustrates an interesting case. We have a parent timeline
7081 : // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
7082 : // from the child timeline, so the parent timeline must be visited. When advacing into
7083 : // the child timeline, the read path needs to remember what the requested Lsn was in
7084 : // order to avoid returning an image that's too new. The test below constructs such
7085 : // a timeline setup and does a few queries around the Lsn of each page image.
7086 : // ```
7087 : // LSN
7088 : // ^
7089 : // |
7090 : // |
7091 : // 500 | --------------------------------------> branch point
7092 : // 400 | X
7093 : // 300 | X
7094 : // 200 | --------------------------------------> requested lsn
7095 : // 100 | X
7096 : // |---------------------------------------> Key
7097 : // |
7098 : // ------> requested key
7099 : //
7100 : // Legend:
7101 : // * X - page images
7102 : // ```
7103 : #[tokio::test]
7104 4 : async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
7105 4 : let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
7106 4 : let (tenant, ctx) = harness.load().await;
7107 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7108 4 :
7109 4 : let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7110 4 : let end_key = start_key.add(1000);
7111 4 : let child_gap_at_key = start_key.add(500);
7112 4 : let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
7113 4 :
7114 4 : let mut current_lsn = Lsn(0x10);
7115 4 :
7116 4 : let timeline_id = TimelineId::generate();
7117 4 : let parent_timeline = tenant
7118 4 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
7119 4 : .await?;
7120 4 :
7121 4 : current_lsn += 0x100;
7122 4 :
7123 16 : for _ in 0..3 {
7124 12 : let mut key = start_key;
7125 12012 : while key < end_key {
7126 12000 : current_lsn += 0x10;
7127 12000 :
7128 12000 : let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
7129 4 :
7130 12000 : let mut writer = parent_timeline.writer().await;
7131 12000 : writer
7132 12000 : .put(
7133 12000 : key,
7134 12000 : current_lsn,
7135 12000 : &Value::Image(test_img(&image_value)),
7136 12000 : &ctx,
7137 12000 : )
7138 12000 : .await?;
7139 12000 : writer.finish_write(current_lsn);
7140 12000 :
7141 12000 : if key == child_gap_at_key {
7142 12 : parent_gap_lsns.insert(current_lsn, image_value);
7143 11988 : }
7144 4 :
7145 12000 : key = key.next();
7146 4 : }
7147 4 :
7148 12 : parent_timeline.freeze_and_flush().await?;
7149 4 : }
7150 4 :
7151 4 : let child_timeline_id = TimelineId::generate();
7152 4 :
7153 4 : let child_timeline = tenant
7154 4 : .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
7155 4 : .await?;
7156 4 :
7157 4 : let mut key = start_key;
7158 4004 : while key < end_key {
7159 4000 : if key == child_gap_at_key {
7160 4 : key = key.next();
7161 4 : continue;
7162 3996 : }
7163 3996 :
7164 3996 : current_lsn += 0x10;
7165 4 :
7166 3996 : let mut writer = child_timeline.writer().await;
7167 3996 : writer
7168 3996 : .put(
7169 3996 : key,
7170 3996 : current_lsn,
7171 3996 : &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
7172 3996 : &ctx,
7173 3996 : )
7174 3996 : .await?;
7175 3996 : writer.finish_write(current_lsn);
7176 3996 :
7177 3996 : key = key.next();
7178 4 : }
7179 4 :
7180 4 : child_timeline.freeze_and_flush().await?;
7181 4 :
7182 4 : let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
7183 4 : let mut query_lsns = Vec::new();
7184 12 : for image_lsn in parent_gap_lsns.keys().rev() {
7185 72 : for offset in lsn_offsets {
7186 60 : query_lsns.push(Lsn(image_lsn
7187 60 : .0
7188 60 : .checked_add_signed(offset)
7189 60 : .expect("Shouldn't overflow")));
7190 60 : }
7191 4 : }
7192 4 :
7193 64 : for query_lsn in query_lsns {
7194 60 : let results = child_timeline
7195 60 : .get_vectored_impl(
7196 60 : KeySpace {
7197 60 : ranges: vec![child_gap_at_key..child_gap_at_key.next()],
7198 60 : },
7199 60 : query_lsn,
7200 60 : &mut ValuesReconstructState::new(io_concurrency.clone()),
7201 60 : &ctx,
7202 60 : )
7203 60 : .await;
7204 4 :
7205 60 : let expected_item = parent_gap_lsns
7206 60 : .iter()
7207 60 : .rev()
7208 136 : .find(|(lsn, _)| **lsn <= query_lsn);
7209 60 :
7210 60 : info!(
7211 4 : "Doing vectored read at LSN {}. Expecting image to be: {:?}",
7212 4 : query_lsn, expected_item
7213 4 : );
7214 4 :
7215 60 : match expected_item {
7216 52 : Some((_, img_value)) => {
7217 52 : let key_results = results.expect("No vectored get error expected");
7218 52 : let key_result = &key_results[&child_gap_at_key];
7219 52 : let returned_img = key_result
7220 52 : .as_ref()
7221 52 : .expect("No page reconstruct error expected");
7222 52 :
7223 52 : info!(
7224 4 : "Vectored read at LSN {} returned image {}",
7225 0 : query_lsn,
7226 0 : std::str::from_utf8(returned_img)?
7227 4 : );
7228 52 : assert_eq!(*returned_img, test_img(img_value));
7229 4 : }
7230 4 : None => {
7231 8 : assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
7232 4 : }
7233 4 : }
7234 4 : }
7235 4 :
7236 4 : Ok(())
7237 4 : }
7238 :
7239 : #[tokio::test]
7240 4 : async fn test_random_updates() -> anyhow::Result<()> {
7241 4 : let names_algorithms = [
7242 4 : ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
7243 4 : ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
7244 4 : ];
7245 12 : for (name, algorithm) in names_algorithms {
7246 8 : test_random_updates_algorithm(name, algorithm).await?;
7247 4 : }
7248 4 : Ok(())
7249 4 : }
7250 :
7251 8 : async fn test_random_updates_algorithm(
7252 8 : name: &'static str,
7253 8 : compaction_algorithm: CompactionAlgorithm,
7254 8 : ) -> anyhow::Result<()> {
7255 8 : let mut harness = TenantHarness::create(name).await?;
7256 8 : harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
7257 8 : kind: compaction_algorithm,
7258 8 : };
7259 8 : let (tenant, ctx) = harness.load().await;
7260 8 : let tline = tenant
7261 8 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7262 8 : .await?;
7263 :
7264 : const NUM_KEYS: usize = 1000;
7265 8 : let cancel = CancellationToken::new();
7266 8 :
7267 8 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7268 8 : let mut test_key_end = test_key;
7269 8 : test_key_end.field6 = NUM_KEYS as u32;
7270 8 : tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
7271 8 :
7272 8 : let mut keyspace = KeySpaceAccum::new();
7273 8 :
7274 8 : // Track when each page was last modified. Used to assert that
7275 8 : // a read sees the latest page version.
7276 8 : let mut updated = [Lsn(0); NUM_KEYS];
7277 8 :
7278 8 : let mut lsn = Lsn(0x10);
7279 : #[allow(clippy::needless_range_loop)]
7280 8008 : for blknum in 0..NUM_KEYS {
7281 8000 : lsn = Lsn(lsn.0 + 0x10);
7282 8000 : test_key.field6 = blknum as u32;
7283 8000 : let mut writer = tline.writer().await;
7284 8000 : writer
7285 8000 : .put(
7286 8000 : test_key,
7287 8000 : lsn,
7288 8000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7289 8000 : &ctx,
7290 8000 : )
7291 8000 : .await?;
7292 8000 : writer.finish_write(lsn);
7293 8000 : updated[blknum] = lsn;
7294 8000 : drop(writer);
7295 8000 :
7296 8000 : keyspace.add_key(test_key);
7297 : }
7298 :
7299 408 : for _ in 0..50 {
7300 400400 : for _ in 0..NUM_KEYS {
7301 400000 : lsn = Lsn(lsn.0 + 0x10);
7302 400000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7303 400000 : test_key.field6 = blknum as u32;
7304 400000 : let mut writer = tline.writer().await;
7305 400000 : writer
7306 400000 : .put(
7307 400000 : test_key,
7308 400000 : lsn,
7309 400000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7310 400000 : &ctx,
7311 400000 : )
7312 400000 : .await?;
7313 400000 : writer.finish_write(lsn);
7314 400000 : drop(writer);
7315 400000 : updated[blknum] = lsn;
7316 : }
7317 :
7318 : // Read all the blocks
7319 400000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7320 400000 : test_key.field6 = blknum as u32;
7321 400000 : assert_eq!(
7322 400000 : tline.get(test_key, lsn, &ctx).await?,
7323 400000 : test_img(&format!("{} at {}", blknum, last_lsn))
7324 : );
7325 : }
7326 :
7327 : // Perform a cycle of flush, and GC
7328 400 : tline.freeze_and_flush().await?;
7329 400 : tenant
7330 400 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7331 400 : .await?;
7332 : }
7333 :
7334 8 : Ok(())
7335 8 : }
7336 :
7337 : #[tokio::test]
7338 4 : async fn test_traverse_branches() -> anyhow::Result<()> {
7339 4 : let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
7340 4 : .await?
7341 4 : .load()
7342 4 : .await;
7343 4 : let mut tline = tenant
7344 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7345 4 : .await?;
7346 4 :
7347 4 : const NUM_KEYS: usize = 1000;
7348 4 :
7349 4 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7350 4 :
7351 4 : let mut keyspace = KeySpaceAccum::new();
7352 4 :
7353 4 : let cancel = CancellationToken::new();
7354 4 :
7355 4 : // Track when each page was last modified. Used to assert that
7356 4 : // a read sees the latest page version.
7357 4 : let mut updated = [Lsn(0); NUM_KEYS];
7358 4 :
7359 4 : let mut lsn = Lsn(0x10);
7360 4 : #[allow(clippy::needless_range_loop)]
7361 4004 : for blknum in 0..NUM_KEYS {
7362 4000 : lsn = Lsn(lsn.0 + 0x10);
7363 4000 : test_key.field6 = blknum as u32;
7364 4000 : let mut writer = tline.writer().await;
7365 4000 : writer
7366 4000 : .put(
7367 4000 : test_key,
7368 4000 : lsn,
7369 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7370 4000 : &ctx,
7371 4000 : )
7372 4000 : .await?;
7373 4000 : writer.finish_write(lsn);
7374 4000 : updated[blknum] = lsn;
7375 4000 : drop(writer);
7376 4000 :
7377 4000 : keyspace.add_key(test_key);
7378 4 : }
7379 4 :
7380 204 : for _ in 0..50 {
7381 200 : let new_tline_id = TimelineId::generate();
7382 200 : tenant
7383 200 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
7384 200 : .await?;
7385 200 : tline = tenant
7386 200 : .get_timeline(new_tline_id, true)
7387 200 : .expect("Should have the branched timeline");
7388 4 :
7389 200200 : for _ in 0..NUM_KEYS {
7390 200000 : lsn = Lsn(lsn.0 + 0x10);
7391 200000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7392 200000 : test_key.field6 = blknum as u32;
7393 200000 : let mut writer = tline.writer().await;
7394 200000 : writer
7395 200000 : .put(
7396 200000 : test_key,
7397 200000 : lsn,
7398 200000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7399 200000 : &ctx,
7400 200000 : )
7401 200000 : .await?;
7402 200000 : println!("updating {} at {}", blknum, lsn);
7403 200000 : writer.finish_write(lsn);
7404 200000 : drop(writer);
7405 200000 : updated[blknum] = lsn;
7406 4 : }
7407 4 :
7408 4 : // Read all the blocks
7409 200000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7410 200000 : test_key.field6 = blknum as u32;
7411 200000 : assert_eq!(
7412 200000 : tline.get(test_key, lsn, &ctx).await?,
7413 200000 : test_img(&format!("{} at {}", blknum, last_lsn))
7414 4 : );
7415 4 : }
7416 4 :
7417 4 : // Perform a cycle of flush, compact, and GC
7418 200 : tline.freeze_and_flush().await?;
7419 200 : tline
7420 200 : .compact(&cancel, CompactFlags::NoYield.into(), &ctx)
7421 200 : .await?;
7422 200 : tenant
7423 200 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7424 200 : .await?;
7425 4 : }
7426 4 :
7427 4 : Ok(())
7428 4 : }
7429 :
7430 : #[tokio::test]
7431 4 : async fn test_traverse_ancestors() -> anyhow::Result<()> {
7432 4 : let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
7433 4 : .await?
7434 4 : .load()
7435 4 : .await;
7436 4 : let mut tline = tenant
7437 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7438 4 : .await?;
7439 4 :
7440 4 : const NUM_KEYS: usize = 100;
7441 4 : const NUM_TLINES: usize = 50;
7442 4 :
7443 4 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7444 4 : // Track page mutation lsns across different timelines.
7445 4 : let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
7446 4 :
7447 4 : let mut lsn = Lsn(0x10);
7448 4 :
7449 4 : #[allow(clippy::needless_range_loop)]
7450 204 : for idx in 0..NUM_TLINES {
7451 200 : let new_tline_id = TimelineId::generate();
7452 200 : tenant
7453 200 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
7454 200 : .await?;
7455 200 : tline = tenant
7456 200 : .get_timeline(new_tline_id, true)
7457 200 : .expect("Should have the branched timeline");
7458 4 :
7459 20200 : for _ in 0..NUM_KEYS {
7460 20000 : lsn = Lsn(lsn.0 + 0x10);
7461 20000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7462 20000 : test_key.field6 = blknum as u32;
7463 20000 : let mut writer = tline.writer().await;
7464 20000 : writer
7465 20000 : .put(
7466 20000 : test_key,
7467 20000 : lsn,
7468 20000 : &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
7469 20000 : &ctx,
7470 20000 : )
7471 20000 : .await?;
7472 20000 : println!("updating [{}][{}] at {}", idx, blknum, lsn);
7473 20000 : writer.finish_write(lsn);
7474 20000 : drop(writer);
7475 20000 : updated[idx][blknum] = lsn;
7476 4 : }
7477 4 : }
7478 4 :
7479 4 : // Read pages from leaf timeline across all ancestors.
7480 200 : for (idx, lsns) in updated.iter().enumerate() {
7481 20000 : for (blknum, lsn) in lsns.iter().enumerate() {
7482 4 : // Skip empty mutations.
7483 20000 : if lsn.0 == 0 {
7484 7318 : continue;
7485 12682 : }
7486 12682 : println!("checking [{idx}][{blknum}] at {lsn}");
7487 12682 : test_key.field6 = blknum as u32;
7488 12682 : assert_eq!(
7489 12682 : tline.get(test_key, *lsn, &ctx).await?,
7490 12682 : test_img(&format!("{idx} {blknum} at {lsn}"))
7491 4 : );
7492 4 : }
7493 4 : }
7494 4 : Ok(())
7495 4 : }
7496 :
7497 : #[tokio::test]
7498 4 : async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
7499 4 : let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
7500 4 : .await?
7501 4 : .load()
7502 4 : .await;
7503 4 :
7504 4 : let initdb_lsn = Lsn(0x20);
7505 4 : let (utline, ctx) = tenant
7506 4 : .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
7507 4 : .await?;
7508 4 : let tline = utline.raw_timeline().unwrap();
7509 4 :
7510 4 : // Spawn flush loop now so that we can set the `expect_initdb_optimization`
7511 4 : tline.maybe_spawn_flush_loop();
7512 4 :
7513 4 : // Make sure the timeline has the minimum set of required keys for operation.
7514 4 : // The only operation you can always do on an empty timeline is to `put` new data.
7515 4 : // Except if you `put` at `initdb_lsn`.
7516 4 : // In that case, there's an optimization to directly create image layers instead of delta layers.
7517 4 : // It uses `repartition()`, which assumes some keys to be present.
7518 4 : // Let's make sure the test timeline can handle that case.
7519 4 : {
7520 4 : let mut state = tline.flush_loop_state.lock().unwrap();
7521 4 : assert_eq!(
7522 4 : timeline::FlushLoopState::Running {
7523 4 : expect_initdb_optimization: false,
7524 4 : initdb_optimization_count: 0,
7525 4 : },
7526 4 : *state
7527 4 : );
7528 4 : *state = timeline::FlushLoopState::Running {
7529 4 : expect_initdb_optimization: true,
7530 4 : initdb_optimization_count: 0,
7531 4 : };
7532 4 : }
7533 4 :
7534 4 : // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
7535 4 : // As explained above, the optimization requires some keys to be present.
7536 4 : // As per `create_empty_timeline` documentation, use init_empty to set them.
7537 4 : // This is what `create_test_timeline` does, by the way.
7538 4 : let mut modification = tline.begin_modification(initdb_lsn);
7539 4 : modification
7540 4 : .init_empty_test_timeline()
7541 4 : .context("init_empty_test_timeline")?;
7542 4 : modification
7543 4 : .commit(&ctx)
7544 4 : .await
7545 4 : .context("commit init_empty_test_timeline modification")?;
7546 4 :
7547 4 : // Do the flush. The flush code will check the expectations that we set above.
7548 4 : tline.freeze_and_flush().await?;
7549 4 :
7550 4 : // assert freeze_and_flush exercised the initdb optimization
7551 4 : {
7552 4 : let state = tline.flush_loop_state.lock().unwrap();
7553 4 : let timeline::FlushLoopState::Running {
7554 4 : expect_initdb_optimization,
7555 4 : initdb_optimization_count,
7556 4 : } = *state
7557 4 : else {
7558 4 : panic!("unexpected state: {:?}", *state);
7559 4 : };
7560 4 : assert!(expect_initdb_optimization);
7561 4 : assert!(initdb_optimization_count > 0);
7562 4 : }
7563 4 : Ok(())
7564 4 : }
7565 :
7566 : #[tokio::test]
7567 4 : async fn test_create_guard_crash() -> anyhow::Result<()> {
7568 4 : let name = "test_create_guard_crash";
7569 4 : let harness = TenantHarness::create(name).await?;
7570 4 : {
7571 4 : let (tenant, ctx) = harness.load().await;
7572 4 : let (tline, _ctx) = tenant
7573 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
7574 4 : .await?;
7575 4 : // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
7576 4 : let raw_tline = tline.raw_timeline().unwrap();
7577 4 : raw_tline
7578 4 : .shutdown(super::timeline::ShutdownMode::Hard)
7579 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))
7580 4 : .await;
7581 4 : std::mem::forget(tline);
7582 4 : }
7583 4 :
7584 4 : let (tenant, _) = harness.load().await;
7585 4 : match tenant.get_timeline(TIMELINE_ID, false) {
7586 4 : Ok(_) => panic!("timeline should've been removed during load"),
7587 4 : Err(e) => {
7588 4 : assert_eq!(
7589 4 : e,
7590 4 : GetTimelineError::NotFound {
7591 4 : tenant_id: tenant.tenant_shard_id,
7592 4 : timeline_id: TIMELINE_ID,
7593 4 : }
7594 4 : )
7595 4 : }
7596 4 : }
7597 4 :
7598 4 : assert!(
7599 4 : !harness
7600 4 : .conf
7601 4 : .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
7602 4 : .exists()
7603 4 : );
7604 4 :
7605 4 : Ok(())
7606 4 : }
7607 :
7608 : #[tokio::test]
7609 4 : async fn test_read_at_max_lsn() -> anyhow::Result<()> {
7610 4 : let names_algorithms = [
7611 4 : ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
7612 4 : ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
7613 4 : ];
7614 12 : for (name, algorithm) in names_algorithms {
7615 8 : test_read_at_max_lsn_algorithm(name, algorithm).await?;
7616 4 : }
7617 4 : Ok(())
7618 4 : }
7619 :
7620 8 : async fn test_read_at_max_lsn_algorithm(
7621 8 : name: &'static str,
7622 8 : compaction_algorithm: CompactionAlgorithm,
7623 8 : ) -> anyhow::Result<()> {
7624 8 : let mut harness = TenantHarness::create(name).await?;
7625 8 : harness.tenant_conf.compaction_algorithm = CompactionAlgorithmSettings {
7626 8 : kind: compaction_algorithm,
7627 8 : };
7628 8 : let (tenant, ctx) = harness.load().await;
7629 8 : let tline = tenant
7630 8 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
7631 8 : .await?;
7632 :
7633 8 : let lsn = Lsn(0x10);
7634 8 : let compact = false;
7635 8 : bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
7636 :
7637 8 : let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7638 8 : let read_lsn = Lsn(u64::MAX - 1);
7639 :
7640 8 : let result = tline.get(test_key, read_lsn, &ctx).await;
7641 8 : assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
7642 :
7643 8 : Ok(())
7644 8 : }
7645 :
7646 : #[tokio::test]
7647 4 : async fn test_metadata_scan() -> anyhow::Result<()> {
7648 4 : let harness = TenantHarness::create("test_metadata_scan").await?;
7649 4 : let (tenant, ctx) = harness.load().await;
7650 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7651 4 : let tline = tenant
7652 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7653 4 : .await?;
7654 4 :
7655 4 : const NUM_KEYS: usize = 1000;
7656 4 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
7657 4 :
7658 4 : let cancel = CancellationToken::new();
7659 4 :
7660 4 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7661 4 : base_key.field1 = AUX_KEY_PREFIX;
7662 4 : let mut test_key = base_key;
7663 4 :
7664 4 : // Track when each page was last modified. Used to assert that
7665 4 : // a read sees the latest page version.
7666 4 : let mut updated = [Lsn(0); NUM_KEYS];
7667 4 :
7668 4 : let mut lsn = Lsn(0x10);
7669 4 : #[allow(clippy::needless_range_loop)]
7670 4004 : for blknum in 0..NUM_KEYS {
7671 4000 : lsn = Lsn(lsn.0 + 0x10);
7672 4000 : test_key.field6 = (blknum * STEP) as u32;
7673 4000 : let mut writer = tline.writer().await;
7674 4000 : writer
7675 4000 : .put(
7676 4000 : test_key,
7677 4000 : lsn,
7678 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7679 4000 : &ctx,
7680 4000 : )
7681 4000 : .await?;
7682 4000 : writer.finish_write(lsn);
7683 4000 : updated[blknum] = lsn;
7684 4000 : drop(writer);
7685 4 : }
7686 4 :
7687 4 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
7688 4 :
7689 48 : for iter in 0..=10 {
7690 4 : // Read all the blocks
7691 44000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7692 44000 : test_key.field6 = (blknum * STEP) as u32;
7693 44000 : assert_eq!(
7694 44000 : tline.get(test_key, lsn, &ctx).await?,
7695 44000 : test_img(&format!("{} at {}", blknum, last_lsn))
7696 4 : );
7697 4 : }
7698 4 :
7699 44 : let mut cnt = 0;
7700 44000 : for (key, value) in tline
7701 44 : .get_vectored_impl(
7702 44 : keyspace.clone(),
7703 44 : lsn,
7704 44 : &mut ValuesReconstructState::new(io_concurrency.clone()),
7705 44 : &ctx,
7706 44 : )
7707 44 : .await?
7708 4 : {
7709 44000 : let blknum = key.field6 as usize;
7710 44000 : let value = value?;
7711 44000 : assert!(blknum % STEP == 0);
7712 44000 : let blknum = blknum / STEP;
7713 44000 : assert_eq!(
7714 44000 : value,
7715 44000 : test_img(&format!("{} at {}", blknum, updated[blknum]))
7716 44000 : );
7717 44000 : cnt += 1;
7718 4 : }
7719 4 :
7720 44 : assert_eq!(cnt, NUM_KEYS);
7721 4 :
7722 44044 : for _ in 0..NUM_KEYS {
7723 44000 : lsn = Lsn(lsn.0 + 0x10);
7724 44000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7725 44000 : test_key.field6 = (blknum * STEP) as u32;
7726 44000 : let mut writer = tline.writer().await;
7727 44000 : writer
7728 44000 : .put(
7729 44000 : test_key,
7730 44000 : lsn,
7731 44000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7732 44000 : &ctx,
7733 44000 : )
7734 44000 : .await?;
7735 44000 : writer.finish_write(lsn);
7736 44000 : drop(writer);
7737 44000 : updated[blknum] = lsn;
7738 4 : }
7739 4 :
7740 4 : // Perform two cycles of flush, compact, and GC
7741 132 : for round in 0..2 {
7742 88 : tline.freeze_and_flush().await?;
7743 88 : tline
7744 88 : .compact(
7745 88 : &cancel,
7746 88 : if iter % 5 == 0 && round == 0 {
7747 12 : let mut flags = EnumSet::new();
7748 12 : flags.insert(CompactFlags::ForceImageLayerCreation);
7749 12 : flags.insert(CompactFlags::ForceRepartition);
7750 12 : flags.insert(CompactFlags::NoYield);
7751 12 : flags
7752 4 : } else {
7753 76 : EnumSet::empty()
7754 4 : },
7755 88 : &ctx,
7756 88 : )
7757 88 : .await?;
7758 88 : tenant
7759 88 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7760 88 : .await?;
7761 4 : }
7762 4 : }
7763 4 :
7764 4 : Ok(())
7765 4 : }
7766 :
7767 : #[tokio::test]
7768 4 : async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
7769 4 : let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
7770 4 : let (tenant, ctx) = harness.load().await;
7771 4 : let tline = tenant
7772 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7773 4 : .await?;
7774 4 :
7775 4 : let cancel = CancellationToken::new();
7776 4 :
7777 4 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7778 4 : base_key.field1 = AUX_KEY_PREFIX;
7779 4 : let test_key = base_key;
7780 4 : let mut lsn = Lsn(0x10);
7781 4 :
7782 84 : for _ in 0..20 {
7783 80 : lsn = Lsn(lsn.0 + 0x10);
7784 80 : let mut writer = tline.writer().await;
7785 80 : writer
7786 80 : .put(
7787 80 : test_key,
7788 80 : lsn,
7789 80 : &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
7790 80 : &ctx,
7791 80 : )
7792 80 : .await?;
7793 80 : writer.finish_write(lsn);
7794 80 : drop(writer);
7795 80 : tline.freeze_and_flush().await?; // force create a delta layer
7796 4 : }
7797 4 :
7798 4 : let before_num_l0_delta_files =
7799 4 : tline.layers.read().await.layer_map()?.level0_deltas().len();
7800 4 :
7801 4 : tline
7802 4 : .compact(&cancel, CompactFlags::NoYield.into(), &ctx)
7803 4 : .await?;
7804 4 :
7805 4 : let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
7806 4 :
7807 4 : assert!(
7808 4 : after_num_l0_delta_files < before_num_l0_delta_files,
7809 4 : "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
7810 4 : );
7811 4 :
7812 4 : assert_eq!(
7813 4 : tline.get(test_key, lsn, &ctx).await?,
7814 4 : test_img(&format!("{} at {}", 0, lsn))
7815 4 : );
7816 4 :
7817 4 : Ok(())
7818 4 : }
7819 :
7820 : #[tokio::test]
7821 4 : async fn test_aux_file_e2e() {
7822 4 : let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
7823 4 :
7824 4 : let (tenant, ctx) = harness.load().await;
7825 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7826 4 :
7827 4 : let mut lsn = Lsn(0x08);
7828 4 :
7829 4 : let tline: Arc<Timeline> = tenant
7830 4 : .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
7831 4 : .await
7832 4 : .unwrap();
7833 4 :
7834 4 : {
7835 4 : lsn += 8;
7836 4 : let mut modification = tline.begin_modification(lsn);
7837 4 : modification
7838 4 : .put_file("pg_logical/mappings/test1", b"first", &ctx)
7839 4 : .await
7840 4 : .unwrap();
7841 4 : modification.commit(&ctx).await.unwrap();
7842 4 : }
7843 4 :
7844 4 : // we can read everything from the storage
7845 4 : let files = tline
7846 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7847 4 : .await
7848 4 : .unwrap();
7849 4 : assert_eq!(
7850 4 : files.get("pg_logical/mappings/test1"),
7851 4 : Some(&bytes::Bytes::from_static(b"first"))
7852 4 : );
7853 4 :
7854 4 : {
7855 4 : lsn += 8;
7856 4 : let mut modification = tline.begin_modification(lsn);
7857 4 : modification
7858 4 : .put_file("pg_logical/mappings/test2", b"second", &ctx)
7859 4 : .await
7860 4 : .unwrap();
7861 4 : modification.commit(&ctx).await.unwrap();
7862 4 : }
7863 4 :
7864 4 : let files = tline
7865 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7866 4 : .await
7867 4 : .unwrap();
7868 4 : assert_eq!(
7869 4 : files.get("pg_logical/mappings/test2"),
7870 4 : Some(&bytes::Bytes::from_static(b"second"))
7871 4 : );
7872 4 :
7873 4 : let child = tenant
7874 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
7875 4 : .await
7876 4 : .unwrap();
7877 4 :
7878 4 : let files = child
7879 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7880 4 : .await
7881 4 : .unwrap();
7882 4 : assert_eq!(files.get("pg_logical/mappings/test1"), None);
7883 4 : assert_eq!(files.get("pg_logical/mappings/test2"), None);
7884 4 : }
7885 :
7886 : #[tokio::test]
7887 4 : async fn test_metadata_image_creation() -> anyhow::Result<()> {
7888 4 : let harness = TenantHarness::create("test_metadata_image_creation").await?;
7889 4 : let (tenant, ctx) = harness.load().await;
7890 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7891 4 : let tline = tenant
7892 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7893 4 : .await?;
7894 4 :
7895 4 : const NUM_KEYS: usize = 1000;
7896 4 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
7897 4 :
7898 4 : let cancel = CancellationToken::new();
7899 4 :
7900 4 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
7901 4 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
7902 4 : let mut test_key = base_key;
7903 4 : let mut lsn = Lsn(0x10);
7904 4 :
7905 16 : async fn scan_with_statistics(
7906 16 : tline: &Timeline,
7907 16 : keyspace: &KeySpace,
7908 16 : lsn: Lsn,
7909 16 : ctx: &RequestContext,
7910 16 : io_concurrency: IoConcurrency,
7911 16 : ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
7912 16 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
7913 16 : let res = tline
7914 16 : .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
7915 16 : .await?;
7916 16 : Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
7917 16 : }
7918 4 :
7919 4004 : for blknum in 0..NUM_KEYS {
7920 4000 : lsn = Lsn(lsn.0 + 0x10);
7921 4000 : test_key.field6 = (blknum * STEP) as u32;
7922 4000 : let mut writer = tline.writer().await;
7923 4000 : writer
7924 4000 : .put(
7925 4000 : test_key,
7926 4000 : lsn,
7927 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7928 4000 : &ctx,
7929 4000 : )
7930 4000 : .await?;
7931 4000 : writer.finish_write(lsn);
7932 4000 : drop(writer);
7933 4 : }
7934 4 :
7935 4 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
7936 4 :
7937 44 : for iter in 1..=10 {
7938 40040 : for _ in 0..NUM_KEYS {
7939 40000 : lsn = Lsn(lsn.0 + 0x10);
7940 40000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7941 40000 : test_key.field6 = (blknum * STEP) as u32;
7942 40000 : let mut writer = tline.writer().await;
7943 40000 : writer
7944 40000 : .put(
7945 40000 : test_key,
7946 40000 : lsn,
7947 40000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7948 40000 : &ctx,
7949 40000 : )
7950 40000 : .await?;
7951 40000 : writer.finish_write(lsn);
7952 40000 : drop(writer);
7953 4 : }
7954 4 :
7955 40 : tline.freeze_and_flush().await?;
7956 4 :
7957 40 : if iter % 5 == 0 {
7958 8 : let (_, before_delta_file_accessed) =
7959 8 : scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
7960 8 : .await?;
7961 8 : tline
7962 8 : .compact(
7963 8 : &cancel,
7964 8 : {
7965 8 : let mut flags = EnumSet::new();
7966 8 : flags.insert(CompactFlags::ForceImageLayerCreation);
7967 8 : flags.insert(CompactFlags::ForceRepartition);
7968 8 : flags.insert(CompactFlags::NoYield);
7969 8 : flags
7970 8 : },
7971 8 : &ctx,
7972 8 : )
7973 8 : .await?;
7974 8 : let (_, after_delta_file_accessed) =
7975 8 : scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
7976 8 : .await?;
7977 8 : assert!(
7978 8 : after_delta_file_accessed < before_delta_file_accessed,
7979 4 : "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
7980 4 : );
7981 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.
7982 8 : assert!(
7983 8 : after_delta_file_accessed <= 2,
7984 4 : "after_delta_file_accessed={after_delta_file_accessed}"
7985 4 : );
7986 32 : }
7987 4 : }
7988 4 :
7989 4 : Ok(())
7990 4 : }
7991 :
7992 : #[tokio::test]
7993 4 : async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
7994 4 : let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
7995 4 : let (tenant, ctx) = harness.load().await;
7996 4 :
7997 4 : let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7998 4 : let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
7999 4 : let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
8000 4 :
8001 4 : let tline = tenant
8002 4 : .create_test_timeline_with_layers(
8003 4 : TIMELINE_ID,
8004 4 : Lsn(0x10),
8005 4 : DEFAULT_PG_VERSION,
8006 4 : &ctx,
8007 4 : Vec::new(), // in-memory layers
8008 4 : Vec::new(), // delta layers
8009 4 : vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
8010 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
8011 4 : )
8012 4 : .await?;
8013 4 : tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
8014 4 :
8015 4 : let child = tenant
8016 4 : .branch_timeline_test_with_layers(
8017 4 : &tline,
8018 4 : NEW_TIMELINE_ID,
8019 4 : Some(Lsn(0x20)),
8020 4 : &ctx,
8021 4 : Vec::new(), // delta layers
8022 4 : vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
8023 4 : Lsn(0x30),
8024 4 : )
8025 4 : .await
8026 4 : .unwrap();
8027 4 :
8028 4 : let lsn = Lsn(0x30);
8029 4 :
8030 4 : // test vectored get on parent timeline
8031 4 : assert_eq!(
8032 4 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
8033 4 : Some(test_img("data key 1"))
8034 4 : );
8035 4 : assert!(
8036 4 : get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
8037 4 : .await
8038 4 : .unwrap_err()
8039 4 : .is_missing_key_error()
8040 4 : );
8041 4 : assert!(
8042 4 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
8043 4 : .await
8044 4 : .unwrap_err()
8045 4 : .is_missing_key_error()
8046 4 : );
8047 4 :
8048 4 : // test vectored get on child timeline
8049 4 : assert_eq!(
8050 4 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
8051 4 : Some(test_img("data key 1"))
8052 4 : );
8053 4 : assert_eq!(
8054 4 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
8055 4 : Some(test_img("data key 2"))
8056 4 : );
8057 4 : assert!(
8058 4 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
8059 4 : .await
8060 4 : .unwrap_err()
8061 4 : .is_missing_key_error()
8062 4 : );
8063 4 :
8064 4 : Ok(())
8065 4 : }
8066 :
8067 : #[tokio::test]
8068 4 : async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
8069 4 : let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
8070 4 : let (tenant, ctx) = harness.load().await;
8071 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8072 4 :
8073 4 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8074 4 : let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
8075 4 : let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
8076 4 : let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
8077 4 :
8078 4 : let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
8079 4 : let base_inherited_key_child =
8080 4 : Key::from_hex("610000000033333333444444445500000001").unwrap();
8081 4 : let base_inherited_key_nonexist =
8082 4 : Key::from_hex("610000000033333333444444445500000002").unwrap();
8083 4 : let base_inherited_key_overwrite =
8084 4 : Key::from_hex("610000000033333333444444445500000003").unwrap();
8085 4 :
8086 4 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
8087 4 : assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
8088 4 :
8089 4 : let tline = tenant
8090 4 : .create_test_timeline_with_layers(
8091 4 : TIMELINE_ID,
8092 4 : Lsn(0x10),
8093 4 : DEFAULT_PG_VERSION,
8094 4 : &ctx,
8095 4 : Vec::new(), // in-memory layers
8096 4 : Vec::new(), // delta layers
8097 4 : vec![(
8098 4 : Lsn(0x20),
8099 4 : vec![
8100 4 : (base_inherited_key, test_img("metadata inherited key 1")),
8101 4 : (
8102 4 : base_inherited_key_overwrite,
8103 4 : test_img("metadata key overwrite 1a"),
8104 4 : ),
8105 4 : (base_key, test_img("metadata key 1")),
8106 4 : (base_key_overwrite, test_img("metadata key overwrite 1b")),
8107 4 : ],
8108 4 : )], // image layers
8109 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
8110 4 : )
8111 4 : .await?;
8112 4 :
8113 4 : let child = tenant
8114 4 : .branch_timeline_test_with_layers(
8115 4 : &tline,
8116 4 : NEW_TIMELINE_ID,
8117 4 : Some(Lsn(0x20)),
8118 4 : &ctx,
8119 4 : Vec::new(), // delta layers
8120 4 : vec![(
8121 4 : Lsn(0x30),
8122 4 : vec![
8123 4 : (
8124 4 : base_inherited_key_child,
8125 4 : test_img("metadata inherited key 2"),
8126 4 : ),
8127 4 : (
8128 4 : base_inherited_key_overwrite,
8129 4 : test_img("metadata key overwrite 2a"),
8130 4 : ),
8131 4 : (base_key_child, test_img("metadata key 2")),
8132 4 : (base_key_overwrite, test_img("metadata key overwrite 2b")),
8133 4 : ],
8134 4 : )], // image layers
8135 4 : Lsn(0x30),
8136 4 : )
8137 4 : .await
8138 4 : .unwrap();
8139 4 :
8140 4 : let lsn = Lsn(0x30);
8141 4 :
8142 4 : // test vectored get on parent timeline
8143 4 : assert_eq!(
8144 4 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
8145 4 : Some(test_img("metadata key 1"))
8146 4 : );
8147 4 : assert_eq!(
8148 4 : get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
8149 4 : None
8150 4 : );
8151 4 : assert_eq!(
8152 4 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
8153 4 : None
8154 4 : );
8155 4 : assert_eq!(
8156 4 : get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
8157 4 : Some(test_img("metadata key overwrite 1b"))
8158 4 : );
8159 4 : assert_eq!(
8160 4 : get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
8161 4 : Some(test_img("metadata inherited key 1"))
8162 4 : );
8163 4 : assert_eq!(
8164 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
8165 4 : None
8166 4 : );
8167 4 : assert_eq!(
8168 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
8169 4 : None
8170 4 : );
8171 4 : assert_eq!(
8172 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
8173 4 : Some(test_img("metadata key overwrite 1a"))
8174 4 : );
8175 4 :
8176 4 : // test vectored get on child timeline
8177 4 : assert_eq!(
8178 4 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
8179 4 : None
8180 4 : );
8181 4 : assert_eq!(
8182 4 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
8183 4 : Some(test_img("metadata key 2"))
8184 4 : );
8185 4 : assert_eq!(
8186 4 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
8187 4 : None
8188 4 : );
8189 4 : assert_eq!(
8190 4 : get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
8191 4 : Some(test_img("metadata inherited key 1"))
8192 4 : );
8193 4 : assert_eq!(
8194 4 : get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
8195 4 : Some(test_img("metadata inherited key 2"))
8196 4 : );
8197 4 : assert_eq!(
8198 4 : get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
8199 4 : None
8200 4 : );
8201 4 : assert_eq!(
8202 4 : get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
8203 4 : Some(test_img("metadata key overwrite 2b"))
8204 4 : );
8205 4 : assert_eq!(
8206 4 : get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
8207 4 : Some(test_img("metadata key overwrite 2a"))
8208 4 : );
8209 4 :
8210 4 : // test vectored scan on parent timeline
8211 4 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
8212 4 : let res = tline
8213 4 : .get_vectored_impl(
8214 4 : KeySpace::single(Key::metadata_key_range()),
8215 4 : lsn,
8216 4 : &mut reconstruct_state,
8217 4 : &ctx,
8218 4 : )
8219 4 : .await?;
8220 4 :
8221 4 : assert_eq!(
8222 4 : res.into_iter()
8223 16 : .map(|(k, v)| (k, v.unwrap()))
8224 4 : .collect::<Vec<_>>(),
8225 4 : vec![
8226 4 : (base_inherited_key, test_img("metadata inherited key 1")),
8227 4 : (
8228 4 : base_inherited_key_overwrite,
8229 4 : test_img("metadata key overwrite 1a")
8230 4 : ),
8231 4 : (base_key, test_img("metadata key 1")),
8232 4 : (base_key_overwrite, test_img("metadata key overwrite 1b")),
8233 4 : ]
8234 4 : );
8235 4 :
8236 4 : // test vectored scan on child timeline
8237 4 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
8238 4 : let res = child
8239 4 : .get_vectored_impl(
8240 4 : KeySpace::single(Key::metadata_key_range()),
8241 4 : lsn,
8242 4 : &mut reconstruct_state,
8243 4 : &ctx,
8244 4 : )
8245 4 : .await?;
8246 4 :
8247 4 : assert_eq!(
8248 4 : res.into_iter()
8249 20 : .map(|(k, v)| (k, v.unwrap()))
8250 4 : .collect::<Vec<_>>(),
8251 4 : vec![
8252 4 : (base_inherited_key, test_img("metadata inherited key 1")),
8253 4 : (
8254 4 : base_inherited_key_child,
8255 4 : test_img("metadata inherited key 2")
8256 4 : ),
8257 4 : (
8258 4 : base_inherited_key_overwrite,
8259 4 : test_img("metadata key overwrite 2a")
8260 4 : ),
8261 4 : (base_key_child, test_img("metadata key 2")),
8262 4 : (base_key_overwrite, test_img("metadata key overwrite 2b")),
8263 4 : ]
8264 4 : );
8265 4 :
8266 4 : Ok(())
8267 4 : }
8268 :
8269 112 : async fn get_vectored_impl_wrapper(
8270 112 : tline: &Arc<Timeline>,
8271 112 : key: Key,
8272 112 : lsn: Lsn,
8273 112 : ctx: &RequestContext,
8274 112 : ) -> Result<Option<Bytes>, GetVectoredError> {
8275 112 : let io_concurrency =
8276 112 : IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
8277 112 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
8278 112 : let mut res = tline
8279 112 : .get_vectored_impl(
8280 112 : KeySpace::single(key..key.next()),
8281 112 : lsn,
8282 112 : &mut reconstruct_state,
8283 112 : ctx,
8284 112 : )
8285 112 : .await?;
8286 100 : Ok(res.pop_last().map(|(k, v)| {
8287 64 : assert_eq!(k, key);
8288 64 : v.unwrap()
8289 100 : }))
8290 112 : }
8291 :
8292 : #[tokio::test]
8293 4 : async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
8294 4 : let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
8295 4 : let (tenant, ctx) = harness.load().await;
8296 4 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
8297 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8298 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8299 4 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
8300 4 :
8301 4 : // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
8302 4 : // Lsn 0x30 key0, key3, no key1+key2
8303 4 : // Lsn 0x20 key1+key2 tomestones
8304 4 : // Lsn 0x10 key1 in image, key2 in delta
8305 4 : let tline = tenant
8306 4 : .create_test_timeline_with_layers(
8307 4 : TIMELINE_ID,
8308 4 : Lsn(0x10),
8309 4 : DEFAULT_PG_VERSION,
8310 4 : &ctx,
8311 4 : Vec::new(), // in-memory layers
8312 4 : // delta layers
8313 4 : vec![
8314 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8315 4 : Lsn(0x10)..Lsn(0x20),
8316 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8317 4 : ),
8318 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8319 4 : Lsn(0x20)..Lsn(0x30),
8320 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8321 4 : ),
8322 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8323 4 : Lsn(0x20)..Lsn(0x30),
8324 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8325 4 : ),
8326 4 : ],
8327 4 : // image layers
8328 4 : vec![
8329 4 : (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
8330 4 : (
8331 4 : Lsn(0x30),
8332 4 : vec![
8333 4 : (key0, test_img("metadata key 0")),
8334 4 : (key3, test_img("metadata key 3")),
8335 4 : ],
8336 4 : ),
8337 4 : ],
8338 4 : Lsn(0x30),
8339 4 : )
8340 4 : .await?;
8341 4 :
8342 4 : let lsn = Lsn(0x30);
8343 4 : let old_lsn = Lsn(0x20);
8344 4 :
8345 4 : assert_eq!(
8346 4 : get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
8347 4 : Some(test_img("metadata key 0"))
8348 4 : );
8349 4 : assert_eq!(
8350 4 : get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
8351 4 : None,
8352 4 : );
8353 4 : assert_eq!(
8354 4 : get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
8355 4 : None,
8356 4 : );
8357 4 : assert_eq!(
8358 4 : get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
8359 4 : Some(Bytes::new()),
8360 4 : );
8361 4 : assert_eq!(
8362 4 : get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
8363 4 : Some(Bytes::new()),
8364 4 : );
8365 4 : assert_eq!(
8366 4 : get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
8367 4 : Some(test_img("metadata key 3"))
8368 4 : );
8369 4 :
8370 4 : Ok(())
8371 4 : }
8372 :
8373 : #[tokio::test]
8374 4 : async fn test_metadata_tombstone_image_creation() {
8375 4 : let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
8376 4 : .await
8377 4 : .unwrap();
8378 4 : let (tenant, ctx) = harness.load().await;
8379 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8380 4 :
8381 4 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
8382 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8383 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8384 4 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
8385 4 :
8386 4 : let tline = tenant
8387 4 : .create_test_timeline_with_layers(
8388 4 : TIMELINE_ID,
8389 4 : Lsn(0x10),
8390 4 : DEFAULT_PG_VERSION,
8391 4 : &ctx,
8392 4 : Vec::new(), // in-memory layers
8393 4 : // delta layers
8394 4 : vec![
8395 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8396 4 : Lsn(0x10)..Lsn(0x20),
8397 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8398 4 : ),
8399 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8400 4 : Lsn(0x20)..Lsn(0x30),
8401 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8402 4 : ),
8403 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8404 4 : Lsn(0x20)..Lsn(0x30),
8405 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8406 4 : ),
8407 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8408 4 : Lsn(0x30)..Lsn(0x40),
8409 4 : vec![
8410 4 : (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
8411 4 : (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
8412 4 : ],
8413 4 : ),
8414 4 : ],
8415 4 : // image layers
8416 4 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
8417 4 : Lsn(0x40),
8418 4 : )
8419 4 : .await
8420 4 : .unwrap();
8421 4 :
8422 4 : let cancel = CancellationToken::new();
8423 4 :
8424 4 : tline
8425 4 : .compact(
8426 4 : &cancel,
8427 4 : {
8428 4 : let mut flags = EnumSet::new();
8429 4 : flags.insert(CompactFlags::ForceImageLayerCreation);
8430 4 : flags.insert(CompactFlags::ForceRepartition);
8431 4 : flags.insert(CompactFlags::NoYield);
8432 4 : flags
8433 4 : },
8434 4 : &ctx,
8435 4 : )
8436 4 : .await
8437 4 : .unwrap();
8438 4 :
8439 4 : // Image layers are created at last_record_lsn
8440 4 : let images = tline
8441 4 : .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
8442 4 : .await
8443 4 : .unwrap()
8444 4 : .into_iter()
8445 36 : .filter(|(k, _)| k.is_metadata_key())
8446 4 : .collect::<Vec<_>>();
8447 4 : assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
8448 4 : }
8449 :
8450 : #[tokio::test]
8451 4 : async fn test_metadata_tombstone_empty_image_creation() {
8452 4 : let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
8453 4 : .await
8454 4 : .unwrap();
8455 4 : let (tenant, ctx) = harness.load().await;
8456 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8457 4 :
8458 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8459 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8460 4 :
8461 4 : let tline = tenant
8462 4 : .create_test_timeline_with_layers(
8463 4 : TIMELINE_ID,
8464 4 : Lsn(0x10),
8465 4 : DEFAULT_PG_VERSION,
8466 4 : &ctx,
8467 4 : Vec::new(), // in-memory layers
8468 4 : // delta layers
8469 4 : vec![
8470 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8471 4 : Lsn(0x10)..Lsn(0x20),
8472 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8473 4 : ),
8474 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8475 4 : Lsn(0x20)..Lsn(0x30),
8476 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8477 4 : ),
8478 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8479 4 : Lsn(0x20)..Lsn(0x30),
8480 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8481 4 : ),
8482 4 : ],
8483 4 : // image layers
8484 4 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
8485 4 : Lsn(0x30),
8486 4 : )
8487 4 : .await
8488 4 : .unwrap();
8489 4 :
8490 4 : let cancel = CancellationToken::new();
8491 4 :
8492 4 : tline
8493 4 : .compact(
8494 4 : &cancel,
8495 4 : {
8496 4 : let mut flags = EnumSet::new();
8497 4 : flags.insert(CompactFlags::ForceImageLayerCreation);
8498 4 : flags.insert(CompactFlags::ForceRepartition);
8499 4 : flags.insert(CompactFlags::NoYield);
8500 4 : flags
8501 4 : },
8502 4 : &ctx,
8503 4 : )
8504 4 : .await
8505 4 : .unwrap();
8506 4 :
8507 4 : // Image layers are created at last_record_lsn
8508 4 : let images = tline
8509 4 : .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
8510 4 : .await
8511 4 : .unwrap()
8512 4 : .into_iter()
8513 28 : .filter(|(k, _)| k.is_metadata_key())
8514 4 : .collect::<Vec<_>>();
8515 4 : assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
8516 4 : }
8517 :
8518 : #[tokio::test]
8519 4 : async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
8520 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
8521 4 : let (tenant, ctx) = harness.load().await;
8522 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8523 4 :
8524 204 : fn get_key(id: u32) -> Key {
8525 204 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8526 204 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8527 204 : key.field6 = id;
8528 204 : key
8529 204 : }
8530 4 :
8531 4 : // We create
8532 4 : // - one bottom-most image layer,
8533 4 : // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
8534 4 : // - a delta layer D2 crossing the GC horizon with data only below the horizon,
8535 4 : // - a delta layer D3 above the horizon.
8536 4 : //
8537 4 : // | D3 |
8538 4 : // | D1 |
8539 4 : // -| |-- gc horizon -----------------
8540 4 : // | | | D2 |
8541 4 : // --------- img layer ------------------
8542 4 : //
8543 4 : // What we should expact from this compaction is:
8544 4 : // | D3 |
8545 4 : // | Part of D1 |
8546 4 : // --------- img layer with D1+D2 at GC horizon------------------
8547 4 :
8548 4 : // img layer at 0x10
8549 4 : let img_layer = (0..10)
8550 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
8551 4 : .collect_vec();
8552 4 :
8553 4 : let delta1 = vec![
8554 4 : (
8555 4 : get_key(1),
8556 4 : Lsn(0x20),
8557 4 : Value::Image(Bytes::from("value 1@0x20")),
8558 4 : ),
8559 4 : (
8560 4 : get_key(2),
8561 4 : Lsn(0x30),
8562 4 : Value::Image(Bytes::from("value 2@0x30")),
8563 4 : ),
8564 4 : (
8565 4 : get_key(3),
8566 4 : Lsn(0x40),
8567 4 : Value::Image(Bytes::from("value 3@0x40")),
8568 4 : ),
8569 4 : ];
8570 4 : let delta2 = vec![
8571 4 : (
8572 4 : get_key(5),
8573 4 : Lsn(0x20),
8574 4 : Value::Image(Bytes::from("value 5@0x20")),
8575 4 : ),
8576 4 : (
8577 4 : get_key(6),
8578 4 : Lsn(0x20),
8579 4 : Value::Image(Bytes::from("value 6@0x20")),
8580 4 : ),
8581 4 : ];
8582 4 : let delta3 = vec![
8583 4 : (
8584 4 : get_key(8),
8585 4 : Lsn(0x48),
8586 4 : Value::Image(Bytes::from("value 8@0x48")),
8587 4 : ),
8588 4 : (
8589 4 : get_key(9),
8590 4 : Lsn(0x48),
8591 4 : Value::Image(Bytes::from("value 9@0x48")),
8592 4 : ),
8593 4 : ];
8594 4 :
8595 4 : let tline = tenant
8596 4 : .create_test_timeline_with_layers(
8597 4 : TIMELINE_ID,
8598 4 : Lsn(0x10),
8599 4 : DEFAULT_PG_VERSION,
8600 4 : &ctx,
8601 4 : Vec::new(), // in-memory layers
8602 4 : vec![
8603 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
8604 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
8605 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
8606 4 : ], // delta layers
8607 4 : vec![(Lsn(0x10), img_layer)], // image layers
8608 4 : Lsn(0x50),
8609 4 : )
8610 4 : .await?;
8611 4 : {
8612 4 : tline
8613 4 : .applied_gc_cutoff_lsn
8614 4 : .lock_for_write()
8615 4 : .store_and_unlock(Lsn(0x30))
8616 4 : .wait()
8617 4 : .await;
8618 4 : // Update GC info
8619 4 : let mut guard = tline.gc_info.write().unwrap();
8620 4 : guard.cutoffs.time = Lsn(0x30);
8621 4 : guard.cutoffs.space = Lsn(0x30);
8622 4 : }
8623 4 :
8624 4 : let expected_result = [
8625 4 : Bytes::from_static(b"value 0@0x10"),
8626 4 : Bytes::from_static(b"value 1@0x20"),
8627 4 : Bytes::from_static(b"value 2@0x30"),
8628 4 : Bytes::from_static(b"value 3@0x40"),
8629 4 : Bytes::from_static(b"value 4@0x10"),
8630 4 : Bytes::from_static(b"value 5@0x20"),
8631 4 : Bytes::from_static(b"value 6@0x20"),
8632 4 : Bytes::from_static(b"value 7@0x10"),
8633 4 : Bytes::from_static(b"value 8@0x48"),
8634 4 : Bytes::from_static(b"value 9@0x48"),
8635 4 : ];
8636 4 :
8637 40 : for (idx, expected) in expected_result.iter().enumerate() {
8638 40 : assert_eq!(
8639 40 : tline
8640 40 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8641 40 : .await
8642 40 : .unwrap(),
8643 4 : expected
8644 4 : );
8645 4 : }
8646 4 :
8647 4 : let cancel = CancellationToken::new();
8648 4 : tline
8649 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8650 4 : .await
8651 4 : .unwrap();
8652 4 :
8653 40 : for (idx, expected) in expected_result.iter().enumerate() {
8654 40 : assert_eq!(
8655 40 : tline
8656 40 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8657 40 : .await
8658 40 : .unwrap(),
8659 4 : expected
8660 4 : );
8661 4 : }
8662 4 :
8663 4 : // Check if the image layer at the GC horizon contains exactly what we want
8664 4 : let image_at_gc_horizon = tline
8665 4 : .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
8666 4 : .await
8667 4 : .unwrap()
8668 4 : .into_iter()
8669 68 : .filter(|(k, _)| k.is_metadata_key())
8670 4 : .collect::<Vec<_>>();
8671 4 :
8672 4 : assert_eq!(image_at_gc_horizon.len(), 10);
8673 4 : let expected_result = [
8674 4 : Bytes::from_static(b"value 0@0x10"),
8675 4 : Bytes::from_static(b"value 1@0x20"),
8676 4 : Bytes::from_static(b"value 2@0x30"),
8677 4 : Bytes::from_static(b"value 3@0x10"),
8678 4 : Bytes::from_static(b"value 4@0x10"),
8679 4 : Bytes::from_static(b"value 5@0x20"),
8680 4 : Bytes::from_static(b"value 6@0x20"),
8681 4 : Bytes::from_static(b"value 7@0x10"),
8682 4 : Bytes::from_static(b"value 8@0x10"),
8683 4 : Bytes::from_static(b"value 9@0x10"),
8684 4 : ];
8685 44 : for idx in 0..10 {
8686 40 : assert_eq!(
8687 40 : image_at_gc_horizon[idx],
8688 40 : (get_key(idx as u32), expected_result[idx].clone())
8689 40 : );
8690 4 : }
8691 4 :
8692 4 : // Check if old layers are removed / new layers have the expected LSN
8693 4 : let all_layers = inspect_and_sort(&tline, None).await;
8694 4 : assert_eq!(
8695 4 : all_layers,
8696 4 : vec![
8697 4 : // Image layer at GC horizon
8698 4 : PersistentLayerKey {
8699 4 : key_range: Key::MIN..Key::MAX,
8700 4 : lsn_range: Lsn(0x30)..Lsn(0x31),
8701 4 : is_delta: false
8702 4 : },
8703 4 : // The delta layer below the horizon
8704 4 : PersistentLayerKey {
8705 4 : key_range: get_key(3)..get_key(4),
8706 4 : lsn_range: Lsn(0x30)..Lsn(0x48),
8707 4 : is_delta: true
8708 4 : },
8709 4 : // The delta3 layer that should not be picked for the compaction
8710 4 : PersistentLayerKey {
8711 4 : key_range: get_key(8)..get_key(10),
8712 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
8713 4 : is_delta: true
8714 4 : }
8715 4 : ]
8716 4 : );
8717 4 :
8718 4 : // increase GC horizon and compact again
8719 4 : {
8720 4 : tline
8721 4 : .applied_gc_cutoff_lsn
8722 4 : .lock_for_write()
8723 4 : .store_and_unlock(Lsn(0x40))
8724 4 : .wait()
8725 4 : .await;
8726 4 : // Update GC info
8727 4 : let mut guard = tline.gc_info.write().unwrap();
8728 4 : guard.cutoffs.time = Lsn(0x40);
8729 4 : guard.cutoffs.space = Lsn(0x40);
8730 4 : }
8731 4 : tline
8732 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8733 4 : .await
8734 4 : .unwrap();
8735 4 :
8736 4 : Ok(())
8737 4 : }
8738 :
8739 : #[cfg(feature = "testing")]
8740 : #[tokio::test]
8741 4 : async fn test_neon_test_record() -> anyhow::Result<()> {
8742 4 : let harness = TenantHarness::create("test_neon_test_record").await?;
8743 4 : let (tenant, ctx) = harness.load().await;
8744 4 :
8745 48 : fn get_key(id: u32) -> Key {
8746 48 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8747 48 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8748 48 : key.field6 = id;
8749 48 : key
8750 48 : }
8751 4 :
8752 4 : let delta1 = vec![
8753 4 : (
8754 4 : get_key(1),
8755 4 : Lsn(0x20),
8756 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
8757 4 : ),
8758 4 : (
8759 4 : get_key(1),
8760 4 : Lsn(0x30),
8761 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
8762 4 : ),
8763 4 : (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
8764 4 : (
8765 4 : get_key(2),
8766 4 : Lsn(0x20),
8767 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
8768 4 : ),
8769 4 : (
8770 4 : get_key(2),
8771 4 : Lsn(0x30),
8772 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
8773 4 : ),
8774 4 : (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
8775 4 : (
8776 4 : get_key(3),
8777 4 : Lsn(0x20),
8778 4 : Value::WalRecord(NeonWalRecord::wal_clear("c")),
8779 4 : ),
8780 4 : (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
8781 4 : (
8782 4 : get_key(4),
8783 4 : Lsn(0x20),
8784 4 : Value::WalRecord(NeonWalRecord::wal_init("i")),
8785 4 : ),
8786 4 : ];
8787 4 : let image1 = vec![(get_key(1), "0x10".into())];
8788 4 :
8789 4 : let tline = tenant
8790 4 : .create_test_timeline_with_layers(
8791 4 : TIMELINE_ID,
8792 4 : Lsn(0x10),
8793 4 : DEFAULT_PG_VERSION,
8794 4 : &ctx,
8795 4 : Vec::new(), // in-memory layers
8796 4 : vec![DeltaLayerTestDesc::new_with_inferred_key_range(
8797 4 : Lsn(0x10)..Lsn(0x40),
8798 4 : delta1,
8799 4 : )], // delta layers
8800 4 : vec![(Lsn(0x10), image1)], // image layers
8801 4 : Lsn(0x50),
8802 4 : )
8803 4 : .await?;
8804 4 :
8805 4 : assert_eq!(
8806 4 : tline.get(get_key(1), Lsn(0x50), &ctx).await?,
8807 4 : Bytes::from_static(b"0x10,0x20,0x30")
8808 4 : );
8809 4 : assert_eq!(
8810 4 : tline.get(get_key(2), Lsn(0x50), &ctx).await?,
8811 4 : Bytes::from_static(b"0x10,0x20,0x30")
8812 4 : );
8813 4 :
8814 4 : // Need to remove the limit of "Neon WAL redo requires base image".
8815 4 :
8816 4 : // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
8817 4 : // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
8818 4 :
8819 4 : Ok(())
8820 4 : }
8821 :
8822 : #[tokio::test(start_paused = true)]
8823 4 : async fn test_lsn_lease() -> anyhow::Result<()> {
8824 4 : let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
8825 4 : .await
8826 4 : .unwrap()
8827 4 : .load()
8828 4 : .await;
8829 4 : // Advance to the lsn lease deadline so that GC is not blocked by
8830 4 : // initial transition into AttachedSingle.
8831 4 : tokio::time::advance(tenant.get_lsn_lease_length()).await;
8832 4 : tokio::time::resume();
8833 4 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
8834 4 :
8835 4 : let end_lsn = Lsn(0x100);
8836 4 : let image_layers = (0x20..=0x90)
8837 4 : .step_by(0x10)
8838 32 : .map(|n| {
8839 32 : (
8840 32 : Lsn(n),
8841 32 : vec![(key, test_img(&format!("data key at {:x}", n)))],
8842 32 : )
8843 32 : })
8844 4 : .collect();
8845 4 :
8846 4 : let timeline = tenant
8847 4 : .create_test_timeline_with_layers(
8848 4 : TIMELINE_ID,
8849 4 : Lsn(0x10),
8850 4 : DEFAULT_PG_VERSION,
8851 4 : &ctx,
8852 4 : Vec::new(), // in-memory layers
8853 4 : Vec::new(),
8854 4 : image_layers,
8855 4 : end_lsn,
8856 4 : )
8857 4 : .await?;
8858 4 :
8859 4 : let leased_lsns = [0x30, 0x50, 0x70];
8860 4 : let mut leases = Vec::new();
8861 12 : leased_lsns.iter().for_each(|n| {
8862 12 : leases.push(
8863 12 : timeline
8864 12 : .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
8865 12 : .expect("lease request should succeed"),
8866 12 : );
8867 12 : });
8868 4 :
8869 4 : let updated_lease_0 = timeline
8870 4 : .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
8871 4 : .expect("lease renewal should succeed");
8872 4 : assert_eq!(
8873 4 : updated_lease_0.valid_until, leases[0].valid_until,
8874 4 : " Renewing with shorter lease should not change the lease."
8875 4 : );
8876 4 :
8877 4 : let updated_lease_1 = timeline
8878 4 : .renew_lsn_lease(
8879 4 : Lsn(leased_lsns[1]),
8880 4 : timeline.get_lsn_lease_length() * 2,
8881 4 : &ctx,
8882 4 : )
8883 4 : .expect("lease renewal should succeed");
8884 4 : assert!(
8885 4 : updated_lease_1.valid_until > leases[1].valid_until,
8886 4 : "Renewing with a long lease should renew lease with later expiration time."
8887 4 : );
8888 4 :
8889 4 : // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
8890 4 : info!(
8891 4 : "applied_gc_cutoff_lsn: {}",
8892 0 : *timeline.get_applied_gc_cutoff_lsn()
8893 4 : );
8894 4 : timeline.force_set_disk_consistent_lsn(end_lsn);
8895 4 :
8896 4 : let res = tenant
8897 4 : .gc_iteration(
8898 4 : Some(TIMELINE_ID),
8899 4 : 0,
8900 4 : Duration::ZERO,
8901 4 : &CancellationToken::new(),
8902 4 : &ctx,
8903 4 : )
8904 4 : .await
8905 4 : .unwrap();
8906 4 :
8907 4 : // Keeping everything <= Lsn(0x80) b/c leases:
8908 4 : // 0/10: initdb layer
8909 4 : // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
8910 4 : assert_eq!(res.layers_needed_by_leases, 7);
8911 4 : // Keeping 0/90 b/c it is the latest layer.
8912 4 : assert_eq!(res.layers_not_updated, 1);
8913 4 : // Removed 0/80.
8914 4 : assert_eq!(res.layers_removed, 1);
8915 4 :
8916 4 : // Make lease on a already GC-ed LSN.
8917 4 : // 0/80 does not have a valid lease + is below latest_gc_cutoff
8918 4 : assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
8919 4 : timeline
8920 4 : .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
8921 4 : .expect_err("lease request on GC-ed LSN should fail");
8922 4 :
8923 4 : // Should still be able to renew a currently valid lease
8924 4 : // Assumption: original lease to is still valid for 0/50.
8925 4 : // (use `Timeline::init_lsn_lease` for testing so it always does validation)
8926 4 : timeline
8927 4 : .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
8928 4 : .expect("lease renewal with validation should succeed");
8929 4 :
8930 4 : Ok(())
8931 4 : }
8932 :
8933 : #[cfg(feature = "testing")]
8934 : #[tokio::test]
8935 4 : async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
8936 4 : test_simple_bottom_most_compaction_deltas_helper(
8937 4 : "test_simple_bottom_most_compaction_deltas_1",
8938 4 : false,
8939 4 : )
8940 4 : .await
8941 4 : }
8942 :
8943 : #[cfg(feature = "testing")]
8944 : #[tokio::test]
8945 4 : async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
8946 4 : test_simple_bottom_most_compaction_deltas_helper(
8947 4 : "test_simple_bottom_most_compaction_deltas_2",
8948 4 : true,
8949 4 : )
8950 4 : .await
8951 4 : }
8952 :
8953 : #[cfg(feature = "testing")]
8954 8 : async fn test_simple_bottom_most_compaction_deltas_helper(
8955 8 : test_name: &'static str,
8956 8 : use_delta_bottom_layer: bool,
8957 8 : ) -> anyhow::Result<()> {
8958 8 : let harness = TenantHarness::create(test_name).await?;
8959 8 : let (tenant, ctx) = harness.load().await;
8960 :
8961 552 : fn get_key(id: u32) -> Key {
8962 552 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8963 552 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8964 552 : key.field6 = id;
8965 552 : key
8966 552 : }
8967 :
8968 : // We create
8969 : // - one bottom-most image layer,
8970 : // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
8971 : // - a delta layer D2 crossing the GC horizon with data only below the horizon,
8972 : // - a delta layer D3 above the horizon.
8973 : //
8974 : // | D3 |
8975 : // | D1 |
8976 : // -| |-- gc horizon -----------------
8977 : // | | | D2 |
8978 : // --------- img layer ------------------
8979 : //
8980 : // What we should expact from this compaction is:
8981 : // | D3 |
8982 : // | Part of D1 |
8983 : // --------- img layer with D1+D2 at GC horizon------------------
8984 :
8985 : // img layer at 0x10
8986 8 : let img_layer = (0..10)
8987 80 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
8988 8 : .collect_vec();
8989 8 : // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
8990 8 : let delta4 = (0..10)
8991 80 : .map(|id| {
8992 80 : (
8993 80 : get_key(id),
8994 80 : Lsn(0x08),
8995 80 : Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
8996 80 : )
8997 80 : })
8998 8 : .collect_vec();
8999 8 :
9000 8 : let delta1 = vec![
9001 8 : (
9002 8 : get_key(1),
9003 8 : Lsn(0x20),
9004 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9005 8 : ),
9006 8 : (
9007 8 : get_key(2),
9008 8 : Lsn(0x30),
9009 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9010 8 : ),
9011 8 : (
9012 8 : get_key(3),
9013 8 : Lsn(0x28),
9014 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9015 8 : ),
9016 8 : (
9017 8 : get_key(3),
9018 8 : Lsn(0x30),
9019 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9020 8 : ),
9021 8 : (
9022 8 : get_key(3),
9023 8 : Lsn(0x40),
9024 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
9025 8 : ),
9026 8 : ];
9027 8 : let delta2 = vec![
9028 8 : (
9029 8 : get_key(5),
9030 8 : Lsn(0x20),
9031 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9032 8 : ),
9033 8 : (
9034 8 : get_key(6),
9035 8 : Lsn(0x20),
9036 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9037 8 : ),
9038 8 : ];
9039 8 : let delta3 = vec![
9040 8 : (
9041 8 : get_key(8),
9042 8 : Lsn(0x48),
9043 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9044 8 : ),
9045 8 : (
9046 8 : get_key(9),
9047 8 : Lsn(0x48),
9048 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9049 8 : ),
9050 8 : ];
9051 :
9052 8 : let tline = if use_delta_bottom_layer {
9053 4 : tenant
9054 4 : .create_test_timeline_with_layers(
9055 4 : TIMELINE_ID,
9056 4 : Lsn(0x08),
9057 4 : DEFAULT_PG_VERSION,
9058 4 : &ctx,
9059 4 : Vec::new(), // in-memory layers
9060 4 : vec![
9061 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9062 4 : Lsn(0x08)..Lsn(0x10),
9063 4 : delta4,
9064 4 : ),
9065 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9066 4 : Lsn(0x20)..Lsn(0x48),
9067 4 : delta1,
9068 4 : ),
9069 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9070 4 : Lsn(0x20)..Lsn(0x48),
9071 4 : delta2,
9072 4 : ),
9073 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9074 4 : Lsn(0x48)..Lsn(0x50),
9075 4 : delta3,
9076 4 : ),
9077 4 : ], // delta layers
9078 4 : vec![], // image layers
9079 4 : Lsn(0x50),
9080 4 : )
9081 4 : .await?
9082 : } else {
9083 4 : tenant
9084 4 : .create_test_timeline_with_layers(
9085 4 : TIMELINE_ID,
9086 4 : Lsn(0x10),
9087 4 : DEFAULT_PG_VERSION,
9088 4 : &ctx,
9089 4 : Vec::new(), // in-memory layers
9090 4 : vec![
9091 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9092 4 : Lsn(0x10)..Lsn(0x48),
9093 4 : delta1,
9094 4 : ),
9095 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9096 4 : Lsn(0x10)..Lsn(0x48),
9097 4 : delta2,
9098 4 : ),
9099 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9100 4 : Lsn(0x48)..Lsn(0x50),
9101 4 : delta3,
9102 4 : ),
9103 4 : ], // delta layers
9104 4 : vec![(Lsn(0x10), img_layer)], // image layers
9105 4 : Lsn(0x50),
9106 4 : )
9107 4 : .await?
9108 : };
9109 : {
9110 8 : tline
9111 8 : .applied_gc_cutoff_lsn
9112 8 : .lock_for_write()
9113 8 : .store_and_unlock(Lsn(0x30))
9114 8 : .wait()
9115 8 : .await;
9116 : // Update GC info
9117 8 : let mut guard = tline.gc_info.write().unwrap();
9118 8 : *guard = GcInfo {
9119 8 : retain_lsns: vec![],
9120 8 : cutoffs: GcCutoffs {
9121 8 : time: Lsn(0x30),
9122 8 : space: Lsn(0x30),
9123 8 : },
9124 8 : leases: Default::default(),
9125 8 : within_ancestor_pitr: false,
9126 8 : };
9127 8 : }
9128 8 :
9129 8 : let expected_result = [
9130 8 : Bytes::from_static(b"value 0@0x10"),
9131 8 : Bytes::from_static(b"value 1@0x10@0x20"),
9132 8 : Bytes::from_static(b"value 2@0x10@0x30"),
9133 8 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
9134 8 : Bytes::from_static(b"value 4@0x10"),
9135 8 : Bytes::from_static(b"value 5@0x10@0x20"),
9136 8 : Bytes::from_static(b"value 6@0x10@0x20"),
9137 8 : Bytes::from_static(b"value 7@0x10"),
9138 8 : Bytes::from_static(b"value 8@0x10@0x48"),
9139 8 : Bytes::from_static(b"value 9@0x10@0x48"),
9140 8 : ];
9141 8 :
9142 8 : let expected_result_at_gc_horizon = [
9143 8 : Bytes::from_static(b"value 0@0x10"),
9144 8 : Bytes::from_static(b"value 1@0x10@0x20"),
9145 8 : Bytes::from_static(b"value 2@0x10@0x30"),
9146 8 : Bytes::from_static(b"value 3@0x10@0x28@0x30"),
9147 8 : Bytes::from_static(b"value 4@0x10"),
9148 8 : Bytes::from_static(b"value 5@0x10@0x20"),
9149 8 : Bytes::from_static(b"value 6@0x10@0x20"),
9150 8 : Bytes::from_static(b"value 7@0x10"),
9151 8 : Bytes::from_static(b"value 8@0x10"),
9152 8 : Bytes::from_static(b"value 9@0x10"),
9153 8 : ];
9154 :
9155 88 : for idx in 0..10 {
9156 80 : assert_eq!(
9157 80 : tline
9158 80 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9159 80 : .await
9160 80 : .unwrap(),
9161 80 : &expected_result[idx]
9162 : );
9163 80 : assert_eq!(
9164 80 : tline
9165 80 : .get(get_key(idx as u32), Lsn(0x30), &ctx)
9166 80 : .await
9167 80 : .unwrap(),
9168 80 : &expected_result_at_gc_horizon[idx]
9169 : );
9170 : }
9171 :
9172 8 : let cancel = CancellationToken::new();
9173 8 : tline
9174 8 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9175 8 : .await
9176 8 : .unwrap();
9177 :
9178 88 : for idx in 0..10 {
9179 80 : assert_eq!(
9180 80 : tline
9181 80 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9182 80 : .await
9183 80 : .unwrap(),
9184 80 : &expected_result[idx]
9185 : );
9186 80 : assert_eq!(
9187 80 : tline
9188 80 : .get(get_key(idx as u32), Lsn(0x30), &ctx)
9189 80 : .await
9190 80 : .unwrap(),
9191 80 : &expected_result_at_gc_horizon[idx]
9192 : );
9193 : }
9194 :
9195 : // increase GC horizon and compact again
9196 : {
9197 8 : tline
9198 8 : .applied_gc_cutoff_lsn
9199 8 : .lock_for_write()
9200 8 : .store_and_unlock(Lsn(0x40))
9201 8 : .wait()
9202 8 : .await;
9203 : // Update GC info
9204 8 : let mut guard = tline.gc_info.write().unwrap();
9205 8 : guard.cutoffs.time = Lsn(0x40);
9206 8 : guard.cutoffs.space = Lsn(0x40);
9207 8 : }
9208 8 : tline
9209 8 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9210 8 : .await
9211 8 : .unwrap();
9212 8 :
9213 8 : Ok(())
9214 8 : }
9215 :
9216 : #[cfg(feature = "testing")]
9217 : #[tokio::test]
9218 4 : async fn test_generate_key_retention() -> anyhow::Result<()> {
9219 4 : let harness = TenantHarness::create("test_generate_key_retention").await?;
9220 4 : let (tenant, ctx) = harness.load().await;
9221 4 : let tline = tenant
9222 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
9223 4 : .await?;
9224 4 : tline.force_advance_lsn(Lsn(0x70));
9225 4 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
9226 4 : let history = vec![
9227 4 : (
9228 4 : key,
9229 4 : Lsn(0x10),
9230 4 : Value::WalRecord(NeonWalRecord::wal_init("0x10")),
9231 4 : ),
9232 4 : (
9233 4 : key,
9234 4 : Lsn(0x20),
9235 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9236 4 : ),
9237 4 : (
9238 4 : key,
9239 4 : Lsn(0x30),
9240 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9241 4 : ),
9242 4 : (
9243 4 : key,
9244 4 : Lsn(0x40),
9245 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9246 4 : ),
9247 4 : (
9248 4 : key,
9249 4 : Lsn(0x50),
9250 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9251 4 : ),
9252 4 : (
9253 4 : key,
9254 4 : Lsn(0x60),
9255 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9256 4 : ),
9257 4 : (
9258 4 : key,
9259 4 : Lsn(0x70),
9260 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9261 4 : ),
9262 4 : (
9263 4 : key,
9264 4 : Lsn(0x80),
9265 4 : Value::Image(Bytes::copy_from_slice(
9266 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9267 4 : )),
9268 4 : ),
9269 4 : (
9270 4 : key,
9271 4 : Lsn(0x90),
9272 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9273 4 : ),
9274 4 : ];
9275 4 : let res = tline
9276 4 : .generate_key_retention(
9277 4 : key,
9278 4 : &history,
9279 4 : Lsn(0x60),
9280 4 : &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
9281 4 : 3,
9282 4 : None,
9283 4 : )
9284 4 : .await
9285 4 : .unwrap();
9286 4 : let expected_res = KeyHistoryRetention {
9287 4 : below_horizon: vec![
9288 4 : (
9289 4 : Lsn(0x20),
9290 4 : KeyLogAtLsn(vec![(
9291 4 : Lsn(0x20),
9292 4 : Value::Image(Bytes::from_static(b"0x10;0x20")),
9293 4 : )]),
9294 4 : ),
9295 4 : (
9296 4 : Lsn(0x40),
9297 4 : KeyLogAtLsn(vec![
9298 4 : (
9299 4 : Lsn(0x30),
9300 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9301 4 : ),
9302 4 : (
9303 4 : Lsn(0x40),
9304 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9305 4 : ),
9306 4 : ]),
9307 4 : ),
9308 4 : (
9309 4 : Lsn(0x50),
9310 4 : KeyLogAtLsn(vec![(
9311 4 : Lsn(0x50),
9312 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
9313 4 : )]),
9314 4 : ),
9315 4 : (
9316 4 : Lsn(0x60),
9317 4 : KeyLogAtLsn(vec![(
9318 4 : Lsn(0x60),
9319 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9320 4 : )]),
9321 4 : ),
9322 4 : ],
9323 4 : above_horizon: KeyLogAtLsn(vec![
9324 4 : (
9325 4 : Lsn(0x70),
9326 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9327 4 : ),
9328 4 : (
9329 4 : Lsn(0x80),
9330 4 : Value::Image(Bytes::copy_from_slice(
9331 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9332 4 : )),
9333 4 : ),
9334 4 : (
9335 4 : Lsn(0x90),
9336 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9337 4 : ),
9338 4 : ]),
9339 4 : };
9340 4 : assert_eq!(res, expected_res);
9341 4 :
9342 4 : // We expect GC-compaction to run with the original GC. This would create a situation that
9343 4 : // the original GC algorithm removes some delta layers b/c there are full image coverage,
9344 4 : // therefore causing some keys to have an incomplete history below the lowest retain LSN.
9345 4 : // For example, we have
9346 4 : // ```plain
9347 4 : // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
9348 4 : // ```
9349 4 : // Now the GC horizon moves up, and we have
9350 4 : // ```plain
9351 4 : // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
9352 4 : // ```
9353 4 : // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
9354 4 : // We will end up with
9355 4 : // ```plain
9356 4 : // delta @ 0x30, image @ 0x40 (gc_horizon)
9357 4 : // ```
9358 4 : // Now we run the GC-compaction, and this key does not have a full history.
9359 4 : // We should be able to handle this partial history and drop everything before the
9360 4 : // gc_horizon image.
9361 4 :
9362 4 : let history = vec![
9363 4 : (
9364 4 : key,
9365 4 : Lsn(0x20),
9366 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9367 4 : ),
9368 4 : (
9369 4 : key,
9370 4 : Lsn(0x30),
9371 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9372 4 : ),
9373 4 : (
9374 4 : key,
9375 4 : Lsn(0x40),
9376 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
9377 4 : ),
9378 4 : (
9379 4 : key,
9380 4 : Lsn(0x50),
9381 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9382 4 : ),
9383 4 : (
9384 4 : key,
9385 4 : Lsn(0x60),
9386 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9387 4 : ),
9388 4 : (
9389 4 : key,
9390 4 : Lsn(0x70),
9391 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9392 4 : ),
9393 4 : (
9394 4 : key,
9395 4 : Lsn(0x80),
9396 4 : Value::Image(Bytes::copy_from_slice(
9397 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9398 4 : )),
9399 4 : ),
9400 4 : (
9401 4 : key,
9402 4 : Lsn(0x90),
9403 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9404 4 : ),
9405 4 : ];
9406 4 : let res = tline
9407 4 : .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
9408 4 : .await
9409 4 : .unwrap();
9410 4 : let expected_res = KeyHistoryRetention {
9411 4 : below_horizon: vec![
9412 4 : (
9413 4 : Lsn(0x40),
9414 4 : KeyLogAtLsn(vec![(
9415 4 : Lsn(0x40),
9416 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
9417 4 : )]),
9418 4 : ),
9419 4 : (
9420 4 : Lsn(0x50),
9421 4 : KeyLogAtLsn(vec![(
9422 4 : Lsn(0x50),
9423 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9424 4 : )]),
9425 4 : ),
9426 4 : (
9427 4 : Lsn(0x60),
9428 4 : KeyLogAtLsn(vec![(
9429 4 : Lsn(0x60),
9430 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9431 4 : )]),
9432 4 : ),
9433 4 : ],
9434 4 : above_horizon: KeyLogAtLsn(vec![
9435 4 : (
9436 4 : Lsn(0x70),
9437 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9438 4 : ),
9439 4 : (
9440 4 : Lsn(0x80),
9441 4 : Value::Image(Bytes::copy_from_slice(
9442 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9443 4 : )),
9444 4 : ),
9445 4 : (
9446 4 : Lsn(0x90),
9447 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9448 4 : ),
9449 4 : ]),
9450 4 : };
9451 4 : assert_eq!(res, expected_res);
9452 4 :
9453 4 : // In case of branch compaction, the branch itself does not have the full history, and we need to provide
9454 4 : // the ancestor image in the test case.
9455 4 :
9456 4 : let history = vec![
9457 4 : (
9458 4 : key,
9459 4 : Lsn(0x20),
9460 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9461 4 : ),
9462 4 : (
9463 4 : key,
9464 4 : Lsn(0x30),
9465 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9466 4 : ),
9467 4 : (
9468 4 : key,
9469 4 : Lsn(0x40),
9470 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9471 4 : ),
9472 4 : (
9473 4 : key,
9474 4 : Lsn(0x70),
9475 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9476 4 : ),
9477 4 : ];
9478 4 : let res = tline
9479 4 : .generate_key_retention(
9480 4 : key,
9481 4 : &history,
9482 4 : Lsn(0x60),
9483 4 : &[],
9484 4 : 3,
9485 4 : Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
9486 4 : )
9487 4 : .await
9488 4 : .unwrap();
9489 4 : let expected_res = KeyHistoryRetention {
9490 4 : below_horizon: vec![(
9491 4 : Lsn(0x60),
9492 4 : KeyLogAtLsn(vec![(
9493 4 : Lsn(0x60),
9494 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
9495 4 : )]),
9496 4 : )],
9497 4 : above_horizon: KeyLogAtLsn(vec![(
9498 4 : Lsn(0x70),
9499 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9500 4 : )]),
9501 4 : };
9502 4 : assert_eq!(res, expected_res);
9503 4 :
9504 4 : let history = vec![
9505 4 : (
9506 4 : key,
9507 4 : Lsn(0x20),
9508 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9509 4 : ),
9510 4 : (
9511 4 : key,
9512 4 : Lsn(0x40),
9513 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9514 4 : ),
9515 4 : (
9516 4 : key,
9517 4 : Lsn(0x60),
9518 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9519 4 : ),
9520 4 : (
9521 4 : key,
9522 4 : Lsn(0x70),
9523 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9524 4 : ),
9525 4 : ];
9526 4 : let res = tline
9527 4 : .generate_key_retention(
9528 4 : key,
9529 4 : &history,
9530 4 : Lsn(0x60),
9531 4 : &[Lsn(0x30)],
9532 4 : 3,
9533 4 : Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
9534 4 : )
9535 4 : .await
9536 4 : .unwrap();
9537 4 : let expected_res = KeyHistoryRetention {
9538 4 : below_horizon: vec![
9539 4 : (
9540 4 : Lsn(0x30),
9541 4 : KeyLogAtLsn(vec![(
9542 4 : Lsn(0x20),
9543 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9544 4 : )]),
9545 4 : ),
9546 4 : (
9547 4 : Lsn(0x60),
9548 4 : KeyLogAtLsn(vec![(
9549 4 : Lsn(0x60),
9550 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
9551 4 : )]),
9552 4 : ),
9553 4 : ],
9554 4 : above_horizon: KeyLogAtLsn(vec![(
9555 4 : Lsn(0x70),
9556 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9557 4 : )]),
9558 4 : };
9559 4 : assert_eq!(res, expected_res);
9560 4 :
9561 4 : Ok(())
9562 4 : }
9563 :
9564 : #[cfg(feature = "testing")]
9565 : #[tokio::test]
9566 4 : async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
9567 4 : let harness =
9568 4 : TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
9569 4 : let (tenant, ctx) = harness.load().await;
9570 4 :
9571 1036 : fn get_key(id: u32) -> Key {
9572 1036 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
9573 1036 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
9574 1036 : key.field6 = id;
9575 1036 : key
9576 1036 : }
9577 4 :
9578 4 : let img_layer = (0..10)
9579 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9580 4 : .collect_vec();
9581 4 :
9582 4 : let delta1 = vec![
9583 4 : (
9584 4 : get_key(1),
9585 4 : Lsn(0x20),
9586 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9587 4 : ),
9588 4 : (
9589 4 : get_key(2),
9590 4 : Lsn(0x30),
9591 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9592 4 : ),
9593 4 : (
9594 4 : get_key(3),
9595 4 : Lsn(0x28),
9596 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9597 4 : ),
9598 4 : (
9599 4 : get_key(3),
9600 4 : Lsn(0x30),
9601 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9602 4 : ),
9603 4 : (
9604 4 : get_key(3),
9605 4 : Lsn(0x40),
9606 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
9607 4 : ),
9608 4 : ];
9609 4 : let delta2 = vec![
9610 4 : (
9611 4 : get_key(5),
9612 4 : Lsn(0x20),
9613 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9614 4 : ),
9615 4 : (
9616 4 : get_key(6),
9617 4 : Lsn(0x20),
9618 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9619 4 : ),
9620 4 : ];
9621 4 : let delta3 = vec![
9622 4 : (
9623 4 : get_key(8),
9624 4 : Lsn(0x48),
9625 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9626 4 : ),
9627 4 : (
9628 4 : get_key(9),
9629 4 : Lsn(0x48),
9630 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9631 4 : ),
9632 4 : ];
9633 4 :
9634 4 : let tline = tenant
9635 4 : .create_test_timeline_with_layers(
9636 4 : TIMELINE_ID,
9637 4 : Lsn(0x10),
9638 4 : DEFAULT_PG_VERSION,
9639 4 : &ctx,
9640 4 : Vec::new(), // in-memory layers
9641 4 : vec![
9642 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
9643 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
9644 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
9645 4 : ], // delta layers
9646 4 : vec![(Lsn(0x10), img_layer)], // image layers
9647 4 : Lsn(0x50),
9648 4 : )
9649 4 : .await?;
9650 4 : {
9651 4 : tline
9652 4 : .applied_gc_cutoff_lsn
9653 4 : .lock_for_write()
9654 4 : .store_and_unlock(Lsn(0x30))
9655 4 : .wait()
9656 4 : .await;
9657 4 : // Update GC info
9658 4 : let mut guard = tline.gc_info.write().unwrap();
9659 4 : *guard = GcInfo {
9660 4 : retain_lsns: vec![
9661 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
9662 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
9663 4 : ],
9664 4 : cutoffs: GcCutoffs {
9665 4 : time: Lsn(0x30),
9666 4 : space: Lsn(0x30),
9667 4 : },
9668 4 : leases: Default::default(),
9669 4 : within_ancestor_pitr: false,
9670 4 : };
9671 4 : }
9672 4 :
9673 4 : let expected_result = [
9674 4 : Bytes::from_static(b"value 0@0x10"),
9675 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9676 4 : Bytes::from_static(b"value 2@0x10@0x30"),
9677 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
9678 4 : Bytes::from_static(b"value 4@0x10"),
9679 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9680 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9681 4 : Bytes::from_static(b"value 7@0x10"),
9682 4 : Bytes::from_static(b"value 8@0x10@0x48"),
9683 4 : Bytes::from_static(b"value 9@0x10@0x48"),
9684 4 : ];
9685 4 :
9686 4 : let expected_result_at_gc_horizon = [
9687 4 : Bytes::from_static(b"value 0@0x10"),
9688 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9689 4 : Bytes::from_static(b"value 2@0x10@0x30"),
9690 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30"),
9691 4 : Bytes::from_static(b"value 4@0x10"),
9692 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9693 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9694 4 : Bytes::from_static(b"value 7@0x10"),
9695 4 : Bytes::from_static(b"value 8@0x10"),
9696 4 : Bytes::from_static(b"value 9@0x10"),
9697 4 : ];
9698 4 :
9699 4 : let expected_result_at_lsn_20 = [
9700 4 : Bytes::from_static(b"value 0@0x10"),
9701 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9702 4 : Bytes::from_static(b"value 2@0x10"),
9703 4 : Bytes::from_static(b"value 3@0x10"),
9704 4 : Bytes::from_static(b"value 4@0x10"),
9705 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9706 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9707 4 : Bytes::from_static(b"value 7@0x10"),
9708 4 : Bytes::from_static(b"value 8@0x10"),
9709 4 : Bytes::from_static(b"value 9@0x10"),
9710 4 : ];
9711 4 :
9712 4 : let expected_result_at_lsn_10 = [
9713 4 : Bytes::from_static(b"value 0@0x10"),
9714 4 : Bytes::from_static(b"value 1@0x10"),
9715 4 : Bytes::from_static(b"value 2@0x10"),
9716 4 : Bytes::from_static(b"value 3@0x10"),
9717 4 : Bytes::from_static(b"value 4@0x10"),
9718 4 : Bytes::from_static(b"value 5@0x10"),
9719 4 : Bytes::from_static(b"value 6@0x10"),
9720 4 : Bytes::from_static(b"value 7@0x10"),
9721 4 : Bytes::from_static(b"value 8@0x10"),
9722 4 : Bytes::from_static(b"value 9@0x10"),
9723 4 : ];
9724 4 :
9725 24 : let verify_result = || async {
9726 24 : let gc_horizon = {
9727 24 : let gc_info = tline.gc_info.read().unwrap();
9728 24 : gc_info.cutoffs.time
9729 4 : };
9730 264 : for idx in 0..10 {
9731 240 : assert_eq!(
9732 240 : tline
9733 240 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9734 240 : .await
9735 240 : .unwrap(),
9736 240 : &expected_result[idx]
9737 4 : );
9738 240 : assert_eq!(
9739 240 : tline
9740 240 : .get(get_key(idx as u32), gc_horizon, &ctx)
9741 240 : .await
9742 240 : .unwrap(),
9743 240 : &expected_result_at_gc_horizon[idx]
9744 4 : );
9745 240 : assert_eq!(
9746 240 : tline
9747 240 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
9748 240 : .await
9749 240 : .unwrap(),
9750 240 : &expected_result_at_lsn_20[idx]
9751 4 : );
9752 240 : assert_eq!(
9753 240 : tline
9754 240 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
9755 240 : .await
9756 240 : .unwrap(),
9757 240 : &expected_result_at_lsn_10[idx]
9758 4 : );
9759 4 : }
9760 48 : };
9761 4 :
9762 4 : verify_result().await;
9763 4 :
9764 4 : let cancel = CancellationToken::new();
9765 4 : let mut dryrun_flags = EnumSet::new();
9766 4 : dryrun_flags.insert(CompactFlags::DryRun);
9767 4 :
9768 4 : tline
9769 4 : .compact_with_gc(
9770 4 : &cancel,
9771 4 : CompactOptions {
9772 4 : flags: dryrun_flags,
9773 4 : ..Default::default()
9774 4 : },
9775 4 : &ctx,
9776 4 : )
9777 4 : .await
9778 4 : .unwrap();
9779 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
9780 4 : // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
9781 4 : verify_result().await;
9782 4 :
9783 4 : tline
9784 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9785 4 : .await
9786 4 : .unwrap();
9787 4 : verify_result().await;
9788 4 :
9789 4 : // compact again
9790 4 : tline
9791 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9792 4 : .await
9793 4 : .unwrap();
9794 4 : verify_result().await;
9795 4 :
9796 4 : // increase GC horizon and compact again
9797 4 : {
9798 4 : tline
9799 4 : .applied_gc_cutoff_lsn
9800 4 : .lock_for_write()
9801 4 : .store_and_unlock(Lsn(0x38))
9802 4 : .wait()
9803 4 : .await;
9804 4 : // Update GC info
9805 4 : let mut guard = tline.gc_info.write().unwrap();
9806 4 : guard.cutoffs.time = Lsn(0x38);
9807 4 : guard.cutoffs.space = Lsn(0x38);
9808 4 : }
9809 4 : tline
9810 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9811 4 : .await
9812 4 : .unwrap();
9813 4 : verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
9814 4 :
9815 4 : // not increasing the GC horizon and compact again
9816 4 : tline
9817 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9818 4 : .await
9819 4 : .unwrap();
9820 4 : verify_result().await;
9821 4 :
9822 4 : Ok(())
9823 4 : }
9824 :
9825 : #[cfg(feature = "testing")]
9826 : #[tokio::test]
9827 4 : async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
9828 4 : {
9829 4 : let harness =
9830 4 : TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
9831 4 : .await?;
9832 4 : let (tenant, ctx) = harness.load().await;
9833 4 :
9834 704 : fn get_key(id: u32) -> Key {
9835 704 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
9836 704 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
9837 704 : key.field6 = id;
9838 704 : key
9839 704 : }
9840 4 :
9841 4 : let img_layer = (0..10)
9842 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9843 4 : .collect_vec();
9844 4 :
9845 4 : let delta1 = vec![
9846 4 : (
9847 4 : get_key(1),
9848 4 : Lsn(0x20),
9849 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9850 4 : ),
9851 4 : (
9852 4 : get_key(1),
9853 4 : Lsn(0x28),
9854 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9855 4 : ),
9856 4 : ];
9857 4 : let delta2 = vec![
9858 4 : (
9859 4 : get_key(1),
9860 4 : Lsn(0x30),
9861 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9862 4 : ),
9863 4 : (
9864 4 : get_key(1),
9865 4 : Lsn(0x38),
9866 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
9867 4 : ),
9868 4 : ];
9869 4 : let delta3 = vec![
9870 4 : (
9871 4 : get_key(8),
9872 4 : Lsn(0x48),
9873 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9874 4 : ),
9875 4 : (
9876 4 : get_key(9),
9877 4 : Lsn(0x48),
9878 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9879 4 : ),
9880 4 : ];
9881 4 :
9882 4 : let tline = tenant
9883 4 : .create_test_timeline_with_layers(
9884 4 : TIMELINE_ID,
9885 4 : Lsn(0x10),
9886 4 : DEFAULT_PG_VERSION,
9887 4 : &ctx,
9888 4 : Vec::new(), // in-memory layers
9889 4 : vec![
9890 4 : // delta1 and delta 2 only contain a single key but multiple updates
9891 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
9892 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
9893 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
9894 4 : ], // delta layers
9895 4 : vec![(Lsn(0x10), img_layer)], // image layers
9896 4 : Lsn(0x50),
9897 4 : )
9898 4 : .await?;
9899 4 : {
9900 4 : tline
9901 4 : .applied_gc_cutoff_lsn
9902 4 : .lock_for_write()
9903 4 : .store_and_unlock(Lsn(0x30))
9904 4 : .wait()
9905 4 : .await;
9906 4 : // Update GC info
9907 4 : let mut guard = tline.gc_info.write().unwrap();
9908 4 : *guard = GcInfo {
9909 4 : retain_lsns: vec![
9910 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
9911 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
9912 4 : ],
9913 4 : cutoffs: GcCutoffs {
9914 4 : time: Lsn(0x30),
9915 4 : space: Lsn(0x30),
9916 4 : },
9917 4 : leases: Default::default(),
9918 4 : within_ancestor_pitr: false,
9919 4 : };
9920 4 : }
9921 4 :
9922 4 : let expected_result = [
9923 4 : Bytes::from_static(b"value 0@0x10"),
9924 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
9925 4 : Bytes::from_static(b"value 2@0x10"),
9926 4 : Bytes::from_static(b"value 3@0x10"),
9927 4 : Bytes::from_static(b"value 4@0x10"),
9928 4 : Bytes::from_static(b"value 5@0x10"),
9929 4 : Bytes::from_static(b"value 6@0x10"),
9930 4 : Bytes::from_static(b"value 7@0x10"),
9931 4 : Bytes::from_static(b"value 8@0x10@0x48"),
9932 4 : Bytes::from_static(b"value 9@0x10@0x48"),
9933 4 : ];
9934 4 :
9935 4 : let expected_result_at_gc_horizon = [
9936 4 : Bytes::from_static(b"value 0@0x10"),
9937 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
9938 4 : Bytes::from_static(b"value 2@0x10"),
9939 4 : Bytes::from_static(b"value 3@0x10"),
9940 4 : Bytes::from_static(b"value 4@0x10"),
9941 4 : Bytes::from_static(b"value 5@0x10"),
9942 4 : Bytes::from_static(b"value 6@0x10"),
9943 4 : Bytes::from_static(b"value 7@0x10"),
9944 4 : Bytes::from_static(b"value 8@0x10"),
9945 4 : Bytes::from_static(b"value 9@0x10"),
9946 4 : ];
9947 4 :
9948 4 : let expected_result_at_lsn_20 = [
9949 4 : Bytes::from_static(b"value 0@0x10"),
9950 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9951 4 : Bytes::from_static(b"value 2@0x10"),
9952 4 : Bytes::from_static(b"value 3@0x10"),
9953 4 : Bytes::from_static(b"value 4@0x10"),
9954 4 : Bytes::from_static(b"value 5@0x10"),
9955 4 : Bytes::from_static(b"value 6@0x10"),
9956 4 : Bytes::from_static(b"value 7@0x10"),
9957 4 : Bytes::from_static(b"value 8@0x10"),
9958 4 : Bytes::from_static(b"value 9@0x10"),
9959 4 : ];
9960 4 :
9961 4 : let expected_result_at_lsn_10 = [
9962 4 : Bytes::from_static(b"value 0@0x10"),
9963 4 : Bytes::from_static(b"value 1@0x10"),
9964 4 : Bytes::from_static(b"value 2@0x10"),
9965 4 : Bytes::from_static(b"value 3@0x10"),
9966 4 : Bytes::from_static(b"value 4@0x10"),
9967 4 : Bytes::from_static(b"value 5@0x10"),
9968 4 : Bytes::from_static(b"value 6@0x10"),
9969 4 : Bytes::from_static(b"value 7@0x10"),
9970 4 : Bytes::from_static(b"value 8@0x10"),
9971 4 : Bytes::from_static(b"value 9@0x10"),
9972 4 : ];
9973 4 :
9974 16 : let verify_result = || async {
9975 16 : let gc_horizon = {
9976 16 : let gc_info = tline.gc_info.read().unwrap();
9977 16 : gc_info.cutoffs.time
9978 4 : };
9979 176 : for idx in 0..10 {
9980 160 : assert_eq!(
9981 160 : tline
9982 160 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9983 160 : .await
9984 160 : .unwrap(),
9985 160 : &expected_result[idx]
9986 4 : );
9987 160 : assert_eq!(
9988 160 : tline
9989 160 : .get(get_key(idx as u32), gc_horizon, &ctx)
9990 160 : .await
9991 160 : .unwrap(),
9992 160 : &expected_result_at_gc_horizon[idx]
9993 4 : );
9994 160 : assert_eq!(
9995 160 : tline
9996 160 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
9997 160 : .await
9998 160 : .unwrap(),
9999 160 : &expected_result_at_lsn_20[idx]
10000 4 : );
10001 160 : assert_eq!(
10002 160 : tline
10003 160 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
10004 160 : .await
10005 160 : .unwrap(),
10006 160 : &expected_result_at_lsn_10[idx]
10007 4 : );
10008 4 : }
10009 32 : };
10010 4 :
10011 4 : verify_result().await;
10012 4 :
10013 4 : let cancel = CancellationToken::new();
10014 4 : let mut dryrun_flags = EnumSet::new();
10015 4 : dryrun_flags.insert(CompactFlags::DryRun);
10016 4 :
10017 4 : tline
10018 4 : .compact_with_gc(
10019 4 : &cancel,
10020 4 : CompactOptions {
10021 4 : flags: dryrun_flags,
10022 4 : ..Default::default()
10023 4 : },
10024 4 : &ctx,
10025 4 : )
10026 4 : .await
10027 4 : .unwrap();
10028 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
10029 4 : // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
10030 4 : verify_result().await;
10031 4 :
10032 4 : tline
10033 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
10034 4 : .await
10035 4 : .unwrap();
10036 4 : verify_result().await;
10037 4 :
10038 4 : // compact again
10039 4 : tline
10040 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
10041 4 : .await
10042 4 : .unwrap();
10043 4 : verify_result().await;
10044 4 :
10045 4 : Ok(())
10046 4 : }
10047 :
10048 : #[cfg(feature = "testing")]
10049 : #[tokio::test]
10050 4 : async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
10051 4 : use models::CompactLsnRange;
10052 4 :
10053 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
10054 4 : let (tenant, ctx) = harness.load().await;
10055 4 :
10056 332 : fn get_key(id: u32) -> Key {
10057 332 : let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
10058 332 : key.field6 = id;
10059 332 : key
10060 332 : }
10061 4 :
10062 4 : let img_layer = (0..10)
10063 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10064 4 : .collect_vec();
10065 4 :
10066 4 : let delta1 = vec![
10067 4 : (
10068 4 : get_key(1),
10069 4 : Lsn(0x20),
10070 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10071 4 : ),
10072 4 : (
10073 4 : get_key(2),
10074 4 : Lsn(0x30),
10075 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
10076 4 : ),
10077 4 : (
10078 4 : get_key(3),
10079 4 : Lsn(0x28),
10080 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
10081 4 : ),
10082 4 : (
10083 4 : get_key(3),
10084 4 : Lsn(0x30),
10085 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
10086 4 : ),
10087 4 : (
10088 4 : get_key(3),
10089 4 : Lsn(0x40),
10090 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
10091 4 : ),
10092 4 : ];
10093 4 : let delta2 = vec![
10094 4 : (
10095 4 : get_key(5),
10096 4 : Lsn(0x20),
10097 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10098 4 : ),
10099 4 : (
10100 4 : get_key(6),
10101 4 : Lsn(0x20),
10102 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10103 4 : ),
10104 4 : ];
10105 4 : let delta3 = vec![
10106 4 : (
10107 4 : get_key(8),
10108 4 : Lsn(0x48),
10109 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10110 4 : ),
10111 4 : (
10112 4 : get_key(9),
10113 4 : Lsn(0x48),
10114 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10115 4 : ),
10116 4 : ];
10117 4 :
10118 4 : let parent_tline = tenant
10119 4 : .create_test_timeline_with_layers(
10120 4 : TIMELINE_ID,
10121 4 : Lsn(0x10),
10122 4 : DEFAULT_PG_VERSION,
10123 4 : &ctx,
10124 4 : vec![], // in-memory layers
10125 4 : vec![], // delta layers
10126 4 : vec![(Lsn(0x18), img_layer)], // image layers
10127 4 : Lsn(0x18),
10128 4 : )
10129 4 : .await?;
10130 4 :
10131 4 : parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
10132 4 :
10133 4 : let branch_tline = tenant
10134 4 : .branch_timeline_test_with_layers(
10135 4 : &parent_tline,
10136 4 : NEW_TIMELINE_ID,
10137 4 : Some(Lsn(0x18)),
10138 4 : &ctx,
10139 4 : vec![
10140 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
10141 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
10142 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
10143 4 : ], // delta layers
10144 4 : vec![], // image layers
10145 4 : Lsn(0x50),
10146 4 : )
10147 4 : .await?;
10148 4 :
10149 4 : branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
10150 4 :
10151 4 : {
10152 4 : parent_tline
10153 4 : .applied_gc_cutoff_lsn
10154 4 : .lock_for_write()
10155 4 : .store_and_unlock(Lsn(0x10))
10156 4 : .wait()
10157 4 : .await;
10158 4 : // Update GC info
10159 4 : let mut guard = parent_tline.gc_info.write().unwrap();
10160 4 : *guard = GcInfo {
10161 4 : retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
10162 4 : cutoffs: GcCutoffs {
10163 4 : time: Lsn(0x10),
10164 4 : space: Lsn(0x10),
10165 4 : },
10166 4 : leases: Default::default(),
10167 4 : within_ancestor_pitr: false,
10168 4 : };
10169 4 : }
10170 4 :
10171 4 : {
10172 4 : branch_tline
10173 4 : .applied_gc_cutoff_lsn
10174 4 : .lock_for_write()
10175 4 : .store_and_unlock(Lsn(0x50))
10176 4 : .wait()
10177 4 : .await;
10178 4 : // Update GC info
10179 4 : let mut guard = branch_tline.gc_info.write().unwrap();
10180 4 : *guard = GcInfo {
10181 4 : retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
10182 4 : cutoffs: GcCutoffs {
10183 4 : time: Lsn(0x50),
10184 4 : space: Lsn(0x50),
10185 4 : },
10186 4 : leases: Default::default(),
10187 4 : within_ancestor_pitr: false,
10188 4 : };
10189 4 : }
10190 4 :
10191 4 : let expected_result_at_gc_horizon = [
10192 4 : Bytes::from_static(b"value 0@0x10"),
10193 4 : Bytes::from_static(b"value 1@0x10@0x20"),
10194 4 : Bytes::from_static(b"value 2@0x10@0x30"),
10195 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
10196 4 : Bytes::from_static(b"value 4@0x10"),
10197 4 : Bytes::from_static(b"value 5@0x10@0x20"),
10198 4 : Bytes::from_static(b"value 6@0x10@0x20"),
10199 4 : Bytes::from_static(b"value 7@0x10"),
10200 4 : Bytes::from_static(b"value 8@0x10@0x48"),
10201 4 : Bytes::from_static(b"value 9@0x10@0x48"),
10202 4 : ];
10203 4 :
10204 4 : let expected_result_at_lsn_40 = [
10205 4 : Bytes::from_static(b"value 0@0x10"),
10206 4 : Bytes::from_static(b"value 1@0x10@0x20"),
10207 4 : Bytes::from_static(b"value 2@0x10@0x30"),
10208 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
10209 4 : Bytes::from_static(b"value 4@0x10"),
10210 4 : Bytes::from_static(b"value 5@0x10@0x20"),
10211 4 : Bytes::from_static(b"value 6@0x10@0x20"),
10212 4 : Bytes::from_static(b"value 7@0x10"),
10213 4 : Bytes::from_static(b"value 8@0x10"),
10214 4 : Bytes::from_static(b"value 9@0x10"),
10215 4 : ];
10216 4 :
10217 12 : let verify_result = || async {
10218 132 : for idx in 0..10 {
10219 120 : assert_eq!(
10220 120 : branch_tline
10221 120 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
10222 120 : .await
10223 120 : .unwrap(),
10224 120 : &expected_result_at_gc_horizon[idx]
10225 4 : );
10226 120 : assert_eq!(
10227 120 : branch_tline
10228 120 : .get(get_key(idx as u32), Lsn(0x40), &ctx)
10229 120 : .await
10230 120 : .unwrap(),
10231 120 : &expected_result_at_lsn_40[idx]
10232 4 : );
10233 4 : }
10234 24 : };
10235 4 :
10236 4 : verify_result().await;
10237 4 :
10238 4 : let cancel = CancellationToken::new();
10239 4 : branch_tline
10240 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
10241 4 : .await
10242 4 : .unwrap();
10243 4 :
10244 4 : verify_result().await;
10245 4 :
10246 4 : // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
10247 4 : // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
10248 4 : branch_tline
10249 4 : .compact_with_gc(
10250 4 : &cancel,
10251 4 : CompactOptions {
10252 4 : compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
10253 4 : ..Default::default()
10254 4 : },
10255 4 : &ctx,
10256 4 : )
10257 4 : .await
10258 4 : .unwrap();
10259 4 :
10260 4 : verify_result().await;
10261 4 :
10262 4 : Ok(())
10263 4 : }
10264 :
10265 : // Regression test for https://github.com/neondatabase/neon/issues/9012
10266 : // Create an image arrangement where we have to read at different LSN ranges
10267 : // from a delta layer. This is achieved by overlapping an image layer on top of
10268 : // a delta layer. Like so:
10269 : //
10270 : // A B
10271 : // +----------------+ -> delta_layer
10272 : // | | ^ lsn
10273 : // | =========|-> nested_image_layer |
10274 : // | C | |
10275 : // +----------------+ |
10276 : // ======== -> baseline_image_layer +-------> key
10277 : //
10278 : //
10279 : // When querying the key range [A, B) we need to read at different LSN ranges
10280 : // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
10281 : #[cfg(feature = "testing")]
10282 : #[tokio::test]
10283 4 : async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
10284 4 : let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
10285 4 : let (tenant, ctx) = harness.load().await;
10286 4 :
10287 4 : let will_init_keys = [2, 6];
10288 88 : fn get_key(id: u32) -> Key {
10289 88 : let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
10290 88 : key.field6 = id;
10291 88 : key
10292 88 : }
10293 4 :
10294 4 : let mut expected_key_values = HashMap::new();
10295 4 :
10296 4 : let baseline_image_layer_lsn = Lsn(0x10);
10297 4 : let mut baseline_img_layer = Vec::new();
10298 24 : for i in 0..5 {
10299 20 : let key = get_key(i);
10300 20 : let value = format!("value {i}@{baseline_image_layer_lsn}");
10301 20 :
10302 20 : let removed = expected_key_values.insert(key, value.clone());
10303 20 : assert!(removed.is_none());
10304 4 :
10305 20 : baseline_img_layer.push((key, Bytes::from(value)));
10306 4 : }
10307 4 :
10308 4 : let nested_image_layer_lsn = Lsn(0x50);
10309 4 : let mut nested_img_layer = Vec::new();
10310 24 : for i in 5..10 {
10311 20 : let key = get_key(i);
10312 20 : let value = format!("value {i}@{nested_image_layer_lsn}");
10313 20 :
10314 20 : let removed = expected_key_values.insert(key, value.clone());
10315 20 : assert!(removed.is_none());
10316 4 :
10317 20 : nested_img_layer.push((key, Bytes::from(value)));
10318 4 : }
10319 4 :
10320 4 : let mut delta_layer_spec = Vec::default();
10321 4 : let delta_layer_start_lsn = Lsn(0x20);
10322 4 : let mut delta_layer_end_lsn = delta_layer_start_lsn;
10323 4 :
10324 44 : for i in 0..10 {
10325 40 : let key = get_key(i);
10326 40 : let key_in_nested = nested_img_layer
10327 40 : .iter()
10328 160 : .any(|(key_with_img, _)| *key_with_img == key);
10329 40 : let lsn = {
10330 40 : if key_in_nested {
10331 20 : Lsn(nested_image_layer_lsn.0 + 0x10)
10332 4 : } else {
10333 20 : delta_layer_start_lsn
10334 4 : }
10335 4 : };
10336 4 :
10337 40 : let will_init = will_init_keys.contains(&i);
10338 40 : if will_init {
10339 8 : delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
10340 8 :
10341 8 : expected_key_values.insert(key, "".to_string());
10342 32 : } else {
10343 32 : let delta = format!("@{lsn}");
10344 32 : delta_layer_spec.push((
10345 32 : key,
10346 32 : lsn,
10347 32 : Value::WalRecord(NeonWalRecord::wal_append(&delta)),
10348 32 : ));
10349 32 :
10350 32 : expected_key_values
10351 32 : .get_mut(&key)
10352 32 : .expect("An image exists for each key")
10353 32 : .push_str(delta.as_str());
10354 32 : }
10355 40 : delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
10356 4 : }
10357 4 :
10358 4 : delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
10359 4 :
10360 4 : assert!(
10361 4 : nested_image_layer_lsn > delta_layer_start_lsn
10362 4 : && nested_image_layer_lsn < delta_layer_end_lsn
10363 4 : );
10364 4 :
10365 4 : let tline = tenant
10366 4 : .create_test_timeline_with_layers(
10367 4 : TIMELINE_ID,
10368 4 : baseline_image_layer_lsn,
10369 4 : DEFAULT_PG_VERSION,
10370 4 : &ctx,
10371 4 : vec![], // in-memory layers
10372 4 : vec![DeltaLayerTestDesc::new_with_inferred_key_range(
10373 4 : delta_layer_start_lsn..delta_layer_end_lsn,
10374 4 : delta_layer_spec,
10375 4 : )], // delta layers
10376 4 : vec![
10377 4 : (baseline_image_layer_lsn, baseline_img_layer),
10378 4 : (nested_image_layer_lsn, nested_img_layer),
10379 4 : ], // image layers
10380 4 : delta_layer_end_lsn,
10381 4 : )
10382 4 : .await?;
10383 4 :
10384 4 : let keyspace = KeySpace::single(get_key(0)..get_key(10));
10385 4 : let results = tline
10386 4 : .get_vectored(
10387 4 : keyspace,
10388 4 : delta_layer_end_lsn,
10389 4 : IoConcurrency::sequential(),
10390 4 : &ctx,
10391 4 : )
10392 4 : .await
10393 4 : .expect("No vectored errors");
10394 44 : for (key, res) in results {
10395 40 : let value = res.expect("No key errors");
10396 40 : let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
10397 40 : assert_eq!(value, Bytes::from(expected_value));
10398 4 : }
10399 4 :
10400 4 : Ok(())
10401 4 : }
10402 :
10403 : #[cfg(feature = "testing")]
10404 : #[tokio::test]
10405 4 : async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
10406 4 : let harness =
10407 4 : TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
10408 4 : let (tenant, ctx) = harness.load().await;
10409 4 :
10410 4 : let will_init_keys = [2, 6];
10411 128 : fn get_key(id: u32) -> Key {
10412 128 : let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
10413 128 : key.field6 = id;
10414 128 : key
10415 128 : }
10416 4 :
10417 4 : let mut expected_key_values = HashMap::new();
10418 4 :
10419 4 : let baseline_image_layer_lsn = Lsn(0x10);
10420 4 : let mut baseline_img_layer = Vec::new();
10421 24 : for i in 0..5 {
10422 20 : let key = get_key(i);
10423 20 : let value = format!("value {i}@{baseline_image_layer_lsn}");
10424 20 :
10425 20 : let removed = expected_key_values.insert(key, value.clone());
10426 20 : assert!(removed.is_none());
10427 4 :
10428 20 : baseline_img_layer.push((key, Bytes::from(value)));
10429 4 : }
10430 4 :
10431 4 : let nested_image_layer_lsn = Lsn(0x50);
10432 4 : let mut nested_img_layer = Vec::new();
10433 24 : for i in 5..10 {
10434 20 : let key = get_key(i);
10435 20 : let value = format!("value {i}@{nested_image_layer_lsn}");
10436 20 :
10437 20 : let removed = expected_key_values.insert(key, value.clone());
10438 20 : assert!(removed.is_none());
10439 4 :
10440 20 : nested_img_layer.push((key, Bytes::from(value)));
10441 4 : }
10442 4 :
10443 4 : let frozen_layer = {
10444 4 : let lsn_range = Lsn(0x40)..Lsn(0x60);
10445 4 : let mut data = Vec::new();
10446 44 : for i in 0..10 {
10447 40 : let key = get_key(i);
10448 40 : let key_in_nested = nested_img_layer
10449 40 : .iter()
10450 160 : .any(|(key_with_img, _)| *key_with_img == key);
10451 40 : let lsn = {
10452 40 : if key_in_nested {
10453 20 : Lsn(nested_image_layer_lsn.0 + 5)
10454 4 : } else {
10455 20 : lsn_range.start
10456 4 : }
10457 4 : };
10458 4 :
10459 40 : let will_init = will_init_keys.contains(&i);
10460 40 : if will_init {
10461 8 : data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
10462 8 :
10463 8 : expected_key_values.insert(key, "".to_string());
10464 32 : } else {
10465 32 : let delta = format!("@{lsn}");
10466 32 : data.push((
10467 32 : key,
10468 32 : lsn,
10469 32 : Value::WalRecord(NeonWalRecord::wal_append(&delta)),
10470 32 : ));
10471 32 :
10472 32 : expected_key_values
10473 32 : .get_mut(&key)
10474 32 : .expect("An image exists for each key")
10475 32 : .push_str(delta.as_str());
10476 32 : }
10477 4 : }
10478 4 :
10479 4 : InMemoryLayerTestDesc {
10480 4 : lsn_range,
10481 4 : is_open: false,
10482 4 : data,
10483 4 : }
10484 4 : };
10485 4 :
10486 4 : let (open_layer, last_record_lsn) = {
10487 4 : let start_lsn = Lsn(0x70);
10488 4 : let mut data = Vec::new();
10489 4 : let mut end_lsn = Lsn(0);
10490 44 : for i in 0..10 {
10491 40 : let key = get_key(i);
10492 40 : let lsn = Lsn(start_lsn.0 + i as u64);
10493 40 : let delta = format!("@{lsn}");
10494 40 : data.push((
10495 40 : key,
10496 40 : lsn,
10497 40 : Value::WalRecord(NeonWalRecord::wal_append(&delta)),
10498 40 : ));
10499 40 :
10500 40 : expected_key_values
10501 40 : .get_mut(&key)
10502 40 : .expect("An image exists for each key")
10503 40 : .push_str(delta.as_str());
10504 40 :
10505 40 : end_lsn = std::cmp::max(end_lsn, lsn);
10506 40 : }
10507 4 :
10508 4 : (
10509 4 : InMemoryLayerTestDesc {
10510 4 : lsn_range: start_lsn..Lsn::MAX,
10511 4 : is_open: true,
10512 4 : data,
10513 4 : },
10514 4 : end_lsn,
10515 4 : )
10516 4 : };
10517 4 :
10518 4 : assert!(
10519 4 : nested_image_layer_lsn > frozen_layer.lsn_range.start
10520 4 : && nested_image_layer_lsn < frozen_layer.lsn_range.end
10521 4 : );
10522 4 :
10523 4 : let tline = tenant
10524 4 : .create_test_timeline_with_layers(
10525 4 : TIMELINE_ID,
10526 4 : baseline_image_layer_lsn,
10527 4 : DEFAULT_PG_VERSION,
10528 4 : &ctx,
10529 4 : vec![open_layer, frozen_layer], // in-memory layers
10530 4 : Vec::new(), // delta layers
10531 4 : vec![
10532 4 : (baseline_image_layer_lsn, baseline_img_layer),
10533 4 : (nested_image_layer_lsn, nested_img_layer),
10534 4 : ], // image layers
10535 4 : last_record_lsn,
10536 4 : )
10537 4 : .await?;
10538 4 :
10539 4 : let keyspace = KeySpace::single(get_key(0)..get_key(10));
10540 4 : let results = tline
10541 4 : .get_vectored(keyspace, last_record_lsn, IoConcurrency::sequential(), &ctx)
10542 4 : .await
10543 4 : .expect("No vectored errors");
10544 44 : for (key, res) in results {
10545 40 : let value = res.expect("No key errors");
10546 40 : let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
10547 40 : assert_eq!(value, Bytes::from(expected_value.clone()));
10548 4 :
10549 40 : tracing::info!("key={key} value={expected_value}");
10550 4 : }
10551 4 :
10552 4 : Ok(())
10553 4 : }
10554 :
10555 428 : fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
10556 428 : (
10557 428 : k1.is_delta,
10558 428 : k1.key_range.start,
10559 428 : k1.key_range.end,
10560 428 : k1.lsn_range.start,
10561 428 : k1.lsn_range.end,
10562 428 : )
10563 428 : .cmp(&(
10564 428 : k2.is_delta,
10565 428 : k2.key_range.start,
10566 428 : k2.key_range.end,
10567 428 : k2.lsn_range.start,
10568 428 : k2.lsn_range.end,
10569 428 : ))
10570 428 : }
10571 :
10572 48 : async fn inspect_and_sort(
10573 48 : tline: &Arc<Timeline>,
10574 48 : filter: Option<std::ops::Range<Key>>,
10575 48 : ) -> Vec<PersistentLayerKey> {
10576 48 : let mut all_layers = tline.inspect_historic_layers().await.unwrap();
10577 48 : if let Some(filter) = filter {
10578 216 : all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
10579 44 : }
10580 48 : all_layers.sort_by(sort_layer_key);
10581 48 : all_layers
10582 48 : }
10583 :
10584 : #[cfg(feature = "testing")]
10585 44 : fn check_layer_map_key_eq(
10586 44 : mut left: Vec<PersistentLayerKey>,
10587 44 : mut right: Vec<PersistentLayerKey>,
10588 44 : ) {
10589 44 : left.sort_by(sort_layer_key);
10590 44 : right.sort_by(sort_layer_key);
10591 44 : if left != right {
10592 0 : eprintln!("---LEFT---");
10593 0 : for left in left.iter() {
10594 0 : eprintln!("{}", left);
10595 0 : }
10596 0 : eprintln!("---RIGHT---");
10597 0 : for right in right.iter() {
10598 0 : eprintln!("{}", right);
10599 0 : }
10600 0 : assert_eq!(left, right);
10601 44 : }
10602 44 : }
10603 :
10604 : #[cfg(feature = "testing")]
10605 : #[tokio::test]
10606 4 : async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
10607 4 : let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
10608 4 : let (tenant, ctx) = harness.load().await;
10609 4 :
10610 364 : fn get_key(id: u32) -> Key {
10611 364 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
10612 364 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
10613 364 : key.field6 = id;
10614 364 : key
10615 364 : }
10616 4 :
10617 4 : // img layer at 0x10
10618 4 : let img_layer = (0..10)
10619 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10620 4 : .collect_vec();
10621 4 :
10622 4 : let delta1 = vec![
10623 4 : (
10624 4 : get_key(1),
10625 4 : Lsn(0x20),
10626 4 : Value::Image(Bytes::from("value 1@0x20")),
10627 4 : ),
10628 4 : (
10629 4 : get_key(2),
10630 4 : Lsn(0x30),
10631 4 : Value::Image(Bytes::from("value 2@0x30")),
10632 4 : ),
10633 4 : (
10634 4 : get_key(3),
10635 4 : Lsn(0x40),
10636 4 : Value::Image(Bytes::from("value 3@0x40")),
10637 4 : ),
10638 4 : ];
10639 4 : let delta2 = vec![
10640 4 : (
10641 4 : get_key(5),
10642 4 : Lsn(0x20),
10643 4 : Value::Image(Bytes::from("value 5@0x20")),
10644 4 : ),
10645 4 : (
10646 4 : get_key(6),
10647 4 : Lsn(0x20),
10648 4 : Value::Image(Bytes::from("value 6@0x20")),
10649 4 : ),
10650 4 : ];
10651 4 : let delta3 = vec![
10652 4 : (
10653 4 : get_key(8),
10654 4 : Lsn(0x48),
10655 4 : Value::Image(Bytes::from("value 8@0x48")),
10656 4 : ),
10657 4 : (
10658 4 : get_key(9),
10659 4 : Lsn(0x48),
10660 4 : Value::Image(Bytes::from("value 9@0x48")),
10661 4 : ),
10662 4 : ];
10663 4 :
10664 4 : let tline = tenant
10665 4 : .create_test_timeline_with_layers(
10666 4 : TIMELINE_ID,
10667 4 : Lsn(0x10),
10668 4 : DEFAULT_PG_VERSION,
10669 4 : &ctx,
10670 4 : vec![], // in-memory layers
10671 4 : vec![
10672 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
10673 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
10674 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
10675 4 : ], // delta layers
10676 4 : vec![(Lsn(0x10), img_layer)], // image layers
10677 4 : Lsn(0x50),
10678 4 : )
10679 4 : .await?;
10680 4 :
10681 4 : {
10682 4 : tline
10683 4 : .applied_gc_cutoff_lsn
10684 4 : .lock_for_write()
10685 4 : .store_and_unlock(Lsn(0x30))
10686 4 : .wait()
10687 4 : .await;
10688 4 : // Update GC info
10689 4 : let mut guard = tline.gc_info.write().unwrap();
10690 4 : *guard = GcInfo {
10691 4 : retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
10692 4 : cutoffs: GcCutoffs {
10693 4 : time: Lsn(0x30),
10694 4 : space: Lsn(0x30),
10695 4 : },
10696 4 : leases: Default::default(),
10697 4 : within_ancestor_pitr: false,
10698 4 : };
10699 4 : }
10700 4 :
10701 4 : let cancel = CancellationToken::new();
10702 4 :
10703 4 : // Do a partial compaction on key range 0..2
10704 4 : tline
10705 4 : .compact_with_gc(
10706 4 : &cancel,
10707 4 : CompactOptions {
10708 4 : flags: EnumSet::new(),
10709 4 : compact_key_range: Some((get_key(0)..get_key(2)).into()),
10710 4 : ..Default::default()
10711 4 : },
10712 4 : &ctx,
10713 4 : )
10714 4 : .await
10715 4 : .unwrap();
10716 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10717 4 : check_layer_map_key_eq(
10718 4 : all_layers,
10719 4 : vec![
10720 4 : // newly-generated image layer for the partial compaction range 0-2
10721 4 : PersistentLayerKey {
10722 4 : key_range: get_key(0)..get_key(2),
10723 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10724 4 : is_delta: false,
10725 4 : },
10726 4 : PersistentLayerKey {
10727 4 : key_range: get_key(0)..get_key(10),
10728 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10729 4 : is_delta: false,
10730 4 : },
10731 4 : // delta1 is split and the second part is rewritten
10732 4 : PersistentLayerKey {
10733 4 : key_range: get_key(2)..get_key(4),
10734 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10735 4 : is_delta: true,
10736 4 : },
10737 4 : PersistentLayerKey {
10738 4 : key_range: get_key(5)..get_key(7),
10739 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10740 4 : is_delta: true,
10741 4 : },
10742 4 : PersistentLayerKey {
10743 4 : key_range: get_key(8)..get_key(10),
10744 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10745 4 : is_delta: true,
10746 4 : },
10747 4 : ],
10748 4 : );
10749 4 :
10750 4 : // Do a partial compaction on key range 2..4
10751 4 : tline
10752 4 : .compact_with_gc(
10753 4 : &cancel,
10754 4 : CompactOptions {
10755 4 : flags: EnumSet::new(),
10756 4 : compact_key_range: Some((get_key(2)..get_key(4)).into()),
10757 4 : ..Default::default()
10758 4 : },
10759 4 : &ctx,
10760 4 : )
10761 4 : .await
10762 4 : .unwrap();
10763 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10764 4 : check_layer_map_key_eq(
10765 4 : all_layers,
10766 4 : vec![
10767 4 : PersistentLayerKey {
10768 4 : key_range: get_key(0)..get_key(2),
10769 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10770 4 : is_delta: false,
10771 4 : },
10772 4 : PersistentLayerKey {
10773 4 : key_range: get_key(0)..get_key(10),
10774 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10775 4 : is_delta: false,
10776 4 : },
10777 4 : // image layer generated for the compaction range 2-4
10778 4 : PersistentLayerKey {
10779 4 : key_range: get_key(2)..get_key(4),
10780 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10781 4 : is_delta: false,
10782 4 : },
10783 4 : // we have key2/key3 above the retain_lsn, so we still need this delta layer
10784 4 : PersistentLayerKey {
10785 4 : key_range: get_key(2)..get_key(4),
10786 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10787 4 : is_delta: true,
10788 4 : },
10789 4 : PersistentLayerKey {
10790 4 : key_range: get_key(5)..get_key(7),
10791 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10792 4 : is_delta: true,
10793 4 : },
10794 4 : PersistentLayerKey {
10795 4 : key_range: get_key(8)..get_key(10),
10796 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10797 4 : is_delta: true,
10798 4 : },
10799 4 : ],
10800 4 : );
10801 4 :
10802 4 : // Do a partial compaction on key range 4..9
10803 4 : tline
10804 4 : .compact_with_gc(
10805 4 : &cancel,
10806 4 : CompactOptions {
10807 4 : flags: EnumSet::new(),
10808 4 : compact_key_range: Some((get_key(4)..get_key(9)).into()),
10809 4 : ..Default::default()
10810 4 : },
10811 4 : &ctx,
10812 4 : )
10813 4 : .await
10814 4 : .unwrap();
10815 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10816 4 : check_layer_map_key_eq(
10817 4 : all_layers,
10818 4 : vec![
10819 4 : PersistentLayerKey {
10820 4 : key_range: get_key(0)..get_key(2),
10821 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10822 4 : is_delta: false,
10823 4 : },
10824 4 : PersistentLayerKey {
10825 4 : key_range: get_key(0)..get_key(10),
10826 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10827 4 : is_delta: false,
10828 4 : },
10829 4 : PersistentLayerKey {
10830 4 : key_range: get_key(2)..get_key(4),
10831 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10832 4 : is_delta: false,
10833 4 : },
10834 4 : PersistentLayerKey {
10835 4 : key_range: get_key(2)..get_key(4),
10836 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10837 4 : is_delta: true,
10838 4 : },
10839 4 : // image layer generated for this compaction range
10840 4 : PersistentLayerKey {
10841 4 : key_range: get_key(4)..get_key(9),
10842 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10843 4 : is_delta: false,
10844 4 : },
10845 4 : PersistentLayerKey {
10846 4 : key_range: get_key(8)..get_key(10),
10847 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10848 4 : is_delta: true,
10849 4 : },
10850 4 : ],
10851 4 : );
10852 4 :
10853 4 : // Do a partial compaction on key range 9..10
10854 4 : tline
10855 4 : .compact_with_gc(
10856 4 : &cancel,
10857 4 : CompactOptions {
10858 4 : flags: EnumSet::new(),
10859 4 : compact_key_range: Some((get_key(9)..get_key(10)).into()),
10860 4 : ..Default::default()
10861 4 : },
10862 4 : &ctx,
10863 4 : )
10864 4 : .await
10865 4 : .unwrap();
10866 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10867 4 : check_layer_map_key_eq(
10868 4 : all_layers,
10869 4 : vec![
10870 4 : PersistentLayerKey {
10871 4 : key_range: get_key(0)..get_key(2),
10872 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10873 4 : is_delta: false,
10874 4 : },
10875 4 : PersistentLayerKey {
10876 4 : key_range: get_key(0)..get_key(10),
10877 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10878 4 : is_delta: false,
10879 4 : },
10880 4 : PersistentLayerKey {
10881 4 : key_range: get_key(2)..get_key(4),
10882 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10883 4 : is_delta: false,
10884 4 : },
10885 4 : PersistentLayerKey {
10886 4 : key_range: get_key(2)..get_key(4),
10887 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10888 4 : is_delta: true,
10889 4 : },
10890 4 : PersistentLayerKey {
10891 4 : key_range: get_key(4)..get_key(9),
10892 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10893 4 : is_delta: false,
10894 4 : },
10895 4 : // image layer generated for the compaction range
10896 4 : PersistentLayerKey {
10897 4 : key_range: get_key(9)..get_key(10),
10898 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10899 4 : is_delta: false,
10900 4 : },
10901 4 : PersistentLayerKey {
10902 4 : key_range: get_key(8)..get_key(10),
10903 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10904 4 : is_delta: true,
10905 4 : },
10906 4 : ],
10907 4 : );
10908 4 :
10909 4 : // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
10910 4 : tline
10911 4 : .compact_with_gc(
10912 4 : &cancel,
10913 4 : CompactOptions {
10914 4 : flags: EnumSet::new(),
10915 4 : compact_key_range: Some((get_key(0)..get_key(10)).into()),
10916 4 : ..Default::default()
10917 4 : },
10918 4 : &ctx,
10919 4 : )
10920 4 : .await
10921 4 : .unwrap();
10922 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10923 4 : check_layer_map_key_eq(
10924 4 : all_layers,
10925 4 : vec![
10926 4 : // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
10927 4 : PersistentLayerKey {
10928 4 : key_range: get_key(0)..get_key(10),
10929 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10930 4 : is_delta: false,
10931 4 : },
10932 4 : PersistentLayerKey {
10933 4 : key_range: get_key(2)..get_key(4),
10934 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10935 4 : is_delta: true,
10936 4 : },
10937 4 : PersistentLayerKey {
10938 4 : key_range: get_key(8)..get_key(10),
10939 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10940 4 : is_delta: true,
10941 4 : },
10942 4 : ],
10943 4 : );
10944 4 : Ok(())
10945 4 : }
10946 :
10947 : #[cfg(feature = "testing")]
10948 : #[tokio::test]
10949 4 : async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
10950 4 : let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
10951 4 : .await
10952 4 : .unwrap();
10953 4 : let (tenant, ctx) = harness.load().await;
10954 4 : let tline_parent = tenant
10955 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
10956 4 : .await
10957 4 : .unwrap();
10958 4 : let tline_child = tenant
10959 4 : .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
10960 4 : .await
10961 4 : .unwrap();
10962 4 : {
10963 4 : let gc_info_parent = tline_parent.gc_info.read().unwrap();
10964 4 : assert_eq!(
10965 4 : gc_info_parent.retain_lsns,
10966 4 : vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
10967 4 : );
10968 4 : }
10969 4 : // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
10970 4 : tline_child
10971 4 : .remote_client
10972 4 : .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
10973 4 : .unwrap();
10974 4 : tline_child.remote_client.wait_completion().await.unwrap();
10975 4 : offload_timeline(&tenant, &tline_child)
10976 4 : .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
10977 4 : .await.unwrap();
10978 4 : let child_timeline_id = tline_child.timeline_id;
10979 4 : Arc::try_unwrap(tline_child).unwrap();
10980 4 :
10981 4 : {
10982 4 : let gc_info_parent = tline_parent.gc_info.read().unwrap();
10983 4 : assert_eq!(
10984 4 : gc_info_parent.retain_lsns,
10985 4 : vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
10986 4 : );
10987 4 : }
10988 4 :
10989 4 : tenant
10990 4 : .get_offloaded_timeline(child_timeline_id)
10991 4 : .unwrap()
10992 4 : .defuse_for_tenant_drop();
10993 4 :
10994 4 : Ok(())
10995 4 : }
10996 :
10997 : #[cfg(feature = "testing")]
10998 : #[tokio::test]
10999 4 : async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
11000 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
11001 4 : let (tenant, ctx) = harness.load().await;
11002 4 :
11003 592 : fn get_key(id: u32) -> Key {
11004 592 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
11005 592 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
11006 592 : key.field6 = id;
11007 592 : key
11008 592 : }
11009 4 :
11010 4 : let img_layer = (0..10)
11011 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
11012 4 : .collect_vec();
11013 4 :
11014 4 : let delta1 = vec![(
11015 4 : get_key(1),
11016 4 : Lsn(0x20),
11017 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
11018 4 : )];
11019 4 : let delta4 = vec![(
11020 4 : get_key(1),
11021 4 : Lsn(0x28),
11022 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
11023 4 : )];
11024 4 : let delta2 = vec![
11025 4 : (
11026 4 : get_key(1),
11027 4 : Lsn(0x30),
11028 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
11029 4 : ),
11030 4 : (
11031 4 : get_key(1),
11032 4 : Lsn(0x38),
11033 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
11034 4 : ),
11035 4 : ];
11036 4 : let delta3 = vec![
11037 4 : (
11038 4 : get_key(8),
11039 4 : Lsn(0x48),
11040 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
11041 4 : ),
11042 4 : (
11043 4 : get_key(9),
11044 4 : Lsn(0x48),
11045 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
11046 4 : ),
11047 4 : ];
11048 4 :
11049 4 : let tline = tenant
11050 4 : .create_test_timeline_with_layers(
11051 4 : TIMELINE_ID,
11052 4 : Lsn(0x10),
11053 4 : DEFAULT_PG_VERSION,
11054 4 : &ctx,
11055 4 : vec![], // in-memory layers
11056 4 : vec![
11057 4 : // delta1/2/4 only contain a single key but multiple updates
11058 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
11059 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
11060 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
11061 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
11062 4 : ], // delta layers
11063 4 : vec![(Lsn(0x10), img_layer)], // image layers
11064 4 : Lsn(0x50),
11065 4 : )
11066 4 : .await?;
11067 4 : {
11068 4 : tline
11069 4 : .applied_gc_cutoff_lsn
11070 4 : .lock_for_write()
11071 4 : .store_and_unlock(Lsn(0x30))
11072 4 : .wait()
11073 4 : .await;
11074 4 : // Update GC info
11075 4 : let mut guard = tline.gc_info.write().unwrap();
11076 4 : *guard = GcInfo {
11077 4 : retain_lsns: vec![
11078 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
11079 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
11080 4 : ],
11081 4 : cutoffs: GcCutoffs {
11082 4 : time: Lsn(0x30),
11083 4 : space: Lsn(0x30),
11084 4 : },
11085 4 : leases: Default::default(),
11086 4 : within_ancestor_pitr: false,
11087 4 : };
11088 4 : }
11089 4 :
11090 4 : let expected_result = [
11091 4 : Bytes::from_static(b"value 0@0x10"),
11092 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
11093 4 : Bytes::from_static(b"value 2@0x10"),
11094 4 : Bytes::from_static(b"value 3@0x10"),
11095 4 : Bytes::from_static(b"value 4@0x10"),
11096 4 : Bytes::from_static(b"value 5@0x10"),
11097 4 : Bytes::from_static(b"value 6@0x10"),
11098 4 : Bytes::from_static(b"value 7@0x10"),
11099 4 : Bytes::from_static(b"value 8@0x10@0x48"),
11100 4 : Bytes::from_static(b"value 9@0x10@0x48"),
11101 4 : ];
11102 4 :
11103 4 : let expected_result_at_gc_horizon = [
11104 4 : Bytes::from_static(b"value 0@0x10"),
11105 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
11106 4 : Bytes::from_static(b"value 2@0x10"),
11107 4 : Bytes::from_static(b"value 3@0x10"),
11108 4 : Bytes::from_static(b"value 4@0x10"),
11109 4 : Bytes::from_static(b"value 5@0x10"),
11110 4 : Bytes::from_static(b"value 6@0x10"),
11111 4 : Bytes::from_static(b"value 7@0x10"),
11112 4 : Bytes::from_static(b"value 8@0x10"),
11113 4 : Bytes::from_static(b"value 9@0x10"),
11114 4 : ];
11115 4 :
11116 4 : let expected_result_at_lsn_20 = [
11117 4 : Bytes::from_static(b"value 0@0x10"),
11118 4 : Bytes::from_static(b"value 1@0x10@0x20"),
11119 4 : Bytes::from_static(b"value 2@0x10"),
11120 4 : Bytes::from_static(b"value 3@0x10"),
11121 4 : Bytes::from_static(b"value 4@0x10"),
11122 4 : Bytes::from_static(b"value 5@0x10"),
11123 4 : Bytes::from_static(b"value 6@0x10"),
11124 4 : Bytes::from_static(b"value 7@0x10"),
11125 4 : Bytes::from_static(b"value 8@0x10"),
11126 4 : Bytes::from_static(b"value 9@0x10"),
11127 4 : ];
11128 4 :
11129 4 : let expected_result_at_lsn_10 = [
11130 4 : Bytes::from_static(b"value 0@0x10"),
11131 4 : Bytes::from_static(b"value 1@0x10"),
11132 4 : Bytes::from_static(b"value 2@0x10"),
11133 4 : Bytes::from_static(b"value 3@0x10"),
11134 4 : Bytes::from_static(b"value 4@0x10"),
11135 4 : Bytes::from_static(b"value 5@0x10"),
11136 4 : Bytes::from_static(b"value 6@0x10"),
11137 4 : Bytes::from_static(b"value 7@0x10"),
11138 4 : Bytes::from_static(b"value 8@0x10"),
11139 4 : Bytes::from_static(b"value 9@0x10"),
11140 4 : ];
11141 4 :
11142 12 : let verify_result = || async {
11143 12 : let gc_horizon = {
11144 12 : let gc_info = tline.gc_info.read().unwrap();
11145 12 : gc_info.cutoffs.time
11146 4 : };
11147 132 : for idx in 0..10 {
11148 120 : assert_eq!(
11149 120 : tline
11150 120 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
11151 120 : .await
11152 120 : .unwrap(),
11153 120 : &expected_result[idx]
11154 4 : );
11155 120 : assert_eq!(
11156 120 : tline
11157 120 : .get(get_key(idx as u32), gc_horizon, &ctx)
11158 120 : .await
11159 120 : .unwrap(),
11160 120 : &expected_result_at_gc_horizon[idx]
11161 4 : );
11162 120 : assert_eq!(
11163 120 : tline
11164 120 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
11165 120 : .await
11166 120 : .unwrap(),
11167 120 : &expected_result_at_lsn_20[idx]
11168 4 : );
11169 120 : assert_eq!(
11170 120 : tline
11171 120 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
11172 120 : .await
11173 120 : .unwrap(),
11174 120 : &expected_result_at_lsn_10[idx]
11175 4 : );
11176 4 : }
11177 24 : };
11178 4 :
11179 4 : verify_result().await;
11180 4 :
11181 4 : let cancel = CancellationToken::new();
11182 4 : tline
11183 4 : .compact_with_gc(
11184 4 : &cancel,
11185 4 : CompactOptions {
11186 4 : compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
11187 4 : ..Default::default()
11188 4 : },
11189 4 : &ctx,
11190 4 : )
11191 4 : .await
11192 4 : .unwrap();
11193 4 : verify_result().await;
11194 4 :
11195 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11196 4 : check_layer_map_key_eq(
11197 4 : all_layers,
11198 4 : vec![
11199 4 : // The original image layer, not compacted
11200 4 : PersistentLayerKey {
11201 4 : key_range: get_key(0)..get_key(10),
11202 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11203 4 : is_delta: false,
11204 4 : },
11205 4 : // Delta layer below the specified above_lsn not compacted
11206 4 : PersistentLayerKey {
11207 4 : key_range: get_key(1)..get_key(2),
11208 4 : lsn_range: Lsn(0x20)..Lsn(0x28),
11209 4 : is_delta: true,
11210 4 : },
11211 4 : // Delta layer compacted above the LSN
11212 4 : PersistentLayerKey {
11213 4 : key_range: get_key(1)..get_key(10),
11214 4 : lsn_range: Lsn(0x28)..Lsn(0x50),
11215 4 : is_delta: true,
11216 4 : },
11217 4 : ],
11218 4 : );
11219 4 :
11220 4 : // compact again
11221 4 : tline
11222 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
11223 4 : .await
11224 4 : .unwrap();
11225 4 : verify_result().await;
11226 4 :
11227 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11228 4 : check_layer_map_key_eq(
11229 4 : all_layers,
11230 4 : vec![
11231 4 : // The compacted image layer (full key range)
11232 4 : PersistentLayerKey {
11233 4 : key_range: Key::MIN..Key::MAX,
11234 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11235 4 : is_delta: false,
11236 4 : },
11237 4 : // All other data in the delta layer
11238 4 : PersistentLayerKey {
11239 4 : key_range: get_key(1)..get_key(10),
11240 4 : lsn_range: Lsn(0x10)..Lsn(0x50),
11241 4 : is_delta: true,
11242 4 : },
11243 4 : ],
11244 4 : );
11245 4 :
11246 4 : Ok(())
11247 4 : }
11248 :
11249 : #[cfg(feature = "testing")]
11250 : #[tokio::test]
11251 4 : async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
11252 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
11253 4 : let (tenant, ctx) = harness.load().await;
11254 4 :
11255 1016 : fn get_key(id: u32) -> Key {
11256 1016 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
11257 1016 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
11258 1016 : key.field6 = id;
11259 1016 : key
11260 1016 : }
11261 4 :
11262 4 : let img_layer = (0..10)
11263 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
11264 4 : .collect_vec();
11265 4 :
11266 4 : let delta1 = vec![(
11267 4 : get_key(1),
11268 4 : Lsn(0x20),
11269 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
11270 4 : )];
11271 4 : let delta4 = vec![(
11272 4 : get_key(1),
11273 4 : Lsn(0x28),
11274 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
11275 4 : )];
11276 4 : let delta2 = vec![
11277 4 : (
11278 4 : get_key(1),
11279 4 : Lsn(0x30),
11280 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
11281 4 : ),
11282 4 : (
11283 4 : get_key(1),
11284 4 : Lsn(0x38),
11285 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
11286 4 : ),
11287 4 : ];
11288 4 : let delta3 = vec![
11289 4 : (
11290 4 : get_key(8),
11291 4 : Lsn(0x48),
11292 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
11293 4 : ),
11294 4 : (
11295 4 : get_key(9),
11296 4 : Lsn(0x48),
11297 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
11298 4 : ),
11299 4 : ];
11300 4 :
11301 4 : let tline = tenant
11302 4 : .create_test_timeline_with_layers(
11303 4 : TIMELINE_ID,
11304 4 : Lsn(0x10),
11305 4 : DEFAULT_PG_VERSION,
11306 4 : &ctx,
11307 4 : vec![], // in-memory layers
11308 4 : vec![
11309 4 : // delta1/2/4 only contain a single key but multiple updates
11310 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
11311 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
11312 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
11313 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
11314 4 : ], // delta layers
11315 4 : vec![(Lsn(0x10), img_layer)], // image layers
11316 4 : Lsn(0x50),
11317 4 : )
11318 4 : .await?;
11319 4 : {
11320 4 : tline
11321 4 : .applied_gc_cutoff_lsn
11322 4 : .lock_for_write()
11323 4 : .store_and_unlock(Lsn(0x30))
11324 4 : .wait()
11325 4 : .await;
11326 4 : // Update GC info
11327 4 : let mut guard = tline.gc_info.write().unwrap();
11328 4 : *guard = GcInfo {
11329 4 : retain_lsns: vec![
11330 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
11331 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
11332 4 : ],
11333 4 : cutoffs: GcCutoffs {
11334 4 : time: Lsn(0x30),
11335 4 : space: Lsn(0x30),
11336 4 : },
11337 4 : leases: Default::default(),
11338 4 : within_ancestor_pitr: false,
11339 4 : };
11340 4 : }
11341 4 :
11342 4 : let expected_result = [
11343 4 : Bytes::from_static(b"value 0@0x10"),
11344 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
11345 4 : Bytes::from_static(b"value 2@0x10"),
11346 4 : Bytes::from_static(b"value 3@0x10"),
11347 4 : Bytes::from_static(b"value 4@0x10"),
11348 4 : Bytes::from_static(b"value 5@0x10"),
11349 4 : Bytes::from_static(b"value 6@0x10"),
11350 4 : Bytes::from_static(b"value 7@0x10"),
11351 4 : Bytes::from_static(b"value 8@0x10@0x48"),
11352 4 : Bytes::from_static(b"value 9@0x10@0x48"),
11353 4 : ];
11354 4 :
11355 4 : let expected_result_at_gc_horizon = [
11356 4 : Bytes::from_static(b"value 0@0x10"),
11357 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
11358 4 : Bytes::from_static(b"value 2@0x10"),
11359 4 : Bytes::from_static(b"value 3@0x10"),
11360 4 : Bytes::from_static(b"value 4@0x10"),
11361 4 : Bytes::from_static(b"value 5@0x10"),
11362 4 : Bytes::from_static(b"value 6@0x10"),
11363 4 : Bytes::from_static(b"value 7@0x10"),
11364 4 : Bytes::from_static(b"value 8@0x10"),
11365 4 : Bytes::from_static(b"value 9@0x10"),
11366 4 : ];
11367 4 :
11368 4 : let expected_result_at_lsn_20 = [
11369 4 : Bytes::from_static(b"value 0@0x10"),
11370 4 : Bytes::from_static(b"value 1@0x10@0x20"),
11371 4 : Bytes::from_static(b"value 2@0x10"),
11372 4 : Bytes::from_static(b"value 3@0x10"),
11373 4 : Bytes::from_static(b"value 4@0x10"),
11374 4 : Bytes::from_static(b"value 5@0x10"),
11375 4 : Bytes::from_static(b"value 6@0x10"),
11376 4 : Bytes::from_static(b"value 7@0x10"),
11377 4 : Bytes::from_static(b"value 8@0x10"),
11378 4 : Bytes::from_static(b"value 9@0x10"),
11379 4 : ];
11380 4 :
11381 4 : let expected_result_at_lsn_10 = [
11382 4 : Bytes::from_static(b"value 0@0x10"),
11383 4 : Bytes::from_static(b"value 1@0x10"),
11384 4 : Bytes::from_static(b"value 2@0x10"),
11385 4 : Bytes::from_static(b"value 3@0x10"),
11386 4 : Bytes::from_static(b"value 4@0x10"),
11387 4 : Bytes::from_static(b"value 5@0x10"),
11388 4 : Bytes::from_static(b"value 6@0x10"),
11389 4 : Bytes::from_static(b"value 7@0x10"),
11390 4 : Bytes::from_static(b"value 8@0x10"),
11391 4 : Bytes::from_static(b"value 9@0x10"),
11392 4 : ];
11393 4 :
11394 20 : let verify_result = || async {
11395 20 : let gc_horizon = {
11396 20 : let gc_info = tline.gc_info.read().unwrap();
11397 20 : gc_info.cutoffs.time
11398 4 : };
11399 220 : for idx in 0..10 {
11400 200 : assert_eq!(
11401 200 : tline
11402 200 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
11403 200 : .await
11404 200 : .unwrap(),
11405 200 : &expected_result[idx]
11406 4 : );
11407 200 : assert_eq!(
11408 200 : tline
11409 200 : .get(get_key(idx as u32), gc_horizon, &ctx)
11410 200 : .await
11411 200 : .unwrap(),
11412 200 : &expected_result_at_gc_horizon[idx]
11413 4 : );
11414 200 : assert_eq!(
11415 200 : tline
11416 200 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
11417 200 : .await
11418 200 : .unwrap(),
11419 200 : &expected_result_at_lsn_20[idx]
11420 4 : );
11421 200 : assert_eq!(
11422 200 : tline
11423 200 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
11424 200 : .await
11425 200 : .unwrap(),
11426 200 : &expected_result_at_lsn_10[idx]
11427 4 : );
11428 4 : }
11429 40 : };
11430 4 :
11431 4 : verify_result().await;
11432 4 :
11433 4 : let cancel = CancellationToken::new();
11434 4 :
11435 4 : tline
11436 4 : .compact_with_gc(
11437 4 : &cancel,
11438 4 : CompactOptions {
11439 4 : compact_key_range: Some((get_key(0)..get_key(2)).into()),
11440 4 : compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
11441 4 : ..Default::default()
11442 4 : },
11443 4 : &ctx,
11444 4 : )
11445 4 : .await
11446 4 : .unwrap();
11447 4 : verify_result().await;
11448 4 :
11449 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11450 4 : check_layer_map_key_eq(
11451 4 : all_layers,
11452 4 : vec![
11453 4 : // The original image layer, not compacted
11454 4 : PersistentLayerKey {
11455 4 : key_range: get_key(0)..get_key(10),
11456 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11457 4 : is_delta: false,
11458 4 : },
11459 4 : // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
11460 4 : // the layer 0x28-0x30 into one.
11461 4 : PersistentLayerKey {
11462 4 : key_range: get_key(1)..get_key(2),
11463 4 : lsn_range: Lsn(0x20)..Lsn(0x30),
11464 4 : is_delta: true,
11465 4 : },
11466 4 : // Above the upper bound and untouched
11467 4 : PersistentLayerKey {
11468 4 : key_range: get_key(1)..get_key(2),
11469 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11470 4 : is_delta: true,
11471 4 : },
11472 4 : // This layer is untouched
11473 4 : PersistentLayerKey {
11474 4 : key_range: get_key(8)..get_key(10),
11475 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11476 4 : is_delta: true,
11477 4 : },
11478 4 : ],
11479 4 : );
11480 4 :
11481 4 : tline
11482 4 : .compact_with_gc(
11483 4 : &cancel,
11484 4 : CompactOptions {
11485 4 : compact_key_range: Some((get_key(3)..get_key(8)).into()),
11486 4 : compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
11487 4 : ..Default::default()
11488 4 : },
11489 4 : &ctx,
11490 4 : )
11491 4 : .await
11492 4 : .unwrap();
11493 4 : verify_result().await;
11494 4 :
11495 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11496 4 : check_layer_map_key_eq(
11497 4 : all_layers,
11498 4 : vec![
11499 4 : // The original image layer, not compacted
11500 4 : PersistentLayerKey {
11501 4 : key_range: get_key(0)..get_key(10),
11502 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11503 4 : is_delta: false,
11504 4 : },
11505 4 : // Not in the compaction key range, uncompacted
11506 4 : PersistentLayerKey {
11507 4 : key_range: get_key(1)..get_key(2),
11508 4 : lsn_range: Lsn(0x20)..Lsn(0x30),
11509 4 : is_delta: true,
11510 4 : },
11511 4 : // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
11512 4 : PersistentLayerKey {
11513 4 : key_range: get_key(1)..get_key(2),
11514 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11515 4 : is_delta: true,
11516 4 : },
11517 4 : // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
11518 4 : // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
11519 4 : // becomes 0x50.
11520 4 : PersistentLayerKey {
11521 4 : key_range: get_key(8)..get_key(10),
11522 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11523 4 : is_delta: true,
11524 4 : },
11525 4 : ],
11526 4 : );
11527 4 :
11528 4 : // compact again
11529 4 : tline
11530 4 : .compact_with_gc(
11531 4 : &cancel,
11532 4 : CompactOptions {
11533 4 : compact_key_range: Some((get_key(0)..get_key(5)).into()),
11534 4 : compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
11535 4 : ..Default::default()
11536 4 : },
11537 4 : &ctx,
11538 4 : )
11539 4 : .await
11540 4 : .unwrap();
11541 4 : verify_result().await;
11542 4 :
11543 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11544 4 : check_layer_map_key_eq(
11545 4 : all_layers,
11546 4 : vec![
11547 4 : // The original image layer, not compacted
11548 4 : PersistentLayerKey {
11549 4 : key_range: get_key(0)..get_key(10),
11550 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11551 4 : is_delta: false,
11552 4 : },
11553 4 : // The range gets compacted
11554 4 : PersistentLayerKey {
11555 4 : key_range: get_key(1)..get_key(2),
11556 4 : lsn_range: Lsn(0x20)..Lsn(0x50),
11557 4 : is_delta: true,
11558 4 : },
11559 4 : // Not touched during this iteration of compaction
11560 4 : PersistentLayerKey {
11561 4 : key_range: get_key(8)..get_key(10),
11562 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11563 4 : is_delta: true,
11564 4 : },
11565 4 : ],
11566 4 : );
11567 4 :
11568 4 : // final full compaction
11569 4 : tline
11570 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
11571 4 : .await
11572 4 : .unwrap();
11573 4 : verify_result().await;
11574 4 :
11575 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11576 4 : check_layer_map_key_eq(
11577 4 : all_layers,
11578 4 : vec![
11579 4 : // The compacted image layer (full key range)
11580 4 : PersistentLayerKey {
11581 4 : key_range: Key::MIN..Key::MAX,
11582 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11583 4 : is_delta: false,
11584 4 : },
11585 4 : // All other data in the delta layer
11586 4 : PersistentLayerKey {
11587 4 : key_range: get_key(1)..get_key(10),
11588 4 : lsn_range: Lsn(0x10)..Lsn(0x50),
11589 4 : is_delta: true,
11590 4 : },
11591 4 : ],
11592 4 : );
11593 4 :
11594 4 : Ok(())
11595 4 : }
11596 : }
|