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

Generated by: LCOV version 2.1-beta