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};
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;
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: pageserver_api::models::TenantConfig,
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(
174 452 : tenant_conf: pageserver_api::models::TenantConfig,
175 452 : location: AttachedLocationConfig,
176 452 : ) -> Self {
177 : // Sets a deadline before which we cannot proceed to GC due to lsn lease.
178 : //
179 : // We do this as the leases mapping are not persisted to disk. By delaying GC by lease
180 : // length, we guarantee that all the leases we granted before will have a chance to renew
181 : // when we run GC for the first time after restart / transition from AttachedMulti to AttachedSingle.
182 452 : let lsn_lease_deadline = if location.attach_mode == AttachmentMode::Single {
183 452 : Some(
184 452 : tokio::time::Instant::now()
185 452 : + tenant_conf
186 452 : .lsn_lease_length
187 452 : .unwrap_or(LsnLease::DEFAULT_LENGTH),
188 452 : )
189 : } else {
190 : // We don't use `lsn_lease_deadline` to delay GC in AttachedMulti and AttachedStale
191 : // because we don't do GC in these modes.
192 0 : None
193 : };
194 :
195 452 : Self {
196 452 : tenant_conf,
197 452 : location,
198 452 : lsn_lease_deadline,
199 452 : }
200 452 : }
201 :
202 452 : fn try_from(location_conf: LocationConf) -> anyhow::Result<Self> {
203 452 : match &location_conf.mode {
204 452 : LocationMode::Attached(attach_conf) => {
205 452 : Ok(Self::new(location_conf.tenant_conf, *attach_conf))
206 : }
207 : LocationMode::Secondary(_) => {
208 0 : anyhow::bail!(
209 0 : "Attempted to construct AttachedTenantConf from a LocationConf in secondary mode"
210 0 : )
211 : }
212 : }
213 452 : }
214 :
215 1524 : fn is_gc_blocked_by_lsn_lease_deadline(&self) -> bool {
216 1524 : self.lsn_lease_deadline
217 1524 : .map(|d| tokio::time::Instant::now() < d)
218 1524 : .unwrap_or(false)
219 1524 : }
220 : }
221 : struct TimelinePreload {
222 : timeline_id: TimelineId,
223 : client: RemoteTimelineClient,
224 : index_part: Result<MaybeDeletedIndexPart, DownloadError>,
225 : previous_heatmap: Option<PreviousHeatmap>,
226 : }
227 :
228 : pub(crate) struct TenantPreload {
229 : tenant_manifest: TenantManifest,
230 : /// Map from timeline ID to a possible timeline preload. It is None iff the timeline is offloaded according to the manifest.
231 : timelines: HashMap<TimelineId, Option<TimelinePreload>>,
232 : }
233 :
234 : /// When we spawn a tenant, there is a special mode for tenant creation that
235 : /// avoids trying to read anything from remote storage.
236 : pub(crate) enum SpawnMode {
237 : /// Activate as soon as possible
238 : Eager,
239 : /// Lazy activation in the background, with the option to skip the queue if the need comes up
240 : Lazy,
241 : }
242 :
243 : ///
244 : /// Tenant consists of multiple timelines. Keep them in a hash table.
245 : ///
246 : pub struct Tenant {
247 : // Global pageserver config parameters
248 : pub conf: &'static PageServerConf,
249 :
250 : /// The value creation timestamp, used to measure activation delay, see:
251 : /// <https://github.com/neondatabase/neon/issues/4025>
252 : constructed_at: Instant,
253 :
254 : state: watch::Sender<TenantState>,
255 :
256 : // Overridden tenant-specific config parameters.
257 : // We keep pageserver_api::models::TenantConfig sturct here to preserve the information
258 : // about parameters that are not set.
259 : // This is necessary to allow global config updates.
260 : tenant_conf: Arc<ArcSwap<AttachedTenantConf>>,
261 :
262 : tenant_shard_id: TenantShardId,
263 :
264 : // The detailed sharding information, beyond the number/count in tenant_shard_id
265 : shard_identity: ShardIdentity,
266 :
267 : /// The remote storage generation, used to protect S3 objects from split-brain.
268 : /// Does not change over the lifetime of the [`Tenant`] object.
269 : ///
270 : /// This duplicates the generation stored in LocationConf, but that structure is mutable:
271 : /// this copy enforces the invariant that generatio doesn't change during a Tenant's lifetime.
272 : generation: Generation,
273 :
274 : timelines: Mutex<HashMap<TimelineId, Arc<Timeline>>>,
275 :
276 : /// During timeline creation, we first insert the TimelineId to the
277 : /// creating map, then `timelines`, then remove it from the creating map.
278 : /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
279 : timelines_creating: std::sync::Mutex<HashSet<TimelineId>>,
280 :
281 : /// Possibly offloaded and archived timelines
282 : /// **Lock order**: if acquiring all (or a subset), acquire them in order `timelines`, `timelines_offloaded`, `timelines_creating`
283 : timelines_offloaded: Mutex<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
284 :
285 : /// Serialize writes of the tenant manifest to remote storage. If there are concurrent operations
286 : /// affecting the manifest, such as timeline deletion and timeline offload, they must wait for
287 : /// each other (this could be optimized to coalesce writes if necessary).
288 : ///
289 : /// The contents of the Mutex are the last manifest we successfully uploaded
290 : tenant_manifest_upload: tokio::sync::Mutex<Option<TenantManifest>>,
291 :
292 : // This mutex prevents creation of new timelines during GC.
293 : // Adding yet another mutex (in addition to `timelines`) is needed because holding
294 : // `timelines` mutex during all GC iteration
295 : // may block for a long time `get_timeline`, `get_timelines_state`,... and other operations
296 : // with timelines, which in turn may cause dropping replication connection, expiration of wait_for_lsn
297 : // timeout...
298 : gc_cs: tokio::sync::Mutex<()>,
299 : walredo_mgr: Option<Arc<WalRedoManager>>,
300 :
301 : // provides access to timeline data sitting in the remote storage
302 : pub(crate) remote_storage: GenericRemoteStorage,
303 :
304 : // Access to global deletion queue for when this tenant wants to schedule a deletion
305 : deletion_queue_client: DeletionQueueClient,
306 :
307 : /// Cached logical sizes updated updated on each [`Tenant::gather_size_inputs`].
308 : cached_logical_sizes: tokio::sync::Mutex<HashMap<(TimelineId, Lsn), u64>>,
309 : cached_synthetic_tenant_size: Arc<AtomicU64>,
310 :
311 : eviction_task_tenant_state: tokio::sync::Mutex<EvictionTaskTenantState>,
312 :
313 : /// Track repeated failures to compact, so that we can back off.
314 : /// Overhead of mutex is acceptable because compaction is done with a multi-second period.
315 : compaction_circuit_breaker: std::sync::Mutex<CircuitBreaker>,
316 :
317 : /// Signals the tenant compaction loop that there is L0 compaction work to be done.
318 : pub(crate) l0_compaction_trigger: Arc<Notify>,
319 :
320 : /// Scheduled gc-compaction tasks.
321 : scheduled_compaction_tasks: std::sync::Mutex<HashMap<TimelineId, Arc<GcCompactionQueue>>>,
322 :
323 : /// If the tenant is in Activating state, notify this to encourage it
324 : /// to proceed to Active as soon as possible, rather than waiting for lazy
325 : /// background warmup.
326 : pub(crate) activate_now_sem: tokio::sync::Semaphore,
327 :
328 : /// Time it took for the tenant to activate. Zero if not active yet.
329 : attach_wal_lag_cooldown: Arc<std::sync::OnceLock<WalLagCooldown>>,
330 :
331 : // Cancellation token fires when we have entered shutdown(). This is a parent of
332 : // Timelines' cancellation token.
333 : pub(crate) cancel: CancellationToken,
334 :
335 : // Users of the Tenant such as the page service must take this Gate to avoid
336 : // trying to use a Tenant which is shutting down.
337 : pub(crate) gate: Gate,
338 :
339 : /// Throttle applied at the top of [`Timeline::get`].
340 : /// All [`Tenant::timelines`] of a given [`Tenant`] instance share the same [`throttle::Throttle`] instance.
341 : pub(crate) pagestream_throttle: Arc<throttle::Throttle>,
342 :
343 : pub(crate) pagestream_throttle_metrics: Arc<crate::metrics::tenant_throttling::Pagestream>,
344 :
345 : /// An ongoing timeline detach concurrency limiter.
346 : ///
347 : /// As a tenant will likely be restarted as part of timeline detach ancestor it makes no sense
348 : /// to have two running at the same time. A different one can be started if an earlier one
349 : /// has failed for whatever reason.
350 : ongoing_timeline_detach: std::sync::Mutex<Option<(TimelineId, utils::completion::Barrier)>>,
351 :
352 : /// `index_part.json` based gc blocking reason tracking.
353 : ///
354 : /// New gc iterations must start a new iteration by acquiring `GcBlock::start` before
355 : /// proceeding.
356 : pub(crate) gc_block: gc_block::GcBlock,
357 :
358 : l0_flush_global_state: L0FlushGlobalState,
359 : }
360 : impl std::fmt::Debug for Tenant {
361 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
362 0 : write!(f, "{} ({})", self.tenant_shard_id, self.current_state())
363 0 : }
364 : }
365 :
366 : pub(crate) enum WalRedoManager {
367 : Prod(WalredoManagerId, PostgresRedoManager),
368 : #[cfg(test)]
369 : Test(harness::TestRedoManager),
370 : }
371 :
372 : #[derive(thiserror::Error, Debug)]
373 : #[error("pageserver is shutting down")]
374 : pub(crate) struct GlobalShutDown;
375 :
376 : impl WalRedoManager {
377 0 : pub(crate) fn new(mgr: PostgresRedoManager) -> Result<Arc<Self>, GlobalShutDown> {
378 0 : let id = WalredoManagerId::next();
379 0 : let arc = Arc::new(Self::Prod(id, mgr));
380 0 : let mut guard = WALREDO_MANAGERS.lock().unwrap();
381 0 : match &mut *guard {
382 0 : Some(map) => {
383 0 : map.insert(id, Arc::downgrade(&arc));
384 0 : Ok(arc)
385 : }
386 0 : None => Err(GlobalShutDown),
387 : }
388 0 : }
389 : }
390 :
391 : impl Drop for WalRedoManager {
392 20 : fn drop(&mut self) {
393 20 : match self {
394 0 : Self::Prod(id, _) => {
395 0 : let mut guard = WALREDO_MANAGERS.lock().unwrap();
396 0 : if let Some(map) = &mut *guard {
397 0 : map.remove(id).expect("new() registers, drop() unregisters");
398 0 : }
399 : }
400 : #[cfg(test)]
401 20 : Self::Test(_) => {
402 20 : // Not applicable to test redo manager
403 20 : }
404 : }
405 20 : }
406 : }
407 :
408 : /// Global registry of all walredo managers so that [`crate::shutdown_pageserver`] can shut down
409 : /// the walredo processes outside of the regular order.
410 : ///
411 : /// This is necessary to work around a systemd bug where it freezes if there are
412 : /// walredo processes left => <https://github.com/neondatabase/cloud/issues/11387>
413 : #[allow(clippy::type_complexity)]
414 : pub(crate) static WALREDO_MANAGERS: once_cell::sync::Lazy<
415 : Mutex<Option<HashMap<WalredoManagerId, Weak<WalRedoManager>>>>,
416 0 : > = once_cell::sync::Lazy::new(|| Mutex::new(Some(HashMap::new())));
417 : #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
418 : pub(crate) struct WalredoManagerId(u64);
419 : impl WalredoManagerId {
420 0 : pub fn next() -> Self {
421 : static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
422 0 : let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
423 0 : if id == 0 {
424 0 : panic!(
425 0 : "WalredoManagerId::new() returned 0, indicating wraparound, risking it's no longer unique"
426 0 : );
427 0 : }
428 0 : Self(id)
429 0 : }
430 : }
431 :
432 : #[cfg(test)]
433 : impl From<harness::TestRedoManager> for WalRedoManager {
434 452 : fn from(mgr: harness::TestRedoManager) -> Self {
435 452 : Self::Test(mgr)
436 452 : }
437 : }
438 :
439 : impl WalRedoManager {
440 12 : pub(crate) async fn shutdown(&self) -> bool {
441 12 : match self {
442 0 : Self::Prod(_, mgr) => mgr.shutdown().await,
443 : #[cfg(test)]
444 : Self::Test(_) => {
445 : // Not applicable to test redo manager
446 12 : true
447 : }
448 : }
449 12 : }
450 :
451 0 : pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
452 0 : match self {
453 0 : Self::Prod(_, mgr) => mgr.maybe_quiesce(idle_timeout),
454 0 : #[cfg(test)]
455 0 : Self::Test(_) => {
456 0 : // Not applicable to test redo manager
457 0 : }
458 0 : }
459 0 : }
460 :
461 : /// # Cancel-Safety
462 : ///
463 : /// This method is cancellation-safe.
464 1676 : pub async fn request_redo(
465 1676 : &self,
466 1676 : key: pageserver_api::key::Key,
467 1676 : lsn: Lsn,
468 1676 : base_img: Option<(Lsn, bytes::Bytes)>,
469 1676 : records: Vec<(Lsn, pageserver_api::record::NeonWalRecord)>,
470 1676 : pg_version: u32,
471 1676 : ) -> Result<bytes::Bytes, walredo::Error> {
472 1676 : match self {
473 0 : Self::Prod(_, mgr) => {
474 0 : mgr.request_redo(key, lsn, base_img, records, pg_version)
475 0 : .await
476 : }
477 : #[cfg(test)]
478 1676 : Self::Test(mgr) => {
479 1676 : mgr.request_redo(key, lsn, base_img, records, pg_version)
480 1676 : .await
481 : }
482 : }
483 1676 : }
484 :
485 0 : pub(crate) fn status(&self) -> Option<WalRedoManagerStatus> {
486 0 : match self {
487 0 : WalRedoManager::Prod(_, m) => Some(m.status()),
488 0 : #[cfg(test)]
489 0 : WalRedoManager::Test(_) => None,
490 0 : }
491 0 : }
492 : }
493 :
494 : /// A very lightweight memory representation of an offloaded timeline.
495 : ///
496 : /// We need to store the list of offloaded timelines so that we can perform operations on them,
497 : /// like unoffloading them, or (at a later date), decide to perform flattening.
498 : /// This type has a much smaller memory impact than [`Timeline`], and thus we can store many
499 : /// more offloaded timelines than we can manage ones that aren't.
500 : pub struct OffloadedTimeline {
501 : pub tenant_shard_id: TenantShardId,
502 : pub timeline_id: TimelineId,
503 : pub ancestor_timeline_id: Option<TimelineId>,
504 : /// Whether to retain the branch lsn at the ancestor or not
505 : pub ancestor_retain_lsn: Option<Lsn>,
506 :
507 : /// When the timeline was archived.
508 : ///
509 : /// Present for future flattening deliberations.
510 : pub archived_at: NaiveDateTime,
511 :
512 : /// Prevent two tasks from deleting the timeline at the same time. If held, the
513 : /// timeline is being deleted. If 'true', the timeline has already been deleted.
514 : pub delete_progress: TimelineDeleteProgress,
515 :
516 : /// Part of the `OffloadedTimeline` object's lifecycle: this needs to be set before we drop it
517 : pub deleted_from_ancestor: AtomicBool,
518 : }
519 :
520 : impl OffloadedTimeline {
521 : /// Obtains an offloaded timeline from a given timeline object.
522 : ///
523 : /// Returns `None` if the `archived_at` flag couldn't be obtained, i.e.
524 : /// the timeline is not in a stopped state.
525 : /// Panics if the timeline is not archived.
526 4 : fn from_timeline(timeline: &Timeline) -> Result<Self, UploadQueueNotReadyError> {
527 4 : let (ancestor_retain_lsn, ancestor_timeline_id) =
528 4 : if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
529 4 : let ancestor_lsn = timeline.get_ancestor_lsn();
530 4 : let ancestor_timeline_id = ancestor_timeline.timeline_id;
531 4 : let mut gc_info = ancestor_timeline.gc_info.write().unwrap();
532 4 : gc_info.insert_child(timeline.timeline_id, ancestor_lsn, MaybeOffloaded::Yes);
533 4 : (Some(ancestor_lsn), Some(ancestor_timeline_id))
534 : } else {
535 0 : (None, None)
536 : };
537 4 : let archived_at = timeline
538 4 : .remote_client
539 4 : .archived_at_stopped_queue()?
540 4 : .expect("must be called on an archived timeline");
541 4 : Ok(Self {
542 4 : tenant_shard_id: timeline.tenant_shard_id,
543 4 : timeline_id: timeline.timeline_id,
544 4 : ancestor_timeline_id,
545 4 : ancestor_retain_lsn,
546 4 : archived_at,
547 4 :
548 4 : delete_progress: timeline.delete_progress.clone(),
549 4 : deleted_from_ancestor: AtomicBool::new(false),
550 4 : })
551 4 : }
552 0 : fn from_manifest(tenant_shard_id: TenantShardId, manifest: &OffloadedTimelineManifest) -> Self {
553 0 : // We expect to reach this case in tenant loading, where the `retain_lsn` is populated in the parent's `gc_info`
554 0 : // by the `initialize_gc_info` function.
555 0 : let OffloadedTimelineManifest {
556 0 : timeline_id,
557 0 : ancestor_timeline_id,
558 0 : ancestor_retain_lsn,
559 0 : archived_at,
560 0 : } = *manifest;
561 0 : Self {
562 0 : tenant_shard_id,
563 0 : timeline_id,
564 0 : ancestor_timeline_id,
565 0 : ancestor_retain_lsn,
566 0 : archived_at,
567 0 : delete_progress: TimelineDeleteProgress::default(),
568 0 : deleted_from_ancestor: AtomicBool::new(false),
569 0 : }
570 0 : }
571 4 : fn manifest(&self) -> OffloadedTimelineManifest {
572 4 : let Self {
573 4 : timeline_id,
574 4 : ancestor_timeline_id,
575 4 : ancestor_retain_lsn,
576 4 : archived_at,
577 4 : ..
578 4 : } = self;
579 4 : OffloadedTimelineManifest {
580 4 : timeline_id: *timeline_id,
581 4 : ancestor_timeline_id: *ancestor_timeline_id,
582 4 : ancestor_retain_lsn: *ancestor_retain_lsn,
583 4 : archived_at: *archived_at,
584 4 : }
585 4 : }
586 : /// Delete this timeline's retain_lsn from its ancestor, if present in the given tenant
587 0 : fn delete_from_ancestor_with_timelines(
588 0 : &self,
589 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
590 0 : ) {
591 0 : if let (Some(_retain_lsn), Some(ancestor_timeline_id)) =
592 0 : (self.ancestor_retain_lsn, self.ancestor_timeline_id)
593 : {
594 0 : if let Some((_, ancestor_timeline)) = timelines
595 0 : .iter()
596 0 : .find(|(tid, _tl)| **tid == ancestor_timeline_id)
597 : {
598 0 : let removal_happened = ancestor_timeline
599 0 : .gc_info
600 0 : .write()
601 0 : .unwrap()
602 0 : .remove_child_offloaded(self.timeline_id);
603 0 : if !removal_happened {
604 0 : tracing::error!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), timeline_id = %self.timeline_id,
605 0 : "Couldn't remove retain_lsn entry from offloaded timeline's parent: already removed");
606 0 : }
607 0 : }
608 0 : }
609 0 : self.deleted_from_ancestor.store(true, Ordering::Release);
610 0 : }
611 : /// Call [`Self::delete_from_ancestor_with_timelines`] instead if possible.
612 : ///
613 : /// As the entire tenant is being dropped, don't bother deregistering the `retain_lsn` from the ancestor.
614 4 : fn defuse_for_tenant_drop(&self) {
615 4 : self.deleted_from_ancestor.store(true, Ordering::Release);
616 4 : }
617 : }
618 :
619 : impl fmt::Debug for OffloadedTimeline {
620 0 : fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621 0 : write!(f, "OffloadedTimeline<{}>", self.timeline_id)
622 0 : }
623 : }
624 :
625 : impl Drop for OffloadedTimeline {
626 4 : fn drop(&mut self) {
627 4 : if !self.deleted_from_ancestor.load(Ordering::Acquire) {
628 0 : tracing::warn!(
629 0 : "offloaded timeline {} was dropped without having cleaned it up at the ancestor",
630 : self.timeline_id
631 : );
632 4 : }
633 4 : }
634 : }
635 :
636 : #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
637 : pub enum MaybeOffloaded {
638 : Yes,
639 : No,
640 : }
641 :
642 : #[derive(Clone, Debug)]
643 : pub enum TimelineOrOffloaded {
644 : Timeline(Arc<Timeline>),
645 : Offloaded(Arc<OffloadedTimeline>),
646 : }
647 :
648 : impl TimelineOrOffloaded {
649 0 : pub fn arc_ref(&self) -> TimelineOrOffloadedArcRef<'_> {
650 0 : match self {
651 0 : TimelineOrOffloaded::Timeline(timeline) => {
652 0 : TimelineOrOffloadedArcRef::Timeline(timeline)
653 : }
654 0 : TimelineOrOffloaded::Offloaded(offloaded) => {
655 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded)
656 : }
657 : }
658 0 : }
659 0 : pub fn tenant_shard_id(&self) -> TenantShardId {
660 0 : self.arc_ref().tenant_shard_id()
661 0 : }
662 0 : pub fn timeline_id(&self) -> TimelineId {
663 0 : self.arc_ref().timeline_id()
664 0 : }
665 4 : pub fn delete_progress(&self) -> &Arc<tokio::sync::Mutex<DeleteTimelineFlow>> {
666 4 : match self {
667 4 : TimelineOrOffloaded::Timeline(timeline) => &timeline.delete_progress,
668 0 : TimelineOrOffloaded::Offloaded(offloaded) => &offloaded.delete_progress,
669 : }
670 4 : }
671 0 : fn maybe_remote_client(&self) -> Option<Arc<RemoteTimelineClient>> {
672 0 : match self {
673 0 : TimelineOrOffloaded::Timeline(timeline) => Some(timeline.remote_client.clone()),
674 0 : TimelineOrOffloaded::Offloaded(_offloaded) => None,
675 : }
676 0 : }
677 : }
678 :
679 : pub enum TimelineOrOffloadedArcRef<'a> {
680 : Timeline(&'a Arc<Timeline>),
681 : Offloaded(&'a Arc<OffloadedTimeline>),
682 : }
683 :
684 : impl TimelineOrOffloadedArcRef<'_> {
685 0 : pub fn tenant_shard_id(&self) -> TenantShardId {
686 0 : match self {
687 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.tenant_shard_id,
688 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.tenant_shard_id,
689 : }
690 0 : }
691 0 : pub fn timeline_id(&self) -> TimelineId {
692 0 : match self {
693 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.timeline_id,
694 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => offloaded.timeline_id,
695 : }
696 0 : }
697 : }
698 :
699 : impl<'a> From<&'a Arc<Timeline>> for TimelineOrOffloadedArcRef<'a> {
700 0 : fn from(timeline: &'a Arc<Timeline>) -> Self {
701 0 : Self::Timeline(timeline)
702 0 : }
703 : }
704 :
705 : impl<'a> From<&'a Arc<OffloadedTimeline>> for TimelineOrOffloadedArcRef<'a> {
706 0 : fn from(timeline: &'a Arc<OffloadedTimeline>) -> Self {
707 0 : Self::Offloaded(timeline)
708 0 : }
709 : }
710 :
711 : #[derive(Debug, thiserror::Error, PartialEq, Eq)]
712 : pub enum GetTimelineError {
713 : #[error("Timeline is shutting down")]
714 : ShuttingDown,
715 : #[error("Timeline {tenant_id}/{timeline_id} is not active, state: {state:?}")]
716 : NotActive {
717 : tenant_id: TenantShardId,
718 : timeline_id: TimelineId,
719 : state: TimelineState,
720 : },
721 : #[error("Timeline {tenant_id}/{timeline_id} was not found")]
722 : NotFound {
723 : tenant_id: TenantShardId,
724 : timeline_id: TimelineId,
725 : },
726 : }
727 :
728 : #[derive(Debug, thiserror::Error)]
729 : pub enum LoadLocalTimelineError {
730 : #[error("FailedToLoad")]
731 : Load(#[source] anyhow::Error),
732 : #[error("FailedToResumeDeletion")]
733 : ResumeDeletion(#[source] anyhow::Error),
734 : }
735 :
736 : #[derive(thiserror::Error)]
737 : pub enum DeleteTimelineError {
738 : #[error("NotFound")]
739 : NotFound,
740 :
741 : #[error("HasChildren")]
742 : HasChildren(Vec<TimelineId>),
743 :
744 : #[error("Timeline deletion is already in progress")]
745 : AlreadyInProgress(Arc<tokio::sync::Mutex<DeleteTimelineFlow>>),
746 :
747 : #[error("Cancelled")]
748 : Cancelled,
749 :
750 : #[error(transparent)]
751 : Other(#[from] anyhow::Error),
752 : }
753 :
754 : impl Debug for DeleteTimelineError {
755 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
756 0 : match self {
757 0 : Self::NotFound => write!(f, "NotFound"),
758 0 : Self::HasChildren(c) => f.debug_tuple("HasChildren").field(c).finish(),
759 0 : Self::AlreadyInProgress(_) => f.debug_tuple("AlreadyInProgress").finish(),
760 0 : Self::Cancelled => f.debug_tuple("Cancelled").finish(),
761 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
762 : }
763 0 : }
764 : }
765 :
766 : #[derive(thiserror::Error)]
767 : pub enum TimelineArchivalError {
768 : #[error("NotFound")]
769 : NotFound,
770 :
771 : #[error("Timeout")]
772 : Timeout,
773 :
774 : #[error("Cancelled")]
775 : Cancelled,
776 :
777 : #[error("ancestor is archived: {}", .0)]
778 : HasArchivedParent(TimelineId),
779 :
780 : #[error("HasUnarchivedChildren")]
781 : HasUnarchivedChildren(Vec<TimelineId>),
782 :
783 : #[error("Timeline archival is already in progress")]
784 : AlreadyInProgress,
785 :
786 : #[error(transparent)]
787 : Other(anyhow::Error),
788 : }
789 :
790 : #[derive(thiserror::Error, Debug)]
791 : pub(crate) enum TenantManifestError {
792 : #[error("Remote storage error: {0}")]
793 : RemoteStorage(anyhow::Error),
794 :
795 : #[error("Cancelled")]
796 : Cancelled,
797 : }
798 :
799 : impl From<TenantManifestError> for TimelineArchivalError {
800 0 : fn from(e: TenantManifestError) -> Self {
801 0 : match e {
802 0 : TenantManifestError::RemoteStorage(e) => Self::Other(e),
803 0 : TenantManifestError::Cancelled => Self::Cancelled,
804 : }
805 0 : }
806 : }
807 :
808 : impl Debug for TimelineArchivalError {
809 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
810 0 : match self {
811 0 : Self::NotFound => write!(f, "NotFound"),
812 0 : Self::Timeout => write!(f, "Timeout"),
813 0 : Self::Cancelled => write!(f, "Cancelled"),
814 0 : Self::HasArchivedParent(p) => f.debug_tuple("HasArchivedParent").field(p).finish(),
815 0 : Self::HasUnarchivedChildren(c) => {
816 0 : f.debug_tuple("HasUnarchivedChildren").field(c).finish()
817 : }
818 0 : Self::AlreadyInProgress => f.debug_tuple("AlreadyInProgress").finish(),
819 0 : Self::Other(e) => f.debug_tuple("Other").field(e).finish(),
820 : }
821 0 : }
822 : }
823 :
824 : pub enum SetStoppingError {
825 : AlreadyStopping(completion::Barrier),
826 : Broken,
827 : }
828 :
829 : impl Debug for SetStoppingError {
830 0 : fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
831 0 : match self {
832 0 : Self::AlreadyStopping(_) => f.debug_tuple("AlreadyStopping").finish(),
833 0 : Self::Broken => write!(f, "Broken"),
834 : }
835 0 : }
836 : }
837 :
838 : /// Arguments to [`Tenant::create_timeline`].
839 : ///
840 : /// Not usable as an idempotency key for timeline creation because if [`CreateTimelineParamsBranch::ancestor_start_lsn`]
841 : /// is `None`, the result of the timeline create call is not deterministic.
842 : ///
843 : /// See [`CreateTimelineIdempotency`] for an idempotency key.
844 : #[derive(Debug)]
845 : pub(crate) enum CreateTimelineParams {
846 : Bootstrap(CreateTimelineParamsBootstrap),
847 : Branch(CreateTimelineParamsBranch),
848 : ImportPgdata(CreateTimelineParamsImportPgdata),
849 : }
850 :
851 : #[derive(Debug)]
852 : pub(crate) struct CreateTimelineParamsBootstrap {
853 : pub(crate) new_timeline_id: TimelineId,
854 : pub(crate) existing_initdb_timeline_id: Option<TimelineId>,
855 : pub(crate) pg_version: u32,
856 : }
857 :
858 : /// NB: See comment on [`CreateTimelineIdempotency::Branch`] for why there's no `pg_version` here.
859 : #[derive(Debug)]
860 : pub(crate) struct CreateTimelineParamsBranch {
861 : pub(crate) new_timeline_id: TimelineId,
862 : pub(crate) ancestor_timeline_id: TimelineId,
863 : pub(crate) ancestor_start_lsn: Option<Lsn>,
864 : }
865 :
866 : #[derive(Debug)]
867 : pub(crate) struct CreateTimelineParamsImportPgdata {
868 : pub(crate) new_timeline_id: TimelineId,
869 : pub(crate) location: import_pgdata::index_part_format::Location,
870 : pub(crate) idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
871 : }
872 :
873 : /// What is used to determine idempotency of a [`Tenant::create_timeline`] call in [`Tenant::start_creating_timeline`] in [`Tenant::start_creating_timeline`].
874 : ///
875 : /// Each [`Timeline`] object holds [`Self`] as an immutable property in [`Timeline::create_idempotency`].
876 : ///
877 : /// We lower timeline creation requests to [`Self`], and then use [`PartialEq::eq`] to compare [`Timeline::create_idempotency`] with the request.
878 : /// If they are equal, we return a reference to the existing timeline, otherwise it's an idempotency conflict.
879 : ///
880 : /// There is special treatment for [`Self::FailWithConflict`] to always return an idempotency conflict.
881 : /// It would be nice to have more advanced derive macros to make that special treatment declarative.
882 : ///
883 : /// Notes:
884 : /// - Unlike [`CreateTimelineParams`], ancestor LSN is fixed, so, branching will be at a deterministic LSN.
885 : /// - We make some trade-offs though, e.g., [`CreateTimelineParamsBootstrap::existing_initdb_timeline_id`]
886 : /// is not considered for idempotency. We can improve on this over time if we deem it necessary.
887 : ///
888 : #[derive(Debug, Clone, PartialEq, Eq)]
889 : pub(crate) enum CreateTimelineIdempotency {
890 : /// NB: special treatment, see comment in [`Self`].
891 : FailWithConflict,
892 : Bootstrap {
893 : pg_version: u32,
894 : },
895 : /// NB: branches always have the same `pg_version` as their ancestor.
896 : /// While [`pageserver_api::models::TimelineCreateRequestMode::Branch::pg_version`]
897 : /// exists as a field, and is set by cplane, it has always been ignored by pageserver when
898 : /// determining the child branch pg_version.
899 : Branch {
900 : ancestor_timeline_id: TimelineId,
901 : ancestor_start_lsn: Lsn,
902 : },
903 : ImportPgdata(CreatingTimelineIdempotencyImportPgdata),
904 : }
905 :
906 : #[derive(Debug, Clone, PartialEq, Eq)]
907 : pub(crate) struct CreatingTimelineIdempotencyImportPgdata {
908 : idempotency_key: import_pgdata::index_part_format::IdempotencyKey,
909 : }
910 :
911 : /// What is returned by [`Tenant::start_creating_timeline`].
912 : #[must_use]
913 : enum StartCreatingTimelineResult {
914 : CreateGuard(TimelineCreateGuard),
915 : Idempotent(Arc<Timeline>),
916 : }
917 :
918 : enum TimelineInitAndSyncResult {
919 : ReadyToActivate(Arc<Timeline>),
920 : NeedsSpawnImportPgdata(TimelineInitAndSyncNeedsSpawnImportPgdata),
921 : }
922 :
923 : impl TimelineInitAndSyncResult {
924 0 : fn ready_to_activate(self) -> Option<Arc<Timeline>> {
925 0 : match self {
926 0 : Self::ReadyToActivate(timeline) => Some(timeline),
927 0 : _ => None,
928 : }
929 0 : }
930 : }
931 :
932 : #[must_use]
933 : struct TimelineInitAndSyncNeedsSpawnImportPgdata {
934 : timeline: Arc<Timeline>,
935 : import_pgdata: import_pgdata::index_part_format::Root,
936 : guard: TimelineCreateGuard,
937 : }
938 :
939 : /// What is returned by [`Tenant::create_timeline`].
940 : enum CreateTimelineResult {
941 : Created(Arc<Timeline>),
942 : Idempotent(Arc<Timeline>),
943 : /// IMPORTANT: This [`Arc<Timeline>`] object is not in [`Tenant::timelines`] when
944 : /// we return this result, nor will this concrete object ever be added there.
945 : /// Cf method comment on [`Tenant::create_timeline_import_pgdata`].
946 : ImportSpawned(Arc<Timeline>),
947 : }
948 :
949 : impl CreateTimelineResult {
950 0 : fn discriminant(&self) -> &'static str {
951 0 : match self {
952 0 : Self::Created(_) => "Created",
953 0 : Self::Idempotent(_) => "Idempotent",
954 0 : Self::ImportSpawned(_) => "ImportSpawned",
955 : }
956 0 : }
957 0 : fn timeline(&self) -> &Arc<Timeline> {
958 0 : match self {
959 0 : Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
960 0 : }
961 0 : }
962 : /// Unit test timelines aren't activated, test has to do it if it needs to.
963 : #[cfg(test)]
964 460 : fn into_timeline_for_test(self) -> Arc<Timeline> {
965 460 : match self {
966 460 : Self::Created(t) | Self::Idempotent(t) | Self::ImportSpawned(t) => t,
967 460 : }
968 460 : }
969 : }
970 :
971 : #[derive(thiserror::Error, Debug)]
972 : pub enum CreateTimelineError {
973 : #[error("creation of timeline with the given ID is in progress")]
974 : AlreadyCreating,
975 : #[error("timeline already exists with different parameters")]
976 : Conflict,
977 : #[error(transparent)]
978 : AncestorLsn(anyhow::Error),
979 : #[error("ancestor timeline is not active")]
980 : AncestorNotActive,
981 : #[error("ancestor timeline is archived")]
982 : AncestorArchived,
983 : #[error("tenant shutting down")]
984 : ShuttingDown,
985 : #[error(transparent)]
986 : Other(#[from] anyhow::Error),
987 : }
988 :
989 : #[derive(thiserror::Error, Debug)]
990 : pub enum InitdbError {
991 : #[error("Operation was cancelled")]
992 : Cancelled,
993 : #[error(transparent)]
994 : Other(anyhow::Error),
995 : #[error(transparent)]
996 : Inner(postgres_initdb::Error),
997 : }
998 :
999 : enum CreateTimelineCause {
1000 : Load,
1001 : Delete,
1002 : }
1003 :
1004 : enum LoadTimelineCause {
1005 : Attach,
1006 : Unoffload,
1007 : ImportPgdata {
1008 : create_guard: TimelineCreateGuard,
1009 : activate: ActivateTimelineArgs,
1010 : },
1011 : }
1012 :
1013 : #[derive(thiserror::Error, Debug)]
1014 : pub(crate) enum GcError {
1015 : // The tenant is shutting down
1016 : #[error("tenant shutting down")]
1017 : TenantCancelled,
1018 :
1019 : // The tenant is shutting down
1020 : #[error("timeline shutting down")]
1021 : TimelineCancelled,
1022 :
1023 : // The tenant is in a state inelegible to run GC
1024 : #[error("not active")]
1025 : NotActive,
1026 :
1027 : // A requested GC cutoff LSN was invalid, for example it tried to move backwards
1028 : #[error("not active")]
1029 : BadLsn { why: String },
1030 :
1031 : // A remote storage error while scheduling updates after compaction
1032 : #[error(transparent)]
1033 : Remote(anyhow::Error),
1034 :
1035 : // An error reading while calculating GC cutoffs
1036 : #[error(transparent)]
1037 : GcCutoffs(PageReconstructError),
1038 :
1039 : // If GC was invoked for a particular timeline, this error means it didn't exist
1040 : #[error("timeline not found")]
1041 : TimelineNotFound,
1042 : }
1043 :
1044 : impl From<PageReconstructError> for GcError {
1045 0 : fn from(value: PageReconstructError) -> Self {
1046 0 : match value {
1047 0 : PageReconstructError::Cancelled => Self::TimelineCancelled,
1048 0 : other => Self::GcCutoffs(other),
1049 : }
1050 0 : }
1051 : }
1052 :
1053 : impl From<NotInitialized> for GcError {
1054 0 : fn from(value: NotInitialized) -> Self {
1055 0 : match value {
1056 0 : NotInitialized::Uninitialized => GcError::Remote(value.into()),
1057 0 : NotInitialized::Stopped | NotInitialized::ShuttingDown => GcError::TimelineCancelled,
1058 : }
1059 0 : }
1060 : }
1061 :
1062 : impl From<timeline::layer_manager::Shutdown> for GcError {
1063 0 : fn from(_: timeline::layer_manager::Shutdown) -> Self {
1064 0 : GcError::TimelineCancelled
1065 0 : }
1066 : }
1067 :
1068 : #[derive(thiserror::Error, Debug)]
1069 : pub(crate) enum LoadConfigError {
1070 : #[error("TOML deserialization error: '{0}'")]
1071 : DeserializeToml(#[from] toml_edit::de::Error),
1072 :
1073 : #[error("Config not found at {0}")]
1074 : NotFound(Utf8PathBuf),
1075 : }
1076 :
1077 : impl Tenant {
1078 : /// Yet another helper for timeline initialization.
1079 : ///
1080 : /// - Initializes the Timeline struct and inserts it into the tenant's hash map
1081 : /// - Scans the local timeline directory for layer files and builds the layer map
1082 : /// - Downloads remote index file and adds remote files to the layer map
1083 : /// - Schedules remote upload tasks for any files that are present locally but missing from remote storage.
1084 : ///
1085 : /// If the operation fails, the timeline is left in the tenant's hash map in Broken state. On success,
1086 : /// it is marked as Active.
1087 : #[allow(clippy::too_many_arguments)]
1088 12 : async fn timeline_init_and_sync(
1089 12 : self: &Arc<Self>,
1090 12 : timeline_id: TimelineId,
1091 12 : resources: TimelineResources,
1092 12 : mut index_part: IndexPart,
1093 12 : metadata: TimelineMetadata,
1094 12 : previous_heatmap: Option<PreviousHeatmap>,
1095 12 : ancestor: Option<Arc<Timeline>>,
1096 12 : cause: LoadTimelineCause,
1097 12 : ctx: &RequestContext,
1098 12 : ) -> anyhow::Result<TimelineInitAndSyncResult> {
1099 12 : let tenant_id = self.tenant_shard_id;
1100 12 :
1101 12 : let import_pgdata = index_part.import_pgdata.take();
1102 12 : let idempotency = match &import_pgdata {
1103 0 : Some(import_pgdata) => {
1104 0 : CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
1105 0 : idempotency_key: import_pgdata.idempotency_key().clone(),
1106 0 : })
1107 : }
1108 : None => {
1109 12 : if metadata.ancestor_timeline().is_none() {
1110 8 : CreateTimelineIdempotency::Bootstrap {
1111 8 : pg_version: metadata.pg_version(),
1112 8 : }
1113 : } else {
1114 4 : CreateTimelineIdempotency::Branch {
1115 4 : ancestor_timeline_id: metadata.ancestor_timeline().unwrap(),
1116 4 : ancestor_start_lsn: metadata.ancestor_lsn(),
1117 4 : }
1118 : }
1119 : }
1120 : };
1121 :
1122 12 : let (timeline, timeline_ctx) = self.create_timeline_struct(
1123 12 : timeline_id,
1124 12 : &metadata,
1125 12 : previous_heatmap,
1126 12 : ancestor.clone(),
1127 12 : resources,
1128 12 : CreateTimelineCause::Load,
1129 12 : idempotency.clone(),
1130 12 : index_part.gc_compaction.clone(),
1131 12 : index_part.rel_size_migration.clone(),
1132 12 : ctx,
1133 12 : )?;
1134 12 : let disk_consistent_lsn = timeline.get_disk_consistent_lsn();
1135 12 : anyhow::ensure!(
1136 12 : disk_consistent_lsn.is_valid(),
1137 0 : "Timeline {tenant_id}/{timeline_id} has invalid disk_consistent_lsn"
1138 : );
1139 12 : assert_eq!(
1140 12 : disk_consistent_lsn,
1141 12 : metadata.disk_consistent_lsn(),
1142 0 : "these are used interchangeably"
1143 : );
1144 :
1145 12 : timeline.remote_client.init_upload_queue(&index_part)?;
1146 :
1147 12 : timeline
1148 12 : .load_layer_map(disk_consistent_lsn, index_part)
1149 12 : .await
1150 12 : .with_context(|| {
1151 0 : format!("Failed to load layermap for timeline {tenant_id}/{timeline_id}")
1152 12 : })?;
1153 :
1154 : // When unarchiving, we've mostly likely lost the heatmap generated prior
1155 : // to the archival operation. To allow warming this timeline up, generate
1156 : // a previous heatmap which contains all visible layers in the layer map.
1157 : // This previous heatmap will be used whenever a fresh heatmap is generated
1158 : // for the timeline.
1159 12 : if self.conf.generate_unarchival_heatmap && matches!(cause, LoadTimelineCause::Unoffload) {
1160 0 : let mut tline_ending_at = Some((&timeline, timeline.get_last_record_lsn()));
1161 0 : while let Some((tline, end_lsn)) = tline_ending_at {
1162 0 : let unarchival_heatmap = tline.generate_unarchival_heatmap(end_lsn).await;
1163 : // Another unearchived timeline might have generated a heatmap for this ancestor.
1164 : // If the current branch point greater than the previous one use the the heatmap
1165 : // we just generated - it should include more layers.
1166 0 : if !tline.should_keep_previous_heatmap(end_lsn) {
1167 0 : tline
1168 0 : .previous_heatmap
1169 0 : .store(Some(Arc::new(unarchival_heatmap)));
1170 0 : } else {
1171 0 : tracing::info!("Previous heatmap preferred. Dropping unarchival heatmap.")
1172 : }
1173 :
1174 0 : match tline.ancestor_timeline() {
1175 0 : Some(ancestor) => {
1176 0 : if ancestor.update_layer_visibility().await.is_err() {
1177 : // Ancestor timeline is shutting down.
1178 0 : break;
1179 0 : }
1180 0 :
1181 0 : tline_ending_at = Some((ancestor, tline.get_ancestor_lsn()));
1182 : }
1183 0 : None => {
1184 0 : tline_ending_at = None;
1185 0 : }
1186 : }
1187 : }
1188 12 : }
1189 :
1190 0 : match import_pgdata {
1191 0 : Some(import_pgdata) if !import_pgdata.is_done() => {
1192 0 : match cause {
1193 0 : LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
1194 : LoadTimelineCause::ImportPgdata { .. } => {
1195 0 : unreachable!(
1196 0 : "ImportPgdata should not be reloading timeline import is done and persisted as such in s3"
1197 0 : )
1198 : }
1199 : }
1200 0 : let mut guard = self.timelines_creating.lock().unwrap();
1201 0 : if !guard.insert(timeline_id) {
1202 : // We should never try and load the same timeline twice during startup
1203 0 : unreachable!("Timeline {tenant_id}/{timeline_id} is already being created")
1204 0 : }
1205 0 : let timeline_create_guard = TimelineCreateGuard {
1206 0 : _tenant_gate_guard: self.gate.enter()?,
1207 0 : owning_tenant: self.clone(),
1208 0 : timeline_id,
1209 0 : idempotency,
1210 0 : // The users of this specific return value don't need the timline_path in there.
1211 0 : timeline_path: timeline
1212 0 : .conf
1213 0 : .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id),
1214 0 : };
1215 0 : Ok(TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
1216 0 : TimelineInitAndSyncNeedsSpawnImportPgdata {
1217 0 : timeline,
1218 0 : import_pgdata,
1219 0 : guard: timeline_create_guard,
1220 0 : },
1221 0 : ))
1222 : }
1223 : Some(_) | None => {
1224 : {
1225 12 : let mut timelines_accessor = self.timelines.lock().unwrap();
1226 12 : match timelines_accessor.entry(timeline_id) {
1227 : // We should never try and load the same timeline twice during startup
1228 : Entry::Occupied(_) => {
1229 0 : unreachable!(
1230 0 : "Timeline {tenant_id}/{timeline_id} already exists in the tenant map"
1231 0 : );
1232 : }
1233 12 : Entry::Vacant(v) => {
1234 12 : v.insert(Arc::clone(&timeline));
1235 12 : timeline.maybe_spawn_flush_loop();
1236 12 : }
1237 : }
1238 : }
1239 :
1240 : // Sanity check: a timeline should have some content.
1241 12 : anyhow::ensure!(
1242 12 : ancestor.is_some()
1243 8 : || timeline
1244 8 : .layers
1245 8 : .read()
1246 8 : .await
1247 8 : .layer_map()
1248 8 : .expect("currently loading, layer manager cannot be shutdown already")
1249 8 : .iter_historic_layers()
1250 8 : .next()
1251 8 : .is_some(),
1252 0 : "Timeline has no ancestor and no layer files"
1253 : );
1254 :
1255 12 : match cause {
1256 12 : LoadTimelineCause::Attach | LoadTimelineCause::Unoffload => (),
1257 : LoadTimelineCause::ImportPgdata {
1258 0 : create_guard,
1259 0 : activate,
1260 0 : } => {
1261 0 : // TODO: see the comment in the task code above how I'm not so certain
1262 0 : // it is safe to activate here because of concurrent shutdowns.
1263 0 : match activate {
1264 0 : ActivateTimelineArgs::Yes { broker_client } => {
1265 0 : info!("activating timeline after reload from pgdata import task");
1266 0 : timeline.activate(self.clone(), broker_client, None, &timeline_ctx);
1267 : }
1268 0 : ActivateTimelineArgs::No => (),
1269 : }
1270 0 : drop(create_guard);
1271 : }
1272 : }
1273 :
1274 12 : Ok(TimelineInitAndSyncResult::ReadyToActivate(timeline))
1275 : }
1276 : }
1277 12 : }
1278 :
1279 : /// Attach a tenant that's available in cloud storage.
1280 : ///
1281 : /// This returns quickly, after just creating the in-memory object
1282 : /// Tenant struct and launching a background task to download
1283 : /// the remote index files. On return, the tenant is most likely still in
1284 : /// Attaching state, and it will become Active once the background task
1285 : /// finishes. You can use wait_until_active() to wait for the task to
1286 : /// complete.
1287 : ///
1288 : #[allow(clippy::too_many_arguments)]
1289 0 : pub(crate) fn spawn(
1290 0 : conf: &'static PageServerConf,
1291 0 : tenant_shard_id: TenantShardId,
1292 0 : resources: TenantSharedResources,
1293 0 : attached_conf: AttachedTenantConf,
1294 0 : shard_identity: ShardIdentity,
1295 0 : init_order: Option<InitializationOrder>,
1296 0 : mode: SpawnMode,
1297 0 : ctx: &RequestContext,
1298 0 : ) -> Result<Arc<Tenant>, GlobalShutDown> {
1299 0 : let wal_redo_manager =
1300 0 : WalRedoManager::new(PostgresRedoManager::new(conf, tenant_shard_id))?;
1301 :
1302 : let TenantSharedResources {
1303 0 : broker_client,
1304 0 : remote_storage,
1305 0 : deletion_queue_client,
1306 0 : l0_flush_global_state,
1307 0 : } = resources;
1308 0 :
1309 0 : let attach_mode = attached_conf.location.attach_mode;
1310 0 : let generation = attached_conf.location.generation;
1311 0 :
1312 0 : let tenant = Arc::new(Tenant::new(
1313 0 : TenantState::Attaching,
1314 0 : conf,
1315 0 : attached_conf,
1316 0 : shard_identity,
1317 0 : Some(wal_redo_manager),
1318 0 : tenant_shard_id,
1319 0 : remote_storage.clone(),
1320 0 : deletion_queue_client,
1321 0 : l0_flush_global_state,
1322 0 : ));
1323 0 :
1324 0 : // The attach task will carry a GateGuard, so that shutdown() reliably waits for it to drop out if
1325 0 : // we shut down while attaching.
1326 0 : let attach_gate_guard = tenant
1327 0 : .gate
1328 0 : .enter()
1329 0 : .expect("We just created the Tenant: nothing else can have shut it down yet");
1330 0 :
1331 0 : // Do all the hard work in the background
1332 0 : let tenant_clone = Arc::clone(&tenant);
1333 0 : let ctx = ctx.detached_child(TaskKind::Attach, DownloadBehavior::Warn);
1334 0 : task_mgr::spawn(
1335 0 : &tokio::runtime::Handle::current(),
1336 0 : TaskKind::Attach,
1337 0 : tenant_shard_id,
1338 0 : None,
1339 0 : "attach tenant",
1340 0 : async move {
1341 0 :
1342 0 : info!(
1343 : ?attach_mode,
1344 0 : "Attaching tenant"
1345 : );
1346 :
1347 0 : let _gate_guard = attach_gate_guard;
1348 0 :
1349 0 : // Is this tenant being spawned as part of process startup?
1350 0 : let starting_up = init_order.is_some();
1351 0 : scopeguard::defer! {
1352 0 : if starting_up {
1353 0 : TENANT.startup_complete.inc();
1354 0 : }
1355 0 : }
1356 :
1357 : // Ideally we should use Tenant::set_broken_no_wait, but it is not supposed to be used when tenant is in loading state.
1358 : enum BrokenVerbosity {
1359 : Error,
1360 : Info
1361 : }
1362 0 : let make_broken =
1363 0 : |t: &Tenant, err: anyhow::Error, verbosity: BrokenVerbosity| {
1364 0 : match verbosity {
1365 : BrokenVerbosity::Info => {
1366 0 : info!("attach cancelled, setting tenant state to Broken: {err}");
1367 : },
1368 : BrokenVerbosity::Error => {
1369 0 : error!("attach failed, setting tenant state to Broken: {err:?}");
1370 : }
1371 : }
1372 0 : t.state.send_modify(|state| {
1373 0 : // The Stopping case is for when we have passed control on to DeleteTenantFlow:
1374 0 : // if it errors, we will call make_broken when tenant is already in Stopping.
1375 0 : assert!(
1376 0 : matches!(*state, TenantState::Attaching | TenantState::Stopping { .. }),
1377 0 : "the attach task owns the tenant state until activation is complete"
1378 : );
1379 :
1380 0 : *state = TenantState::broken_from_reason(err.to_string());
1381 0 : });
1382 0 : };
1383 :
1384 : // TODO: should also be rejecting tenant conf changes that violate this check.
1385 0 : if let Err(e) = crate::tenant::storage_layer::inmemory_layer::IndexEntry::validate_checkpoint_distance(tenant_clone.get_checkpoint_distance()) {
1386 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1387 0 : return Ok(());
1388 0 : }
1389 0 :
1390 0 : let mut init_order = init_order;
1391 0 : // take the completion because initial tenant loading will complete when all of
1392 0 : // these tasks complete.
1393 0 : let _completion = init_order
1394 0 : .as_mut()
1395 0 : .and_then(|x| x.initial_tenant_load.take());
1396 0 : let remote_load_completion = init_order
1397 0 : .as_mut()
1398 0 : .and_then(|x| x.initial_tenant_load_remote.take());
1399 :
1400 : enum AttachType<'a> {
1401 : /// We are attaching this tenant lazily in the background.
1402 : Warmup {
1403 : _permit: tokio::sync::SemaphorePermit<'a>,
1404 : during_startup: bool
1405 : },
1406 : /// We are attaching this tenant as soon as we can, because for example an
1407 : /// endpoint tried to access it.
1408 : OnDemand,
1409 : /// During normal operations after startup, we are attaching a tenant, and
1410 : /// eager attach was requested.
1411 : Normal,
1412 : }
1413 :
1414 0 : let attach_type = if matches!(mode, SpawnMode::Lazy) {
1415 : // Before doing any I/O, wait for at least one of:
1416 : // - A client attempting to access to this tenant (on-demand loading)
1417 : // - A permit becoming available in the warmup semaphore (background warmup)
1418 :
1419 0 : tokio::select!(
1420 0 : permit = tenant_clone.activate_now_sem.acquire() => {
1421 0 : let _ = permit.expect("activate_now_sem is never closed");
1422 0 : tracing::info!("Activating tenant (on-demand)");
1423 0 : AttachType::OnDemand
1424 : },
1425 0 : permit = conf.concurrent_tenant_warmup.inner().acquire() => {
1426 0 : let _permit = permit.expect("concurrent_tenant_warmup semaphore is never closed");
1427 0 : tracing::info!("Activating tenant (warmup)");
1428 0 : AttachType::Warmup {
1429 0 : _permit,
1430 0 : during_startup: init_order.is_some()
1431 0 : }
1432 : }
1433 0 : _ = tenant_clone.cancel.cancelled() => {
1434 : // This is safe, but should be pretty rare: it is interesting if a tenant
1435 : // stayed in Activating for such a long time that shutdown found it in
1436 : // that state.
1437 0 : tracing::info!(state=%tenant_clone.current_state(), "Tenant shut down before activation");
1438 : // Make the tenant broken so that set_stopping will not hang waiting for it to leave
1439 : // the Attaching state. This is an over-reaction (nothing really broke, the tenant is
1440 : // just shutting down), but ensures progress.
1441 0 : make_broken(&tenant_clone, anyhow::anyhow!("Shut down while Attaching"), BrokenVerbosity::Info);
1442 0 : return Ok(());
1443 : },
1444 : )
1445 : } else {
1446 : // SpawnMode::{Create,Eager} always cause jumping ahead of the
1447 : // concurrent_tenant_warmup queue
1448 0 : AttachType::Normal
1449 : };
1450 :
1451 0 : let preload = match &mode {
1452 : SpawnMode::Eager | SpawnMode::Lazy => {
1453 0 : let _preload_timer = TENANT.preload.start_timer();
1454 0 : let res = tenant_clone
1455 0 : .preload(&remote_storage, task_mgr::shutdown_token())
1456 0 : .await;
1457 0 : match res {
1458 0 : Ok(p) => Some(p),
1459 0 : Err(e) => {
1460 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1461 0 : return Ok(());
1462 : }
1463 : }
1464 : }
1465 :
1466 : };
1467 :
1468 : // Remote preload is complete.
1469 0 : drop(remote_load_completion);
1470 0 :
1471 0 :
1472 0 : // We will time the duration of the attach phase unless this is a creation (attach will do no work)
1473 0 : let attach_start = std::time::Instant::now();
1474 0 : let attached = {
1475 0 : let _attach_timer = Some(TENANT.attach.start_timer());
1476 0 : tenant_clone.attach(preload, &ctx).await
1477 : };
1478 0 : let attach_duration = attach_start.elapsed();
1479 0 : _ = tenant_clone.attach_wal_lag_cooldown.set(WalLagCooldown::new(attach_start, attach_duration));
1480 0 :
1481 0 : match attached {
1482 : Ok(()) => {
1483 0 : info!("attach finished, activating");
1484 0 : tenant_clone.activate(broker_client, None, &ctx);
1485 : }
1486 0 : Err(e) => {
1487 0 : make_broken(&tenant_clone, anyhow::anyhow!(e), BrokenVerbosity::Error);
1488 0 : }
1489 : }
1490 :
1491 : // If we are doing an opportunistic warmup attachment at startup, initialize
1492 : // logical size at the same time. This is better than starting a bunch of idle tenants
1493 : // with cold caches and then coming back later to initialize their logical sizes.
1494 : //
1495 : // It also prevents the warmup proccess competing with the concurrency limit on
1496 : // logical size calculations: if logical size calculation semaphore is saturated,
1497 : // then warmup will wait for that before proceeding to the next tenant.
1498 0 : if matches!(attach_type, AttachType::Warmup { during_startup: true, .. }) {
1499 0 : let mut futs: FuturesUnordered<_> = tenant_clone.timelines.lock().unwrap().values().cloned().map(|t| t.await_initial_logical_size()).collect();
1500 0 : tracing::info!("Waiting for initial logical sizes while warming up...");
1501 0 : while futs.next().await.is_some() {}
1502 0 : tracing::info!("Warm-up complete");
1503 0 : }
1504 :
1505 0 : Ok(())
1506 0 : }
1507 0 : .instrument(tracing::info_span!(parent: None, "attach", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), gen=?generation)),
1508 : );
1509 0 : Ok(tenant)
1510 0 : }
1511 :
1512 : #[instrument(skip_all)]
1513 : pub(crate) async fn preload(
1514 : self: &Arc<Self>,
1515 : remote_storage: &GenericRemoteStorage,
1516 : cancel: CancellationToken,
1517 : ) -> anyhow::Result<TenantPreload> {
1518 : span::debug_assert_current_span_has_tenant_id();
1519 : // Get list of remote timelines
1520 : // download index files for every tenant timeline
1521 : info!("listing remote timelines");
1522 : let (mut remote_timeline_ids, other_keys) = remote_timeline_client::list_remote_timelines(
1523 : remote_storage,
1524 : self.tenant_shard_id,
1525 : cancel.clone(),
1526 : )
1527 : .await?;
1528 : let (offloaded_add, tenant_manifest) =
1529 : match remote_timeline_client::download_tenant_manifest(
1530 : remote_storage,
1531 : &self.tenant_shard_id,
1532 : self.generation,
1533 : &cancel,
1534 : )
1535 : .await
1536 : {
1537 : Ok((tenant_manifest, _generation, _manifest_mtime)) => (
1538 : format!("{} offloaded", tenant_manifest.offloaded_timelines.len()),
1539 : tenant_manifest,
1540 : ),
1541 : Err(DownloadError::NotFound) => {
1542 : ("no manifest".to_string(), TenantManifest::empty())
1543 : }
1544 : Err(e) => Err(e)?,
1545 : };
1546 :
1547 : info!(
1548 : "found {} timelines, and {offloaded_add}",
1549 : remote_timeline_ids.len()
1550 : );
1551 :
1552 : for k in other_keys {
1553 : warn!("Unexpected non timeline key {k}");
1554 : }
1555 :
1556 : // Avoid downloading IndexPart of offloaded timelines.
1557 : let mut offloaded_with_prefix = HashSet::new();
1558 : for offloaded in tenant_manifest.offloaded_timelines.iter() {
1559 : if remote_timeline_ids.remove(&offloaded.timeline_id) {
1560 : offloaded_with_prefix.insert(offloaded.timeline_id);
1561 : } else {
1562 : // We'll take care later of timelines in the manifest without a prefix
1563 : }
1564 : }
1565 :
1566 : // TODO(vlad): Could go to S3 if the secondary is freezing cold and hasn't even
1567 : // pulled the first heatmap. Not entirely necessary since the storage controller
1568 : // will kick the secondary in any case and cause a download.
1569 : let maybe_heatmap_at = self.read_on_disk_heatmap().await;
1570 :
1571 : let timelines = self
1572 : .load_timelines_metadata(
1573 : remote_timeline_ids,
1574 : remote_storage,
1575 : maybe_heatmap_at,
1576 : cancel,
1577 : )
1578 : .await?;
1579 :
1580 : Ok(TenantPreload {
1581 : tenant_manifest,
1582 : timelines: timelines
1583 : .into_iter()
1584 12 : .map(|(id, tl)| (id, Some(tl)))
1585 0 : .chain(offloaded_with_prefix.into_iter().map(|id| (id, None)))
1586 : .collect(),
1587 : })
1588 : }
1589 :
1590 452 : async fn read_on_disk_heatmap(&self) -> Option<(HeatMapTenant, std::time::Instant)> {
1591 452 : if !self.conf.load_previous_heatmap {
1592 0 : return None;
1593 452 : }
1594 452 :
1595 452 : let on_disk_heatmap_path = self.conf.tenant_heatmap_path(&self.tenant_shard_id);
1596 452 : match tokio::fs::read_to_string(on_disk_heatmap_path).await {
1597 0 : Ok(heatmap) => match serde_json::from_str::<HeatMapTenant>(&heatmap) {
1598 0 : Ok(heatmap) => Some((heatmap, std::time::Instant::now())),
1599 0 : Err(err) => {
1600 0 : error!("Failed to deserialize old heatmap: {err}");
1601 0 : None
1602 : }
1603 : },
1604 452 : Err(err) => match err.kind() {
1605 452 : std::io::ErrorKind::NotFound => None,
1606 : _ => {
1607 0 : error!("Unexpected IO error reading old heatmap: {err}");
1608 0 : None
1609 : }
1610 : },
1611 : }
1612 452 : }
1613 :
1614 : ///
1615 : /// Background task that downloads all data for a tenant and brings it to Active state.
1616 : ///
1617 : /// No background tasks are started as part of this routine.
1618 : ///
1619 452 : async fn attach(
1620 452 : self: &Arc<Tenant>,
1621 452 : preload: Option<TenantPreload>,
1622 452 : ctx: &RequestContext,
1623 452 : ) -> anyhow::Result<()> {
1624 452 : span::debug_assert_current_span_has_tenant_id();
1625 452 :
1626 452 : failpoint_support::sleep_millis_async!("before-attaching-tenant");
1627 :
1628 452 : let Some(preload) = preload else {
1629 0 : anyhow::bail!(
1630 0 : "local-only deployment is no longer supported, https://github.com/neondatabase/neon/issues/5624"
1631 0 : );
1632 : };
1633 :
1634 452 : let mut offloaded_timeline_ids = HashSet::new();
1635 452 : let mut offloaded_timelines_list = Vec::new();
1636 452 : for timeline_manifest in preload.tenant_manifest.offloaded_timelines.iter() {
1637 0 : let timeline_id = timeline_manifest.timeline_id;
1638 0 : let offloaded_timeline =
1639 0 : OffloadedTimeline::from_manifest(self.tenant_shard_id, timeline_manifest);
1640 0 : offloaded_timelines_list.push((timeline_id, Arc::new(offloaded_timeline)));
1641 0 : offloaded_timeline_ids.insert(timeline_id);
1642 0 : }
1643 : // Complete deletions for offloaded timeline id's from manifest.
1644 : // The manifest will be uploaded later in this function.
1645 452 : offloaded_timelines_list
1646 452 : .retain(|(offloaded_id, offloaded)| {
1647 0 : // Existence of a timeline is finally determined by the existence of an index-part.json in remote storage.
1648 0 : // If there is dangling references in another location, they need to be cleaned up.
1649 0 : let delete = !preload.timelines.contains_key(offloaded_id);
1650 0 : if delete {
1651 0 : tracing::info!("Removing offloaded timeline {offloaded_id} from manifest as no remote prefix was found");
1652 0 : offloaded.defuse_for_tenant_drop();
1653 0 : }
1654 0 : !delete
1655 452 : });
1656 452 :
1657 452 : let mut timelines_to_resume_deletions = vec![];
1658 452 :
1659 452 : let mut remote_index_and_client = HashMap::new();
1660 452 : let mut timeline_ancestors = HashMap::new();
1661 452 : let mut existent_timelines = HashSet::new();
1662 464 : for (timeline_id, preload) in preload.timelines {
1663 12 : let Some(preload) = preload else { continue };
1664 : // This is an invariant of the `preload` function's API
1665 12 : assert!(!offloaded_timeline_ids.contains(&timeline_id));
1666 12 : let index_part = match preload.index_part {
1667 12 : Ok(i) => {
1668 12 : debug!("remote index part exists for timeline {timeline_id}");
1669 : // We found index_part on the remote, this is the standard case.
1670 12 : existent_timelines.insert(timeline_id);
1671 12 : i
1672 : }
1673 : Err(DownloadError::NotFound) => {
1674 : // There is no index_part on the remote. We only get here
1675 : // if there is some prefix for the timeline in the remote storage.
1676 : // This can e.g. be the initdb.tar.zst archive, maybe a
1677 : // remnant from a prior incomplete creation or deletion attempt.
1678 : // Delete the local directory as the deciding criterion for a
1679 : // timeline's existence is presence of index_part.
1680 0 : info!(%timeline_id, "index_part not found on remote");
1681 0 : continue;
1682 : }
1683 0 : Err(DownloadError::Fatal(why)) => {
1684 0 : // If, while loading one remote timeline, we saw an indication that our generation
1685 0 : // number is likely invalid, then we should not load the whole tenant.
1686 0 : error!(%timeline_id, "Fatal error loading timeline: {why}");
1687 0 : anyhow::bail!(why.to_string());
1688 : }
1689 0 : Err(e) => {
1690 0 : // Some (possibly ephemeral) error happened during index_part download.
1691 0 : // Pretend the timeline exists to not delete the timeline directory,
1692 0 : // as it might be a temporary issue and we don't want to re-download
1693 0 : // everything after it resolves.
1694 0 : warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
1695 :
1696 0 : existent_timelines.insert(timeline_id);
1697 0 : continue;
1698 : }
1699 : };
1700 12 : match index_part {
1701 12 : MaybeDeletedIndexPart::IndexPart(index_part) => {
1702 12 : timeline_ancestors.insert(timeline_id, index_part.metadata.clone());
1703 12 : remote_index_and_client.insert(
1704 12 : timeline_id,
1705 12 : (index_part, preload.client, preload.previous_heatmap),
1706 12 : );
1707 12 : }
1708 0 : MaybeDeletedIndexPart::Deleted(index_part) => {
1709 0 : info!(
1710 0 : "timeline {} is deleted, picking to resume deletion",
1711 : timeline_id
1712 : );
1713 0 : timelines_to_resume_deletions.push((timeline_id, index_part, preload.client));
1714 : }
1715 : }
1716 : }
1717 :
1718 452 : let mut gc_blocks = HashMap::new();
1719 :
1720 : // For every timeline, download the metadata file, scan the local directory,
1721 : // and build a layer map that contains an entry for each remote and local
1722 : // layer file.
1723 452 : let sorted_timelines = tree_sort_timelines(timeline_ancestors, |m| m.ancestor_timeline())?;
1724 464 : for (timeline_id, remote_metadata) in sorted_timelines {
1725 12 : let (index_part, remote_client, previous_heatmap) = remote_index_and_client
1726 12 : .remove(&timeline_id)
1727 12 : .expect("just put it in above");
1728 :
1729 12 : if let Some(blocking) = index_part.gc_blocking.as_ref() {
1730 : // could just filter these away, but it helps while testing
1731 0 : anyhow::ensure!(
1732 0 : !blocking.reasons.is_empty(),
1733 0 : "index_part for {timeline_id} is malformed: it should not have gc blocking with zero reasons"
1734 : );
1735 0 : let prev = gc_blocks.insert(timeline_id, blocking.reasons);
1736 0 : assert!(prev.is_none());
1737 12 : }
1738 :
1739 : // TODO again handle early failure
1740 12 : let effect = self
1741 12 : .load_remote_timeline(
1742 12 : timeline_id,
1743 12 : index_part,
1744 12 : remote_metadata,
1745 12 : previous_heatmap,
1746 12 : self.get_timeline_resources_for(remote_client),
1747 12 : LoadTimelineCause::Attach,
1748 12 : ctx,
1749 12 : )
1750 12 : .await
1751 12 : .with_context(|| {
1752 0 : format!(
1753 0 : "failed to load remote timeline {} for tenant {}",
1754 0 : timeline_id, self.tenant_shard_id
1755 0 : )
1756 12 : })?;
1757 :
1758 12 : match effect {
1759 12 : TimelineInitAndSyncResult::ReadyToActivate(_) => {
1760 12 : // activation happens later, on Tenant::activate
1761 12 : }
1762 : TimelineInitAndSyncResult::NeedsSpawnImportPgdata(
1763 : TimelineInitAndSyncNeedsSpawnImportPgdata {
1764 0 : timeline,
1765 0 : import_pgdata,
1766 0 : guard,
1767 0 : },
1768 0 : ) => {
1769 0 : tokio::task::spawn(self.clone().create_timeline_import_pgdata_task(
1770 0 : timeline,
1771 0 : import_pgdata,
1772 0 : ActivateTimelineArgs::No,
1773 0 : guard,
1774 0 : ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
1775 0 : ));
1776 0 : }
1777 : }
1778 : }
1779 :
1780 : // Walk through deleted timelines, resume deletion
1781 452 : for (timeline_id, index_part, remote_timeline_client) in timelines_to_resume_deletions {
1782 0 : remote_timeline_client
1783 0 : .init_upload_queue_stopped_to_continue_deletion(&index_part)
1784 0 : .context("init queue stopped")
1785 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1786 :
1787 0 : DeleteTimelineFlow::resume_deletion(
1788 0 : Arc::clone(self),
1789 0 : timeline_id,
1790 0 : &index_part.metadata,
1791 0 : remote_timeline_client,
1792 0 : ctx,
1793 0 : )
1794 0 : .instrument(tracing::info_span!("timeline_delete", %timeline_id))
1795 0 : .await
1796 0 : .context("resume_deletion")
1797 0 : .map_err(LoadLocalTimelineError::ResumeDeletion)?;
1798 : }
1799 452 : let needs_manifest_upload =
1800 452 : offloaded_timelines_list.len() != preload.tenant_manifest.offloaded_timelines.len();
1801 452 : {
1802 452 : let mut offloaded_timelines_accessor = self.timelines_offloaded.lock().unwrap();
1803 452 : offloaded_timelines_accessor.extend(offloaded_timelines_list.into_iter());
1804 452 : }
1805 452 : if needs_manifest_upload {
1806 0 : self.store_tenant_manifest().await?;
1807 452 : }
1808 :
1809 : // The local filesystem contents are a cache of what's in the remote IndexPart;
1810 : // IndexPart is the source of truth.
1811 452 : self.clean_up_timelines(&existent_timelines)?;
1812 :
1813 452 : self.gc_block.set_scanned(gc_blocks);
1814 452 :
1815 452 : fail::fail_point!("attach-before-activate", |_| {
1816 0 : anyhow::bail!("attach-before-activate");
1817 452 : });
1818 452 : failpoint_support::sleep_millis_async!("attach-before-activate-sleep", &self.cancel);
1819 :
1820 452 : info!("Done");
1821 :
1822 452 : Ok(())
1823 452 : }
1824 :
1825 : /// Check for any local timeline directories that are temporary, or do not correspond to a
1826 : /// timeline that still exists: this can happen if we crashed during a deletion/creation, or
1827 : /// if a timeline was deleted while the tenant was attached to a different pageserver.
1828 452 : fn clean_up_timelines(&self, existent_timelines: &HashSet<TimelineId>) -> anyhow::Result<()> {
1829 452 : let timelines_dir = self.conf.timelines_path(&self.tenant_shard_id);
1830 :
1831 452 : let entries = match timelines_dir.read_dir_utf8() {
1832 452 : Ok(d) => d,
1833 0 : Err(e) => {
1834 0 : if e.kind() == std::io::ErrorKind::NotFound {
1835 0 : return Ok(());
1836 : } else {
1837 0 : return Err(e).context("list timelines directory for tenant");
1838 : }
1839 : }
1840 : };
1841 :
1842 468 : for entry in entries {
1843 16 : let entry = entry.context("read timeline dir entry")?;
1844 16 : let entry_path = entry.path();
1845 :
1846 16 : let purge = if crate::is_temporary(entry_path) {
1847 0 : true
1848 : } else {
1849 16 : match TimelineId::try_from(entry_path.file_name()) {
1850 16 : Ok(i) => {
1851 16 : // Purge if the timeline ID does not exist in remote storage: remote storage is the authority.
1852 16 : !existent_timelines.contains(&i)
1853 : }
1854 0 : Err(e) => {
1855 0 : tracing::warn!(
1856 0 : "Unparseable directory in timelines directory: {entry_path}, ignoring ({e})"
1857 : );
1858 : // Do not purge junk: if we don't recognize it, be cautious and leave it for a human.
1859 0 : false
1860 : }
1861 : }
1862 : };
1863 :
1864 16 : if purge {
1865 4 : tracing::info!("Purging stale timeline dentry {entry_path}");
1866 4 : if let Err(e) = match entry.file_type() {
1867 4 : Ok(t) => if t.is_dir() {
1868 4 : std::fs::remove_dir_all(entry_path)
1869 : } else {
1870 0 : std::fs::remove_file(entry_path)
1871 : }
1872 4 : .or_else(fs_ext::ignore_not_found),
1873 0 : Err(e) => Err(e),
1874 : } {
1875 0 : tracing::warn!("Failed to purge stale timeline dentry {entry_path}: {e}");
1876 4 : }
1877 12 : }
1878 : }
1879 :
1880 452 : Ok(())
1881 452 : }
1882 :
1883 : /// Get sum of all remote timelines sizes
1884 : ///
1885 : /// This function relies on the index_part instead of listing the remote storage
1886 0 : pub fn remote_size(&self) -> u64 {
1887 0 : let mut size = 0;
1888 :
1889 0 : for timeline in self.list_timelines() {
1890 0 : size += timeline.remote_client.get_remote_physical_size();
1891 0 : }
1892 :
1893 0 : size
1894 0 : }
1895 :
1896 : #[instrument(skip_all, fields(timeline_id=%timeline_id))]
1897 : #[allow(clippy::too_many_arguments)]
1898 : async fn load_remote_timeline(
1899 : self: &Arc<Self>,
1900 : timeline_id: TimelineId,
1901 : index_part: IndexPart,
1902 : remote_metadata: TimelineMetadata,
1903 : previous_heatmap: Option<PreviousHeatmap>,
1904 : resources: TimelineResources,
1905 : cause: LoadTimelineCause,
1906 : ctx: &RequestContext,
1907 : ) -> anyhow::Result<TimelineInitAndSyncResult> {
1908 : span::debug_assert_current_span_has_tenant_id();
1909 :
1910 : info!("downloading index file for timeline {}", timeline_id);
1911 : tokio::fs::create_dir_all(self.conf.timeline_path(&self.tenant_shard_id, &timeline_id))
1912 : .await
1913 : .context("Failed to create new timeline directory")?;
1914 :
1915 : let ancestor = if let Some(ancestor_id) = remote_metadata.ancestor_timeline() {
1916 : let timelines = self.timelines.lock().unwrap();
1917 : Some(Arc::clone(timelines.get(&ancestor_id).ok_or_else(
1918 0 : || {
1919 0 : anyhow::anyhow!(
1920 0 : "cannot find ancestor timeline {ancestor_id} for timeline {timeline_id}"
1921 0 : )
1922 0 : },
1923 : )?))
1924 : } else {
1925 : None
1926 : };
1927 :
1928 : self.timeline_init_and_sync(
1929 : timeline_id,
1930 : resources,
1931 : index_part,
1932 : remote_metadata,
1933 : previous_heatmap,
1934 : ancestor,
1935 : cause,
1936 : ctx,
1937 : )
1938 : .await
1939 : }
1940 :
1941 452 : async fn load_timelines_metadata(
1942 452 : self: &Arc<Tenant>,
1943 452 : timeline_ids: HashSet<TimelineId>,
1944 452 : remote_storage: &GenericRemoteStorage,
1945 452 : heatmap: Option<(HeatMapTenant, std::time::Instant)>,
1946 452 : cancel: CancellationToken,
1947 452 : ) -> anyhow::Result<HashMap<TimelineId, TimelinePreload>> {
1948 452 : let mut timeline_heatmaps = heatmap.map(|h| (h.0.into_timelines_index(), h.1));
1949 452 :
1950 452 : let mut part_downloads = JoinSet::new();
1951 464 : for timeline_id in timeline_ids {
1952 12 : let cancel_clone = cancel.clone();
1953 12 :
1954 12 : let previous_timeline_heatmap = timeline_heatmaps.as_mut().and_then(|hs| {
1955 0 : hs.0.remove(&timeline_id).map(|h| PreviousHeatmap::Active {
1956 0 : heatmap: h,
1957 0 : read_at: hs.1,
1958 0 : end_lsn: None,
1959 0 : })
1960 12 : });
1961 12 : part_downloads.spawn(
1962 12 : self.load_timeline_metadata(
1963 12 : timeline_id,
1964 12 : remote_storage.clone(),
1965 12 : previous_timeline_heatmap,
1966 12 : cancel_clone,
1967 12 : )
1968 12 : .instrument(info_span!("download_index_part", %timeline_id)),
1969 : );
1970 : }
1971 :
1972 452 : let mut timeline_preloads: HashMap<TimelineId, TimelinePreload> = HashMap::new();
1973 :
1974 : loop {
1975 464 : tokio::select!(
1976 464 : next = part_downloads.join_next() => {
1977 464 : match next {
1978 12 : Some(result) => {
1979 12 : let preload = result.context("join preload task")?;
1980 12 : timeline_preloads.insert(preload.timeline_id, preload);
1981 : },
1982 : None => {
1983 452 : break;
1984 : }
1985 : }
1986 : },
1987 464 : _ = cancel.cancelled() => {
1988 0 : anyhow::bail!("Cancelled while waiting for remote index download")
1989 : }
1990 : )
1991 : }
1992 :
1993 452 : Ok(timeline_preloads)
1994 452 : }
1995 :
1996 12 : fn build_timeline_client(
1997 12 : &self,
1998 12 : timeline_id: TimelineId,
1999 12 : remote_storage: GenericRemoteStorage,
2000 12 : ) -> RemoteTimelineClient {
2001 12 : RemoteTimelineClient::new(
2002 12 : remote_storage.clone(),
2003 12 : self.deletion_queue_client.clone(),
2004 12 : self.conf,
2005 12 : self.tenant_shard_id,
2006 12 : timeline_id,
2007 12 : self.generation,
2008 12 : &self.tenant_conf.load().location,
2009 12 : )
2010 12 : }
2011 :
2012 12 : fn load_timeline_metadata(
2013 12 : self: &Arc<Tenant>,
2014 12 : timeline_id: TimelineId,
2015 12 : remote_storage: GenericRemoteStorage,
2016 12 : previous_heatmap: Option<PreviousHeatmap>,
2017 12 : cancel: CancellationToken,
2018 12 : ) -> impl Future<Output = TimelinePreload> + use<> {
2019 12 : let client = self.build_timeline_client(timeline_id, remote_storage);
2020 12 : async move {
2021 12 : debug_assert_current_span_has_tenant_and_timeline_id();
2022 12 : debug!("starting index part download");
2023 :
2024 12 : let index_part = client.download_index_file(&cancel).await;
2025 :
2026 12 : debug!("finished index part download");
2027 :
2028 12 : TimelinePreload {
2029 12 : client,
2030 12 : timeline_id,
2031 12 : index_part,
2032 12 : previous_heatmap,
2033 12 : }
2034 12 : }
2035 12 : }
2036 :
2037 0 : fn check_to_be_archived_has_no_unarchived_children(
2038 0 : timeline_id: TimelineId,
2039 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
2040 0 : ) -> Result<(), TimelineArchivalError> {
2041 0 : let children: Vec<TimelineId> = timelines
2042 0 : .iter()
2043 0 : .filter_map(|(id, entry)| {
2044 0 : if entry.get_ancestor_timeline_id() != Some(timeline_id) {
2045 0 : return None;
2046 0 : }
2047 0 : if entry.is_archived() == Some(true) {
2048 0 : return None;
2049 0 : }
2050 0 : Some(*id)
2051 0 : })
2052 0 : .collect();
2053 0 :
2054 0 : if !children.is_empty() {
2055 0 : return Err(TimelineArchivalError::HasUnarchivedChildren(children));
2056 0 : }
2057 0 : Ok(())
2058 0 : }
2059 :
2060 0 : fn check_ancestor_of_to_be_unarchived_is_not_archived(
2061 0 : ancestor_timeline_id: TimelineId,
2062 0 : timelines: &std::sync::MutexGuard<'_, HashMap<TimelineId, Arc<Timeline>>>,
2063 0 : offloaded_timelines: &std::sync::MutexGuard<
2064 0 : '_,
2065 0 : HashMap<TimelineId, Arc<OffloadedTimeline>>,
2066 0 : >,
2067 0 : ) -> Result<(), TimelineArchivalError> {
2068 0 : let has_archived_parent =
2069 0 : if let Some(ancestor_timeline) = timelines.get(&ancestor_timeline_id) {
2070 0 : ancestor_timeline.is_archived() == Some(true)
2071 0 : } else if offloaded_timelines.contains_key(&ancestor_timeline_id) {
2072 0 : true
2073 : } else {
2074 0 : error!("ancestor timeline {ancestor_timeline_id} not found");
2075 0 : if cfg!(debug_assertions) {
2076 0 : panic!("ancestor timeline {ancestor_timeline_id} not found");
2077 0 : }
2078 0 : return Err(TimelineArchivalError::NotFound);
2079 : };
2080 0 : if has_archived_parent {
2081 0 : return Err(TimelineArchivalError::HasArchivedParent(
2082 0 : ancestor_timeline_id,
2083 0 : ));
2084 0 : }
2085 0 : Ok(())
2086 0 : }
2087 :
2088 0 : fn check_to_be_unarchived_timeline_has_no_archived_parent(
2089 0 : timeline: &Arc<Timeline>,
2090 0 : ) -> Result<(), TimelineArchivalError> {
2091 0 : if let Some(ancestor_timeline) = timeline.ancestor_timeline() {
2092 0 : if ancestor_timeline.is_archived() == Some(true) {
2093 0 : return Err(TimelineArchivalError::HasArchivedParent(
2094 0 : ancestor_timeline.timeline_id,
2095 0 : ));
2096 0 : }
2097 0 : }
2098 0 : Ok(())
2099 0 : }
2100 :
2101 : /// Loads the specified (offloaded) timeline from S3 and attaches it as a loaded timeline
2102 : ///
2103 : /// Counterpart to [`offload_timeline`].
2104 0 : async fn unoffload_timeline(
2105 0 : self: &Arc<Self>,
2106 0 : timeline_id: TimelineId,
2107 0 : broker_client: storage_broker::BrokerClientChannel,
2108 0 : ctx: RequestContext,
2109 0 : ) -> Result<Arc<Timeline>, TimelineArchivalError> {
2110 0 : info!("unoffloading timeline");
2111 :
2112 : // We activate the timeline below manually, so this must be called on an active tenant.
2113 : // We expect callers of this function to ensure this.
2114 0 : match self.current_state() {
2115 : TenantState::Activating { .. }
2116 : | TenantState::Attaching
2117 : | TenantState::Broken { .. } => {
2118 0 : panic!("Timeline expected to be active")
2119 : }
2120 0 : TenantState::Stopping { .. } => return Err(TimelineArchivalError::Cancelled),
2121 0 : TenantState::Active => {}
2122 0 : }
2123 0 : let cancel = self.cancel.clone();
2124 0 :
2125 0 : // Protect against concurrent attempts to use this TimelineId
2126 0 : // We don't care much about idempotency, as it's ensured a layer above.
2127 0 : let allow_offloaded = true;
2128 0 : let _create_guard = self
2129 0 : .create_timeline_create_guard(
2130 0 : timeline_id,
2131 0 : CreateTimelineIdempotency::FailWithConflict,
2132 0 : allow_offloaded,
2133 0 : )
2134 0 : .map_err(|err| match err {
2135 0 : TimelineExclusionError::AlreadyCreating => TimelineArchivalError::AlreadyInProgress,
2136 : TimelineExclusionError::AlreadyExists { .. } => {
2137 0 : TimelineArchivalError::Other(anyhow::anyhow!("Timeline already exists"))
2138 : }
2139 0 : TimelineExclusionError::Other(e) => TimelineArchivalError::Other(e),
2140 0 : TimelineExclusionError::ShuttingDown => TimelineArchivalError::Cancelled,
2141 0 : })?;
2142 :
2143 0 : let timeline_preload = self
2144 0 : .load_timeline_metadata(
2145 0 : timeline_id,
2146 0 : self.remote_storage.clone(),
2147 0 : None,
2148 0 : cancel.clone(),
2149 0 : )
2150 0 : .await;
2151 :
2152 0 : let index_part = match timeline_preload.index_part {
2153 0 : Ok(index_part) => {
2154 0 : debug!("remote index part exists for timeline {timeline_id}");
2155 0 : index_part
2156 : }
2157 : Err(DownloadError::NotFound) => {
2158 0 : error!(%timeline_id, "index_part not found on remote");
2159 0 : return Err(TimelineArchivalError::NotFound);
2160 : }
2161 0 : Err(DownloadError::Cancelled) => return Err(TimelineArchivalError::Cancelled),
2162 0 : Err(e) => {
2163 0 : // Some (possibly ephemeral) error happened during index_part download.
2164 0 : warn!(%timeline_id, "Failed to load index_part from remote storage, failed creation? ({e})");
2165 0 : return Err(TimelineArchivalError::Other(
2166 0 : anyhow::Error::new(e).context("downloading index_part from remote storage"),
2167 0 : ));
2168 : }
2169 : };
2170 0 : let index_part = match index_part {
2171 0 : MaybeDeletedIndexPart::IndexPart(index_part) => index_part,
2172 0 : MaybeDeletedIndexPart::Deleted(_index_part) => {
2173 0 : info!("timeline is deleted according to index_part.json");
2174 0 : return Err(TimelineArchivalError::NotFound);
2175 : }
2176 : };
2177 0 : let remote_metadata = index_part.metadata.clone();
2178 0 : let timeline_resources = self.build_timeline_resources(timeline_id);
2179 0 : self.load_remote_timeline(
2180 0 : timeline_id,
2181 0 : index_part,
2182 0 : remote_metadata,
2183 0 : None,
2184 0 : timeline_resources,
2185 0 : LoadTimelineCause::Unoffload,
2186 0 : &ctx,
2187 0 : )
2188 0 : .await
2189 0 : .with_context(|| {
2190 0 : format!(
2191 0 : "failed to load remote timeline {} for tenant {}",
2192 0 : timeline_id, self.tenant_shard_id
2193 0 : )
2194 0 : })
2195 0 : .map_err(TimelineArchivalError::Other)?;
2196 :
2197 0 : let timeline = {
2198 0 : let timelines = self.timelines.lock().unwrap();
2199 0 : let Some(timeline) = timelines.get(&timeline_id) else {
2200 0 : warn!("timeline not available directly after attach");
2201 : // This is not a panic because no locks are held between `load_remote_timeline`
2202 : // which puts the timeline into timelines, and our look into the timeline map.
2203 0 : return Err(TimelineArchivalError::Other(anyhow::anyhow!(
2204 0 : "timeline not available directly after attach"
2205 0 : )));
2206 : };
2207 0 : let mut offloaded_timelines = self.timelines_offloaded.lock().unwrap();
2208 0 : match offloaded_timelines.remove(&timeline_id) {
2209 0 : Some(offloaded) => {
2210 0 : offloaded.delete_from_ancestor_with_timelines(&timelines);
2211 0 : }
2212 0 : None => warn!("timeline already removed from offloaded timelines"),
2213 : }
2214 :
2215 0 : self.initialize_gc_info(&timelines, &offloaded_timelines, Some(timeline_id));
2216 0 :
2217 0 : Arc::clone(timeline)
2218 0 : };
2219 0 :
2220 0 : // Upload new list of offloaded timelines to S3
2221 0 : self.store_tenant_manifest().await?;
2222 :
2223 : // Activate the timeline (if it makes sense)
2224 0 : if !(timeline.is_broken() || timeline.is_stopping()) {
2225 0 : let background_jobs_can_start = None;
2226 0 : timeline.activate(
2227 0 : self.clone(),
2228 0 : broker_client.clone(),
2229 0 : background_jobs_can_start,
2230 0 : &ctx.with_scope_timeline(&timeline),
2231 0 : );
2232 0 : }
2233 :
2234 0 : info!("timeline unoffloading complete");
2235 0 : Ok(timeline)
2236 0 : }
2237 :
2238 0 : pub(crate) async fn apply_timeline_archival_config(
2239 0 : self: &Arc<Self>,
2240 0 : timeline_id: TimelineId,
2241 0 : new_state: TimelineArchivalState,
2242 0 : broker_client: storage_broker::BrokerClientChannel,
2243 0 : ctx: RequestContext,
2244 0 : ) -> Result<(), TimelineArchivalError> {
2245 0 : info!("setting timeline archival config");
2246 : // First part: figure out what is needed to do, and do validation
2247 0 : let timeline_or_unarchive_offloaded = 'outer: {
2248 0 : let timelines = self.timelines.lock().unwrap();
2249 :
2250 0 : let Some(timeline) = timelines.get(&timeline_id) else {
2251 0 : let offloaded_timelines = self.timelines_offloaded.lock().unwrap();
2252 0 : let Some(offloaded) = offloaded_timelines.get(&timeline_id) else {
2253 0 : return Err(TimelineArchivalError::NotFound);
2254 : };
2255 0 : if new_state == TimelineArchivalState::Archived {
2256 : // It's offloaded already, so nothing to do
2257 0 : return Ok(());
2258 0 : }
2259 0 : if let Some(ancestor_timeline_id) = offloaded.ancestor_timeline_id {
2260 0 : Self::check_ancestor_of_to_be_unarchived_is_not_archived(
2261 0 : ancestor_timeline_id,
2262 0 : &timelines,
2263 0 : &offloaded_timelines,
2264 0 : )?;
2265 0 : }
2266 0 : break 'outer None;
2267 : };
2268 :
2269 : // Do some validation. We release the timelines lock below, so there is potential
2270 : // for race conditions: these checks are more present to prevent misunderstandings of
2271 : // the API's capabilities, instead of serving as the sole way to defend their invariants.
2272 0 : match new_state {
2273 : TimelineArchivalState::Unarchived => {
2274 0 : Self::check_to_be_unarchived_timeline_has_no_archived_parent(timeline)?
2275 : }
2276 : TimelineArchivalState::Archived => {
2277 0 : Self::check_to_be_archived_has_no_unarchived_children(timeline_id, &timelines)?
2278 : }
2279 : }
2280 0 : Some(Arc::clone(timeline))
2281 : };
2282 :
2283 : // Second part: unoffload timeline (if needed)
2284 0 : let timeline = if let Some(timeline) = timeline_or_unarchive_offloaded {
2285 0 : timeline
2286 : } else {
2287 : // Turn offloaded timeline into a non-offloaded one
2288 0 : self.unoffload_timeline(timeline_id, broker_client, ctx)
2289 0 : .await?
2290 : };
2291 :
2292 : // Third part: upload new timeline archival state and block until it is present in S3
2293 0 : let upload_needed = match timeline
2294 0 : .remote_client
2295 0 : .schedule_index_upload_for_timeline_archival_state(new_state)
2296 : {
2297 0 : Ok(upload_needed) => upload_needed,
2298 0 : Err(e) => {
2299 0 : if timeline.cancel.is_cancelled() {
2300 0 : return Err(TimelineArchivalError::Cancelled);
2301 : } else {
2302 0 : return Err(TimelineArchivalError::Other(e));
2303 : }
2304 : }
2305 : };
2306 :
2307 0 : if upload_needed {
2308 0 : info!("Uploading new state");
2309 : const MAX_WAIT: Duration = Duration::from_secs(10);
2310 0 : let Ok(v) =
2311 0 : tokio::time::timeout(MAX_WAIT, timeline.remote_client.wait_completion()).await
2312 : else {
2313 0 : tracing::warn!("reached timeout for waiting on upload queue");
2314 0 : return Err(TimelineArchivalError::Timeout);
2315 : };
2316 0 : v.map_err(|e| match e {
2317 0 : WaitCompletionError::NotInitialized(e) => {
2318 0 : TimelineArchivalError::Other(anyhow::anyhow!(e))
2319 : }
2320 : WaitCompletionError::UploadQueueShutDownOrStopped => {
2321 0 : TimelineArchivalError::Cancelled
2322 : }
2323 0 : })?;
2324 0 : }
2325 0 : Ok(())
2326 0 : }
2327 :
2328 4 : pub fn get_offloaded_timeline(
2329 4 : &self,
2330 4 : timeline_id: TimelineId,
2331 4 : ) -> Result<Arc<OffloadedTimeline>, GetTimelineError> {
2332 4 : self.timelines_offloaded
2333 4 : .lock()
2334 4 : .unwrap()
2335 4 : .get(&timeline_id)
2336 4 : .map(Arc::clone)
2337 4 : .ok_or(GetTimelineError::NotFound {
2338 4 : tenant_id: self.tenant_shard_id,
2339 4 : timeline_id,
2340 4 : })
2341 4 : }
2342 :
2343 8 : pub(crate) fn tenant_shard_id(&self) -> TenantShardId {
2344 8 : self.tenant_shard_id
2345 8 : }
2346 :
2347 : /// Get Timeline handle for given Neon timeline ID.
2348 : /// This function is idempotent. It doesn't change internal state in any way.
2349 444 : pub fn get_timeline(
2350 444 : &self,
2351 444 : timeline_id: TimelineId,
2352 444 : active_only: bool,
2353 444 : ) -> Result<Arc<Timeline>, GetTimelineError> {
2354 444 : let timelines_accessor = self.timelines.lock().unwrap();
2355 444 : let timeline = timelines_accessor
2356 444 : .get(&timeline_id)
2357 444 : .ok_or(GetTimelineError::NotFound {
2358 444 : tenant_id: self.tenant_shard_id,
2359 444 : timeline_id,
2360 444 : })?;
2361 :
2362 440 : if active_only && !timeline.is_active() {
2363 0 : Err(GetTimelineError::NotActive {
2364 0 : tenant_id: self.tenant_shard_id,
2365 0 : timeline_id,
2366 0 : state: timeline.current_state(),
2367 0 : })
2368 : } else {
2369 440 : Ok(Arc::clone(timeline))
2370 : }
2371 444 : }
2372 :
2373 : /// Lists timelines the tenant contains.
2374 : /// It's up to callers to omit certain timelines that are not considered ready for use.
2375 0 : pub fn list_timelines(&self) -> Vec<Arc<Timeline>> {
2376 0 : self.timelines
2377 0 : .lock()
2378 0 : .unwrap()
2379 0 : .values()
2380 0 : .map(Arc::clone)
2381 0 : .collect()
2382 0 : }
2383 :
2384 : /// Lists timelines the tenant manages, including offloaded ones.
2385 : ///
2386 : /// It's up to callers to omit certain timelines that are not considered ready for use.
2387 0 : pub fn list_timelines_and_offloaded(
2388 0 : &self,
2389 0 : ) -> (Vec<Arc<Timeline>>, Vec<Arc<OffloadedTimeline>>) {
2390 0 : let timelines = self
2391 0 : .timelines
2392 0 : .lock()
2393 0 : .unwrap()
2394 0 : .values()
2395 0 : .map(Arc::clone)
2396 0 : .collect();
2397 0 : let offloaded = self
2398 0 : .timelines_offloaded
2399 0 : .lock()
2400 0 : .unwrap()
2401 0 : .values()
2402 0 : .map(Arc::clone)
2403 0 : .collect();
2404 0 : (timelines, offloaded)
2405 0 : }
2406 :
2407 0 : pub fn list_timeline_ids(&self) -> Vec<TimelineId> {
2408 0 : self.timelines.lock().unwrap().keys().cloned().collect()
2409 0 : }
2410 :
2411 : /// This is used by tests & import-from-basebackup.
2412 : ///
2413 : /// The returned [`UninitializedTimeline`] contains no data nor metadata and it is in
2414 : /// a state that will fail [`Tenant::load_remote_timeline`] because `disk_consistent_lsn=Lsn(0)`.
2415 : ///
2416 : /// The caller is responsible for getting the timeline into a state that will be accepted
2417 : /// by [`Tenant::load_remote_timeline`] / [`Tenant::attach`].
2418 : /// Then they may call [`UninitializedTimeline::finish_creation`] to add the timeline
2419 : /// to the [`Tenant::timelines`].
2420 : ///
2421 : /// Tests should use `Tenant::create_test_timeline` to set up the minimum required metadata keys.
2422 436 : pub(crate) async fn create_empty_timeline(
2423 436 : self: &Arc<Self>,
2424 436 : new_timeline_id: TimelineId,
2425 436 : initdb_lsn: Lsn,
2426 436 : pg_version: u32,
2427 436 : ctx: &RequestContext,
2428 436 : ) -> anyhow::Result<(UninitializedTimeline, RequestContext)> {
2429 436 : anyhow::ensure!(
2430 436 : self.is_active(),
2431 0 : "Cannot create empty timelines on inactive tenant"
2432 : );
2433 :
2434 : // Protect against concurrent attempts to use this TimelineId
2435 436 : let create_guard = match self
2436 436 : .start_creating_timeline(new_timeline_id, CreateTimelineIdempotency::FailWithConflict)
2437 436 : .await?
2438 : {
2439 432 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
2440 : StartCreatingTimelineResult::Idempotent(_) => {
2441 0 : unreachable!("FailWithConflict implies we get an error instead")
2442 : }
2443 : };
2444 :
2445 432 : let new_metadata = TimelineMetadata::new(
2446 432 : // Initialize disk_consistent LSN to 0, The caller must import some data to
2447 432 : // make it valid, before calling finish_creation()
2448 432 : Lsn(0),
2449 432 : None,
2450 432 : None,
2451 432 : Lsn(0),
2452 432 : initdb_lsn,
2453 432 : initdb_lsn,
2454 432 : pg_version,
2455 432 : );
2456 432 : self.prepare_new_timeline(
2457 432 : new_timeline_id,
2458 432 : &new_metadata,
2459 432 : create_guard,
2460 432 : initdb_lsn,
2461 432 : None,
2462 432 : None,
2463 432 : ctx,
2464 432 : )
2465 432 : .await
2466 436 : }
2467 :
2468 : /// Helper for unit tests to create an empty timeline.
2469 : ///
2470 : /// The timeline is has state value `Active` but its background loops are not running.
2471 : // This makes the various functions which anyhow::ensure! for Active state work in tests.
2472 : // Our current tests don't need the background loops.
2473 : #[cfg(test)]
2474 416 : pub async fn create_test_timeline(
2475 416 : self: &Arc<Self>,
2476 416 : new_timeline_id: TimelineId,
2477 416 : initdb_lsn: Lsn,
2478 416 : pg_version: u32,
2479 416 : ctx: &RequestContext,
2480 416 : ) -> anyhow::Result<Arc<Timeline>> {
2481 416 : let (uninit_tl, ctx) = self
2482 416 : .create_empty_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
2483 416 : .await?;
2484 416 : let tline = uninit_tl.raw_timeline().expect("we just created it");
2485 416 : assert_eq!(tline.get_last_record_lsn(), Lsn(0));
2486 :
2487 : // Setup minimum keys required for the timeline to be usable.
2488 416 : let mut modification = tline.begin_modification(initdb_lsn);
2489 416 : modification
2490 416 : .init_empty_test_timeline()
2491 416 : .context("init_empty_test_timeline")?;
2492 416 : modification
2493 416 : .commit(&ctx)
2494 416 : .await
2495 416 : .context("commit init_empty_test_timeline modification")?;
2496 :
2497 : // Flush to disk so that uninit_tl's check for valid disk_consistent_lsn passes.
2498 416 : tline.maybe_spawn_flush_loop();
2499 416 : tline.freeze_and_flush().await.context("freeze_and_flush")?;
2500 :
2501 : // Make sure the freeze_and_flush reaches remote storage.
2502 416 : tline.remote_client.wait_completion().await.unwrap();
2503 :
2504 416 : let tl = uninit_tl.finish_creation().await?;
2505 : // The non-test code would call tl.activate() here.
2506 416 : tl.set_state(TimelineState::Active);
2507 416 : Ok(tl)
2508 416 : }
2509 :
2510 : /// Helper for unit tests to create a timeline with some pre-loaded states.
2511 : #[cfg(test)]
2512 : #[allow(clippy::too_many_arguments)]
2513 84 : pub async fn create_test_timeline_with_layers(
2514 84 : self: &Arc<Self>,
2515 84 : new_timeline_id: TimelineId,
2516 84 : initdb_lsn: Lsn,
2517 84 : pg_version: u32,
2518 84 : ctx: &RequestContext,
2519 84 : in_memory_layer_desc: Vec<timeline::InMemoryLayerTestDesc>,
2520 84 : delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
2521 84 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
2522 84 : end_lsn: Lsn,
2523 84 : ) -> anyhow::Result<Arc<Timeline>> {
2524 : use checks::check_valid_layermap;
2525 : use itertools::Itertools;
2526 :
2527 84 : let tline = self
2528 84 : .create_test_timeline(new_timeline_id, initdb_lsn, pg_version, ctx)
2529 84 : .await?;
2530 84 : tline.force_advance_lsn(end_lsn);
2531 256 : for deltas in delta_layer_desc {
2532 172 : tline
2533 172 : .force_create_delta_layer(deltas, Some(initdb_lsn), ctx)
2534 172 : .await?;
2535 : }
2536 204 : for (lsn, images) in image_layer_desc {
2537 120 : tline
2538 120 : .force_create_image_layer(lsn, images, Some(initdb_lsn), ctx)
2539 120 : .await?;
2540 : }
2541 92 : for in_memory in in_memory_layer_desc {
2542 8 : tline
2543 8 : .force_create_in_memory_layer(in_memory, Some(initdb_lsn), ctx)
2544 8 : .await?;
2545 : }
2546 84 : let layer_names = tline
2547 84 : .layers
2548 84 : .read()
2549 84 : .await
2550 84 : .layer_map()
2551 84 : .unwrap()
2552 84 : .iter_historic_layers()
2553 376 : .map(|layer| layer.layer_name())
2554 84 : .collect_vec();
2555 84 : if let Some(err) = check_valid_layermap(&layer_names) {
2556 0 : bail!("invalid layermap: {err}");
2557 84 : }
2558 84 : Ok(tline)
2559 84 : }
2560 :
2561 : /// Create a new timeline.
2562 : ///
2563 : /// Returns the new timeline ID and reference to its Timeline object.
2564 : ///
2565 : /// If the caller specified the timeline ID to use (`new_timeline_id`), and timeline with
2566 : /// the same timeline ID already exists, returns CreateTimelineError::AlreadyExists.
2567 : #[allow(clippy::too_many_arguments)]
2568 0 : pub(crate) async fn create_timeline(
2569 0 : self: &Arc<Tenant>,
2570 0 : params: CreateTimelineParams,
2571 0 : broker_client: storage_broker::BrokerClientChannel,
2572 0 : ctx: &RequestContext,
2573 0 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
2574 0 : if !self.is_active() {
2575 0 : if matches!(self.current_state(), TenantState::Stopping { .. }) {
2576 0 : return Err(CreateTimelineError::ShuttingDown);
2577 : } else {
2578 0 : return Err(CreateTimelineError::Other(anyhow::anyhow!(
2579 0 : "Cannot create timelines on inactive tenant"
2580 0 : )));
2581 : }
2582 0 : }
2583 :
2584 0 : let _gate = self
2585 0 : .gate
2586 0 : .enter()
2587 0 : .map_err(|_| CreateTimelineError::ShuttingDown)?;
2588 :
2589 0 : let result: CreateTimelineResult = match params {
2590 : CreateTimelineParams::Bootstrap(CreateTimelineParamsBootstrap {
2591 0 : new_timeline_id,
2592 0 : existing_initdb_timeline_id,
2593 0 : pg_version,
2594 0 : }) => {
2595 0 : self.bootstrap_timeline(
2596 0 : new_timeline_id,
2597 0 : pg_version,
2598 0 : existing_initdb_timeline_id,
2599 0 : ctx,
2600 0 : )
2601 0 : .await?
2602 : }
2603 : CreateTimelineParams::Branch(CreateTimelineParamsBranch {
2604 0 : new_timeline_id,
2605 0 : ancestor_timeline_id,
2606 0 : mut ancestor_start_lsn,
2607 : }) => {
2608 0 : let ancestor_timeline = self
2609 0 : .get_timeline(ancestor_timeline_id, false)
2610 0 : .context("Cannot branch off the timeline that's not present in pageserver")?;
2611 :
2612 : // instead of waiting around, just deny the request because ancestor is not yet
2613 : // ready for other purposes either.
2614 0 : if !ancestor_timeline.is_active() {
2615 0 : return Err(CreateTimelineError::AncestorNotActive);
2616 0 : }
2617 0 :
2618 0 : if ancestor_timeline.is_archived() == Some(true) {
2619 0 : info!("tried to branch archived timeline");
2620 0 : return Err(CreateTimelineError::AncestorArchived);
2621 0 : }
2622 :
2623 0 : if let Some(lsn) = ancestor_start_lsn.as_mut() {
2624 0 : *lsn = lsn.align();
2625 0 :
2626 0 : let ancestor_ancestor_lsn = ancestor_timeline.get_ancestor_lsn();
2627 0 : if ancestor_ancestor_lsn > *lsn {
2628 : // can we safely just branch from the ancestor instead?
2629 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
2630 0 : "invalid start lsn {} for ancestor timeline {}: less than timeline ancestor lsn {}",
2631 0 : lsn,
2632 0 : ancestor_timeline_id,
2633 0 : ancestor_ancestor_lsn,
2634 0 : )));
2635 0 : }
2636 0 :
2637 0 : // Wait for the WAL to arrive and be processed on the parent branch up
2638 0 : // to the requested branch point. The repository code itself doesn't
2639 0 : // require it, but if we start to receive WAL on the new timeline,
2640 0 : // decoding the new WAL might need to look up previous pages, relation
2641 0 : // sizes etc. and that would get confused if the previous page versions
2642 0 : // are not in the repository yet.
2643 0 : ancestor_timeline
2644 0 : .wait_lsn(
2645 0 : *lsn,
2646 0 : timeline::WaitLsnWaiter::Tenant,
2647 0 : timeline::WaitLsnTimeout::Default,
2648 0 : ctx,
2649 0 : )
2650 0 : .await
2651 0 : .map_err(|e| match e {
2652 0 : e @ (WaitLsnError::Timeout(_) | WaitLsnError::BadState { .. }) => {
2653 0 : CreateTimelineError::AncestorLsn(anyhow::anyhow!(e))
2654 : }
2655 0 : WaitLsnError::Shutdown => CreateTimelineError::ShuttingDown,
2656 0 : })?;
2657 0 : }
2658 :
2659 0 : self.branch_timeline(&ancestor_timeline, new_timeline_id, ancestor_start_lsn, ctx)
2660 0 : .await?
2661 : }
2662 0 : CreateTimelineParams::ImportPgdata(params) => {
2663 0 : self.create_timeline_import_pgdata(
2664 0 : params,
2665 0 : ActivateTimelineArgs::Yes {
2666 0 : broker_client: broker_client.clone(),
2667 0 : },
2668 0 : ctx,
2669 0 : )
2670 0 : .await?
2671 : }
2672 : };
2673 :
2674 : // At this point we have dropped our guard on [`Self::timelines_creating`], and
2675 : // the timeline is visible in [`Self::timelines`], but it is _not_ durable yet. We must
2676 : // not send a success to the caller until it is. The same applies to idempotent retries.
2677 : //
2678 : // TODO: the timeline is already visible in [`Self::timelines`]; a caller could incorrectly
2679 : // assume that, because they can see the timeline via API, that the creation is done and
2680 : // that it is durable. Ideally, we would keep the timeline hidden (in [`Self::timelines_creating`])
2681 : // until it is durable, e.g., by extending the time we hold the creation guard. This also
2682 : // interacts with UninitializedTimeline and is generally a bit tricky.
2683 : //
2684 : // To re-emphasize: the only correct way to create a timeline is to repeat calling the
2685 : // creation API until it returns success. Only then is durability guaranteed.
2686 0 : info!(creation_result=%result.discriminant(), "waiting for timeline to be durable");
2687 0 : result
2688 0 : .timeline()
2689 0 : .remote_client
2690 0 : .wait_completion()
2691 0 : .await
2692 0 : .map_err(|e| match e {
2693 : WaitCompletionError::NotInitialized(
2694 0 : e, // If the queue is already stopped, it's a shutdown error.
2695 0 : ) if e.is_stopping() => CreateTimelineError::ShuttingDown,
2696 : WaitCompletionError::NotInitialized(_) => {
2697 : // This is a bug: we should never try to wait for uploads before initializing the timeline
2698 0 : debug_assert!(false);
2699 0 : CreateTimelineError::Other(anyhow::anyhow!("timeline not initialized"))
2700 : }
2701 : WaitCompletionError::UploadQueueShutDownOrStopped => {
2702 0 : CreateTimelineError::ShuttingDown
2703 : }
2704 0 : })?;
2705 :
2706 : // The creating task is responsible for activating the timeline.
2707 : // We do this after `wait_completion()` so that we don't spin up tasks that start
2708 : // doing stuff before the IndexPart is durable in S3, which is done by the previous section.
2709 0 : let activated_timeline = match result {
2710 0 : CreateTimelineResult::Created(timeline) => {
2711 0 : timeline.activate(
2712 0 : self.clone(),
2713 0 : broker_client,
2714 0 : None,
2715 0 : &ctx.with_scope_timeline(&timeline),
2716 0 : );
2717 0 : timeline
2718 : }
2719 0 : CreateTimelineResult::Idempotent(timeline) => {
2720 0 : info!(
2721 0 : "request was deemed idempotent, activation will be done by the creating task"
2722 : );
2723 0 : timeline
2724 : }
2725 0 : CreateTimelineResult::ImportSpawned(timeline) => {
2726 0 : info!(
2727 0 : "import task spawned, timeline will become visible and activated once the import is done"
2728 : );
2729 0 : timeline
2730 : }
2731 : };
2732 :
2733 0 : Ok(activated_timeline)
2734 0 : }
2735 :
2736 : /// The returned [`Arc<Timeline>`] is NOT in the [`Tenant::timelines`] map until the import
2737 : /// completes in the background. A DIFFERENT [`Arc<Timeline>`] will be inserted into the
2738 : /// [`Tenant::timelines`] map when the import completes.
2739 : /// We only return an [`Arc<Timeline>`] here so the API handler can create a [`pageserver_api::models::TimelineInfo`]
2740 : /// for the response.
2741 0 : async fn create_timeline_import_pgdata(
2742 0 : self: &Arc<Tenant>,
2743 0 : params: CreateTimelineParamsImportPgdata,
2744 0 : activate: ActivateTimelineArgs,
2745 0 : ctx: &RequestContext,
2746 0 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
2747 0 : let CreateTimelineParamsImportPgdata {
2748 0 : new_timeline_id,
2749 0 : location,
2750 0 : idempotency_key,
2751 0 : } = params;
2752 0 :
2753 0 : let started_at = chrono::Utc::now().naive_utc();
2754 :
2755 : //
2756 : // There's probably a simpler way to upload an index part, but, remote_timeline_client
2757 : // is the canonical way we do it.
2758 : // - create an empty timeline in-memory
2759 : // - use its remote_timeline_client to do the upload
2760 : // - dispose of the uninit timeline
2761 : // - keep the creation guard alive
2762 :
2763 0 : let timeline_create_guard = match self
2764 0 : .start_creating_timeline(
2765 0 : new_timeline_id,
2766 0 : CreateTimelineIdempotency::ImportPgdata(CreatingTimelineIdempotencyImportPgdata {
2767 0 : idempotency_key: idempotency_key.clone(),
2768 0 : }),
2769 0 : )
2770 0 : .await?
2771 : {
2772 0 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
2773 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
2774 0 : return Ok(CreateTimelineResult::Idempotent(timeline));
2775 : }
2776 : };
2777 :
2778 0 : let (mut uninit_timeline, timeline_ctx) = {
2779 0 : let this = &self;
2780 0 : let initdb_lsn = Lsn(0);
2781 0 : async move {
2782 0 : let new_metadata = TimelineMetadata::new(
2783 0 : // Initialize disk_consistent LSN to 0, The caller must import some data to
2784 0 : // make it valid, before calling finish_creation()
2785 0 : Lsn(0),
2786 0 : None,
2787 0 : None,
2788 0 : Lsn(0),
2789 0 : initdb_lsn,
2790 0 : initdb_lsn,
2791 0 : 15,
2792 0 : );
2793 0 : this.prepare_new_timeline(
2794 0 : new_timeline_id,
2795 0 : &new_metadata,
2796 0 : timeline_create_guard,
2797 0 : initdb_lsn,
2798 0 : None,
2799 0 : None,
2800 0 : ctx,
2801 0 : )
2802 0 : .await
2803 0 : }
2804 0 : }
2805 0 : .await?;
2806 :
2807 0 : let in_progress = import_pgdata::index_part_format::InProgress {
2808 0 : idempotency_key,
2809 0 : location,
2810 0 : started_at,
2811 0 : };
2812 0 : let index_part = import_pgdata::index_part_format::Root::V1(
2813 0 : import_pgdata::index_part_format::V1::InProgress(in_progress),
2814 0 : );
2815 0 : uninit_timeline
2816 0 : .raw_timeline()
2817 0 : .unwrap()
2818 0 : .remote_client
2819 0 : .schedule_index_upload_for_import_pgdata_state_update(Some(index_part.clone()))?;
2820 :
2821 : // wait_completion happens in caller
2822 :
2823 0 : let (timeline, timeline_create_guard) = uninit_timeline.finish_creation_myself();
2824 0 :
2825 0 : tokio::spawn(self.clone().create_timeline_import_pgdata_task(
2826 0 : timeline.clone(),
2827 0 : index_part,
2828 0 : activate,
2829 0 : timeline_create_guard,
2830 0 : timeline_ctx.detached_child(TaskKind::ImportPgdata, DownloadBehavior::Warn),
2831 0 : ));
2832 0 :
2833 0 : // NB: the timeline doesn't exist in self.timelines at this point
2834 0 : Ok(CreateTimelineResult::ImportSpawned(timeline))
2835 0 : }
2836 :
2837 : #[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))]
2838 : async fn create_timeline_import_pgdata_task(
2839 : self: Arc<Tenant>,
2840 : timeline: Arc<Timeline>,
2841 : index_part: import_pgdata::index_part_format::Root,
2842 : activate: ActivateTimelineArgs,
2843 : timeline_create_guard: TimelineCreateGuard,
2844 : ctx: RequestContext,
2845 : ) {
2846 : debug_assert_current_span_has_tenant_and_timeline_id();
2847 : info!("starting");
2848 : scopeguard::defer! {info!("exiting")};
2849 :
2850 : let res = self
2851 : .create_timeline_import_pgdata_task_impl(
2852 : timeline,
2853 : index_part,
2854 : activate,
2855 : timeline_create_guard,
2856 : ctx,
2857 : )
2858 : .await;
2859 : if let Err(err) = &res {
2860 : error!(?err, "task failed");
2861 : // TODO sleep & retry, sensitive to tenant shutdown
2862 : // TODO: allow timeline deletion requests => should cancel the task
2863 : }
2864 : }
2865 :
2866 0 : async fn create_timeline_import_pgdata_task_impl(
2867 0 : self: Arc<Tenant>,
2868 0 : timeline: Arc<Timeline>,
2869 0 : index_part: import_pgdata::index_part_format::Root,
2870 0 : activate: ActivateTimelineArgs,
2871 0 : timeline_create_guard: TimelineCreateGuard,
2872 0 : ctx: RequestContext,
2873 0 : ) -> Result<(), anyhow::Error> {
2874 0 : info!("importing pgdata");
2875 0 : import_pgdata::doit(&timeline, index_part, &ctx, self.cancel.clone())
2876 0 : .await
2877 0 : .context("import")?;
2878 0 : info!("import done");
2879 :
2880 : //
2881 : // Reload timeline from remote.
2882 : // This proves that the remote state is attachable, and it reuses the code.
2883 : //
2884 : // TODO: think about whether this is safe to do with concurrent Tenant::shutdown.
2885 : // timeline_create_guard hols the tenant gate open, so, shutdown cannot _complete_ until we exit.
2886 : // But our activate() call might launch new background tasks after Tenant::shutdown
2887 : // already went past shutting down the Tenant::timelines, which this timeline here is no part of.
2888 : // I think the same problem exists with the bootstrap & branch mgmt API tasks (tenant shutting
2889 : // down while bootstrapping/branching + activating), but, the race condition is much more likely
2890 : // to manifest because of the long runtime of this import task.
2891 :
2892 : // in theory this shouldn't even .await anything except for coop yield
2893 0 : info!("shutting down timeline");
2894 0 : timeline.shutdown(ShutdownMode::Hard).await;
2895 0 : info!("timeline shut down, reloading from remote");
2896 : // TODO: we can't do the following check because create_timeline_import_pgdata must return an Arc<Timeline>
2897 : // let Some(timeline) = Arc::into_inner(timeline) else {
2898 : // anyhow::bail!("implementation error: timeline that we shut down was still referenced from somewhere");
2899 : // };
2900 0 : let timeline_id = timeline.timeline_id;
2901 0 :
2902 0 : // load from object storage like Tenant::attach does
2903 0 : let resources = self.build_timeline_resources(timeline_id);
2904 0 : let index_part = resources
2905 0 : .remote_client
2906 0 : .download_index_file(&self.cancel)
2907 0 : .await?;
2908 0 : let index_part = match index_part {
2909 : MaybeDeletedIndexPart::Deleted(_) => {
2910 : // likely concurrent delete call, cplane should prevent this
2911 0 : anyhow::bail!(
2912 0 : "index part says deleted but we are not done creating yet, this should not happen but"
2913 0 : )
2914 : }
2915 0 : MaybeDeletedIndexPart::IndexPart(p) => p,
2916 0 : };
2917 0 : let metadata = index_part.metadata.clone();
2918 0 : self
2919 0 : .load_remote_timeline(timeline_id, index_part, metadata, None, resources, LoadTimelineCause::ImportPgdata{
2920 0 : create_guard: timeline_create_guard, activate, }, &ctx)
2921 0 : .await?
2922 0 : .ready_to_activate()
2923 0 : .context("implementation error: reloaded timeline still needs import after import reported success")?;
2924 :
2925 0 : anyhow::Ok(())
2926 0 : }
2927 :
2928 0 : pub(crate) async fn delete_timeline(
2929 0 : self: Arc<Self>,
2930 0 : timeline_id: TimelineId,
2931 0 : ) -> Result<(), DeleteTimelineError> {
2932 0 : DeleteTimelineFlow::run(&self, timeline_id).await?;
2933 :
2934 0 : Ok(())
2935 0 : }
2936 :
2937 : /// perform one garbage collection iteration, removing old data files from disk.
2938 : /// this function is periodically called by gc task.
2939 : /// also it can be explicitly requested through page server api 'do_gc' command.
2940 : ///
2941 : /// `target_timeline_id` specifies the timeline to GC, or None for all.
2942 : ///
2943 : /// The `horizon` an `pitr` parameters determine how much WAL history needs to be retained.
2944 : /// Also known as the retention period, or the GC cutoff point. `horizon` specifies
2945 : /// the amount of history, as LSN difference from current latest LSN on each timeline.
2946 : /// `pitr` specifies the same as a time difference from the current time. The effective
2947 : /// GC cutoff point is determined conservatively by either `horizon` and `pitr`, whichever
2948 : /// requires more history to be retained.
2949 : //
2950 1508 : pub(crate) async fn gc_iteration(
2951 1508 : &self,
2952 1508 : target_timeline_id: Option<TimelineId>,
2953 1508 : horizon: u64,
2954 1508 : pitr: Duration,
2955 1508 : cancel: &CancellationToken,
2956 1508 : ctx: &RequestContext,
2957 1508 : ) -> Result<GcResult, GcError> {
2958 1508 : // Don't start doing work during shutdown
2959 1508 : if let TenantState::Stopping { .. } = self.current_state() {
2960 0 : return Ok(GcResult::default());
2961 1508 : }
2962 1508 :
2963 1508 : // there is a global allowed_error for this
2964 1508 : if !self.is_active() {
2965 0 : return Err(GcError::NotActive);
2966 1508 : }
2967 1508 :
2968 1508 : {
2969 1508 : let conf = self.tenant_conf.load();
2970 1508 :
2971 1508 : // If we may not delete layers, then simply skip GC. Even though a tenant
2972 1508 : // in AttachedMulti state could do GC and just enqueue the blocked deletions,
2973 1508 : // the only advantage to doing it is to perhaps shrink the LayerMap metadata
2974 1508 : // a bit sooner than we would achieve by waiting for AttachedSingle status.
2975 1508 : if !conf.location.may_delete_layers_hint() {
2976 0 : info!("Skipping GC in location state {:?}", conf.location);
2977 0 : return Ok(GcResult::default());
2978 1508 : }
2979 1508 :
2980 1508 : if conf.is_gc_blocked_by_lsn_lease_deadline() {
2981 1500 : info!("Skipping GC because lsn lease deadline is not reached");
2982 1500 : return Ok(GcResult::default());
2983 8 : }
2984 : }
2985 :
2986 8 : let _guard = match self.gc_block.start().await {
2987 8 : Ok(guard) => guard,
2988 0 : Err(reasons) => {
2989 0 : info!("Skipping GC: {reasons}");
2990 0 : return Ok(GcResult::default());
2991 : }
2992 : };
2993 :
2994 8 : self.gc_iteration_internal(target_timeline_id, horizon, pitr, cancel, ctx)
2995 8 : .await
2996 1508 : }
2997 :
2998 : /// Performs one compaction iteration. Called periodically from the compaction loop. Returns
2999 : /// whether another compaction is needed, if we still have pending work or if we yield for
3000 : /// immediate L0 compaction.
3001 : ///
3002 : /// Compaction can also be explicitly requested for a timeline via the HTTP API.
3003 0 : async fn compaction_iteration(
3004 0 : self: &Arc<Self>,
3005 0 : cancel: &CancellationToken,
3006 0 : ctx: &RequestContext,
3007 0 : ) -> Result<CompactionOutcome, CompactionError> {
3008 0 : // Don't compact inactive tenants.
3009 0 : if !self.is_active() {
3010 0 : return Ok(CompactionOutcome::Skipped);
3011 0 : }
3012 0 :
3013 0 : // Don't compact tenants that can't upload layers. We don't check `may_delete_layers_hint`,
3014 0 : // since we need to compact L0 even in AttachedMulti to bound read amplification.
3015 0 : let location = self.tenant_conf.load().location;
3016 0 : if !location.may_upload_layers_hint() {
3017 0 : info!("skipping compaction in location state {location:?}");
3018 0 : return Ok(CompactionOutcome::Skipped);
3019 0 : }
3020 0 :
3021 0 : // Don't compact if the circuit breaker is tripped.
3022 0 : if self.compaction_circuit_breaker.lock().unwrap().is_broken() {
3023 0 : info!("skipping compaction due to previous failures");
3024 0 : return Ok(CompactionOutcome::Skipped);
3025 0 : }
3026 0 :
3027 0 : // Collect all timelines to compact, along with offload instructions and L0 counts.
3028 0 : let mut compact: Vec<Arc<Timeline>> = Vec::new();
3029 0 : let mut offload: HashSet<TimelineId> = HashSet::new();
3030 0 : let mut l0_counts: HashMap<TimelineId, usize> = HashMap::new();
3031 0 :
3032 0 : {
3033 0 : let offload_enabled = self.get_timeline_offloading_enabled();
3034 0 : let timelines = self.timelines.lock().unwrap();
3035 0 : for (&timeline_id, timeline) in timelines.iter() {
3036 : // Skip inactive timelines.
3037 0 : if !timeline.is_active() {
3038 0 : continue;
3039 0 : }
3040 0 :
3041 0 : // Schedule the timeline for compaction.
3042 0 : compact.push(timeline.clone());
3043 :
3044 : // Schedule the timeline for offloading if eligible.
3045 0 : let can_offload = offload_enabled
3046 0 : && timeline.can_offload().0
3047 0 : && !timelines
3048 0 : .iter()
3049 0 : .any(|(_, tli)| tli.get_ancestor_timeline_id() == Some(timeline_id));
3050 0 : if can_offload {
3051 0 : offload.insert(timeline_id);
3052 0 : }
3053 : }
3054 : } // release timelines lock
3055 :
3056 0 : for timeline in &compact {
3057 : // Collect L0 counts. Can't await while holding lock above.
3058 0 : if let Ok(lm) = timeline.layers.read().await.layer_map() {
3059 0 : l0_counts.insert(timeline.timeline_id, lm.level0_deltas().len());
3060 0 : }
3061 : }
3062 :
3063 : // Pass 1: L0 compaction across all timelines, in order of L0 count. We prioritize this to
3064 : // bound read amplification.
3065 : //
3066 : // TODO: this may spin on one or more ingest-heavy timelines, starving out image/GC
3067 : // compaction and offloading. We leave that as a potential problem to solve later. Consider
3068 : // splitting L0 and image/GC compaction to separate background jobs.
3069 0 : if self.get_compaction_l0_first() {
3070 0 : let compaction_threshold = self.get_compaction_threshold();
3071 0 : let compact_l0 = compact
3072 0 : .iter()
3073 0 : .map(|tli| (tli, l0_counts.get(&tli.timeline_id).copied().unwrap_or(0)))
3074 0 : .filter(|&(_, l0)| l0 >= compaction_threshold)
3075 0 : .sorted_by_key(|&(_, l0)| l0)
3076 0 : .rev()
3077 0 : .map(|(tli, _)| tli.clone())
3078 0 : .collect_vec();
3079 0 :
3080 0 : let mut has_pending_l0 = false;
3081 0 : for timeline in compact_l0 {
3082 0 : let ctx = &ctx.with_scope_timeline(&timeline);
3083 0 : let outcome = timeline
3084 0 : .compact(cancel, CompactFlags::OnlyL0Compaction.into(), ctx)
3085 0 : .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
3086 0 : .await
3087 0 : .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
3088 0 : match outcome {
3089 0 : CompactionOutcome::Done => {}
3090 0 : CompactionOutcome::Skipped => {}
3091 0 : CompactionOutcome::Pending => has_pending_l0 = true,
3092 0 : CompactionOutcome::YieldForL0 => has_pending_l0 = true,
3093 : }
3094 : }
3095 0 : if has_pending_l0 {
3096 0 : return Ok(CompactionOutcome::YieldForL0); // do another pass
3097 0 : }
3098 0 : }
3099 :
3100 : // Pass 2: image compaction and timeline offloading. If any timelines have accumulated
3101 : // more L0 layers, they may also be compacted here.
3102 : //
3103 : // NB: image compaction may yield if there is pending L0 compaction.
3104 : //
3105 : // TODO: it will only yield if there is pending L0 compaction on the same timeline. If a
3106 : // different timeline needs compaction, it won't. It should check `l0_compaction_trigger`.
3107 : // We leave this for a later PR.
3108 : //
3109 : // TODO: consider ordering timelines by some priority, e.g. time since last full compaction,
3110 : // amount of L1 delta debt or garbage, offload-eligible timelines first, etc.
3111 0 : let mut has_pending = false;
3112 0 : for timeline in compact {
3113 0 : if !timeline.is_active() {
3114 0 : continue;
3115 0 : }
3116 0 : let ctx = &ctx.with_scope_timeline(&timeline);
3117 :
3118 0 : let mut outcome = timeline
3119 0 : .compact(cancel, EnumSet::default(), ctx)
3120 0 : .instrument(info_span!("compact_timeline", timeline_id = %timeline.timeline_id))
3121 0 : .await
3122 0 : .inspect_err(|err| self.maybe_trip_compaction_breaker(err))?;
3123 :
3124 : // If we're done compacting, check the scheduled GC compaction queue for more work.
3125 0 : if outcome == CompactionOutcome::Done {
3126 0 : let queue = {
3127 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3128 0 : guard
3129 0 : .entry(timeline.timeline_id)
3130 0 : .or_insert_with(|| Arc::new(GcCompactionQueue::new()))
3131 0 : .clone()
3132 0 : };
3133 0 : outcome = queue
3134 0 : .iteration(cancel, ctx, &self.gc_block, &timeline)
3135 0 : .instrument(
3136 0 : info_span!("gc_compact_timeline", timeline_id = %timeline.timeline_id),
3137 : )
3138 0 : .await?;
3139 0 : }
3140 :
3141 : // If we're done compacting, offload the timeline if requested.
3142 0 : if outcome == CompactionOutcome::Done && offload.contains(&timeline.timeline_id) {
3143 0 : pausable_failpoint!("before-timeline-auto-offload");
3144 0 : offload_timeline(self, &timeline)
3145 0 : .instrument(info_span!("offload_timeline", timeline_id = %timeline.timeline_id))
3146 0 : .await
3147 0 : .or_else(|err| match err {
3148 : // Ignore this, we likely raced with unarchival.
3149 0 : OffloadError::NotArchived => Ok(()),
3150 0 : err => Err(err),
3151 0 : })?;
3152 0 : }
3153 :
3154 0 : match outcome {
3155 0 : CompactionOutcome::Done => {}
3156 0 : CompactionOutcome::Skipped => {}
3157 0 : CompactionOutcome::Pending => has_pending = true,
3158 : // This mostly makes sense when the L0-only pass above is enabled, since there's
3159 : // otherwise no guarantee that we'll start with the timeline that has high L0.
3160 0 : CompactionOutcome::YieldForL0 => return Ok(CompactionOutcome::YieldForL0),
3161 : }
3162 : }
3163 :
3164 : // Success! Untrip the breaker if necessary.
3165 0 : self.compaction_circuit_breaker
3166 0 : .lock()
3167 0 : .unwrap()
3168 0 : .success(&CIRCUIT_BREAKERS_UNBROKEN);
3169 0 :
3170 0 : match has_pending {
3171 0 : true => Ok(CompactionOutcome::Pending),
3172 0 : false => Ok(CompactionOutcome::Done),
3173 : }
3174 0 : }
3175 :
3176 : /// Trips the compaction circuit breaker if appropriate.
3177 0 : pub(crate) fn maybe_trip_compaction_breaker(&self, err: &CompactionError) {
3178 0 : match err {
3179 0 : err if err.is_cancel() => {}
3180 0 : CompactionError::ShuttingDown => (),
3181 : // Offload failures don't trip the circuit breaker, since they're cheap to retry and
3182 : // shouldn't block compaction.
3183 0 : CompactionError::Offload(_) => {}
3184 0 : CompactionError::CollectKeySpaceError(err) => {
3185 0 : // CollectKeySpaceError::Cancelled and PageRead::Cancelled are handled in `err.is_cancel` branch.
3186 0 : self.compaction_circuit_breaker
3187 0 : .lock()
3188 0 : .unwrap()
3189 0 : .fail(&CIRCUIT_BREAKERS_BROKEN, err);
3190 0 : }
3191 0 : CompactionError::Other(err) => {
3192 0 : self.compaction_circuit_breaker
3193 0 : .lock()
3194 0 : .unwrap()
3195 0 : .fail(&CIRCUIT_BREAKERS_BROKEN, err);
3196 0 : }
3197 0 : CompactionError::AlreadyRunning(_) => {}
3198 : }
3199 0 : }
3200 :
3201 : /// Cancel scheduled compaction tasks
3202 0 : pub(crate) fn cancel_scheduled_compaction(&self, timeline_id: TimelineId) {
3203 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3204 0 : if let Some(q) = guard.get_mut(&timeline_id) {
3205 0 : q.cancel_scheduled();
3206 0 : }
3207 0 : }
3208 :
3209 0 : pub(crate) fn get_scheduled_compaction_tasks(
3210 0 : &self,
3211 0 : timeline_id: TimelineId,
3212 0 : ) -> Vec<CompactInfoResponse> {
3213 0 : let res = {
3214 0 : let guard = self.scheduled_compaction_tasks.lock().unwrap();
3215 0 : guard.get(&timeline_id).map(|q| q.remaining_jobs())
3216 : };
3217 0 : let Some((running, remaining)) = res else {
3218 0 : return Vec::new();
3219 : };
3220 0 : let mut result = Vec::new();
3221 0 : if let Some((id, running)) = running {
3222 0 : result.extend(running.into_compact_info_resp(id, true));
3223 0 : }
3224 0 : for (id, job) in remaining {
3225 0 : result.extend(job.into_compact_info_resp(id, false));
3226 0 : }
3227 0 : result
3228 0 : }
3229 :
3230 : /// Schedule a compaction task for a timeline.
3231 0 : pub(crate) async fn schedule_compaction(
3232 0 : &self,
3233 0 : timeline_id: TimelineId,
3234 0 : options: CompactOptions,
3235 0 : ) -> anyhow::Result<tokio::sync::oneshot::Receiver<()>> {
3236 0 : let (tx, rx) = tokio::sync::oneshot::channel();
3237 0 : let mut guard = self.scheduled_compaction_tasks.lock().unwrap();
3238 0 : let q = guard
3239 0 : .entry(timeline_id)
3240 0 : .or_insert_with(|| Arc::new(GcCompactionQueue::new()));
3241 0 : q.schedule_manual_compaction(options, Some(tx));
3242 0 : Ok(rx)
3243 0 : }
3244 :
3245 : /// Performs periodic housekeeping, via the tenant housekeeping background task.
3246 0 : async fn housekeeping(&self) {
3247 0 : // Call through to all timelines to freeze ephemeral layers as needed. This usually happens
3248 0 : // during ingest, but we don't want idle timelines to hold open layers for too long.
3249 0 : let timelines = self
3250 0 : .timelines
3251 0 : .lock()
3252 0 : .unwrap()
3253 0 : .values()
3254 0 : .filter(|tli| tli.is_active())
3255 0 : .cloned()
3256 0 : .collect_vec();
3257 :
3258 0 : for timeline in timelines {
3259 0 : timeline.maybe_freeze_ephemeral_layer().await;
3260 : }
3261 :
3262 : // Shut down walredo if idle.
3263 : const WALREDO_IDLE_TIMEOUT: Duration = Duration::from_secs(180);
3264 0 : if let Some(ref walredo_mgr) = self.walredo_mgr {
3265 0 : walredo_mgr.maybe_quiesce(WALREDO_IDLE_TIMEOUT);
3266 0 : }
3267 0 : }
3268 :
3269 0 : pub fn timeline_has_no_attached_children(&self, timeline_id: TimelineId) -> bool {
3270 0 : let timelines = self.timelines.lock().unwrap();
3271 0 : !timelines
3272 0 : .iter()
3273 0 : .any(|(_id, tl)| tl.get_ancestor_timeline_id() == Some(timeline_id))
3274 0 : }
3275 :
3276 3476 : pub fn current_state(&self) -> TenantState {
3277 3476 : self.state.borrow().clone()
3278 3476 : }
3279 :
3280 1952 : pub fn is_active(&self) -> bool {
3281 1952 : self.current_state() == TenantState::Active
3282 1952 : }
3283 :
3284 0 : pub fn generation(&self) -> Generation {
3285 0 : self.generation
3286 0 : }
3287 :
3288 0 : pub(crate) fn wal_redo_manager_status(&self) -> Option<WalRedoManagerStatus> {
3289 0 : self.walredo_mgr.as_ref().and_then(|mgr| mgr.status())
3290 0 : }
3291 :
3292 : /// Changes tenant status to active, unless shutdown was already requested.
3293 : ///
3294 : /// `background_jobs_can_start` is an optional barrier set to a value during pageserver startup
3295 : /// to delay background jobs. Background jobs can be started right away when None is given.
3296 0 : fn activate(
3297 0 : self: &Arc<Self>,
3298 0 : broker_client: BrokerClientChannel,
3299 0 : background_jobs_can_start: Option<&completion::Barrier>,
3300 0 : ctx: &RequestContext,
3301 0 : ) {
3302 0 : span::debug_assert_current_span_has_tenant_id();
3303 0 :
3304 0 : let mut activating = false;
3305 0 : self.state.send_modify(|current_state| {
3306 : use pageserver_api::models::ActivatingFrom;
3307 0 : match &*current_state {
3308 : TenantState::Activating(_) | TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => {
3309 0 : panic!("caller is responsible for calling activate() only on Loading / Attaching tenants, got {state:?}", state = current_state);
3310 : }
3311 0 : TenantState::Attaching => {
3312 0 : *current_state = TenantState::Activating(ActivatingFrom::Attaching);
3313 0 : }
3314 0 : }
3315 0 : debug!(tenant_id = %self.tenant_shard_id.tenant_id, shard_id = %self.tenant_shard_id.shard_slug(), "Activating tenant");
3316 0 : activating = true;
3317 0 : // Continue outside the closure. We need to grab timelines.lock()
3318 0 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
3319 0 : });
3320 0 :
3321 0 : if activating {
3322 0 : let timelines_accessor = self.timelines.lock().unwrap();
3323 0 : let timelines_offloaded_accessor = self.timelines_offloaded.lock().unwrap();
3324 0 : let timelines_to_activate = timelines_accessor
3325 0 : .values()
3326 0 : .filter(|timeline| !(timeline.is_broken() || timeline.is_stopping()));
3327 0 :
3328 0 : // Before activation, populate each Timeline's GcInfo with information about its children
3329 0 : self.initialize_gc_info(&timelines_accessor, &timelines_offloaded_accessor, None);
3330 0 :
3331 0 : // Spawn gc and compaction loops. The loops will shut themselves
3332 0 : // down when they notice that the tenant is inactive.
3333 0 : tasks::start_background_loops(self, background_jobs_can_start);
3334 0 :
3335 0 : let mut activated_timelines = 0;
3336 :
3337 0 : for timeline in timelines_to_activate {
3338 0 : timeline.activate(
3339 0 : self.clone(),
3340 0 : broker_client.clone(),
3341 0 : background_jobs_can_start,
3342 0 : &ctx.with_scope_timeline(timeline),
3343 0 : );
3344 0 : activated_timelines += 1;
3345 0 : }
3346 :
3347 0 : self.state.send_modify(move |current_state| {
3348 0 : assert!(
3349 0 : matches!(current_state, TenantState::Activating(_)),
3350 0 : "set_stopping and set_broken wait for us to leave Activating state",
3351 : );
3352 0 : *current_state = TenantState::Active;
3353 0 :
3354 0 : let elapsed = self.constructed_at.elapsed();
3355 0 : let total_timelines = timelines_accessor.len();
3356 0 :
3357 0 : // log a lot of stuff, because some tenants sometimes suffer from user-visible
3358 0 : // times to activate. see https://github.com/neondatabase/neon/issues/4025
3359 0 : info!(
3360 0 : since_creation_millis = elapsed.as_millis(),
3361 0 : tenant_id = %self.tenant_shard_id.tenant_id,
3362 0 : shard_id = %self.tenant_shard_id.shard_slug(),
3363 0 : activated_timelines,
3364 0 : total_timelines,
3365 0 : post_state = <&'static str>::from(&*current_state),
3366 0 : "activation attempt finished"
3367 : );
3368 :
3369 0 : TENANT.activation.observe(elapsed.as_secs_f64());
3370 0 : });
3371 0 : }
3372 0 : }
3373 :
3374 : /// Shutdown the tenant and join all of the spawned tasks.
3375 : ///
3376 : /// The method caters for all use-cases:
3377 : /// - pageserver shutdown (freeze_and_flush == true)
3378 : /// - detach + ignore (freeze_and_flush == false)
3379 : ///
3380 : /// This will attempt to shutdown even if tenant is broken.
3381 : ///
3382 : /// `shutdown_progress` is a [`completion::Barrier`] for the shutdown initiated by this call.
3383 : /// If the tenant is already shutting down, we return a clone of the first shutdown call's
3384 : /// `Barrier` as an `Err`. This not-first caller can use the returned barrier to join with
3385 : /// the ongoing shutdown.
3386 12 : async fn shutdown(
3387 12 : &self,
3388 12 : shutdown_progress: completion::Barrier,
3389 12 : shutdown_mode: timeline::ShutdownMode,
3390 12 : ) -> Result<(), completion::Barrier> {
3391 12 : span::debug_assert_current_span_has_tenant_id();
3392 :
3393 : // Set tenant (and its timlines) to Stoppping state.
3394 : //
3395 : // Since we can only transition into Stopping state after activation is complete,
3396 : // run it in a JoinSet so all tenants have a chance to stop before we get SIGKILLed.
3397 : //
3398 : // Transitioning tenants to Stopping state has a couple of non-obvious side effects:
3399 : // 1. Lock out any new requests to the tenants.
3400 : // 2. Signal cancellation to WAL receivers (we wait on it below).
3401 : // 3. Signal cancellation for other tenant background loops.
3402 : // 4. ???
3403 : //
3404 : // The waiting for the cancellation is not done uniformly.
3405 : // We certainly wait for WAL receivers to shut down.
3406 : // That is necessary so that no new data comes in before the freeze_and_flush.
3407 : // But the tenant background loops are joined-on in our caller.
3408 : // It's mesed up.
3409 : // we just ignore the failure to stop
3410 :
3411 : // If we're still attaching, fire the cancellation token early to drop out: this
3412 : // will prevent us flushing, but ensures timely shutdown if some I/O during attach
3413 : // is very slow.
3414 12 : let shutdown_mode = if matches!(self.current_state(), TenantState::Attaching) {
3415 0 : self.cancel.cancel();
3416 0 :
3417 0 : // Having fired our cancellation token, do not try and flush timelines: their cancellation tokens
3418 0 : // are children of ours, so their flush loops will have shut down already
3419 0 : timeline::ShutdownMode::Hard
3420 : } else {
3421 12 : shutdown_mode
3422 : };
3423 :
3424 12 : match self.set_stopping(shutdown_progress, false, false).await {
3425 12 : Ok(()) => {}
3426 0 : Err(SetStoppingError::Broken) => {
3427 0 : // assume that this is acceptable
3428 0 : }
3429 0 : Err(SetStoppingError::AlreadyStopping(other)) => {
3430 0 : // give caller the option to wait for this this shutdown
3431 0 : info!("Tenant::shutdown: AlreadyStopping");
3432 0 : return Err(other);
3433 : }
3434 : };
3435 :
3436 12 : let mut js = tokio::task::JoinSet::new();
3437 12 : {
3438 12 : let timelines = self.timelines.lock().unwrap();
3439 12 : timelines.values().for_each(|timeline| {
3440 12 : let timeline = Arc::clone(timeline);
3441 12 : let timeline_id = timeline.timeline_id;
3442 12 : let span = tracing::info_span!("timeline_shutdown", %timeline_id, ?shutdown_mode);
3443 12 : js.spawn(async move { timeline.shutdown(shutdown_mode).instrument(span).await });
3444 12 : });
3445 12 : }
3446 12 : {
3447 12 : let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
3448 12 : timelines_offloaded.values().for_each(|timeline| {
3449 0 : timeline.defuse_for_tenant_drop();
3450 12 : });
3451 12 : }
3452 12 : // test_long_timeline_create_then_tenant_delete is leaning on this message
3453 12 : tracing::info!("Waiting for timelines...");
3454 24 : while let Some(res) = js.join_next().await {
3455 0 : match res {
3456 12 : Ok(()) => {}
3457 0 : Err(je) if je.is_cancelled() => unreachable!("no cancelling used"),
3458 0 : Err(je) if je.is_panic() => { /* logged already */ }
3459 0 : Err(je) => warn!("unexpected JoinError: {je:?}"),
3460 : }
3461 : }
3462 :
3463 12 : if let ShutdownMode::Reload = shutdown_mode {
3464 0 : tracing::info!("Flushing deletion queue");
3465 0 : if let Err(e) = self.deletion_queue_client.flush().await {
3466 0 : match e {
3467 0 : DeletionQueueError::ShuttingDown => {
3468 0 : // This is the only error we expect for now. In the future, if more error
3469 0 : // variants are added, we should handle them here.
3470 0 : }
3471 : }
3472 0 : }
3473 12 : }
3474 :
3475 : // We cancel the Tenant's cancellation token _after_ the timelines have all shut down. This permits
3476 : // them to continue to do work during their shutdown methods, e.g. flushing data.
3477 12 : tracing::debug!("Cancelling CancellationToken");
3478 12 : self.cancel.cancel();
3479 12 :
3480 12 : // shutdown all tenant and timeline tasks: gc, compaction, page service
3481 12 : // No new tasks will be started for this tenant because it's in `Stopping` state.
3482 12 : //
3483 12 : // this will additionally shutdown and await all timeline tasks.
3484 12 : tracing::debug!("Waiting for tasks...");
3485 12 : task_mgr::shutdown_tasks(None, Some(self.tenant_shard_id), None).await;
3486 :
3487 12 : if let Some(walredo_mgr) = self.walredo_mgr.as_ref() {
3488 12 : walredo_mgr.shutdown().await;
3489 0 : }
3490 :
3491 : // Wait for any in-flight operations to complete
3492 12 : self.gate.close().await;
3493 :
3494 12 : remove_tenant_metrics(&self.tenant_shard_id);
3495 12 :
3496 12 : Ok(())
3497 12 : }
3498 :
3499 : /// Change tenant status to Stopping, to mark that it is being shut down.
3500 : ///
3501 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
3502 : ///
3503 : /// This function is not cancel-safe!
3504 : ///
3505 : /// `allow_transition_from_loading` is needed for the special case of loading task deleting the tenant.
3506 : /// `allow_transition_from_attaching` is needed for the special case of attaching deleted tenant.
3507 12 : async fn set_stopping(
3508 12 : &self,
3509 12 : progress: completion::Barrier,
3510 12 : _allow_transition_from_loading: bool,
3511 12 : allow_transition_from_attaching: bool,
3512 12 : ) -> Result<(), SetStoppingError> {
3513 12 : let mut rx = self.state.subscribe();
3514 12 :
3515 12 : // cannot stop before we're done activating, so wait out until we're done activating
3516 12 : rx.wait_for(|state| match state {
3517 0 : TenantState::Attaching if allow_transition_from_attaching => true,
3518 : TenantState::Activating(_) | TenantState::Attaching => {
3519 0 : info!(
3520 0 : "waiting for {} to turn Active|Broken|Stopping",
3521 0 : <&'static str>::from(state)
3522 : );
3523 0 : false
3524 : }
3525 12 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
3526 12 : })
3527 12 : .await
3528 12 : .expect("cannot drop self.state while on a &self method");
3529 12 :
3530 12 : // we now know we're done activating, let's see whether this task is the winner to transition into Stopping
3531 12 : let mut err = None;
3532 12 : let stopping = self.state.send_if_modified(|current_state| match current_state {
3533 : TenantState::Activating(_) => {
3534 0 : unreachable!("1we ensured above that we're done with activation, and, there is no re-activation")
3535 : }
3536 : TenantState::Attaching => {
3537 0 : if !allow_transition_from_attaching {
3538 0 : unreachable!("2we ensured above that we're done with activation, and, there is no re-activation")
3539 0 : };
3540 0 : *current_state = TenantState::Stopping { progress };
3541 0 : true
3542 : }
3543 : TenantState::Active => {
3544 : // FIXME: due to time-of-check vs time-of-use issues, it can happen that new timelines
3545 : // are created after the transition to Stopping. That's harmless, as the Timelines
3546 : // won't be accessible to anyone afterwards, because the Tenant is in Stopping state.
3547 12 : *current_state = TenantState::Stopping { progress };
3548 12 : // Continue stopping outside the closure. We need to grab timelines.lock()
3549 12 : // and we plan to turn it into a tokio::sync::Mutex in a future patch.
3550 12 : true
3551 : }
3552 0 : TenantState::Broken { reason, .. } => {
3553 0 : info!(
3554 0 : "Cannot set tenant to Stopping state, it is in Broken state due to: {reason}"
3555 : );
3556 0 : err = Some(SetStoppingError::Broken);
3557 0 : false
3558 : }
3559 0 : TenantState::Stopping { progress } => {
3560 0 : info!("Tenant is already in Stopping state");
3561 0 : err = Some(SetStoppingError::AlreadyStopping(progress.clone()));
3562 0 : false
3563 : }
3564 12 : });
3565 12 : match (stopping, err) {
3566 12 : (true, None) => {} // continue
3567 0 : (false, Some(err)) => return Err(err),
3568 0 : (true, Some(_)) => unreachable!(
3569 0 : "send_if_modified closure must error out if not transitioning to Stopping"
3570 0 : ),
3571 0 : (false, None) => unreachable!(
3572 0 : "send_if_modified closure must return true if transitioning to Stopping"
3573 0 : ),
3574 : }
3575 :
3576 12 : let timelines_accessor = self.timelines.lock().unwrap();
3577 12 : let not_broken_timelines = timelines_accessor
3578 12 : .values()
3579 12 : .filter(|timeline| !timeline.is_broken());
3580 24 : for timeline in not_broken_timelines {
3581 12 : timeline.set_state(TimelineState::Stopping);
3582 12 : }
3583 12 : Ok(())
3584 12 : }
3585 :
3586 : /// Method for tenant::mgr to transition us into Broken state in case of a late failure in
3587 : /// `remove_tenant_from_memory`
3588 : ///
3589 : /// This function waits for the tenant to become active if it isn't already, before transitioning it into Stopping state.
3590 : ///
3591 : /// In tests, we also use this to set tenants to Broken state on purpose.
3592 0 : pub(crate) async fn set_broken(&self, reason: String) {
3593 0 : let mut rx = self.state.subscribe();
3594 0 :
3595 0 : // The load & attach routines own the tenant state until it has reached `Active`.
3596 0 : // So, wait until it's done.
3597 0 : rx.wait_for(|state| match state {
3598 : TenantState::Activating(_) | TenantState::Attaching => {
3599 0 : info!(
3600 0 : "waiting for {} to turn Active|Broken|Stopping",
3601 0 : <&'static str>::from(state)
3602 : );
3603 0 : false
3604 : }
3605 0 : TenantState::Active | TenantState::Broken { .. } | TenantState::Stopping { .. } => true,
3606 0 : })
3607 0 : .await
3608 0 : .expect("cannot drop self.state while on a &self method");
3609 0 :
3610 0 : // we now know we're done activating, let's see whether this task is the winner to transition into Broken
3611 0 : self.set_broken_no_wait(reason)
3612 0 : }
3613 :
3614 0 : pub(crate) fn set_broken_no_wait(&self, reason: impl Display) {
3615 0 : let reason = reason.to_string();
3616 0 : self.state.send_modify(|current_state| {
3617 0 : match *current_state {
3618 : TenantState::Activating(_) | TenantState::Attaching => {
3619 0 : unreachable!("we ensured above that we're done with activation, and, there is no re-activation")
3620 : }
3621 : TenantState::Active => {
3622 0 : if cfg!(feature = "testing") {
3623 0 : warn!("Changing Active tenant to Broken state, reason: {}", reason);
3624 0 : *current_state = TenantState::broken_from_reason(reason);
3625 : } else {
3626 0 : unreachable!("not allowed to call set_broken on Active tenants in non-testing builds")
3627 : }
3628 : }
3629 : TenantState::Broken { .. } => {
3630 0 : warn!("Tenant is already in Broken state");
3631 : }
3632 : // This is the only "expected" path, any other path is a bug.
3633 : TenantState::Stopping { .. } => {
3634 0 : warn!(
3635 0 : "Marking Stopping tenant as Broken state, reason: {}",
3636 : reason
3637 : );
3638 0 : *current_state = TenantState::broken_from_reason(reason);
3639 : }
3640 : }
3641 0 : });
3642 0 : }
3643 :
3644 0 : pub fn subscribe_for_state_updates(&self) -> watch::Receiver<TenantState> {
3645 0 : self.state.subscribe()
3646 0 : }
3647 :
3648 : /// The activate_now semaphore is initialized with zero units. As soon as
3649 : /// we add a unit, waiters will be able to acquire a unit and proceed.
3650 0 : pub(crate) fn activate_now(&self) {
3651 0 : self.activate_now_sem.add_permits(1);
3652 0 : }
3653 :
3654 0 : pub(crate) async fn wait_to_become_active(
3655 0 : &self,
3656 0 : timeout: Duration,
3657 0 : ) -> Result<(), GetActiveTenantError> {
3658 0 : let mut receiver = self.state.subscribe();
3659 : loop {
3660 0 : let current_state = receiver.borrow_and_update().clone();
3661 0 : match current_state {
3662 : TenantState::Attaching | TenantState::Activating(_) => {
3663 : // in these states, there's a chance that we can reach ::Active
3664 0 : self.activate_now();
3665 0 : match timeout_cancellable(timeout, &self.cancel, receiver.changed()).await {
3666 0 : Ok(r) => {
3667 0 : r.map_err(
3668 0 : |_e: tokio::sync::watch::error::RecvError|
3669 : // Tenant existed but was dropped: report it as non-existent
3670 0 : GetActiveTenantError::NotFound(GetTenantError::ShardNotFound(self.tenant_shard_id))
3671 0 : )?
3672 : }
3673 : Err(TimeoutCancellableError::Cancelled) => {
3674 0 : return Err(GetActiveTenantError::Cancelled);
3675 : }
3676 : Err(TimeoutCancellableError::Timeout) => {
3677 0 : return Err(GetActiveTenantError::WaitForActiveTimeout {
3678 0 : latest_state: Some(self.current_state()),
3679 0 : wait_time: timeout,
3680 0 : });
3681 : }
3682 : }
3683 : }
3684 : TenantState::Active { .. } => {
3685 0 : return Ok(());
3686 : }
3687 0 : TenantState::Broken { reason, .. } => {
3688 0 : // This is fatal, and reported distinctly from the general case of "will never be active" because
3689 0 : // it's logically a 500 to external API users (broken is always a bug).
3690 0 : return Err(GetActiveTenantError::Broken(reason));
3691 : }
3692 : TenantState::Stopping { .. } => {
3693 : // There's no chance the tenant can transition back into ::Active
3694 0 : return Err(GetActiveTenantError::WillNotBecomeActive(current_state));
3695 : }
3696 : }
3697 : }
3698 0 : }
3699 :
3700 0 : pub(crate) fn get_attach_mode(&self) -> AttachmentMode {
3701 0 : self.tenant_conf.load().location.attach_mode
3702 0 : }
3703 :
3704 : /// For API access: generate a LocationConfig equivalent to the one that would be used to
3705 : /// create a Tenant in the same state. Do not use this in hot paths: it's for relatively
3706 : /// rare external API calls, like a reconciliation at startup.
3707 0 : pub(crate) fn get_location_conf(&self) -> models::LocationConfig {
3708 0 : let attached_tenant_conf = self.tenant_conf.load();
3709 :
3710 0 : let location_config_mode = match attached_tenant_conf.location.attach_mode {
3711 0 : AttachmentMode::Single => models::LocationConfigMode::AttachedSingle,
3712 0 : AttachmentMode::Multi => models::LocationConfigMode::AttachedMulti,
3713 0 : AttachmentMode::Stale => models::LocationConfigMode::AttachedStale,
3714 : };
3715 :
3716 0 : models::LocationConfig {
3717 0 : mode: location_config_mode,
3718 0 : generation: self.generation.into(),
3719 0 : secondary_conf: None,
3720 0 : shard_number: self.shard_identity.number.0,
3721 0 : shard_count: self.shard_identity.count.literal(),
3722 0 : shard_stripe_size: self.shard_identity.stripe_size.0,
3723 0 : tenant_conf: attached_tenant_conf.tenant_conf.clone(),
3724 0 : }
3725 0 : }
3726 :
3727 0 : pub(crate) fn get_tenant_shard_id(&self) -> &TenantShardId {
3728 0 : &self.tenant_shard_id
3729 0 : }
3730 :
3731 0 : pub(crate) fn get_shard_stripe_size(&self) -> ShardStripeSize {
3732 0 : self.shard_identity.stripe_size
3733 0 : }
3734 :
3735 0 : pub(crate) fn get_generation(&self) -> Generation {
3736 0 : self.generation
3737 0 : }
3738 :
3739 : /// This function partially shuts down the tenant (it shuts down the Timelines) and is fallible,
3740 : /// and can leave the tenant in a bad state if it fails. The caller is responsible for
3741 : /// resetting this tenant to a valid state if we fail.
3742 0 : pub(crate) async fn split_prepare(
3743 0 : &self,
3744 0 : child_shards: &Vec<TenantShardId>,
3745 0 : ) -> anyhow::Result<()> {
3746 0 : let (timelines, offloaded) = {
3747 0 : let timelines = self.timelines.lock().unwrap();
3748 0 : let offloaded = self.timelines_offloaded.lock().unwrap();
3749 0 : (timelines.clone(), offloaded.clone())
3750 0 : };
3751 0 : let timelines_iter = timelines
3752 0 : .values()
3753 0 : .map(TimelineOrOffloadedArcRef::<'_>::from)
3754 0 : .chain(
3755 0 : offloaded
3756 0 : .values()
3757 0 : .map(TimelineOrOffloadedArcRef::<'_>::from),
3758 0 : );
3759 0 : for timeline in timelines_iter {
3760 : // We do not block timeline creation/deletion during splits inside the pageserver: it is up to higher levels
3761 : // to ensure that they do not start a split if currently in the process of doing these.
3762 :
3763 0 : let timeline_id = timeline.timeline_id();
3764 :
3765 0 : if let TimelineOrOffloadedArcRef::Timeline(timeline) = timeline {
3766 : // Upload an index from the parent: this is partly to provide freshness for the
3767 : // child tenants that will copy it, and partly for general ease-of-debugging: there will
3768 : // always be a parent shard index in the same generation as we wrote the child shard index.
3769 0 : tracing::info!(%timeline_id, "Uploading index");
3770 0 : timeline
3771 0 : .remote_client
3772 0 : .schedule_index_upload_for_file_changes()?;
3773 0 : timeline.remote_client.wait_completion().await?;
3774 0 : }
3775 :
3776 0 : let remote_client = match timeline {
3777 0 : TimelineOrOffloadedArcRef::Timeline(timeline) => timeline.remote_client.clone(),
3778 0 : TimelineOrOffloadedArcRef::Offloaded(offloaded) => {
3779 0 : let remote_client = self
3780 0 : .build_timeline_client(offloaded.timeline_id, self.remote_storage.clone());
3781 0 : Arc::new(remote_client)
3782 : }
3783 : };
3784 :
3785 : // Shut down the timeline's remote client: this means that the indices we write
3786 : // for child shards will not be invalidated by the parent shard deleting layers.
3787 0 : tracing::info!(%timeline_id, "Shutting down remote storage client");
3788 0 : remote_client.shutdown().await;
3789 :
3790 : // Download methods can still be used after shutdown, as they don't flow through the remote client's
3791 : // queue. In principal the RemoteTimelineClient could provide this without downloading it, but this
3792 : // operation is rare, so it's simpler to just download it (and robustly guarantees that the index
3793 : // we use here really is the remotely persistent one).
3794 0 : tracing::info!(%timeline_id, "Downloading index_part from parent");
3795 0 : let result = remote_client
3796 0 : .download_index_file(&self.cancel)
3797 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))
3798 0 : .await?;
3799 0 : let index_part = match result {
3800 : MaybeDeletedIndexPart::Deleted(_) => {
3801 0 : anyhow::bail!("Timeline deletion happened concurrently with split")
3802 : }
3803 0 : MaybeDeletedIndexPart::IndexPart(p) => p,
3804 : };
3805 :
3806 0 : for child_shard in child_shards {
3807 0 : tracing::info!(%timeline_id, "Uploading index_part for child {}", child_shard.to_index());
3808 0 : upload_index_part(
3809 0 : &self.remote_storage,
3810 0 : child_shard,
3811 0 : &timeline_id,
3812 0 : self.generation,
3813 0 : &index_part,
3814 0 : &self.cancel,
3815 0 : )
3816 0 : .await?;
3817 : }
3818 : }
3819 :
3820 0 : let tenant_manifest = self.build_tenant_manifest();
3821 0 : for child_shard in child_shards {
3822 0 : tracing::info!(
3823 0 : "Uploading tenant manifest for child {}",
3824 0 : child_shard.to_index()
3825 : );
3826 0 : upload_tenant_manifest(
3827 0 : &self.remote_storage,
3828 0 : child_shard,
3829 0 : self.generation,
3830 0 : &tenant_manifest,
3831 0 : &self.cancel,
3832 0 : )
3833 0 : .await?;
3834 : }
3835 :
3836 0 : Ok(())
3837 0 : }
3838 :
3839 0 : pub(crate) fn get_sizes(&self) -> TopTenantShardItem {
3840 0 : let mut result = TopTenantShardItem {
3841 0 : id: self.tenant_shard_id,
3842 0 : resident_size: 0,
3843 0 : physical_size: 0,
3844 0 : max_logical_size: 0,
3845 0 : max_logical_size_per_shard: 0,
3846 0 : };
3847 :
3848 0 : for timeline in self.timelines.lock().unwrap().values() {
3849 0 : result.resident_size += timeline.metrics.resident_physical_size_gauge.get();
3850 0 :
3851 0 : result.physical_size += timeline
3852 0 : .remote_client
3853 0 : .metrics
3854 0 : .remote_physical_size_gauge
3855 0 : .get();
3856 0 : result.max_logical_size = std::cmp::max(
3857 0 : result.max_logical_size,
3858 0 : timeline.metrics.current_logical_size_gauge.get(),
3859 0 : );
3860 0 : }
3861 :
3862 0 : result.max_logical_size_per_shard = result
3863 0 : .max_logical_size
3864 0 : .div_ceil(self.tenant_shard_id.shard_count.count() as u64);
3865 0 :
3866 0 : result
3867 0 : }
3868 : }
3869 :
3870 : /// Given a Vec of timelines and their ancestors (timeline_id, ancestor_id),
3871 : /// perform a topological sort, so that the parent of each timeline comes
3872 : /// before the children.
3873 : /// E extracts the ancestor from T
3874 : /// This allows for T to be different. It can be TimelineMetadata, can be Timeline itself, etc.
3875 452 : fn tree_sort_timelines<T, E>(
3876 452 : timelines: HashMap<TimelineId, T>,
3877 452 : extractor: E,
3878 452 : ) -> anyhow::Result<Vec<(TimelineId, T)>>
3879 452 : where
3880 452 : E: Fn(&T) -> Option<TimelineId>,
3881 452 : {
3882 452 : let mut result = Vec::with_capacity(timelines.len());
3883 452 :
3884 452 : let mut now = Vec::with_capacity(timelines.len());
3885 452 : // (ancestor, children)
3886 452 : let mut later: HashMap<TimelineId, Vec<(TimelineId, T)>> =
3887 452 : HashMap::with_capacity(timelines.len());
3888 :
3889 464 : for (timeline_id, value) in timelines {
3890 12 : if let Some(ancestor_id) = extractor(&value) {
3891 4 : let children = later.entry(ancestor_id).or_default();
3892 4 : children.push((timeline_id, value));
3893 8 : } else {
3894 8 : now.push((timeline_id, value));
3895 8 : }
3896 : }
3897 :
3898 464 : while let Some((timeline_id, metadata)) = now.pop() {
3899 12 : result.push((timeline_id, metadata));
3900 : // All children of this can be loaded now
3901 12 : if let Some(mut children) = later.remove(&timeline_id) {
3902 4 : now.append(&mut children);
3903 8 : }
3904 : }
3905 :
3906 : // All timelines should be visited now. Unless there were timelines with missing ancestors.
3907 452 : if !later.is_empty() {
3908 0 : for (missing_id, orphan_ids) in later {
3909 0 : for (orphan_id, _) in orphan_ids {
3910 0 : error!(
3911 0 : "could not load timeline {orphan_id} because its ancestor timeline {missing_id} could not be loaded"
3912 : );
3913 : }
3914 : }
3915 0 : bail!("could not load tenant because some timelines are missing ancestors");
3916 452 : }
3917 452 :
3918 452 : Ok(result)
3919 452 : }
3920 :
3921 : enum ActivateTimelineArgs {
3922 : Yes {
3923 : broker_client: storage_broker::BrokerClientChannel,
3924 : },
3925 : No,
3926 : }
3927 :
3928 : impl Tenant {
3929 0 : pub fn tenant_specific_overrides(&self) -> pageserver_api::models::TenantConfig {
3930 0 : self.tenant_conf.load().tenant_conf.clone()
3931 0 : }
3932 :
3933 0 : pub fn effective_config(&self) -> pageserver_api::config::TenantConfigToml {
3934 0 : self.tenant_specific_overrides()
3935 0 : .merge(self.conf.default_tenant_conf.clone())
3936 0 : }
3937 :
3938 0 : pub fn get_checkpoint_distance(&self) -> u64 {
3939 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3940 0 : tenant_conf
3941 0 : .checkpoint_distance
3942 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_distance)
3943 0 : }
3944 :
3945 0 : pub fn get_checkpoint_timeout(&self) -> Duration {
3946 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3947 0 : tenant_conf
3948 0 : .checkpoint_timeout
3949 0 : .unwrap_or(self.conf.default_tenant_conf.checkpoint_timeout)
3950 0 : }
3951 :
3952 0 : pub fn get_compaction_target_size(&self) -> u64 {
3953 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3954 0 : tenant_conf
3955 0 : .compaction_target_size
3956 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_target_size)
3957 0 : }
3958 :
3959 0 : pub fn get_compaction_period(&self) -> Duration {
3960 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3961 0 : tenant_conf
3962 0 : .compaction_period
3963 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_period)
3964 0 : }
3965 :
3966 0 : pub fn get_compaction_threshold(&self) -> usize {
3967 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3968 0 : tenant_conf
3969 0 : .compaction_threshold
3970 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_threshold)
3971 0 : }
3972 :
3973 0 : pub fn get_rel_size_v2_enabled(&self) -> bool {
3974 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3975 0 : tenant_conf
3976 0 : .rel_size_v2_enabled
3977 0 : .unwrap_or(self.conf.default_tenant_conf.rel_size_v2_enabled)
3978 0 : }
3979 :
3980 0 : pub fn get_compaction_upper_limit(&self) -> usize {
3981 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3982 0 : tenant_conf
3983 0 : .compaction_upper_limit
3984 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_upper_limit)
3985 0 : }
3986 :
3987 0 : pub fn get_compaction_l0_first(&self) -> bool {
3988 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3989 0 : tenant_conf
3990 0 : .compaction_l0_first
3991 0 : .unwrap_or(self.conf.default_tenant_conf.compaction_l0_first)
3992 0 : }
3993 :
3994 0 : pub fn get_gc_horizon(&self) -> u64 {
3995 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
3996 0 : tenant_conf
3997 0 : .gc_horizon
3998 0 : .unwrap_or(self.conf.default_tenant_conf.gc_horizon)
3999 0 : }
4000 :
4001 0 : pub fn get_gc_period(&self) -> Duration {
4002 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4003 0 : tenant_conf
4004 0 : .gc_period
4005 0 : .unwrap_or(self.conf.default_tenant_conf.gc_period)
4006 0 : }
4007 :
4008 0 : pub fn get_image_creation_threshold(&self) -> usize {
4009 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4010 0 : tenant_conf
4011 0 : .image_creation_threshold
4012 0 : .unwrap_or(self.conf.default_tenant_conf.image_creation_threshold)
4013 0 : }
4014 :
4015 0 : pub fn get_pitr_interval(&self) -> Duration {
4016 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4017 0 : tenant_conf
4018 0 : .pitr_interval
4019 0 : .unwrap_or(self.conf.default_tenant_conf.pitr_interval)
4020 0 : }
4021 :
4022 0 : pub fn get_min_resident_size_override(&self) -> Option<u64> {
4023 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4024 0 : tenant_conf
4025 0 : .min_resident_size_override
4026 0 : .or(self.conf.default_tenant_conf.min_resident_size_override)
4027 0 : }
4028 :
4029 0 : pub fn get_heatmap_period(&self) -> Option<Duration> {
4030 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4031 0 : let heatmap_period = tenant_conf
4032 0 : .heatmap_period
4033 0 : .unwrap_or(self.conf.default_tenant_conf.heatmap_period);
4034 0 : if heatmap_period.is_zero() {
4035 0 : None
4036 : } else {
4037 0 : Some(heatmap_period)
4038 : }
4039 0 : }
4040 :
4041 8 : pub fn get_lsn_lease_length(&self) -> Duration {
4042 8 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4043 8 : tenant_conf
4044 8 : .lsn_lease_length
4045 8 : .unwrap_or(self.conf.default_tenant_conf.lsn_lease_length)
4046 8 : }
4047 :
4048 0 : pub fn get_timeline_offloading_enabled(&self) -> bool {
4049 0 : if self.conf.timeline_offloading {
4050 0 : return true;
4051 0 : }
4052 0 : let tenant_conf = self.tenant_conf.load().tenant_conf.clone();
4053 0 : tenant_conf
4054 0 : .timeline_offloading
4055 0 : .unwrap_or(self.conf.default_tenant_conf.timeline_offloading)
4056 0 : }
4057 :
4058 : /// Generate an up-to-date TenantManifest based on the state of this Tenant.
4059 4 : fn build_tenant_manifest(&self) -> TenantManifest {
4060 4 : let timelines_offloaded = self.timelines_offloaded.lock().unwrap();
4061 4 :
4062 4 : let mut timeline_manifests = timelines_offloaded
4063 4 : .iter()
4064 4 : .map(|(_timeline_id, offloaded)| offloaded.manifest())
4065 4 : .collect::<Vec<_>>();
4066 4 : // Sort the manifests so that our output is deterministic
4067 4 : timeline_manifests.sort_by_key(|timeline_manifest| timeline_manifest.timeline_id);
4068 4 :
4069 4 : TenantManifest {
4070 4 : version: LATEST_TENANT_MANIFEST_VERSION,
4071 4 : offloaded_timelines: timeline_manifests,
4072 4 : }
4073 4 : }
4074 :
4075 0 : pub fn update_tenant_config<
4076 0 : F: Fn(
4077 0 : pageserver_api::models::TenantConfig,
4078 0 : ) -> anyhow::Result<pageserver_api::models::TenantConfig>,
4079 0 : >(
4080 0 : &self,
4081 0 : update: F,
4082 0 : ) -> anyhow::Result<pageserver_api::models::TenantConfig> {
4083 0 : // Use read-copy-update in order to avoid overwriting the location config
4084 0 : // state if this races with [`Tenant::set_new_location_config`]. Note that
4085 0 : // this race is not possible if both request types come from the storage
4086 0 : // controller (as they should!) because an exclusive op lock is required
4087 0 : // on the storage controller side.
4088 0 :
4089 0 : self.tenant_conf
4090 0 : .try_rcu(|attached_conf| -> Result<_, anyhow::Error> {
4091 0 : Ok(Arc::new(AttachedTenantConf {
4092 0 : tenant_conf: update(attached_conf.tenant_conf.clone())?,
4093 0 : location: attached_conf.location,
4094 0 : lsn_lease_deadline: attached_conf.lsn_lease_deadline,
4095 : }))
4096 0 : })?;
4097 :
4098 0 : let updated = self.tenant_conf.load();
4099 0 :
4100 0 : self.tenant_conf_updated(&updated.tenant_conf);
4101 0 : // Don't hold self.timelines.lock() during the notifies.
4102 0 : // There's no risk of deadlock right now, but there could be if we consolidate
4103 0 : // mutexes in struct Timeline in the future.
4104 0 : let timelines = self.list_timelines();
4105 0 : for timeline in timelines {
4106 0 : timeline.tenant_conf_updated(&updated);
4107 0 : }
4108 :
4109 0 : Ok(updated.tenant_conf.clone())
4110 0 : }
4111 :
4112 0 : pub(crate) fn set_new_location_config(&self, new_conf: AttachedTenantConf) {
4113 0 : let new_tenant_conf = new_conf.tenant_conf.clone();
4114 0 :
4115 0 : self.tenant_conf.store(Arc::new(new_conf.clone()));
4116 0 :
4117 0 : self.tenant_conf_updated(&new_tenant_conf);
4118 0 : // Don't hold self.timelines.lock() during the notifies.
4119 0 : // There's no risk of deadlock right now, but there could be if we consolidate
4120 0 : // mutexes in struct Timeline in the future.
4121 0 : let timelines = self.list_timelines();
4122 0 : for timeline in timelines {
4123 0 : timeline.tenant_conf_updated(&new_conf);
4124 0 : }
4125 0 : }
4126 :
4127 452 : fn get_pagestream_throttle_config(
4128 452 : psconf: &'static PageServerConf,
4129 452 : overrides: &pageserver_api::models::TenantConfig,
4130 452 : ) -> throttle::Config {
4131 452 : overrides
4132 452 : .timeline_get_throttle
4133 452 : .clone()
4134 452 : .unwrap_or(psconf.default_tenant_conf.timeline_get_throttle.clone())
4135 452 : }
4136 :
4137 0 : pub(crate) fn tenant_conf_updated(&self, new_conf: &pageserver_api::models::TenantConfig) {
4138 0 : let conf = Self::get_pagestream_throttle_config(self.conf, new_conf);
4139 0 : self.pagestream_throttle.reconfigure(conf)
4140 0 : }
4141 :
4142 : /// Helper function to create a new Timeline struct.
4143 : ///
4144 : /// The returned Timeline is in Loading state. The caller is responsible for
4145 : /// initializing any on-disk state, and for inserting the Timeline to the 'timelines'
4146 : /// map.
4147 : ///
4148 : /// `validate_ancestor == false` is used when a timeline is created for deletion
4149 : /// and we might not have the ancestor present anymore which is fine for to be
4150 : /// deleted timelines.
4151 : #[allow(clippy::too_many_arguments)]
4152 904 : fn create_timeline_struct(
4153 904 : &self,
4154 904 : new_timeline_id: TimelineId,
4155 904 : new_metadata: &TimelineMetadata,
4156 904 : previous_heatmap: Option<PreviousHeatmap>,
4157 904 : ancestor: Option<Arc<Timeline>>,
4158 904 : resources: TimelineResources,
4159 904 : cause: CreateTimelineCause,
4160 904 : create_idempotency: CreateTimelineIdempotency,
4161 904 : gc_compaction_state: Option<GcCompactionState>,
4162 904 : rel_size_v2_status: Option<RelSizeMigration>,
4163 904 : ctx: &RequestContext,
4164 904 : ) -> anyhow::Result<(Arc<Timeline>, RequestContext)> {
4165 904 : let state = match cause {
4166 : CreateTimelineCause::Load => {
4167 904 : let ancestor_id = new_metadata.ancestor_timeline();
4168 904 : anyhow::ensure!(
4169 904 : ancestor_id == ancestor.as_ref().map(|t| t.timeline_id),
4170 0 : "Timeline's {new_timeline_id} ancestor {ancestor_id:?} was not found"
4171 : );
4172 904 : TimelineState::Loading
4173 : }
4174 0 : CreateTimelineCause::Delete => TimelineState::Stopping,
4175 : };
4176 :
4177 904 : let pg_version = new_metadata.pg_version();
4178 904 :
4179 904 : let timeline = Timeline::new(
4180 904 : self.conf,
4181 904 : Arc::clone(&self.tenant_conf),
4182 904 : new_metadata,
4183 904 : previous_heatmap,
4184 904 : ancestor,
4185 904 : new_timeline_id,
4186 904 : self.tenant_shard_id,
4187 904 : self.generation,
4188 904 : self.shard_identity,
4189 904 : self.walredo_mgr.clone(),
4190 904 : resources,
4191 904 : pg_version,
4192 904 : state,
4193 904 : self.attach_wal_lag_cooldown.clone(),
4194 904 : create_idempotency,
4195 904 : gc_compaction_state,
4196 904 : rel_size_v2_status,
4197 904 : self.cancel.child_token(),
4198 904 : );
4199 904 :
4200 904 : let timeline_ctx = RequestContextBuilder::extend(ctx)
4201 904 : .scope(context::Scope::new_timeline(&timeline))
4202 904 : .build();
4203 904 :
4204 904 : Ok((timeline, timeline_ctx))
4205 904 : }
4206 :
4207 : /// [`Tenant::shutdown`] must be called before dropping the returned [`Tenant`] object
4208 : /// to ensure proper cleanup of background tasks and metrics.
4209 : //
4210 : // Allow too_many_arguments because a constructor's argument list naturally grows with the
4211 : // number of attributes in the struct: breaking these out into a builder wouldn't be helpful.
4212 : #[allow(clippy::too_many_arguments)]
4213 452 : fn new(
4214 452 : state: TenantState,
4215 452 : conf: &'static PageServerConf,
4216 452 : attached_conf: AttachedTenantConf,
4217 452 : shard_identity: ShardIdentity,
4218 452 : walredo_mgr: Option<Arc<WalRedoManager>>,
4219 452 : tenant_shard_id: TenantShardId,
4220 452 : remote_storage: GenericRemoteStorage,
4221 452 : deletion_queue_client: DeletionQueueClient,
4222 452 : l0_flush_global_state: L0FlushGlobalState,
4223 452 : ) -> Tenant {
4224 452 : debug_assert!(
4225 452 : !attached_conf.location.generation.is_none() || conf.control_plane_api.is_none()
4226 : );
4227 :
4228 452 : let (state, mut rx) = watch::channel(state);
4229 452 :
4230 452 : tokio::spawn(async move {
4231 452 : // reflect tenant state in metrics:
4232 452 : // - global per tenant state: TENANT_STATE_METRIC
4233 452 : // - "set" of broken tenants: BROKEN_TENANTS_SET
4234 452 : //
4235 452 : // set of broken tenants should not have zero counts so that it remains accessible for
4236 452 : // alerting.
4237 452 :
4238 452 : let tid = tenant_shard_id.to_string();
4239 452 : let shard_id = tenant_shard_id.shard_slug().to_string();
4240 452 : let set_key = &[tid.as_str(), shard_id.as_str()][..];
4241 :
4242 904 : fn inspect_state(state: &TenantState) -> ([&'static str; 1], bool) {
4243 904 : ([state.into()], matches!(state, TenantState::Broken { .. }))
4244 904 : }
4245 :
4246 452 : let mut tuple = inspect_state(&rx.borrow_and_update());
4247 452 :
4248 452 : let is_broken = tuple.1;
4249 452 : let mut counted_broken = if is_broken {
4250 : // add the id to the set right away, there should not be any updates on the channel
4251 : // after before tenant is removed, if ever
4252 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
4253 0 : true
4254 : } else {
4255 452 : false
4256 : };
4257 :
4258 : loop {
4259 904 : let labels = &tuple.0;
4260 904 : let current = TENANT_STATE_METRIC.with_label_values(labels);
4261 904 : current.inc();
4262 904 :
4263 904 : if rx.changed().await.is_err() {
4264 : // tenant has been dropped
4265 28 : current.dec();
4266 28 : drop(BROKEN_TENANTS_SET.remove_label_values(set_key));
4267 28 : break;
4268 452 : }
4269 452 :
4270 452 : current.dec();
4271 452 : tuple = inspect_state(&rx.borrow_and_update());
4272 452 :
4273 452 : let is_broken = tuple.1;
4274 452 : if is_broken && !counted_broken {
4275 0 : counted_broken = true;
4276 0 : // insert the tenant_id (back) into the set while avoiding needless counter
4277 0 : // access
4278 0 : BROKEN_TENANTS_SET.with_label_values(set_key).set(1);
4279 452 : }
4280 : }
4281 452 : });
4282 452 :
4283 452 : Tenant {
4284 452 : tenant_shard_id,
4285 452 : shard_identity,
4286 452 : generation: attached_conf.location.generation,
4287 452 : conf,
4288 452 : // using now here is good enough approximation to catch tenants with really long
4289 452 : // activation times.
4290 452 : constructed_at: Instant::now(),
4291 452 : timelines: Mutex::new(HashMap::new()),
4292 452 : timelines_creating: Mutex::new(HashSet::new()),
4293 452 : timelines_offloaded: Mutex::new(HashMap::new()),
4294 452 : tenant_manifest_upload: Default::default(),
4295 452 : gc_cs: tokio::sync::Mutex::new(()),
4296 452 : walredo_mgr,
4297 452 : remote_storage,
4298 452 : deletion_queue_client,
4299 452 : state,
4300 452 : cached_logical_sizes: tokio::sync::Mutex::new(HashMap::new()),
4301 452 : cached_synthetic_tenant_size: Arc::new(AtomicU64::new(0)),
4302 452 : eviction_task_tenant_state: tokio::sync::Mutex::new(EvictionTaskTenantState::default()),
4303 452 : compaction_circuit_breaker: std::sync::Mutex::new(CircuitBreaker::new(
4304 452 : format!("compaction-{tenant_shard_id}"),
4305 452 : 5,
4306 452 : // Compaction can be a very expensive operation, and might leak disk space. It also ought
4307 452 : // to be infallible, as long as remote storage is available. So if it repeatedly fails,
4308 452 : // use an extremely long backoff.
4309 452 : Some(Duration::from_secs(3600 * 24)),
4310 452 : )),
4311 452 : l0_compaction_trigger: Arc::new(Notify::new()),
4312 452 : scheduled_compaction_tasks: Mutex::new(Default::default()),
4313 452 : activate_now_sem: tokio::sync::Semaphore::new(0),
4314 452 : attach_wal_lag_cooldown: Arc::new(std::sync::OnceLock::new()),
4315 452 : cancel: CancellationToken::default(),
4316 452 : gate: Gate::default(),
4317 452 : pagestream_throttle: Arc::new(throttle::Throttle::new(
4318 452 : Tenant::get_pagestream_throttle_config(conf, &attached_conf.tenant_conf),
4319 452 : )),
4320 452 : pagestream_throttle_metrics: Arc::new(
4321 452 : crate::metrics::tenant_throttling::Pagestream::new(&tenant_shard_id),
4322 452 : ),
4323 452 : tenant_conf: Arc::new(ArcSwap::from_pointee(attached_conf)),
4324 452 : ongoing_timeline_detach: std::sync::Mutex::default(),
4325 452 : gc_block: Default::default(),
4326 452 : l0_flush_global_state,
4327 452 : }
4328 452 : }
4329 :
4330 : /// Locate and load config
4331 0 : pub(super) fn load_tenant_config(
4332 0 : conf: &'static PageServerConf,
4333 0 : tenant_shard_id: &TenantShardId,
4334 0 : ) -> Result<LocationConf, LoadConfigError> {
4335 0 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
4336 0 :
4337 0 : info!("loading tenant configuration from {config_path}");
4338 :
4339 : // load and parse file
4340 0 : let config = fs::read_to_string(&config_path).map_err(|e| {
4341 0 : match e.kind() {
4342 : std::io::ErrorKind::NotFound => {
4343 : // The config should almost always exist for a tenant directory:
4344 : // - When attaching a tenant, the config is the first thing we write
4345 : // - When detaching a tenant, we atomically move the directory to a tmp location
4346 : // before deleting contents.
4347 : //
4348 : // The very rare edge case that can result in a missing config is if we crash during attach
4349 : // between creating directory and writing config. Callers should handle that as if the
4350 : // directory didn't exist.
4351 :
4352 0 : LoadConfigError::NotFound(config_path)
4353 : }
4354 : _ => {
4355 : // No IO errors except NotFound are acceptable here: other kinds of error indicate local storage or permissions issues
4356 : // that we cannot cleanly recover
4357 0 : crate::virtual_file::on_fatal_io_error(&e, "Reading tenant config file")
4358 : }
4359 : }
4360 0 : })?;
4361 :
4362 0 : Ok(toml_edit::de::from_str::<LocationConf>(&config)?)
4363 0 : }
4364 :
4365 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
4366 : pub(super) async fn persist_tenant_config(
4367 : conf: &'static PageServerConf,
4368 : tenant_shard_id: &TenantShardId,
4369 : location_conf: &LocationConf,
4370 : ) -> std::io::Result<()> {
4371 : let config_path = conf.tenant_location_config_path(tenant_shard_id);
4372 :
4373 : Self::persist_tenant_config_at(tenant_shard_id, &config_path, location_conf).await
4374 : }
4375 :
4376 : #[tracing::instrument(skip_all, fields(tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug()))]
4377 : pub(super) async fn persist_tenant_config_at(
4378 : tenant_shard_id: &TenantShardId,
4379 : config_path: &Utf8Path,
4380 : location_conf: &LocationConf,
4381 : ) -> std::io::Result<()> {
4382 : debug!("persisting tenantconf to {config_path}");
4383 :
4384 : let mut conf_content = r#"# This file contains a specific per-tenant's config.
4385 : # It is read in case of pageserver restart.
4386 : "#
4387 : .to_string();
4388 :
4389 0 : fail::fail_point!("tenant-config-before-write", |_| {
4390 0 : Err(std::io::Error::new(
4391 0 : std::io::ErrorKind::Other,
4392 0 : "tenant-config-before-write",
4393 0 : ))
4394 0 : });
4395 :
4396 : // Convert the config to a toml file.
4397 : conf_content +=
4398 : &toml_edit::ser::to_string_pretty(&location_conf).expect("Config serialization failed");
4399 :
4400 : let temp_path = path_with_suffix_extension(config_path, TEMP_FILE_SUFFIX);
4401 :
4402 : let conf_content = conf_content.into_bytes();
4403 : VirtualFile::crashsafe_overwrite(config_path.to_owned(), temp_path, conf_content).await
4404 : }
4405 :
4406 : //
4407 : // How garbage collection works:
4408 : //
4409 : // +--bar------------->
4410 : // /
4411 : // +----+-----foo---------------->
4412 : // /
4413 : // ----main--+-------------------------->
4414 : // \
4415 : // +-----baz-------->
4416 : //
4417 : //
4418 : // 1. Grab 'gc_cs' mutex to prevent new timelines from being created while Timeline's
4419 : // `gc_infos` are being refreshed
4420 : // 2. Scan collected timelines, and on each timeline, make note of the
4421 : // all the points where other timelines have been branched off.
4422 : // We will refrain from removing page versions at those LSNs.
4423 : // 3. For each timeline, scan all layer files on the timeline.
4424 : // Remove all files for which a newer file exists and which
4425 : // don't cover any branch point LSNs.
4426 : //
4427 : // TODO:
4428 : // - if a relation has a non-incremental persistent layer on a child branch, then we
4429 : // don't need to keep that in the parent anymore. But currently
4430 : // we do.
4431 8 : async fn gc_iteration_internal(
4432 8 : &self,
4433 8 : target_timeline_id: Option<TimelineId>,
4434 8 : horizon: u64,
4435 8 : pitr: Duration,
4436 8 : cancel: &CancellationToken,
4437 8 : ctx: &RequestContext,
4438 8 : ) -> Result<GcResult, GcError> {
4439 8 : let mut totals: GcResult = Default::default();
4440 8 : let now = Instant::now();
4441 :
4442 8 : let gc_timelines = self
4443 8 : .refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
4444 8 : .await?;
4445 :
4446 8 : failpoint_support::sleep_millis_async!("gc_iteration_internal_after_getting_gc_timelines");
4447 :
4448 : // If there is nothing to GC, we don't want any messages in the INFO log.
4449 8 : if !gc_timelines.is_empty() {
4450 8 : info!("{} timelines need GC", gc_timelines.len());
4451 : } else {
4452 0 : debug!("{} timelines need GC", gc_timelines.len());
4453 : }
4454 :
4455 : // Perform GC for each timeline.
4456 : //
4457 : // Note that we don't hold the `Tenant::gc_cs` lock here because we don't want to delay the
4458 : // branch creation task, which requires the GC lock. A GC iteration can run concurrently
4459 : // with branch creation.
4460 : //
4461 : // See comments in [`Tenant::branch_timeline`] for more information about why branch
4462 : // creation task can run concurrently with timeline's GC iteration.
4463 16 : for timeline in gc_timelines {
4464 8 : if cancel.is_cancelled() {
4465 : // We were requested to shut down. Stop and return with the progress we
4466 : // made.
4467 0 : break;
4468 8 : }
4469 8 : let result = match timeline.gc().await {
4470 : Err(GcError::TimelineCancelled) => {
4471 0 : if target_timeline_id.is_some() {
4472 : // If we were targetting this specific timeline, surface cancellation to caller
4473 0 : return Err(GcError::TimelineCancelled);
4474 : } else {
4475 : // A timeline may be shutting down independently of the tenant's lifecycle: we should
4476 : // skip past this and proceed to try GC on other timelines.
4477 0 : continue;
4478 : }
4479 : }
4480 8 : r => r?,
4481 : };
4482 8 : totals += result;
4483 : }
4484 :
4485 8 : totals.elapsed = now.elapsed();
4486 8 : Ok(totals)
4487 8 : }
4488 :
4489 : /// Refreshes the Timeline::gc_info for all timelines, returning the
4490 : /// vector of timelines which have [`Timeline::get_last_record_lsn`] past
4491 : /// [`Tenant::get_gc_horizon`].
4492 : ///
4493 : /// This is usually executed as part of periodic gc, but can now be triggered more often.
4494 0 : pub(crate) async fn refresh_gc_info(
4495 0 : &self,
4496 0 : cancel: &CancellationToken,
4497 0 : ctx: &RequestContext,
4498 0 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
4499 0 : // since this method can now be called at different rates than the configured gc loop, it
4500 0 : // might be that these configuration values get applied faster than what it was previously,
4501 0 : // since these were only read from the gc task.
4502 0 : let horizon = self.get_gc_horizon();
4503 0 : let pitr = self.get_pitr_interval();
4504 0 :
4505 0 : // refresh all timelines
4506 0 : let target_timeline_id = None;
4507 0 :
4508 0 : self.refresh_gc_info_internal(target_timeline_id, horizon, pitr, cancel, ctx)
4509 0 : .await
4510 0 : }
4511 :
4512 : /// Populate all Timelines' `GcInfo` with information about their children. We do not set the
4513 : /// PITR cutoffs here, because that requires I/O: this is done later, before GC, by [`Self::refresh_gc_info_internal`]
4514 : ///
4515 : /// Subsequently, parent-child relationships are updated incrementally inside [`Timeline::new`] and [`Timeline::drop`].
4516 0 : fn initialize_gc_info(
4517 0 : &self,
4518 0 : timelines: &std::sync::MutexGuard<HashMap<TimelineId, Arc<Timeline>>>,
4519 0 : timelines_offloaded: &std::sync::MutexGuard<HashMap<TimelineId, Arc<OffloadedTimeline>>>,
4520 0 : restrict_to_timeline: Option<TimelineId>,
4521 0 : ) {
4522 0 : if restrict_to_timeline.is_none() {
4523 : // This function must be called before activation: after activation timeline create/delete operations
4524 : // might happen, and this function is not safe to run concurrently with those.
4525 0 : assert!(!self.is_active());
4526 0 : }
4527 :
4528 : // Scan all timelines. For each timeline, remember the timeline ID and
4529 : // the branch point where it was created.
4530 0 : let mut all_branchpoints: BTreeMap<TimelineId, Vec<(Lsn, TimelineId, MaybeOffloaded)>> =
4531 0 : BTreeMap::new();
4532 0 : timelines.iter().for_each(|(timeline_id, timeline_entry)| {
4533 0 : if let Some(ancestor_timeline_id) = &timeline_entry.get_ancestor_timeline_id() {
4534 0 : let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
4535 0 : ancestor_children.push((
4536 0 : timeline_entry.get_ancestor_lsn(),
4537 0 : *timeline_id,
4538 0 : MaybeOffloaded::No,
4539 0 : ));
4540 0 : }
4541 0 : });
4542 0 : timelines_offloaded
4543 0 : .iter()
4544 0 : .for_each(|(timeline_id, timeline_entry)| {
4545 0 : let Some(ancestor_timeline_id) = &timeline_entry.ancestor_timeline_id else {
4546 0 : return;
4547 : };
4548 0 : let Some(retain_lsn) = timeline_entry.ancestor_retain_lsn else {
4549 0 : return;
4550 : };
4551 0 : let ancestor_children = all_branchpoints.entry(*ancestor_timeline_id).or_default();
4552 0 : ancestor_children.push((retain_lsn, *timeline_id, MaybeOffloaded::Yes));
4553 0 : });
4554 0 :
4555 0 : // The number of bytes we always keep, irrespective of PITR: this is a constant across timelines
4556 0 : let horizon = self.get_gc_horizon();
4557 :
4558 : // Populate each timeline's GcInfo with information about its child branches
4559 0 : let timelines_to_write = if let Some(timeline_id) = restrict_to_timeline {
4560 0 : itertools::Either::Left(timelines.get(&timeline_id).into_iter())
4561 : } else {
4562 0 : itertools::Either::Right(timelines.values())
4563 : };
4564 0 : for timeline in timelines_to_write {
4565 0 : let mut branchpoints: Vec<(Lsn, TimelineId, MaybeOffloaded)> = all_branchpoints
4566 0 : .remove(&timeline.timeline_id)
4567 0 : .unwrap_or_default();
4568 0 :
4569 0 : branchpoints.sort_by_key(|b| b.0);
4570 0 :
4571 0 : let mut target = timeline.gc_info.write().unwrap();
4572 0 :
4573 0 : target.retain_lsns = branchpoints;
4574 0 :
4575 0 : let space_cutoff = timeline
4576 0 : .get_last_record_lsn()
4577 0 : .checked_sub(horizon)
4578 0 : .unwrap_or(Lsn(0));
4579 0 :
4580 0 : target.cutoffs = GcCutoffs {
4581 0 : space: space_cutoff,
4582 0 : time: Lsn::INVALID,
4583 0 : };
4584 0 : }
4585 0 : }
4586 :
4587 8 : async fn refresh_gc_info_internal(
4588 8 : &self,
4589 8 : target_timeline_id: Option<TimelineId>,
4590 8 : horizon: u64,
4591 8 : pitr: Duration,
4592 8 : cancel: &CancellationToken,
4593 8 : ctx: &RequestContext,
4594 8 : ) -> Result<Vec<Arc<Timeline>>, GcError> {
4595 8 : // before taking the gc_cs lock, do the heavier weight finding of gc_cutoff points for
4596 8 : // currently visible timelines.
4597 8 : let timelines = self
4598 8 : .timelines
4599 8 : .lock()
4600 8 : .unwrap()
4601 8 : .values()
4602 8 : .filter(|tl| match target_timeline_id.as_ref() {
4603 8 : Some(target) => &tl.timeline_id == target,
4604 0 : None => true,
4605 8 : })
4606 8 : .cloned()
4607 8 : .collect::<Vec<_>>();
4608 8 :
4609 8 : if target_timeline_id.is_some() && timelines.is_empty() {
4610 : // We were to act on a particular timeline and it wasn't found
4611 0 : return Err(GcError::TimelineNotFound);
4612 8 : }
4613 8 :
4614 8 : let mut gc_cutoffs: HashMap<TimelineId, GcCutoffs> =
4615 8 : HashMap::with_capacity(timelines.len());
4616 8 :
4617 8 : // Ensures all timelines use the same start time when computing the time cutoff.
4618 8 : let now_ts_for_pitr_calc = SystemTime::now();
4619 8 : for timeline in timelines.iter() {
4620 8 : let ctx = &ctx.with_scope_timeline(timeline);
4621 8 : let cutoff = timeline
4622 8 : .get_last_record_lsn()
4623 8 : .checked_sub(horizon)
4624 8 : .unwrap_or(Lsn(0));
4625 :
4626 8 : let cutoffs = timeline
4627 8 : .find_gc_cutoffs(now_ts_for_pitr_calc, cutoff, pitr, cancel, ctx)
4628 8 : .await?;
4629 8 : let old = gc_cutoffs.insert(timeline.timeline_id, cutoffs);
4630 8 : assert!(old.is_none());
4631 : }
4632 :
4633 8 : if !self.is_active() || self.cancel.is_cancelled() {
4634 0 : return Err(GcError::TenantCancelled);
4635 8 : }
4636 :
4637 : // grab mutex to prevent new timelines from being created here; avoid doing long operations
4638 : // because that will stall branch creation.
4639 8 : let gc_cs = self.gc_cs.lock().await;
4640 :
4641 : // Ok, we now know all the branch points.
4642 : // Update the GC information for each timeline.
4643 8 : let mut gc_timelines = Vec::with_capacity(timelines.len());
4644 16 : for timeline in timelines {
4645 : // We filtered the timeline list above
4646 8 : if let Some(target_timeline_id) = target_timeline_id {
4647 8 : assert_eq!(target_timeline_id, timeline.timeline_id);
4648 0 : }
4649 :
4650 : {
4651 8 : let mut target = timeline.gc_info.write().unwrap();
4652 8 :
4653 8 : // Cull any expired leases
4654 8 : let now = SystemTime::now();
4655 12 : target.leases.retain(|_, lease| !lease.is_expired(&now));
4656 8 :
4657 8 : timeline
4658 8 : .metrics
4659 8 : .valid_lsn_lease_count_gauge
4660 8 : .set(target.leases.len() as u64);
4661 :
4662 : // Look up parent's PITR cutoff to update the child's knowledge of whether it is within parent's PITR
4663 8 : if let Some(ancestor_id) = timeline.get_ancestor_timeline_id() {
4664 0 : if let Some(ancestor_gc_cutoffs) = gc_cutoffs.get(&ancestor_id) {
4665 0 : target.within_ancestor_pitr =
4666 0 : timeline.get_ancestor_lsn() >= ancestor_gc_cutoffs.time;
4667 0 : }
4668 8 : }
4669 :
4670 : // Update metrics that depend on GC state
4671 8 : timeline
4672 8 : .metrics
4673 8 : .archival_size
4674 8 : .set(if target.within_ancestor_pitr {
4675 0 : timeline.metrics.current_logical_size_gauge.get()
4676 : } else {
4677 8 : 0
4678 : });
4679 8 : timeline.metrics.pitr_history_size.set(
4680 8 : timeline
4681 8 : .get_last_record_lsn()
4682 8 : .checked_sub(target.cutoffs.time)
4683 8 : .unwrap_or(Lsn(0))
4684 8 : .0,
4685 8 : );
4686 :
4687 : // Apply the cutoffs we found to the Timeline's GcInfo. Why might we _not_ have cutoffs for a timeline?
4688 : // - this timeline was created while we were finding cutoffs
4689 : // - lsn for timestamp search fails for this timeline repeatedly
4690 8 : if let Some(cutoffs) = gc_cutoffs.get(&timeline.timeline_id) {
4691 8 : let original_cutoffs = target.cutoffs.clone();
4692 8 : // GC cutoffs should never go back
4693 8 : target.cutoffs = GcCutoffs {
4694 8 : space: Lsn(cutoffs.space.0.max(original_cutoffs.space.0)),
4695 8 : time: Lsn(cutoffs.time.0.max(original_cutoffs.time.0)),
4696 8 : }
4697 0 : }
4698 : }
4699 :
4700 8 : gc_timelines.push(timeline);
4701 : }
4702 8 : drop(gc_cs);
4703 8 : Ok(gc_timelines)
4704 8 : }
4705 :
4706 : /// A substitute for `branch_timeline` for use in unit tests.
4707 : /// The returned timeline will have state value `Active` to make various `anyhow::ensure!()`
4708 : /// calls pass, but, we do not actually call `.activate()` under the hood. So, none of the
4709 : /// timeline background tasks are launched, except the flush loop.
4710 : #[cfg(test)]
4711 464 : async fn branch_timeline_test(
4712 464 : self: &Arc<Self>,
4713 464 : src_timeline: &Arc<Timeline>,
4714 464 : dst_id: TimelineId,
4715 464 : ancestor_lsn: Option<Lsn>,
4716 464 : ctx: &RequestContext,
4717 464 : ) -> Result<Arc<Timeline>, CreateTimelineError> {
4718 464 : let tl = self
4719 464 : .branch_timeline_impl(src_timeline, dst_id, ancestor_lsn, ctx)
4720 464 : .await?
4721 456 : .into_timeline_for_test();
4722 456 : tl.set_state(TimelineState::Active);
4723 456 : Ok(tl)
4724 464 : }
4725 :
4726 : /// Helper for unit tests to branch a timeline with some pre-loaded states.
4727 : #[cfg(test)]
4728 : #[allow(clippy::too_many_arguments)]
4729 12 : pub async fn branch_timeline_test_with_layers(
4730 12 : self: &Arc<Self>,
4731 12 : src_timeline: &Arc<Timeline>,
4732 12 : dst_id: TimelineId,
4733 12 : ancestor_lsn: Option<Lsn>,
4734 12 : ctx: &RequestContext,
4735 12 : delta_layer_desc: Vec<timeline::DeltaLayerTestDesc>,
4736 12 : image_layer_desc: Vec<(Lsn, Vec<(pageserver_api::key::Key, bytes::Bytes)>)>,
4737 12 : end_lsn: Lsn,
4738 12 : ) -> anyhow::Result<Arc<Timeline>> {
4739 : use checks::check_valid_layermap;
4740 : use itertools::Itertools;
4741 :
4742 12 : let tline = self
4743 12 : .branch_timeline_test(src_timeline, dst_id, ancestor_lsn, ctx)
4744 12 : .await?;
4745 12 : let ancestor_lsn = if let Some(ancestor_lsn) = ancestor_lsn {
4746 12 : ancestor_lsn
4747 : } else {
4748 0 : tline.get_last_record_lsn()
4749 : };
4750 12 : assert!(end_lsn >= ancestor_lsn);
4751 12 : tline.force_advance_lsn(end_lsn);
4752 24 : for deltas in delta_layer_desc {
4753 12 : tline
4754 12 : .force_create_delta_layer(deltas, Some(ancestor_lsn), ctx)
4755 12 : .await?;
4756 : }
4757 20 : for (lsn, images) in image_layer_desc {
4758 8 : tline
4759 8 : .force_create_image_layer(lsn, images, Some(ancestor_lsn), ctx)
4760 8 : .await?;
4761 : }
4762 12 : let layer_names = tline
4763 12 : .layers
4764 12 : .read()
4765 12 : .await
4766 12 : .layer_map()
4767 12 : .unwrap()
4768 12 : .iter_historic_layers()
4769 20 : .map(|layer| layer.layer_name())
4770 12 : .collect_vec();
4771 12 : if let Some(err) = check_valid_layermap(&layer_names) {
4772 0 : bail!("invalid layermap: {err}");
4773 12 : }
4774 12 : Ok(tline)
4775 12 : }
4776 :
4777 : /// Branch an existing timeline.
4778 0 : async fn branch_timeline(
4779 0 : self: &Arc<Self>,
4780 0 : src_timeline: &Arc<Timeline>,
4781 0 : dst_id: TimelineId,
4782 0 : start_lsn: Option<Lsn>,
4783 0 : ctx: &RequestContext,
4784 0 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
4785 0 : self.branch_timeline_impl(src_timeline, dst_id, start_lsn, ctx)
4786 0 : .await
4787 0 : }
4788 :
4789 464 : async fn branch_timeline_impl(
4790 464 : self: &Arc<Self>,
4791 464 : src_timeline: &Arc<Timeline>,
4792 464 : dst_id: TimelineId,
4793 464 : start_lsn: Option<Lsn>,
4794 464 : ctx: &RequestContext,
4795 464 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
4796 464 : let src_id = src_timeline.timeline_id;
4797 :
4798 : // We will validate our ancestor LSN in this function. Acquire the GC lock so that
4799 : // this check cannot race with GC, and the ancestor LSN is guaranteed to remain
4800 : // valid while we are creating the branch.
4801 464 : let _gc_cs = self.gc_cs.lock().await;
4802 :
4803 : // If no start LSN is specified, we branch the new timeline from the source timeline's last record LSN
4804 464 : let start_lsn = start_lsn.unwrap_or_else(|| {
4805 4 : let lsn = src_timeline.get_last_record_lsn();
4806 4 : info!("branching timeline {dst_id} from timeline {src_id} at last record LSN: {lsn}");
4807 4 : lsn
4808 464 : });
4809 :
4810 : // we finally have determined the ancestor_start_lsn, so we can get claim exclusivity now
4811 464 : let timeline_create_guard = match self
4812 464 : .start_creating_timeline(
4813 464 : dst_id,
4814 464 : CreateTimelineIdempotency::Branch {
4815 464 : ancestor_timeline_id: src_timeline.timeline_id,
4816 464 : ancestor_start_lsn: start_lsn,
4817 464 : },
4818 464 : )
4819 464 : .await?
4820 : {
4821 464 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
4822 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
4823 0 : return Ok(CreateTimelineResult::Idempotent(timeline));
4824 : }
4825 : };
4826 :
4827 : // Ensure that `start_lsn` is valid, i.e. the LSN is within the PITR
4828 : // horizon on the source timeline
4829 : //
4830 : // We check it against both the planned GC cutoff stored in 'gc_info',
4831 : // and the 'latest_gc_cutoff' of the last GC that was performed. The
4832 : // planned GC cutoff in 'gc_info' is normally larger than
4833 : // 'applied_gc_cutoff_lsn', but beware of corner cases like if you just
4834 : // changed the GC settings for the tenant to make the PITR window
4835 : // larger, but some of the data was already removed by an earlier GC
4836 : // iteration.
4837 :
4838 : // check against last actual 'latest_gc_cutoff' first
4839 464 : let applied_gc_cutoff_lsn = src_timeline.get_applied_gc_cutoff_lsn();
4840 464 : {
4841 464 : let gc_info = src_timeline.gc_info.read().unwrap();
4842 464 : let planned_cutoff = gc_info.min_cutoff();
4843 464 : if gc_info.lsn_covered_by_lease(start_lsn) {
4844 0 : tracing::info!(
4845 0 : "skipping comparison of {start_lsn} with gc cutoff {} and planned gc cutoff {planned_cutoff} due to lsn lease",
4846 0 : *applied_gc_cutoff_lsn
4847 : );
4848 : } else {
4849 464 : src_timeline
4850 464 : .check_lsn_is_in_scope(start_lsn, &applied_gc_cutoff_lsn)
4851 464 : .context(format!(
4852 464 : "invalid branch start lsn: less than latest GC cutoff {}",
4853 464 : *applied_gc_cutoff_lsn,
4854 464 : ))
4855 464 : .map_err(CreateTimelineError::AncestorLsn)?;
4856 :
4857 : // and then the planned GC cutoff
4858 456 : if start_lsn < planned_cutoff {
4859 0 : return Err(CreateTimelineError::AncestorLsn(anyhow::anyhow!(
4860 0 : "invalid branch start lsn: less than planned GC cutoff {planned_cutoff}"
4861 0 : )));
4862 456 : }
4863 : }
4864 : }
4865 :
4866 : //
4867 : // The branch point is valid, and we are still holding the 'gc_cs' lock
4868 : // so that GC cannot advance the GC cutoff until we are finished.
4869 : // Proceed with the branch creation.
4870 : //
4871 :
4872 : // Determine prev-LSN for the new timeline. We can only determine it if
4873 : // the timeline was branched at the current end of the source timeline.
4874 : let RecordLsn {
4875 456 : last: src_last,
4876 456 : prev: src_prev,
4877 456 : } = src_timeline.get_last_record_rlsn();
4878 456 : let dst_prev = if src_last == start_lsn {
4879 432 : Some(src_prev)
4880 : } else {
4881 24 : None
4882 : };
4883 :
4884 : // Create the metadata file, noting the ancestor of the new timeline.
4885 : // There is initially no data in it, but all the read-calls know to look
4886 : // into the ancestor.
4887 456 : let metadata = TimelineMetadata::new(
4888 456 : start_lsn,
4889 456 : dst_prev,
4890 456 : Some(src_id),
4891 456 : start_lsn,
4892 456 : *src_timeline.applied_gc_cutoff_lsn.read(), // FIXME: should we hold onto this guard longer?
4893 456 : src_timeline.initdb_lsn,
4894 456 : src_timeline.pg_version,
4895 456 : );
4896 :
4897 456 : let (uninitialized_timeline, _timeline_ctx) = self
4898 456 : .prepare_new_timeline(
4899 456 : dst_id,
4900 456 : &metadata,
4901 456 : timeline_create_guard,
4902 456 : start_lsn + 1,
4903 456 : Some(Arc::clone(src_timeline)),
4904 456 : Some(src_timeline.get_rel_size_v2_status()),
4905 456 : ctx,
4906 456 : )
4907 456 : .await?;
4908 :
4909 456 : let new_timeline = uninitialized_timeline.finish_creation().await?;
4910 :
4911 : // Root timeline gets its layers during creation and uploads them along with the metadata.
4912 : // A branch timeline though, when created, can get no writes for some time, hence won't get any layers created.
4913 : // We still need to upload its metadata eagerly: if other nodes `attach` the tenant and miss this timeline, their GC
4914 : // could get incorrect information and remove more layers, than needed.
4915 : // See also https://github.com/neondatabase/neon/issues/3865
4916 456 : new_timeline
4917 456 : .remote_client
4918 456 : .schedule_index_upload_for_full_metadata_update(&metadata)
4919 456 : .context("branch initial metadata upload")?;
4920 :
4921 : // Callers are responsible to wait for uploads to complete and for activating the timeline.
4922 :
4923 456 : Ok(CreateTimelineResult::Created(new_timeline))
4924 464 : }
4925 :
4926 : /// For unit tests, make this visible so that other modules can directly create timelines
4927 : #[cfg(test)]
4928 : #[tracing::instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug(), %timeline_id))]
4929 : pub(crate) async fn bootstrap_timeline_test(
4930 : self: &Arc<Self>,
4931 : timeline_id: TimelineId,
4932 : pg_version: u32,
4933 : load_existing_initdb: Option<TimelineId>,
4934 : ctx: &RequestContext,
4935 : ) -> anyhow::Result<Arc<Timeline>> {
4936 : self.bootstrap_timeline(timeline_id, pg_version, load_existing_initdb, ctx)
4937 : .await
4938 : .map_err(anyhow::Error::new)
4939 4 : .map(|r| r.into_timeline_for_test())
4940 : }
4941 :
4942 : /// Get exclusive access to the timeline ID for creation.
4943 : ///
4944 : /// Timeline-creating code paths must use this function before making changes
4945 : /// to in-memory or persistent state.
4946 : ///
4947 : /// The `state` parameter is a description of the timeline creation operation
4948 : /// we intend to perform.
4949 : /// If the timeline was already created in the meantime, we check whether this
4950 : /// request conflicts or is idempotent , based on `state`.
4951 904 : async fn start_creating_timeline(
4952 904 : self: &Arc<Self>,
4953 904 : new_timeline_id: TimelineId,
4954 904 : idempotency: CreateTimelineIdempotency,
4955 904 : ) -> Result<StartCreatingTimelineResult, CreateTimelineError> {
4956 904 : let allow_offloaded = false;
4957 904 : match self.create_timeline_create_guard(new_timeline_id, idempotency, allow_offloaded) {
4958 900 : Ok(create_guard) => {
4959 900 : pausable_failpoint!("timeline-creation-after-uninit");
4960 900 : Ok(StartCreatingTimelineResult::CreateGuard(create_guard))
4961 : }
4962 0 : Err(TimelineExclusionError::ShuttingDown) => Err(CreateTimelineError::ShuttingDown),
4963 : Err(TimelineExclusionError::AlreadyCreating) => {
4964 : // Creation is in progress, we cannot create it again, and we cannot
4965 : // check if this request matches the existing one, so caller must try
4966 : // again later.
4967 0 : Err(CreateTimelineError::AlreadyCreating)
4968 : }
4969 0 : Err(TimelineExclusionError::Other(e)) => Err(CreateTimelineError::Other(e)),
4970 : Err(TimelineExclusionError::AlreadyExists {
4971 0 : existing: TimelineOrOffloaded::Offloaded(_existing),
4972 0 : ..
4973 0 : }) => {
4974 0 : info!("timeline already exists but is offloaded");
4975 0 : Err(CreateTimelineError::Conflict)
4976 : }
4977 : Err(TimelineExclusionError::AlreadyExists {
4978 4 : existing: TimelineOrOffloaded::Timeline(existing),
4979 4 : arg,
4980 4 : }) => {
4981 4 : {
4982 4 : let existing = &existing.create_idempotency;
4983 4 : let _span = info_span!("idempotency_check", ?existing, ?arg).entered();
4984 4 : debug!("timeline already exists");
4985 :
4986 4 : match (existing, &arg) {
4987 : // FailWithConflict => no idempotency check
4988 : (CreateTimelineIdempotency::FailWithConflict, _)
4989 : | (_, CreateTimelineIdempotency::FailWithConflict) => {
4990 4 : warn!("timeline already exists, failing request");
4991 4 : return Err(CreateTimelineError::Conflict);
4992 : }
4993 : // Idempotent <=> CreateTimelineIdempotency is identical
4994 0 : (x, y) if x == y => {
4995 0 : info!(
4996 0 : "timeline already exists and idempotency matches, succeeding request"
4997 : );
4998 : // fallthrough
4999 : }
5000 : (_, _) => {
5001 0 : warn!("idempotency conflict, failing request");
5002 0 : return Err(CreateTimelineError::Conflict);
5003 : }
5004 : }
5005 : }
5006 :
5007 0 : Ok(StartCreatingTimelineResult::Idempotent(existing))
5008 : }
5009 : }
5010 904 : }
5011 :
5012 0 : async fn upload_initdb(
5013 0 : &self,
5014 0 : timelines_path: &Utf8PathBuf,
5015 0 : pgdata_path: &Utf8PathBuf,
5016 0 : timeline_id: &TimelineId,
5017 0 : ) -> anyhow::Result<()> {
5018 0 : let temp_path = timelines_path.join(format!(
5019 0 : "{INITDB_PATH}.upload-{timeline_id}.{TEMP_FILE_SUFFIX}"
5020 0 : ));
5021 0 :
5022 0 : scopeguard::defer! {
5023 0 : if let Err(e) = fs::remove_file(&temp_path) {
5024 0 : error!("Failed to remove temporary initdb archive '{temp_path}': {e}");
5025 0 : }
5026 0 : }
5027 :
5028 0 : let (pgdata_zstd, tar_zst_size) = create_zst_tarball(pgdata_path, &temp_path).await?;
5029 : const INITDB_TAR_ZST_WARN_LIMIT: u64 = 2 * 1024 * 1024;
5030 0 : if tar_zst_size > INITDB_TAR_ZST_WARN_LIMIT {
5031 0 : warn!(
5032 0 : "compressed {temp_path} size of {tar_zst_size} is above limit {INITDB_TAR_ZST_WARN_LIMIT}."
5033 : );
5034 0 : }
5035 :
5036 0 : pausable_failpoint!("before-initdb-upload");
5037 :
5038 0 : backoff::retry(
5039 0 : || async {
5040 0 : self::remote_timeline_client::upload_initdb_dir(
5041 0 : &self.remote_storage,
5042 0 : &self.tenant_shard_id.tenant_id,
5043 0 : timeline_id,
5044 0 : pgdata_zstd.try_clone().await?,
5045 0 : tar_zst_size,
5046 0 : &self.cancel,
5047 0 : )
5048 0 : .await
5049 0 : },
5050 0 : |_| false,
5051 0 : 3,
5052 0 : u32::MAX,
5053 0 : "persist_initdb_tar_zst",
5054 0 : &self.cancel,
5055 0 : )
5056 0 : .await
5057 0 : .ok_or_else(|| anyhow::Error::new(TimeoutOrCancel::Cancel))
5058 0 : .and_then(|x| x)
5059 0 : }
5060 :
5061 : /// - run initdb to init temporary instance and get bootstrap data
5062 : /// - after initialization completes, tar up the temp dir and upload it to S3.
5063 4 : async fn bootstrap_timeline(
5064 4 : self: &Arc<Self>,
5065 4 : timeline_id: TimelineId,
5066 4 : pg_version: u32,
5067 4 : load_existing_initdb: Option<TimelineId>,
5068 4 : ctx: &RequestContext,
5069 4 : ) -> Result<CreateTimelineResult, CreateTimelineError> {
5070 4 : let timeline_create_guard = match self
5071 4 : .start_creating_timeline(
5072 4 : timeline_id,
5073 4 : CreateTimelineIdempotency::Bootstrap { pg_version },
5074 4 : )
5075 4 : .await?
5076 : {
5077 4 : StartCreatingTimelineResult::CreateGuard(guard) => guard,
5078 0 : StartCreatingTimelineResult::Idempotent(timeline) => {
5079 0 : return Ok(CreateTimelineResult::Idempotent(timeline));
5080 : }
5081 : };
5082 :
5083 : // create a `tenant/{tenant_id}/timelines/basebackup-{timeline_id}.{TEMP_FILE_SUFFIX}/`
5084 : // temporary directory for basebackup files for the given timeline.
5085 :
5086 4 : let timelines_path = self.conf.timelines_path(&self.tenant_shard_id);
5087 4 : let pgdata_path = path_with_suffix_extension(
5088 4 : timelines_path.join(format!("basebackup-{timeline_id}")),
5089 4 : TEMP_FILE_SUFFIX,
5090 4 : );
5091 4 :
5092 4 : // Remove whatever was left from the previous runs: safe because TimelineCreateGuard guarantees
5093 4 : // we won't race with other creations or existent timelines with the same path.
5094 4 : if pgdata_path.exists() {
5095 0 : fs::remove_dir_all(&pgdata_path).with_context(|| {
5096 0 : format!("Failed to remove already existing initdb directory: {pgdata_path}")
5097 0 : })?;
5098 0 : tracing::info!("removed previous attempt's temporary initdb directory '{pgdata_path}'");
5099 4 : }
5100 :
5101 : // this new directory is very temporary, set to remove it immediately after bootstrap, we don't need it
5102 4 : let pgdata_path_deferred = pgdata_path.clone();
5103 4 : scopeguard::defer! {
5104 4 : if let Err(e) = fs::remove_dir_all(&pgdata_path_deferred).or_else(fs_ext::ignore_not_found) {
5105 4 : // this is unlikely, but we will remove the directory on pageserver restart or another bootstrap call
5106 4 : error!("Failed to remove temporary initdb directory '{pgdata_path_deferred}': {e}");
5107 4 : } else {
5108 4 : tracing::info!("removed temporary initdb directory '{pgdata_path_deferred}'");
5109 4 : }
5110 4 : }
5111 4 : if let Some(existing_initdb_timeline_id) = load_existing_initdb {
5112 4 : if existing_initdb_timeline_id != timeline_id {
5113 0 : let source_path = &remote_initdb_archive_path(
5114 0 : &self.tenant_shard_id.tenant_id,
5115 0 : &existing_initdb_timeline_id,
5116 0 : );
5117 0 : let dest_path =
5118 0 : &remote_initdb_archive_path(&self.tenant_shard_id.tenant_id, &timeline_id);
5119 0 :
5120 0 : // if this fails, it will get retried by retried control plane requests
5121 0 : self.remote_storage
5122 0 : .copy_object(source_path, dest_path, &self.cancel)
5123 0 : .await
5124 0 : .context("copy initdb tar")?;
5125 4 : }
5126 4 : let (initdb_tar_zst_path, initdb_tar_zst) =
5127 4 : self::remote_timeline_client::download_initdb_tar_zst(
5128 4 : self.conf,
5129 4 : &self.remote_storage,
5130 4 : &self.tenant_shard_id,
5131 4 : &existing_initdb_timeline_id,
5132 4 : &self.cancel,
5133 4 : )
5134 4 : .await
5135 4 : .context("download initdb tar")?;
5136 :
5137 4 : scopeguard::defer! {
5138 4 : if let Err(e) = fs::remove_file(&initdb_tar_zst_path) {
5139 4 : error!("Failed to remove temporary initdb archive '{initdb_tar_zst_path}': {e}");
5140 4 : }
5141 4 : }
5142 4 :
5143 4 : let buf_read =
5144 4 : BufReader::with_capacity(remote_timeline_client::BUFFER_SIZE, initdb_tar_zst);
5145 4 : extract_zst_tarball(&pgdata_path, buf_read)
5146 4 : .await
5147 4 : .context("extract initdb tar")?;
5148 : } else {
5149 : // Init temporarily repo to get bootstrap data, this creates a directory in the `pgdata_path` path
5150 0 : run_initdb(self.conf, &pgdata_path, pg_version, &self.cancel)
5151 0 : .await
5152 0 : .context("run initdb")?;
5153 :
5154 : // Upload the created data dir to S3
5155 0 : if self.tenant_shard_id().is_shard_zero() {
5156 0 : self.upload_initdb(&timelines_path, &pgdata_path, &timeline_id)
5157 0 : .await?;
5158 0 : }
5159 : }
5160 4 : let pgdata_lsn = import_datadir::get_lsn_from_controlfile(&pgdata_path)?.align();
5161 4 :
5162 4 : // Import the contents of the data directory at the initial checkpoint
5163 4 : // LSN, and any WAL after that.
5164 4 : // Initdb lsn will be equal to last_record_lsn which will be set after import.
5165 4 : // Because we know it upfront avoid having an option or dummy zero value by passing it to the metadata.
5166 4 : let new_metadata = TimelineMetadata::new(
5167 4 : Lsn(0),
5168 4 : None,
5169 4 : None,
5170 4 : Lsn(0),
5171 4 : pgdata_lsn,
5172 4 : pgdata_lsn,
5173 4 : pg_version,
5174 4 : );
5175 4 : let (mut raw_timeline, timeline_ctx) = self
5176 4 : .prepare_new_timeline(
5177 4 : timeline_id,
5178 4 : &new_metadata,
5179 4 : timeline_create_guard,
5180 4 : pgdata_lsn,
5181 4 : None,
5182 4 : None,
5183 4 : ctx,
5184 4 : )
5185 4 : .await?;
5186 :
5187 4 : let tenant_shard_id = raw_timeline.owning_tenant.tenant_shard_id;
5188 4 : raw_timeline
5189 4 : .write(|unfinished_timeline| async move {
5190 4 : import_datadir::import_timeline_from_postgres_datadir(
5191 4 : &unfinished_timeline,
5192 4 : &pgdata_path,
5193 4 : pgdata_lsn,
5194 4 : &timeline_ctx,
5195 4 : )
5196 4 : .await
5197 4 : .with_context(|| {
5198 0 : format!(
5199 0 : "Failed to import pgdatadir for timeline {tenant_shard_id}/{timeline_id}"
5200 0 : )
5201 4 : })?;
5202 :
5203 4 : fail::fail_point!("before-checkpoint-new-timeline", |_| {
5204 0 : Err(CreateTimelineError::Other(anyhow::anyhow!(
5205 0 : "failpoint before-checkpoint-new-timeline"
5206 0 : )))
5207 4 : });
5208 :
5209 4 : Ok(())
5210 8 : })
5211 4 : .await?;
5212 :
5213 : // All done!
5214 4 : let timeline = raw_timeline.finish_creation().await?;
5215 :
5216 : // Callers are responsible to wait for uploads to complete and for activating the timeline.
5217 :
5218 4 : Ok(CreateTimelineResult::Created(timeline))
5219 4 : }
5220 :
5221 892 : fn build_timeline_remote_client(&self, timeline_id: TimelineId) -> RemoteTimelineClient {
5222 892 : RemoteTimelineClient::new(
5223 892 : self.remote_storage.clone(),
5224 892 : self.deletion_queue_client.clone(),
5225 892 : self.conf,
5226 892 : self.tenant_shard_id,
5227 892 : timeline_id,
5228 892 : self.generation,
5229 892 : &self.tenant_conf.load().location,
5230 892 : )
5231 892 : }
5232 :
5233 : /// Builds required resources for a new timeline.
5234 892 : fn build_timeline_resources(&self, timeline_id: TimelineId) -> TimelineResources {
5235 892 : let remote_client = self.build_timeline_remote_client(timeline_id);
5236 892 : self.get_timeline_resources_for(remote_client)
5237 892 : }
5238 :
5239 : /// Builds timeline resources for the given remote client.
5240 904 : fn get_timeline_resources_for(&self, remote_client: RemoteTimelineClient) -> TimelineResources {
5241 904 : TimelineResources {
5242 904 : remote_client,
5243 904 : pagestream_throttle: self.pagestream_throttle.clone(),
5244 904 : pagestream_throttle_metrics: self.pagestream_throttle_metrics.clone(),
5245 904 : l0_compaction_trigger: self.l0_compaction_trigger.clone(),
5246 904 : l0_flush_global_state: self.l0_flush_global_state.clone(),
5247 904 : }
5248 904 : }
5249 :
5250 : /// Creates intermediate timeline structure and its files.
5251 : ///
5252 : /// An empty layer map is initialized, and new data and WAL can be imported starting
5253 : /// at 'disk_consistent_lsn'. After any initial data has been imported, call
5254 : /// `finish_creation` to insert the Timeline into the timelines map.
5255 : #[allow(clippy::too_many_arguments)]
5256 892 : async fn prepare_new_timeline<'a>(
5257 892 : &'a self,
5258 892 : new_timeline_id: TimelineId,
5259 892 : new_metadata: &TimelineMetadata,
5260 892 : create_guard: TimelineCreateGuard,
5261 892 : start_lsn: Lsn,
5262 892 : ancestor: Option<Arc<Timeline>>,
5263 892 : rel_size_v2_status: Option<RelSizeMigration>,
5264 892 : ctx: &RequestContext,
5265 892 : ) -> anyhow::Result<(UninitializedTimeline<'a>, RequestContext)> {
5266 892 : let tenant_shard_id = self.tenant_shard_id;
5267 892 :
5268 892 : let resources = self.build_timeline_resources(new_timeline_id);
5269 892 : resources
5270 892 : .remote_client
5271 892 : .init_upload_queue_for_empty_remote(new_metadata, rel_size_v2_status.clone())?;
5272 :
5273 892 : let (timeline_struct, timeline_ctx) = self
5274 892 : .create_timeline_struct(
5275 892 : new_timeline_id,
5276 892 : new_metadata,
5277 892 : None,
5278 892 : ancestor,
5279 892 : resources,
5280 892 : CreateTimelineCause::Load,
5281 892 : create_guard.idempotency.clone(),
5282 892 : None,
5283 892 : rel_size_v2_status,
5284 892 : ctx,
5285 892 : )
5286 892 : .context("Failed to create timeline data structure")?;
5287 :
5288 892 : timeline_struct.init_empty_layer_map(start_lsn);
5289 :
5290 892 : if let Err(e) = self
5291 892 : .create_timeline_files(&create_guard.timeline_path)
5292 892 : .await
5293 : {
5294 0 : error!(
5295 0 : "Failed to create initial files for timeline {tenant_shard_id}/{new_timeline_id}, cleaning up: {e:?}"
5296 : );
5297 0 : cleanup_timeline_directory(create_guard);
5298 0 : return Err(e);
5299 892 : }
5300 892 :
5301 892 : debug!(
5302 0 : "Successfully created initial files for timeline {tenant_shard_id}/{new_timeline_id}"
5303 : );
5304 :
5305 892 : Ok((
5306 892 : UninitializedTimeline::new(
5307 892 : self,
5308 892 : new_timeline_id,
5309 892 : Some((timeline_struct, create_guard)),
5310 892 : ),
5311 892 : timeline_ctx,
5312 892 : ))
5313 892 : }
5314 :
5315 892 : async fn create_timeline_files(&self, timeline_path: &Utf8Path) -> anyhow::Result<()> {
5316 892 : crashsafe::create_dir(timeline_path).context("Failed to create timeline directory")?;
5317 :
5318 892 : fail::fail_point!("after-timeline-dir-creation", |_| {
5319 0 : anyhow::bail!("failpoint after-timeline-dir-creation");
5320 892 : });
5321 :
5322 892 : Ok(())
5323 892 : }
5324 :
5325 : /// Get a guard that provides exclusive access to the timeline directory, preventing
5326 : /// concurrent attempts to create the same timeline.
5327 : ///
5328 : /// The `allow_offloaded` parameter controls whether to tolerate the existence of
5329 : /// offloaded timelines or not.
5330 904 : fn create_timeline_create_guard(
5331 904 : self: &Arc<Self>,
5332 904 : timeline_id: TimelineId,
5333 904 : idempotency: CreateTimelineIdempotency,
5334 904 : allow_offloaded: bool,
5335 904 : ) -> Result<TimelineCreateGuard, TimelineExclusionError> {
5336 904 : let tenant_shard_id = self.tenant_shard_id;
5337 904 :
5338 904 : let timeline_path = self.conf.timeline_path(&tenant_shard_id, &timeline_id);
5339 :
5340 904 : let create_guard = TimelineCreateGuard::new(
5341 904 : self,
5342 904 : timeline_id,
5343 904 : timeline_path.clone(),
5344 904 : idempotency,
5345 904 : allow_offloaded,
5346 904 : )?;
5347 :
5348 : // At this stage, we have got exclusive access to in-memory state for this timeline ID
5349 : // for creation.
5350 : // A timeline directory should never exist on disk already:
5351 : // - a previous failed creation would have cleaned up after itself
5352 : // - a pageserver restart would clean up timeline directories that don't have valid remote state
5353 : //
5354 : // Therefore it is an unexpected internal error to encounter a timeline directory already existing here,
5355 : // this error may indicate a bug in cleanup on failed creations.
5356 900 : if timeline_path.exists() {
5357 0 : return Err(TimelineExclusionError::Other(anyhow::anyhow!(
5358 0 : "Timeline directory already exists! This is a bug."
5359 0 : )));
5360 900 : }
5361 900 :
5362 900 : Ok(create_guard)
5363 904 : }
5364 :
5365 : /// Gathers inputs from all of the timelines to produce a sizing model input.
5366 : ///
5367 : /// Future is cancellation safe. Only one calculation can be running at once per tenant.
5368 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5369 : pub async fn gather_size_inputs(
5370 : &self,
5371 : // `max_retention_period` overrides the cutoff that is used to calculate the size
5372 : // (only if it is shorter than the real cutoff).
5373 : max_retention_period: Option<u64>,
5374 : cause: LogicalSizeCalculationCause,
5375 : cancel: &CancellationToken,
5376 : ctx: &RequestContext,
5377 : ) -> Result<size::ModelInputs, size::CalculateSyntheticSizeError> {
5378 : let logical_sizes_at_once = self
5379 : .conf
5380 : .concurrent_tenant_size_logical_size_queries
5381 : .inner();
5382 :
5383 : // TODO: Having a single mutex block concurrent reads is not great for performance.
5384 : //
5385 : // But the only case where we need to run multiple of these at once is when we
5386 : // request a size for a tenant manually via API, while another background calculation
5387 : // is in progress (which is not a common case).
5388 : //
5389 : // See more for on the issue #2748 condenced out of the initial PR review.
5390 : let mut shared_cache = tokio::select! {
5391 : locked = self.cached_logical_sizes.lock() => locked,
5392 : _ = cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
5393 : _ = self.cancel.cancelled() => return Err(size::CalculateSyntheticSizeError::Cancelled),
5394 : };
5395 :
5396 : size::gather_inputs(
5397 : self,
5398 : logical_sizes_at_once,
5399 : max_retention_period,
5400 : &mut shared_cache,
5401 : cause,
5402 : cancel,
5403 : ctx,
5404 : )
5405 : .await
5406 : }
5407 :
5408 : /// Calculate synthetic tenant size and cache the result.
5409 : /// This is periodically called by background worker.
5410 : /// result is cached in tenant struct
5411 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5412 : pub async fn calculate_synthetic_size(
5413 : &self,
5414 : cause: LogicalSizeCalculationCause,
5415 : cancel: &CancellationToken,
5416 : ctx: &RequestContext,
5417 : ) -> Result<u64, size::CalculateSyntheticSizeError> {
5418 : let inputs = self.gather_size_inputs(None, cause, cancel, ctx).await?;
5419 :
5420 : let size = inputs.calculate();
5421 :
5422 : self.set_cached_synthetic_size(size);
5423 :
5424 : Ok(size)
5425 : }
5426 :
5427 : /// Cache given synthetic size and update the metric value
5428 0 : pub fn set_cached_synthetic_size(&self, size: u64) {
5429 0 : self.cached_synthetic_tenant_size
5430 0 : .store(size, Ordering::Relaxed);
5431 0 :
5432 0 : // Only shard zero should be calculating synthetic sizes
5433 0 : debug_assert!(self.shard_identity.is_shard_zero());
5434 :
5435 0 : TENANT_SYNTHETIC_SIZE_METRIC
5436 0 : .get_metric_with_label_values(&[&self.tenant_shard_id.tenant_id.to_string()])
5437 0 : .unwrap()
5438 0 : .set(size);
5439 0 : }
5440 :
5441 0 : pub fn cached_synthetic_size(&self) -> u64 {
5442 0 : self.cached_synthetic_tenant_size.load(Ordering::Relaxed)
5443 0 : }
5444 :
5445 : /// Flush any in-progress layers, schedule uploads, and wait for uploads to complete.
5446 : ///
5447 : /// This function can take a long time: callers should wrap it in a timeout if calling
5448 : /// from an external API handler.
5449 : ///
5450 : /// Cancel-safety: cancelling this function may leave I/O running, but such I/O is
5451 : /// still bounded by tenant/timeline shutdown.
5452 : #[tracing::instrument(skip_all)]
5453 : pub(crate) async fn flush_remote(&self) -> anyhow::Result<()> {
5454 : let timelines = self.timelines.lock().unwrap().clone();
5455 :
5456 0 : async fn flush_timeline(_gate: GateGuard, timeline: Arc<Timeline>) -> anyhow::Result<()> {
5457 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Flushing...");
5458 0 : timeline.freeze_and_flush().await?;
5459 0 : tracing::info!(timeline_id=%timeline.timeline_id, "Waiting for uploads...");
5460 0 : timeline.remote_client.wait_completion().await?;
5461 :
5462 0 : Ok(())
5463 0 : }
5464 :
5465 : // We do not use a JoinSet for these tasks, because we don't want them to be
5466 : // aborted when this function's future is cancelled: they should stay alive
5467 : // holding their GateGuard until they complete, to ensure their I/Os complete
5468 : // before Timeline shutdown completes.
5469 : let mut results = FuturesUnordered::new();
5470 :
5471 : for (_timeline_id, timeline) in timelines {
5472 : // Run each timeline's flush in a task holding the timeline's gate: this
5473 : // means that if this function's future is cancelled, the Timeline shutdown
5474 : // will still wait for any I/O in here to complete.
5475 : let Ok(gate) = timeline.gate.enter() else {
5476 : continue;
5477 : };
5478 0 : let jh = tokio::task::spawn(async move { flush_timeline(gate, timeline).await });
5479 : results.push(jh);
5480 : }
5481 :
5482 : while let Some(r) = results.next().await {
5483 : if let Err(e) = r {
5484 : if !e.is_cancelled() && !e.is_panic() {
5485 : tracing::error!("unexpected join error: {e:?}");
5486 : }
5487 : }
5488 : }
5489 :
5490 : // The flushes we did above were just writes, but the Tenant might have had
5491 : // pending deletions as well from recent compaction/gc: we want to flush those
5492 : // as well. This requires flushing the global delete queue. This is cheap
5493 : // because it's typically a no-op.
5494 : match self.deletion_queue_client.flush_execute().await {
5495 : Ok(_) => {}
5496 : Err(DeletionQueueError::ShuttingDown) => {}
5497 : }
5498 :
5499 : Ok(())
5500 : }
5501 :
5502 0 : pub(crate) fn get_tenant_conf(&self) -> pageserver_api::models::TenantConfig {
5503 0 : self.tenant_conf.load().tenant_conf.clone()
5504 0 : }
5505 :
5506 : /// How much local storage would this tenant like to have? It can cope with
5507 : /// less than this (via eviction and on-demand downloads), but this function enables
5508 : /// the Tenant to advertise how much storage it would prefer to have to provide fast I/O
5509 : /// by keeping important things on local disk.
5510 : ///
5511 : /// This is a heuristic, not a guarantee: tenants that are long-idle will actually use less
5512 : /// than they report here, due to layer eviction. Tenants with many active branches may
5513 : /// actually use more than they report here.
5514 0 : pub(crate) fn local_storage_wanted(&self) -> u64 {
5515 0 : let timelines = self.timelines.lock().unwrap();
5516 0 :
5517 0 : // Heuristic: we use the max() of the timelines' visible sizes, rather than the sum. This
5518 0 : // reflects the observation that on tenants with multiple large branches, typically only one
5519 0 : // of them is used actively enough to occupy space on disk.
5520 0 : timelines
5521 0 : .values()
5522 0 : .map(|t| t.metrics.visible_physical_size_gauge.get())
5523 0 : .max()
5524 0 : .unwrap_or(0)
5525 0 : }
5526 :
5527 : /// Serialize and write the latest TenantManifest to remote storage.
5528 4 : pub(crate) async fn store_tenant_manifest(&self) -> Result<(), TenantManifestError> {
5529 : // Only one manifest write may be done at at time, and the contents of the manifest
5530 : // must be loaded while holding this lock. This makes it safe to call this function
5531 : // from anywhere without worrying about colliding updates.
5532 4 : let mut guard = tokio::select! {
5533 4 : g = self.tenant_manifest_upload.lock() => {
5534 4 : g
5535 : },
5536 4 : _ = self.cancel.cancelled() => {
5537 0 : return Err(TenantManifestError::Cancelled);
5538 : }
5539 : };
5540 :
5541 4 : let manifest = self.build_tenant_manifest();
5542 4 : if Some(&manifest) == (*guard).as_ref() {
5543 : // Optimisation: skip uploads that don't change anything.
5544 0 : return Ok(());
5545 4 : }
5546 4 :
5547 4 : // Remote storage does no retries internally, so wrap it
5548 4 : match backoff::retry(
5549 4 : || async {
5550 4 : upload_tenant_manifest(
5551 4 : &self.remote_storage,
5552 4 : &self.tenant_shard_id,
5553 4 : self.generation,
5554 4 : &manifest,
5555 4 : &self.cancel,
5556 4 : )
5557 4 : .await
5558 8 : },
5559 4 : |_e| self.cancel.is_cancelled(),
5560 4 : FAILED_UPLOAD_WARN_THRESHOLD,
5561 4 : FAILED_REMOTE_OP_RETRIES,
5562 4 : "uploading tenant manifest",
5563 4 : &self.cancel,
5564 4 : )
5565 4 : .await
5566 : {
5567 0 : None => Err(TenantManifestError::Cancelled),
5568 0 : Some(Err(_)) if self.cancel.is_cancelled() => Err(TenantManifestError::Cancelled),
5569 0 : Some(Err(e)) => Err(TenantManifestError::RemoteStorage(e)),
5570 : Some(Ok(_)) => {
5571 : // Store the successfully uploaded manifest, so that future callers can avoid
5572 : // re-uploading the same thing.
5573 4 : *guard = Some(manifest);
5574 4 :
5575 4 : Ok(())
5576 : }
5577 : }
5578 4 : }
5579 : }
5580 :
5581 : /// Create the cluster temporarily in 'initdbpath' directory inside the repository
5582 : /// to get bootstrap data for timeline initialization.
5583 0 : async fn run_initdb(
5584 0 : conf: &'static PageServerConf,
5585 0 : initdb_target_dir: &Utf8Path,
5586 0 : pg_version: u32,
5587 0 : cancel: &CancellationToken,
5588 0 : ) -> Result<(), InitdbError> {
5589 0 : let initdb_bin_path = conf
5590 0 : .pg_bin_dir(pg_version)
5591 0 : .map_err(InitdbError::Other)?
5592 0 : .join("initdb");
5593 0 : let initdb_lib_dir = conf.pg_lib_dir(pg_version).map_err(InitdbError::Other)?;
5594 0 : info!(
5595 0 : "running {} in {}, libdir: {}",
5596 : initdb_bin_path, initdb_target_dir, initdb_lib_dir,
5597 : );
5598 :
5599 0 : let _permit = {
5600 0 : let _timer = INITDB_SEMAPHORE_ACQUISITION_TIME.start_timer();
5601 0 : INIT_DB_SEMAPHORE.acquire().await
5602 : };
5603 :
5604 0 : CONCURRENT_INITDBS.inc();
5605 0 : scopeguard::defer! {
5606 0 : CONCURRENT_INITDBS.dec();
5607 0 : }
5608 0 :
5609 0 : let _timer = INITDB_RUN_TIME.start_timer();
5610 0 : let res = postgres_initdb::do_run_initdb(postgres_initdb::RunInitdbArgs {
5611 0 : superuser: &conf.superuser,
5612 0 : locale: &conf.locale,
5613 0 : initdb_bin: &initdb_bin_path,
5614 0 : pg_version,
5615 0 : library_search_path: &initdb_lib_dir,
5616 0 : pgdata: initdb_target_dir,
5617 0 : })
5618 0 : .await
5619 0 : .map_err(InitdbError::Inner);
5620 0 :
5621 0 : // This isn't true cancellation support, see above. Still return an error to
5622 0 : // excercise the cancellation code path.
5623 0 : if cancel.is_cancelled() {
5624 0 : return Err(InitdbError::Cancelled);
5625 0 : }
5626 0 :
5627 0 : res
5628 0 : }
5629 :
5630 : /// Dump contents of a layer file to stdout.
5631 0 : pub async fn dump_layerfile_from_path(
5632 0 : path: &Utf8Path,
5633 0 : verbose: bool,
5634 0 : ctx: &RequestContext,
5635 0 : ) -> anyhow::Result<()> {
5636 : use std::os::unix::fs::FileExt;
5637 :
5638 : // All layer files start with a two-byte "magic" value, to identify the kind of
5639 : // file.
5640 0 : let file = File::open(path)?;
5641 0 : let mut header_buf = [0u8; 2];
5642 0 : file.read_exact_at(&mut header_buf, 0)?;
5643 :
5644 0 : match u16::from_be_bytes(header_buf) {
5645 : crate::IMAGE_FILE_MAGIC => {
5646 0 : ImageLayer::new_for_path(path, file)?
5647 0 : .dump(verbose, ctx)
5648 0 : .await?
5649 : }
5650 : crate::DELTA_FILE_MAGIC => {
5651 0 : DeltaLayer::new_for_path(path, file)?
5652 0 : .dump(verbose, ctx)
5653 0 : .await?
5654 : }
5655 0 : magic => bail!("unrecognized magic identifier: {:?}", magic),
5656 : }
5657 :
5658 0 : Ok(())
5659 0 : }
5660 :
5661 : #[cfg(test)]
5662 : pub(crate) mod harness {
5663 : use bytes::{Bytes, BytesMut};
5664 : use hex_literal::hex;
5665 : use once_cell::sync::OnceCell;
5666 : use pageserver_api::key::Key;
5667 : use pageserver_api::models::ShardParameters;
5668 : use pageserver_api::record::NeonWalRecord;
5669 : use pageserver_api::shard::ShardIndex;
5670 : use utils::id::TenantId;
5671 : use utils::logging;
5672 :
5673 : use super::*;
5674 : use crate::deletion_queue::mock::MockDeletionQueue;
5675 : use crate::l0_flush::L0FlushConfig;
5676 : use crate::walredo::apply_neon;
5677 :
5678 : pub const TIMELINE_ID: TimelineId =
5679 : TimelineId::from_array(hex!("11223344556677881122334455667788"));
5680 : pub const NEW_TIMELINE_ID: TimelineId =
5681 : TimelineId::from_array(hex!("AA223344556677881122334455667788"));
5682 :
5683 : /// Convenience function to create a page image with given string as the only content
5684 10057531 : pub fn test_img(s: &str) -> Bytes {
5685 10057531 : let mut buf = BytesMut::new();
5686 10057531 : buf.extend_from_slice(s.as_bytes());
5687 10057531 : buf.resize(64, 0);
5688 10057531 :
5689 10057531 : buf.freeze()
5690 10057531 : }
5691 :
5692 : pub struct TenantHarness {
5693 : pub conf: &'static PageServerConf,
5694 : pub tenant_conf: pageserver_api::models::TenantConfig,
5695 : pub tenant_shard_id: TenantShardId,
5696 : pub generation: Generation,
5697 : pub shard: ShardIndex,
5698 : pub remote_storage: GenericRemoteStorage,
5699 : pub remote_fs_dir: Utf8PathBuf,
5700 : pub deletion_queue: MockDeletionQueue,
5701 : }
5702 :
5703 : static LOG_HANDLE: OnceCell<()> = OnceCell::new();
5704 :
5705 500 : pub(crate) fn setup_logging() {
5706 500 : LOG_HANDLE.get_or_init(|| {
5707 476 : logging::init(
5708 476 : logging::LogFormat::Test,
5709 476 : // enable it in case the tests exercise code paths that use
5710 476 : // debug_assert_current_span_has_tenant_and_timeline_id
5711 476 : logging::TracingErrorLayerEnablement::EnableWithRustLogFilter,
5712 476 : logging::Output::Stdout,
5713 476 : )
5714 476 : .expect("Failed to init test logging");
5715 500 : });
5716 500 : }
5717 :
5718 : impl TenantHarness {
5719 452 : pub async fn create_custom(
5720 452 : test_name: &'static str,
5721 452 : tenant_conf: pageserver_api::models::TenantConfig,
5722 452 : tenant_id: TenantId,
5723 452 : shard_identity: ShardIdentity,
5724 452 : generation: Generation,
5725 452 : ) -> anyhow::Result<Self> {
5726 452 : setup_logging();
5727 452 :
5728 452 : let repo_dir = PageServerConf::test_repo_dir(test_name);
5729 452 : let _ = fs::remove_dir_all(&repo_dir);
5730 452 : fs::create_dir_all(&repo_dir)?;
5731 :
5732 452 : let conf = PageServerConf::dummy_conf(repo_dir);
5733 452 : // Make a static copy of the config. This can never be free'd, but that's
5734 452 : // OK in a test.
5735 452 : let conf: &'static PageServerConf = Box::leak(Box::new(conf));
5736 452 :
5737 452 : let shard = shard_identity.shard_index();
5738 452 : let tenant_shard_id = TenantShardId {
5739 452 : tenant_id,
5740 452 : shard_number: shard.shard_number,
5741 452 : shard_count: shard.shard_count,
5742 452 : };
5743 452 : fs::create_dir_all(conf.tenant_path(&tenant_shard_id))?;
5744 452 : fs::create_dir_all(conf.timelines_path(&tenant_shard_id))?;
5745 :
5746 : use remote_storage::{RemoteStorageConfig, RemoteStorageKind};
5747 452 : let remote_fs_dir = conf.workdir.join("localfs");
5748 452 : std::fs::create_dir_all(&remote_fs_dir).unwrap();
5749 452 : let config = RemoteStorageConfig {
5750 452 : storage: RemoteStorageKind::LocalFs {
5751 452 : local_path: remote_fs_dir.clone(),
5752 452 : },
5753 452 : timeout: RemoteStorageConfig::DEFAULT_TIMEOUT,
5754 452 : small_timeout: RemoteStorageConfig::DEFAULT_SMALL_TIMEOUT,
5755 452 : };
5756 452 : let remote_storage = GenericRemoteStorage::from_config(&config).await.unwrap();
5757 452 : let deletion_queue = MockDeletionQueue::new(Some(remote_storage.clone()));
5758 452 :
5759 452 : Ok(Self {
5760 452 : conf,
5761 452 : tenant_conf,
5762 452 : tenant_shard_id,
5763 452 : generation,
5764 452 : shard,
5765 452 : remote_storage,
5766 452 : remote_fs_dir,
5767 452 : deletion_queue,
5768 452 : })
5769 452 : }
5770 :
5771 428 : pub async fn create(test_name: &'static str) -> anyhow::Result<Self> {
5772 428 : // Disable automatic GC and compaction to make the unit tests more deterministic.
5773 428 : // The tests perform them manually if needed.
5774 428 : let tenant_conf = pageserver_api::models::TenantConfig {
5775 428 : gc_period: Some(Duration::ZERO),
5776 428 : compaction_period: Some(Duration::ZERO),
5777 428 : ..Default::default()
5778 428 : };
5779 428 : let tenant_id = TenantId::generate();
5780 428 : let shard = ShardIdentity::unsharded();
5781 428 : Self::create_custom(
5782 428 : test_name,
5783 428 : tenant_conf,
5784 428 : tenant_id,
5785 428 : shard,
5786 428 : Generation::new(0xdeadbeef),
5787 428 : )
5788 428 : .await
5789 428 : }
5790 :
5791 40 : pub fn span(&self) -> tracing::Span {
5792 40 : info_span!("TenantHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
5793 40 : }
5794 :
5795 452 : pub(crate) async fn load(&self) -> (Arc<Tenant>, RequestContext) {
5796 452 : let ctx = RequestContext::new(TaskKind::UnitTest, DownloadBehavior::Error)
5797 452 : .with_scope_unit_test();
5798 452 : (
5799 452 : self.do_try_load(&ctx)
5800 452 : .await
5801 452 : .expect("failed to load test tenant"),
5802 452 : ctx,
5803 452 : )
5804 452 : }
5805 :
5806 : #[instrument(skip_all, fields(tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug()))]
5807 : pub(crate) async fn do_try_load(
5808 : &self,
5809 : ctx: &RequestContext,
5810 : ) -> anyhow::Result<Arc<Tenant>> {
5811 : let walredo_mgr = Arc::new(WalRedoManager::from(TestRedoManager));
5812 :
5813 : let tenant = Arc::new(Tenant::new(
5814 : TenantState::Attaching,
5815 : self.conf,
5816 : AttachedTenantConf::try_from(LocationConf::attached_single(
5817 : self.tenant_conf.clone(),
5818 : self.generation,
5819 : &ShardParameters::default(),
5820 : ))
5821 : .unwrap(),
5822 : // This is a legacy/test code path: sharding isn't supported here.
5823 : ShardIdentity::unsharded(),
5824 : Some(walredo_mgr),
5825 : self.tenant_shard_id,
5826 : self.remote_storage.clone(),
5827 : self.deletion_queue.new_client(),
5828 : // TODO: ideally we should run all unit tests with both configs
5829 : L0FlushGlobalState::new(L0FlushConfig::default()),
5830 : ));
5831 :
5832 : let preload = tenant
5833 : .preload(&self.remote_storage, CancellationToken::new())
5834 : .await?;
5835 : tenant.attach(Some(preload), ctx).await?;
5836 :
5837 : tenant.state.send_replace(TenantState::Active);
5838 : for timeline in tenant.timelines.lock().unwrap().values() {
5839 : timeline.set_state(TimelineState::Active);
5840 : }
5841 : Ok(tenant)
5842 : }
5843 :
5844 4 : pub fn timeline_path(&self, timeline_id: &TimelineId) -> Utf8PathBuf {
5845 4 : self.conf.timeline_path(&self.tenant_shard_id, timeline_id)
5846 4 : }
5847 : }
5848 :
5849 : // Mock WAL redo manager that doesn't do much
5850 : pub(crate) struct TestRedoManager;
5851 :
5852 : impl TestRedoManager {
5853 : /// # Cancel-Safety
5854 : ///
5855 : /// This method is cancellation-safe.
5856 1676 : pub async fn request_redo(
5857 1676 : &self,
5858 1676 : key: Key,
5859 1676 : lsn: Lsn,
5860 1676 : base_img: Option<(Lsn, Bytes)>,
5861 1676 : records: Vec<(Lsn, NeonWalRecord)>,
5862 1676 : _pg_version: u32,
5863 1676 : ) -> Result<Bytes, walredo::Error> {
5864 2472 : let records_neon = records.iter().all(|r| apply_neon::can_apply_in_neon(&r.1));
5865 1676 : if records_neon {
5866 : // For Neon wal records, we can decode without spawning postgres, so do so.
5867 1676 : let mut page = match (base_img, records.first()) {
5868 1536 : (Some((_lsn, img)), _) => {
5869 1536 : let mut page = BytesMut::new();
5870 1536 : page.extend_from_slice(&img);
5871 1536 : page
5872 : }
5873 140 : (_, Some((_lsn, rec))) if rec.will_init() => BytesMut::new(),
5874 : _ => {
5875 0 : panic!("Neon WAL redo requires base image or will init record");
5876 : }
5877 : };
5878 :
5879 4148 : for (record_lsn, record) in records {
5880 2472 : apply_neon::apply_in_neon(&record, record_lsn, key, &mut page)?;
5881 : }
5882 1676 : Ok(page.freeze())
5883 : } else {
5884 : // We never spawn a postgres walredo process in unit tests: just log what we might have done.
5885 0 : let s = format!(
5886 0 : "redo for {} to get to {}, with {} and {} records",
5887 0 : key,
5888 0 : lsn,
5889 0 : if base_img.is_some() {
5890 0 : "base image"
5891 : } else {
5892 0 : "no base image"
5893 : },
5894 0 : records.len()
5895 0 : );
5896 0 : println!("{s}");
5897 0 :
5898 0 : Ok(test_img(&s))
5899 : }
5900 1676 : }
5901 : }
5902 : }
5903 :
5904 : #[cfg(test)]
5905 : mod tests {
5906 : use std::collections::{BTreeMap, BTreeSet};
5907 :
5908 : use bytes::{Bytes, BytesMut};
5909 : use hex_literal::hex;
5910 : use itertools::Itertools;
5911 : #[cfg(feature = "testing")]
5912 : use models::CompactLsnRange;
5913 : use pageserver_api::key::{AUX_KEY_PREFIX, Key, NON_INHERITED_RANGE, RELATION_SIZE_PREFIX};
5914 : use pageserver_api::keyspace::KeySpace;
5915 : use pageserver_api::models::{CompactionAlgorithm, CompactionAlgorithmSettings};
5916 : #[cfg(feature = "testing")]
5917 : use pageserver_api::record::NeonWalRecord;
5918 : use pageserver_api::value::Value;
5919 : use pageserver_compaction::helpers::overlaps_with;
5920 : use rand::{Rng, thread_rng};
5921 : use storage_layer::{IoConcurrency, PersistentLayerKey};
5922 : use tests::storage_layer::ValuesReconstructState;
5923 : use tests::timeline::{GetVectoredError, ShutdownMode};
5924 : #[cfg(feature = "testing")]
5925 : use timeline::GcInfo;
5926 : #[cfg(feature = "testing")]
5927 : use timeline::InMemoryLayerTestDesc;
5928 : #[cfg(feature = "testing")]
5929 : use timeline::compaction::{KeyHistoryRetention, KeyLogAtLsn};
5930 : use timeline::{CompactOptions, DeltaLayerTestDesc};
5931 : use utils::id::TenantId;
5932 :
5933 : use super::*;
5934 : use crate::DEFAULT_PG_VERSION;
5935 : use crate::keyspace::KeySpaceAccum;
5936 : use crate::tenant::harness::*;
5937 : use crate::tenant::timeline::CompactFlags;
5938 :
5939 : static TEST_KEY: Lazy<Key> =
5940 36 : Lazy::new(|| Key::from_slice(&hex!("010000000033333333444444445500000001")));
5941 :
5942 : #[tokio::test]
5943 4 : async fn test_basic() -> anyhow::Result<()> {
5944 4 : let (tenant, ctx) = TenantHarness::create("test_basic").await?.load().await;
5945 4 : let tline = tenant
5946 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
5947 4 : .await?;
5948 4 :
5949 4 : let mut writer = tline.writer().await;
5950 4 : writer
5951 4 : .put(
5952 4 : *TEST_KEY,
5953 4 : Lsn(0x10),
5954 4 : &Value::Image(test_img("foo at 0x10")),
5955 4 : &ctx,
5956 4 : )
5957 4 : .await?;
5958 4 : writer.finish_write(Lsn(0x10));
5959 4 : drop(writer);
5960 4 :
5961 4 : let mut writer = tline.writer().await;
5962 4 : writer
5963 4 : .put(
5964 4 : *TEST_KEY,
5965 4 : Lsn(0x20),
5966 4 : &Value::Image(test_img("foo at 0x20")),
5967 4 : &ctx,
5968 4 : )
5969 4 : .await?;
5970 4 : writer.finish_write(Lsn(0x20));
5971 4 : drop(writer);
5972 4 :
5973 4 : assert_eq!(
5974 4 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
5975 4 : test_img("foo at 0x10")
5976 4 : );
5977 4 : assert_eq!(
5978 4 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
5979 4 : test_img("foo at 0x10")
5980 4 : );
5981 4 : assert_eq!(
5982 4 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
5983 4 : test_img("foo at 0x20")
5984 4 : );
5985 4 :
5986 4 : Ok(())
5987 4 : }
5988 :
5989 : #[tokio::test]
5990 4 : async fn no_duplicate_timelines() -> anyhow::Result<()> {
5991 4 : let (tenant, ctx) = TenantHarness::create("no_duplicate_timelines")
5992 4 : .await?
5993 4 : .load()
5994 4 : .await;
5995 4 : let _ = tenant
5996 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
5997 4 : .await?;
5998 4 :
5999 4 : match tenant
6000 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6001 4 : .await
6002 4 : {
6003 4 : Ok(_) => panic!("duplicate timeline creation should fail"),
6004 4 : Err(e) => assert_eq!(
6005 4 : e.to_string(),
6006 4 : "timeline already exists with different parameters".to_string()
6007 4 : ),
6008 4 : }
6009 4 :
6010 4 : Ok(())
6011 4 : }
6012 :
6013 : /// Convenience function to create a page image with given string as the only content
6014 20 : pub fn test_value(s: &str) -> Value {
6015 20 : let mut buf = BytesMut::new();
6016 20 : buf.extend_from_slice(s.as_bytes());
6017 20 : Value::Image(buf.freeze())
6018 20 : }
6019 :
6020 : ///
6021 : /// Test branch creation
6022 : ///
6023 : #[tokio::test]
6024 4 : async fn test_branch() -> anyhow::Result<()> {
6025 4 : use std::str::from_utf8;
6026 4 :
6027 4 : let (tenant, ctx) = TenantHarness::create("test_branch").await?.load().await;
6028 4 : let tline = tenant
6029 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6030 4 : .await?;
6031 4 : let mut writer = tline.writer().await;
6032 4 :
6033 4 : #[allow(non_snake_case)]
6034 4 : let TEST_KEY_A: Key = Key::from_hex("110000000033333333444444445500000001").unwrap();
6035 4 : #[allow(non_snake_case)]
6036 4 : let TEST_KEY_B: Key = Key::from_hex("110000000033333333444444445500000002").unwrap();
6037 4 :
6038 4 : // Insert a value on the timeline
6039 4 : writer
6040 4 : .put(TEST_KEY_A, Lsn(0x20), &test_value("foo at 0x20"), &ctx)
6041 4 : .await?;
6042 4 : writer
6043 4 : .put(TEST_KEY_B, Lsn(0x20), &test_value("foobar at 0x20"), &ctx)
6044 4 : .await?;
6045 4 : writer.finish_write(Lsn(0x20));
6046 4 :
6047 4 : writer
6048 4 : .put(TEST_KEY_A, Lsn(0x30), &test_value("foo at 0x30"), &ctx)
6049 4 : .await?;
6050 4 : writer.finish_write(Lsn(0x30));
6051 4 : writer
6052 4 : .put(TEST_KEY_A, Lsn(0x40), &test_value("foo at 0x40"), &ctx)
6053 4 : .await?;
6054 4 : writer.finish_write(Lsn(0x40));
6055 4 :
6056 4 : //assert_current_logical_size(&tline, Lsn(0x40));
6057 4 :
6058 4 : // Branch the history, modify relation differently on the new timeline
6059 4 : tenant
6060 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x30)), &ctx)
6061 4 : .await?;
6062 4 : let newtline = tenant
6063 4 : .get_timeline(NEW_TIMELINE_ID, true)
6064 4 : .expect("Should have a local timeline");
6065 4 : let mut new_writer = newtline.writer().await;
6066 4 : new_writer
6067 4 : .put(TEST_KEY_A, Lsn(0x40), &test_value("bar at 0x40"), &ctx)
6068 4 : .await?;
6069 4 : new_writer.finish_write(Lsn(0x40));
6070 4 :
6071 4 : // Check page contents on both branches
6072 4 : assert_eq!(
6073 4 : from_utf8(&tline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
6074 4 : "foo at 0x40"
6075 4 : );
6076 4 : assert_eq!(
6077 4 : from_utf8(&newtline.get(TEST_KEY_A, Lsn(0x40), &ctx).await?)?,
6078 4 : "bar at 0x40"
6079 4 : );
6080 4 : assert_eq!(
6081 4 : from_utf8(&newtline.get(TEST_KEY_B, Lsn(0x40), &ctx).await?)?,
6082 4 : "foobar at 0x20"
6083 4 : );
6084 4 :
6085 4 : //assert_current_logical_size(&tline, Lsn(0x40));
6086 4 :
6087 4 : Ok(())
6088 4 : }
6089 :
6090 40 : async fn make_some_layers(
6091 40 : tline: &Timeline,
6092 40 : start_lsn: Lsn,
6093 40 : ctx: &RequestContext,
6094 40 : ) -> anyhow::Result<()> {
6095 40 : let mut lsn = start_lsn;
6096 : {
6097 40 : let mut writer = tline.writer().await;
6098 : // Create a relation on the timeline
6099 40 : writer
6100 40 : .put(
6101 40 : *TEST_KEY,
6102 40 : lsn,
6103 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6104 40 : ctx,
6105 40 : )
6106 40 : .await?;
6107 40 : writer.finish_write(lsn);
6108 40 : lsn += 0x10;
6109 40 : writer
6110 40 : .put(
6111 40 : *TEST_KEY,
6112 40 : lsn,
6113 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6114 40 : ctx,
6115 40 : )
6116 40 : .await?;
6117 40 : writer.finish_write(lsn);
6118 40 : lsn += 0x10;
6119 40 : }
6120 40 : tline.freeze_and_flush().await?;
6121 : {
6122 40 : let mut writer = tline.writer().await;
6123 40 : writer
6124 40 : .put(
6125 40 : *TEST_KEY,
6126 40 : lsn,
6127 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6128 40 : ctx,
6129 40 : )
6130 40 : .await?;
6131 40 : writer.finish_write(lsn);
6132 40 : lsn += 0x10;
6133 40 : writer
6134 40 : .put(
6135 40 : *TEST_KEY,
6136 40 : lsn,
6137 40 : &Value::Image(test_img(&format!("foo at {}", lsn))),
6138 40 : ctx,
6139 40 : )
6140 40 : .await?;
6141 40 : writer.finish_write(lsn);
6142 40 : }
6143 40 : tline.freeze_and_flush().await.map_err(|e| e.into())
6144 40 : }
6145 :
6146 : #[tokio::test(start_paused = true)]
6147 4 : async fn test_prohibit_branch_creation_on_garbage_collected_data() -> anyhow::Result<()> {
6148 4 : let (tenant, ctx) =
6149 4 : TenantHarness::create("test_prohibit_branch_creation_on_garbage_collected_data")
6150 4 : .await?
6151 4 : .load()
6152 4 : .await;
6153 4 : // Advance to the lsn lease deadline so that GC is not blocked by
6154 4 : // initial transition into AttachedSingle.
6155 4 : tokio::time::advance(tenant.get_lsn_lease_length()).await;
6156 4 : tokio::time::resume();
6157 4 : let tline = tenant
6158 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6159 4 : .await?;
6160 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6161 4 :
6162 4 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
6163 4 : // FIXME: this doesn't actually remove any layer currently, given how the flushing
6164 4 : // and compaction works. But it does set the 'cutoff' point so that the cross check
6165 4 : // below should fail.
6166 4 : tenant
6167 4 : .gc_iteration(
6168 4 : Some(TIMELINE_ID),
6169 4 : 0x10,
6170 4 : Duration::ZERO,
6171 4 : &CancellationToken::new(),
6172 4 : &ctx,
6173 4 : )
6174 4 : .await?;
6175 4 :
6176 4 : // try to branch at lsn 25, should fail because we already garbage collected the data
6177 4 : match tenant
6178 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
6179 4 : .await
6180 4 : {
6181 4 : Ok(_) => panic!("branching should have failed"),
6182 4 : Err(err) => {
6183 4 : let CreateTimelineError::AncestorLsn(err) = err else {
6184 4 : panic!("wrong error type")
6185 4 : };
6186 4 : assert!(err.to_string().contains("invalid branch start lsn"));
6187 4 : assert!(
6188 4 : err.source()
6189 4 : .unwrap()
6190 4 : .to_string()
6191 4 : .contains("we might've already garbage collected needed data")
6192 4 : )
6193 4 : }
6194 4 : }
6195 4 :
6196 4 : Ok(())
6197 4 : }
6198 :
6199 : #[tokio::test]
6200 4 : async fn test_prohibit_branch_creation_on_pre_initdb_lsn() -> anyhow::Result<()> {
6201 4 : let (tenant, ctx) =
6202 4 : TenantHarness::create("test_prohibit_branch_creation_on_pre_initdb_lsn")
6203 4 : .await?
6204 4 : .load()
6205 4 : .await;
6206 4 :
6207 4 : let tline = tenant
6208 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x50), DEFAULT_PG_VERSION, &ctx)
6209 4 : .await?;
6210 4 : // try to branch at lsn 0x25, should fail because initdb lsn is 0x50
6211 4 : match tenant
6212 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x25)), &ctx)
6213 4 : .await
6214 4 : {
6215 4 : Ok(_) => panic!("branching should have failed"),
6216 4 : Err(err) => {
6217 4 : let CreateTimelineError::AncestorLsn(err) = err else {
6218 4 : panic!("wrong error type");
6219 4 : };
6220 4 : assert!(&err.to_string().contains("invalid branch start lsn"));
6221 4 : assert!(
6222 4 : &err.source()
6223 4 : .unwrap()
6224 4 : .to_string()
6225 4 : .contains("is earlier than latest GC cutoff")
6226 4 : );
6227 4 : }
6228 4 : }
6229 4 :
6230 4 : Ok(())
6231 4 : }
6232 :
6233 : /*
6234 : // FIXME: This currently fails to error out. Calling GC doesn't currently
6235 : // remove the old value, we'd need to work a little harder
6236 : #[tokio::test]
6237 : async fn test_prohibit_get_for_garbage_collected_data() -> anyhow::Result<()> {
6238 : let repo =
6239 : RepoHarness::create("test_prohibit_get_for_garbage_collected_data")?
6240 : .load();
6241 :
6242 : let tline = repo.create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION)?;
6243 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6244 :
6245 : repo.gc_iteration(Some(TIMELINE_ID), 0x10, Duration::ZERO)?;
6246 : let applied_gc_cutoff_lsn = tline.get_applied_gc_cutoff_lsn();
6247 : assert!(*applied_gc_cutoff_lsn > Lsn(0x25));
6248 : match tline.get(*TEST_KEY, Lsn(0x25)) {
6249 : Ok(_) => panic!("request for page should have failed"),
6250 : Err(err) => assert!(err.to_string().contains("not found at")),
6251 : }
6252 : Ok(())
6253 : }
6254 : */
6255 :
6256 : #[tokio::test]
6257 4 : async fn test_get_branchpoints_from_an_inactive_timeline() -> anyhow::Result<()> {
6258 4 : let (tenant, ctx) =
6259 4 : TenantHarness::create("test_get_branchpoints_from_an_inactive_timeline")
6260 4 : .await?
6261 4 : .load()
6262 4 : .await;
6263 4 : let tline = tenant
6264 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6265 4 : .await?;
6266 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6267 4 :
6268 4 : tenant
6269 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6270 4 : .await?;
6271 4 : let newtline = tenant
6272 4 : .get_timeline(NEW_TIMELINE_ID, true)
6273 4 : .expect("Should have a local timeline");
6274 4 :
6275 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6276 4 :
6277 4 : tline.set_broken("test".to_owned());
6278 4 :
6279 4 : tenant
6280 4 : .gc_iteration(
6281 4 : Some(TIMELINE_ID),
6282 4 : 0x10,
6283 4 : Duration::ZERO,
6284 4 : &CancellationToken::new(),
6285 4 : &ctx,
6286 4 : )
6287 4 : .await?;
6288 4 :
6289 4 : // The branchpoints should contain all timelines, even ones marked
6290 4 : // as Broken.
6291 4 : {
6292 4 : let branchpoints = &tline.gc_info.read().unwrap().retain_lsns;
6293 4 : assert_eq!(branchpoints.len(), 1);
6294 4 : assert_eq!(
6295 4 : branchpoints[0],
6296 4 : (Lsn(0x40), NEW_TIMELINE_ID, MaybeOffloaded::No)
6297 4 : );
6298 4 : }
6299 4 :
6300 4 : // You can read the key from the child branch even though the parent is
6301 4 : // Broken, as long as you don't need to access data from the parent.
6302 4 : assert_eq!(
6303 4 : newtline.get(*TEST_KEY, Lsn(0x70), &ctx).await?,
6304 4 : test_img(&format!("foo at {}", Lsn(0x70)))
6305 4 : );
6306 4 :
6307 4 : // This needs to traverse to the parent, and fails.
6308 4 : let err = newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await.unwrap_err();
6309 4 : assert!(
6310 4 : err.to_string().starts_with(&format!(
6311 4 : "bad state on timeline {}: Broken",
6312 4 : tline.timeline_id
6313 4 : )),
6314 4 : "{err}"
6315 4 : );
6316 4 :
6317 4 : Ok(())
6318 4 : }
6319 :
6320 : #[tokio::test]
6321 4 : async fn test_retain_data_in_parent_which_is_needed_for_child() -> anyhow::Result<()> {
6322 4 : let (tenant, ctx) =
6323 4 : TenantHarness::create("test_retain_data_in_parent_which_is_needed_for_child")
6324 4 : .await?
6325 4 : .load()
6326 4 : .await;
6327 4 : let tline = tenant
6328 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6329 4 : .await?;
6330 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6331 4 :
6332 4 : tenant
6333 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6334 4 : .await?;
6335 4 : let newtline = tenant
6336 4 : .get_timeline(NEW_TIMELINE_ID, true)
6337 4 : .expect("Should have a local timeline");
6338 4 : // this removes layers before lsn 40 (50 minus 10), so there are two remaining layers, image and delta for 31-50
6339 4 : tenant
6340 4 : .gc_iteration(
6341 4 : Some(TIMELINE_ID),
6342 4 : 0x10,
6343 4 : Duration::ZERO,
6344 4 : &CancellationToken::new(),
6345 4 : &ctx,
6346 4 : )
6347 4 : .await?;
6348 4 : assert!(newtline.get(*TEST_KEY, Lsn(0x25), &ctx).await.is_ok());
6349 4 :
6350 4 : Ok(())
6351 4 : }
6352 : #[tokio::test]
6353 4 : async fn test_parent_keeps_data_forever_after_branching() -> anyhow::Result<()> {
6354 4 : let (tenant, ctx) = TenantHarness::create("test_parent_keeps_data_forever_after_branching")
6355 4 : .await?
6356 4 : .load()
6357 4 : .await;
6358 4 : let tline = tenant
6359 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6360 4 : .await?;
6361 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6362 4 :
6363 4 : tenant
6364 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6365 4 : .await?;
6366 4 : let newtline = tenant
6367 4 : .get_timeline(NEW_TIMELINE_ID, true)
6368 4 : .expect("Should have a local timeline");
6369 4 :
6370 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6371 4 :
6372 4 : // run gc on parent
6373 4 : tenant
6374 4 : .gc_iteration(
6375 4 : Some(TIMELINE_ID),
6376 4 : 0x10,
6377 4 : Duration::ZERO,
6378 4 : &CancellationToken::new(),
6379 4 : &ctx,
6380 4 : )
6381 4 : .await?;
6382 4 :
6383 4 : // Check that the data is still accessible on the branch.
6384 4 : assert_eq!(
6385 4 : newtline.get(*TEST_KEY, Lsn(0x50), &ctx).await?,
6386 4 : test_img(&format!("foo at {}", Lsn(0x40)))
6387 4 : );
6388 4 :
6389 4 : Ok(())
6390 4 : }
6391 :
6392 : #[tokio::test]
6393 4 : async fn timeline_load() -> anyhow::Result<()> {
6394 4 : const TEST_NAME: &str = "timeline_load";
6395 4 : let harness = TenantHarness::create(TEST_NAME).await?;
6396 4 : {
6397 4 : let (tenant, ctx) = harness.load().await;
6398 4 : let tline = tenant
6399 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x7000), DEFAULT_PG_VERSION, &ctx)
6400 4 : .await?;
6401 4 : make_some_layers(tline.as_ref(), Lsn(0x8000), &ctx).await?;
6402 4 : // so that all uploads finish & we can call harness.load() below again
6403 4 : tenant
6404 4 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
6405 4 : .instrument(harness.span())
6406 4 : .await
6407 4 : .ok()
6408 4 : .unwrap();
6409 4 : }
6410 4 :
6411 4 : let (tenant, _ctx) = harness.load().await;
6412 4 : tenant
6413 4 : .get_timeline(TIMELINE_ID, true)
6414 4 : .expect("cannot load timeline");
6415 4 :
6416 4 : Ok(())
6417 4 : }
6418 :
6419 : #[tokio::test]
6420 4 : async fn timeline_load_with_ancestor() -> anyhow::Result<()> {
6421 4 : const TEST_NAME: &str = "timeline_load_with_ancestor";
6422 4 : let harness = TenantHarness::create(TEST_NAME).await?;
6423 4 : // create two timelines
6424 4 : {
6425 4 : let (tenant, ctx) = harness.load().await;
6426 4 : let tline = tenant
6427 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6428 4 : .await?;
6429 4 :
6430 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6431 4 :
6432 4 : let child_tline = tenant
6433 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(Lsn(0x40)), &ctx)
6434 4 : .await?;
6435 4 : child_tline.set_state(TimelineState::Active);
6436 4 :
6437 4 : let newtline = tenant
6438 4 : .get_timeline(NEW_TIMELINE_ID, true)
6439 4 : .expect("Should have a local timeline");
6440 4 :
6441 4 : make_some_layers(newtline.as_ref(), Lsn(0x60), &ctx).await?;
6442 4 :
6443 4 : // so that all uploads finish & we can call harness.load() below again
6444 4 : tenant
6445 4 : .shutdown(Default::default(), ShutdownMode::FreezeAndFlush)
6446 4 : .instrument(harness.span())
6447 4 : .await
6448 4 : .ok()
6449 4 : .unwrap();
6450 4 : }
6451 4 :
6452 4 : // check that both of them are initially unloaded
6453 4 : let (tenant, _ctx) = harness.load().await;
6454 4 :
6455 4 : // check that both, child and ancestor are loaded
6456 4 : let _child_tline = tenant
6457 4 : .get_timeline(NEW_TIMELINE_ID, true)
6458 4 : .expect("cannot get child timeline loaded");
6459 4 :
6460 4 : let _ancestor_tline = tenant
6461 4 : .get_timeline(TIMELINE_ID, true)
6462 4 : .expect("cannot get ancestor timeline loaded");
6463 4 :
6464 4 : Ok(())
6465 4 : }
6466 :
6467 : #[tokio::test]
6468 4 : async fn delta_layer_dumping() -> anyhow::Result<()> {
6469 4 : use storage_layer::AsLayerDesc;
6470 4 : let (tenant, ctx) = TenantHarness::create("test_layer_dumping")
6471 4 : .await?
6472 4 : .load()
6473 4 : .await;
6474 4 : let tline = tenant
6475 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
6476 4 : .await?;
6477 4 : make_some_layers(tline.as_ref(), Lsn(0x20), &ctx).await?;
6478 4 :
6479 4 : let layer_map = tline.layers.read().await;
6480 4 : let level0_deltas = layer_map
6481 4 : .layer_map()?
6482 4 : .level0_deltas()
6483 4 : .iter()
6484 8 : .map(|desc| layer_map.get_from_desc(desc))
6485 4 : .collect::<Vec<_>>();
6486 4 :
6487 4 : assert!(!level0_deltas.is_empty());
6488 4 :
6489 12 : for delta in level0_deltas {
6490 4 : // Ensure we are dumping a delta layer here
6491 8 : assert!(delta.layer_desc().is_delta);
6492 8 : delta.dump(true, &ctx).await.unwrap();
6493 4 : }
6494 4 :
6495 4 : Ok(())
6496 4 : }
6497 :
6498 : #[tokio::test]
6499 4 : async fn test_images() -> anyhow::Result<()> {
6500 4 : let (tenant, ctx) = TenantHarness::create("test_images").await?.load().await;
6501 4 : let tline = tenant
6502 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6503 4 : .await?;
6504 4 :
6505 4 : let mut writer = tline.writer().await;
6506 4 : writer
6507 4 : .put(
6508 4 : *TEST_KEY,
6509 4 : Lsn(0x10),
6510 4 : &Value::Image(test_img("foo at 0x10")),
6511 4 : &ctx,
6512 4 : )
6513 4 : .await?;
6514 4 : writer.finish_write(Lsn(0x10));
6515 4 : drop(writer);
6516 4 :
6517 4 : tline.freeze_and_flush().await?;
6518 4 : tline
6519 4 : .compact(
6520 4 : &CancellationToken::new(),
6521 4 : CompactFlags::NoYield.into(),
6522 4 : &ctx,
6523 4 : )
6524 4 : .await?;
6525 4 :
6526 4 : let mut writer = tline.writer().await;
6527 4 : writer
6528 4 : .put(
6529 4 : *TEST_KEY,
6530 4 : Lsn(0x20),
6531 4 : &Value::Image(test_img("foo at 0x20")),
6532 4 : &ctx,
6533 4 : )
6534 4 : .await?;
6535 4 : writer.finish_write(Lsn(0x20));
6536 4 : drop(writer);
6537 4 :
6538 4 : tline.freeze_and_flush().await?;
6539 4 : tline
6540 4 : .compact(
6541 4 : &CancellationToken::new(),
6542 4 : CompactFlags::NoYield.into(),
6543 4 : &ctx,
6544 4 : )
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(0x30),
6552 4 : &Value::Image(test_img("foo at 0x30")),
6553 4 : &ctx,
6554 4 : )
6555 4 : .await?;
6556 4 : writer.finish_write(Lsn(0x30));
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(0x40),
6573 4 : &Value::Image(test_img("foo at 0x40")),
6574 4 : &ctx,
6575 4 : )
6576 4 : .await?;
6577 4 : writer.finish_write(Lsn(0x40));
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 : assert_eq!(
6590 4 : tline.get(*TEST_KEY, Lsn(0x10), &ctx).await?,
6591 4 : test_img("foo at 0x10")
6592 4 : );
6593 4 : assert_eq!(
6594 4 : tline.get(*TEST_KEY, Lsn(0x1f), &ctx).await?,
6595 4 : test_img("foo at 0x10")
6596 4 : );
6597 4 : assert_eq!(
6598 4 : tline.get(*TEST_KEY, Lsn(0x20), &ctx).await?,
6599 4 : test_img("foo at 0x20")
6600 4 : );
6601 4 : assert_eq!(
6602 4 : tline.get(*TEST_KEY, Lsn(0x30), &ctx).await?,
6603 4 : test_img("foo at 0x30")
6604 4 : );
6605 4 : assert_eq!(
6606 4 : tline.get(*TEST_KEY, Lsn(0x40), &ctx).await?,
6607 4 : test_img("foo at 0x40")
6608 4 : );
6609 4 :
6610 4 : Ok(())
6611 4 : }
6612 :
6613 8 : async fn bulk_insert_compact_gc(
6614 8 : tenant: &Tenant,
6615 8 : timeline: &Arc<Timeline>,
6616 8 : ctx: &RequestContext,
6617 8 : lsn: Lsn,
6618 8 : repeat: usize,
6619 8 : key_count: usize,
6620 8 : ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
6621 8 : let compact = true;
6622 8 : bulk_insert_maybe_compact_gc(tenant, timeline, ctx, lsn, repeat, key_count, compact).await
6623 8 : }
6624 :
6625 16 : async fn bulk_insert_maybe_compact_gc(
6626 16 : tenant: &Tenant,
6627 16 : timeline: &Arc<Timeline>,
6628 16 : ctx: &RequestContext,
6629 16 : mut lsn: Lsn,
6630 16 : repeat: usize,
6631 16 : key_count: usize,
6632 16 : compact: bool,
6633 16 : ) -> anyhow::Result<HashMap<Key, BTreeSet<Lsn>>> {
6634 16 : let mut inserted: HashMap<Key, BTreeSet<Lsn>> = Default::default();
6635 16 :
6636 16 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6637 16 : let mut blknum = 0;
6638 16 :
6639 16 : // Enforce that key range is monotonously increasing
6640 16 : let mut keyspace = KeySpaceAccum::new();
6641 16 :
6642 16 : let cancel = CancellationToken::new();
6643 16 :
6644 16 : for _ in 0..repeat {
6645 800 : for _ in 0..key_count {
6646 8000000 : test_key.field6 = blknum;
6647 8000000 : let mut writer = timeline.writer().await;
6648 8000000 : writer
6649 8000000 : .put(
6650 8000000 : test_key,
6651 8000000 : lsn,
6652 8000000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
6653 8000000 : ctx,
6654 8000000 : )
6655 8000000 : .await?;
6656 8000000 : inserted.entry(test_key).or_default().insert(lsn);
6657 8000000 : writer.finish_write(lsn);
6658 8000000 : drop(writer);
6659 8000000 :
6660 8000000 : keyspace.add_key(test_key);
6661 8000000 :
6662 8000000 : lsn = Lsn(lsn.0 + 0x10);
6663 8000000 : blknum += 1;
6664 : }
6665 :
6666 800 : timeline.freeze_and_flush().await?;
6667 800 : if compact {
6668 : // this requires timeline to be &Arc<Timeline>
6669 400 : timeline
6670 400 : .compact(&cancel, CompactFlags::NoYield.into(), ctx)
6671 400 : .await?;
6672 400 : }
6673 :
6674 : // this doesn't really need to use the timeline_id target, but it is closer to what it
6675 : // originally was.
6676 800 : let res = tenant
6677 800 : .gc_iteration(Some(timeline.timeline_id), 0, Duration::ZERO, &cancel, ctx)
6678 800 : .await?;
6679 :
6680 800 : assert_eq!(res.layers_removed, 0, "this never removes anything");
6681 : }
6682 :
6683 16 : Ok(inserted)
6684 16 : }
6685 :
6686 : //
6687 : // Insert 1000 key-value pairs with increasing keys, flush, compact, GC.
6688 : // Repeat 50 times.
6689 : //
6690 : #[tokio::test]
6691 4 : async fn test_bulk_insert() -> anyhow::Result<()> {
6692 4 : let harness = TenantHarness::create("test_bulk_insert").await?;
6693 4 : let (tenant, ctx) = harness.load().await;
6694 4 : let tline = tenant
6695 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6696 4 : .await?;
6697 4 :
6698 4 : let lsn = Lsn(0x10);
6699 4 : bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
6700 4 :
6701 4 : Ok(())
6702 4 : }
6703 :
6704 : // Test the vectored get real implementation against a simple sequential implementation.
6705 : //
6706 : // The test generates a keyspace by repeatedly flushing the in-memory layer and compacting.
6707 : // Projected to 2D the key space looks like below. Lsn grows upwards on the Y axis and keys
6708 : // grow to the right on the X axis.
6709 : // [Delta]
6710 : // [Delta]
6711 : // [Delta]
6712 : // [Delta]
6713 : // ------------ Image ---------------
6714 : //
6715 : // After layer generation we pick the ranges to query as follows:
6716 : // 1. The beginning of each delta layer
6717 : // 2. At the seam between two adjacent delta layers
6718 : //
6719 : // There's one major downside to this test: delta layers only contains images,
6720 : // so the search can stop at the first delta layer and doesn't traverse any deeper.
6721 : #[tokio::test]
6722 4 : async fn test_get_vectored() -> anyhow::Result<()> {
6723 4 : let harness = TenantHarness::create("test_get_vectored").await?;
6724 4 : let (tenant, ctx) = harness.load().await;
6725 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6726 4 : let tline = tenant
6727 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
6728 4 : .await?;
6729 4 :
6730 4 : let lsn = Lsn(0x10);
6731 4 : let inserted = bulk_insert_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000).await?;
6732 4 :
6733 4 : let guard = tline.layers.read().await;
6734 4 : let lm = guard.layer_map()?;
6735 4 :
6736 4 : lm.dump(true, &ctx).await?;
6737 4 :
6738 4 : let mut reads = Vec::new();
6739 4 : let mut prev = None;
6740 24 : lm.iter_historic_layers().for_each(|desc| {
6741 24 : if !desc.is_delta() {
6742 4 : prev = Some(desc.clone());
6743 4 : return;
6744 20 : }
6745 20 :
6746 20 : let start = desc.key_range.start;
6747 20 : let end = desc
6748 20 : .key_range
6749 20 : .start
6750 20 : .add(Timeline::MAX_GET_VECTORED_KEYS.try_into().unwrap());
6751 20 : reads.push(KeySpace {
6752 20 : ranges: vec![start..end],
6753 20 : });
6754 4 :
6755 20 : if let Some(prev) = &prev {
6756 20 : if !prev.is_delta() {
6757 20 : return;
6758 4 : }
6759 0 :
6760 0 : let first_range = Key {
6761 0 : field6: prev.key_range.end.field6 - 4,
6762 0 : ..prev.key_range.end
6763 0 : }..prev.key_range.end;
6764 0 :
6765 0 : let second_range = desc.key_range.start..Key {
6766 0 : field6: desc.key_range.start.field6 + 4,
6767 0 : ..desc.key_range.start
6768 0 : };
6769 0 :
6770 0 : reads.push(KeySpace {
6771 0 : ranges: vec![first_range, second_range],
6772 0 : });
6773 4 : };
6774 4 :
6775 4 : prev = Some(desc.clone());
6776 24 : });
6777 4 :
6778 4 : drop(guard);
6779 4 :
6780 4 : // Pick a big LSN such that we query over all the changes.
6781 4 : let reads_lsn = Lsn(u64::MAX - 1);
6782 4 :
6783 24 : for read in reads {
6784 20 : info!("Doing vectored read on {:?}", read);
6785 4 :
6786 20 : let vectored_res = tline
6787 20 : .get_vectored_impl(
6788 20 : read.clone(),
6789 20 : reads_lsn,
6790 20 : &mut ValuesReconstructState::new(io_concurrency.clone()),
6791 20 : &ctx,
6792 20 : )
6793 20 : .await;
6794 4 :
6795 20 : let mut expected_lsns: HashMap<Key, Lsn> = Default::default();
6796 20 : let mut expect_missing = false;
6797 20 : let mut key = read.start().unwrap();
6798 660 : while key != read.end().unwrap() {
6799 640 : if let Some(lsns) = inserted.get(&key) {
6800 640 : let expected_lsn = lsns.iter().rfind(|lsn| **lsn <= reads_lsn);
6801 640 : match expected_lsn {
6802 640 : Some(lsn) => {
6803 640 : expected_lsns.insert(key, *lsn);
6804 640 : }
6805 4 : None => {
6806 4 : expect_missing = true;
6807 0 : break;
6808 4 : }
6809 4 : }
6810 4 : } else {
6811 4 : expect_missing = true;
6812 0 : break;
6813 4 : }
6814 4 :
6815 640 : key = key.next();
6816 4 : }
6817 4 :
6818 20 : if expect_missing {
6819 4 : assert!(matches!(vectored_res, Err(GetVectoredError::MissingKey(_))));
6820 4 : } else {
6821 640 : for (key, image) in vectored_res? {
6822 640 : let expected_lsn = expected_lsns.get(&key).expect("determined above");
6823 640 : let expected_image = test_img(&format!("{} at {}", key.field6, expected_lsn));
6824 640 : assert_eq!(image?, expected_image);
6825 4 : }
6826 4 : }
6827 4 : }
6828 4 :
6829 4 : Ok(())
6830 4 : }
6831 :
6832 : #[tokio::test]
6833 4 : async fn test_get_vectored_aux_files() -> anyhow::Result<()> {
6834 4 : let harness = TenantHarness::create("test_get_vectored_aux_files").await?;
6835 4 :
6836 4 : let (tenant, ctx) = harness.load().await;
6837 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6838 4 : let (tline, ctx) = tenant
6839 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
6840 4 : .await?;
6841 4 : let tline = tline.raw_timeline().unwrap();
6842 4 :
6843 4 : let mut modification = tline.begin_modification(Lsn(0x1000));
6844 4 : modification.put_file("foo/bar1", b"content1", &ctx).await?;
6845 4 : modification.set_lsn(Lsn(0x1008))?;
6846 4 : modification.put_file("foo/bar2", b"content2", &ctx).await?;
6847 4 : modification.commit(&ctx).await?;
6848 4 :
6849 4 : let child_timeline_id = TimelineId::generate();
6850 4 : tenant
6851 4 : .branch_timeline_test(
6852 4 : tline,
6853 4 : child_timeline_id,
6854 4 : Some(tline.get_last_record_lsn()),
6855 4 : &ctx,
6856 4 : )
6857 4 : .await?;
6858 4 :
6859 4 : let child_timeline = tenant
6860 4 : .get_timeline(child_timeline_id, true)
6861 4 : .expect("Should have the branched timeline");
6862 4 :
6863 4 : let aux_keyspace = KeySpace {
6864 4 : ranges: vec![NON_INHERITED_RANGE],
6865 4 : };
6866 4 : let read_lsn = child_timeline.get_last_record_lsn();
6867 4 :
6868 4 : let vectored_res = child_timeline
6869 4 : .get_vectored_impl(
6870 4 : aux_keyspace.clone(),
6871 4 : read_lsn,
6872 4 : &mut ValuesReconstructState::new(io_concurrency.clone()),
6873 4 : &ctx,
6874 4 : )
6875 4 : .await;
6876 4 :
6877 4 : let images = vectored_res?;
6878 4 : assert!(images.is_empty());
6879 4 : Ok(())
6880 4 : }
6881 :
6882 : // Test that vectored get handles layer gaps correctly
6883 : // by advancing into the next ancestor timeline if required.
6884 : //
6885 : // The test generates timelines that look like the diagram below.
6886 : // We leave a gap in one of the L1 layers at `gap_at_key` (`/` in the diagram).
6887 : // The reconstruct data for that key lies in the ancestor timeline (`X` in the diagram).
6888 : //
6889 : // ```
6890 : //-------------------------------+
6891 : // ... |
6892 : // [ L1 ] |
6893 : // [ / L1 ] | Child Timeline
6894 : // ... |
6895 : // ------------------------------+
6896 : // [ X L1 ] | Parent Timeline
6897 : // ------------------------------+
6898 : // ```
6899 : #[tokio::test]
6900 4 : async fn test_get_vectored_key_gap() -> anyhow::Result<()> {
6901 4 : let tenant_conf = pageserver_api::models::TenantConfig {
6902 4 : // Make compaction deterministic
6903 4 : gc_period: Some(Duration::ZERO),
6904 4 : compaction_period: Some(Duration::ZERO),
6905 4 : // Encourage creation of L1 layers
6906 4 : checkpoint_distance: Some(16 * 1024),
6907 4 : compaction_target_size: Some(8 * 1024),
6908 4 : ..Default::default()
6909 4 : };
6910 4 :
6911 4 : let harness = TenantHarness::create_custom(
6912 4 : "test_get_vectored_key_gap",
6913 4 : tenant_conf,
6914 4 : TenantId::generate(),
6915 4 : ShardIdentity::unsharded(),
6916 4 : Generation::new(0xdeadbeef),
6917 4 : )
6918 4 : .await?;
6919 4 : let (tenant, ctx) = harness.load().await;
6920 4 : let io_concurrency = IoConcurrency::spawn_for_test();
6921 4 :
6922 4 : let mut current_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
6923 4 : let gap_at_key = current_key.add(100);
6924 4 : let mut current_lsn = Lsn(0x10);
6925 4 :
6926 4 : const KEY_COUNT: usize = 10_000;
6927 4 :
6928 4 : let timeline_id = TimelineId::generate();
6929 4 : let current_timeline = tenant
6930 4 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
6931 4 : .await?;
6932 4 :
6933 4 : current_lsn += 0x100;
6934 4 :
6935 4 : let mut writer = current_timeline.writer().await;
6936 4 : writer
6937 4 : .put(
6938 4 : gap_at_key,
6939 4 : current_lsn,
6940 4 : &Value::Image(test_img(&format!("{} at {}", gap_at_key, current_lsn))),
6941 4 : &ctx,
6942 4 : )
6943 4 : .await?;
6944 4 : writer.finish_write(current_lsn);
6945 4 : drop(writer);
6946 4 :
6947 4 : let mut latest_lsns = HashMap::new();
6948 4 : latest_lsns.insert(gap_at_key, current_lsn);
6949 4 :
6950 4 : current_timeline.freeze_and_flush().await?;
6951 4 :
6952 4 : let child_timeline_id = TimelineId::generate();
6953 4 :
6954 4 : tenant
6955 4 : .branch_timeline_test(
6956 4 : ¤t_timeline,
6957 4 : child_timeline_id,
6958 4 : Some(current_lsn),
6959 4 : &ctx,
6960 4 : )
6961 4 : .await?;
6962 4 : let child_timeline = tenant
6963 4 : .get_timeline(child_timeline_id, true)
6964 4 : .expect("Should have the branched timeline");
6965 4 :
6966 40004 : for i in 0..KEY_COUNT {
6967 40000 : if current_key == gap_at_key {
6968 4 : current_key = current_key.next();
6969 4 : continue;
6970 39996 : }
6971 39996 :
6972 39996 : current_lsn += 0x10;
6973 4 :
6974 39996 : let mut writer = child_timeline.writer().await;
6975 39996 : writer
6976 39996 : .put(
6977 39996 : current_key,
6978 39996 : current_lsn,
6979 39996 : &Value::Image(test_img(&format!("{} at {}", current_key, current_lsn))),
6980 39996 : &ctx,
6981 39996 : )
6982 39996 : .await?;
6983 39996 : writer.finish_write(current_lsn);
6984 39996 : drop(writer);
6985 39996 :
6986 39996 : latest_lsns.insert(current_key, current_lsn);
6987 39996 : current_key = current_key.next();
6988 39996 :
6989 39996 : // Flush every now and then to encourage layer file creation.
6990 39996 : if i % 500 == 0 {
6991 80 : child_timeline.freeze_and_flush().await?;
6992 39916 : }
6993 4 : }
6994 4 :
6995 4 : child_timeline.freeze_and_flush().await?;
6996 4 : let mut flags = EnumSet::new();
6997 4 : flags.insert(CompactFlags::ForceRepartition);
6998 4 : flags.insert(CompactFlags::NoYield);
6999 4 : child_timeline
7000 4 : .compact(&CancellationToken::new(), flags, &ctx)
7001 4 : .await?;
7002 4 :
7003 4 : let key_near_end = {
7004 4 : let mut tmp = current_key;
7005 4 : tmp.field6 -= 10;
7006 4 : tmp
7007 4 : };
7008 4 :
7009 4 : let key_near_gap = {
7010 4 : let mut tmp = gap_at_key;
7011 4 : tmp.field6 -= 10;
7012 4 : tmp
7013 4 : };
7014 4 :
7015 4 : let read = KeySpace {
7016 4 : ranges: vec![key_near_gap..gap_at_key.next(), key_near_end..current_key],
7017 4 : };
7018 4 : let results = child_timeline
7019 4 : .get_vectored_impl(
7020 4 : read.clone(),
7021 4 : current_lsn,
7022 4 : &mut ValuesReconstructState::new(io_concurrency.clone()),
7023 4 : &ctx,
7024 4 : )
7025 4 : .await?;
7026 4 :
7027 88 : for (key, img_res) in results {
7028 84 : let expected = test_img(&format!("{} at {}", key, latest_lsns[&key]));
7029 84 : assert_eq!(img_res?, expected);
7030 4 : }
7031 4 :
7032 4 : Ok(())
7033 4 : }
7034 :
7035 : // Test that vectored get descends into ancestor timelines correctly and
7036 : // does not return an image that's newer than requested.
7037 : //
7038 : // The diagram below ilustrates an interesting case. We have a parent timeline
7039 : // (top of the Lsn range) and a child timeline. The request key cannot be reconstructed
7040 : // from the child timeline, so the parent timeline must be visited. When advacing into
7041 : // the child timeline, the read path needs to remember what the requested Lsn was in
7042 : // order to avoid returning an image that's too new. The test below constructs such
7043 : // a timeline setup and does a few queries around the Lsn of each page image.
7044 : // ```
7045 : // LSN
7046 : // ^
7047 : // |
7048 : // |
7049 : // 500 | --------------------------------------> branch point
7050 : // 400 | X
7051 : // 300 | X
7052 : // 200 | --------------------------------------> requested lsn
7053 : // 100 | X
7054 : // |---------------------------------------> Key
7055 : // |
7056 : // ------> requested key
7057 : //
7058 : // Legend:
7059 : // * X - page images
7060 : // ```
7061 : #[tokio::test]
7062 4 : async fn test_get_vectored_ancestor_descent() -> anyhow::Result<()> {
7063 4 : let harness = TenantHarness::create("test_get_vectored_on_lsn_axis").await?;
7064 4 : let (tenant, ctx) = harness.load().await;
7065 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7066 4 :
7067 4 : let start_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7068 4 : let end_key = start_key.add(1000);
7069 4 : let child_gap_at_key = start_key.add(500);
7070 4 : let mut parent_gap_lsns: BTreeMap<Lsn, String> = BTreeMap::new();
7071 4 :
7072 4 : let mut current_lsn = Lsn(0x10);
7073 4 :
7074 4 : let timeline_id = TimelineId::generate();
7075 4 : let parent_timeline = tenant
7076 4 : .create_test_timeline(timeline_id, current_lsn, DEFAULT_PG_VERSION, &ctx)
7077 4 : .await?;
7078 4 :
7079 4 : current_lsn += 0x100;
7080 4 :
7081 16 : for _ in 0..3 {
7082 12 : let mut key = start_key;
7083 12012 : while key < end_key {
7084 12000 : current_lsn += 0x10;
7085 12000 :
7086 12000 : let image_value = format!("{} at {}", child_gap_at_key, current_lsn);
7087 4 :
7088 12000 : let mut writer = parent_timeline.writer().await;
7089 12000 : writer
7090 12000 : .put(
7091 12000 : key,
7092 12000 : current_lsn,
7093 12000 : &Value::Image(test_img(&image_value)),
7094 12000 : &ctx,
7095 12000 : )
7096 12000 : .await?;
7097 12000 : writer.finish_write(current_lsn);
7098 12000 :
7099 12000 : if key == child_gap_at_key {
7100 12 : parent_gap_lsns.insert(current_lsn, image_value);
7101 11988 : }
7102 4 :
7103 12000 : key = key.next();
7104 4 : }
7105 4 :
7106 12 : parent_timeline.freeze_and_flush().await?;
7107 4 : }
7108 4 :
7109 4 : let child_timeline_id = TimelineId::generate();
7110 4 :
7111 4 : let child_timeline = tenant
7112 4 : .branch_timeline_test(&parent_timeline, child_timeline_id, Some(current_lsn), &ctx)
7113 4 : .await?;
7114 4 :
7115 4 : let mut key = start_key;
7116 4004 : while key < end_key {
7117 4000 : if key == child_gap_at_key {
7118 4 : key = key.next();
7119 4 : continue;
7120 3996 : }
7121 3996 :
7122 3996 : current_lsn += 0x10;
7123 4 :
7124 3996 : let mut writer = child_timeline.writer().await;
7125 3996 : writer
7126 3996 : .put(
7127 3996 : key,
7128 3996 : current_lsn,
7129 3996 : &Value::Image(test_img(&format!("{} at {}", key, current_lsn))),
7130 3996 : &ctx,
7131 3996 : )
7132 3996 : .await?;
7133 3996 : writer.finish_write(current_lsn);
7134 3996 :
7135 3996 : key = key.next();
7136 4 : }
7137 4 :
7138 4 : child_timeline.freeze_and_flush().await?;
7139 4 :
7140 4 : let lsn_offsets: [i64; 5] = [-10, -1, 0, 1, 10];
7141 4 : let mut query_lsns = Vec::new();
7142 12 : for image_lsn in parent_gap_lsns.keys().rev() {
7143 72 : for offset in lsn_offsets {
7144 60 : query_lsns.push(Lsn(image_lsn
7145 60 : .0
7146 60 : .checked_add_signed(offset)
7147 60 : .expect("Shouldn't overflow")));
7148 60 : }
7149 4 : }
7150 4 :
7151 64 : for query_lsn in query_lsns {
7152 60 : let results = child_timeline
7153 60 : .get_vectored_impl(
7154 60 : KeySpace {
7155 60 : ranges: vec![child_gap_at_key..child_gap_at_key.next()],
7156 60 : },
7157 60 : query_lsn,
7158 60 : &mut ValuesReconstructState::new(io_concurrency.clone()),
7159 60 : &ctx,
7160 60 : )
7161 60 : .await;
7162 4 :
7163 60 : let expected_item = parent_gap_lsns
7164 60 : .iter()
7165 60 : .rev()
7166 136 : .find(|(lsn, _)| **lsn <= query_lsn);
7167 60 :
7168 60 : info!(
7169 4 : "Doing vectored read at LSN {}. Expecting image to be: {:?}",
7170 4 : query_lsn, expected_item
7171 4 : );
7172 4 :
7173 60 : match expected_item {
7174 52 : Some((_, img_value)) => {
7175 52 : let key_results = results.expect("No vectored get error expected");
7176 52 : let key_result = &key_results[&child_gap_at_key];
7177 52 : let returned_img = key_result
7178 52 : .as_ref()
7179 52 : .expect("No page reconstruct error expected");
7180 52 :
7181 52 : info!(
7182 4 : "Vectored read at LSN {} returned image {}",
7183 0 : query_lsn,
7184 0 : std::str::from_utf8(returned_img)?
7185 4 : );
7186 52 : assert_eq!(*returned_img, test_img(img_value));
7187 4 : }
7188 4 : None => {
7189 8 : assert!(matches!(results, Err(GetVectoredError::MissingKey(_))));
7190 4 : }
7191 4 : }
7192 4 : }
7193 4 :
7194 4 : Ok(())
7195 4 : }
7196 :
7197 : #[tokio::test]
7198 4 : async fn test_random_updates() -> anyhow::Result<()> {
7199 4 : let names_algorithms = [
7200 4 : ("test_random_updates_legacy", CompactionAlgorithm::Legacy),
7201 4 : ("test_random_updates_tiered", CompactionAlgorithm::Tiered),
7202 4 : ];
7203 12 : for (name, algorithm) in names_algorithms {
7204 8 : test_random_updates_algorithm(name, algorithm).await?;
7205 4 : }
7206 4 : Ok(())
7207 4 : }
7208 :
7209 8 : async fn test_random_updates_algorithm(
7210 8 : name: &'static str,
7211 8 : compaction_algorithm: CompactionAlgorithm,
7212 8 : ) -> anyhow::Result<()> {
7213 8 : let mut harness = TenantHarness::create(name).await?;
7214 8 : harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
7215 8 : kind: compaction_algorithm,
7216 8 : });
7217 8 : let (tenant, ctx) = harness.load().await;
7218 8 : let tline = tenant
7219 8 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7220 8 : .await?;
7221 :
7222 : const NUM_KEYS: usize = 1000;
7223 8 : let cancel = CancellationToken::new();
7224 8 :
7225 8 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7226 8 : let mut test_key_end = test_key;
7227 8 : test_key_end.field6 = NUM_KEYS as u32;
7228 8 : tline.add_extra_test_dense_keyspace(KeySpace::single(test_key..test_key_end));
7229 8 :
7230 8 : let mut keyspace = KeySpaceAccum::new();
7231 8 :
7232 8 : // Track when each page was last modified. Used to assert that
7233 8 : // a read sees the latest page version.
7234 8 : let mut updated = [Lsn(0); NUM_KEYS];
7235 8 :
7236 8 : let mut lsn = Lsn(0x10);
7237 : #[allow(clippy::needless_range_loop)]
7238 8008 : for blknum in 0..NUM_KEYS {
7239 8000 : lsn = Lsn(lsn.0 + 0x10);
7240 8000 : test_key.field6 = blknum as u32;
7241 8000 : let mut writer = tline.writer().await;
7242 8000 : writer
7243 8000 : .put(
7244 8000 : test_key,
7245 8000 : lsn,
7246 8000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7247 8000 : &ctx,
7248 8000 : )
7249 8000 : .await?;
7250 8000 : writer.finish_write(lsn);
7251 8000 : updated[blknum] = lsn;
7252 8000 : drop(writer);
7253 8000 :
7254 8000 : keyspace.add_key(test_key);
7255 : }
7256 :
7257 408 : for _ in 0..50 {
7258 400400 : for _ in 0..NUM_KEYS {
7259 400000 : lsn = Lsn(lsn.0 + 0x10);
7260 400000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7261 400000 : test_key.field6 = blknum as u32;
7262 400000 : let mut writer = tline.writer().await;
7263 400000 : writer
7264 400000 : .put(
7265 400000 : test_key,
7266 400000 : lsn,
7267 400000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7268 400000 : &ctx,
7269 400000 : )
7270 400000 : .await?;
7271 400000 : writer.finish_write(lsn);
7272 400000 : drop(writer);
7273 400000 : updated[blknum] = lsn;
7274 : }
7275 :
7276 : // Read all the blocks
7277 400000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7278 400000 : test_key.field6 = blknum as u32;
7279 400000 : assert_eq!(
7280 400000 : tline.get(test_key, lsn, &ctx).await?,
7281 400000 : test_img(&format!("{} at {}", blknum, last_lsn))
7282 : );
7283 : }
7284 :
7285 : // Perform a cycle of flush, and GC
7286 400 : tline.freeze_and_flush().await?;
7287 400 : tenant
7288 400 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7289 400 : .await?;
7290 : }
7291 :
7292 8 : Ok(())
7293 8 : }
7294 :
7295 : #[tokio::test]
7296 4 : async fn test_traverse_branches() -> anyhow::Result<()> {
7297 4 : let (tenant, ctx) = TenantHarness::create("test_traverse_branches")
7298 4 : .await?
7299 4 : .load()
7300 4 : .await;
7301 4 : let mut tline = tenant
7302 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7303 4 : .await?;
7304 4 :
7305 4 : const NUM_KEYS: usize = 1000;
7306 4 :
7307 4 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7308 4 :
7309 4 : let mut keyspace = KeySpaceAccum::new();
7310 4 :
7311 4 : let cancel = CancellationToken::new();
7312 4 :
7313 4 : // Track when each page was last modified. Used to assert that
7314 4 : // a read sees the latest page version.
7315 4 : let mut updated = [Lsn(0); NUM_KEYS];
7316 4 :
7317 4 : let mut lsn = Lsn(0x10);
7318 4 : #[allow(clippy::needless_range_loop)]
7319 4004 : for blknum in 0..NUM_KEYS {
7320 4000 : lsn = Lsn(lsn.0 + 0x10);
7321 4000 : test_key.field6 = blknum as u32;
7322 4000 : let mut writer = tline.writer().await;
7323 4000 : writer
7324 4000 : .put(
7325 4000 : test_key,
7326 4000 : lsn,
7327 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7328 4000 : &ctx,
7329 4000 : )
7330 4000 : .await?;
7331 4000 : writer.finish_write(lsn);
7332 4000 : updated[blknum] = lsn;
7333 4000 : drop(writer);
7334 4000 :
7335 4000 : keyspace.add_key(test_key);
7336 4 : }
7337 4 :
7338 204 : for _ in 0..50 {
7339 200 : let new_tline_id = TimelineId::generate();
7340 200 : tenant
7341 200 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
7342 200 : .await?;
7343 200 : tline = tenant
7344 200 : .get_timeline(new_tline_id, true)
7345 200 : .expect("Should have the branched timeline");
7346 4 :
7347 200200 : for _ in 0..NUM_KEYS {
7348 200000 : lsn = Lsn(lsn.0 + 0x10);
7349 200000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7350 200000 : test_key.field6 = blknum as u32;
7351 200000 : let mut writer = tline.writer().await;
7352 200000 : writer
7353 200000 : .put(
7354 200000 : test_key,
7355 200000 : lsn,
7356 200000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7357 200000 : &ctx,
7358 200000 : )
7359 200000 : .await?;
7360 200000 : println!("updating {} at {}", blknum, lsn);
7361 200000 : writer.finish_write(lsn);
7362 200000 : drop(writer);
7363 200000 : updated[blknum] = lsn;
7364 4 : }
7365 4 :
7366 4 : // Read all the blocks
7367 200000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7368 200000 : test_key.field6 = blknum as u32;
7369 200000 : assert_eq!(
7370 200000 : tline.get(test_key, lsn, &ctx).await?,
7371 200000 : test_img(&format!("{} at {}", blknum, last_lsn))
7372 4 : );
7373 4 : }
7374 4 :
7375 4 : // Perform a cycle of flush, compact, and GC
7376 200 : tline.freeze_and_flush().await?;
7377 200 : tline
7378 200 : .compact(&cancel, CompactFlags::NoYield.into(), &ctx)
7379 200 : .await?;
7380 200 : tenant
7381 200 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7382 200 : .await?;
7383 4 : }
7384 4 :
7385 4 : Ok(())
7386 4 : }
7387 :
7388 : #[tokio::test]
7389 4 : async fn test_traverse_ancestors() -> anyhow::Result<()> {
7390 4 : let (tenant, ctx) = TenantHarness::create("test_traverse_ancestors")
7391 4 : .await?
7392 4 : .load()
7393 4 : .await;
7394 4 : let mut tline = tenant
7395 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7396 4 : .await?;
7397 4 :
7398 4 : const NUM_KEYS: usize = 100;
7399 4 : const NUM_TLINES: usize = 50;
7400 4 :
7401 4 : let mut test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7402 4 : // Track page mutation lsns across different timelines.
7403 4 : let mut updated = [[Lsn(0); NUM_KEYS]; NUM_TLINES];
7404 4 :
7405 4 : let mut lsn = Lsn(0x10);
7406 4 :
7407 4 : #[allow(clippy::needless_range_loop)]
7408 204 : for idx in 0..NUM_TLINES {
7409 200 : let new_tline_id = TimelineId::generate();
7410 200 : tenant
7411 200 : .branch_timeline_test(&tline, new_tline_id, Some(lsn), &ctx)
7412 200 : .await?;
7413 200 : tline = tenant
7414 200 : .get_timeline(new_tline_id, true)
7415 200 : .expect("Should have the branched timeline");
7416 4 :
7417 20200 : for _ in 0..NUM_KEYS {
7418 20000 : lsn = Lsn(lsn.0 + 0x10);
7419 20000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7420 20000 : test_key.field6 = blknum as u32;
7421 20000 : let mut writer = tline.writer().await;
7422 20000 : writer
7423 20000 : .put(
7424 20000 : test_key,
7425 20000 : lsn,
7426 20000 : &Value::Image(test_img(&format!("{} {} at {}", idx, blknum, lsn))),
7427 20000 : &ctx,
7428 20000 : )
7429 20000 : .await?;
7430 20000 : println!("updating [{}][{}] at {}", idx, blknum, lsn);
7431 20000 : writer.finish_write(lsn);
7432 20000 : drop(writer);
7433 20000 : updated[idx][blknum] = lsn;
7434 4 : }
7435 4 : }
7436 4 :
7437 4 : // Read pages from leaf timeline across all ancestors.
7438 200 : for (idx, lsns) in updated.iter().enumerate() {
7439 20000 : for (blknum, lsn) in lsns.iter().enumerate() {
7440 4 : // Skip empty mutations.
7441 20000 : if lsn.0 == 0 {
7442 7357 : continue;
7443 12643 : }
7444 12643 : println!("checking [{idx}][{blknum}] at {lsn}");
7445 12643 : test_key.field6 = blknum as u32;
7446 12643 : assert_eq!(
7447 12643 : tline.get(test_key, *lsn, &ctx).await?,
7448 12643 : test_img(&format!("{idx} {blknum} at {lsn}"))
7449 4 : );
7450 4 : }
7451 4 : }
7452 4 : Ok(())
7453 4 : }
7454 :
7455 : #[tokio::test]
7456 4 : async fn test_write_at_initdb_lsn_takes_optimization_code_path() -> anyhow::Result<()> {
7457 4 : let (tenant, ctx) = TenantHarness::create("test_empty_test_timeline_is_usable")
7458 4 : .await?
7459 4 : .load()
7460 4 : .await;
7461 4 :
7462 4 : let initdb_lsn = Lsn(0x20);
7463 4 : let (utline, ctx) = tenant
7464 4 : .create_empty_timeline(TIMELINE_ID, initdb_lsn, DEFAULT_PG_VERSION, &ctx)
7465 4 : .await?;
7466 4 : let tline = utline.raw_timeline().unwrap();
7467 4 :
7468 4 : // Spawn flush loop now so that we can set the `expect_initdb_optimization`
7469 4 : tline.maybe_spawn_flush_loop();
7470 4 :
7471 4 : // Make sure the timeline has the minimum set of required keys for operation.
7472 4 : // The only operation you can always do on an empty timeline is to `put` new data.
7473 4 : // Except if you `put` at `initdb_lsn`.
7474 4 : // In that case, there's an optimization to directly create image layers instead of delta layers.
7475 4 : // It uses `repartition()`, which assumes some keys to be present.
7476 4 : // Let's make sure the test timeline can handle that case.
7477 4 : {
7478 4 : let mut state = tline.flush_loop_state.lock().unwrap();
7479 4 : assert_eq!(
7480 4 : timeline::FlushLoopState::Running {
7481 4 : expect_initdb_optimization: false,
7482 4 : initdb_optimization_count: 0,
7483 4 : },
7484 4 : *state
7485 4 : );
7486 4 : *state = timeline::FlushLoopState::Running {
7487 4 : expect_initdb_optimization: true,
7488 4 : initdb_optimization_count: 0,
7489 4 : };
7490 4 : }
7491 4 :
7492 4 : // Make writes at the initdb_lsn. When we flush it below, it should be handled by the optimization.
7493 4 : // As explained above, the optimization requires some keys to be present.
7494 4 : // As per `create_empty_timeline` documentation, use init_empty to set them.
7495 4 : // This is what `create_test_timeline` does, by the way.
7496 4 : let mut modification = tline.begin_modification(initdb_lsn);
7497 4 : modification
7498 4 : .init_empty_test_timeline()
7499 4 : .context("init_empty_test_timeline")?;
7500 4 : modification
7501 4 : .commit(&ctx)
7502 4 : .await
7503 4 : .context("commit init_empty_test_timeline modification")?;
7504 4 :
7505 4 : // Do the flush. The flush code will check the expectations that we set above.
7506 4 : tline.freeze_and_flush().await?;
7507 4 :
7508 4 : // assert freeze_and_flush exercised the initdb optimization
7509 4 : {
7510 4 : let state = tline.flush_loop_state.lock().unwrap();
7511 4 : let timeline::FlushLoopState::Running {
7512 4 : expect_initdb_optimization,
7513 4 : initdb_optimization_count,
7514 4 : } = *state
7515 4 : else {
7516 4 : panic!("unexpected state: {:?}", *state);
7517 4 : };
7518 4 : assert!(expect_initdb_optimization);
7519 4 : assert!(initdb_optimization_count > 0);
7520 4 : }
7521 4 : Ok(())
7522 4 : }
7523 :
7524 : #[tokio::test]
7525 4 : async fn test_create_guard_crash() -> anyhow::Result<()> {
7526 4 : let name = "test_create_guard_crash";
7527 4 : let harness = TenantHarness::create(name).await?;
7528 4 : {
7529 4 : let (tenant, ctx) = harness.load().await;
7530 4 : let (tline, _ctx) = tenant
7531 4 : .create_empty_timeline(TIMELINE_ID, Lsn(0), DEFAULT_PG_VERSION, &ctx)
7532 4 : .await?;
7533 4 : // Leave the timeline ID in [`Tenant::timelines_creating`] to exclude attempting to create it again
7534 4 : let raw_tline = tline.raw_timeline().unwrap();
7535 4 : raw_tline
7536 4 : .shutdown(super::timeline::ShutdownMode::Hard)
7537 4 : .instrument(info_span!("test_shutdown", tenant_id=%raw_tline.tenant_shard_id, shard_id=%raw_tline.tenant_shard_id.shard_slug(), timeline_id=%TIMELINE_ID))
7538 4 : .await;
7539 4 : std::mem::forget(tline);
7540 4 : }
7541 4 :
7542 4 : let (tenant, _) = harness.load().await;
7543 4 : match tenant.get_timeline(TIMELINE_ID, false) {
7544 4 : Ok(_) => panic!("timeline should've been removed during load"),
7545 4 : Err(e) => {
7546 4 : assert_eq!(
7547 4 : e,
7548 4 : GetTimelineError::NotFound {
7549 4 : tenant_id: tenant.tenant_shard_id,
7550 4 : timeline_id: TIMELINE_ID,
7551 4 : }
7552 4 : )
7553 4 : }
7554 4 : }
7555 4 :
7556 4 : assert!(
7557 4 : !harness
7558 4 : .conf
7559 4 : .timeline_path(&tenant.tenant_shard_id, &TIMELINE_ID)
7560 4 : .exists()
7561 4 : );
7562 4 :
7563 4 : Ok(())
7564 4 : }
7565 :
7566 : #[tokio::test]
7567 4 : async fn test_read_at_max_lsn() -> anyhow::Result<()> {
7568 4 : let names_algorithms = [
7569 4 : ("test_read_at_max_lsn_legacy", CompactionAlgorithm::Legacy),
7570 4 : ("test_read_at_max_lsn_tiered", CompactionAlgorithm::Tiered),
7571 4 : ];
7572 12 : for (name, algorithm) in names_algorithms {
7573 8 : test_read_at_max_lsn_algorithm(name, algorithm).await?;
7574 4 : }
7575 4 : Ok(())
7576 4 : }
7577 :
7578 8 : async fn test_read_at_max_lsn_algorithm(
7579 8 : name: &'static str,
7580 8 : compaction_algorithm: CompactionAlgorithm,
7581 8 : ) -> anyhow::Result<()> {
7582 8 : let mut harness = TenantHarness::create(name).await?;
7583 8 : harness.tenant_conf.compaction_algorithm = Some(CompactionAlgorithmSettings {
7584 8 : kind: compaction_algorithm,
7585 8 : });
7586 8 : let (tenant, ctx) = harness.load().await;
7587 8 : let tline = tenant
7588 8 : .create_test_timeline(TIMELINE_ID, Lsn(0x08), DEFAULT_PG_VERSION, &ctx)
7589 8 : .await?;
7590 :
7591 8 : let lsn = Lsn(0x10);
7592 8 : let compact = false;
7593 8 : bulk_insert_maybe_compact_gc(&tenant, &tline, &ctx, lsn, 50, 10000, compact).await?;
7594 :
7595 8 : let test_key = Key::from_hex("010000000033333333444444445500000000").unwrap();
7596 8 : let read_lsn = Lsn(u64::MAX - 1);
7597 :
7598 8 : let result = tline.get(test_key, read_lsn, &ctx).await;
7599 8 : assert!(result.is_ok(), "result is not Ok: {}", result.unwrap_err());
7600 :
7601 8 : Ok(())
7602 8 : }
7603 :
7604 : #[tokio::test]
7605 4 : async fn test_metadata_scan() -> anyhow::Result<()> {
7606 4 : let harness = TenantHarness::create("test_metadata_scan").await?;
7607 4 : let (tenant, ctx) = harness.load().await;
7608 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7609 4 : let tline = tenant
7610 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7611 4 : .await?;
7612 4 :
7613 4 : const NUM_KEYS: usize = 1000;
7614 4 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
7615 4 :
7616 4 : let cancel = CancellationToken::new();
7617 4 :
7618 4 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7619 4 : base_key.field1 = AUX_KEY_PREFIX;
7620 4 : let mut test_key = base_key;
7621 4 :
7622 4 : // Track when each page was last modified. Used to assert that
7623 4 : // a read sees the latest page version.
7624 4 : let mut updated = [Lsn(0); NUM_KEYS];
7625 4 :
7626 4 : let mut lsn = Lsn(0x10);
7627 4 : #[allow(clippy::needless_range_loop)]
7628 4004 : for blknum in 0..NUM_KEYS {
7629 4000 : lsn = Lsn(lsn.0 + 0x10);
7630 4000 : test_key.field6 = (blknum * STEP) as u32;
7631 4000 : let mut writer = tline.writer().await;
7632 4000 : writer
7633 4000 : .put(
7634 4000 : test_key,
7635 4000 : lsn,
7636 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7637 4000 : &ctx,
7638 4000 : )
7639 4000 : .await?;
7640 4000 : writer.finish_write(lsn);
7641 4000 : updated[blknum] = lsn;
7642 4000 : drop(writer);
7643 4 : }
7644 4 :
7645 4 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
7646 4 :
7647 48 : for iter in 0..=10 {
7648 4 : // Read all the blocks
7649 44000 : for (blknum, last_lsn) in updated.iter().enumerate() {
7650 44000 : test_key.field6 = (blknum * STEP) as u32;
7651 44000 : assert_eq!(
7652 44000 : tline.get(test_key, lsn, &ctx).await?,
7653 44000 : test_img(&format!("{} at {}", blknum, last_lsn))
7654 4 : );
7655 4 : }
7656 4 :
7657 44 : let mut cnt = 0;
7658 44000 : for (key, value) in tline
7659 44 : .get_vectored_impl(
7660 44 : keyspace.clone(),
7661 44 : lsn,
7662 44 : &mut ValuesReconstructState::new(io_concurrency.clone()),
7663 44 : &ctx,
7664 44 : )
7665 44 : .await?
7666 4 : {
7667 44000 : let blknum = key.field6 as usize;
7668 44000 : let value = value?;
7669 44000 : assert!(blknum % STEP == 0);
7670 44000 : let blknum = blknum / STEP;
7671 44000 : assert_eq!(
7672 44000 : value,
7673 44000 : test_img(&format!("{} at {}", blknum, updated[blknum]))
7674 44000 : );
7675 44000 : cnt += 1;
7676 4 : }
7677 4 :
7678 44 : assert_eq!(cnt, NUM_KEYS);
7679 4 :
7680 44044 : for _ in 0..NUM_KEYS {
7681 44000 : lsn = Lsn(lsn.0 + 0x10);
7682 44000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7683 44000 : test_key.field6 = (blknum * STEP) as u32;
7684 44000 : let mut writer = tline.writer().await;
7685 44000 : writer
7686 44000 : .put(
7687 44000 : test_key,
7688 44000 : lsn,
7689 44000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7690 44000 : &ctx,
7691 44000 : )
7692 44000 : .await?;
7693 44000 : writer.finish_write(lsn);
7694 44000 : drop(writer);
7695 44000 : updated[blknum] = lsn;
7696 4 : }
7697 4 :
7698 4 : // Perform two cycles of flush, compact, and GC
7699 132 : for round in 0..2 {
7700 88 : tline.freeze_and_flush().await?;
7701 88 : tline
7702 88 : .compact(
7703 88 : &cancel,
7704 88 : if iter % 5 == 0 && round == 0 {
7705 12 : let mut flags = EnumSet::new();
7706 12 : flags.insert(CompactFlags::ForceImageLayerCreation);
7707 12 : flags.insert(CompactFlags::ForceRepartition);
7708 12 : flags.insert(CompactFlags::NoYield);
7709 12 : flags
7710 4 : } else {
7711 76 : EnumSet::empty()
7712 4 : },
7713 88 : &ctx,
7714 88 : )
7715 88 : .await?;
7716 88 : tenant
7717 88 : .gc_iteration(Some(tline.timeline_id), 0, Duration::ZERO, &cancel, &ctx)
7718 88 : .await?;
7719 4 : }
7720 4 : }
7721 4 :
7722 4 : Ok(())
7723 4 : }
7724 :
7725 : #[tokio::test]
7726 4 : async fn test_metadata_compaction_trigger() -> anyhow::Result<()> {
7727 4 : let harness = TenantHarness::create("test_metadata_compaction_trigger").await?;
7728 4 : let (tenant, ctx) = harness.load().await;
7729 4 : let tline = tenant
7730 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7731 4 : .await?;
7732 4 :
7733 4 : let cancel = CancellationToken::new();
7734 4 :
7735 4 : let mut base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7736 4 : base_key.field1 = AUX_KEY_PREFIX;
7737 4 : let test_key = base_key;
7738 4 : let mut lsn = Lsn(0x10);
7739 4 :
7740 84 : for _ in 0..20 {
7741 80 : lsn = Lsn(lsn.0 + 0x10);
7742 80 : let mut writer = tline.writer().await;
7743 80 : writer
7744 80 : .put(
7745 80 : test_key,
7746 80 : lsn,
7747 80 : &Value::Image(test_img(&format!("{} at {}", 0, lsn))),
7748 80 : &ctx,
7749 80 : )
7750 80 : .await?;
7751 80 : writer.finish_write(lsn);
7752 80 : drop(writer);
7753 80 : tline.freeze_and_flush().await?; // force create a delta layer
7754 4 : }
7755 4 :
7756 4 : let before_num_l0_delta_files =
7757 4 : tline.layers.read().await.layer_map()?.level0_deltas().len();
7758 4 :
7759 4 : tline
7760 4 : .compact(&cancel, CompactFlags::NoYield.into(), &ctx)
7761 4 : .await?;
7762 4 :
7763 4 : let after_num_l0_delta_files = tline.layers.read().await.layer_map()?.level0_deltas().len();
7764 4 :
7765 4 : assert!(
7766 4 : after_num_l0_delta_files < before_num_l0_delta_files,
7767 4 : "after_num_l0_delta_files={after_num_l0_delta_files}, before_num_l0_delta_files={before_num_l0_delta_files}"
7768 4 : );
7769 4 :
7770 4 : assert_eq!(
7771 4 : tline.get(test_key, lsn, &ctx).await?,
7772 4 : test_img(&format!("{} at {}", 0, lsn))
7773 4 : );
7774 4 :
7775 4 : Ok(())
7776 4 : }
7777 :
7778 : #[tokio::test]
7779 4 : async fn test_aux_file_e2e() {
7780 4 : let harness = TenantHarness::create("test_aux_file_e2e").await.unwrap();
7781 4 :
7782 4 : let (tenant, ctx) = harness.load().await;
7783 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7784 4 :
7785 4 : let mut lsn = Lsn(0x08);
7786 4 :
7787 4 : let tline: Arc<Timeline> = tenant
7788 4 : .create_test_timeline(TIMELINE_ID, lsn, DEFAULT_PG_VERSION, &ctx)
7789 4 : .await
7790 4 : .unwrap();
7791 4 :
7792 4 : {
7793 4 : lsn += 8;
7794 4 : let mut modification = tline.begin_modification(lsn);
7795 4 : modification
7796 4 : .put_file("pg_logical/mappings/test1", b"first", &ctx)
7797 4 : .await
7798 4 : .unwrap();
7799 4 : modification.commit(&ctx).await.unwrap();
7800 4 : }
7801 4 :
7802 4 : // we can read everything from the storage
7803 4 : let files = tline
7804 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7805 4 : .await
7806 4 : .unwrap();
7807 4 : assert_eq!(
7808 4 : files.get("pg_logical/mappings/test1"),
7809 4 : Some(&bytes::Bytes::from_static(b"first"))
7810 4 : );
7811 4 :
7812 4 : {
7813 4 : lsn += 8;
7814 4 : let mut modification = tline.begin_modification(lsn);
7815 4 : modification
7816 4 : .put_file("pg_logical/mappings/test2", b"second", &ctx)
7817 4 : .await
7818 4 : .unwrap();
7819 4 : modification.commit(&ctx).await.unwrap();
7820 4 : }
7821 4 :
7822 4 : let files = tline
7823 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7824 4 : .await
7825 4 : .unwrap();
7826 4 : assert_eq!(
7827 4 : files.get("pg_logical/mappings/test2"),
7828 4 : Some(&bytes::Bytes::from_static(b"second"))
7829 4 : );
7830 4 :
7831 4 : let child = tenant
7832 4 : .branch_timeline_test(&tline, NEW_TIMELINE_ID, Some(lsn), &ctx)
7833 4 : .await
7834 4 : .unwrap();
7835 4 :
7836 4 : let files = child
7837 4 : .list_aux_files(lsn, &ctx, io_concurrency.clone())
7838 4 : .await
7839 4 : .unwrap();
7840 4 : assert_eq!(files.get("pg_logical/mappings/test1"), None);
7841 4 : assert_eq!(files.get("pg_logical/mappings/test2"), None);
7842 4 : }
7843 :
7844 : #[tokio::test]
7845 4 : async fn test_metadata_image_creation() -> anyhow::Result<()> {
7846 4 : let harness = TenantHarness::create("test_metadata_image_creation").await?;
7847 4 : let (tenant, ctx) = harness.load().await;
7848 4 : let io_concurrency = IoConcurrency::spawn_for_test();
7849 4 : let tline = tenant
7850 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
7851 4 : .await?;
7852 4 :
7853 4 : const NUM_KEYS: usize = 1000;
7854 4 : const STEP: usize = 10000; // random update + scan base_key + idx * STEP
7855 4 :
7856 4 : let cancel = CancellationToken::new();
7857 4 :
7858 4 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
7859 4 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
7860 4 : let mut test_key = base_key;
7861 4 : let mut lsn = Lsn(0x10);
7862 4 :
7863 16 : async fn scan_with_statistics(
7864 16 : tline: &Timeline,
7865 16 : keyspace: &KeySpace,
7866 16 : lsn: Lsn,
7867 16 : ctx: &RequestContext,
7868 16 : io_concurrency: IoConcurrency,
7869 16 : ) -> anyhow::Result<(BTreeMap<Key, Result<Bytes, PageReconstructError>>, usize)> {
7870 16 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
7871 16 : let res = tline
7872 16 : .get_vectored_impl(keyspace.clone(), lsn, &mut reconstruct_state, ctx)
7873 16 : .await?;
7874 16 : Ok((res, reconstruct_state.get_delta_layers_visited() as usize))
7875 16 : }
7876 4 :
7877 4004 : for blknum in 0..NUM_KEYS {
7878 4000 : lsn = Lsn(lsn.0 + 0x10);
7879 4000 : test_key.field6 = (blknum * STEP) as u32;
7880 4000 : let mut writer = tline.writer().await;
7881 4000 : writer
7882 4000 : .put(
7883 4000 : test_key,
7884 4000 : lsn,
7885 4000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7886 4000 : &ctx,
7887 4000 : )
7888 4000 : .await?;
7889 4000 : writer.finish_write(lsn);
7890 4000 : drop(writer);
7891 4 : }
7892 4 :
7893 4 : let keyspace = KeySpace::single(base_key..base_key.add((NUM_KEYS * STEP) as u32));
7894 4 :
7895 44 : for iter in 1..=10 {
7896 40040 : for _ in 0..NUM_KEYS {
7897 40000 : lsn = Lsn(lsn.0 + 0x10);
7898 40000 : let blknum = thread_rng().gen_range(0..NUM_KEYS);
7899 40000 : test_key.field6 = (blknum * STEP) as u32;
7900 40000 : let mut writer = tline.writer().await;
7901 40000 : writer
7902 40000 : .put(
7903 40000 : test_key,
7904 40000 : lsn,
7905 40000 : &Value::Image(test_img(&format!("{} at {}", blknum, lsn))),
7906 40000 : &ctx,
7907 40000 : )
7908 40000 : .await?;
7909 40000 : writer.finish_write(lsn);
7910 40000 : drop(writer);
7911 4 : }
7912 4 :
7913 40 : tline.freeze_and_flush().await?;
7914 4 :
7915 40 : if iter % 5 == 0 {
7916 8 : let (_, before_delta_file_accessed) =
7917 8 : scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
7918 8 : .await?;
7919 8 : tline
7920 8 : .compact(
7921 8 : &cancel,
7922 8 : {
7923 8 : let mut flags = EnumSet::new();
7924 8 : flags.insert(CompactFlags::ForceImageLayerCreation);
7925 8 : flags.insert(CompactFlags::ForceRepartition);
7926 8 : flags.insert(CompactFlags::NoYield);
7927 8 : flags
7928 8 : },
7929 8 : &ctx,
7930 8 : )
7931 8 : .await?;
7932 8 : let (_, after_delta_file_accessed) =
7933 8 : scan_with_statistics(&tline, &keyspace, lsn, &ctx, io_concurrency.clone())
7934 8 : .await?;
7935 8 : assert!(
7936 8 : after_delta_file_accessed < before_delta_file_accessed,
7937 4 : "after_delta_file_accessed={after_delta_file_accessed}, before_delta_file_accessed={before_delta_file_accessed}"
7938 4 : );
7939 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.
7940 8 : assert!(
7941 8 : after_delta_file_accessed <= 2,
7942 4 : "after_delta_file_accessed={after_delta_file_accessed}"
7943 4 : );
7944 32 : }
7945 4 : }
7946 4 :
7947 4 : Ok(())
7948 4 : }
7949 :
7950 : #[tokio::test]
7951 4 : async fn test_vectored_missing_data_key_reads() -> anyhow::Result<()> {
7952 4 : let harness = TenantHarness::create("test_vectored_missing_data_key_reads").await?;
7953 4 : let (tenant, ctx) = harness.load().await;
7954 4 :
7955 4 : let base_key = Key::from_hex("000000000033333333444444445500000000").unwrap();
7956 4 : let base_key_child = Key::from_hex("000000000033333333444444445500000001").unwrap();
7957 4 : let base_key_nonexist = Key::from_hex("000000000033333333444444445500000002").unwrap();
7958 4 :
7959 4 : let tline = tenant
7960 4 : .create_test_timeline_with_layers(
7961 4 : TIMELINE_ID,
7962 4 : Lsn(0x10),
7963 4 : DEFAULT_PG_VERSION,
7964 4 : &ctx,
7965 4 : Vec::new(), // in-memory layers
7966 4 : Vec::new(), // delta layers
7967 4 : vec![(Lsn(0x20), vec![(base_key, test_img("data key 1"))])], // image layers
7968 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
7969 4 : )
7970 4 : .await?;
7971 4 : tline.add_extra_test_dense_keyspace(KeySpace::single(base_key..(base_key_nonexist.next())));
7972 4 :
7973 4 : let child = tenant
7974 4 : .branch_timeline_test_with_layers(
7975 4 : &tline,
7976 4 : NEW_TIMELINE_ID,
7977 4 : Some(Lsn(0x20)),
7978 4 : &ctx,
7979 4 : Vec::new(), // delta layers
7980 4 : vec![(Lsn(0x30), vec![(base_key_child, test_img("data key 2"))])], // image layers
7981 4 : Lsn(0x30),
7982 4 : )
7983 4 : .await
7984 4 : .unwrap();
7985 4 :
7986 4 : let lsn = Lsn(0x30);
7987 4 :
7988 4 : // test vectored get on parent timeline
7989 4 : assert_eq!(
7990 4 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
7991 4 : Some(test_img("data key 1"))
7992 4 : );
7993 4 : assert!(
7994 4 : get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx)
7995 4 : .await
7996 4 : .unwrap_err()
7997 4 : .is_missing_key_error()
7998 4 : );
7999 4 : assert!(
8000 4 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx)
8001 4 : .await
8002 4 : .unwrap_err()
8003 4 : .is_missing_key_error()
8004 4 : );
8005 4 :
8006 4 : // test vectored get on child timeline
8007 4 : assert_eq!(
8008 4 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
8009 4 : Some(test_img("data key 1"))
8010 4 : );
8011 4 : assert_eq!(
8012 4 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
8013 4 : Some(test_img("data key 2"))
8014 4 : );
8015 4 : assert!(
8016 4 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx)
8017 4 : .await
8018 4 : .unwrap_err()
8019 4 : .is_missing_key_error()
8020 4 : );
8021 4 :
8022 4 : Ok(())
8023 4 : }
8024 :
8025 : #[tokio::test]
8026 4 : async fn test_vectored_missing_metadata_key_reads() -> anyhow::Result<()> {
8027 4 : let harness = TenantHarness::create("test_vectored_missing_metadata_key_reads").await?;
8028 4 : let (tenant, ctx) = harness.load().await;
8029 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8030 4 :
8031 4 : let base_key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8032 4 : let base_key_child = Key::from_hex("620000000033333333444444445500000001").unwrap();
8033 4 : let base_key_nonexist = Key::from_hex("620000000033333333444444445500000002").unwrap();
8034 4 : let base_key_overwrite = Key::from_hex("620000000033333333444444445500000003").unwrap();
8035 4 :
8036 4 : let base_inherited_key = Key::from_hex("610000000033333333444444445500000000").unwrap();
8037 4 : let base_inherited_key_child =
8038 4 : Key::from_hex("610000000033333333444444445500000001").unwrap();
8039 4 : let base_inherited_key_nonexist =
8040 4 : Key::from_hex("610000000033333333444444445500000002").unwrap();
8041 4 : let base_inherited_key_overwrite =
8042 4 : Key::from_hex("610000000033333333444444445500000003").unwrap();
8043 4 :
8044 4 : assert_eq!(base_key.field1, AUX_KEY_PREFIX); // in case someone accidentally changed the prefix...
8045 4 : assert_eq!(base_inherited_key.field1, RELATION_SIZE_PREFIX);
8046 4 :
8047 4 : let tline = tenant
8048 4 : .create_test_timeline_with_layers(
8049 4 : TIMELINE_ID,
8050 4 : Lsn(0x10),
8051 4 : DEFAULT_PG_VERSION,
8052 4 : &ctx,
8053 4 : Vec::new(), // in-memory layers
8054 4 : Vec::new(), // delta layers
8055 4 : vec![(
8056 4 : Lsn(0x20),
8057 4 : vec![
8058 4 : (base_inherited_key, test_img("metadata inherited key 1")),
8059 4 : (
8060 4 : base_inherited_key_overwrite,
8061 4 : test_img("metadata key overwrite 1a"),
8062 4 : ),
8063 4 : (base_key, test_img("metadata key 1")),
8064 4 : (base_key_overwrite, test_img("metadata key overwrite 1b")),
8065 4 : ],
8066 4 : )], // image layers
8067 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
8068 4 : )
8069 4 : .await?;
8070 4 :
8071 4 : let child = tenant
8072 4 : .branch_timeline_test_with_layers(
8073 4 : &tline,
8074 4 : NEW_TIMELINE_ID,
8075 4 : Some(Lsn(0x20)),
8076 4 : &ctx,
8077 4 : Vec::new(), // delta layers
8078 4 : vec![(
8079 4 : Lsn(0x30),
8080 4 : vec![
8081 4 : (
8082 4 : base_inherited_key_child,
8083 4 : test_img("metadata inherited key 2"),
8084 4 : ),
8085 4 : (
8086 4 : base_inherited_key_overwrite,
8087 4 : test_img("metadata key overwrite 2a"),
8088 4 : ),
8089 4 : (base_key_child, test_img("metadata key 2")),
8090 4 : (base_key_overwrite, test_img("metadata key overwrite 2b")),
8091 4 : ],
8092 4 : )], // image layers
8093 4 : Lsn(0x30),
8094 4 : )
8095 4 : .await
8096 4 : .unwrap();
8097 4 :
8098 4 : let lsn = Lsn(0x30);
8099 4 :
8100 4 : // test vectored get on parent timeline
8101 4 : assert_eq!(
8102 4 : get_vectored_impl_wrapper(&tline, base_key, lsn, &ctx).await?,
8103 4 : Some(test_img("metadata key 1"))
8104 4 : );
8105 4 : assert_eq!(
8106 4 : get_vectored_impl_wrapper(&tline, base_key_child, lsn, &ctx).await?,
8107 4 : None
8108 4 : );
8109 4 : assert_eq!(
8110 4 : get_vectored_impl_wrapper(&tline, base_key_nonexist, lsn, &ctx).await?,
8111 4 : None
8112 4 : );
8113 4 : assert_eq!(
8114 4 : get_vectored_impl_wrapper(&tline, base_key_overwrite, lsn, &ctx).await?,
8115 4 : Some(test_img("metadata key overwrite 1b"))
8116 4 : );
8117 4 : assert_eq!(
8118 4 : get_vectored_impl_wrapper(&tline, base_inherited_key, lsn, &ctx).await?,
8119 4 : Some(test_img("metadata inherited key 1"))
8120 4 : );
8121 4 : assert_eq!(
8122 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_child, lsn, &ctx).await?,
8123 4 : None
8124 4 : );
8125 4 : assert_eq!(
8126 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_nonexist, lsn, &ctx).await?,
8127 4 : None
8128 4 : );
8129 4 : assert_eq!(
8130 4 : get_vectored_impl_wrapper(&tline, base_inherited_key_overwrite, lsn, &ctx).await?,
8131 4 : Some(test_img("metadata key overwrite 1a"))
8132 4 : );
8133 4 :
8134 4 : // test vectored get on child timeline
8135 4 : assert_eq!(
8136 4 : get_vectored_impl_wrapper(&child, base_key, lsn, &ctx).await?,
8137 4 : None
8138 4 : );
8139 4 : assert_eq!(
8140 4 : get_vectored_impl_wrapper(&child, base_key_child, lsn, &ctx).await?,
8141 4 : Some(test_img("metadata key 2"))
8142 4 : );
8143 4 : assert_eq!(
8144 4 : get_vectored_impl_wrapper(&child, base_key_nonexist, lsn, &ctx).await?,
8145 4 : None
8146 4 : );
8147 4 : assert_eq!(
8148 4 : get_vectored_impl_wrapper(&child, base_inherited_key, lsn, &ctx).await?,
8149 4 : Some(test_img("metadata inherited key 1"))
8150 4 : );
8151 4 : assert_eq!(
8152 4 : get_vectored_impl_wrapper(&child, base_inherited_key_child, lsn, &ctx).await?,
8153 4 : Some(test_img("metadata inherited key 2"))
8154 4 : );
8155 4 : assert_eq!(
8156 4 : get_vectored_impl_wrapper(&child, base_inherited_key_nonexist, lsn, &ctx).await?,
8157 4 : None
8158 4 : );
8159 4 : assert_eq!(
8160 4 : get_vectored_impl_wrapper(&child, base_key_overwrite, lsn, &ctx).await?,
8161 4 : Some(test_img("metadata key overwrite 2b"))
8162 4 : );
8163 4 : assert_eq!(
8164 4 : get_vectored_impl_wrapper(&child, base_inherited_key_overwrite, lsn, &ctx).await?,
8165 4 : Some(test_img("metadata key overwrite 2a"))
8166 4 : );
8167 4 :
8168 4 : // test vectored scan on parent timeline
8169 4 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
8170 4 : let res = tline
8171 4 : .get_vectored_impl(
8172 4 : KeySpace::single(Key::metadata_key_range()),
8173 4 : lsn,
8174 4 : &mut reconstruct_state,
8175 4 : &ctx,
8176 4 : )
8177 4 : .await?;
8178 4 :
8179 4 : assert_eq!(
8180 4 : res.into_iter()
8181 16 : .map(|(k, v)| (k, v.unwrap()))
8182 4 : .collect::<Vec<_>>(),
8183 4 : vec![
8184 4 : (base_inherited_key, test_img("metadata inherited key 1")),
8185 4 : (
8186 4 : base_inherited_key_overwrite,
8187 4 : test_img("metadata key overwrite 1a")
8188 4 : ),
8189 4 : (base_key, test_img("metadata key 1")),
8190 4 : (base_key_overwrite, test_img("metadata key overwrite 1b")),
8191 4 : ]
8192 4 : );
8193 4 :
8194 4 : // test vectored scan on child timeline
8195 4 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
8196 4 : let res = child
8197 4 : .get_vectored_impl(
8198 4 : KeySpace::single(Key::metadata_key_range()),
8199 4 : lsn,
8200 4 : &mut reconstruct_state,
8201 4 : &ctx,
8202 4 : )
8203 4 : .await?;
8204 4 :
8205 4 : assert_eq!(
8206 4 : res.into_iter()
8207 20 : .map(|(k, v)| (k, v.unwrap()))
8208 4 : .collect::<Vec<_>>(),
8209 4 : vec![
8210 4 : (base_inherited_key, test_img("metadata inherited key 1")),
8211 4 : (
8212 4 : base_inherited_key_child,
8213 4 : test_img("metadata inherited key 2")
8214 4 : ),
8215 4 : (
8216 4 : base_inherited_key_overwrite,
8217 4 : test_img("metadata key overwrite 2a")
8218 4 : ),
8219 4 : (base_key_child, test_img("metadata key 2")),
8220 4 : (base_key_overwrite, test_img("metadata key overwrite 2b")),
8221 4 : ]
8222 4 : );
8223 4 :
8224 4 : Ok(())
8225 4 : }
8226 :
8227 112 : async fn get_vectored_impl_wrapper(
8228 112 : tline: &Arc<Timeline>,
8229 112 : key: Key,
8230 112 : lsn: Lsn,
8231 112 : ctx: &RequestContext,
8232 112 : ) -> Result<Option<Bytes>, GetVectoredError> {
8233 112 : let io_concurrency =
8234 112 : IoConcurrency::spawn_from_conf(tline.conf, tline.gate.enter().unwrap());
8235 112 : let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
8236 112 : let mut res = tline
8237 112 : .get_vectored_impl(
8238 112 : KeySpace::single(key..key.next()),
8239 112 : lsn,
8240 112 : &mut reconstruct_state,
8241 112 : ctx,
8242 112 : )
8243 112 : .await?;
8244 100 : Ok(res.pop_last().map(|(k, v)| {
8245 64 : assert_eq!(k, key);
8246 64 : v.unwrap()
8247 100 : }))
8248 112 : }
8249 :
8250 : #[tokio::test]
8251 4 : async fn test_metadata_tombstone_reads() -> anyhow::Result<()> {
8252 4 : let harness = TenantHarness::create("test_metadata_tombstone_reads").await?;
8253 4 : let (tenant, ctx) = harness.load().await;
8254 4 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
8255 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8256 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8257 4 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
8258 4 :
8259 4 : // We emulate the situation that the compaction algorithm creates an image layer that removes the tombstones
8260 4 : // Lsn 0x30 key0, key3, no key1+key2
8261 4 : // Lsn 0x20 key1+key2 tomestones
8262 4 : // Lsn 0x10 key1 in image, key2 in delta
8263 4 : let tline = tenant
8264 4 : .create_test_timeline_with_layers(
8265 4 : TIMELINE_ID,
8266 4 : Lsn(0x10),
8267 4 : DEFAULT_PG_VERSION,
8268 4 : &ctx,
8269 4 : Vec::new(), // in-memory layers
8270 4 : // delta layers
8271 4 : vec![
8272 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8273 4 : Lsn(0x10)..Lsn(0x20),
8274 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8275 4 : ),
8276 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8277 4 : Lsn(0x20)..Lsn(0x30),
8278 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8279 4 : ),
8280 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8281 4 : Lsn(0x20)..Lsn(0x30),
8282 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8283 4 : ),
8284 4 : ],
8285 4 : // image layers
8286 4 : vec![
8287 4 : (Lsn(0x10), vec![(key1, test_img("metadata key 1"))]),
8288 4 : (
8289 4 : Lsn(0x30),
8290 4 : vec![
8291 4 : (key0, test_img("metadata key 0")),
8292 4 : (key3, test_img("metadata key 3")),
8293 4 : ],
8294 4 : ),
8295 4 : ],
8296 4 : Lsn(0x30),
8297 4 : )
8298 4 : .await?;
8299 4 :
8300 4 : let lsn = Lsn(0x30);
8301 4 : let old_lsn = Lsn(0x20);
8302 4 :
8303 4 : assert_eq!(
8304 4 : get_vectored_impl_wrapper(&tline, key0, lsn, &ctx).await?,
8305 4 : Some(test_img("metadata key 0"))
8306 4 : );
8307 4 : assert_eq!(
8308 4 : get_vectored_impl_wrapper(&tline, key1, lsn, &ctx).await?,
8309 4 : None,
8310 4 : );
8311 4 : assert_eq!(
8312 4 : get_vectored_impl_wrapper(&tline, key2, lsn, &ctx).await?,
8313 4 : None,
8314 4 : );
8315 4 : assert_eq!(
8316 4 : get_vectored_impl_wrapper(&tline, key1, old_lsn, &ctx).await?,
8317 4 : Some(Bytes::new()),
8318 4 : );
8319 4 : assert_eq!(
8320 4 : get_vectored_impl_wrapper(&tline, key2, old_lsn, &ctx).await?,
8321 4 : Some(Bytes::new()),
8322 4 : );
8323 4 : assert_eq!(
8324 4 : get_vectored_impl_wrapper(&tline, key3, lsn, &ctx).await?,
8325 4 : Some(test_img("metadata key 3"))
8326 4 : );
8327 4 :
8328 4 : Ok(())
8329 4 : }
8330 :
8331 : #[tokio::test]
8332 4 : async fn test_metadata_tombstone_image_creation() {
8333 4 : let harness = TenantHarness::create("test_metadata_tombstone_image_creation")
8334 4 : .await
8335 4 : .unwrap();
8336 4 : let (tenant, ctx) = harness.load().await;
8337 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8338 4 :
8339 4 : let key0 = Key::from_hex("620000000033333333444444445500000000").unwrap();
8340 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8341 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8342 4 : let key3 = Key::from_hex("620000000033333333444444445500000003").unwrap();
8343 4 :
8344 4 : let tline = tenant
8345 4 : .create_test_timeline_with_layers(
8346 4 : TIMELINE_ID,
8347 4 : Lsn(0x10),
8348 4 : DEFAULT_PG_VERSION,
8349 4 : &ctx,
8350 4 : Vec::new(), // in-memory layers
8351 4 : // delta layers
8352 4 : vec![
8353 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8354 4 : Lsn(0x10)..Lsn(0x20),
8355 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8356 4 : ),
8357 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8358 4 : Lsn(0x20)..Lsn(0x30),
8359 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8360 4 : ),
8361 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8362 4 : Lsn(0x20)..Lsn(0x30),
8363 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8364 4 : ),
8365 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8366 4 : Lsn(0x30)..Lsn(0x40),
8367 4 : vec![
8368 4 : (key0, Lsn(0x30), Value::Image(test_img("metadata key 0"))),
8369 4 : (key3, Lsn(0x30), Value::Image(test_img("metadata key 3"))),
8370 4 : ],
8371 4 : ),
8372 4 : ],
8373 4 : // image layers
8374 4 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
8375 4 : Lsn(0x40),
8376 4 : )
8377 4 : .await
8378 4 : .unwrap();
8379 4 :
8380 4 : let cancel = CancellationToken::new();
8381 4 :
8382 4 : tline
8383 4 : .compact(
8384 4 : &cancel,
8385 4 : {
8386 4 : let mut flags = EnumSet::new();
8387 4 : flags.insert(CompactFlags::ForceImageLayerCreation);
8388 4 : flags.insert(CompactFlags::ForceRepartition);
8389 4 : flags.insert(CompactFlags::NoYield);
8390 4 : flags
8391 4 : },
8392 4 : &ctx,
8393 4 : )
8394 4 : .await
8395 4 : .unwrap();
8396 4 :
8397 4 : // Image layers are created at last_record_lsn
8398 4 : let images = tline
8399 4 : .inspect_image_layers(Lsn(0x40), &ctx, io_concurrency.clone())
8400 4 : .await
8401 4 : .unwrap()
8402 4 : .into_iter()
8403 36 : .filter(|(k, _)| k.is_metadata_key())
8404 4 : .collect::<Vec<_>>();
8405 4 : assert_eq!(images.len(), 2); // the image layer should only contain two existing keys, tombstones should be removed.
8406 4 : }
8407 :
8408 : #[tokio::test]
8409 4 : async fn test_metadata_tombstone_empty_image_creation() {
8410 4 : let harness = TenantHarness::create("test_metadata_tombstone_empty_image_creation")
8411 4 : .await
8412 4 : .unwrap();
8413 4 : let (tenant, ctx) = harness.load().await;
8414 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8415 4 :
8416 4 : let key1 = Key::from_hex("620000000033333333444444445500000001").unwrap();
8417 4 : let key2 = Key::from_hex("620000000033333333444444445500000002").unwrap();
8418 4 :
8419 4 : let tline = tenant
8420 4 : .create_test_timeline_with_layers(
8421 4 : TIMELINE_ID,
8422 4 : Lsn(0x10),
8423 4 : DEFAULT_PG_VERSION,
8424 4 : &ctx,
8425 4 : Vec::new(), // in-memory layers
8426 4 : // delta layers
8427 4 : vec![
8428 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8429 4 : Lsn(0x10)..Lsn(0x20),
8430 4 : vec![(key2, Lsn(0x10), Value::Image(test_img("metadata key 2")))],
8431 4 : ),
8432 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8433 4 : Lsn(0x20)..Lsn(0x30),
8434 4 : vec![(key1, Lsn(0x20), Value::Image(Bytes::new()))],
8435 4 : ),
8436 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
8437 4 : Lsn(0x20)..Lsn(0x30),
8438 4 : vec![(key2, Lsn(0x20), Value::Image(Bytes::new()))],
8439 4 : ),
8440 4 : ],
8441 4 : // image layers
8442 4 : vec![(Lsn(0x10), vec![(key1, test_img("metadata key 1"))])],
8443 4 : Lsn(0x30),
8444 4 : )
8445 4 : .await
8446 4 : .unwrap();
8447 4 :
8448 4 : let cancel = CancellationToken::new();
8449 4 :
8450 4 : tline
8451 4 : .compact(
8452 4 : &cancel,
8453 4 : {
8454 4 : let mut flags = EnumSet::new();
8455 4 : flags.insert(CompactFlags::ForceImageLayerCreation);
8456 4 : flags.insert(CompactFlags::ForceRepartition);
8457 4 : flags.insert(CompactFlags::NoYield);
8458 4 : flags
8459 4 : },
8460 4 : &ctx,
8461 4 : )
8462 4 : .await
8463 4 : .unwrap();
8464 4 :
8465 4 : // Image layers are created at last_record_lsn
8466 4 : let images = tline
8467 4 : .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
8468 4 : .await
8469 4 : .unwrap()
8470 4 : .into_iter()
8471 28 : .filter(|(k, _)| k.is_metadata_key())
8472 4 : .collect::<Vec<_>>();
8473 4 : assert_eq!(images.len(), 0); // the image layer should not contain tombstones, or it is not created
8474 4 : }
8475 :
8476 : #[tokio::test]
8477 4 : async fn test_simple_bottom_most_compaction_images() -> anyhow::Result<()> {
8478 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_images").await?;
8479 4 : let (tenant, ctx) = harness.load().await;
8480 4 : let io_concurrency = IoConcurrency::spawn_for_test();
8481 4 :
8482 204 : fn get_key(id: u32) -> Key {
8483 204 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8484 204 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8485 204 : key.field6 = id;
8486 204 : key
8487 204 : }
8488 4 :
8489 4 : // We create
8490 4 : // - one bottom-most image layer,
8491 4 : // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
8492 4 : // - a delta layer D2 crossing the GC horizon with data only below the horizon,
8493 4 : // - a delta layer D3 above the horizon.
8494 4 : //
8495 4 : // | D3 |
8496 4 : // | D1 |
8497 4 : // -| |-- gc horizon -----------------
8498 4 : // | | | D2 |
8499 4 : // --------- img layer ------------------
8500 4 : //
8501 4 : // What we should expact from this compaction is:
8502 4 : // | D3 |
8503 4 : // | Part of D1 |
8504 4 : // --------- img layer with D1+D2 at GC horizon------------------
8505 4 :
8506 4 : // img layer at 0x10
8507 4 : let img_layer = (0..10)
8508 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
8509 4 : .collect_vec();
8510 4 :
8511 4 : let delta1 = vec![
8512 4 : (
8513 4 : get_key(1),
8514 4 : Lsn(0x20),
8515 4 : Value::Image(Bytes::from("value 1@0x20")),
8516 4 : ),
8517 4 : (
8518 4 : get_key(2),
8519 4 : Lsn(0x30),
8520 4 : Value::Image(Bytes::from("value 2@0x30")),
8521 4 : ),
8522 4 : (
8523 4 : get_key(3),
8524 4 : Lsn(0x40),
8525 4 : Value::Image(Bytes::from("value 3@0x40")),
8526 4 : ),
8527 4 : ];
8528 4 : let delta2 = vec![
8529 4 : (
8530 4 : get_key(5),
8531 4 : Lsn(0x20),
8532 4 : Value::Image(Bytes::from("value 5@0x20")),
8533 4 : ),
8534 4 : (
8535 4 : get_key(6),
8536 4 : Lsn(0x20),
8537 4 : Value::Image(Bytes::from("value 6@0x20")),
8538 4 : ),
8539 4 : ];
8540 4 : let delta3 = vec![
8541 4 : (
8542 4 : get_key(8),
8543 4 : Lsn(0x48),
8544 4 : Value::Image(Bytes::from("value 8@0x48")),
8545 4 : ),
8546 4 : (
8547 4 : get_key(9),
8548 4 : Lsn(0x48),
8549 4 : Value::Image(Bytes::from("value 9@0x48")),
8550 4 : ),
8551 4 : ];
8552 4 :
8553 4 : let tline = tenant
8554 4 : .create_test_timeline_with_layers(
8555 4 : TIMELINE_ID,
8556 4 : Lsn(0x10),
8557 4 : DEFAULT_PG_VERSION,
8558 4 : &ctx,
8559 4 : Vec::new(), // in-memory layers
8560 4 : vec![
8561 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
8562 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
8563 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
8564 4 : ], // delta layers
8565 4 : vec![(Lsn(0x10), img_layer)], // image layers
8566 4 : Lsn(0x50),
8567 4 : )
8568 4 : .await?;
8569 4 : {
8570 4 : tline
8571 4 : .applied_gc_cutoff_lsn
8572 4 : .lock_for_write()
8573 4 : .store_and_unlock(Lsn(0x30))
8574 4 : .wait()
8575 4 : .await;
8576 4 : // Update GC info
8577 4 : let mut guard = tline.gc_info.write().unwrap();
8578 4 : guard.cutoffs.time = Lsn(0x30);
8579 4 : guard.cutoffs.space = Lsn(0x30);
8580 4 : }
8581 4 :
8582 4 : let expected_result = [
8583 4 : Bytes::from_static(b"value 0@0x10"),
8584 4 : Bytes::from_static(b"value 1@0x20"),
8585 4 : Bytes::from_static(b"value 2@0x30"),
8586 4 : Bytes::from_static(b"value 3@0x40"),
8587 4 : Bytes::from_static(b"value 4@0x10"),
8588 4 : Bytes::from_static(b"value 5@0x20"),
8589 4 : Bytes::from_static(b"value 6@0x20"),
8590 4 : Bytes::from_static(b"value 7@0x10"),
8591 4 : Bytes::from_static(b"value 8@0x48"),
8592 4 : Bytes::from_static(b"value 9@0x48"),
8593 4 : ];
8594 4 :
8595 40 : for (idx, expected) in expected_result.iter().enumerate() {
8596 40 : assert_eq!(
8597 40 : tline
8598 40 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8599 40 : .await
8600 40 : .unwrap(),
8601 4 : expected
8602 4 : );
8603 4 : }
8604 4 :
8605 4 : let cancel = CancellationToken::new();
8606 4 : tline
8607 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8608 4 : .await
8609 4 : .unwrap();
8610 4 :
8611 40 : for (idx, expected) in expected_result.iter().enumerate() {
8612 40 : assert_eq!(
8613 40 : tline
8614 40 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
8615 40 : .await
8616 40 : .unwrap(),
8617 4 : expected
8618 4 : );
8619 4 : }
8620 4 :
8621 4 : // Check if the image layer at the GC horizon contains exactly what we want
8622 4 : let image_at_gc_horizon = tline
8623 4 : .inspect_image_layers(Lsn(0x30), &ctx, io_concurrency.clone())
8624 4 : .await
8625 4 : .unwrap()
8626 4 : .into_iter()
8627 68 : .filter(|(k, _)| k.is_metadata_key())
8628 4 : .collect::<Vec<_>>();
8629 4 :
8630 4 : assert_eq!(image_at_gc_horizon.len(), 10);
8631 4 : let expected_result = [
8632 4 : Bytes::from_static(b"value 0@0x10"),
8633 4 : Bytes::from_static(b"value 1@0x20"),
8634 4 : Bytes::from_static(b"value 2@0x30"),
8635 4 : Bytes::from_static(b"value 3@0x10"),
8636 4 : Bytes::from_static(b"value 4@0x10"),
8637 4 : Bytes::from_static(b"value 5@0x20"),
8638 4 : Bytes::from_static(b"value 6@0x20"),
8639 4 : Bytes::from_static(b"value 7@0x10"),
8640 4 : Bytes::from_static(b"value 8@0x10"),
8641 4 : Bytes::from_static(b"value 9@0x10"),
8642 4 : ];
8643 44 : for idx in 0..10 {
8644 40 : assert_eq!(
8645 40 : image_at_gc_horizon[idx],
8646 40 : (get_key(idx as u32), expected_result[idx].clone())
8647 40 : );
8648 4 : }
8649 4 :
8650 4 : // Check if old layers are removed / new layers have the expected LSN
8651 4 : let all_layers = inspect_and_sort(&tline, None).await;
8652 4 : assert_eq!(
8653 4 : all_layers,
8654 4 : vec![
8655 4 : // Image layer at GC horizon
8656 4 : PersistentLayerKey {
8657 4 : key_range: Key::MIN..Key::MAX,
8658 4 : lsn_range: Lsn(0x30)..Lsn(0x31),
8659 4 : is_delta: false
8660 4 : },
8661 4 : // The delta layer below the horizon
8662 4 : PersistentLayerKey {
8663 4 : key_range: get_key(3)..get_key(4),
8664 4 : lsn_range: Lsn(0x30)..Lsn(0x48),
8665 4 : is_delta: true
8666 4 : },
8667 4 : // The delta3 layer that should not be picked for the compaction
8668 4 : PersistentLayerKey {
8669 4 : key_range: get_key(8)..get_key(10),
8670 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
8671 4 : is_delta: true
8672 4 : }
8673 4 : ]
8674 4 : );
8675 4 :
8676 4 : // increase GC horizon and compact again
8677 4 : {
8678 4 : tline
8679 4 : .applied_gc_cutoff_lsn
8680 4 : .lock_for_write()
8681 4 : .store_and_unlock(Lsn(0x40))
8682 4 : .wait()
8683 4 : .await;
8684 4 : // Update GC info
8685 4 : let mut guard = tline.gc_info.write().unwrap();
8686 4 : guard.cutoffs.time = Lsn(0x40);
8687 4 : guard.cutoffs.space = Lsn(0x40);
8688 4 : }
8689 4 : tline
8690 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
8691 4 : .await
8692 4 : .unwrap();
8693 4 :
8694 4 : Ok(())
8695 4 : }
8696 :
8697 : #[cfg(feature = "testing")]
8698 : #[tokio::test]
8699 4 : async fn test_neon_test_record() -> anyhow::Result<()> {
8700 4 : let harness = TenantHarness::create("test_neon_test_record").await?;
8701 4 : let (tenant, ctx) = harness.load().await;
8702 4 :
8703 48 : fn get_key(id: u32) -> Key {
8704 48 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8705 48 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8706 48 : key.field6 = id;
8707 48 : key
8708 48 : }
8709 4 :
8710 4 : let delta1 = vec![
8711 4 : (
8712 4 : get_key(1),
8713 4 : Lsn(0x20),
8714 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
8715 4 : ),
8716 4 : (
8717 4 : get_key(1),
8718 4 : Lsn(0x30),
8719 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
8720 4 : ),
8721 4 : (get_key(2), Lsn(0x10), Value::Image("0x10".into())),
8722 4 : (
8723 4 : get_key(2),
8724 4 : Lsn(0x20),
8725 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x20")),
8726 4 : ),
8727 4 : (
8728 4 : get_key(2),
8729 4 : Lsn(0x30),
8730 4 : Value::WalRecord(NeonWalRecord::wal_append(",0x30")),
8731 4 : ),
8732 4 : (get_key(3), Lsn(0x10), Value::Image("0x10".into())),
8733 4 : (
8734 4 : get_key(3),
8735 4 : Lsn(0x20),
8736 4 : Value::WalRecord(NeonWalRecord::wal_clear("c")),
8737 4 : ),
8738 4 : (get_key(4), Lsn(0x10), Value::Image("0x10".into())),
8739 4 : (
8740 4 : get_key(4),
8741 4 : Lsn(0x20),
8742 4 : Value::WalRecord(NeonWalRecord::wal_init("i")),
8743 4 : ),
8744 4 : ];
8745 4 : let image1 = vec![(get_key(1), "0x10".into())];
8746 4 :
8747 4 : let tline = tenant
8748 4 : .create_test_timeline_with_layers(
8749 4 : TIMELINE_ID,
8750 4 : Lsn(0x10),
8751 4 : DEFAULT_PG_VERSION,
8752 4 : &ctx,
8753 4 : Vec::new(), // in-memory layers
8754 4 : vec![DeltaLayerTestDesc::new_with_inferred_key_range(
8755 4 : Lsn(0x10)..Lsn(0x40),
8756 4 : delta1,
8757 4 : )], // delta layers
8758 4 : vec![(Lsn(0x10), image1)], // image layers
8759 4 : Lsn(0x50),
8760 4 : )
8761 4 : .await?;
8762 4 :
8763 4 : assert_eq!(
8764 4 : tline.get(get_key(1), Lsn(0x50), &ctx).await?,
8765 4 : Bytes::from_static(b"0x10,0x20,0x30")
8766 4 : );
8767 4 : assert_eq!(
8768 4 : tline.get(get_key(2), Lsn(0x50), &ctx).await?,
8769 4 : Bytes::from_static(b"0x10,0x20,0x30")
8770 4 : );
8771 4 :
8772 4 : // Need to remove the limit of "Neon WAL redo requires base image".
8773 4 :
8774 4 : // assert_eq!(tline.get(get_key(3), Lsn(0x50), &ctx).await?, Bytes::new());
8775 4 : // assert_eq!(tline.get(get_key(4), Lsn(0x50), &ctx).await?, Bytes::new());
8776 4 :
8777 4 : Ok(())
8778 4 : }
8779 :
8780 : #[tokio::test(start_paused = true)]
8781 4 : async fn test_lsn_lease() -> anyhow::Result<()> {
8782 4 : let (tenant, ctx) = TenantHarness::create("test_lsn_lease")
8783 4 : .await
8784 4 : .unwrap()
8785 4 : .load()
8786 4 : .await;
8787 4 : // Advance to the lsn lease deadline so that GC is not blocked by
8788 4 : // initial transition into AttachedSingle.
8789 4 : tokio::time::advance(tenant.get_lsn_lease_length()).await;
8790 4 : tokio::time::resume();
8791 4 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
8792 4 :
8793 4 : let end_lsn = Lsn(0x100);
8794 4 : let image_layers = (0x20..=0x90)
8795 4 : .step_by(0x10)
8796 32 : .map(|n| {
8797 32 : (
8798 32 : Lsn(n),
8799 32 : vec![(key, test_img(&format!("data key at {:x}", n)))],
8800 32 : )
8801 32 : })
8802 4 : .collect();
8803 4 :
8804 4 : let timeline = tenant
8805 4 : .create_test_timeline_with_layers(
8806 4 : TIMELINE_ID,
8807 4 : Lsn(0x10),
8808 4 : DEFAULT_PG_VERSION,
8809 4 : &ctx,
8810 4 : Vec::new(), // in-memory layers
8811 4 : Vec::new(),
8812 4 : image_layers,
8813 4 : end_lsn,
8814 4 : )
8815 4 : .await?;
8816 4 :
8817 4 : let leased_lsns = [0x30, 0x50, 0x70];
8818 4 : let mut leases = Vec::new();
8819 12 : leased_lsns.iter().for_each(|n| {
8820 12 : leases.push(
8821 12 : timeline
8822 12 : .init_lsn_lease(Lsn(*n), timeline.get_lsn_lease_length(), &ctx)
8823 12 : .expect("lease request should succeed"),
8824 12 : );
8825 12 : });
8826 4 :
8827 4 : let updated_lease_0 = timeline
8828 4 : .renew_lsn_lease(Lsn(leased_lsns[0]), Duration::from_secs(0), &ctx)
8829 4 : .expect("lease renewal should succeed");
8830 4 : assert_eq!(
8831 4 : updated_lease_0.valid_until, leases[0].valid_until,
8832 4 : " Renewing with shorter lease should not change the lease."
8833 4 : );
8834 4 :
8835 4 : let updated_lease_1 = timeline
8836 4 : .renew_lsn_lease(
8837 4 : Lsn(leased_lsns[1]),
8838 4 : timeline.get_lsn_lease_length() * 2,
8839 4 : &ctx,
8840 4 : )
8841 4 : .expect("lease renewal should succeed");
8842 4 : assert!(
8843 4 : updated_lease_1.valid_until > leases[1].valid_until,
8844 4 : "Renewing with a long lease should renew lease with later expiration time."
8845 4 : );
8846 4 :
8847 4 : // Force set disk consistent lsn so we can get the cutoff at `end_lsn`.
8848 4 : info!(
8849 4 : "applied_gc_cutoff_lsn: {}",
8850 0 : *timeline.get_applied_gc_cutoff_lsn()
8851 4 : );
8852 4 : timeline.force_set_disk_consistent_lsn(end_lsn);
8853 4 :
8854 4 : let res = tenant
8855 4 : .gc_iteration(
8856 4 : Some(TIMELINE_ID),
8857 4 : 0,
8858 4 : Duration::ZERO,
8859 4 : &CancellationToken::new(),
8860 4 : &ctx,
8861 4 : )
8862 4 : .await
8863 4 : .unwrap();
8864 4 :
8865 4 : // Keeping everything <= Lsn(0x80) b/c leases:
8866 4 : // 0/10: initdb layer
8867 4 : // (0/20..=0/70).step_by(0x10): image layers added when creating the timeline.
8868 4 : assert_eq!(res.layers_needed_by_leases, 7);
8869 4 : // Keeping 0/90 b/c it is the latest layer.
8870 4 : assert_eq!(res.layers_not_updated, 1);
8871 4 : // Removed 0/80.
8872 4 : assert_eq!(res.layers_removed, 1);
8873 4 :
8874 4 : // Make lease on a already GC-ed LSN.
8875 4 : // 0/80 does not have a valid lease + is below latest_gc_cutoff
8876 4 : assert!(Lsn(0x80) < *timeline.get_applied_gc_cutoff_lsn());
8877 4 : timeline
8878 4 : .init_lsn_lease(Lsn(0x80), timeline.get_lsn_lease_length(), &ctx)
8879 4 : .expect_err("lease request on GC-ed LSN should fail");
8880 4 :
8881 4 : // Should still be able to renew a currently valid lease
8882 4 : // Assumption: original lease to is still valid for 0/50.
8883 4 : // (use `Timeline::init_lsn_lease` for testing so it always does validation)
8884 4 : timeline
8885 4 : .init_lsn_lease(Lsn(leased_lsns[1]), timeline.get_lsn_lease_length(), &ctx)
8886 4 : .expect("lease renewal with validation should succeed");
8887 4 :
8888 4 : Ok(())
8889 4 : }
8890 :
8891 : #[cfg(feature = "testing")]
8892 : #[tokio::test]
8893 4 : async fn test_simple_bottom_most_compaction_deltas_1() -> anyhow::Result<()> {
8894 4 : test_simple_bottom_most_compaction_deltas_helper(
8895 4 : "test_simple_bottom_most_compaction_deltas_1",
8896 4 : false,
8897 4 : )
8898 4 : .await
8899 4 : }
8900 :
8901 : #[cfg(feature = "testing")]
8902 : #[tokio::test]
8903 4 : async fn test_simple_bottom_most_compaction_deltas_2() -> anyhow::Result<()> {
8904 4 : test_simple_bottom_most_compaction_deltas_helper(
8905 4 : "test_simple_bottom_most_compaction_deltas_2",
8906 4 : true,
8907 4 : )
8908 4 : .await
8909 4 : }
8910 :
8911 : #[cfg(feature = "testing")]
8912 8 : async fn test_simple_bottom_most_compaction_deltas_helper(
8913 8 : test_name: &'static str,
8914 8 : use_delta_bottom_layer: bool,
8915 8 : ) -> anyhow::Result<()> {
8916 8 : let harness = TenantHarness::create(test_name).await?;
8917 8 : let (tenant, ctx) = harness.load().await;
8918 :
8919 552 : fn get_key(id: u32) -> Key {
8920 552 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
8921 552 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
8922 552 : key.field6 = id;
8923 552 : key
8924 552 : }
8925 :
8926 : // We create
8927 : // - one bottom-most image layer,
8928 : // - a delta layer D1 crossing the GC horizon with data below and above the horizon,
8929 : // - a delta layer D2 crossing the GC horizon with data only below the horizon,
8930 : // - a delta layer D3 above the horizon.
8931 : //
8932 : // | D3 |
8933 : // | D1 |
8934 : // -| |-- gc horizon -----------------
8935 : // | | | D2 |
8936 : // --------- img layer ------------------
8937 : //
8938 : // What we should expact from this compaction is:
8939 : // | D3 |
8940 : // | Part of D1 |
8941 : // --------- img layer with D1+D2 at GC horizon------------------
8942 :
8943 : // img layer at 0x10
8944 8 : let img_layer = (0..10)
8945 80 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
8946 8 : .collect_vec();
8947 8 : // or, delta layer at 0x10 if `use_delta_bottom_layer` is true
8948 8 : let delta4 = (0..10)
8949 80 : .map(|id| {
8950 80 : (
8951 80 : get_key(id),
8952 80 : Lsn(0x08),
8953 80 : Value::WalRecord(NeonWalRecord::wal_init(format!("value {id}@0x10"))),
8954 80 : )
8955 80 : })
8956 8 : .collect_vec();
8957 8 :
8958 8 : let delta1 = vec![
8959 8 : (
8960 8 : get_key(1),
8961 8 : Lsn(0x20),
8962 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8963 8 : ),
8964 8 : (
8965 8 : get_key(2),
8966 8 : Lsn(0x30),
8967 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
8968 8 : ),
8969 8 : (
8970 8 : get_key(3),
8971 8 : Lsn(0x28),
8972 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
8973 8 : ),
8974 8 : (
8975 8 : get_key(3),
8976 8 : Lsn(0x30),
8977 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
8978 8 : ),
8979 8 : (
8980 8 : get_key(3),
8981 8 : Lsn(0x40),
8982 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
8983 8 : ),
8984 8 : ];
8985 8 : let delta2 = vec![
8986 8 : (
8987 8 : get_key(5),
8988 8 : Lsn(0x20),
8989 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8990 8 : ),
8991 8 : (
8992 8 : get_key(6),
8993 8 : Lsn(0x20),
8994 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
8995 8 : ),
8996 8 : ];
8997 8 : let delta3 = vec![
8998 8 : (
8999 8 : get_key(8),
9000 8 : Lsn(0x48),
9001 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9002 8 : ),
9003 8 : (
9004 8 : get_key(9),
9005 8 : Lsn(0x48),
9006 8 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9007 8 : ),
9008 8 : ];
9009 :
9010 8 : let tline = if use_delta_bottom_layer {
9011 4 : tenant
9012 4 : .create_test_timeline_with_layers(
9013 4 : TIMELINE_ID,
9014 4 : Lsn(0x08),
9015 4 : DEFAULT_PG_VERSION,
9016 4 : &ctx,
9017 4 : Vec::new(), // in-memory layers
9018 4 : vec![
9019 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9020 4 : Lsn(0x08)..Lsn(0x10),
9021 4 : delta4,
9022 4 : ),
9023 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9024 4 : Lsn(0x20)..Lsn(0x48),
9025 4 : delta1,
9026 4 : ),
9027 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9028 4 : Lsn(0x20)..Lsn(0x48),
9029 4 : delta2,
9030 4 : ),
9031 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9032 4 : Lsn(0x48)..Lsn(0x50),
9033 4 : delta3,
9034 4 : ),
9035 4 : ], // delta layers
9036 4 : vec![], // image layers
9037 4 : Lsn(0x50),
9038 4 : )
9039 4 : .await?
9040 : } else {
9041 4 : tenant
9042 4 : .create_test_timeline_with_layers(
9043 4 : TIMELINE_ID,
9044 4 : Lsn(0x10),
9045 4 : DEFAULT_PG_VERSION,
9046 4 : &ctx,
9047 4 : Vec::new(), // in-memory layers
9048 4 : vec![
9049 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9050 4 : Lsn(0x10)..Lsn(0x48),
9051 4 : delta1,
9052 4 : ),
9053 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9054 4 : Lsn(0x10)..Lsn(0x48),
9055 4 : delta2,
9056 4 : ),
9057 4 : DeltaLayerTestDesc::new_with_inferred_key_range(
9058 4 : Lsn(0x48)..Lsn(0x50),
9059 4 : delta3,
9060 4 : ),
9061 4 : ], // delta layers
9062 4 : vec![(Lsn(0x10), img_layer)], // image layers
9063 4 : Lsn(0x50),
9064 4 : )
9065 4 : .await?
9066 : };
9067 : {
9068 8 : tline
9069 8 : .applied_gc_cutoff_lsn
9070 8 : .lock_for_write()
9071 8 : .store_and_unlock(Lsn(0x30))
9072 8 : .wait()
9073 8 : .await;
9074 : // Update GC info
9075 8 : let mut guard = tline.gc_info.write().unwrap();
9076 8 : *guard = GcInfo {
9077 8 : retain_lsns: vec![],
9078 8 : cutoffs: GcCutoffs {
9079 8 : time: Lsn(0x30),
9080 8 : space: Lsn(0x30),
9081 8 : },
9082 8 : leases: Default::default(),
9083 8 : within_ancestor_pitr: false,
9084 8 : };
9085 8 : }
9086 8 :
9087 8 : let expected_result = [
9088 8 : Bytes::from_static(b"value 0@0x10"),
9089 8 : Bytes::from_static(b"value 1@0x10@0x20"),
9090 8 : Bytes::from_static(b"value 2@0x10@0x30"),
9091 8 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
9092 8 : Bytes::from_static(b"value 4@0x10"),
9093 8 : Bytes::from_static(b"value 5@0x10@0x20"),
9094 8 : Bytes::from_static(b"value 6@0x10@0x20"),
9095 8 : Bytes::from_static(b"value 7@0x10"),
9096 8 : Bytes::from_static(b"value 8@0x10@0x48"),
9097 8 : Bytes::from_static(b"value 9@0x10@0x48"),
9098 8 : ];
9099 8 :
9100 8 : let expected_result_at_gc_horizon = [
9101 8 : Bytes::from_static(b"value 0@0x10"),
9102 8 : Bytes::from_static(b"value 1@0x10@0x20"),
9103 8 : Bytes::from_static(b"value 2@0x10@0x30"),
9104 8 : Bytes::from_static(b"value 3@0x10@0x28@0x30"),
9105 8 : Bytes::from_static(b"value 4@0x10"),
9106 8 : Bytes::from_static(b"value 5@0x10@0x20"),
9107 8 : Bytes::from_static(b"value 6@0x10@0x20"),
9108 8 : Bytes::from_static(b"value 7@0x10"),
9109 8 : Bytes::from_static(b"value 8@0x10"),
9110 8 : Bytes::from_static(b"value 9@0x10"),
9111 8 : ];
9112 :
9113 88 : for idx in 0..10 {
9114 80 : assert_eq!(
9115 80 : tline
9116 80 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9117 80 : .await
9118 80 : .unwrap(),
9119 80 : &expected_result[idx]
9120 : );
9121 80 : assert_eq!(
9122 80 : tline
9123 80 : .get(get_key(idx as u32), Lsn(0x30), &ctx)
9124 80 : .await
9125 80 : .unwrap(),
9126 80 : &expected_result_at_gc_horizon[idx]
9127 : );
9128 : }
9129 :
9130 8 : let cancel = CancellationToken::new();
9131 8 : tline
9132 8 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9133 8 : .await
9134 8 : .unwrap();
9135 :
9136 88 : for idx in 0..10 {
9137 80 : assert_eq!(
9138 80 : tline
9139 80 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9140 80 : .await
9141 80 : .unwrap(),
9142 80 : &expected_result[idx]
9143 : );
9144 80 : assert_eq!(
9145 80 : tline
9146 80 : .get(get_key(idx as u32), Lsn(0x30), &ctx)
9147 80 : .await
9148 80 : .unwrap(),
9149 80 : &expected_result_at_gc_horizon[idx]
9150 : );
9151 : }
9152 :
9153 : // increase GC horizon and compact again
9154 : {
9155 8 : tline
9156 8 : .applied_gc_cutoff_lsn
9157 8 : .lock_for_write()
9158 8 : .store_and_unlock(Lsn(0x40))
9159 8 : .wait()
9160 8 : .await;
9161 : // Update GC info
9162 8 : let mut guard = tline.gc_info.write().unwrap();
9163 8 : guard.cutoffs.time = Lsn(0x40);
9164 8 : guard.cutoffs.space = Lsn(0x40);
9165 8 : }
9166 8 : tline
9167 8 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9168 8 : .await
9169 8 : .unwrap();
9170 8 :
9171 8 : Ok(())
9172 8 : }
9173 :
9174 : #[cfg(feature = "testing")]
9175 : #[tokio::test]
9176 4 : async fn test_generate_key_retention() -> anyhow::Result<()> {
9177 4 : let harness = TenantHarness::create("test_generate_key_retention").await?;
9178 4 : let (tenant, ctx) = harness.load().await;
9179 4 : let tline = tenant
9180 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
9181 4 : .await?;
9182 4 : tline.force_advance_lsn(Lsn(0x70));
9183 4 : let key = Key::from_hex("010000000033333333444444445500000000").unwrap();
9184 4 : let history = vec![
9185 4 : (
9186 4 : key,
9187 4 : Lsn(0x10),
9188 4 : Value::WalRecord(NeonWalRecord::wal_init("0x10")),
9189 4 : ),
9190 4 : (
9191 4 : key,
9192 4 : Lsn(0x20),
9193 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9194 4 : ),
9195 4 : (
9196 4 : key,
9197 4 : Lsn(0x30),
9198 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9199 4 : ),
9200 4 : (
9201 4 : key,
9202 4 : Lsn(0x40),
9203 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9204 4 : ),
9205 4 : (
9206 4 : key,
9207 4 : Lsn(0x50),
9208 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9209 4 : ),
9210 4 : (
9211 4 : key,
9212 4 : Lsn(0x60),
9213 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9214 4 : ),
9215 4 : (
9216 4 : key,
9217 4 : Lsn(0x70),
9218 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9219 4 : ),
9220 4 : (
9221 4 : key,
9222 4 : Lsn(0x80),
9223 4 : Value::Image(Bytes::copy_from_slice(
9224 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9225 4 : )),
9226 4 : ),
9227 4 : (
9228 4 : key,
9229 4 : Lsn(0x90),
9230 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9231 4 : ),
9232 4 : ];
9233 4 : let res = tline
9234 4 : .generate_key_retention(
9235 4 : key,
9236 4 : &history,
9237 4 : Lsn(0x60),
9238 4 : &[Lsn(0x20), Lsn(0x40), Lsn(0x50)],
9239 4 : 3,
9240 4 : None,
9241 4 : )
9242 4 : .await
9243 4 : .unwrap();
9244 4 : let expected_res = KeyHistoryRetention {
9245 4 : below_horizon: vec![
9246 4 : (
9247 4 : Lsn(0x20),
9248 4 : KeyLogAtLsn(vec![(
9249 4 : Lsn(0x20),
9250 4 : Value::Image(Bytes::from_static(b"0x10;0x20")),
9251 4 : )]),
9252 4 : ),
9253 4 : (
9254 4 : Lsn(0x40),
9255 4 : KeyLogAtLsn(vec![
9256 4 : (
9257 4 : Lsn(0x30),
9258 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9259 4 : ),
9260 4 : (
9261 4 : Lsn(0x40),
9262 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9263 4 : ),
9264 4 : ]),
9265 4 : ),
9266 4 : (
9267 4 : Lsn(0x50),
9268 4 : KeyLogAtLsn(vec![(
9269 4 : Lsn(0x50),
9270 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40;0x50")),
9271 4 : )]),
9272 4 : ),
9273 4 : (
9274 4 : Lsn(0x60),
9275 4 : KeyLogAtLsn(vec![(
9276 4 : Lsn(0x60),
9277 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9278 4 : )]),
9279 4 : ),
9280 4 : ],
9281 4 : above_horizon: KeyLogAtLsn(vec![
9282 4 : (
9283 4 : Lsn(0x70),
9284 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9285 4 : ),
9286 4 : (
9287 4 : Lsn(0x80),
9288 4 : Value::Image(Bytes::copy_from_slice(
9289 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9290 4 : )),
9291 4 : ),
9292 4 : (
9293 4 : Lsn(0x90),
9294 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9295 4 : ),
9296 4 : ]),
9297 4 : };
9298 4 : assert_eq!(res, expected_res);
9299 4 :
9300 4 : // We expect GC-compaction to run with the original GC. This would create a situation that
9301 4 : // the original GC algorithm removes some delta layers b/c there are full image coverage,
9302 4 : // therefore causing some keys to have an incomplete history below the lowest retain LSN.
9303 4 : // For example, we have
9304 4 : // ```plain
9305 4 : // init delta @ 0x10, image @ 0x20, delta @ 0x30 (gc_horizon), image @ 0x40.
9306 4 : // ```
9307 4 : // Now the GC horizon moves up, and we have
9308 4 : // ```plain
9309 4 : // init delta @ 0x10, image @ 0x20, delta @ 0x30, image @ 0x40 (gc_horizon)
9310 4 : // ```
9311 4 : // The original GC algorithm kicks in, and removes delta @ 0x10, image @ 0x20.
9312 4 : // We will end up with
9313 4 : // ```plain
9314 4 : // delta @ 0x30, image @ 0x40 (gc_horizon)
9315 4 : // ```
9316 4 : // Now we run the GC-compaction, and this key does not have a full history.
9317 4 : // We should be able to handle this partial history and drop everything before the
9318 4 : // gc_horizon image.
9319 4 :
9320 4 : let history = vec![
9321 4 : (
9322 4 : key,
9323 4 : Lsn(0x20),
9324 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9325 4 : ),
9326 4 : (
9327 4 : key,
9328 4 : Lsn(0x30),
9329 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9330 4 : ),
9331 4 : (
9332 4 : key,
9333 4 : Lsn(0x40),
9334 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
9335 4 : ),
9336 4 : (
9337 4 : key,
9338 4 : Lsn(0x50),
9339 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9340 4 : ),
9341 4 : (
9342 4 : key,
9343 4 : Lsn(0x60),
9344 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9345 4 : ),
9346 4 : (
9347 4 : key,
9348 4 : Lsn(0x70),
9349 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9350 4 : ),
9351 4 : (
9352 4 : key,
9353 4 : Lsn(0x80),
9354 4 : Value::Image(Bytes::copy_from_slice(
9355 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9356 4 : )),
9357 4 : ),
9358 4 : (
9359 4 : key,
9360 4 : Lsn(0x90),
9361 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9362 4 : ),
9363 4 : ];
9364 4 : let res = tline
9365 4 : .generate_key_retention(key, &history, Lsn(0x60), &[Lsn(0x40), Lsn(0x50)], 3, None)
9366 4 : .await
9367 4 : .unwrap();
9368 4 : let expected_res = KeyHistoryRetention {
9369 4 : below_horizon: vec![
9370 4 : (
9371 4 : Lsn(0x40),
9372 4 : KeyLogAtLsn(vec![(
9373 4 : Lsn(0x40),
9374 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")),
9375 4 : )]),
9376 4 : ),
9377 4 : (
9378 4 : Lsn(0x50),
9379 4 : KeyLogAtLsn(vec![(
9380 4 : Lsn(0x50),
9381 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x50")),
9382 4 : )]),
9383 4 : ),
9384 4 : (
9385 4 : Lsn(0x60),
9386 4 : KeyLogAtLsn(vec![(
9387 4 : Lsn(0x60),
9388 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9389 4 : )]),
9390 4 : ),
9391 4 : ],
9392 4 : above_horizon: KeyLogAtLsn(vec![
9393 4 : (
9394 4 : Lsn(0x70),
9395 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9396 4 : ),
9397 4 : (
9398 4 : Lsn(0x80),
9399 4 : Value::Image(Bytes::copy_from_slice(
9400 4 : b"0x10;0x20;0x30;0x40;0x50;0x60;0x70;0x80",
9401 4 : )),
9402 4 : ),
9403 4 : (
9404 4 : Lsn(0x90),
9405 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x90")),
9406 4 : ),
9407 4 : ]),
9408 4 : };
9409 4 : assert_eq!(res, expected_res);
9410 4 :
9411 4 : // In case of branch compaction, the branch itself does not have the full history, and we need to provide
9412 4 : // the ancestor image in the test case.
9413 4 :
9414 4 : let history = vec![
9415 4 : (
9416 4 : key,
9417 4 : Lsn(0x20),
9418 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9419 4 : ),
9420 4 : (
9421 4 : key,
9422 4 : Lsn(0x30),
9423 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x30")),
9424 4 : ),
9425 4 : (
9426 4 : key,
9427 4 : Lsn(0x40),
9428 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9429 4 : ),
9430 4 : (
9431 4 : key,
9432 4 : Lsn(0x70),
9433 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9434 4 : ),
9435 4 : ];
9436 4 : let res = tline
9437 4 : .generate_key_retention(
9438 4 : key,
9439 4 : &history,
9440 4 : Lsn(0x60),
9441 4 : &[],
9442 4 : 3,
9443 4 : Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
9444 4 : )
9445 4 : .await
9446 4 : .unwrap();
9447 4 : let expected_res = KeyHistoryRetention {
9448 4 : below_horizon: vec![(
9449 4 : Lsn(0x60),
9450 4 : KeyLogAtLsn(vec![(
9451 4 : Lsn(0x60),
9452 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x30;0x40")), // use the ancestor image to reconstruct the page
9453 4 : )]),
9454 4 : )],
9455 4 : above_horizon: KeyLogAtLsn(vec![(
9456 4 : Lsn(0x70),
9457 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9458 4 : )]),
9459 4 : };
9460 4 : assert_eq!(res, expected_res);
9461 4 :
9462 4 : let history = vec![
9463 4 : (
9464 4 : key,
9465 4 : Lsn(0x20),
9466 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9467 4 : ),
9468 4 : (
9469 4 : key,
9470 4 : Lsn(0x40),
9471 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x40")),
9472 4 : ),
9473 4 : (
9474 4 : key,
9475 4 : Lsn(0x60),
9476 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x60")),
9477 4 : ),
9478 4 : (
9479 4 : key,
9480 4 : Lsn(0x70),
9481 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9482 4 : ),
9483 4 : ];
9484 4 : let res = tline
9485 4 : .generate_key_retention(
9486 4 : key,
9487 4 : &history,
9488 4 : Lsn(0x60),
9489 4 : &[Lsn(0x30)],
9490 4 : 3,
9491 4 : Some((key, Lsn(0x10), Bytes::copy_from_slice(b"0x10"))),
9492 4 : )
9493 4 : .await
9494 4 : .unwrap();
9495 4 : let expected_res = KeyHistoryRetention {
9496 4 : below_horizon: vec![
9497 4 : (
9498 4 : Lsn(0x30),
9499 4 : KeyLogAtLsn(vec![(
9500 4 : Lsn(0x20),
9501 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x20")),
9502 4 : )]),
9503 4 : ),
9504 4 : (
9505 4 : Lsn(0x60),
9506 4 : KeyLogAtLsn(vec![(
9507 4 : Lsn(0x60),
9508 4 : Value::Image(Bytes::copy_from_slice(b"0x10;0x20;0x40;0x60")),
9509 4 : )]),
9510 4 : ),
9511 4 : ],
9512 4 : above_horizon: KeyLogAtLsn(vec![(
9513 4 : Lsn(0x70),
9514 4 : Value::WalRecord(NeonWalRecord::wal_append(";0x70")),
9515 4 : )]),
9516 4 : };
9517 4 : assert_eq!(res, expected_res);
9518 4 :
9519 4 : Ok(())
9520 4 : }
9521 :
9522 : #[cfg(feature = "testing")]
9523 : #[tokio::test]
9524 4 : async fn test_simple_bottom_most_compaction_with_retain_lsns() -> anyhow::Result<()> {
9525 4 : let harness =
9526 4 : TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns").await?;
9527 4 : let (tenant, ctx) = harness.load().await;
9528 4 :
9529 1036 : fn get_key(id: u32) -> Key {
9530 1036 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
9531 1036 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
9532 1036 : key.field6 = id;
9533 1036 : key
9534 1036 : }
9535 4 :
9536 4 : let img_layer = (0..10)
9537 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9538 4 : .collect_vec();
9539 4 :
9540 4 : let delta1 = vec![
9541 4 : (
9542 4 : get_key(1),
9543 4 : Lsn(0x20),
9544 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9545 4 : ),
9546 4 : (
9547 4 : get_key(2),
9548 4 : Lsn(0x30),
9549 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9550 4 : ),
9551 4 : (
9552 4 : get_key(3),
9553 4 : Lsn(0x28),
9554 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9555 4 : ),
9556 4 : (
9557 4 : get_key(3),
9558 4 : Lsn(0x30),
9559 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9560 4 : ),
9561 4 : (
9562 4 : get_key(3),
9563 4 : Lsn(0x40),
9564 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
9565 4 : ),
9566 4 : ];
9567 4 : let delta2 = vec![
9568 4 : (
9569 4 : get_key(5),
9570 4 : Lsn(0x20),
9571 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9572 4 : ),
9573 4 : (
9574 4 : get_key(6),
9575 4 : Lsn(0x20),
9576 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9577 4 : ),
9578 4 : ];
9579 4 : let delta3 = vec![
9580 4 : (
9581 4 : get_key(8),
9582 4 : Lsn(0x48),
9583 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9584 4 : ),
9585 4 : (
9586 4 : get_key(9),
9587 4 : Lsn(0x48),
9588 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9589 4 : ),
9590 4 : ];
9591 4 :
9592 4 : let tline = tenant
9593 4 : .create_test_timeline_with_layers(
9594 4 : TIMELINE_ID,
9595 4 : Lsn(0x10),
9596 4 : DEFAULT_PG_VERSION,
9597 4 : &ctx,
9598 4 : Vec::new(), // in-memory layers
9599 4 : vec![
9600 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta1),
9601 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x48), delta2),
9602 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
9603 4 : ], // delta layers
9604 4 : vec![(Lsn(0x10), img_layer)], // image layers
9605 4 : Lsn(0x50),
9606 4 : )
9607 4 : .await?;
9608 4 : {
9609 4 : tline
9610 4 : .applied_gc_cutoff_lsn
9611 4 : .lock_for_write()
9612 4 : .store_and_unlock(Lsn(0x30))
9613 4 : .wait()
9614 4 : .await;
9615 4 : // Update GC info
9616 4 : let mut guard = tline.gc_info.write().unwrap();
9617 4 : *guard = GcInfo {
9618 4 : retain_lsns: vec![
9619 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
9620 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
9621 4 : ],
9622 4 : cutoffs: GcCutoffs {
9623 4 : time: Lsn(0x30),
9624 4 : space: Lsn(0x30),
9625 4 : },
9626 4 : leases: Default::default(),
9627 4 : within_ancestor_pitr: false,
9628 4 : };
9629 4 : }
9630 4 :
9631 4 : let expected_result = [
9632 4 : Bytes::from_static(b"value 0@0x10"),
9633 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9634 4 : Bytes::from_static(b"value 2@0x10@0x30"),
9635 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
9636 4 : Bytes::from_static(b"value 4@0x10"),
9637 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9638 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9639 4 : Bytes::from_static(b"value 7@0x10"),
9640 4 : Bytes::from_static(b"value 8@0x10@0x48"),
9641 4 : Bytes::from_static(b"value 9@0x10@0x48"),
9642 4 : ];
9643 4 :
9644 4 : let expected_result_at_gc_horizon = [
9645 4 : Bytes::from_static(b"value 0@0x10"),
9646 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9647 4 : Bytes::from_static(b"value 2@0x10@0x30"),
9648 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30"),
9649 4 : Bytes::from_static(b"value 4@0x10"),
9650 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9651 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9652 4 : Bytes::from_static(b"value 7@0x10"),
9653 4 : Bytes::from_static(b"value 8@0x10"),
9654 4 : Bytes::from_static(b"value 9@0x10"),
9655 4 : ];
9656 4 :
9657 4 : let expected_result_at_lsn_20 = [
9658 4 : Bytes::from_static(b"value 0@0x10"),
9659 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9660 4 : Bytes::from_static(b"value 2@0x10"),
9661 4 : Bytes::from_static(b"value 3@0x10"),
9662 4 : Bytes::from_static(b"value 4@0x10"),
9663 4 : Bytes::from_static(b"value 5@0x10@0x20"),
9664 4 : Bytes::from_static(b"value 6@0x10@0x20"),
9665 4 : Bytes::from_static(b"value 7@0x10"),
9666 4 : Bytes::from_static(b"value 8@0x10"),
9667 4 : Bytes::from_static(b"value 9@0x10"),
9668 4 : ];
9669 4 :
9670 4 : let expected_result_at_lsn_10 = [
9671 4 : Bytes::from_static(b"value 0@0x10"),
9672 4 : Bytes::from_static(b"value 1@0x10"),
9673 4 : Bytes::from_static(b"value 2@0x10"),
9674 4 : Bytes::from_static(b"value 3@0x10"),
9675 4 : Bytes::from_static(b"value 4@0x10"),
9676 4 : Bytes::from_static(b"value 5@0x10"),
9677 4 : Bytes::from_static(b"value 6@0x10"),
9678 4 : Bytes::from_static(b"value 7@0x10"),
9679 4 : Bytes::from_static(b"value 8@0x10"),
9680 4 : Bytes::from_static(b"value 9@0x10"),
9681 4 : ];
9682 4 :
9683 24 : let verify_result = || async {
9684 24 : let gc_horizon = {
9685 24 : let gc_info = tline.gc_info.read().unwrap();
9686 24 : gc_info.cutoffs.time
9687 4 : };
9688 264 : for idx in 0..10 {
9689 240 : assert_eq!(
9690 240 : tline
9691 240 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9692 240 : .await
9693 240 : .unwrap(),
9694 240 : &expected_result[idx]
9695 4 : );
9696 240 : assert_eq!(
9697 240 : tline
9698 240 : .get(get_key(idx as u32), gc_horizon, &ctx)
9699 240 : .await
9700 240 : .unwrap(),
9701 240 : &expected_result_at_gc_horizon[idx]
9702 4 : );
9703 240 : assert_eq!(
9704 240 : tline
9705 240 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
9706 240 : .await
9707 240 : .unwrap(),
9708 240 : &expected_result_at_lsn_20[idx]
9709 4 : );
9710 240 : assert_eq!(
9711 240 : tline
9712 240 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
9713 240 : .await
9714 240 : .unwrap(),
9715 240 : &expected_result_at_lsn_10[idx]
9716 4 : );
9717 4 : }
9718 48 : };
9719 4 :
9720 4 : verify_result().await;
9721 4 :
9722 4 : let cancel = CancellationToken::new();
9723 4 : let mut dryrun_flags = EnumSet::new();
9724 4 : dryrun_flags.insert(CompactFlags::DryRun);
9725 4 :
9726 4 : tline
9727 4 : .compact_with_gc(
9728 4 : &cancel,
9729 4 : CompactOptions {
9730 4 : flags: dryrun_flags,
9731 4 : ..Default::default()
9732 4 : },
9733 4 : &ctx,
9734 4 : )
9735 4 : .await
9736 4 : .unwrap();
9737 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
9738 4 : // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
9739 4 : verify_result().await;
9740 4 :
9741 4 : tline
9742 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9743 4 : .await
9744 4 : .unwrap();
9745 4 : verify_result().await;
9746 4 :
9747 4 : // compact again
9748 4 : tline
9749 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9750 4 : .await
9751 4 : .unwrap();
9752 4 : verify_result().await;
9753 4 :
9754 4 : // increase GC horizon and compact again
9755 4 : {
9756 4 : tline
9757 4 : .applied_gc_cutoff_lsn
9758 4 : .lock_for_write()
9759 4 : .store_and_unlock(Lsn(0x38))
9760 4 : .wait()
9761 4 : .await;
9762 4 : // Update GC info
9763 4 : let mut guard = tline.gc_info.write().unwrap();
9764 4 : guard.cutoffs.time = Lsn(0x38);
9765 4 : guard.cutoffs.space = Lsn(0x38);
9766 4 : }
9767 4 : tline
9768 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9769 4 : .await
9770 4 : .unwrap();
9771 4 : verify_result().await; // no wals between 0x30 and 0x38, so we should obtain the same result
9772 4 :
9773 4 : // not increasing the GC horizon and compact again
9774 4 : tline
9775 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9776 4 : .await
9777 4 : .unwrap();
9778 4 : verify_result().await;
9779 4 :
9780 4 : Ok(())
9781 4 : }
9782 :
9783 : #[cfg(feature = "testing")]
9784 : #[tokio::test]
9785 4 : async fn test_simple_bottom_most_compaction_with_retain_lsns_single_key() -> anyhow::Result<()>
9786 4 : {
9787 4 : let harness =
9788 4 : TenantHarness::create("test_simple_bottom_most_compaction_with_retain_lsns_single_key")
9789 4 : .await?;
9790 4 : let (tenant, ctx) = harness.load().await;
9791 4 :
9792 704 : fn get_key(id: u32) -> Key {
9793 704 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
9794 704 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
9795 704 : key.field6 = id;
9796 704 : key
9797 704 : }
9798 4 :
9799 4 : let img_layer = (0..10)
9800 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
9801 4 : .collect_vec();
9802 4 :
9803 4 : let delta1 = vec![
9804 4 : (
9805 4 : get_key(1),
9806 4 : Lsn(0x20),
9807 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
9808 4 : ),
9809 4 : (
9810 4 : get_key(1),
9811 4 : Lsn(0x28),
9812 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
9813 4 : ),
9814 4 : ];
9815 4 : let delta2 = vec![
9816 4 : (
9817 4 : get_key(1),
9818 4 : Lsn(0x30),
9819 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
9820 4 : ),
9821 4 : (
9822 4 : get_key(1),
9823 4 : Lsn(0x38),
9824 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
9825 4 : ),
9826 4 : ];
9827 4 : let delta3 = vec![
9828 4 : (
9829 4 : get_key(8),
9830 4 : Lsn(0x48),
9831 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9832 4 : ),
9833 4 : (
9834 4 : get_key(9),
9835 4 : Lsn(0x48),
9836 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
9837 4 : ),
9838 4 : ];
9839 4 :
9840 4 : let tline = tenant
9841 4 : .create_test_timeline_with_layers(
9842 4 : TIMELINE_ID,
9843 4 : Lsn(0x10),
9844 4 : DEFAULT_PG_VERSION,
9845 4 : &ctx,
9846 4 : Vec::new(), // in-memory layers
9847 4 : vec![
9848 4 : // delta1 and delta 2 only contain a single key but multiple updates
9849 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x30), delta1),
9850 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
9851 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x10)..Lsn(0x50), delta3),
9852 4 : ], // delta layers
9853 4 : vec![(Lsn(0x10), img_layer)], // image layers
9854 4 : Lsn(0x50),
9855 4 : )
9856 4 : .await?;
9857 4 : {
9858 4 : tline
9859 4 : .applied_gc_cutoff_lsn
9860 4 : .lock_for_write()
9861 4 : .store_and_unlock(Lsn(0x30))
9862 4 : .wait()
9863 4 : .await;
9864 4 : // Update GC info
9865 4 : let mut guard = tline.gc_info.write().unwrap();
9866 4 : *guard = GcInfo {
9867 4 : retain_lsns: vec![
9868 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
9869 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
9870 4 : ],
9871 4 : cutoffs: GcCutoffs {
9872 4 : time: Lsn(0x30),
9873 4 : space: Lsn(0x30),
9874 4 : },
9875 4 : leases: Default::default(),
9876 4 : within_ancestor_pitr: false,
9877 4 : };
9878 4 : }
9879 4 :
9880 4 : let expected_result = [
9881 4 : Bytes::from_static(b"value 0@0x10"),
9882 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
9883 4 : Bytes::from_static(b"value 2@0x10"),
9884 4 : Bytes::from_static(b"value 3@0x10"),
9885 4 : Bytes::from_static(b"value 4@0x10"),
9886 4 : Bytes::from_static(b"value 5@0x10"),
9887 4 : Bytes::from_static(b"value 6@0x10"),
9888 4 : Bytes::from_static(b"value 7@0x10"),
9889 4 : Bytes::from_static(b"value 8@0x10@0x48"),
9890 4 : Bytes::from_static(b"value 9@0x10@0x48"),
9891 4 : ];
9892 4 :
9893 4 : let expected_result_at_gc_horizon = [
9894 4 : Bytes::from_static(b"value 0@0x10"),
9895 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
9896 4 : Bytes::from_static(b"value 2@0x10"),
9897 4 : Bytes::from_static(b"value 3@0x10"),
9898 4 : Bytes::from_static(b"value 4@0x10"),
9899 4 : Bytes::from_static(b"value 5@0x10"),
9900 4 : Bytes::from_static(b"value 6@0x10"),
9901 4 : Bytes::from_static(b"value 7@0x10"),
9902 4 : Bytes::from_static(b"value 8@0x10"),
9903 4 : Bytes::from_static(b"value 9@0x10"),
9904 4 : ];
9905 4 :
9906 4 : let expected_result_at_lsn_20 = [
9907 4 : Bytes::from_static(b"value 0@0x10"),
9908 4 : Bytes::from_static(b"value 1@0x10@0x20"),
9909 4 : Bytes::from_static(b"value 2@0x10"),
9910 4 : Bytes::from_static(b"value 3@0x10"),
9911 4 : Bytes::from_static(b"value 4@0x10"),
9912 4 : Bytes::from_static(b"value 5@0x10"),
9913 4 : Bytes::from_static(b"value 6@0x10"),
9914 4 : Bytes::from_static(b"value 7@0x10"),
9915 4 : Bytes::from_static(b"value 8@0x10"),
9916 4 : Bytes::from_static(b"value 9@0x10"),
9917 4 : ];
9918 4 :
9919 4 : let expected_result_at_lsn_10 = [
9920 4 : Bytes::from_static(b"value 0@0x10"),
9921 4 : Bytes::from_static(b"value 1@0x10"),
9922 4 : Bytes::from_static(b"value 2@0x10"),
9923 4 : Bytes::from_static(b"value 3@0x10"),
9924 4 : Bytes::from_static(b"value 4@0x10"),
9925 4 : Bytes::from_static(b"value 5@0x10"),
9926 4 : Bytes::from_static(b"value 6@0x10"),
9927 4 : Bytes::from_static(b"value 7@0x10"),
9928 4 : Bytes::from_static(b"value 8@0x10"),
9929 4 : Bytes::from_static(b"value 9@0x10"),
9930 4 : ];
9931 4 :
9932 16 : let verify_result = || async {
9933 16 : let gc_horizon = {
9934 16 : let gc_info = tline.gc_info.read().unwrap();
9935 16 : gc_info.cutoffs.time
9936 4 : };
9937 176 : for idx in 0..10 {
9938 160 : assert_eq!(
9939 160 : tline
9940 160 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
9941 160 : .await
9942 160 : .unwrap(),
9943 160 : &expected_result[idx]
9944 4 : );
9945 160 : assert_eq!(
9946 160 : tline
9947 160 : .get(get_key(idx as u32), gc_horizon, &ctx)
9948 160 : .await
9949 160 : .unwrap(),
9950 160 : &expected_result_at_gc_horizon[idx]
9951 4 : );
9952 160 : assert_eq!(
9953 160 : tline
9954 160 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
9955 160 : .await
9956 160 : .unwrap(),
9957 160 : &expected_result_at_lsn_20[idx]
9958 4 : );
9959 160 : assert_eq!(
9960 160 : tline
9961 160 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
9962 160 : .await
9963 160 : .unwrap(),
9964 160 : &expected_result_at_lsn_10[idx]
9965 4 : );
9966 4 : }
9967 32 : };
9968 4 :
9969 4 : verify_result().await;
9970 4 :
9971 4 : let cancel = CancellationToken::new();
9972 4 : let mut dryrun_flags = EnumSet::new();
9973 4 : dryrun_flags.insert(CompactFlags::DryRun);
9974 4 :
9975 4 : tline
9976 4 : .compact_with_gc(
9977 4 : &cancel,
9978 4 : CompactOptions {
9979 4 : flags: dryrun_flags,
9980 4 : ..Default::default()
9981 4 : },
9982 4 : &ctx,
9983 4 : )
9984 4 : .await
9985 4 : .unwrap();
9986 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
9987 4 : // cleaning things up, and therefore, we don't do sanity checks on the layer map during unit tests.
9988 4 : verify_result().await;
9989 4 :
9990 4 : tline
9991 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9992 4 : .await
9993 4 : .unwrap();
9994 4 : verify_result().await;
9995 4 :
9996 4 : // compact again
9997 4 : tline
9998 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
9999 4 : .await
10000 4 : .unwrap();
10001 4 : verify_result().await;
10002 4 :
10003 4 : Ok(())
10004 4 : }
10005 :
10006 : #[cfg(feature = "testing")]
10007 : #[tokio::test]
10008 4 : async fn test_simple_bottom_most_compaction_on_branch() -> anyhow::Result<()> {
10009 4 : use models::CompactLsnRange;
10010 4 :
10011 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_on_branch").await?;
10012 4 : let (tenant, ctx) = harness.load().await;
10013 4 :
10014 332 : fn get_key(id: u32) -> Key {
10015 332 : let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
10016 332 : key.field6 = id;
10017 332 : key
10018 332 : }
10019 4 :
10020 4 : let img_layer = (0..10)
10021 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10022 4 : .collect_vec();
10023 4 :
10024 4 : let delta1 = vec![
10025 4 : (
10026 4 : get_key(1),
10027 4 : Lsn(0x20),
10028 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10029 4 : ),
10030 4 : (
10031 4 : get_key(2),
10032 4 : Lsn(0x30),
10033 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
10034 4 : ),
10035 4 : (
10036 4 : get_key(3),
10037 4 : Lsn(0x28),
10038 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
10039 4 : ),
10040 4 : (
10041 4 : get_key(3),
10042 4 : Lsn(0x30),
10043 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
10044 4 : ),
10045 4 : (
10046 4 : get_key(3),
10047 4 : Lsn(0x40),
10048 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x40")),
10049 4 : ),
10050 4 : ];
10051 4 : let delta2 = vec![
10052 4 : (
10053 4 : get_key(5),
10054 4 : Lsn(0x20),
10055 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10056 4 : ),
10057 4 : (
10058 4 : get_key(6),
10059 4 : Lsn(0x20),
10060 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10061 4 : ),
10062 4 : ];
10063 4 : let delta3 = vec![
10064 4 : (
10065 4 : get_key(8),
10066 4 : Lsn(0x48),
10067 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10068 4 : ),
10069 4 : (
10070 4 : get_key(9),
10071 4 : Lsn(0x48),
10072 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10073 4 : ),
10074 4 : ];
10075 4 :
10076 4 : let parent_tline = tenant
10077 4 : .create_test_timeline_with_layers(
10078 4 : TIMELINE_ID,
10079 4 : Lsn(0x10),
10080 4 : DEFAULT_PG_VERSION,
10081 4 : &ctx,
10082 4 : vec![], // in-memory layers
10083 4 : vec![], // delta layers
10084 4 : vec![(Lsn(0x18), img_layer)], // image layers
10085 4 : Lsn(0x18),
10086 4 : )
10087 4 : .await?;
10088 4 :
10089 4 : parent_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
10090 4 :
10091 4 : let branch_tline = tenant
10092 4 : .branch_timeline_test_with_layers(
10093 4 : &parent_tline,
10094 4 : NEW_TIMELINE_ID,
10095 4 : Some(Lsn(0x18)),
10096 4 : &ctx,
10097 4 : vec![
10098 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
10099 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
10100 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
10101 4 : ], // delta layers
10102 4 : vec![], // image layers
10103 4 : Lsn(0x50),
10104 4 : )
10105 4 : .await?;
10106 4 :
10107 4 : branch_tline.add_extra_test_dense_keyspace(KeySpace::single(get_key(0)..get_key(10)));
10108 4 :
10109 4 : {
10110 4 : parent_tline
10111 4 : .applied_gc_cutoff_lsn
10112 4 : .lock_for_write()
10113 4 : .store_and_unlock(Lsn(0x10))
10114 4 : .wait()
10115 4 : .await;
10116 4 : // Update GC info
10117 4 : let mut guard = parent_tline.gc_info.write().unwrap();
10118 4 : *guard = GcInfo {
10119 4 : retain_lsns: vec![(Lsn(0x18), branch_tline.timeline_id, MaybeOffloaded::No)],
10120 4 : cutoffs: GcCutoffs {
10121 4 : time: Lsn(0x10),
10122 4 : space: Lsn(0x10),
10123 4 : },
10124 4 : leases: Default::default(),
10125 4 : within_ancestor_pitr: false,
10126 4 : };
10127 4 : }
10128 4 :
10129 4 : {
10130 4 : branch_tline
10131 4 : .applied_gc_cutoff_lsn
10132 4 : .lock_for_write()
10133 4 : .store_and_unlock(Lsn(0x50))
10134 4 : .wait()
10135 4 : .await;
10136 4 : // Update GC info
10137 4 : let mut guard = branch_tline.gc_info.write().unwrap();
10138 4 : *guard = GcInfo {
10139 4 : retain_lsns: vec![(Lsn(0x40), branch_tline.timeline_id, MaybeOffloaded::No)],
10140 4 : cutoffs: GcCutoffs {
10141 4 : time: Lsn(0x50),
10142 4 : space: Lsn(0x50),
10143 4 : },
10144 4 : leases: Default::default(),
10145 4 : within_ancestor_pitr: false,
10146 4 : };
10147 4 : }
10148 4 :
10149 4 : let expected_result_at_gc_horizon = [
10150 4 : Bytes::from_static(b"value 0@0x10"),
10151 4 : Bytes::from_static(b"value 1@0x10@0x20"),
10152 4 : Bytes::from_static(b"value 2@0x10@0x30"),
10153 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
10154 4 : Bytes::from_static(b"value 4@0x10"),
10155 4 : Bytes::from_static(b"value 5@0x10@0x20"),
10156 4 : Bytes::from_static(b"value 6@0x10@0x20"),
10157 4 : Bytes::from_static(b"value 7@0x10"),
10158 4 : Bytes::from_static(b"value 8@0x10@0x48"),
10159 4 : Bytes::from_static(b"value 9@0x10@0x48"),
10160 4 : ];
10161 4 :
10162 4 : let expected_result_at_lsn_40 = [
10163 4 : Bytes::from_static(b"value 0@0x10"),
10164 4 : Bytes::from_static(b"value 1@0x10@0x20"),
10165 4 : Bytes::from_static(b"value 2@0x10@0x30"),
10166 4 : Bytes::from_static(b"value 3@0x10@0x28@0x30@0x40"),
10167 4 : Bytes::from_static(b"value 4@0x10"),
10168 4 : Bytes::from_static(b"value 5@0x10@0x20"),
10169 4 : Bytes::from_static(b"value 6@0x10@0x20"),
10170 4 : Bytes::from_static(b"value 7@0x10"),
10171 4 : Bytes::from_static(b"value 8@0x10"),
10172 4 : Bytes::from_static(b"value 9@0x10"),
10173 4 : ];
10174 4 :
10175 12 : let verify_result = || async {
10176 132 : for idx in 0..10 {
10177 120 : assert_eq!(
10178 120 : branch_tline
10179 120 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
10180 120 : .await
10181 120 : .unwrap(),
10182 120 : &expected_result_at_gc_horizon[idx]
10183 4 : );
10184 120 : assert_eq!(
10185 120 : branch_tline
10186 120 : .get(get_key(idx as u32), Lsn(0x40), &ctx)
10187 120 : .await
10188 120 : .unwrap(),
10189 120 : &expected_result_at_lsn_40[idx]
10190 4 : );
10191 4 : }
10192 24 : };
10193 4 :
10194 4 : verify_result().await;
10195 4 :
10196 4 : let cancel = CancellationToken::new();
10197 4 : branch_tline
10198 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
10199 4 : .await
10200 4 : .unwrap();
10201 4 :
10202 4 : verify_result().await;
10203 4 :
10204 4 : // Piggyback a compaction with above_lsn. Ensure it works correctly when the specified LSN intersects with the layer files.
10205 4 : // Now we already have a single large delta layer, so the compaction min_layer_lsn should be the same as ancestor LSN (0x18).
10206 4 : branch_tline
10207 4 : .compact_with_gc(
10208 4 : &cancel,
10209 4 : CompactOptions {
10210 4 : compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x40))),
10211 4 : ..Default::default()
10212 4 : },
10213 4 : &ctx,
10214 4 : )
10215 4 : .await
10216 4 : .unwrap();
10217 4 :
10218 4 : verify_result().await;
10219 4 :
10220 4 : Ok(())
10221 4 : }
10222 :
10223 : // Regression test for https://github.com/neondatabase/neon/issues/9012
10224 : // Create an image arrangement where we have to read at different LSN ranges
10225 : // from a delta layer. This is achieved by overlapping an image layer on top of
10226 : // a delta layer. Like so:
10227 : //
10228 : // A B
10229 : // +----------------+ -> delta_layer
10230 : // | | ^ lsn
10231 : // | =========|-> nested_image_layer |
10232 : // | C | |
10233 : // +----------------+ |
10234 : // ======== -> baseline_image_layer +-------> key
10235 : //
10236 : //
10237 : // When querying the key range [A, B) we need to read at different LSN ranges
10238 : // for [A, C) and [C, B). This test checks that the described edge case is handled correctly.
10239 : #[cfg(feature = "testing")]
10240 : #[tokio::test]
10241 4 : async fn test_vectored_read_with_nested_image_layer() -> anyhow::Result<()> {
10242 4 : let harness = TenantHarness::create("test_vectored_read_with_nested_image_layer").await?;
10243 4 : let (tenant, ctx) = harness.load().await;
10244 4 :
10245 4 : let will_init_keys = [2, 6];
10246 88 : fn get_key(id: u32) -> Key {
10247 88 : let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
10248 88 : key.field6 = id;
10249 88 : key
10250 88 : }
10251 4 :
10252 4 : let mut expected_key_values = HashMap::new();
10253 4 :
10254 4 : let baseline_image_layer_lsn = Lsn(0x10);
10255 4 : let mut baseline_img_layer = Vec::new();
10256 24 : for i in 0..5 {
10257 20 : let key = get_key(i);
10258 20 : let value = format!("value {i}@{baseline_image_layer_lsn}");
10259 20 :
10260 20 : let removed = expected_key_values.insert(key, value.clone());
10261 20 : assert!(removed.is_none());
10262 4 :
10263 20 : baseline_img_layer.push((key, Bytes::from(value)));
10264 4 : }
10265 4 :
10266 4 : let nested_image_layer_lsn = Lsn(0x50);
10267 4 : let mut nested_img_layer = Vec::new();
10268 24 : for i in 5..10 {
10269 20 : let key = get_key(i);
10270 20 : let value = format!("value {i}@{nested_image_layer_lsn}");
10271 20 :
10272 20 : let removed = expected_key_values.insert(key, value.clone());
10273 20 : assert!(removed.is_none());
10274 4 :
10275 20 : nested_img_layer.push((key, Bytes::from(value)));
10276 4 : }
10277 4 :
10278 4 : let mut delta_layer_spec = Vec::default();
10279 4 : let delta_layer_start_lsn = Lsn(0x20);
10280 4 : let mut delta_layer_end_lsn = delta_layer_start_lsn;
10281 4 :
10282 44 : for i in 0..10 {
10283 40 : let key = get_key(i);
10284 40 : let key_in_nested = nested_img_layer
10285 40 : .iter()
10286 160 : .any(|(key_with_img, _)| *key_with_img == key);
10287 40 : let lsn = {
10288 40 : if key_in_nested {
10289 20 : Lsn(nested_image_layer_lsn.0 + 0x10)
10290 4 : } else {
10291 20 : delta_layer_start_lsn
10292 4 : }
10293 4 : };
10294 4 :
10295 40 : let will_init = will_init_keys.contains(&i);
10296 40 : if will_init {
10297 8 : delta_layer_spec.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
10298 8 :
10299 8 : expected_key_values.insert(key, "".to_string());
10300 32 : } else {
10301 32 : let delta = format!("@{lsn}");
10302 32 : delta_layer_spec.push((
10303 32 : key,
10304 32 : lsn,
10305 32 : Value::WalRecord(NeonWalRecord::wal_append(&delta)),
10306 32 : ));
10307 32 :
10308 32 : expected_key_values
10309 32 : .get_mut(&key)
10310 32 : .expect("An image exists for each key")
10311 32 : .push_str(delta.as_str());
10312 32 : }
10313 40 : delta_layer_end_lsn = std::cmp::max(delta_layer_start_lsn, lsn);
10314 4 : }
10315 4 :
10316 4 : delta_layer_end_lsn = Lsn(delta_layer_end_lsn.0 + 1);
10317 4 :
10318 4 : assert!(
10319 4 : nested_image_layer_lsn > delta_layer_start_lsn
10320 4 : && nested_image_layer_lsn < delta_layer_end_lsn
10321 4 : );
10322 4 :
10323 4 : let tline = tenant
10324 4 : .create_test_timeline_with_layers(
10325 4 : TIMELINE_ID,
10326 4 : baseline_image_layer_lsn,
10327 4 : DEFAULT_PG_VERSION,
10328 4 : &ctx,
10329 4 : vec![], // in-memory layers
10330 4 : vec![DeltaLayerTestDesc::new_with_inferred_key_range(
10331 4 : delta_layer_start_lsn..delta_layer_end_lsn,
10332 4 : delta_layer_spec,
10333 4 : )], // delta layers
10334 4 : vec![
10335 4 : (baseline_image_layer_lsn, baseline_img_layer),
10336 4 : (nested_image_layer_lsn, nested_img_layer),
10337 4 : ], // image layers
10338 4 : delta_layer_end_lsn,
10339 4 : )
10340 4 : .await?;
10341 4 :
10342 4 : let keyspace = KeySpace::single(get_key(0)..get_key(10));
10343 4 : let results = tline
10344 4 : .get_vectored(
10345 4 : keyspace,
10346 4 : delta_layer_end_lsn,
10347 4 : IoConcurrency::sequential(),
10348 4 : &ctx,
10349 4 : )
10350 4 : .await
10351 4 : .expect("No vectored errors");
10352 44 : for (key, res) in results {
10353 40 : let value = res.expect("No key errors");
10354 40 : let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
10355 40 : assert_eq!(value, Bytes::from(expected_value));
10356 4 : }
10357 4 :
10358 4 : Ok(())
10359 4 : }
10360 :
10361 : #[cfg(feature = "testing")]
10362 : #[tokio::test]
10363 4 : async fn test_vectored_read_with_image_layer_inside_inmem() -> anyhow::Result<()> {
10364 4 : let harness =
10365 4 : TenantHarness::create("test_vectored_read_with_image_layer_inside_inmem").await?;
10366 4 : let (tenant, ctx) = harness.load().await;
10367 4 :
10368 4 : let will_init_keys = [2, 6];
10369 128 : fn get_key(id: u32) -> Key {
10370 128 : let mut key = Key::from_hex("110000000033333333444444445500000000").unwrap();
10371 128 : key.field6 = id;
10372 128 : key
10373 128 : }
10374 4 :
10375 4 : let mut expected_key_values = HashMap::new();
10376 4 :
10377 4 : let baseline_image_layer_lsn = Lsn(0x10);
10378 4 : let mut baseline_img_layer = Vec::new();
10379 24 : for i in 0..5 {
10380 20 : let key = get_key(i);
10381 20 : let value = format!("value {i}@{baseline_image_layer_lsn}");
10382 20 :
10383 20 : let removed = expected_key_values.insert(key, value.clone());
10384 20 : assert!(removed.is_none());
10385 4 :
10386 20 : baseline_img_layer.push((key, Bytes::from(value)));
10387 4 : }
10388 4 :
10389 4 : let nested_image_layer_lsn = Lsn(0x50);
10390 4 : let mut nested_img_layer = Vec::new();
10391 24 : for i in 5..10 {
10392 20 : let key = get_key(i);
10393 20 : let value = format!("value {i}@{nested_image_layer_lsn}");
10394 20 :
10395 20 : let removed = expected_key_values.insert(key, value.clone());
10396 20 : assert!(removed.is_none());
10397 4 :
10398 20 : nested_img_layer.push((key, Bytes::from(value)));
10399 4 : }
10400 4 :
10401 4 : let frozen_layer = {
10402 4 : let lsn_range = Lsn(0x40)..Lsn(0x60);
10403 4 : let mut data = Vec::new();
10404 44 : for i in 0..10 {
10405 40 : let key = get_key(i);
10406 40 : let key_in_nested = nested_img_layer
10407 40 : .iter()
10408 160 : .any(|(key_with_img, _)| *key_with_img == key);
10409 40 : let lsn = {
10410 40 : if key_in_nested {
10411 20 : Lsn(nested_image_layer_lsn.0 + 5)
10412 4 : } else {
10413 20 : lsn_range.start
10414 4 : }
10415 4 : };
10416 4 :
10417 40 : let will_init = will_init_keys.contains(&i);
10418 40 : if will_init {
10419 8 : data.push((key, lsn, Value::WalRecord(NeonWalRecord::wal_init(""))));
10420 8 :
10421 8 : expected_key_values.insert(key, "".to_string());
10422 32 : } else {
10423 32 : let delta = format!("@{lsn}");
10424 32 : data.push((
10425 32 : key,
10426 32 : lsn,
10427 32 : Value::WalRecord(NeonWalRecord::wal_append(&delta)),
10428 32 : ));
10429 32 :
10430 32 : expected_key_values
10431 32 : .get_mut(&key)
10432 32 : .expect("An image exists for each key")
10433 32 : .push_str(delta.as_str());
10434 32 : }
10435 4 : }
10436 4 :
10437 4 : InMemoryLayerTestDesc {
10438 4 : lsn_range,
10439 4 : is_open: false,
10440 4 : data,
10441 4 : }
10442 4 : };
10443 4 :
10444 4 : let (open_layer, last_record_lsn) = {
10445 4 : let start_lsn = Lsn(0x70);
10446 4 : let mut data = Vec::new();
10447 4 : let mut end_lsn = Lsn(0);
10448 44 : for i in 0..10 {
10449 40 : let key = get_key(i);
10450 40 : let lsn = Lsn(start_lsn.0 + i as u64);
10451 40 : let delta = format!("@{lsn}");
10452 40 : data.push((
10453 40 : key,
10454 40 : lsn,
10455 40 : Value::WalRecord(NeonWalRecord::wal_append(&delta)),
10456 40 : ));
10457 40 :
10458 40 : expected_key_values
10459 40 : .get_mut(&key)
10460 40 : .expect("An image exists for each key")
10461 40 : .push_str(delta.as_str());
10462 40 :
10463 40 : end_lsn = std::cmp::max(end_lsn, lsn);
10464 40 : }
10465 4 :
10466 4 : (
10467 4 : InMemoryLayerTestDesc {
10468 4 : lsn_range: start_lsn..Lsn::MAX,
10469 4 : is_open: true,
10470 4 : data,
10471 4 : },
10472 4 : end_lsn,
10473 4 : )
10474 4 : };
10475 4 :
10476 4 : assert!(
10477 4 : nested_image_layer_lsn > frozen_layer.lsn_range.start
10478 4 : && nested_image_layer_lsn < frozen_layer.lsn_range.end
10479 4 : );
10480 4 :
10481 4 : let tline = tenant
10482 4 : .create_test_timeline_with_layers(
10483 4 : TIMELINE_ID,
10484 4 : baseline_image_layer_lsn,
10485 4 : DEFAULT_PG_VERSION,
10486 4 : &ctx,
10487 4 : vec![open_layer, frozen_layer], // in-memory layers
10488 4 : Vec::new(), // delta layers
10489 4 : vec![
10490 4 : (baseline_image_layer_lsn, baseline_img_layer),
10491 4 : (nested_image_layer_lsn, nested_img_layer),
10492 4 : ], // image layers
10493 4 : last_record_lsn,
10494 4 : )
10495 4 : .await?;
10496 4 :
10497 4 : let keyspace = KeySpace::single(get_key(0)..get_key(10));
10498 4 : let results = tline
10499 4 : .get_vectored(keyspace, last_record_lsn, IoConcurrency::sequential(), &ctx)
10500 4 : .await
10501 4 : .expect("No vectored errors");
10502 44 : for (key, res) in results {
10503 40 : let value = res.expect("No key errors");
10504 40 : let expected_value = expected_key_values.remove(&key).expect("No unknown keys");
10505 40 : assert_eq!(value, Bytes::from(expected_value.clone()));
10506 4 :
10507 40 : tracing::info!("key={key} value={expected_value}");
10508 4 : }
10509 4 :
10510 4 : Ok(())
10511 4 : }
10512 :
10513 428 : fn sort_layer_key(k1: &PersistentLayerKey, k2: &PersistentLayerKey) -> std::cmp::Ordering {
10514 428 : (
10515 428 : k1.is_delta,
10516 428 : k1.key_range.start,
10517 428 : k1.key_range.end,
10518 428 : k1.lsn_range.start,
10519 428 : k1.lsn_range.end,
10520 428 : )
10521 428 : .cmp(&(
10522 428 : k2.is_delta,
10523 428 : k2.key_range.start,
10524 428 : k2.key_range.end,
10525 428 : k2.lsn_range.start,
10526 428 : k2.lsn_range.end,
10527 428 : ))
10528 428 : }
10529 :
10530 48 : async fn inspect_and_sort(
10531 48 : tline: &Arc<Timeline>,
10532 48 : filter: Option<std::ops::Range<Key>>,
10533 48 : ) -> Vec<PersistentLayerKey> {
10534 48 : let mut all_layers = tline.inspect_historic_layers().await.unwrap();
10535 48 : if let Some(filter) = filter {
10536 216 : all_layers.retain(|layer| overlaps_with(&layer.key_range, &filter));
10537 44 : }
10538 48 : all_layers.sort_by(sort_layer_key);
10539 48 : all_layers
10540 48 : }
10541 :
10542 : #[cfg(feature = "testing")]
10543 44 : fn check_layer_map_key_eq(
10544 44 : mut left: Vec<PersistentLayerKey>,
10545 44 : mut right: Vec<PersistentLayerKey>,
10546 44 : ) {
10547 44 : left.sort_by(sort_layer_key);
10548 44 : right.sort_by(sort_layer_key);
10549 44 : if left != right {
10550 0 : eprintln!("---LEFT---");
10551 0 : for left in left.iter() {
10552 0 : eprintln!("{}", left);
10553 0 : }
10554 0 : eprintln!("---RIGHT---");
10555 0 : for right in right.iter() {
10556 0 : eprintln!("{}", right);
10557 0 : }
10558 0 : assert_eq!(left, right);
10559 44 : }
10560 44 : }
10561 :
10562 : #[cfg(feature = "testing")]
10563 : #[tokio::test]
10564 4 : async fn test_simple_partial_bottom_most_compaction() -> anyhow::Result<()> {
10565 4 : let harness = TenantHarness::create("test_simple_partial_bottom_most_compaction").await?;
10566 4 : let (tenant, ctx) = harness.load().await;
10567 4 :
10568 364 : fn get_key(id: u32) -> Key {
10569 364 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
10570 364 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
10571 364 : key.field6 = id;
10572 364 : key
10573 364 : }
10574 4 :
10575 4 : // img layer at 0x10
10576 4 : let img_layer = (0..10)
10577 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10578 4 : .collect_vec();
10579 4 :
10580 4 : let delta1 = vec![
10581 4 : (
10582 4 : get_key(1),
10583 4 : Lsn(0x20),
10584 4 : Value::Image(Bytes::from("value 1@0x20")),
10585 4 : ),
10586 4 : (
10587 4 : get_key(2),
10588 4 : Lsn(0x30),
10589 4 : Value::Image(Bytes::from("value 2@0x30")),
10590 4 : ),
10591 4 : (
10592 4 : get_key(3),
10593 4 : Lsn(0x40),
10594 4 : Value::Image(Bytes::from("value 3@0x40")),
10595 4 : ),
10596 4 : ];
10597 4 : let delta2 = vec![
10598 4 : (
10599 4 : get_key(5),
10600 4 : Lsn(0x20),
10601 4 : Value::Image(Bytes::from("value 5@0x20")),
10602 4 : ),
10603 4 : (
10604 4 : get_key(6),
10605 4 : Lsn(0x20),
10606 4 : Value::Image(Bytes::from("value 6@0x20")),
10607 4 : ),
10608 4 : ];
10609 4 : let delta3 = vec![
10610 4 : (
10611 4 : get_key(8),
10612 4 : Lsn(0x48),
10613 4 : Value::Image(Bytes::from("value 8@0x48")),
10614 4 : ),
10615 4 : (
10616 4 : get_key(9),
10617 4 : Lsn(0x48),
10618 4 : Value::Image(Bytes::from("value 9@0x48")),
10619 4 : ),
10620 4 : ];
10621 4 :
10622 4 : let tline = tenant
10623 4 : .create_test_timeline_with_layers(
10624 4 : TIMELINE_ID,
10625 4 : Lsn(0x10),
10626 4 : DEFAULT_PG_VERSION,
10627 4 : &ctx,
10628 4 : vec![], // in-memory layers
10629 4 : vec![
10630 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta1),
10631 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x48), delta2),
10632 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x48)..Lsn(0x50), delta3),
10633 4 : ], // delta layers
10634 4 : vec![(Lsn(0x10), img_layer)], // image layers
10635 4 : Lsn(0x50),
10636 4 : )
10637 4 : .await?;
10638 4 :
10639 4 : {
10640 4 : tline
10641 4 : .applied_gc_cutoff_lsn
10642 4 : .lock_for_write()
10643 4 : .store_and_unlock(Lsn(0x30))
10644 4 : .wait()
10645 4 : .await;
10646 4 : // Update GC info
10647 4 : let mut guard = tline.gc_info.write().unwrap();
10648 4 : *guard = GcInfo {
10649 4 : retain_lsns: vec![(Lsn(0x20), tline.timeline_id, MaybeOffloaded::No)],
10650 4 : cutoffs: GcCutoffs {
10651 4 : time: Lsn(0x30),
10652 4 : space: Lsn(0x30),
10653 4 : },
10654 4 : leases: Default::default(),
10655 4 : within_ancestor_pitr: false,
10656 4 : };
10657 4 : }
10658 4 :
10659 4 : let cancel = CancellationToken::new();
10660 4 :
10661 4 : // Do a partial compaction on key range 0..2
10662 4 : tline
10663 4 : .compact_with_gc(
10664 4 : &cancel,
10665 4 : CompactOptions {
10666 4 : flags: EnumSet::new(),
10667 4 : compact_key_range: Some((get_key(0)..get_key(2)).into()),
10668 4 : ..Default::default()
10669 4 : },
10670 4 : &ctx,
10671 4 : )
10672 4 : .await
10673 4 : .unwrap();
10674 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10675 4 : check_layer_map_key_eq(
10676 4 : all_layers,
10677 4 : vec![
10678 4 : // newly-generated image layer for the partial compaction range 0-2
10679 4 : PersistentLayerKey {
10680 4 : key_range: get_key(0)..get_key(2),
10681 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10682 4 : is_delta: false,
10683 4 : },
10684 4 : PersistentLayerKey {
10685 4 : key_range: get_key(0)..get_key(10),
10686 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10687 4 : is_delta: false,
10688 4 : },
10689 4 : // delta1 is split and the second part is rewritten
10690 4 : PersistentLayerKey {
10691 4 : key_range: get_key(2)..get_key(4),
10692 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10693 4 : is_delta: true,
10694 4 : },
10695 4 : PersistentLayerKey {
10696 4 : key_range: get_key(5)..get_key(7),
10697 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10698 4 : is_delta: true,
10699 4 : },
10700 4 : PersistentLayerKey {
10701 4 : key_range: get_key(8)..get_key(10),
10702 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10703 4 : is_delta: true,
10704 4 : },
10705 4 : ],
10706 4 : );
10707 4 :
10708 4 : // Do a partial compaction on key range 2..4
10709 4 : tline
10710 4 : .compact_with_gc(
10711 4 : &cancel,
10712 4 : CompactOptions {
10713 4 : flags: EnumSet::new(),
10714 4 : compact_key_range: Some((get_key(2)..get_key(4)).into()),
10715 4 : ..Default::default()
10716 4 : },
10717 4 : &ctx,
10718 4 : )
10719 4 : .await
10720 4 : .unwrap();
10721 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10722 4 : check_layer_map_key_eq(
10723 4 : all_layers,
10724 4 : vec![
10725 4 : PersistentLayerKey {
10726 4 : key_range: get_key(0)..get_key(2),
10727 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10728 4 : is_delta: false,
10729 4 : },
10730 4 : PersistentLayerKey {
10731 4 : key_range: get_key(0)..get_key(10),
10732 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10733 4 : is_delta: false,
10734 4 : },
10735 4 : // image layer generated for the compaction range 2-4
10736 4 : PersistentLayerKey {
10737 4 : key_range: get_key(2)..get_key(4),
10738 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10739 4 : is_delta: false,
10740 4 : },
10741 4 : // we have key2/key3 above the retain_lsn, so we still need this delta layer
10742 4 : PersistentLayerKey {
10743 4 : key_range: get_key(2)..get_key(4),
10744 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10745 4 : is_delta: true,
10746 4 : },
10747 4 : PersistentLayerKey {
10748 4 : key_range: get_key(5)..get_key(7),
10749 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10750 4 : is_delta: true,
10751 4 : },
10752 4 : PersistentLayerKey {
10753 4 : key_range: get_key(8)..get_key(10),
10754 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10755 4 : is_delta: true,
10756 4 : },
10757 4 : ],
10758 4 : );
10759 4 :
10760 4 : // Do a partial compaction on key range 4..9
10761 4 : tline
10762 4 : .compact_with_gc(
10763 4 : &cancel,
10764 4 : CompactOptions {
10765 4 : flags: EnumSet::new(),
10766 4 : compact_key_range: Some((get_key(4)..get_key(9)).into()),
10767 4 : ..Default::default()
10768 4 : },
10769 4 : &ctx,
10770 4 : )
10771 4 : .await
10772 4 : .unwrap();
10773 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10774 4 : check_layer_map_key_eq(
10775 4 : all_layers,
10776 4 : vec![
10777 4 : PersistentLayerKey {
10778 4 : key_range: get_key(0)..get_key(2),
10779 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10780 4 : is_delta: false,
10781 4 : },
10782 4 : PersistentLayerKey {
10783 4 : key_range: get_key(0)..get_key(10),
10784 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10785 4 : is_delta: false,
10786 4 : },
10787 4 : PersistentLayerKey {
10788 4 : key_range: get_key(2)..get_key(4),
10789 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10790 4 : is_delta: false,
10791 4 : },
10792 4 : PersistentLayerKey {
10793 4 : key_range: get_key(2)..get_key(4),
10794 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10795 4 : is_delta: true,
10796 4 : },
10797 4 : // image layer generated for this compaction range
10798 4 : PersistentLayerKey {
10799 4 : key_range: get_key(4)..get_key(9),
10800 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10801 4 : is_delta: false,
10802 4 : },
10803 4 : PersistentLayerKey {
10804 4 : key_range: get_key(8)..get_key(10),
10805 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10806 4 : is_delta: true,
10807 4 : },
10808 4 : ],
10809 4 : );
10810 4 :
10811 4 : // Do a partial compaction on key range 9..10
10812 4 : tline
10813 4 : .compact_with_gc(
10814 4 : &cancel,
10815 4 : CompactOptions {
10816 4 : flags: EnumSet::new(),
10817 4 : compact_key_range: Some((get_key(9)..get_key(10)).into()),
10818 4 : ..Default::default()
10819 4 : },
10820 4 : &ctx,
10821 4 : )
10822 4 : .await
10823 4 : .unwrap();
10824 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10825 4 : check_layer_map_key_eq(
10826 4 : all_layers,
10827 4 : vec![
10828 4 : PersistentLayerKey {
10829 4 : key_range: get_key(0)..get_key(2),
10830 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10831 4 : is_delta: false,
10832 4 : },
10833 4 : PersistentLayerKey {
10834 4 : key_range: get_key(0)..get_key(10),
10835 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
10836 4 : is_delta: false,
10837 4 : },
10838 4 : PersistentLayerKey {
10839 4 : key_range: get_key(2)..get_key(4),
10840 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10841 4 : is_delta: false,
10842 4 : },
10843 4 : PersistentLayerKey {
10844 4 : key_range: get_key(2)..get_key(4),
10845 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10846 4 : is_delta: true,
10847 4 : },
10848 4 : PersistentLayerKey {
10849 4 : key_range: get_key(4)..get_key(9),
10850 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10851 4 : is_delta: false,
10852 4 : },
10853 4 : // image layer generated for the compaction range
10854 4 : PersistentLayerKey {
10855 4 : key_range: get_key(9)..get_key(10),
10856 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10857 4 : is_delta: false,
10858 4 : },
10859 4 : PersistentLayerKey {
10860 4 : key_range: get_key(8)..get_key(10),
10861 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10862 4 : is_delta: true,
10863 4 : },
10864 4 : ],
10865 4 : );
10866 4 :
10867 4 : // Do a partial compaction on key range 0..10, all image layers below LSN 20 can be replaced with new ones.
10868 4 : tline
10869 4 : .compact_with_gc(
10870 4 : &cancel,
10871 4 : CompactOptions {
10872 4 : flags: EnumSet::new(),
10873 4 : compact_key_range: Some((get_key(0)..get_key(10)).into()),
10874 4 : ..Default::default()
10875 4 : },
10876 4 : &ctx,
10877 4 : )
10878 4 : .await
10879 4 : .unwrap();
10880 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
10881 4 : check_layer_map_key_eq(
10882 4 : all_layers,
10883 4 : vec![
10884 4 : // aha, we removed all unnecessary image/delta layers and got a very clean layer map!
10885 4 : PersistentLayerKey {
10886 4 : key_range: get_key(0)..get_key(10),
10887 4 : lsn_range: Lsn(0x20)..Lsn(0x21),
10888 4 : is_delta: false,
10889 4 : },
10890 4 : PersistentLayerKey {
10891 4 : key_range: get_key(2)..get_key(4),
10892 4 : lsn_range: Lsn(0x20)..Lsn(0x48),
10893 4 : is_delta: true,
10894 4 : },
10895 4 : PersistentLayerKey {
10896 4 : key_range: get_key(8)..get_key(10),
10897 4 : lsn_range: Lsn(0x48)..Lsn(0x50),
10898 4 : is_delta: true,
10899 4 : },
10900 4 : ],
10901 4 : );
10902 4 : Ok(())
10903 4 : }
10904 :
10905 : #[cfg(feature = "testing")]
10906 : #[tokio::test]
10907 4 : async fn test_timeline_offload_retain_lsn() -> anyhow::Result<()> {
10908 4 : let harness = TenantHarness::create("test_timeline_offload_retain_lsn")
10909 4 : .await
10910 4 : .unwrap();
10911 4 : let (tenant, ctx) = harness.load().await;
10912 4 : let tline_parent = tenant
10913 4 : .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
10914 4 : .await
10915 4 : .unwrap();
10916 4 : let tline_child = tenant
10917 4 : .branch_timeline_test(&tline_parent, NEW_TIMELINE_ID, Some(Lsn(0x20)), &ctx)
10918 4 : .await
10919 4 : .unwrap();
10920 4 : {
10921 4 : let gc_info_parent = tline_parent.gc_info.read().unwrap();
10922 4 : assert_eq!(
10923 4 : gc_info_parent.retain_lsns,
10924 4 : vec![(Lsn(0x20), tline_child.timeline_id, MaybeOffloaded::No)]
10925 4 : );
10926 4 : }
10927 4 : // We have to directly call the remote_client instead of using the archive function to avoid constructing broker client...
10928 4 : tline_child
10929 4 : .remote_client
10930 4 : .schedule_index_upload_for_timeline_archival_state(TimelineArchivalState::Archived)
10931 4 : .unwrap();
10932 4 : tline_child.remote_client.wait_completion().await.unwrap();
10933 4 : offload_timeline(&tenant, &tline_child)
10934 4 : .instrument(tracing::info_span!(parent: None, "offload_test", tenant_id=%"test", shard_id=%"test", timeline_id=%"test"))
10935 4 : .await.unwrap();
10936 4 : let child_timeline_id = tline_child.timeline_id;
10937 4 : Arc::try_unwrap(tline_child).unwrap();
10938 4 :
10939 4 : {
10940 4 : let gc_info_parent = tline_parent.gc_info.read().unwrap();
10941 4 : assert_eq!(
10942 4 : gc_info_parent.retain_lsns,
10943 4 : vec![(Lsn(0x20), child_timeline_id, MaybeOffloaded::Yes)]
10944 4 : );
10945 4 : }
10946 4 :
10947 4 : tenant
10948 4 : .get_offloaded_timeline(child_timeline_id)
10949 4 : .unwrap()
10950 4 : .defuse_for_tenant_drop();
10951 4 :
10952 4 : Ok(())
10953 4 : }
10954 :
10955 : #[cfg(feature = "testing")]
10956 : #[tokio::test]
10957 4 : async fn test_simple_bottom_most_compaction_above_lsn() -> anyhow::Result<()> {
10958 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_above_lsn").await?;
10959 4 : let (tenant, ctx) = harness.load().await;
10960 4 :
10961 592 : fn get_key(id: u32) -> Key {
10962 592 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
10963 592 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
10964 592 : key.field6 = id;
10965 592 : key
10966 592 : }
10967 4 :
10968 4 : let img_layer = (0..10)
10969 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
10970 4 : .collect_vec();
10971 4 :
10972 4 : let delta1 = vec![(
10973 4 : get_key(1),
10974 4 : Lsn(0x20),
10975 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
10976 4 : )];
10977 4 : let delta4 = vec![(
10978 4 : get_key(1),
10979 4 : Lsn(0x28),
10980 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
10981 4 : )];
10982 4 : let delta2 = vec![
10983 4 : (
10984 4 : get_key(1),
10985 4 : Lsn(0x30),
10986 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
10987 4 : ),
10988 4 : (
10989 4 : get_key(1),
10990 4 : Lsn(0x38),
10991 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
10992 4 : ),
10993 4 : ];
10994 4 : let delta3 = vec![
10995 4 : (
10996 4 : get_key(8),
10997 4 : Lsn(0x48),
10998 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
10999 4 : ),
11000 4 : (
11001 4 : get_key(9),
11002 4 : Lsn(0x48),
11003 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
11004 4 : ),
11005 4 : ];
11006 4 :
11007 4 : let tline = tenant
11008 4 : .create_test_timeline_with_layers(
11009 4 : TIMELINE_ID,
11010 4 : Lsn(0x10),
11011 4 : DEFAULT_PG_VERSION,
11012 4 : &ctx,
11013 4 : vec![], // in-memory layers
11014 4 : vec![
11015 4 : // delta1/2/4 only contain a single key but multiple updates
11016 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
11017 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
11018 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
11019 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
11020 4 : ], // delta layers
11021 4 : vec![(Lsn(0x10), img_layer)], // image layers
11022 4 : Lsn(0x50),
11023 4 : )
11024 4 : .await?;
11025 4 : {
11026 4 : tline
11027 4 : .applied_gc_cutoff_lsn
11028 4 : .lock_for_write()
11029 4 : .store_and_unlock(Lsn(0x30))
11030 4 : .wait()
11031 4 : .await;
11032 4 : // Update GC info
11033 4 : let mut guard = tline.gc_info.write().unwrap();
11034 4 : *guard = GcInfo {
11035 4 : retain_lsns: vec![
11036 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
11037 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
11038 4 : ],
11039 4 : cutoffs: GcCutoffs {
11040 4 : time: Lsn(0x30),
11041 4 : space: Lsn(0x30),
11042 4 : },
11043 4 : leases: Default::default(),
11044 4 : within_ancestor_pitr: false,
11045 4 : };
11046 4 : }
11047 4 :
11048 4 : let expected_result = [
11049 4 : Bytes::from_static(b"value 0@0x10"),
11050 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
11051 4 : Bytes::from_static(b"value 2@0x10"),
11052 4 : Bytes::from_static(b"value 3@0x10"),
11053 4 : Bytes::from_static(b"value 4@0x10"),
11054 4 : Bytes::from_static(b"value 5@0x10"),
11055 4 : Bytes::from_static(b"value 6@0x10"),
11056 4 : Bytes::from_static(b"value 7@0x10"),
11057 4 : Bytes::from_static(b"value 8@0x10@0x48"),
11058 4 : Bytes::from_static(b"value 9@0x10@0x48"),
11059 4 : ];
11060 4 :
11061 4 : let expected_result_at_gc_horizon = [
11062 4 : Bytes::from_static(b"value 0@0x10"),
11063 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
11064 4 : Bytes::from_static(b"value 2@0x10"),
11065 4 : Bytes::from_static(b"value 3@0x10"),
11066 4 : Bytes::from_static(b"value 4@0x10"),
11067 4 : Bytes::from_static(b"value 5@0x10"),
11068 4 : Bytes::from_static(b"value 6@0x10"),
11069 4 : Bytes::from_static(b"value 7@0x10"),
11070 4 : Bytes::from_static(b"value 8@0x10"),
11071 4 : Bytes::from_static(b"value 9@0x10"),
11072 4 : ];
11073 4 :
11074 4 : let expected_result_at_lsn_20 = [
11075 4 : Bytes::from_static(b"value 0@0x10"),
11076 4 : Bytes::from_static(b"value 1@0x10@0x20"),
11077 4 : Bytes::from_static(b"value 2@0x10"),
11078 4 : Bytes::from_static(b"value 3@0x10"),
11079 4 : Bytes::from_static(b"value 4@0x10"),
11080 4 : Bytes::from_static(b"value 5@0x10"),
11081 4 : Bytes::from_static(b"value 6@0x10"),
11082 4 : Bytes::from_static(b"value 7@0x10"),
11083 4 : Bytes::from_static(b"value 8@0x10"),
11084 4 : Bytes::from_static(b"value 9@0x10"),
11085 4 : ];
11086 4 :
11087 4 : let expected_result_at_lsn_10 = [
11088 4 : Bytes::from_static(b"value 0@0x10"),
11089 4 : Bytes::from_static(b"value 1@0x10"),
11090 4 : Bytes::from_static(b"value 2@0x10"),
11091 4 : Bytes::from_static(b"value 3@0x10"),
11092 4 : Bytes::from_static(b"value 4@0x10"),
11093 4 : Bytes::from_static(b"value 5@0x10"),
11094 4 : Bytes::from_static(b"value 6@0x10"),
11095 4 : Bytes::from_static(b"value 7@0x10"),
11096 4 : Bytes::from_static(b"value 8@0x10"),
11097 4 : Bytes::from_static(b"value 9@0x10"),
11098 4 : ];
11099 4 :
11100 12 : let verify_result = || async {
11101 12 : let gc_horizon = {
11102 12 : let gc_info = tline.gc_info.read().unwrap();
11103 12 : gc_info.cutoffs.time
11104 4 : };
11105 132 : for idx in 0..10 {
11106 120 : assert_eq!(
11107 120 : tline
11108 120 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
11109 120 : .await
11110 120 : .unwrap(),
11111 120 : &expected_result[idx]
11112 4 : );
11113 120 : assert_eq!(
11114 120 : tline
11115 120 : .get(get_key(idx as u32), gc_horizon, &ctx)
11116 120 : .await
11117 120 : .unwrap(),
11118 120 : &expected_result_at_gc_horizon[idx]
11119 4 : );
11120 120 : assert_eq!(
11121 120 : tline
11122 120 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
11123 120 : .await
11124 120 : .unwrap(),
11125 120 : &expected_result_at_lsn_20[idx]
11126 4 : );
11127 120 : assert_eq!(
11128 120 : tline
11129 120 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
11130 120 : .await
11131 120 : .unwrap(),
11132 120 : &expected_result_at_lsn_10[idx]
11133 4 : );
11134 4 : }
11135 24 : };
11136 4 :
11137 4 : verify_result().await;
11138 4 :
11139 4 : let cancel = CancellationToken::new();
11140 4 : tline
11141 4 : .compact_with_gc(
11142 4 : &cancel,
11143 4 : CompactOptions {
11144 4 : compact_lsn_range: Some(CompactLsnRange::above(Lsn(0x28))),
11145 4 : ..Default::default()
11146 4 : },
11147 4 : &ctx,
11148 4 : )
11149 4 : .await
11150 4 : .unwrap();
11151 4 : verify_result().await;
11152 4 :
11153 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11154 4 : check_layer_map_key_eq(
11155 4 : all_layers,
11156 4 : vec![
11157 4 : // The original image layer, not compacted
11158 4 : PersistentLayerKey {
11159 4 : key_range: get_key(0)..get_key(10),
11160 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11161 4 : is_delta: false,
11162 4 : },
11163 4 : // Delta layer below the specified above_lsn not compacted
11164 4 : PersistentLayerKey {
11165 4 : key_range: get_key(1)..get_key(2),
11166 4 : lsn_range: Lsn(0x20)..Lsn(0x28),
11167 4 : is_delta: true,
11168 4 : },
11169 4 : // Delta layer compacted above the LSN
11170 4 : PersistentLayerKey {
11171 4 : key_range: get_key(1)..get_key(10),
11172 4 : lsn_range: Lsn(0x28)..Lsn(0x50),
11173 4 : is_delta: true,
11174 4 : },
11175 4 : ],
11176 4 : );
11177 4 :
11178 4 : // compact again
11179 4 : tline
11180 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
11181 4 : .await
11182 4 : .unwrap();
11183 4 : verify_result().await;
11184 4 :
11185 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11186 4 : check_layer_map_key_eq(
11187 4 : all_layers,
11188 4 : vec![
11189 4 : // The compacted image layer (full key range)
11190 4 : PersistentLayerKey {
11191 4 : key_range: Key::MIN..Key::MAX,
11192 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11193 4 : is_delta: false,
11194 4 : },
11195 4 : // All other data in the delta layer
11196 4 : PersistentLayerKey {
11197 4 : key_range: get_key(1)..get_key(10),
11198 4 : lsn_range: Lsn(0x10)..Lsn(0x50),
11199 4 : is_delta: true,
11200 4 : },
11201 4 : ],
11202 4 : );
11203 4 :
11204 4 : Ok(())
11205 4 : }
11206 :
11207 : #[cfg(feature = "testing")]
11208 : #[tokio::test]
11209 4 : async fn test_simple_bottom_most_compaction_rectangle() -> anyhow::Result<()> {
11210 4 : let harness = TenantHarness::create("test_simple_bottom_most_compaction_rectangle").await?;
11211 4 : let (tenant, ctx) = harness.load().await;
11212 4 :
11213 1016 : fn get_key(id: u32) -> Key {
11214 1016 : // using aux key here b/c they are guaranteed to be inside `collect_keyspace`.
11215 1016 : let mut key = Key::from_hex("620000000033333333444444445500000000").unwrap();
11216 1016 : key.field6 = id;
11217 1016 : key
11218 1016 : }
11219 4 :
11220 4 : let img_layer = (0..10)
11221 40 : .map(|id| (get_key(id), Bytes::from(format!("value {id}@0x10"))))
11222 4 : .collect_vec();
11223 4 :
11224 4 : let delta1 = vec![(
11225 4 : get_key(1),
11226 4 : Lsn(0x20),
11227 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x20")),
11228 4 : )];
11229 4 : let delta4 = vec![(
11230 4 : get_key(1),
11231 4 : Lsn(0x28),
11232 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x28")),
11233 4 : )];
11234 4 : let delta2 = vec![
11235 4 : (
11236 4 : get_key(1),
11237 4 : Lsn(0x30),
11238 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x30")),
11239 4 : ),
11240 4 : (
11241 4 : get_key(1),
11242 4 : Lsn(0x38),
11243 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x38")),
11244 4 : ),
11245 4 : ];
11246 4 : let delta3 = vec![
11247 4 : (
11248 4 : get_key(8),
11249 4 : Lsn(0x48),
11250 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
11251 4 : ),
11252 4 : (
11253 4 : get_key(9),
11254 4 : Lsn(0x48),
11255 4 : Value::WalRecord(NeonWalRecord::wal_append("@0x48")),
11256 4 : ),
11257 4 : ];
11258 4 :
11259 4 : let tline = tenant
11260 4 : .create_test_timeline_with_layers(
11261 4 : TIMELINE_ID,
11262 4 : Lsn(0x10),
11263 4 : DEFAULT_PG_VERSION,
11264 4 : &ctx,
11265 4 : vec![], // in-memory layers
11266 4 : vec![
11267 4 : // delta1/2/4 only contain a single key but multiple updates
11268 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x20)..Lsn(0x28), delta1),
11269 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta2),
11270 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x28)..Lsn(0x30), delta4),
11271 4 : DeltaLayerTestDesc::new_with_inferred_key_range(Lsn(0x30)..Lsn(0x50), delta3),
11272 4 : ], // delta layers
11273 4 : vec![(Lsn(0x10), img_layer)], // image layers
11274 4 : Lsn(0x50),
11275 4 : )
11276 4 : .await?;
11277 4 : {
11278 4 : tline
11279 4 : .applied_gc_cutoff_lsn
11280 4 : .lock_for_write()
11281 4 : .store_and_unlock(Lsn(0x30))
11282 4 : .wait()
11283 4 : .await;
11284 4 : // Update GC info
11285 4 : let mut guard = tline.gc_info.write().unwrap();
11286 4 : *guard = GcInfo {
11287 4 : retain_lsns: vec![
11288 4 : (Lsn(0x10), tline.timeline_id, MaybeOffloaded::No),
11289 4 : (Lsn(0x20), tline.timeline_id, MaybeOffloaded::No),
11290 4 : ],
11291 4 : cutoffs: GcCutoffs {
11292 4 : time: Lsn(0x30),
11293 4 : space: Lsn(0x30),
11294 4 : },
11295 4 : leases: Default::default(),
11296 4 : within_ancestor_pitr: false,
11297 4 : };
11298 4 : }
11299 4 :
11300 4 : let expected_result = [
11301 4 : Bytes::from_static(b"value 0@0x10"),
11302 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30@0x38"),
11303 4 : Bytes::from_static(b"value 2@0x10"),
11304 4 : Bytes::from_static(b"value 3@0x10"),
11305 4 : Bytes::from_static(b"value 4@0x10"),
11306 4 : Bytes::from_static(b"value 5@0x10"),
11307 4 : Bytes::from_static(b"value 6@0x10"),
11308 4 : Bytes::from_static(b"value 7@0x10"),
11309 4 : Bytes::from_static(b"value 8@0x10@0x48"),
11310 4 : Bytes::from_static(b"value 9@0x10@0x48"),
11311 4 : ];
11312 4 :
11313 4 : let expected_result_at_gc_horizon = [
11314 4 : Bytes::from_static(b"value 0@0x10"),
11315 4 : Bytes::from_static(b"value 1@0x10@0x20@0x28@0x30"),
11316 4 : Bytes::from_static(b"value 2@0x10"),
11317 4 : Bytes::from_static(b"value 3@0x10"),
11318 4 : Bytes::from_static(b"value 4@0x10"),
11319 4 : Bytes::from_static(b"value 5@0x10"),
11320 4 : Bytes::from_static(b"value 6@0x10"),
11321 4 : Bytes::from_static(b"value 7@0x10"),
11322 4 : Bytes::from_static(b"value 8@0x10"),
11323 4 : Bytes::from_static(b"value 9@0x10"),
11324 4 : ];
11325 4 :
11326 4 : let expected_result_at_lsn_20 = [
11327 4 : Bytes::from_static(b"value 0@0x10"),
11328 4 : Bytes::from_static(b"value 1@0x10@0x20"),
11329 4 : Bytes::from_static(b"value 2@0x10"),
11330 4 : Bytes::from_static(b"value 3@0x10"),
11331 4 : Bytes::from_static(b"value 4@0x10"),
11332 4 : Bytes::from_static(b"value 5@0x10"),
11333 4 : Bytes::from_static(b"value 6@0x10"),
11334 4 : Bytes::from_static(b"value 7@0x10"),
11335 4 : Bytes::from_static(b"value 8@0x10"),
11336 4 : Bytes::from_static(b"value 9@0x10"),
11337 4 : ];
11338 4 :
11339 4 : let expected_result_at_lsn_10 = [
11340 4 : Bytes::from_static(b"value 0@0x10"),
11341 4 : Bytes::from_static(b"value 1@0x10"),
11342 4 : Bytes::from_static(b"value 2@0x10"),
11343 4 : Bytes::from_static(b"value 3@0x10"),
11344 4 : Bytes::from_static(b"value 4@0x10"),
11345 4 : Bytes::from_static(b"value 5@0x10"),
11346 4 : Bytes::from_static(b"value 6@0x10"),
11347 4 : Bytes::from_static(b"value 7@0x10"),
11348 4 : Bytes::from_static(b"value 8@0x10"),
11349 4 : Bytes::from_static(b"value 9@0x10"),
11350 4 : ];
11351 4 :
11352 20 : let verify_result = || async {
11353 20 : let gc_horizon = {
11354 20 : let gc_info = tline.gc_info.read().unwrap();
11355 20 : gc_info.cutoffs.time
11356 4 : };
11357 220 : for idx in 0..10 {
11358 200 : assert_eq!(
11359 200 : tline
11360 200 : .get(get_key(idx as u32), Lsn(0x50), &ctx)
11361 200 : .await
11362 200 : .unwrap(),
11363 200 : &expected_result[idx]
11364 4 : );
11365 200 : assert_eq!(
11366 200 : tline
11367 200 : .get(get_key(idx as u32), gc_horizon, &ctx)
11368 200 : .await
11369 200 : .unwrap(),
11370 200 : &expected_result_at_gc_horizon[idx]
11371 4 : );
11372 200 : assert_eq!(
11373 200 : tline
11374 200 : .get(get_key(idx as u32), Lsn(0x20), &ctx)
11375 200 : .await
11376 200 : .unwrap(),
11377 200 : &expected_result_at_lsn_20[idx]
11378 4 : );
11379 200 : assert_eq!(
11380 200 : tline
11381 200 : .get(get_key(idx as u32), Lsn(0x10), &ctx)
11382 200 : .await
11383 200 : .unwrap(),
11384 200 : &expected_result_at_lsn_10[idx]
11385 4 : );
11386 4 : }
11387 40 : };
11388 4 :
11389 4 : verify_result().await;
11390 4 :
11391 4 : let cancel = CancellationToken::new();
11392 4 :
11393 4 : tline
11394 4 : .compact_with_gc(
11395 4 : &cancel,
11396 4 : CompactOptions {
11397 4 : compact_key_range: Some((get_key(0)..get_key(2)).into()),
11398 4 : compact_lsn_range: Some((Lsn(0x20)..Lsn(0x28)).into()),
11399 4 : ..Default::default()
11400 4 : },
11401 4 : &ctx,
11402 4 : )
11403 4 : .await
11404 4 : .unwrap();
11405 4 : verify_result().await;
11406 4 :
11407 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11408 4 : check_layer_map_key_eq(
11409 4 : all_layers,
11410 4 : vec![
11411 4 : // The original image layer, not compacted
11412 4 : PersistentLayerKey {
11413 4 : key_range: get_key(0)..get_key(10),
11414 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11415 4 : is_delta: false,
11416 4 : },
11417 4 : // According the selection logic, we select all layers with start key <= 0x28, so we would merge the layer 0x20-0x28 and
11418 4 : // the layer 0x28-0x30 into one.
11419 4 : PersistentLayerKey {
11420 4 : key_range: get_key(1)..get_key(2),
11421 4 : lsn_range: Lsn(0x20)..Lsn(0x30),
11422 4 : is_delta: true,
11423 4 : },
11424 4 : // Above the upper bound and untouched
11425 4 : PersistentLayerKey {
11426 4 : key_range: get_key(1)..get_key(2),
11427 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11428 4 : is_delta: true,
11429 4 : },
11430 4 : // This layer is untouched
11431 4 : PersistentLayerKey {
11432 4 : key_range: get_key(8)..get_key(10),
11433 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11434 4 : is_delta: true,
11435 4 : },
11436 4 : ],
11437 4 : );
11438 4 :
11439 4 : tline
11440 4 : .compact_with_gc(
11441 4 : &cancel,
11442 4 : CompactOptions {
11443 4 : compact_key_range: Some((get_key(3)..get_key(8)).into()),
11444 4 : compact_lsn_range: Some((Lsn(0x28)..Lsn(0x40)).into()),
11445 4 : ..Default::default()
11446 4 : },
11447 4 : &ctx,
11448 4 : )
11449 4 : .await
11450 4 : .unwrap();
11451 4 : verify_result().await;
11452 4 :
11453 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11454 4 : check_layer_map_key_eq(
11455 4 : all_layers,
11456 4 : vec![
11457 4 : // The original image layer, not compacted
11458 4 : PersistentLayerKey {
11459 4 : key_range: get_key(0)..get_key(10),
11460 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11461 4 : is_delta: false,
11462 4 : },
11463 4 : // Not in the compaction key range, uncompacted
11464 4 : PersistentLayerKey {
11465 4 : key_range: get_key(1)..get_key(2),
11466 4 : lsn_range: Lsn(0x20)..Lsn(0x30),
11467 4 : is_delta: true,
11468 4 : },
11469 4 : // Not in the compaction key range, uncompacted but need rewrite because the delta layer overlaps with the range
11470 4 : PersistentLayerKey {
11471 4 : key_range: get_key(1)..get_key(2),
11472 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11473 4 : is_delta: true,
11474 4 : },
11475 4 : // Note that when we specify the LSN upper bound to be 0x40, the compaction algorithm will not try to cut the layer
11476 4 : // horizontally in half. Instead, it will include all LSNs that overlap with 0x40. So the real max_lsn of the compaction
11477 4 : // becomes 0x50.
11478 4 : PersistentLayerKey {
11479 4 : key_range: get_key(8)..get_key(10),
11480 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11481 4 : is_delta: true,
11482 4 : },
11483 4 : ],
11484 4 : );
11485 4 :
11486 4 : // compact again
11487 4 : tline
11488 4 : .compact_with_gc(
11489 4 : &cancel,
11490 4 : CompactOptions {
11491 4 : compact_key_range: Some((get_key(0)..get_key(5)).into()),
11492 4 : compact_lsn_range: Some((Lsn(0x20)..Lsn(0x50)).into()),
11493 4 : ..Default::default()
11494 4 : },
11495 4 : &ctx,
11496 4 : )
11497 4 : .await
11498 4 : .unwrap();
11499 4 : verify_result().await;
11500 4 :
11501 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11502 4 : check_layer_map_key_eq(
11503 4 : all_layers,
11504 4 : vec![
11505 4 : // The original image layer, not compacted
11506 4 : PersistentLayerKey {
11507 4 : key_range: get_key(0)..get_key(10),
11508 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11509 4 : is_delta: false,
11510 4 : },
11511 4 : // The range gets compacted
11512 4 : PersistentLayerKey {
11513 4 : key_range: get_key(1)..get_key(2),
11514 4 : lsn_range: Lsn(0x20)..Lsn(0x50),
11515 4 : is_delta: true,
11516 4 : },
11517 4 : // Not touched during this iteration of compaction
11518 4 : PersistentLayerKey {
11519 4 : key_range: get_key(8)..get_key(10),
11520 4 : lsn_range: Lsn(0x30)..Lsn(0x50),
11521 4 : is_delta: true,
11522 4 : },
11523 4 : ],
11524 4 : );
11525 4 :
11526 4 : // final full compaction
11527 4 : tline
11528 4 : .compact_with_gc(&cancel, CompactOptions::default(), &ctx)
11529 4 : .await
11530 4 : .unwrap();
11531 4 : verify_result().await;
11532 4 :
11533 4 : let all_layers = inspect_and_sort(&tline, Some(get_key(0)..get_key(10))).await;
11534 4 : check_layer_map_key_eq(
11535 4 : all_layers,
11536 4 : vec![
11537 4 : // The compacted image layer (full key range)
11538 4 : PersistentLayerKey {
11539 4 : key_range: Key::MIN..Key::MAX,
11540 4 : lsn_range: Lsn(0x10)..Lsn(0x11),
11541 4 : is_delta: false,
11542 4 : },
11543 4 : // All other data in the delta layer
11544 4 : PersistentLayerKey {
11545 4 : key_range: get_key(1)..get_key(10),
11546 4 : lsn_range: Lsn(0x10)..Lsn(0x50),
11547 4 : is_delta: true,
11548 4 : },
11549 4 : ],
11550 4 : );
11551 4 :
11552 4 : Ok(())
11553 4 : }
11554 : }
|