LCOV - code coverage report
Current view: top level - pageserver/src/tenant/timeline - detach_ancestor.rs (source / functions) Coverage Total Hit
Test: aca806cab4756d7eb6a304846130f4a73a5d5393.info Lines: 0.0 % 875 0
Test Date: 2025-04-24 20:31:15 Functions: 0.0 % 80 0

            Line data    Source code
       1              : use std::collections::HashSet;
       2              : use std::sync::Arc;
       3              : 
       4              : use anyhow::Context;
       5              : use bytes::Bytes;
       6              : use http_utils::error::ApiError;
       7              : use pageserver_api::key::Key;
       8              : use pageserver_api::keyspace::KeySpace;
       9              : use pageserver_api::models::DetachBehavior;
      10              : use pageserver_api::models::detach_ancestor::AncestorDetached;
      11              : use pageserver_api::shard::ShardIdentity;
      12              : use pageserver_compaction::helpers::overlaps_with;
      13              : use tokio::sync::Semaphore;
      14              : use tokio_util::sync::CancellationToken;
      15              : use tracing::Instrument;
      16              : use utils::completion;
      17              : use utils::generation::Generation;
      18              : use utils::id::TimelineId;
      19              : use utils::lsn::Lsn;
      20              : use utils::sync::gate::GateError;
      21              : 
      22              : use super::layer_manager::LayerManager;
      23              : use super::{FlushLayerError, Timeline};
      24              : use crate::context::{DownloadBehavior, RequestContext};
      25              : use crate::task_mgr::TaskKind;
      26              : use crate::tenant::TenantShard;
      27              : use crate::tenant::remote_timeline_client::index::GcBlockingReason::DetachAncestor;
      28              : use crate::tenant::storage_layer::layer::local_layer_path;
      29              : use crate::tenant::storage_layer::{
      30              :     AsLayerDesc as _, DeltaLayerWriter, ImageLayerWriter, IoConcurrency, Layer, ResidentLayer,
      31              :     ValuesReconstructState,
      32              : };
      33              : use crate::tenant::timeline::VersionedKeySpaceQuery;
      34              : use crate::virtual_file::{MaybeFatalIo, VirtualFile};
      35              : 
      36              : #[derive(Debug, thiserror::Error)]
      37              : pub(crate) enum Error {
      38              :     #[error("no ancestors")]
      39              :     NoAncestor,
      40              : 
      41              :     #[error("too many ancestors")]
      42              :     TooManyAncestors,
      43              : 
      44              :     #[error("ancestor is not empty")]
      45              :     AncestorNotEmpty,
      46              : 
      47              :     #[error("shutting down, please retry later")]
      48              :     ShuttingDown,
      49              : 
      50              :     #[error("archived: {}", .0)]
      51              :     Archived(TimelineId),
      52              : 
      53              :     #[error(transparent)]
      54              :     NotFound(crate::tenant::GetTimelineError),
      55              : 
      56              :     #[error("failed to reparent all candidate timelines, please retry")]
      57              :     FailedToReparentAll,
      58              : 
      59              :     #[error("ancestor is already being detached by: {}", .0)]
      60              :     OtherTimelineDetachOngoing(TimelineId),
      61              : 
      62              :     #[error("preparing to timeline ancestor detach failed")]
      63              :     Prepare(#[source] anyhow::Error),
      64              : 
      65              :     #[error("detaching and reparenting failed")]
      66              :     DetachReparent(#[source] anyhow::Error),
      67              : 
      68              :     #[error("completing ancestor detach failed")]
      69              :     Complete(#[source] anyhow::Error),
      70              : 
      71              :     #[error("failpoint: {}", .0)]
      72              :     Failpoint(&'static str),
      73              : }
      74              : 
      75              : impl Error {
      76              :     /// Try to catch cancellation from within the `anyhow::Error`, or wrap the anyhow as the given
      77              :     /// variant or fancier `or_else`.
      78            0 :     fn launder<F>(e: anyhow::Error, or_else: F) -> Error
      79            0 :     where
      80            0 :         F: Fn(anyhow::Error) -> Error,
      81            0 :     {
      82              :         use remote_storage::TimeoutOrCancel;
      83              : 
      84              :         use crate::tenant::remote_timeline_client::WaitCompletionError;
      85              :         use crate::tenant::upload_queue::NotInitialized;
      86              : 
      87            0 :         if e.is::<NotInitialized>()
      88            0 :             || TimeoutOrCancel::caused_by_cancel(&e)
      89            0 :             || e.downcast_ref::<remote_storage::DownloadError>()
      90            0 :                 .is_some_and(|e| e.is_cancelled())
      91            0 :             || e.is::<WaitCompletionError>()
      92              :         {
      93            0 :             Error::ShuttingDown
      94              :         } else {
      95            0 :             or_else(e)
      96              :         }
      97            0 :     }
      98              : }
      99              : 
     100              : impl From<Error> for ApiError {
     101            0 :     fn from(value: Error) -> Self {
     102            0 :         match value {
     103            0 :             Error::NoAncestor => ApiError::Conflict(value.to_string()),
     104              :             Error::TooManyAncestors | Error::AncestorNotEmpty => {
     105            0 :                 ApiError::BadRequest(anyhow::anyhow!("{value}"))
     106              :             }
     107            0 :             Error::ShuttingDown => ApiError::ShuttingDown,
     108            0 :             Error::Archived(_) => ApiError::BadRequest(anyhow::anyhow!("{value}")),
     109              :             Error::OtherTimelineDetachOngoing(_) | Error::FailedToReparentAll => {
     110            0 :                 ApiError::ResourceUnavailable(value.to_string().into())
     111              :             }
     112            0 :             Error::NotFound(e) => ApiError::from(e),
     113              :             // these variants should have no cancellation errors because of Error::launder
     114              :             Error::Prepare(_)
     115              :             | Error::DetachReparent(_)
     116              :             | Error::Complete(_)
     117            0 :             | Error::Failpoint(_) => ApiError::InternalServerError(value.into()),
     118              :         }
     119            0 :     }
     120              : }
     121              : 
     122              : impl From<crate::tenant::upload_queue::NotInitialized> for Error {
     123            0 :     fn from(_: crate::tenant::upload_queue::NotInitialized) -> Self {
     124            0 :         // treat all as shutting down signals, even though that is not entirely correct
     125            0 :         // (uninitialized state)
     126            0 :         Error::ShuttingDown
     127            0 :     }
     128              : }
     129              : impl From<super::layer_manager::Shutdown> for Error {
     130            0 :     fn from(_: super::layer_manager::Shutdown) -> Self {
     131            0 :         Error::ShuttingDown
     132            0 :     }
     133              : }
     134              : 
     135              : pub(crate) enum Progress {
     136              :     Prepared(Attempt, PreparedTimelineDetach),
     137              :     Done(AncestorDetached),
     138              : }
     139              : 
     140              : pub(crate) struct PreparedTimelineDetach {
     141              :     layers: Vec<Layer>,
     142              : }
     143              : 
     144              : // TODO: this should be part of PageserverConf because we cannot easily modify cplane arguments.
     145              : #[derive(Debug)]
     146              : pub(crate) struct Options {
     147              :     pub(crate) rewrite_concurrency: std::num::NonZeroUsize,
     148              :     pub(crate) copy_concurrency: std::num::NonZeroUsize,
     149              : }
     150              : 
     151              : impl Default for Options {
     152            0 :     fn default() -> Self {
     153            0 :         Self {
     154            0 :             rewrite_concurrency: std::num::NonZeroUsize::new(2).unwrap(),
     155            0 :             copy_concurrency: std::num::NonZeroUsize::new(100).unwrap(),
     156            0 :         }
     157            0 :     }
     158              : }
     159              : 
     160              : /// Represents an across tenant reset exclusive single attempt to detach ancestor.
     161              : #[derive(Debug)]
     162              : pub(crate) struct Attempt {
     163              :     pub(crate) timeline_id: TimelineId,
     164              :     pub(crate) ancestor_timeline_id: TimelineId,
     165              :     pub(crate) ancestor_lsn: Lsn,
     166              :     _guard: completion::Completion,
     167              :     gate_entered: Option<utils::sync::gate::GateGuard>,
     168              : }
     169              : 
     170              : impl Attempt {
     171            0 :     pub(crate) fn before_reset_tenant(&mut self) {
     172            0 :         let taken = self.gate_entered.take();
     173            0 :         assert!(taken.is_some());
     174            0 :     }
     175              : 
     176            0 :     pub(crate) fn new_barrier(&self) -> completion::Barrier {
     177            0 :         self._guard.barrier()
     178            0 :     }
     179              : }
     180              : 
     181            0 : async fn generate_tombstone_image_layer(
     182            0 :     detached: &Arc<Timeline>,
     183            0 :     ancestor: &Arc<Timeline>,
     184            0 :     ancestor_lsn: Lsn,
     185            0 :     ctx: &RequestContext,
     186            0 : ) -> Result<Option<ResidentLayer>, Error> {
     187            0 :     tracing::info!(
     188            0 :         "removing non-inherited keys by writing an image layer with tombstones at the detach LSN"
     189              :     );
     190            0 :     let io_concurrency = IoConcurrency::spawn_from_conf(
     191            0 :         detached.conf,
     192            0 :         detached.gate.enter().map_err(|_| Error::ShuttingDown)?,
     193              :     );
     194            0 :     let mut reconstruct_state = ValuesReconstructState::new(io_concurrency);
     195            0 :     // Directly use `get_vectored_impl` to skip the max_vectored_read_key limit check. Note that the keyspace should
     196            0 :     // not contain too many keys, otherwise this takes a lot of memory. Currently we limit it to 10k keys in the compute.
     197            0 :     let key_range = Key::sparse_non_inherited_keyspace();
     198            0 :     // avoid generating a "future layer" which will then be removed
     199            0 :     let image_lsn = ancestor_lsn;
     200              : 
     201              :     {
     202            0 :         let layers = detached.layers.read().await;
     203            0 :         for layer in layers.all_persistent_layers() {
     204            0 :             if !layer.is_delta
     205            0 :                 && layer.lsn_range.start == image_lsn
     206            0 :                 && overlaps_with(&key_range, &layer.key_range)
     207              :             {
     208            0 :                 tracing::warn!(
     209            0 :                     layer=%layer, "image layer at the detach LSN already exists, skipping removing aux files"
     210              :                 );
     211            0 :                 return Ok(None);
     212            0 :             }
     213              :         }
     214              :     }
     215              : 
     216            0 :     let query = VersionedKeySpaceQuery::uniform(KeySpace::single(key_range.clone()), image_lsn);
     217            0 :     let data = ancestor
     218            0 :         .get_vectored_impl(query, &mut reconstruct_state, ctx)
     219            0 :         .await
     220            0 :         .context("failed to retrieve aux keys")
     221            0 :         .map_err(|e| Error::launder(e, Error::Prepare))?;
     222            0 :     if !data.is_empty() {
     223              :         // TODO: is it possible that we can have an image at `image_lsn`? Unlikely because image layers are only generated
     224              :         // upon compaction but theoretically possible.
     225            0 :         let mut image_layer_writer = ImageLayerWriter::new(
     226            0 :             detached.conf,
     227            0 :             detached.timeline_id,
     228            0 :             detached.tenant_shard_id,
     229            0 :             &key_range,
     230            0 :             image_lsn,
     231            0 :             &detached.gate,
     232            0 :             detached.cancel.clone(),
     233            0 :             ctx,
     234            0 :         )
     235            0 :         .await
     236            0 :         .context("failed to create image layer writer")
     237            0 :         .map_err(Error::Prepare)?;
     238            0 :         for key in data.keys() {
     239            0 :             image_layer_writer
     240            0 :                 .put_image(*key, Bytes::new(), ctx)
     241            0 :                 .await
     242            0 :                 .context("failed to write key")
     243            0 :                 .map_err(|e| Error::launder(e, Error::Prepare))?;
     244              :         }
     245            0 :         let (desc, path) = image_layer_writer
     246            0 :             .finish(ctx)
     247            0 :             .await
     248            0 :             .context("failed to finish image layer writer for removing the metadata keys")
     249            0 :             .map_err(|e| Error::launder(e, Error::Prepare))?;
     250            0 :         let generated = Layer::finish_creating(detached.conf, detached, desc, &path)
     251            0 :             .map_err(|e| Error::launder(e, Error::Prepare))?;
     252            0 :         detached
     253            0 :             .remote_client
     254            0 :             .upload_layer_file(&generated, &detached.cancel)
     255            0 :             .await
     256            0 :             .map_err(|e| Error::launder(e, Error::Prepare))?;
     257            0 :         tracing::info!(layer=%generated, "wrote image layer");
     258            0 :         Ok(Some(generated))
     259              :     } else {
     260            0 :         tracing::info!("no aux keys found in ancestor");
     261            0 :         Ok(None)
     262              :     }
     263            0 : }
     264              : 
     265              : /// See [`Timeline::prepare_to_detach_from_ancestor`]
     266            0 : pub(super) async fn prepare(
     267            0 :     detached: &Arc<Timeline>,
     268            0 :     tenant: &TenantShard,
     269            0 :     behavior: DetachBehavior,
     270            0 :     options: Options,
     271            0 :     ctx: &RequestContext,
     272            0 : ) -> Result<Progress, Error> {
     273              :     use Error::*;
     274              : 
     275            0 :     let Some((mut ancestor, mut ancestor_lsn)) = detached
     276            0 :         .ancestor_timeline
     277            0 :         .as_ref()
     278            0 :         .map(|tl| (tl.clone(), detached.ancestor_lsn))
     279              :     else {
     280              :         let ancestor_id;
     281              :         let ancestor_lsn;
     282            0 :         let still_in_progress = {
     283            0 :             let accessor = detached.remote_client.initialized_upload_queue()?;
     284              : 
     285              :             // we are safe to inspect the latest uploaded, because we can only witness this after
     286              :             // restart is complete and ancestor is no more.
     287            0 :             let latest = accessor.latest_uploaded_index_part();
     288            0 :             let Some((id, lsn)) = latest.lineage.detached_previous_ancestor() else {
     289            0 :                 return Err(NoAncestor);
     290              :             };
     291            0 :             ancestor_id = id;
     292            0 :             ancestor_lsn = lsn;
     293            0 : 
     294            0 :             latest
     295            0 :                 .gc_blocking
     296            0 :                 .as_ref()
     297            0 :                 .is_some_and(|b| b.blocked_by(DetachAncestor))
     298            0 :         };
     299            0 : 
     300            0 :         if still_in_progress {
     301              :             // gc is still blocked, we can still reparent and complete.
     302              :             // we are safe to reparent remaining, because they were locked in in the beginning.
     303            0 :             let attempt =
     304            0 :                 continue_with_blocked_gc(detached, tenant, ancestor_id, ancestor_lsn).await?;
     305              : 
     306              :             // because the ancestor of detached is already set to none, we have published all
     307              :             // of the layers, so we are still "prepared."
     308            0 :             return Ok(Progress::Prepared(
     309            0 :                 attempt,
     310            0 :                 PreparedTimelineDetach { layers: Vec::new() },
     311            0 :             ));
     312            0 :         }
     313              : 
     314            0 :         let reparented_timelines = reparented_direct_children(detached, tenant)?;
     315            0 :         return Ok(Progress::Done(AncestorDetached {
     316            0 :             reparented_timelines,
     317            0 :         }));
     318              :     };
     319              : 
     320            0 :     if detached.is_archived() != Some(false) {
     321            0 :         return Err(Archived(detached.timeline_id));
     322            0 :     }
     323            0 : 
     324            0 :     if !ancestor_lsn.is_valid() {
     325              :         // rare case, probably wouldn't even load
     326            0 :         tracing::error!("ancestor is set, but ancestor_lsn is invalid, this timeline needs fixing");
     327            0 :         return Err(NoAncestor);
     328            0 :     }
     329            0 : 
     330            0 :     check_no_archived_children_of_ancestor(tenant, detached, &ancestor, ancestor_lsn, behavior)?;
     331              : 
     332            0 :     if let DetachBehavior::MultiLevelAndNoReparent = behavior {
     333              :         // If the ancestor has an ancestor, we might be able to fast-path detach it if the current ancestor does not have any data written/used by the detaching timeline.
     334            0 :         while let Some(ancestor_of_ancestor) = ancestor.ancestor_timeline.clone() {
     335            0 :             if ancestor_lsn != ancestor.ancestor_lsn {
     336              :                 // non-technical requirement; we could flatten still if ancestor LSN does not match but that needs
     337              :                 // us to copy and cut more layers.
     338            0 :                 return Err(AncestorNotEmpty);
     339            0 :             }
     340            0 :             // Use the ancestor of the ancestor as the new ancestor (only when the ancestor LSNs are the same)
     341            0 :             ancestor_lsn = ancestor.ancestor_lsn; // Get the LSN first before resetting the `ancestor` variable
     342            0 :             ancestor = ancestor_of_ancestor;
     343            0 :             // TODO: do we still need to check if we don't want to reparent?
     344            0 :             check_no_archived_children_of_ancestor(
     345            0 :                 tenant,
     346            0 :                 detached,
     347            0 :                 &ancestor,
     348            0 :                 ancestor_lsn,
     349            0 :                 behavior,
     350            0 :             )?;
     351              :         }
     352            0 :     } else if ancestor.ancestor_timeline.is_some() {
     353              :         // non-technical requirement; we could flatten N ancestors just as easily but we chose
     354              :         // not to, at least initially
     355            0 :         return Err(TooManyAncestors);
     356            0 :     }
     357              : 
     358            0 :     tracing::info!(
     359            0 :         "attempt to detach the timeline from the ancestor: {}@{}, behavior={:?}",
     360            0 :         ancestor.timeline_id,
     361              :         ancestor_lsn,
     362              :         behavior
     363              :     );
     364              : 
     365            0 :     let attempt = start_new_attempt(detached, tenant, ancestor.timeline_id, ancestor_lsn).await?;
     366              : 
     367            0 :     utils::pausable_failpoint!("timeline-detach-ancestor::before_starting_after_locking-pausable");
     368              : 
     369            0 :     fail::fail_point!(
     370            0 :         "timeline-detach-ancestor::before_starting_after_locking",
     371            0 :         |_| Err(Error::Failpoint(
     372            0 :             "timeline-detach-ancestor::before_starting_after_locking"
     373            0 :         ))
     374            0 :     );
     375              : 
     376            0 :     if ancestor_lsn >= ancestor.get_disk_consistent_lsn() {
     377            0 :         let span =
     378            0 :             tracing::info_span!("freeze_and_flush", ancestor_timeline_id=%ancestor.timeline_id);
     379            0 :         async {
     380            0 :             let started_at = std::time::Instant::now();
     381            0 :             let freeze_and_flush = ancestor.freeze_and_flush0();
     382            0 :             let mut freeze_and_flush = std::pin::pin!(freeze_and_flush);
     383              : 
     384            0 :             let res =
     385            0 :                 tokio::time::timeout(std::time::Duration::from_secs(1), &mut freeze_and_flush)
     386            0 :                     .await;
     387              : 
     388            0 :             let res = match res {
     389            0 :                 Ok(res) => res,
     390            0 :                 Err(_elapsed) => {
     391            0 :                     tracing::info!("freezing and flushing ancestor is still ongoing");
     392            0 :                     freeze_and_flush.await
     393              :                 }
     394              :             };
     395              : 
     396            0 :             res.map_err(|e| {
     397              :                 use FlushLayerError::*;
     398            0 :                 match e {
     399              :                     Cancelled | NotRunning(_) => {
     400              :                         // FIXME(#6424): technically statically unreachable right now, given how we never
     401              :                         // drop the sender
     402            0 :                         Error::ShuttingDown
     403              :                     }
     404            0 :                     CreateImageLayersError(_) | Other(_) => Error::Prepare(e.into()),
     405              :                 }
     406            0 :             })?;
     407              : 
     408              :             // we do not need to wait for uploads to complete but we do need `struct Layer`,
     409              :             // copying delta prefix is unsupported currently for `InMemoryLayer`.
     410            0 :             tracing::info!(
     411            0 :                 elapsed_ms = started_at.elapsed().as_millis(),
     412            0 :                 "froze and flushed the ancestor"
     413              :             );
     414            0 :             Ok::<_, Error>(())
     415            0 :         }
     416            0 :         .instrument(span)
     417            0 :         .await?;
     418            0 :     }
     419              : 
     420            0 :     let end_lsn = ancestor_lsn + 1;
     421              : 
     422            0 :     let (filtered_layers, straddling_branchpoint, rest_of_historic) = {
     423              :         // we do not need to start from our layers, because they can only be layers that come
     424              :         // *after* ancestor_lsn
     425            0 :         let layers = tokio::select! {
     426            0 :             guard = ancestor.layers.read() => guard,
     427            0 :             _ = detached.cancel.cancelled() => {
     428            0 :                 return Err(ShuttingDown);
     429              :             }
     430            0 :             _ = ancestor.cancel.cancelled() => {
     431            0 :                 return Err(ShuttingDown);
     432              :             }
     433              :         };
     434              : 
     435              :         // between retries, these can change if compaction or gc ran in between. this will mean
     436              :         // we have to redo work.
     437            0 :         partition_work(ancestor_lsn, &layers)?
     438              :     };
     439              : 
     440              :     // TODO: layers are already sorted by something: use that to determine how much of remote
     441              :     // copies are already done -- gc is blocked, but a compaction could had happened on ancestor,
     442              :     // which is something to keep in mind if copy skipping is implemented.
     443            0 :     tracing::info!(filtered=%filtered_layers, to_rewrite = straddling_branchpoint.len(), historic=%rest_of_historic.len(), "collected layers");
     444              : 
     445              :     // TODO: copying and lsn prefix copying could be done at the same time with a single fsync after
     446            0 :     let mut new_layers: Vec<Layer> =
     447            0 :         Vec::with_capacity(straddling_branchpoint.len() + rest_of_historic.len() + 1);
     448              : 
     449            0 :     if let Some(tombstone_layer) =
     450            0 :         generate_tombstone_image_layer(detached, &ancestor, ancestor_lsn, ctx).await?
     451            0 :     {
     452            0 :         new_layers.push(tombstone_layer.into());
     453            0 :     }
     454              : 
     455              :     {
     456            0 :         tracing::info!(to_rewrite = %straddling_branchpoint.len(), "copying prefix of delta layers");
     457              : 
     458            0 :         let mut tasks = tokio::task::JoinSet::new();
     459            0 : 
     460            0 :         let mut wrote_any = false;
     461            0 : 
     462            0 :         let limiter = Arc::new(Semaphore::new(options.rewrite_concurrency.get()));
     463              : 
     464            0 :         for layer in straddling_branchpoint {
     465            0 :             let limiter = limiter.clone();
     466            0 :             let timeline = detached.clone();
     467            0 :             let ctx = ctx.detached_child(TaskKind::DetachAncestor, DownloadBehavior::Download);
     468              : 
     469            0 :             let span = tracing::info_span!("upload_rewritten_layer", %layer);
     470            0 :             tasks.spawn(
     471            0 :                 async move {
     472            0 :                     let _permit = limiter.acquire().await;
     473            0 :                     let copied =
     474            0 :                         upload_rewritten_layer(end_lsn, &layer, &timeline, &timeline.cancel, &ctx)
     475            0 :                             .await?;
     476            0 :                     if let Some(copied) = copied.as_ref() {
     477            0 :                         tracing::info!(%copied, "rewrote and uploaded");
     478            0 :                     }
     479            0 :                     Ok(copied)
     480            0 :                 }
     481            0 :                 .instrument(span),
     482            0 :             );
     483            0 :         }
     484              : 
     485            0 :         while let Some(res) = tasks.join_next().await {
     486            0 :             match res {
     487            0 :                 Ok(Ok(Some(copied))) => {
     488            0 :                     wrote_any = true;
     489            0 :                     new_layers.push(copied);
     490            0 :                 }
     491            0 :                 Ok(Ok(None)) => {}
     492            0 :                 Ok(Err(e)) => return Err(e),
     493            0 :                 Err(je) => return Err(Error::Prepare(je.into())),
     494              :             }
     495              :         }
     496              : 
     497              :         // FIXME: the fsync should be mandatory, after both rewrites and copies
     498            0 :         if wrote_any {
     499            0 :             fsync_timeline_dir(detached, ctx).await;
     500            0 :         }
     501              :     }
     502              : 
     503            0 :     let mut tasks = tokio::task::JoinSet::new();
     504            0 :     let limiter = Arc::new(Semaphore::new(options.copy_concurrency.get()));
     505            0 :     let cancel_eval = CancellationToken::new();
     506              : 
     507            0 :     for adopted in rest_of_historic {
     508            0 :         let limiter = limiter.clone();
     509            0 :         let timeline = detached.clone();
     510            0 :         let cancel_eval = cancel_eval.clone();
     511            0 : 
     512            0 :         tasks.spawn(
     513            0 :             async move {
     514            0 :                 let _permit = tokio::select! {
     515            0 :                     permit = limiter.acquire() => {
     516            0 :                         permit
     517              :                     }
     518              :                     // Wait for the cancellation here instead of letting the entire task be cancelled.
     519              :                     // Cancellations are racy in that they might leave layers on disk.
     520            0 :                     _ = cancel_eval.cancelled() => {
     521            0 :                         Err(Error::ShuttingDown)?
     522              :                     }
     523              :                 };
     524            0 :                 let (owned, did_hardlink) = remote_copy(
     525            0 :                     &adopted,
     526            0 :                     &timeline,
     527            0 :                     timeline.generation,
     528            0 :                     timeline.shard_identity,
     529            0 :                     &timeline.cancel,
     530            0 :                 )
     531            0 :                 .await?;
     532            0 :                 tracing::info!(layer=%owned, did_hard_link=%did_hardlink, "remote copied");
     533            0 :                 Ok((owned, did_hardlink))
     534            0 :             }
     535            0 :             .in_current_span(),
     536            0 :         );
     537            0 :     }
     538              : 
     539            0 :     fn delete_layers(timeline: &Timeline, layers: Vec<Layer>) -> Result<(), Error> {
     540              :         // We are deleting layers, so we must hold the gate
     541            0 :         let _gate = timeline.gate.enter().map_err(|e| match e {
     542            0 :             GateError::GateClosed => Error::ShuttingDown,
     543            0 :         })?;
     544            0 :         {
     545            0 :             layers.into_iter().for_each(|l: Layer| {
     546            0 :                 l.delete_on_drop();
     547            0 :                 std::mem::drop(l);
     548            0 :             });
     549            0 :         }
     550            0 :         Ok(())
     551            0 :     }
     552              : 
     553            0 :     let mut should_fsync = false;
     554            0 :     let mut first_err = None;
     555            0 :     while let Some(res) = tasks.join_next().await {
     556            0 :         match res {
     557            0 :             Ok(Ok((owned, did_hardlink))) => {
     558            0 :                 if did_hardlink {
     559            0 :                     should_fsync = true;
     560            0 :                 }
     561            0 :                 new_layers.push(owned);
     562              :             }
     563              : 
     564              :             // Don't stop the evaluation on errors, so that we get the full set of hardlinked layers to delete.
     565            0 :             Ok(Err(failed)) => {
     566            0 :                 cancel_eval.cancel();
     567            0 :                 first_err.get_or_insert(failed);
     568            0 :             }
     569            0 :             Err(je) => {
     570            0 :                 cancel_eval.cancel();
     571            0 :                 first_err.get_or_insert(Error::Prepare(je.into()));
     572            0 :             }
     573              :         }
     574              :     }
     575              : 
     576            0 :     if let Some(failed) = first_err {
     577            0 :         delete_layers(detached, new_layers)?;
     578            0 :         return Err(failed);
     579            0 :     }
     580            0 : 
     581            0 :     // fsync directory again if we hardlinked something
     582            0 :     if should_fsync {
     583            0 :         fsync_timeline_dir(detached, ctx).await;
     584            0 :     }
     585              : 
     586            0 :     let prepared = PreparedTimelineDetach { layers: new_layers };
     587            0 : 
     588            0 :     Ok(Progress::Prepared(attempt, prepared))
     589            0 : }
     590              : 
     591            0 : async fn start_new_attempt(
     592            0 :     detached: &Timeline,
     593            0 :     tenant: &TenantShard,
     594            0 :     ancestor_timeline_id: TimelineId,
     595            0 :     ancestor_lsn: Lsn,
     596            0 : ) -> Result<Attempt, Error> {
     597            0 :     let attempt = obtain_exclusive_attempt(detached, tenant, ancestor_timeline_id, ancestor_lsn)?;
     598              : 
     599              :     // insert the block in the index_part.json, if not already there.
     600            0 :     let _dont_care = tenant
     601            0 :         .gc_block
     602            0 :         .insert(
     603            0 :             detached,
     604            0 :             crate::tenant::remote_timeline_client::index::GcBlockingReason::DetachAncestor,
     605            0 :         )
     606            0 :         .await
     607            0 :         .map_err(|e| Error::launder(e, Error::Prepare))?;
     608              : 
     609            0 :     Ok(attempt)
     610            0 : }
     611              : 
     612            0 : async fn continue_with_blocked_gc(
     613            0 :     detached: &Timeline,
     614            0 :     tenant: &TenantShard,
     615            0 :     ancestor_timeline_id: TimelineId,
     616            0 :     ancestor_lsn: Lsn,
     617            0 : ) -> Result<Attempt, Error> {
     618            0 :     // FIXME: it would be nice to confirm that there is an in-memory version, since we've just
     619            0 :     // verified there is a persistent one?
     620            0 :     obtain_exclusive_attempt(detached, tenant, ancestor_timeline_id, ancestor_lsn)
     621            0 : }
     622              : 
     623            0 : fn obtain_exclusive_attempt(
     624            0 :     detached: &Timeline,
     625            0 :     tenant: &TenantShard,
     626            0 :     ancestor_timeline_id: TimelineId,
     627            0 :     ancestor_lsn: Lsn,
     628            0 : ) -> Result<Attempt, Error> {
     629              :     use Error::{OtherTimelineDetachOngoing, ShuttingDown};
     630              : 
     631              :     // ensure we are the only active attempt for this tenant
     632            0 :     let (guard, barrier) = completion::channel();
     633            0 :     {
     634            0 :         let mut guard = tenant.ongoing_timeline_detach.lock().unwrap();
     635            0 :         if let Some((tl, other)) = guard.as_ref() {
     636            0 :             if !other.is_ready() {
     637            0 :                 return Err(OtherTimelineDetachOngoing(*tl));
     638            0 :             }
     639              :             // FIXME: no test enters here
     640            0 :         }
     641            0 :         *guard = Some((detached.timeline_id, barrier));
     642              :     }
     643              : 
     644              :     // ensure the gate is still open
     645            0 :     let _gate_entered = detached.gate.enter().map_err(|_| ShuttingDown)?;
     646              : 
     647            0 :     Ok(Attempt {
     648            0 :         timeline_id: detached.timeline_id,
     649            0 :         ancestor_timeline_id,
     650            0 :         ancestor_lsn,
     651            0 :         _guard: guard,
     652            0 :         gate_entered: Some(_gate_entered),
     653            0 :     })
     654            0 : }
     655              : 
     656            0 : fn reparented_direct_children(
     657            0 :     detached: &Arc<Timeline>,
     658            0 :     tenant: &TenantShard,
     659            0 : ) -> Result<HashSet<TimelineId>, Error> {
     660            0 :     let mut all_direct_children = tenant
     661            0 :         .timelines
     662            0 :         .lock()
     663            0 :         .unwrap()
     664            0 :         .values()
     665            0 :         .filter_map(|tl| {
     666            0 :             let is_direct_child = matches!(tl.ancestor_timeline.as_ref(), Some(ancestor) if Arc::ptr_eq(ancestor, detached));
     667              : 
     668            0 :             if is_direct_child {
     669            0 :                 Some(tl.clone())
     670              :             } else {
     671            0 :                 if let Some(timeline) = tl.ancestor_timeline.as_ref() {
     672            0 :                     assert_ne!(timeline.timeline_id, detached.timeline_id, "we cannot have two timelines with the same timeline_id live");
     673            0 :                 }
     674            0 :                 None
     675              :             }
     676            0 :         })
     677            0 :         // Collect to avoid lock taking order problem with Tenant::timelines and
     678            0 :         // Timeline::remote_client
     679            0 :         .collect::<Vec<_>>();
     680            0 : 
     681            0 :     let mut any_shutdown = false;
     682            0 : 
     683            0 :     all_direct_children.retain(|tl| match tl.remote_client.initialized_upload_queue() {
     684            0 :         Ok(accessor) => accessor
     685            0 :             .latest_uploaded_index_part()
     686            0 :             .lineage
     687            0 :             .is_reparented(),
     688            0 :         Err(_shutdownalike) => {
     689            0 :             // not 100% a shutdown, but let's bail early not to give inconsistent results in
     690            0 :             // sharded enviroment.
     691            0 :             any_shutdown = true;
     692            0 :             true
     693              :         }
     694            0 :     });
     695            0 : 
     696            0 :     if any_shutdown {
     697              :         // it could be one or many being deleted; have client retry
     698            0 :         return Err(Error::ShuttingDown);
     699            0 :     }
     700            0 : 
     701            0 :     Ok(all_direct_children
     702            0 :         .into_iter()
     703            0 :         .map(|tl| tl.timeline_id)
     704            0 :         .collect())
     705            0 : }
     706              : 
     707            0 : fn partition_work(
     708            0 :     ancestor_lsn: Lsn,
     709            0 :     source: &LayerManager,
     710            0 : ) -> Result<(usize, Vec<Layer>, Vec<Layer>), Error> {
     711            0 :     let mut straddling_branchpoint = vec![];
     712            0 :     let mut rest_of_historic = vec![];
     713            0 : 
     714            0 :     let mut later_by_lsn = 0;
     715              : 
     716            0 :     for desc in source.layer_map()?.iter_historic_layers() {
     717              :         // off by one chances here:
     718              :         // - start is inclusive
     719              :         // - end is exclusive
     720            0 :         if desc.lsn_range.start > ancestor_lsn {
     721            0 :             later_by_lsn += 1;
     722            0 :             continue;
     723            0 :         }
     724              : 
     725            0 :         let target = if desc.lsn_range.start <= ancestor_lsn
     726            0 :             && desc.lsn_range.end > ancestor_lsn
     727            0 :             && desc.is_delta
     728              :         {
     729              :             // TODO: image layer at Lsn optimization
     730            0 :             &mut straddling_branchpoint
     731              :         } else {
     732            0 :             &mut rest_of_historic
     733              :         };
     734              : 
     735            0 :         target.push(source.get_from_desc(&desc));
     736              :     }
     737              : 
     738            0 :     Ok((later_by_lsn, straddling_branchpoint, rest_of_historic))
     739            0 : }
     740              : 
     741            0 : async fn upload_rewritten_layer(
     742            0 :     end_lsn: Lsn,
     743            0 :     layer: &Layer,
     744            0 :     target: &Arc<Timeline>,
     745            0 :     cancel: &CancellationToken,
     746            0 :     ctx: &RequestContext,
     747            0 : ) -> Result<Option<Layer>, Error> {
     748            0 :     let copied = copy_lsn_prefix(end_lsn, layer, target, ctx).await?;
     749              : 
     750            0 :     let Some(copied) = copied else {
     751            0 :         return Ok(None);
     752              :     };
     753              : 
     754            0 :     target
     755            0 :         .remote_client
     756            0 :         .upload_layer_file(&copied, cancel)
     757            0 :         .await
     758            0 :         .map_err(|e| Error::launder(e, Error::Prepare))?;
     759              : 
     760            0 :     Ok(Some(copied.into()))
     761            0 : }
     762              : 
     763            0 : async fn copy_lsn_prefix(
     764            0 :     end_lsn: Lsn,
     765            0 :     layer: &Layer,
     766            0 :     target_timeline: &Arc<Timeline>,
     767            0 :     ctx: &RequestContext,
     768            0 : ) -> Result<Option<ResidentLayer>, Error> {
     769            0 :     if target_timeline.cancel.is_cancelled() {
     770            0 :         return Err(Error::ShuttingDown);
     771            0 :     }
     772            0 : 
     773            0 :     tracing::debug!(%layer, %end_lsn, "copying lsn prefix");
     774              : 
     775            0 :     let mut writer = DeltaLayerWriter::new(
     776            0 :         target_timeline.conf,
     777            0 :         target_timeline.timeline_id,
     778            0 :         target_timeline.tenant_shard_id,
     779            0 :         layer.layer_desc().key_range.start,
     780            0 :         layer.layer_desc().lsn_range.start..end_lsn,
     781            0 :         &target_timeline.gate,
     782            0 :         target_timeline.cancel.clone(),
     783            0 :         ctx,
     784            0 :     )
     785            0 :     .await
     786            0 :     .with_context(|| format!("prepare to copy lsn prefix of ancestors {layer}"))
     787            0 :     .map_err(Error::Prepare)?;
     788              : 
     789            0 :     let resident = layer.download_and_keep_resident(ctx).await.map_err(|e| {
     790            0 :         if e.is_cancelled() {
     791            0 :             Error::ShuttingDown
     792              :         } else {
     793            0 :             Error::Prepare(e.into())
     794              :         }
     795            0 :     })?;
     796              : 
     797            0 :     let records = resident
     798            0 :         .copy_delta_prefix(&mut writer, end_lsn, ctx)
     799            0 :         .await
     800            0 :         .with_context(|| format!("copy lsn prefix of ancestors {layer}"))
     801            0 :         .map_err(Error::Prepare)?;
     802              : 
     803            0 :     drop(resident);
     804            0 : 
     805            0 :     tracing::debug!(%layer, records, "copied records");
     806              : 
     807            0 :     if records == 0 {
     808            0 :         drop(writer);
     809            0 :         // TODO: we might want to store an empty marker in remote storage for this
     810            0 :         // layer so that we will not needlessly walk `layer` on repeated attempts.
     811            0 :         Ok(None)
     812              :     } else {
     813              :         // reuse the key instead of adding more holes between layers by using the real
     814              :         // highest key in the layer.
     815            0 :         let reused_highest_key = layer.layer_desc().key_range.end;
     816            0 :         let (desc, path) = writer
     817            0 :             .finish(reused_highest_key, ctx)
     818            0 :             .await
     819            0 :             .map_err(Error::Prepare)?;
     820            0 :         let copied = Layer::finish_creating(target_timeline.conf, target_timeline, desc, &path)
     821            0 :             .map_err(Error::Prepare)?;
     822              : 
     823            0 :         tracing::debug!(%layer, %copied, "new layer produced");
     824              : 
     825            0 :         Ok(Some(copied))
     826              :     }
     827            0 : }
     828              : 
     829              : /// Creates a new Layer instance for the adopted layer, and ensures it is found in the remote
     830              : /// storage on successful return. without the adopted layer being added to `index_part.json`.
     831              : /// Returns (Layer, did hardlink)
     832            0 : async fn remote_copy(
     833            0 :     adopted: &Layer,
     834            0 :     adoptee: &Arc<Timeline>,
     835            0 :     generation: Generation,
     836            0 :     shard_identity: ShardIdentity,
     837            0 :     cancel: &CancellationToken,
     838            0 : ) -> Result<(Layer, bool), Error> {
     839            0 :     let mut metadata = adopted.metadata();
     840            0 :     debug_assert!(metadata.generation <= generation);
     841            0 :     metadata.generation = generation;
     842            0 :     metadata.shard = shard_identity.shard_index();
     843            0 : 
     844            0 :     let conf = adoptee.conf;
     845            0 :     let file_name = adopted.layer_desc().layer_name();
     846              : 
     847              :     // We don't want to shut the timeline down during this operation because we do `delete_on_drop` below
     848            0 :     let _gate = adoptee.gate.enter().map_err(|e| match e {
     849            0 :         GateError::GateClosed => Error::ShuttingDown,
     850            0 :     })?;
     851              : 
     852              :     // depending if Layer::keep_resident, do a hardlink
     853              :     let did_hardlink;
     854            0 :     let owned = if let Some(adopted_resident) = adopted.keep_resident().await {
     855            0 :         let adopted_path = adopted_resident.local_path();
     856            0 :         let adoptee_path = local_layer_path(
     857            0 :             conf,
     858            0 :             &adoptee.tenant_shard_id,
     859            0 :             &adoptee.timeline_id,
     860            0 :             &file_name,
     861            0 :             &metadata.generation,
     862            0 :         );
     863            0 : 
     864            0 :         match std::fs::hard_link(adopted_path, &adoptee_path) {
     865            0 :             Ok(()) => {}
     866            0 :             Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
     867            0 :                 // In theory we should not get into this situation as we are doing cleanups of the layer file after errors.
     868            0 :                 // However, we don't do cleanups for errors past `prepare`, so there is the slight chance to get to this branch.
     869            0 : 
     870            0 :                 // Double check that the file is orphan (probably from an earlier attempt), then delete it
     871            0 :                 let key = file_name.clone().into();
     872            0 :                 if adoptee.layers.read().await.contains_key(&key) {
     873              :                     // We are supposed to filter out such cases before coming to this function
     874            0 :                     return Err(Error::Prepare(anyhow::anyhow!(
     875            0 :                         "layer file {file_name} already present and inside layer map"
     876            0 :                     )));
     877            0 :                 }
     878            0 :                 tracing::info!("Deleting orphan layer file to make way for hard linking");
     879              :                 // Delete orphan layer file and try again, to ensure this layer has a well understood source
     880            0 :                 std::fs::remove_file(adopted_path)
     881            0 :                     .map_err(|e| Error::launder(e.into(), Error::Prepare))?;
     882            0 :                 std::fs::hard_link(adopted_path, &adoptee_path)
     883            0 :                     .map_err(|e| Error::launder(e.into(), Error::Prepare))?;
     884              :             }
     885            0 :             Err(e) => {
     886            0 :                 return Err(Error::launder(e.into(), Error::Prepare));
     887              :             }
     888              :         };
     889            0 :         did_hardlink = true;
     890            0 :         Layer::for_resident(conf, adoptee, adoptee_path, file_name, metadata).drop_eviction_guard()
     891              :     } else {
     892            0 :         did_hardlink = false;
     893            0 :         Layer::for_evicted(conf, adoptee, file_name, metadata)
     894              :     };
     895              : 
     896            0 :     let layer = match adoptee
     897            0 :         .remote_client
     898            0 :         .copy_timeline_layer(adopted, &owned, cancel)
     899            0 :         .await
     900              :     {
     901            0 :         Ok(()) => owned,
     902            0 :         Err(e) => {
     903            0 :             {
     904            0 :                 // Clean up the layer so that on a retry we don't get errors that the file already exists
     905            0 :                 owned.delete_on_drop();
     906            0 :                 std::mem::drop(owned);
     907            0 :             }
     908            0 :             return Err(Error::launder(e, Error::Prepare));
     909              :         }
     910              :     };
     911              : 
     912            0 :     Ok((layer, did_hardlink))
     913            0 : }
     914              : 
     915              : pub(crate) enum DetachingAndReparenting {
     916              :     /// All of the following timeline ids were reparented and the timeline ancestor detach must be
     917              :     /// marked as completed.
     918              :     Reparented(HashSet<TimelineId>),
     919              : 
     920              :     /// Some of the reparentings failed. The timeline ancestor detach must **not** be marked as
     921              :     /// completed.
     922              :     ///
     923              :     /// Nested `must_reset_tenant` is set to true when any restart requiring changes were made.
     924              :     SomeReparentingFailed { must_reset_tenant: bool },
     925              : 
     926              :     /// Detaching and reparentings were completed in a previous attempt. Timeline ancestor detach
     927              :     /// must be marked as completed.
     928              :     AlreadyDone(HashSet<TimelineId>),
     929              : }
     930              : 
     931              : impl DetachingAndReparenting {
     932            0 :     pub(crate) fn reset_tenant_required(&self) -> bool {
     933              :         use DetachingAndReparenting::*;
     934            0 :         match self {
     935            0 :             Reparented(_) => true,
     936            0 :             SomeReparentingFailed { must_reset_tenant } => *must_reset_tenant,
     937            0 :             AlreadyDone(_) => false,
     938              :         }
     939            0 :     }
     940              : 
     941            0 :     pub(crate) fn completed(self) -> Option<HashSet<TimelineId>> {
     942              :         use DetachingAndReparenting::*;
     943            0 :         match self {
     944            0 :             Reparented(x) | AlreadyDone(x) => Some(x),
     945            0 :             SomeReparentingFailed { .. } => None,
     946              :         }
     947            0 :     }
     948              : }
     949              : 
     950              : /// See [`Timeline::detach_from_ancestor_and_reparent`].
     951            0 : pub(super) async fn detach_and_reparent(
     952            0 :     detached: &Arc<Timeline>,
     953            0 :     tenant: &TenantShard,
     954            0 :     prepared: PreparedTimelineDetach,
     955            0 :     ancestor_timeline_id: TimelineId,
     956            0 :     ancestor_lsn: Lsn,
     957            0 :     behavior: DetachBehavior,
     958            0 :     _ctx: &RequestContext,
     959            0 : ) -> Result<DetachingAndReparenting, Error> {
     960            0 :     let PreparedTimelineDetach { layers } = prepared;
     961              : 
     962              :     #[derive(Debug)]
     963              :     enum Ancestor {
     964              :         NotDetached(Arc<Timeline>, Lsn),
     965              :         Detached(Arc<Timeline>, Lsn),
     966              :     }
     967              : 
     968            0 :     let (recorded_branchpoint, still_ongoing) = {
     969            0 :         let access = detached.remote_client.initialized_upload_queue()?;
     970            0 :         let latest = access.latest_uploaded_index_part();
     971            0 : 
     972            0 :         (
     973            0 :             latest.lineage.detached_previous_ancestor(),
     974            0 :             latest
     975            0 :                 .gc_blocking
     976            0 :                 .as_ref()
     977            0 :                 .is_some_and(|b| b.blocked_by(DetachAncestor)),
     978            0 :         )
     979            0 :     };
     980            0 :     assert!(
     981            0 :         still_ongoing,
     982            0 :         "cannot (detach? reparent)? complete if the operation is not still ongoing"
     983              :     );
     984              : 
     985            0 :     let ancestor_to_detach = match detached.ancestor_timeline.as_ref() {
     986            0 :         Some(mut ancestor) => {
     987            0 :             while ancestor.timeline_id != ancestor_timeline_id {
     988            0 :                 match ancestor.ancestor_timeline.as_ref() {
     989            0 :                     Some(found) => {
     990            0 :                         if ancestor_lsn != ancestor.ancestor_lsn {
     991            0 :                             return Err(Error::DetachReparent(anyhow::anyhow!(
     992            0 :                                 "cannot find the ancestor timeline to detach from: wrong ancestor lsn"
     993            0 :                             )));
     994            0 :                         }
     995            0 :                         ancestor = found;
     996              :                     }
     997              :                     None => {
     998            0 :                         return Err(Error::DetachReparent(anyhow::anyhow!(
     999            0 :                             "cannot find the ancestor timeline to detach from"
    1000            0 :                         )));
    1001              :                     }
    1002              :                 }
    1003              :             }
    1004            0 :             Some(ancestor)
    1005              :         }
    1006            0 :         None => None,
    1007              :     };
    1008            0 :     let ancestor = match (ancestor_to_detach, recorded_branchpoint) {
    1009            0 :         (Some(ancestor), None) => {
    1010            0 :             assert!(
    1011            0 :                 !layers.is_empty(),
    1012            0 :                 "there should always be at least one layer to inherit"
    1013              :             );
    1014            0 :             Ancestor::NotDetached(ancestor.clone(), detached.ancestor_lsn)
    1015              :         }
    1016              :         (Some(_), Some(_)) => {
    1017            0 :             panic!(
    1018            0 :                 "it should be impossible to get to here without having gone through the tenant reset; if the tenant was reset, then the ancestor_timeline would be None"
    1019            0 :             );
    1020              :         }
    1021            0 :         (None, Some((ancestor_id, ancestor_lsn))) => {
    1022            0 :             // it has been either:
    1023            0 :             // - detached but still exists => we can try reparenting
    1024            0 :             // - detached and deleted
    1025            0 :             //
    1026            0 :             // either way, we must complete
    1027            0 :             assert!(
    1028            0 :                 layers.is_empty(),
    1029            0 :                 "no layers should had been copied as detach is done"
    1030              :             );
    1031              : 
    1032            0 :             let existing = tenant.timelines.lock().unwrap().get(&ancestor_id).cloned();
    1033              : 
    1034            0 :             if let Some(ancestor) = existing {
    1035            0 :                 Ancestor::Detached(ancestor, ancestor_lsn)
    1036              :             } else {
    1037            0 :                 let direct_children = reparented_direct_children(detached, tenant)?;
    1038            0 :                 return Ok(DetachingAndReparenting::AlreadyDone(direct_children));
    1039              :             }
    1040              :         }
    1041              :         (None, None) => {
    1042              :             // TODO: make sure there are no `?` before tenant_reset from after a questionmark from
    1043              :             // here.
    1044            0 :             panic!(
    1045            0 :                 "bug: detach_and_reparent called on a timeline which has not been detached or which has no live ancestor"
    1046            0 :             );
    1047              :         }
    1048              :     };
    1049              : 
    1050              :     // publish the prepared layers before we reparent any of the timelines, so that on restart
    1051              :     // reparented timelines find layers. also do the actual detaching.
    1052              :     //
    1053              :     // if we crash after this operation, a retry will allow reparenting the remaining timelines as
    1054              :     // gc is blocked.
    1055              : 
    1056            0 :     let (ancestor, ancestor_lsn, was_detached) = match ancestor {
    1057            0 :         Ancestor::NotDetached(ancestor, ancestor_lsn) => {
    1058            0 :             // this has to complete before any reparentings because otherwise they would not have
    1059            0 :             // layers on the new parent.
    1060            0 :             detached
    1061            0 :                 .remote_client
    1062            0 :                 .schedule_adding_existing_layers_to_index_detach_and_wait(
    1063            0 :                     &layers,
    1064            0 :                     (ancestor.timeline_id, ancestor_lsn),
    1065            0 :                 )
    1066            0 :                 .await
    1067            0 :                 .context("publish layers and detach ancestor")
    1068            0 :                 .map_err(|e| Error::launder(e, Error::DetachReparent))?;
    1069              : 
    1070            0 :             tracing::info!(
    1071            0 :                 ancestor=%ancestor.timeline_id,
    1072            0 :                 %ancestor_lsn,
    1073            0 :                 inherited_layers=%layers.len(),
    1074            0 :                 "detached from ancestor"
    1075              :             );
    1076            0 :             (ancestor, ancestor_lsn, true)
    1077              :         }
    1078            0 :         Ancestor::Detached(ancestor, ancestor_lsn) => (ancestor, ancestor_lsn, false),
    1079              :     };
    1080              : 
    1081            0 :     if let DetachBehavior::MultiLevelAndNoReparent = behavior {
    1082              :         // Do not reparent if the user requests to behave so.
    1083            0 :         return Ok(DetachingAndReparenting::Reparented(HashSet::new()));
    1084            0 :     }
    1085            0 : 
    1086            0 :     let mut tasks = tokio::task::JoinSet::new();
    1087            0 : 
    1088            0 :     // Returns a single permit semaphore which will be used to make one reparenting succeed,
    1089            0 :     // others will fail as if those timelines had been stopped for whatever reason.
    1090            0 :     #[cfg(feature = "testing")]
    1091            0 :     let failpoint_sem = || -> Option<Arc<Semaphore>> {
    1092            0 :         fail::fail_point!("timeline-detach-ancestor::allow_one_reparented", |_| Some(
    1093            0 :             Arc::new(Semaphore::new(1))
    1094            0 :         ));
    1095            0 :         None
    1096            0 :     }();
    1097            0 : 
    1098            0 :     // because we are now keeping the slot in progress, it is unlikely that there will be any
    1099            0 :     // timeline deletions during this time. if we raced one, then we'll just ignore it.
    1100            0 :     {
    1101            0 :         let g = tenant.timelines.lock().unwrap();
    1102            0 :         reparentable_timelines(g.values(), detached, &ancestor, ancestor_lsn)
    1103            0 :             .cloned()
    1104            0 :             .for_each(|timeline| {
    1105              :                 // important in this scope: we are holding the Tenant::timelines lock
    1106            0 :                 let span = tracing::info_span!("reparent", reparented=%timeline.timeline_id);
    1107            0 :                 let new_parent = detached.timeline_id;
    1108            0 :                 #[cfg(feature = "testing")]
    1109            0 :                 let failpoint_sem = failpoint_sem.clone();
    1110            0 : 
    1111            0 :                 tasks.spawn(
    1112            0 :                     async move {
    1113            0 :                         let res = async {
    1114              :                             #[cfg(feature = "testing")]
    1115            0 :                             if let Some(failpoint_sem) = failpoint_sem {
    1116            0 :                                 let _permit = failpoint_sem.acquire().await.map_err(|_| {
    1117            0 :                                     anyhow::anyhow!(
    1118            0 :                                         "failpoint: timeline-detach-ancestor::allow_one_reparented",
    1119            0 :                                     )
    1120            0 :                                 })?;
    1121            0 :                                 failpoint_sem.close();
    1122            0 :                             }
    1123              : 
    1124            0 :                             timeline
    1125            0 :                                 .remote_client
    1126            0 :                                 .schedule_reparenting_and_wait(&new_parent)
    1127            0 :                                 .await
    1128            0 :                         }
    1129            0 :                         .await;
    1130              : 
    1131            0 :                         match res {
    1132              :                             Ok(()) => {
    1133            0 :                                 tracing::info!("reparented");
    1134            0 :                                 Some(timeline)
    1135              :                             }
    1136            0 :                             Err(e) => {
    1137            0 :                                 // with the use of tenant slot, raced timeline deletion is the most
    1138            0 :                                 // likely reason.
    1139            0 :                                 tracing::warn!("reparenting failed: {e:#}");
    1140            0 :                                 None
    1141              :                             }
    1142              :                         }
    1143            0 :                     }
    1144            0 :                     .instrument(span),
    1145            0 :                 );
    1146            0 :             });
    1147            0 :     }
    1148            0 : 
    1149            0 :     let reparenting_candidates = tasks.len();
    1150            0 :     let mut reparented = HashSet::with_capacity(tasks.len());
    1151              : 
    1152            0 :     while let Some(res) = tasks.join_next().await {
    1153            0 :         match res {
    1154            0 :             Ok(Some(timeline)) => {
    1155            0 :                 assert!(
    1156            0 :                     reparented.insert(timeline.timeline_id),
    1157            0 :                     "duplicate reparenting? timeline_id={}",
    1158            0 :                     timeline.timeline_id
    1159              :                 );
    1160              :             }
    1161            0 :             Err(je) if je.is_cancelled() => unreachable!("not used"),
    1162              :             // just ignore failures now, we can retry
    1163            0 :             Ok(None) => {}
    1164            0 :             Err(je) if je.is_panic() => {}
    1165            0 :             Err(je) => tracing::error!("unexpected join error: {je:?}"),
    1166              :         }
    1167              :     }
    1168              : 
    1169            0 :     let reparented_all = reparenting_candidates == reparented.len();
    1170            0 : 
    1171            0 :     if reparented_all {
    1172            0 :         Ok(DetachingAndReparenting::Reparented(reparented))
    1173              :     } else {
    1174            0 :         tracing::info!(
    1175            0 :             reparented = reparented.len(),
    1176            0 :             candidates = reparenting_candidates,
    1177            0 :             "failed to reparent all candidates; they can be retried after the tenant_reset",
    1178              :         );
    1179              : 
    1180            0 :         let must_reset_tenant = !reparented.is_empty() || was_detached;
    1181            0 :         Ok(DetachingAndReparenting::SomeReparentingFailed { must_reset_tenant })
    1182              :     }
    1183            0 : }
    1184              : 
    1185            0 : pub(super) async fn complete(
    1186            0 :     detached: &Arc<Timeline>,
    1187            0 :     tenant: &TenantShard,
    1188            0 :     mut attempt: Attempt,
    1189            0 :     _ctx: &RequestContext,
    1190            0 : ) -> Result<(), Error> {
    1191            0 :     assert_eq!(detached.timeline_id, attempt.timeline_id);
    1192              : 
    1193            0 :     if attempt.gate_entered.is_none() {
    1194            0 :         let entered = detached.gate.enter().map_err(|_| Error::ShuttingDown)?;
    1195            0 :         attempt.gate_entered = Some(entered);
    1196            0 :     } else {
    1197            0 :         // Some(gate_entered) means the tenant was not restarted, as is not required
    1198            0 :     }
    1199              : 
    1200            0 :     assert!(detached.ancestor_timeline.is_none());
    1201              : 
    1202              :     // this should be an 503 at least...?
    1203            0 :     fail::fail_point!(
    1204            0 :         "timeline-detach-ancestor::complete_before_uploading",
    1205            0 :         |_| Err(Error::Failpoint(
    1206            0 :             "timeline-detach-ancestor::complete_before_uploading"
    1207            0 :         ))
    1208            0 :     );
    1209              : 
    1210            0 :     tenant
    1211            0 :         .gc_block
    1212            0 :         .remove(
    1213            0 :             detached,
    1214            0 :             crate::tenant::remote_timeline_client::index::GcBlockingReason::DetachAncestor,
    1215            0 :         )
    1216            0 :         .await
    1217            0 :         .map_err(|e| Error::launder(e, Error::Complete))?;
    1218              : 
    1219            0 :     Ok(())
    1220            0 : }
    1221              : 
    1222              : /// Query against a locked `Tenant::timelines`.
    1223              : ///
    1224              : /// A timeline is reparentable if:
    1225              : ///
    1226              : /// - It is not the timeline being detached.
    1227              : /// - It has the same ancestor as the timeline being detached. Note that the ancestor might not be the direct ancestor.
    1228            0 : fn reparentable_timelines<'a, I>(
    1229            0 :     timelines: I,
    1230            0 :     detached: &'a Arc<Timeline>,
    1231            0 :     ancestor: &'a Arc<Timeline>,
    1232            0 :     ancestor_lsn: Lsn,
    1233            0 : ) -> impl Iterator<Item = &'a Arc<Timeline>> + 'a
    1234            0 : where
    1235            0 :     I: Iterator<Item = &'a Arc<Timeline>> + 'a,
    1236            0 : {
    1237            0 :     timelines.filter_map(move |tl| {
    1238            0 :         if Arc::ptr_eq(tl, detached) {
    1239            0 :             return None;
    1240            0 :         }
    1241              : 
    1242            0 :         let tl_ancestor = tl.ancestor_timeline.as_ref()?;
    1243            0 :         let is_same = Arc::ptr_eq(ancestor, tl_ancestor);
    1244            0 :         let is_earlier = tl.get_ancestor_lsn() <= ancestor_lsn;
    1245            0 : 
    1246            0 :         let is_deleting = tl
    1247            0 :             .delete_progress
    1248            0 :             .try_lock()
    1249            0 :             .map(|flow| !flow.is_not_started())
    1250            0 :             .unwrap_or(true);
    1251            0 : 
    1252            0 :         if is_same && is_earlier && !is_deleting {
    1253            0 :             Some(tl)
    1254              :         } else {
    1255            0 :             None
    1256              :         }
    1257            0 :     })
    1258            0 : }
    1259              : 
    1260            0 : fn check_no_archived_children_of_ancestor(
    1261            0 :     tenant: &TenantShard,
    1262            0 :     detached: &Arc<Timeline>,
    1263            0 :     ancestor: &Arc<Timeline>,
    1264            0 :     ancestor_lsn: Lsn,
    1265            0 :     detach_behavior: DetachBehavior,
    1266            0 : ) -> Result<(), Error> {
    1267            0 :     match detach_behavior {
    1268              :         DetachBehavior::NoAncestorAndReparent => {
    1269            0 :             let timelines = tenant.timelines.lock().unwrap();
    1270            0 :             let timelines_offloaded = tenant.timelines_offloaded.lock().unwrap();
    1271              : 
    1272            0 :             for timeline in
    1273            0 :                 reparentable_timelines(timelines.values(), detached, ancestor, ancestor_lsn)
    1274              :             {
    1275            0 :                 if timeline.is_archived() == Some(true) {
    1276            0 :                     return Err(Error::Archived(timeline.timeline_id));
    1277            0 :                 }
    1278              :             }
    1279              : 
    1280            0 :             for timeline_offloaded in timelines_offloaded.values() {
    1281            0 :                 if timeline_offloaded.ancestor_timeline_id != Some(ancestor.timeline_id) {
    1282            0 :                     continue;
    1283            0 :                 }
    1284              :                 // This forbids the detach ancestor feature if flattened timelines are present,
    1285              :                 // even if the ancestor_lsn is from after the branchpoint of the detached timeline.
    1286              :                 // But as per current design, we don't record the ancestor_lsn of flattened timelines.
    1287              :                 // This is a bit unfortunate, but as of writing this we don't support flattening
    1288              :                 // anyway. Maybe we can evolve the data model in the future.
    1289            0 :                 if let Some(retain_lsn) = timeline_offloaded.ancestor_retain_lsn {
    1290            0 :                     let is_earlier = retain_lsn <= ancestor_lsn;
    1291            0 :                     if !is_earlier {
    1292            0 :                         continue;
    1293            0 :                     }
    1294            0 :                 }
    1295            0 :                 return Err(Error::Archived(timeline_offloaded.timeline_id));
    1296              :             }
    1297              :         }
    1298            0 :         DetachBehavior::MultiLevelAndNoReparent => {
    1299            0 :             // We don't need to check anything if the user requested to not reparent.
    1300            0 :         }
    1301              :     }
    1302              : 
    1303            0 :     Ok(())
    1304            0 : }
    1305              : 
    1306            0 : async fn fsync_timeline_dir(timeline: &Timeline, ctx: &RequestContext) {
    1307            0 :     let path = &timeline
    1308            0 :         .conf
    1309            0 :         .timeline_path(&timeline.tenant_shard_id, &timeline.timeline_id);
    1310            0 :     let timeline_dir = VirtualFile::open(&path, ctx)
    1311            0 :         .await
    1312            0 :         .fatal_err("VirtualFile::open for timeline dir fsync");
    1313            0 :     timeline_dir
    1314            0 :         .sync_all()
    1315            0 :         .await
    1316            0 :         .fatal_err("VirtualFile::sync_all timeline dir");
    1317            0 : }
        

Generated by: LCOV version 2.1-beta