LCOV - code coverage report
Current view: top level - pageserver/src/tenant/storage_layer - layer.rs (source / functions) Coverage Total Hit
Test: 12c2fc96834f59604b8ade5b9add28f1dce41ec6.info Lines: 79.5 % 1290 1025
Test Date: 2024-07-03 15:33:13 Functions: 77.2 % 158 122

            Line data    Source code
       1              : use anyhow::Context;
       2              : use camino::{Utf8Path, Utf8PathBuf};
       3              : use pageserver_api::keyspace::KeySpace;
       4              : use pageserver_api::models::{
       5              :     HistoricLayerInfo, LayerAccessKind, LayerResidenceEventReason, LayerResidenceStatus,
       6              : };
       7              : use pageserver_api::shard::{ShardIdentity, ShardIndex, TenantShardId};
       8              : use std::ops::Range;
       9              : use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
      10              : use std::sync::{Arc, Weak};
      11              : use std::time::{Duration, SystemTime};
      12              : use tracing::Instrument;
      13              : use utils::id::TimelineId;
      14              : use utils::lsn::Lsn;
      15              : use utils::sync::{gate, heavier_once_cell};
      16              : 
      17              : use crate::config::PageServerConf;
      18              : use crate::context::{DownloadBehavior, RequestContext};
      19              : use crate::repository::Key;
      20              : use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
      21              : use crate::task_mgr::TaskKind;
      22              : use crate::tenant::timeline::GetVectoredError;
      23              : use crate::tenant::{remote_timeline_client::LayerFileMetadata, Timeline};
      24              : 
      25              : use super::delta_layer::{self, DeltaEntry};
      26              : use super::image_layer::{self};
      27              : use super::{
      28              :     AsLayerDesc, ImageLayerWriter, LayerAccessStats, LayerAccessStatsReset, LayerName,
      29              :     PersistentLayerDesc, ValueReconstructResult, ValueReconstructState, ValuesReconstructState,
      30              : };
      31              : 
      32              : use utils::generation::Generation;
      33              : 
      34              : #[cfg(test)]
      35              : mod tests;
      36              : 
      37              : #[cfg(test)]
      38              : mod failpoints;
      39              : 
      40              : /// A Layer contains all data in a "rectangle" consisting of a range of keys and
      41              : /// range of LSNs.
      42              : ///
      43              : /// There are two kinds of layers, in-memory and on-disk layers. In-memory
      44              : /// layers are used to ingest incoming WAL, and provide fast access to the
      45              : /// recent page versions. On-disk layers are stored as files on disk, and are
      46              : /// immutable. This type represents the on-disk kind while in-memory kind are represented by
      47              : /// [`InMemoryLayer`].
      48              : ///
      49              : /// Furthermore, there are two kinds of on-disk layers: delta and image layers.
      50              : /// A delta layer contains all modifications within a range of LSNs and keys.
      51              : /// An image layer is a snapshot of all the data in a key-range, at a single
      52              : /// LSN.
      53              : ///
      54              : /// This type models the on-disk layers, which can be evicted and on-demand downloaded. As a
      55              : /// general goal, read accesses should always win eviction and eviction should not wait for
      56              : /// download.
      57              : ///
      58              : /// ### State transitions
      59              : ///
      60              : /// The internal state of `Layer` is composed of most importantly the on-filesystem state and the
      61              : /// [`ResidentOrWantedEvicted`] enum. On-filesystem state can be either present (fully downloaded,
      62              : /// right size) or deleted.
      63              : ///
      64              : /// Reads will always win requests to evict until `wait_for_turn_and_evict` has acquired the
      65              : /// `heavier_once_cell::InitPermit` and has started to `evict_blocking`. Before the
      66              : /// `heavier_once_cell::InitPermit` has been acquired, any read request
      67              : /// (`get_or_maybe_download`) can "re-initialize" using the existing downloaded file and thus
      68              : /// cancelling the eviction.
      69              : ///
      70              : /// ```text
      71              : ///  +-----------------+   get_or_maybe_download    +--------------------------------+
      72              : ///  | not initialized |--------------------------->| Resident(Arc<DownloadedLayer>) |
      73              : ///  |     ENOENT      |                         /->|                                |
      74              : ///  +-----------------+                         |  +--------------------------------+
      75              : ///                  ^                           |                         |       ^
      76              : ///                  |    get_or_maybe_download  |                         |       | get_or_maybe_download, either:
      77              : ///   evict_blocking | /-------------------------/                         |       | - upgrade weak to strong
      78              : ///                  | |                                                   |       | - re-initialize without download
      79              : ///                  | |                                    evict_and_wait |       |
      80              : ///  +-----------------+                                                   v       |
      81              : ///  | not initialized |  on_downloaded_layer_drop  +--------------------------------------+
      82              : ///  | file is present |<---------------------------| WantedEvicted(Weak<DownloadedLayer>) |
      83              : ///  +-----------------+                            +--------------------------------------+
      84              : /// ```
      85              : ///
      86              : /// ### Unsupported
      87              : ///
      88              : /// - Evicting by the operator deleting files from the filesystem
      89              : ///
      90              : /// [`InMemoryLayer`]: super::inmemory_layer::InMemoryLayer
      91              : #[derive(Clone)]
      92              : pub(crate) struct Layer(Arc<LayerInner>);
      93              : 
      94              : impl std::fmt::Display for Layer {
      95         1880 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      96         1880 :         write!(
      97         1880 :             f,
      98         1880 :             "{}{}",
      99         1880 :             self.layer_desc().short_id(),
     100         1880 :             self.0.generation.get_suffix()
     101         1880 :         )
     102         1880 :     }
     103              : }
     104              : 
     105              : impl std::fmt::Debug for Layer {
     106            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     107            0 :         write!(f, "{}", self)
     108            0 :     }
     109              : }
     110              : 
     111              : impl AsLayerDesc for Layer {
     112       718465 :     fn layer_desc(&self) -> &PersistentLayerDesc {
     113       718465 :         self.0.layer_desc()
     114       718465 :     }
     115              : }
     116              : 
     117              : impl PartialEq for Layer {
     118            4 :     fn eq(&self, other: &Self) -> bool {
     119            4 :         Arc::as_ptr(&self.0) == Arc::as_ptr(&other.0)
     120            4 :     }
     121              : }
     122              : 
     123         1574 : pub(crate) fn local_layer_path(
     124         1574 :     conf: &PageServerConf,
     125         1574 :     tenant_shard_id: &TenantShardId,
     126         1574 :     timeline_id: &TimelineId,
     127         1574 :     layer_file_name: &LayerName,
     128         1574 :     generation: &Generation,
     129         1574 : ) -> Utf8PathBuf {
     130         1574 :     let timeline_path = conf.timeline_path(tenant_shard_id, timeline_id);
     131         1574 : 
     132         1574 :     if generation.is_none() {
     133              :         // Without a generation, we may only use legacy path style
     134            0 :         timeline_path.join(layer_file_name.to_string())
     135              :     } else {
     136         1574 :         timeline_path.join(format!("{}-v1{}", layer_file_name, generation.get_suffix()))
     137              :     }
     138         1574 : }
     139              : 
     140              : impl Layer {
     141              :     /// Creates a layer value for a file we know to not be resident.
     142            0 :     pub(crate) fn for_evicted(
     143            0 :         conf: &'static PageServerConf,
     144            0 :         timeline: &Arc<Timeline>,
     145            0 :         file_name: LayerName,
     146            0 :         metadata: LayerFileMetadata,
     147            0 :     ) -> Self {
     148            0 :         let local_path = local_layer_path(
     149            0 :             conf,
     150            0 :             &timeline.tenant_shard_id,
     151            0 :             &timeline.timeline_id,
     152            0 :             &file_name,
     153            0 :             &metadata.generation,
     154            0 :         );
     155            0 : 
     156            0 :         let desc = PersistentLayerDesc::from_filename(
     157            0 :             timeline.tenant_shard_id,
     158            0 :             timeline.timeline_id,
     159            0 :             file_name,
     160            0 :             metadata.file_size,
     161            0 :         );
     162            0 : 
     163            0 :         let access_stats = LayerAccessStats::for_loading_layer(LayerResidenceStatus::Evicted);
     164            0 : 
     165            0 :         let owner = Layer(Arc::new(LayerInner::new(
     166            0 :             conf,
     167            0 :             timeline,
     168            0 :             local_path,
     169            0 :             access_stats,
     170            0 :             desc,
     171            0 :             None,
     172            0 :             metadata.generation,
     173            0 :             metadata.shard,
     174            0 :         )));
     175            0 : 
     176            0 :         debug_assert!(owner.0.needs_download_blocking().unwrap().is_some());
     177              : 
     178            0 :         owner
     179            0 :     }
     180              : 
     181              :     /// Creates a Layer value for a file we know to be resident in timeline directory.
     182           24 :     pub(crate) fn for_resident(
     183           24 :         conf: &'static PageServerConf,
     184           24 :         timeline: &Arc<Timeline>,
     185           24 :         local_path: Utf8PathBuf,
     186           24 :         file_name: LayerName,
     187           24 :         metadata: LayerFileMetadata,
     188           24 :     ) -> ResidentLayer {
     189           24 :         let desc = PersistentLayerDesc::from_filename(
     190           24 :             timeline.tenant_shard_id,
     191           24 :             timeline.timeline_id,
     192           24 :             file_name,
     193           24 :             metadata.file_size,
     194           24 :         );
     195           24 : 
     196           24 :         let access_stats = LayerAccessStats::for_loading_layer(LayerResidenceStatus::Resident);
     197           24 : 
     198           24 :         let mut resident = None;
     199           24 : 
     200           24 :         let owner = Layer(Arc::new_cyclic(|owner| {
     201           24 :             let inner = Arc::new(DownloadedLayer {
     202           24 :                 owner: owner.clone(),
     203           24 :                 kind: tokio::sync::OnceCell::default(),
     204           24 :                 version: 0,
     205           24 :             });
     206           24 :             resident = Some(inner.clone());
     207           24 : 
     208           24 :             LayerInner::new(
     209           24 :                 conf,
     210           24 :                 timeline,
     211           24 :                 local_path,
     212           24 :                 access_stats,
     213           24 :                 desc,
     214           24 :                 Some(inner),
     215           24 :                 metadata.generation,
     216           24 :                 metadata.shard,
     217           24 :             )
     218           24 :         }));
     219           24 : 
     220           24 :         let downloaded = resident.expect("just initialized");
     221           24 : 
     222           24 :         debug_assert!(owner.0.needs_download_blocking().unwrap().is_none());
     223              : 
     224           24 :         timeline
     225           24 :             .metrics
     226           24 :             .resident_physical_size_add(metadata.file_size);
     227           24 : 
     228           24 :         ResidentLayer { downloaded, owner }
     229           24 :     }
     230              : 
     231              :     /// Creates a Layer value for freshly written out new layer file by renaming it from a
     232              :     /// temporary path.
     233         1566 :     pub(crate) fn finish_creating(
     234         1566 :         conf: &'static PageServerConf,
     235         1566 :         timeline: &Arc<Timeline>,
     236         1566 :         desc: PersistentLayerDesc,
     237         1566 :         temp_path: &Utf8Path,
     238         1566 :     ) -> anyhow::Result<ResidentLayer> {
     239         1566 :         let mut resident = None;
     240         1566 : 
     241         1566 :         let owner = Layer(Arc::new_cyclic(|owner| {
     242         1566 :             let inner = Arc::new(DownloadedLayer {
     243         1566 :                 owner: owner.clone(),
     244         1566 :                 kind: tokio::sync::OnceCell::default(),
     245         1566 :                 version: 0,
     246         1566 :             });
     247         1566 :             resident = Some(inner.clone());
     248         1566 :             let access_stats = LayerAccessStats::empty_will_record_residence_event_later();
     249         1566 :             access_stats.record_residence_event(
     250         1566 :                 LayerResidenceStatus::Resident,
     251         1566 :                 LayerResidenceEventReason::LayerCreate,
     252         1566 :             );
     253         1566 : 
     254         1566 :             let local_path = local_layer_path(
     255         1566 :                 conf,
     256         1566 :                 &timeline.tenant_shard_id,
     257         1566 :                 &timeline.timeline_id,
     258         1566 :                 &desc.layer_name(),
     259         1566 :                 &timeline.generation,
     260         1566 :             );
     261         1566 : 
     262         1566 :             LayerInner::new(
     263         1566 :                 conf,
     264         1566 :                 timeline,
     265         1566 :                 local_path,
     266         1566 :                 access_stats,
     267         1566 :                 desc,
     268         1566 :                 Some(inner),
     269         1566 :                 timeline.generation,
     270         1566 :                 timeline.get_shard_index(),
     271         1566 :             )
     272         1566 :         }));
     273         1566 : 
     274         1566 :         let downloaded = resident.expect("just initialized");
     275         1566 : 
     276         1566 :         // We never want to overwrite an existing file, so we use `RENAME_NOREPLACE`.
     277         1566 :         // TODO: this leaves the temp file in place if the rename fails, risking us running
     278         1566 :         // out of space. Should we clean it up here or does the calling context deal with this?
     279         1566 :         utils::fs_ext::rename_noreplace(temp_path.as_std_path(), owner.local_path().as_std_path())
     280         1566 :             .with_context(|| format!("rename temporary file as correct path for {owner}"))?;
     281              : 
     282         1566 :         Ok(ResidentLayer { downloaded, owner })
     283         1566 :     }
     284              : 
     285              :     /// Requests the layer to be evicted and waits for this to be done.
     286              :     ///
     287              :     /// If the file is not resident, an [`EvictionError::NotFound`] is returned.
     288              :     ///
     289              :     /// If for a bad luck or blocking of the executor, we miss the actual eviction and the layer is
     290              :     /// re-downloaded, [`EvictionError::Downloaded`] is returned.
     291              :     ///
     292              :     /// Timeout is mandatory, because waiting for eviction is only needed for our tests; eviction
     293              :     /// will happen regardless the future returned by this method completing unless there is a
     294              :     /// read access before eviction gets to complete.
     295              :     ///
     296              :     /// Technically cancellation safe, but cancelling might shift the viewpoint of what generation
     297              :     /// of download-evict cycle on retry.
     298           36 :     pub(crate) async fn evict_and_wait(&self, timeout: Duration) -> Result<(), EvictionError> {
     299           49 :         self.0.evict_and_wait(timeout).await
     300           32 :     }
     301              : 
     302              :     /// Delete the layer file when the `self` gets dropped, also try to schedule a remote index upload
     303              :     /// then.
     304              :     ///
     305              :     /// On drop, this will cause a call to [`crate::tenant::remote_timeline_client::RemoteTimelineClient::schedule_deletion_of_unlinked`].
     306              :     /// This means that the unlinking by [gc] or [compaction] must have happened strictly before
     307              :     /// the value this is called on gets dropped.
     308              :     ///
     309              :     /// This is ensured by both of those methods accepting references to Layer.
     310              :     ///
     311              :     /// [gc]: [`RemoteTimelineClient::schedule_gc_update`]
     312              :     /// [compaction]: [`RemoteTimelineClient::schedule_compaction_update`]
     313          438 :     pub(crate) fn delete_on_drop(&self) {
     314          438 :         self.0.delete_on_drop();
     315          438 :     }
     316              : 
     317              :     /// Return data needed to reconstruct given page at LSN.
     318              :     ///
     319              :     /// It is up to the caller to collect more data from the previous layer and
     320              :     /// perform WAL redo, if necessary.
     321              :     ///
     322              :     /// # Cancellation-Safety
     323              :     ///
     324              :     /// This method is cancellation-safe.
     325       211274 :     pub(crate) async fn get_value_reconstruct_data(
     326       211274 :         &self,
     327       211274 :         key: Key,
     328       211274 :         lsn_range: Range<Lsn>,
     329       211274 :         reconstruct_data: &mut ValueReconstructState,
     330       211274 :         ctx: &RequestContext,
     331       211274 :     ) -> anyhow::Result<ValueReconstructResult> {
     332              :         use anyhow::ensure;
     333              : 
     334       211274 :         let layer = self.0.get_or_maybe_download(true, Some(ctx)).await?;
     335       211274 :         self.0
     336       211274 :             .access_stats
     337       211274 :             .record_access(LayerAccessKind::GetValueReconstructData, ctx);
     338       211274 : 
     339       211274 :         if self.layer_desc().is_delta {
     340       204163 :             ensure!(lsn_range.start >= self.layer_desc().lsn_range.start);
     341       204163 :             ensure!(self.layer_desc().key_range.contains(&key));
     342              :         } else {
     343         7111 :             ensure!(self.layer_desc().key_range.contains(&key));
     344         7111 :             ensure!(lsn_range.start >= self.layer_desc().image_layer_lsn());
     345         7111 :             ensure!(lsn_range.end >= self.layer_desc().image_layer_lsn());
     346              :         }
     347              : 
     348       211274 :         layer
     349       211274 :             .get_value_reconstruct_data(key, lsn_range, reconstruct_data, &self.0, ctx)
     350       211274 :             .instrument(tracing::debug_span!("get_value_reconstruct_data", layer=%self))
     351        30071 :             .await
     352       211274 :             .with_context(|| format!("get_value_reconstruct_data for layer {self}"))
     353       211274 :     }
     354              : 
     355          228 :     pub(crate) async fn get_values_reconstruct_data(
     356          228 :         &self,
     357          228 :         keyspace: KeySpace,
     358          228 :         lsn_range: Range<Lsn>,
     359          228 :         reconstruct_data: &mut ValuesReconstructState,
     360          228 :         ctx: &RequestContext,
     361          228 :     ) -> Result<(), GetVectoredError> {
     362          228 :         let layer = self
     363          228 :             .0
     364          228 :             .get_or_maybe_download(true, Some(ctx))
     365            0 :             .await
     366          228 :             .map_err(|err| match err {
     367            0 :                 DownloadError::DownloadCancelled => GetVectoredError::Cancelled,
     368            0 :                 other => GetVectoredError::Other(anyhow::anyhow!(other)),
     369          228 :             })?;
     370              : 
     371          228 :         self.0
     372          228 :             .access_stats
     373          228 :             .record_access(LayerAccessKind::GetValueReconstructData, ctx);
     374          228 : 
     375          228 :         layer
     376          228 :             .get_values_reconstruct_data(keyspace, lsn_range, reconstruct_data, &self.0, ctx)
     377          228 :             .instrument(tracing::debug_span!("get_values_reconstruct_data", layer=%self))
     378        11516 :             .await
     379          228 :             .map_err(|err| match err {
     380            0 :                 GetVectoredError::Other(err) => GetVectoredError::Other(
     381            0 :                     err.context(format!("get_values_reconstruct_data for layer {self}")),
     382            0 :                 ),
     383            0 :                 err => err,
     384          228 :             })
     385          228 :     }
     386              : 
     387              :     /// Get all key/values in the layer. Should be replaced with an iterator-based API in the future.
     388           16 :     pub(crate) async fn load_key_values(
     389           16 :         &self,
     390           16 :         ctx: &RequestContext,
     391           16 :     ) -> anyhow::Result<Vec<(Key, Lsn, crate::repository::Value)>> {
     392           16 :         let layer = self
     393           16 :             .0
     394           16 :             .get_or_maybe_download(true, Some(ctx))
     395            0 :             .await
     396           16 :             .map_err(|err| match err {
     397            0 :                 DownloadError::DownloadCancelled => GetVectoredError::Cancelled,
     398            0 :                 other => GetVectoredError::Other(anyhow::anyhow!(other)),
     399           16 :             })?;
     400           16 :         layer.load_key_values(&self.0, ctx).await
     401           16 :     }
     402              : 
     403              :     /// Download the layer if evicted.
     404              :     ///
     405              :     /// Will not error when the layer is already downloaded.
     406            0 :     pub(crate) async fn download(&self) -> anyhow::Result<()> {
     407            0 :         self.0.get_or_maybe_download(true, None).await?;
     408            0 :         Ok(())
     409            0 :     }
     410              : 
     411              :     /// Assuming the layer is already downloaded, returns a guard which will prohibit eviction
     412              :     /// while the guard exists.
     413              :     ///
     414              :     /// Returns None if the layer is currently evicted or becoming evicted.
     415              :     #[cfg(test)]
     416           20 :     pub(crate) async fn keep_resident(&self) -> Option<ResidentLayer> {
     417           20 :         let downloaded = self.0.inner.get().and_then(|rowe| rowe.get())?;
     418              : 
     419           14 :         Some(ResidentLayer {
     420           14 :             downloaded,
     421           14 :             owner: self.clone(),
     422           14 :         })
     423           20 :     }
     424              : 
     425              :     /// Weak indicator of is the layer resident or not. Good enough for eviction, which can deal
     426              :     /// with `EvictionError::NotFound`.
     427              :     ///
     428              :     /// Returns `true` if this layer might be resident, or `false`, if it most likely evicted or
     429              :     /// will be unless a read happens soon.
     430           44 :     pub(crate) fn is_likely_resident(&self) -> bool {
     431           44 :         self.0
     432           44 :             .inner
     433           44 :             .get()
     434           44 :             .map(|rowe| rowe.is_likely_resident())
     435           44 :             .unwrap_or(false)
     436           44 :     }
     437              : 
     438              :     /// Downloads if necessary and creates a guard, which will keep this layer from being evicted.
     439          414 :     pub(crate) async fn download_and_keep_resident(&self) -> anyhow::Result<ResidentLayer> {
     440          414 :         let downloaded = self.0.get_or_maybe_download(true, None).await?;
     441              : 
     442          414 :         Ok(ResidentLayer {
     443          414 :             downloaded,
     444          414 :             owner: self.clone(),
     445          414 :         })
     446          414 :     }
     447              : 
     448            0 :     pub(crate) fn info(&self, reset: LayerAccessStatsReset) -> HistoricLayerInfo {
     449            0 :         self.0.info(reset)
     450            0 :     }
     451              : 
     452            0 :     pub(crate) fn access_stats(&self) -> &LayerAccessStats {
     453            0 :         &self.0.access_stats
     454            0 :     }
     455              : 
     456         1568 :     pub(crate) fn local_path(&self) -> &Utf8Path {
     457         1568 :         &self.0.path
     458         1568 :     }
     459              : 
     460       211270 :     pub(crate) fn debug_str(&self) -> &Arc<str> {
     461       211270 :         &self.0.debug_str
     462       211270 :     }
     463              : 
     464         1498 :     pub(crate) fn metadata(&self) -> LayerFileMetadata {
     465         1498 :         self.0.metadata()
     466         1498 :     }
     467              : 
     468            0 :     pub(crate) fn get_timeline_id(&self) -> Option<TimelineId> {
     469            0 :         self.0
     470            0 :             .timeline
     471            0 :             .upgrade()
     472            0 :             .map(|timeline| timeline.timeline_id)
     473            0 :     }
     474              : 
     475              :     /// Traditional debug dumping facility
     476              :     #[allow(unused)]
     477            4 :     pub(crate) async fn dump(&self, verbose: bool, ctx: &RequestContext) -> anyhow::Result<()> {
     478            4 :         self.0.desc.dump();
     479            4 : 
     480            4 :         if verbose {
     481              :             // for now, unconditionally download everything, even if that might not be wanted.
     482            4 :             let l = self.0.get_or_maybe_download(true, Some(ctx)).await?;
     483            8 :             l.dump(&self.0, ctx).await?
     484            0 :         }
     485              : 
     486            4 :         Ok(())
     487            4 :     }
     488              : 
     489              :     /// Waits until this layer has been dropped (and if needed, local file deletion and remote
     490              :     /// deletion scheduling has completed).
     491              :     ///
     492              :     /// Does not start local deletion, use [`Self::delete_on_drop`] for that
     493              :     /// separatedly.
     494              :     #[cfg(any(feature = "testing", test))]
     495            2 :     pub(crate) fn wait_drop(&self) -> impl std::future::Future<Output = ()> + 'static {
     496            2 :         let mut rx = self.0.status.as_ref().unwrap().subscribe();
     497              : 
     498            2 :         async move {
     499              :             loop {
     500            6 :                 if rx.changed().await.is_err() {
     501            2 :                     break;
     502            0 :                 }
     503              :             }
     504            2 :         }
     505            2 :     }
     506              : }
     507              : 
     508              : /// The download-ness ([`DownloadedLayer`]) can be either resident or wanted evicted.
     509              : ///
     510              : /// However when we want something evicted, we cannot evict it right away as there might be current
     511              : /// reads happening on it. For example: it has been searched from [`LayerMap::search`] but not yet
     512              : /// read with [`Layer::get_value_reconstruct_data`].
     513              : ///
     514              : /// [`LayerMap::search`]: crate::tenant::layer_map::LayerMap::search
     515              : #[derive(Debug)]
     516              : enum ResidentOrWantedEvicted {
     517              :     Resident(Arc<DownloadedLayer>),
     518              :     WantedEvicted(Weak<DownloadedLayer>, usize),
     519              : }
     520              : 
     521              : impl ResidentOrWantedEvicted {
     522              :     /// Non-mutating access to the a DownloadedLayer, if possible.
     523              :     ///
     524              :     /// This is not used on the read path (anything that calls
     525              :     /// [`LayerInner::get_or_maybe_download`]) because it was decided that reads always win
     526              :     /// evictions, and part of that winning is using [`ResidentOrWantedEvicted::get_and_upgrade`].
     527              :     #[cfg(test)]
     528           14 :     fn get(&self) -> Option<Arc<DownloadedLayer>> {
     529           14 :         match self {
     530           14 :             ResidentOrWantedEvicted::Resident(strong) => Some(strong.clone()),
     531            0 :             ResidentOrWantedEvicted::WantedEvicted(weak, _) => weak.upgrade(),
     532              :         }
     533           14 :     }
     534              : 
     535              :     /// Best-effort query for residency right now, not as strong guarantee as receiving a strong
     536              :     /// reference from `ResidentOrWantedEvicted::get`.
     537           38 :     fn is_likely_resident(&self) -> bool {
     538           38 :         match self {
     539           32 :             ResidentOrWantedEvicted::Resident(_) => true,
     540            6 :             ResidentOrWantedEvicted::WantedEvicted(weak, _) => weak.strong_count() > 0,
     541              :         }
     542           38 :     }
     543              : 
     544              :     /// Upgrades any weak to strong if possible.
     545              :     ///
     546              :     /// Returns a strong reference if possible, along with a boolean telling if an upgrade
     547              :     /// happened.
     548       211940 :     fn get_and_upgrade(&mut self) -> Option<(Arc<DownloadedLayer>, bool)> {
     549       211940 :         match self {
     550       211932 :             ResidentOrWantedEvicted::Resident(strong) => Some((strong.clone(), false)),
     551            8 :             ResidentOrWantedEvicted::WantedEvicted(weak, _) => match weak.upgrade() {
     552            0 :                 Some(strong) => {
     553            0 :                     LAYER_IMPL_METRICS.inc_raced_wanted_evicted_accesses();
     554            0 : 
     555            0 :                     *self = ResidentOrWantedEvicted::Resident(strong.clone());
     556            0 : 
     557            0 :                     Some((strong, true))
     558              :                 }
     559            8 :                 None => None,
     560              :             },
     561              :         }
     562       211940 :     }
     563              : 
     564              :     /// When eviction is first requested, drop down to holding a [`Weak`].
     565              :     ///
     566              :     /// Returns `Some` if this was the first time eviction was requested. Care should be taken to
     567              :     /// drop the possibly last strong reference outside of the mutex of
     568              :     /// [`heavier_once_cell::OnceCell`].
     569           30 :     fn downgrade(&mut self) -> Option<Arc<DownloadedLayer>> {
     570           30 :         match self {
     571           26 :             ResidentOrWantedEvicted::Resident(strong) => {
     572           26 :                 let weak = Arc::downgrade(strong);
     573           26 :                 let mut temp = ResidentOrWantedEvicted::WantedEvicted(weak, strong.version);
     574           26 :                 std::mem::swap(self, &mut temp);
     575           26 :                 match temp {
     576           26 :                     ResidentOrWantedEvicted::Resident(strong) => Some(strong),
     577            0 :                     ResidentOrWantedEvicted::WantedEvicted(..) => unreachable!("just swapped"),
     578              :                 }
     579              :             }
     580            4 :             ResidentOrWantedEvicted::WantedEvicted(..) => None,
     581              :         }
     582           30 :     }
     583              : }
     584              : 
     585              : struct LayerInner {
     586              :     /// Only needed to check ondemand_download_behavior_treat_error_as_warn and creation of
     587              :     /// [`Self::path`].
     588              :     conf: &'static PageServerConf,
     589              : 
     590              :     /// Full path to the file; unclear if this should exist anymore.
     591              :     path: Utf8PathBuf,
     592              : 
     593              :     /// String representation of the layer, used for traversal id.
     594              :     debug_str: Arc<str>,
     595              : 
     596              :     desc: PersistentLayerDesc,
     597              : 
     598              :     /// Timeline access is needed for remote timeline client and metrics.
     599              :     ///
     600              :     /// There should not be an access to timeline for any reason without entering the
     601              :     /// [`Timeline::gate`] at the same time.
     602              :     timeline: Weak<Timeline>,
     603              : 
     604              :     access_stats: LayerAccessStats,
     605              : 
     606              :     /// This custom OnceCell is backed by std mutex, but only held for short time periods.
     607              :     ///
     608              :     /// Filesystem changes (download, evict) are only done while holding a permit which the
     609              :     /// `heavier_once_cell` provides.
     610              :     ///
     611              :     /// A number of fields in `Layer` are meant to only be updated when holding the InitPermit, but
     612              :     /// possibly read while not holding it.
     613              :     inner: heavier_once_cell::OnceCell<ResidentOrWantedEvicted>,
     614              : 
     615              :     /// Do we want to delete locally and remotely this when `LayerInner` is dropped
     616              :     wanted_deleted: AtomicBool,
     617              : 
     618              :     /// Version is to make sure we will only evict a specific initialization of the downloaded file.
     619              :     ///
     620              :     /// Incremented for each initialization, stored in `DownloadedLayer::version` or
     621              :     /// `ResidentOrWantedEvicted::WantedEvicted`.
     622              :     version: AtomicUsize,
     623              : 
     624              :     /// Allow subscribing to when the layer actually gets evicted, a non-cancellable download
     625              :     /// starts, or completes.
     626              :     ///
     627              :     /// Updates must only be posted while holding the InitPermit or the heavier_once_cell::Guard.
     628              :     /// Holding the InitPermit is the only time we can do state transitions, but we also need to
     629              :     /// cancel a pending eviction on upgrading a [`ResidentOrWantedEvicted::WantedEvicted`] back to
     630              :     /// [`ResidentOrWantedEvicted::Resident`] on access.
     631              :     ///
     632              :     /// The sender is wrapped in an Option to facilitate moving it out on [`LayerInner::drop`].
     633              :     status: Option<tokio::sync::watch::Sender<Status>>,
     634              : 
     635              :     /// Counter for exponential backoff with the download.
     636              :     ///
     637              :     /// This is atomic only for the purposes of having additional data only accessed while holding
     638              :     /// the InitPermit.
     639              :     consecutive_failures: AtomicUsize,
     640              : 
     641              :     /// The generation of this Layer.
     642              :     ///
     643              :     /// For loaded layers (resident or evicted) this comes from [`LayerFileMetadata::generation`],
     644              :     /// for created layers from [`Timeline::generation`].
     645              :     generation: Generation,
     646              : 
     647              :     /// The shard of this Layer.
     648              :     ///
     649              :     /// For layers created in this process, this will always be the [`ShardIndex`] of the
     650              :     /// current `ShardIdentity`` (TODO: add link once it's introduced).
     651              :     ///
     652              :     /// For loaded layers, this may be some other value if the tenant has undergone
     653              :     /// a shard split since the layer was originally written.
     654              :     shard: ShardIndex,
     655              : 
     656              :     /// When the Layer was last evicted but has not been downloaded since.
     657              :     ///
     658              :     /// This is used solely for updating metrics. See [`LayerImplMetrics::redownload_after`].
     659              :     last_evicted_at: std::sync::Mutex<Option<std::time::Instant>>,
     660              : 
     661              :     #[cfg(test)]
     662              :     failpoints: std::sync::Mutex<Vec<failpoints::Failpoint>>,
     663              : }
     664              : 
     665              : impl std::fmt::Display for LayerInner {
     666           30 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     667           30 :         write!(f, "{}", self.layer_desc().short_id())
     668           30 :     }
     669              : }
     670              : 
     671              : impl AsLayerDesc for LayerInner {
     672       720660 :     fn layer_desc(&self) -> &PersistentLayerDesc {
     673       720660 :         &self.desc
     674       720660 :     }
     675              : }
     676              : 
     677              : #[derive(Debug, Clone, Copy)]
     678              : enum Status {
     679              :     Resident,
     680              :     Evicted,
     681              :     Downloading,
     682              : }
     683              : 
     684              : impl Drop for LayerInner {
     685          481 :     fn drop(&mut self) {
     686              :         // if there was a pending eviction, mark it cancelled here to balance metrics
     687          481 :         if let Some((ResidentOrWantedEvicted::WantedEvicted(..), _)) = self.inner.take_and_deinit()
     688            2 :         {
     689            2 :             // eviction has already been started
     690            2 :             LAYER_IMPL_METRICS.inc_eviction_cancelled(EvictionCancelled::LayerGone);
     691            2 : 
     692            2 :             // eviction request is intentionally not honored as no one is present to wait for it
     693            2 :             // and we could be delaying shutdown for nothing.
     694          479 :         }
     695              : 
     696          481 :         if !*self.wanted_deleted.get_mut() {
     697           48 :             return;
     698          433 :         }
     699              : 
     700          433 :         let span = tracing::info_span!(parent: None, "layer_delete", tenant_id = %self.layer_desc().tenant_shard_id.tenant_id, shard_id=%self.layer_desc().tenant_shard_id.shard_slug(), timeline_id = %self.layer_desc().timeline_id);
     701              : 
     702          433 :         let path = std::mem::take(&mut self.path);
     703          433 :         let file_name = self.layer_desc().layer_name();
     704          433 :         let file_size = self.layer_desc().file_size;
     705          433 :         let timeline = self.timeline.clone();
     706          433 :         let meta = self.metadata();
     707          433 :         let status = self.status.take();
     708          433 : 
     709          433 :         Self::spawn_blocking(move || {
     710          432 :             let _g = span.entered();
     711          432 : 
     712          432 :             // carry this until we are finished for [`Layer::wait_drop`] support
     713          432 :             let _status = status;
     714              : 
     715          432 :             let Some(timeline) = timeline.upgrade() else {
     716              :                 // no need to nag that timeline is gone: under normal situation on
     717              :                 // task_mgr::remove_tenant_from_memory the timeline is gone before we get dropped.
     718            0 :                 LAYER_IMPL_METRICS.inc_deletes_failed(DeleteFailed::TimelineGone);
     719            0 :                 return;
     720              :             };
     721              : 
     722          432 :             let Ok(_guard) = timeline.gate.enter() else {
     723            0 :                 LAYER_IMPL_METRICS.inc_deletes_failed(DeleteFailed::TimelineGone);
     724            0 :                 return;
     725              :             };
     726              : 
     727          432 :             let removed = match std::fs::remove_file(path) {
     728          430 :                 Ok(()) => true,
     729            2 :                 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
     730            2 :                     // until we no longer do detaches by removing all local files before removing the
     731            2 :                     // tenant from the global map, we will always get these errors even if we knew what
     732            2 :                     // is the latest state.
     733            2 :                     //
     734            2 :                     // we currently do not track the latest state, so we'll also end up here on evicted
     735            2 :                     // layers.
     736            2 :                     false
     737              :                 }
     738            0 :                 Err(e) => {
     739            0 :                     tracing::error!("failed to remove wanted deleted layer: {e}");
     740            0 :                     LAYER_IMPL_METRICS.inc_delete_removes_failed();
     741            0 :                     false
     742              :                 }
     743              :             };
     744              : 
     745          432 :             if removed {
     746          430 :                 timeline.metrics.resident_physical_size_sub(file_size);
     747          430 :             }
     748          432 :             let res = timeline
     749          432 :                 .remote_client
     750          432 :                 .schedule_deletion_of_unlinked(vec![(file_name, meta)]);
     751              : 
     752          432 :             if let Err(e) = res {
     753              :                 // test_timeline_deletion_with_files_stuck_in_upload_queue is good at
     754              :                 // demonstrating this deadlock (without spawn_blocking): stop will drop
     755              :                 // queued items, which will have ResidentLayer's, and those drops would try
     756              :                 // to re-entrantly lock the RemoteTimelineClient inner state.
     757            0 :                 if !timeline.is_active() {
     758            0 :                     tracing::info!("scheduling deletion on drop failed: {e:#}");
     759              :                 } else {
     760            0 :                     tracing::warn!("scheduling deletion on drop failed: {e:#}");
     761              :                 }
     762            0 :                 LAYER_IMPL_METRICS.inc_deletes_failed(DeleteFailed::DeleteSchedulingFailed);
     763          432 :             } else {
     764          432 :                 LAYER_IMPL_METRICS.inc_completed_deletes();
     765          432 :             }
     766          433 :         });
     767          481 :     }
     768              : }
     769              : 
     770              : impl LayerInner {
     771              :     #[allow(clippy::too_many_arguments)]
     772         1590 :     fn new(
     773         1590 :         conf: &'static PageServerConf,
     774         1590 :         timeline: &Arc<Timeline>,
     775         1590 :         local_path: Utf8PathBuf,
     776         1590 :         access_stats: LayerAccessStats,
     777         1590 :         desc: PersistentLayerDesc,
     778         1590 :         downloaded: Option<Arc<DownloadedLayer>>,
     779         1590 :         generation: Generation,
     780         1590 :         shard: ShardIndex,
     781         1590 :     ) -> Self {
     782         1590 :         let (inner, version, init_status) = if let Some(inner) = downloaded {
     783         1590 :             let version = inner.version;
     784         1590 :             let resident = ResidentOrWantedEvicted::Resident(inner);
     785         1590 :             (
     786         1590 :                 heavier_once_cell::OnceCell::new(resident),
     787         1590 :                 version,
     788         1590 :                 Status::Resident,
     789         1590 :             )
     790              :         } else {
     791            0 :             (heavier_once_cell::OnceCell::default(), 0, Status::Evicted)
     792              :         };
     793              : 
     794         1590 :         LayerInner {
     795         1590 :             conf,
     796         1590 :             debug_str: {
     797         1590 :                 format!("timelines/{}/{}", timeline.timeline_id, desc.layer_name()).into()
     798         1590 :             },
     799         1590 :             path: local_path,
     800         1590 :             desc,
     801         1590 :             timeline: Arc::downgrade(timeline),
     802         1590 :             access_stats,
     803         1590 :             wanted_deleted: AtomicBool::new(false),
     804         1590 :             inner,
     805         1590 :             version: AtomicUsize::new(version),
     806         1590 :             status: Some(tokio::sync::watch::channel(init_status).0),
     807         1590 :             consecutive_failures: AtomicUsize::new(0),
     808         1590 :             generation,
     809         1590 :             shard,
     810         1590 :             last_evicted_at: std::sync::Mutex::default(),
     811         1590 :             #[cfg(test)]
     812         1590 :             failpoints: Default::default(),
     813         1590 :         }
     814         1590 :     }
     815              : 
     816          438 :     fn delete_on_drop(&self) {
     817          438 :         let res =
     818          438 :             self.wanted_deleted
     819          438 :                 .compare_exchange(false, true, Ordering::Release, Ordering::Relaxed);
     820          438 : 
     821          438 :         if res.is_ok() {
     822          434 :             LAYER_IMPL_METRICS.inc_started_deletes();
     823          434 :         }
     824          438 :     }
     825              : 
     826              :     /// Cancellation safe, however dropping the future and calling this method again might result
     827              :     /// in a new attempt to evict OR join the previously started attempt.
     828          108 :     #[tracing::instrument(level = tracing::Level::DEBUG, skip_all, ret, err(level = tracing::Level::DEBUG), fields(layer=%self))]
     829              :     pub(crate) async fn evict_and_wait(&self, timeout: Duration) -> Result<(), EvictionError> {
     830              :         let mut rx = self.status.as_ref().unwrap().subscribe();
     831              : 
     832              :         {
     833              :             let current = rx.borrow_and_update();
     834              :             match &*current {
     835              :                 Status::Resident => {
     836              :                     // we might get lucky and evict this; continue
     837              :                 }
     838              :                 Status::Evicted | Status::Downloading => {
     839              :                     // it is already evicted
     840              :                     return Err(EvictionError::NotFound);
     841              :                 }
     842              :             }
     843              :         }
     844              : 
     845              :         let strong = {
     846              :             match self.inner.get() {
     847              :                 Some(mut either) => either.downgrade(),
     848              :                 None => {
     849              :                     // we already have a scheduled eviction, which just has not gotten to run yet.
     850              :                     // it might still race with a read access, but that could also get cancelled,
     851              :                     // so let's say this is not evictable.
     852              :                     return Err(EvictionError::NotFound);
     853              :                 }
     854              :             }
     855              :         };
     856              : 
     857              :         if strong.is_some() {
     858              :             // drop the DownloadedLayer outside of the holding the guard
     859              :             drop(strong);
     860              : 
     861              :             // idea here is that only one evicter should ever get to witness a strong reference,
     862              :             // which means whenever get_or_maybe_download upgrades a weak, it must mark up a
     863              :             // cancelled eviction and signal us, like it currently does.
     864              :             //
     865              :             // a second concurrent evict_and_wait will not see a strong reference.
     866              :             LAYER_IMPL_METRICS.inc_started_evictions();
     867              :         }
     868              : 
     869              :         let changed = rx.changed();
     870              :         let changed = tokio::time::timeout(timeout, changed).await;
     871              : 
     872              :         let Ok(changed) = changed else {
     873              :             return Err(EvictionError::Timeout);
     874              :         };
     875              : 
     876              :         let _: () = changed.expect("cannot be closed, because we are holding a strong reference");
     877              : 
     878              :         let current = rx.borrow_and_update();
     879              : 
     880              :         match &*current {
     881              :             // the easiest case
     882              :             Status::Evicted => Ok(()),
     883              :             // it surely was evicted in between, but then there was a new access now; we can't know
     884              :             // if it'll succeed so lets just call it evicted
     885              :             Status::Downloading => Ok(()),
     886              :             // either the download which was started after eviction completed already, or it was
     887              :             // never evicted
     888              :             Status::Resident => Err(EvictionError::Downloaded),
     889              :         }
     890              :     }
     891              : 
     892              :     /// Cancellation safe.
     893       211948 :     async fn get_or_maybe_download(
     894       211948 :         self: &Arc<Self>,
     895       211948 :         allow_download: bool,
     896       211948 :         ctx: Option<&RequestContext>,
     897       211948 :     ) -> Result<Arc<DownloadedLayer>, DownloadError> {
     898           16 :         let (weak, permit) = {
     899              :             // get_or_init_detached can:
     900              :             // - be fast (mutex lock) OR uncontested semaphore permit acquire
     901              :             // - be slow (wait for semaphore permit or closing)
     902       211948 :             let init_cancelled = scopeguard::guard((), |_| LAYER_IMPL_METRICS.inc_init_cancelled());
     903              : 
     904       211948 :             let locked = self
     905       211948 :                 .inner
     906       211948 :                 .get_or_init_detached()
     907            3 :                 .await
     908       211948 :                 .map(|mut guard| guard.get_and_upgrade().ok_or(guard));
     909       211948 : 
     910       211948 :             scopeguard::ScopeGuard::into_inner(init_cancelled);
     911              : 
     912       211932 :             match locked {
     913              :                 // this path could had been a RwLock::read
     914       211932 :                 Ok(Ok((strong, upgraded))) if !upgraded => return Ok(strong),
     915            0 :                 Ok(Ok((strong, _))) => {
     916            0 :                     // when upgraded back, the Arc<DownloadedLayer> is still available, but
     917            0 :                     // previously a `evict_and_wait` was received. this is the only place when we
     918            0 :                     // send out an update without holding the InitPermit.
     919            0 :                     //
     920            0 :                     // note that we also have dropped the Guard; this is fine, because we just made
     921            0 :                     // a state change and are holding a strong reference to be returned.
     922            0 :                     self.status.as_ref().unwrap().send_replace(Status::Resident);
     923            0 :                     LAYER_IMPL_METRICS
     924            0 :                         .inc_eviction_cancelled(EvictionCancelled::UpgradedBackOnAccess);
     925            0 : 
     926            0 :                     return Ok(strong);
     927              :                 }
     928            8 :                 Ok(Err(guard)) => {
     929            8 :                     // path to here: we won the eviction, the file should still be on the disk.
     930            8 :                     let (weak, permit) = guard.take_and_deinit();
     931            8 :                     (Some(weak), permit)
     932              :                 }
     933            8 :                 Err(permit) => (None, permit),
     934              :             }
     935              :         };
     936              : 
     937           16 :         if let Some(weak) = weak {
     938              :             // only drop the weak after dropping the heavier_once_cell guard
     939            8 :             assert!(
     940            8 :                 matches!(weak, ResidentOrWantedEvicted::WantedEvicted(..)),
     941            0 :                 "unexpected {weak:?}, ResidentOrWantedEvicted::get_and_upgrade has a bug"
     942              :             );
     943            8 :         }
     944              : 
     945           16 :         let timeline = self
     946           16 :             .timeline
     947           16 :             .upgrade()
     948           16 :             .ok_or_else(|| DownloadError::TimelineShutdown)?;
     949              : 
     950              :         // count cancellations, which currently remain largely unexpected
     951           16 :         let init_cancelled = scopeguard::guard((), |_| LAYER_IMPL_METRICS.inc_init_cancelled());
     952              : 
     953              :         // check if we really need to be downloaded: this can happen if a read access won the
     954              :         // semaphore before eviction.
     955              :         //
     956              :         // if we are cancelled while doing this `stat` the `self.inner` will be uninitialized. a
     957              :         // pending eviction will try to evict even upon finding an uninitialized `self.inner`.
     958           16 :         let needs_download = self
     959           16 :             .needs_download()
     960           15 :             .await
     961           16 :             .map_err(DownloadError::PreStatFailed);
     962           16 : 
     963           16 :         scopeguard::ScopeGuard::into_inner(init_cancelled);
     964              : 
     965           16 :         let needs_download = needs_download?;
     966              : 
     967           16 :         let Some(reason) = needs_download else {
     968              :             // the file is present locally because eviction has not had a chance to run yet
     969              : 
     970              :             #[cfg(test)]
     971            8 :             self.failpoint(failpoints::FailpointKind::AfterDeterminingLayerNeedsNoDownload)
     972            2 :                 .await?;
     973              : 
     974            6 :             LAYER_IMPL_METRICS.inc_init_needed_no_download();
     975            6 : 
     976            6 :             return Ok(self.initialize_after_layer_is_on_disk(permit));
     977              :         };
     978              : 
     979              :         // we must download; getting cancelled before spawning the download is not an issue as
     980              :         // any still running eviction would not find anything to evict.
     981              : 
     982            8 :         if let NeedsDownload::NotFile(ft) = reason {
     983            0 :             return Err(DownloadError::NotFile(ft));
     984            8 :         }
     985              : 
     986            8 :         if let Some(ctx) = ctx {
     987            2 :             self.check_expected_download(ctx)?;
     988            6 :         }
     989              : 
     990            8 :         if !allow_download {
     991              :             // this is only used from tests, but it is hard to test without the boolean
     992            2 :             return Err(DownloadError::DownloadRequired);
     993            6 :         }
     994            6 : 
     995            6 :         let download_ctx = ctx
     996            6 :             .map(|ctx| ctx.detached_child(TaskKind::LayerDownload, DownloadBehavior::Download))
     997            6 :             .unwrap_or(RequestContext::new(
     998            6 :                 TaskKind::LayerDownload,
     999            6 :                 DownloadBehavior::Download,
    1000            6 :             ));
    1001              : 
    1002            6 :         async move {
    1003            6 :             tracing::info!(%reason, "downloading on-demand");
    1004              : 
    1005            6 :             let init_cancelled = scopeguard::guard((), |_| LAYER_IMPL_METRICS.inc_init_cancelled());
    1006            6 :             let res = self
    1007            6 :                 .download_init_and_wait(timeline, permit, download_ctx)
    1008           10 :                 .await?;
    1009            6 :             scopeguard::ScopeGuard::into_inner(init_cancelled);
    1010            6 :             Ok(res)
    1011            6 :         }
    1012            6 :         .instrument(tracing::info_span!("get_or_maybe_download", layer=%self))
    1013           10 :         .await
    1014       211948 :     }
    1015              : 
    1016              :     /// Nag or fail per RequestContext policy
    1017            2 :     fn check_expected_download(&self, ctx: &RequestContext) -> Result<(), DownloadError> {
    1018            2 :         use crate::context::DownloadBehavior::*;
    1019            2 :         let b = ctx.download_behavior();
    1020            2 :         match b {
    1021            2 :             Download => Ok(()),
    1022              :             Warn | Error => {
    1023            0 :                 tracing::info!(
    1024            0 :                     "unexpectedly on-demand downloading for task kind {:?}",
    1025            0 :                     ctx.task_kind()
    1026              :                 );
    1027            0 :                 crate::metrics::UNEXPECTED_ONDEMAND_DOWNLOADS.inc();
    1028              : 
    1029            0 :                 let really_error =
    1030            0 :                     matches!(b, Error) && !self.conf.ondemand_download_behavior_treat_error_as_warn;
    1031              : 
    1032            0 :                 if really_error {
    1033              :                     // this check is only probablistic, seems like flakyness footgun
    1034            0 :                     Err(DownloadError::ContextAndConfigReallyDeniesDownloads)
    1035              :                 } else {
    1036            0 :                     Ok(())
    1037              :                 }
    1038              :             }
    1039              :         }
    1040            2 :     }
    1041              : 
    1042              :     /// Actual download, at most one is executed at the time.
    1043            6 :     async fn download_init_and_wait(
    1044            6 :         self: &Arc<Self>,
    1045            6 :         timeline: Arc<Timeline>,
    1046            6 :         permit: heavier_once_cell::InitPermit,
    1047            6 :         ctx: RequestContext,
    1048            6 :     ) -> Result<Arc<DownloadedLayer>, DownloadError> {
    1049            6 :         debug_assert_current_span_has_tenant_and_timeline_id();
    1050            6 : 
    1051            6 :         let (tx, rx) = tokio::sync::oneshot::channel();
    1052            6 : 
    1053            6 :         let this: Arc<Self> = self.clone();
    1054              : 
    1055            6 :         let guard = timeline
    1056            6 :             .gate
    1057            6 :             .enter()
    1058            6 :             .map_err(|_| DownloadError::DownloadCancelled)?;
    1059              : 
    1060            6 :         Self::spawn(
    1061            6 :             async move {
    1062            0 :                 let _guard = guard;
    1063            0 : 
    1064            0 :                 // now that we have commited to downloading, send out an update to:
    1065            0 :                 // - unhang any pending eviction
    1066            0 :                 // - break out of evict_and_wait
    1067            0 :                 this.status
    1068            0 :                     .as_ref()
    1069            0 :                     .unwrap()
    1070            0 :                     .send_replace(Status::Downloading);
    1071            6 : 
    1072            6 :                 #[cfg(test)]
    1073            6 :                 this.failpoint(failpoints::FailpointKind::WaitBeforeDownloading)
    1074            2 :                     .await
    1075            6 :                     .unwrap();
    1076              : 
    1077           98 :                 let res = this.download_and_init(timeline, permit, &ctx).await;
    1078              : 
    1079            6 :                 if let Err(res) = tx.send(res) {
    1080            0 :                     match res {
    1081            0 :                         Ok(_res) => {
    1082            0 :                             tracing::debug!("layer initialized, but caller has been cancelled");
    1083            0 :                             LAYER_IMPL_METRICS.inc_init_completed_without_requester();
    1084              :                         }
    1085            0 :                         Err(e) => {
    1086            0 :                             tracing::info!(
    1087            0 :                                 "layer file download failed, and caller has been cancelled: {e:?}"
    1088              :                             );
    1089            0 :                             LAYER_IMPL_METRICS.inc_download_failed_without_requester();
    1090              :                         }
    1091              :                     }
    1092            6 :                 }
    1093            6 :             }
    1094            6 :             .in_current_span(),
    1095            6 :         );
    1096            6 : 
    1097           10 :         match rx.await {
    1098            6 :             Ok(Ok(res)) => Ok(res),
    1099              :             Ok(Err(remote_storage::DownloadError::Cancelled)) => {
    1100            0 :                 Err(DownloadError::DownloadCancelled)
    1101              :             }
    1102            0 :             Ok(Err(_)) => Err(DownloadError::DownloadFailed),
    1103            0 :             Err(_gone) => Err(DownloadError::DownloadCancelled),
    1104              :         }
    1105            6 :     }
    1106              : 
    1107            6 :     async fn download_and_init(
    1108            6 :         self: &Arc<LayerInner>,
    1109            6 :         timeline: Arc<Timeline>,
    1110            6 :         permit: heavier_once_cell::InitPermit,
    1111            6 :         ctx: &RequestContext,
    1112            6 :     ) -> Result<Arc<DownloadedLayer>, remote_storage::DownloadError> {
    1113            6 :         let result = timeline
    1114            6 :             .remote_client
    1115            6 :             .download_layer_file(
    1116            6 :                 &self.desc.layer_name(),
    1117            6 :                 &self.metadata(),
    1118            6 :                 &self.path,
    1119            6 :                 &timeline.cancel,
    1120            6 :                 ctx,
    1121            6 :             )
    1122           93 :             .await;
    1123              : 
    1124            6 :         match result {
    1125            6 :             Ok(size) => {
    1126            6 :                 assert_eq!(size, self.desc.file_size);
    1127              : 
    1128            6 :                 match self.needs_download().await {
    1129            0 :                     Ok(Some(reason)) => {
    1130            0 :                         // this is really a bug in needs_download or remote timeline client
    1131            0 :                         panic!("post-condition failed: needs_download returned {reason:?}");
    1132              :                     }
    1133            6 :                     Ok(None) => {
    1134            6 :                         // as expected
    1135            6 :                     }
    1136            0 :                     Err(e) => {
    1137            0 :                         panic!("post-condition failed: needs_download errored: {e:?}");
    1138              :                     }
    1139              :                 }
    1140              : 
    1141            6 :                 tracing::info!(size=%self.desc.file_size, "on-demand download successful");
    1142            6 :                 timeline
    1143            6 :                     .metrics
    1144            6 :                     .resident_physical_size_add(self.desc.file_size);
    1145            6 :                 self.consecutive_failures.store(0, Ordering::Relaxed);
    1146            6 : 
    1147            6 :                 let since_last_eviction = self
    1148            6 :                     .last_evicted_at
    1149            6 :                     .lock()
    1150            6 :                     .unwrap()
    1151            6 :                     .take()
    1152            6 :                     .map(|ts| ts.elapsed());
    1153            6 :                 if let Some(since_last_eviction) = since_last_eviction {
    1154            6 :                     LAYER_IMPL_METRICS.record_redownloaded_after(since_last_eviction);
    1155            6 :                 }
    1156              : 
    1157            6 :                 self.access_stats.record_residence_event(
    1158            6 :                     LayerResidenceStatus::Resident,
    1159            6 :                     LayerResidenceEventReason::ResidenceChange,
    1160            6 :                 );
    1161            6 : 
    1162            6 :                 Ok(self.initialize_after_layer_is_on_disk(permit))
    1163              :             }
    1164            0 :             Err(e) => {
    1165            0 :                 let consecutive_failures =
    1166            0 :                     1 + self.consecutive_failures.fetch_add(1, Ordering::Relaxed);
    1167            0 : 
    1168            0 :                 if timeline.cancel.is_cancelled() {
    1169              :                     // If we're shutting down, drop out before logging the error
    1170            0 :                     return Err(e);
    1171            0 :                 }
    1172            0 : 
    1173            0 :                 tracing::error!(consecutive_failures, "layer file download failed: {e:#}");
    1174              : 
    1175            0 :                 let backoff = utils::backoff::exponential_backoff_duration_seconds(
    1176            0 :                     consecutive_failures.min(u32::MAX as usize) as u32,
    1177            0 :                     1.5,
    1178            0 :                     60.0,
    1179            0 :                 );
    1180            0 : 
    1181            0 :                 let backoff = std::time::Duration::from_secs_f64(backoff);
    1182              : 
    1183              :                 tokio::select! {
    1184              :                     _ = tokio::time::sleep(backoff) => {},
    1185              :                     _ = timeline.cancel.cancelled() => {},
    1186              :                 };
    1187              : 
    1188            0 :                 Err(e)
    1189              :             }
    1190              :         }
    1191            6 :     }
    1192              : 
    1193              :     /// Initializes the `Self::inner` to a "resident" state.
    1194              :     ///
    1195              :     /// Callers are assumed to ensure that the file is actually on disk with `Self::needs_download`
    1196              :     /// before calling this method.
    1197              :     ///
    1198              :     /// If this method is ever made async, it needs to be cancellation safe so that no state
    1199              :     /// changes are made before we can write to the OnceCell in non-cancellable fashion.
    1200           12 :     fn initialize_after_layer_is_on_disk(
    1201           12 :         self: &Arc<LayerInner>,
    1202           12 :         permit: heavier_once_cell::InitPermit,
    1203           12 :     ) -> Arc<DownloadedLayer> {
    1204           12 :         debug_assert_current_span_has_tenant_and_timeline_id();
    1205           12 : 
    1206           12 :         // disable any scheduled but not yet running eviction deletions for this initialization
    1207           12 :         let next_version = 1 + self.version.fetch_add(1, Ordering::Relaxed);
    1208           12 :         self.status.as_ref().unwrap().send_replace(Status::Resident);
    1209           12 : 
    1210           12 :         let res = Arc::new(DownloadedLayer {
    1211           12 :             owner: Arc::downgrade(self),
    1212           12 :             kind: tokio::sync::OnceCell::default(),
    1213           12 :             version: next_version,
    1214           12 :         });
    1215           12 : 
    1216           12 :         let waiters = self.inner.initializer_count();
    1217           12 :         if waiters > 0 {
    1218            0 :             tracing::info!(waiters, "completing layer init for other tasks");
    1219           12 :         }
    1220              : 
    1221           12 :         let value = ResidentOrWantedEvicted::Resident(res.clone());
    1222           12 : 
    1223           12 :         self.inner.set(value, permit);
    1224           12 : 
    1225           12 :         res
    1226           12 :     }
    1227              : 
    1228           24 :     async fn needs_download(&self) -> Result<Option<NeedsDownload>, std::io::Error> {
    1229           24 :         match tokio::fs::metadata(&self.path).await {
    1230           16 :             Ok(m) => Ok(self.is_file_present_and_good_size(&m).err()),
    1231            8 :             Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Some(NeedsDownload::NotFound)),
    1232            0 :             Err(e) => Err(e),
    1233              :         }
    1234           24 :     }
    1235              : 
    1236           24 :     fn needs_download_blocking(&self) -> Result<Option<NeedsDownload>, std::io::Error> {
    1237           24 :         match self.path.metadata() {
    1238           24 :             Ok(m) => Ok(self.is_file_present_and_good_size(&m).err()),
    1239            0 :             Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Some(NeedsDownload::NotFound)),
    1240            0 :             Err(e) => Err(e),
    1241              :         }
    1242           24 :     }
    1243              : 
    1244           40 :     fn is_file_present_and_good_size(&self, m: &std::fs::Metadata) -> Result<(), NeedsDownload> {
    1245           40 :         // in future, this should include sha2-256 validation of the file.
    1246           40 :         if !m.is_file() {
    1247            0 :             Err(NeedsDownload::NotFile(m.file_type()))
    1248           40 :         } else if m.len() != self.desc.file_size {
    1249            0 :             Err(NeedsDownload::WrongSize {
    1250            0 :                 actual: m.len(),
    1251            0 :                 expected: self.desc.file_size,
    1252            0 :             })
    1253              :         } else {
    1254           40 :             Ok(())
    1255              :         }
    1256           40 :     }
    1257              : 
    1258            0 :     fn info(&self, reset: LayerAccessStatsReset) -> HistoricLayerInfo {
    1259            0 :         let layer_name = self.desc.layer_name().to_string();
    1260            0 : 
    1261            0 :         let resident = self
    1262            0 :             .inner
    1263            0 :             .get()
    1264            0 :             .map(|rowe| rowe.is_likely_resident())
    1265            0 :             .unwrap_or(false);
    1266            0 : 
    1267            0 :         let access_stats = self.access_stats.as_api_model(reset);
    1268            0 : 
    1269            0 :         if self.desc.is_delta {
    1270            0 :             let lsn_range = &self.desc.lsn_range;
    1271            0 : 
    1272            0 :             HistoricLayerInfo::Delta {
    1273            0 :                 layer_file_name: layer_name,
    1274            0 :                 layer_file_size: self.desc.file_size,
    1275            0 :                 lsn_start: lsn_range.start,
    1276            0 :                 lsn_end: lsn_range.end,
    1277            0 :                 remote: !resident,
    1278            0 :                 access_stats,
    1279            0 :                 l0: crate::tenant::layer_map::LayerMap::is_l0(self.layer_desc()),
    1280            0 :             }
    1281              :         } else {
    1282            0 :             let lsn = self.desc.image_layer_lsn();
    1283            0 : 
    1284            0 :             HistoricLayerInfo::Image {
    1285            0 :                 layer_file_name: layer_name,
    1286            0 :                 layer_file_size: self.desc.file_size,
    1287            0 :                 lsn_start: lsn,
    1288            0 :                 remote: !resident,
    1289            0 :                 access_stats,
    1290            0 :             }
    1291              :         }
    1292            0 :     }
    1293              : 
    1294              :     /// `DownloadedLayer` is being dropped, so it calls this method.
    1295           24 :     fn on_downloaded_layer_drop(self: Arc<LayerInner>, only_version: usize) {
    1296              :         // we cannot know without inspecting LayerInner::inner if we should evict or not, even
    1297              :         // though here it is very likely
    1298           24 :         let span = tracing::info_span!(parent: None, "layer_evict", tenant_id = %self.desc.tenant_shard_id.tenant_id, shard_id = %self.desc.tenant_shard_id.shard_slug(), timeline_id = %self.desc.timeline_id, layer=%self, version=%only_version);
    1299              : 
    1300              :         // NOTE: this scope *must* never call `self.inner.get` because evict_and_wait might
    1301              :         // drop while the `self.inner` is being locked, leading to a deadlock.
    1302              : 
    1303           24 :         let start_evicting = async move {
    1304           24 :             #[cfg(test)]
    1305           24 :             self.failpoint(failpoints::FailpointKind::WaitBeforeStartingEvicting)
    1306           14 :                 .await
    1307           24 :                 .expect("failpoint should not have errored");
    1308           24 : 
    1309           24 :             tracing::debug!("eviction started");
    1310              : 
    1311           24 :             let res = self.wait_for_turn_and_evict(only_version).await;
    1312              :             // metrics: ignore the Ok branch, it is not done yet
    1313           24 :             if let Err(e) = res {
    1314            6 :                 tracing::debug!(res=?Err::<(), _>(&e), "eviction completed");
    1315            6 :                 LAYER_IMPL_METRICS.inc_eviction_cancelled(e);
    1316           18 :             }
    1317           24 :         };
    1318              : 
    1319           24 :         Self::spawn(start_evicting.instrument(span));
    1320           24 :     }
    1321              : 
    1322           24 :     async fn wait_for_turn_and_evict(
    1323           24 :         self: Arc<LayerInner>,
    1324           24 :         only_version: usize,
    1325           24 :     ) -> Result<(), EvictionCancelled> {
    1326           46 :         fn is_good_to_continue(status: &Status) -> Result<(), EvictionCancelled> {
    1327           46 :             use Status::*;
    1328           46 :             match status {
    1329           44 :                 Resident => Ok(()),
    1330            2 :                 Evicted => Err(EvictionCancelled::UnexpectedEvictedState),
    1331            0 :                 Downloading => Err(EvictionCancelled::LostToDownload),
    1332              :             }
    1333           46 :         }
    1334              : 
    1335           24 :         let timeline = self
    1336           24 :             .timeline
    1337           24 :             .upgrade()
    1338           24 :             .ok_or(EvictionCancelled::TimelineGone)?;
    1339              : 
    1340           24 :         let mut rx = self
    1341           24 :             .status
    1342           24 :             .as_ref()
    1343           24 :             .expect("LayerInner cannot be dropped, holding strong ref")
    1344           24 :             .subscribe();
    1345           24 : 
    1346           24 :         is_good_to_continue(&rx.borrow_and_update())?;
    1347              : 
    1348           22 :         let Ok(gate) = timeline.gate.enter() else {
    1349            0 :             return Err(EvictionCancelled::TimelineGone);
    1350              :         };
    1351              : 
    1352           18 :         let permit = {
    1353              :             // we cannot just `std::fs::remove_file` because there might already be an
    1354              :             // get_or_maybe_download which will inspect filesystem and reinitialize. filesystem
    1355              :             // operations must be done while holding the heavier_once_cell::InitPermit
    1356           22 :             let mut wait = std::pin::pin!(self.inner.get_or_init_detached());
    1357              : 
    1358           22 :             let waited = loop {
    1359           22 :                 // we must race to the Downloading starting, otherwise we would have to wait until the
    1360           22 :                 // completion of the download. waiting for download could be long and hinder our
    1361           22 :                 // efforts to alert on "hanging" evictions.
    1362           22 :                 tokio::select! {
    1363              :                     res = &mut wait => break res,
    1364              :                     _ = rx.changed() => {
    1365              :                         is_good_to_continue(&rx.borrow_and_update())?;
    1366              :                         // two possibilities for Status::Resident:
    1367              :                         // - the layer was found locally from disk by a read
    1368              :                         // - we missed a bunch of updates and now the layer is
    1369              :                         // again downloaded -- assume we'll fail later on with
    1370              :                         // version check or AlreadyReinitialized
    1371              :                     }
    1372           22 :                 }
    1373           22 :             };
    1374              : 
    1375              :             // re-check now that we have the guard or permit; all updates should have happened
    1376              :             // while holding the permit.
    1377           22 :             is_good_to_continue(&rx.borrow_and_update())?;
    1378              : 
    1379              :             // the term deinitialize is used here, because we clearing out the Weak will eventually
    1380              :             // lead to deallocating the reference counted value, and the value we
    1381              :             // `Guard::take_and_deinit` is likely to be the last because the Weak is never cloned.
    1382           22 :             let (_weak, permit) = match waited {
    1383           20 :                 Ok(guard) => {
    1384           20 :                     match &*guard {
    1385           18 :                         ResidentOrWantedEvicted::WantedEvicted(_weak, version)
    1386           18 :                             if *version == only_version =>
    1387           16 :                         {
    1388           16 :                             tracing::debug!(version, "deinitializing matching WantedEvicted");
    1389           16 :                             let (weak, permit) = guard.take_and_deinit();
    1390           16 :                             (Some(weak), permit)
    1391              :                         }
    1392            2 :                         ResidentOrWantedEvicted::WantedEvicted(_, version) => {
    1393            2 :                             // if we were not doing the version check, we would need to try to
    1394            2 :                             // upgrade the weak here to see if it really is dropped. version check
    1395            2 :                             // is done instead assuming that it is cheaper.
    1396            2 :                             tracing::debug!(
    1397              :                                 version,
    1398              :                                 only_version,
    1399            0 :                                 "version mismatch, not deinitializing"
    1400              :                             );
    1401            2 :                             return Err(EvictionCancelled::VersionCheckFailed);
    1402              :                         }
    1403              :                         ResidentOrWantedEvicted::Resident(_) => {
    1404            2 :                             return Err(EvictionCancelled::AlreadyReinitialized);
    1405              :                         }
    1406              :                     }
    1407              :                 }
    1408            2 :                 Err(permit) => {
    1409            2 :                     tracing::debug!("continuing after cancelled get_or_maybe_download or eviction");
    1410            2 :                     (None, permit)
    1411              :                 }
    1412              :             };
    1413              : 
    1414           18 :             permit
    1415           18 :         };
    1416           18 : 
    1417           18 :         let span = tracing::Span::current();
    1418           18 : 
    1419           18 :         let spawned_at = std::time::Instant::now();
    1420           18 : 
    1421           18 :         // this is on purpose a detached spawn; we don't need to wait for it
    1422           18 :         //
    1423           18 :         // eviction completion reporting is the only thing hinging on this, and it can be just as
    1424           18 :         // well from a spawn_blocking thread.
    1425           18 :         //
    1426           18 :         // important to note that now that we've acquired the permit we have made sure the evicted
    1427           18 :         // file is either the exact `WantedEvicted` we wanted to evict, or uninitialized in case
    1428           18 :         // there are multiple evictions. The rest is not cancellable, and we've now commited to
    1429           18 :         // evicting.
    1430           18 :         //
    1431           18 :         // If spawn_blocking has a queue and maximum number of threads are in use, we could stall
    1432           18 :         // reads. We will need to add cancellation for that if necessary.
    1433           18 :         Self::spawn_blocking(move || {
    1434           18 :             let _span = span.entered();
    1435           18 : 
    1436           18 :             let res = self.evict_blocking(&timeline, &gate, &permit);
    1437           18 : 
    1438           18 :             let waiters = self.inner.initializer_count();
    1439           18 : 
    1440           18 :             if waiters > 0 {
    1441            0 :                 LAYER_IMPL_METRICS.inc_evicted_with_waiters();
    1442           18 :             }
    1443              : 
    1444           18 :             let completed_in = spawned_at.elapsed();
    1445           18 :             LAYER_IMPL_METRICS.record_time_to_evict(completed_in);
    1446           18 : 
    1447           18 :             match res {
    1448           18 :                 Ok(()) => LAYER_IMPL_METRICS.inc_completed_evictions(),
    1449            0 :                 Err(e) => LAYER_IMPL_METRICS.inc_eviction_cancelled(e),
    1450              :             }
    1451              : 
    1452           18 :             tracing::debug!(?res, elapsed_ms=%completed_in.as_millis(), %waiters, "eviction completed");
    1453           18 :         });
    1454           18 : 
    1455           18 :         Ok(())
    1456           24 :     }
    1457              : 
    1458              :     /// This is blocking only to do just one spawn_blocking hop compared to multiple via tokio::fs.
    1459           18 :     fn evict_blocking(
    1460           18 :         &self,
    1461           18 :         timeline: &Timeline,
    1462           18 :         _gate: &gate::GateGuard,
    1463           18 :         _permit: &heavier_once_cell::InitPermit,
    1464           18 :     ) -> Result<(), EvictionCancelled> {
    1465           18 :         // now accesses to `self.inner.get_or_init*` wait on the semaphore or the `_permit`
    1466           18 : 
    1467           18 :         match capture_mtime_and_remove(&self.path) {
    1468           18 :             Ok(local_layer_mtime) => {
    1469           18 :                 let duration = SystemTime::now().duration_since(local_layer_mtime);
    1470           18 :                 match duration {
    1471           18 :                     Ok(elapsed) => {
    1472           18 :                         timeline
    1473           18 :                             .metrics
    1474           18 :                             .evictions_with_low_residence_duration
    1475           18 :                             .read()
    1476           18 :                             .unwrap()
    1477           18 :                             .observe(elapsed);
    1478           18 :                         tracing::info!(
    1479            0 :                             residence_millis = elapsed.as_millis(),
    1480            0 :                             "evicted layer after known residence period"
    1481              :                         );
    1482              :                     }
    1483              :                     Err(_) => {
    1484            0 :                         tracing::info!("evicted layer after unknown residence period");
    1485              :                     }
    1486              :                 }
    1487           18 :                 timeline.metrics.evictions.inc();
    1488           18 :                 timeline
    1489           18 :                     .metrics
    1490           18 :                     .resident_physical_size_sub(self.desc.file_size);
    1491              :             }
    1492            0 :             Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
    1493            0 :                 tracing::error!(
    1494              :                     layer_size = %self.desc.file_size,
    1495            0 :                     "failed to evict layer from disk, it was already gone"
    1496              :                 );
    1497            0 :                 return Err(EvictionCancelled::FileNotFound);
    1498              :             }
    1499            0 :             Err(e) => {
    1500            0 :                 // FIXME: this should probably be an abort
    1501            0 :                 tracing::error!("failed to evict file from disk: {e:#}");
    1502            0 :                 return Err(EvictionCancelled::RemoveFailed);
    1503              :             }
    1504              :         }
    1505              : 
    1506           18 :         self.access_stats.record_residence_event(
    1507           18 :             LayerResidenceStatus::Evicted,
    1508           18 :             LayerResidenceEventReason::ResidenceChange,
    1509           18 :         );
    1510           18 : 
    1511           18 :         self.status.as_ref().unwrap().send_replace(Status::Evicted);
    1512           18 : 
    1513           18 :         *self.last_evicted_at.lock().unwrap() = Some(std::time::Instant::now());
    1514           18 : 
    1515           18 :         Ok(())
    1516           18 :     }
    1517              : 
    1518         1937 :     fn metadata(&self) -> LayerFileMetadata {
    1519         1937 :         LayerFileMetadata::new(self.desc.file_size, self.generation, self.shard)
    1520         1937 :     }
    1521              : 
    1522              :     /// Needed to use entered runtime in tests, but otherwise use BACKGROUND_RUNTIME.
    1523              :     ///
    1524              :     /// Synchronizing with spawned tasks is very complicated otherwise.
    1525           30 :     fn spawn<F>(fut: F)
    1526           30 :     where
    1527           30 :         F: std::future::Future<Output = ()> + Send + 'static,
    1528           30 :     {
    1529           30 :         #[cfg(test)]
    1530           30 :         tokio::task::spawn(fut);
    1531           30 :         #[cfg(not(test))]
    1532           30 :         crate::task_mgr::BACKGROUND_RUNTIME.spawn(fut);
    1533           30 :     }
    1534              : 
    1535              :     /// Needed to use entered runtime in tests, but otherwise use BACKGROUND_RUNTIME.
    1536          451 :     fn spawn_blocking<F>(f: F)
    1537          451 :     where
    1538          451 :         F: FnOnce() + Send + 'static,
    1539          451 :     {
    1540          451 :         #[cfg(test)]
    1541          451 :         tokio::task::spawn_blocking(f);
    1542          451 :         #[cfg(not(test))]
    1543          451 :         crate::task_mgr::BACKGROUND_RUNTIME.spawn_blocking(f);
    1544          451 :     }
    1545              : }
    1546              : 
    1547           18 : fn capture_mtime_and_remove(path: &Utf8Path) -> Result<SystemTime, std::io::Error> {
    1548           18 :     let m = path.metadata()?;
    1549           18 :     let local_layer_mtime = m.modified()?;
    1550           18 :     std::fs::remove_file(path)?;
    1551           18 :     Ok(local_layer_mtime)
    1552           18 : }
    1553              : 
    1554            0 : #[derive(Debug, thiserror::Error)]
    1555              : pub(crate) enum EvictionError {
    1556              :     #[error("layer was already evicted")]
    1557              :     NotFound,
    1558              : 
    1559              :     /// Evictions must always lose to downloads in races, and this time it happened.
    1560              :     #[error("layer was downloaded instead")]
    1561              :     Downloaded,
    1562              : 
    1563              :     #[error("eviction did not happen within timeout")]
    1564              :     Timeout,
    1565              : }
    1566              : 
    1567              : /// Error internal to the [`LayerInner::get_or_maybe_download`]
    1568            0 : #[derive(Debug, thiserror::Error)]
    1569              : pub(crate) enum DownloadError {
    1570              :     #[error("timeline has already shutdown")]
    1571              :     TimelineShutdown,
    1572              :     #[error("context denies downloading")]
    1573              :     ContextAndConfigReallyDeniesDownloads,
    1574              :     #[error("downloading is really required but not allowed by this method")]
    1575              :     DownloadRequired,
    1576              :     #[error("layer path exists, but it is not a file: {0:?}")]
    1577              :     NotFile(std::fs::FileType),
    1578              :     /// Why no error here? Because it will be reported by page_service. We should had also done
    1579              :     /// retries already.
    1580              :     #[error("downloading evicted layer file failed")]
    1581              :     DownloadFailed,
    1582              :     #[error("downloading failed, possibly for shutdown")]
    1583              :     DownloadCancelled,
    1584              :     #[error("pre-condition: stat before download failed")]
    1585              :     PreStatFailed(#[source] std::io::Error),
    1586              : 
    1587              :     #[cfg(test)]
    1588              :     #[error("failpoint: {0:?}")]
    1589              :     Failpoint(failpoints::FailpointKind),
    1590              : }
    1591              : 
    1592              : #[derive(Debug, PartialEq)]
    1593              : pub(crate) enum NeedsDownload {
    1594              :     NotFound,
    1595              :     NotFile(std::fs::FileType),
    1596              :     WrongSize { actual: u64, expected: u64 },
    1597              : }
    1598              : 
    1599              : impl std::fmt::Display for NeedsDownload {
    1600            6 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    1601            6 :         match self {
    1602            6 :             NeedsDownload::NotFound => write!(f, "file was not found"),
    1603            0 :             NeedsDownload::NotFile(ft) => write!(f, "path is not a file; {ft:?}"),
    1604            0 :             NeedsDownload::WrongSize { actual, expected } => {
    1605            0 :                 write!(f, "file size mismatch {actual} vs. {expected}")
    1606              :             }
    1607              :         }
    1608            6 :     }
    1609              : }
    1610              : 
    1611              : /// Existence of `DownloadedLayer` means that we have the file locally, and can later evict it.
    1612              : pub(crate) struct DownloadedLayer {
    1613              :     owner: Weak<LayerInner>,
    1614              :     // Use tokio OnceCell as we do not need to deinitialize this, it'll just get dropped with the
    1615              :     // DownloadedLayer
    1616              :     kind: tokio::sync::OnceCell<anyhow::Result<LayerKind>>,
    1617              :     version: usize,
    1618              : }
    1619              : 
    1620              : impl std::fmt::Debug for DownloadedLayer {
    1621            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    1622            0 :         f.debug_struct("DownloadedLayer")
    1623            0 :             // owner omitted because it is always "Weak"
    1624            0 :             .field("kind", &self.kind)
    1625            0 :             .field("version", &self.version)
    1626            0 :             .finish()
    1627            0 :     }
    1628              : }
    1629              : 
    1630              : impl Drop for DownloadedLayer {
    1631          503 :     fn drop(&mut self) {
    1632          503 :         if let Some(owner) = self.owner.upgrade() {
    1633           24 :             owner.on_downloaded_layer_drop(self.version);
    1634          479 :         } else {
    1635          479 :             // Layer::drop will handle cancelling the eviction; because of drop order and
    1636          479 :             // `DownloadedLayer` never leaking, we cannot know here if eviction was requested.
    1637          479 :         }
    1638          503 :     }
    1639              : }
    1640              : 
    1641              : impl DownloadedLayer {
    1642              :     /// Initializes the `DeltaLayerInner` or `ImageLayerInner` within [`LayerKind`], or fails to
    1643              :     /// initialize it permanently.
    1644              :     ///
    1645              :     /// `owner` parameter is a strong reference at the same `LayerInner` as the
    1646              :     /// `DownloadedLayer::owner` would be when upgraded. Given how this method ends up called,
    1647              :     /// we will always have the LayerInner on the callstack, so we can just use it.
    1648       211978 :     async fn get<'a>(
    1649       211978 :         &'a self,
    1650       211978 :         owner: &Arc<LayerInner>,
    1651       211978 :         ctx: &RequestContext,
    1652       211978 :     ) -> anyhow::Result<&'a LayerKind> {
    1653       211978 :         let init = || async {
    1654         1090 :             assert_eq!(
    1655         1090 :                 Weak::as_ptr(&self.owner),
    1656         1090 :                 Arc::as_ptr(owner),
    1657         1090 :                 "these are the same, just avoiding the upgrade"
    1658         1090 :             );
    1659         1090 : 
    1660         1090 :             let res = if owner.desc.is_delta {
    1661         1090 :                 let summary = Some(delta_layer::Summary::expected(
    1662         1000 :                     owner.desc.tenant_shard_id.tenant_id,
    1663         1000 :                     owner.desc.timeline_id,
    1664         1000 :                     owner.desc.key_range.clone(),
    1665         1000 :                     owner.desc.lsn_range.clone(),
    1666         1000 :                 ));
    1667         1000 :                 delta_layer::DeltaLayerInner::load(
    1668         1000 :                     &owner.path,
    1669         1000 :                     summary,
    1670         1000 :                     Some(owner.conf.max_vectored_read_bytes),
    1671         1000 :                     ctx,
    1672         1000 :                 )
    1673         1090 :                 .await
    1674         1090 :                 .map(|res| res.map(LayerKind::Delta))
    1675         1090 :             } else {
    1676         1090 :                 let lsn = owner.desc.image_layer_lsn();
    1677           90 :                 let summary = Some(image_layer::Summary::expected(
    1678           90 :                     owner.desc.tenant_shard_id.tenant_id,
    1679           90 :                     owner.desc.timeline_id,
    1680           90 :                     owner.desc.key_range.clone(),
    1681           90 :                     lsn,
    1682           90 :                 ));
    1683           90 :                 image_layer::ImageLayerInner::load(
    1684           90 :                     &owner.path,
    1685           90 :                     lsn,
    1686           90 :                     summary,
    1687           90 :                     Some(owner.conf.max_vectored_read_bytes),
    1688           90 :                     ctx,
    1689           90 :                 )
    1690         1090 :                 .await
    1691         1090 :                 .map(|res| res.map(LayerKind::Image))
    1692         1090 :             };
    1693         1090 : 
    1694         1090 :             match res {
    1695         1090 :                 Ok(Ok(layer)) => Ok(Ok(layer)),
    1696         1090 :                 Ok(Err(transient)) => Err(transient),
    1697         1090 :                 Err(permanent) => {
    1698            0 :                     LAYER_IMPL_METRICS.inc_permanent_loading_failures();
    1699            0 :                     // TODO(#5815): we are not logging all errors, so temporarily log them **once**
    1700            0 :                     // here as well
    1701            0 :                     let permanent = permanent.context("load layer");
    1702            0 :                     tracing::error!("layer loading failed permanently: {permanent:#}");
    1703         1090 :                     Ok(Err(permanent))
    1704         1090 :                 }
    1705         1090 :             }
    1706         1090 :         };
    1707       211978 :         self.kind
    1708       211978 :             .get_or_try_init(init)
    1709              :             // return transient errors using `?`
    1710         1102 :             .await?
    1711       211978 :             .as_ref()
    1712       211978 :             .map_err(|e| {
    1713            0 :                 // errors are not clonabled, cannot but stringify
    1714            0 :                 // test_broken_timeline matches this string
    1715            0 :                 anyhow::anyhow!("layer loading failed: {e:#}")
    1716       211978 :             })
    1717       211978 :     }
    1718              : 
    1719       211274 :     async fn get_value_reconstruct_data(
    1720       211274 :         &self,
    1721       211274 :         key: Key,
    1722       211274 :         lsn_range: Range<Lsn>,
    1723       211274 :         reconstruct_data: &mut ValueReconstructState,
    1724       211274 :         owner: &Arc<LayerInner>,
    1725       211274 :         ctx: &RequestContext,
    1726       211274 :     ) -> anyhow::Result<ValueReconstructResult> {
    1727       211274 :         use LayerKind::*;
    1728       211274 : 
    1729       211274 :         match self.get(owner, ctx).await? {
    1730       204163 :             Delta(d) => {
    1731       204163 :                 d.get_value_reconstruct_data(key, lsn_range, reconstruct_data, ctx)
    1732        28617 :                     .await
    1733              :             }
    1734         7111 :             Image(i) => {
    1735         7111 :                 i.get_value_reconstruct_data(key, reconstruct_data, ctx)
    1736          708 :                     .await
    1737              :             }
    1738              :         }
    1739       211274 :     }
    1740              : 
    1741          228 :     async fn get_values_reconstruct_data(
    1742          228 :         &self,
    1743          228 :         keyspace: KeySpace,
    1744          228 :         lsn_range: Range<Lsn>,
    1745          228 :         reconstruct_data: &mut ValuesReconstructState,
    1746          228 :         owner: &Arc<LayerInner>,
    1747          228 :         ctx: &RequestContext,
    1748          228 :     ) -> Result<(), GetVectoredError> {
    1749          228 :         use LayerKind::*;
    1750          228 : 
    1751          228 :         match self.get(owner, ctx).await.map_err(GetVectoredError::from)? {
    1752          154 :             Delta(d) => {
    1753          154 :                 d.get_values_reconstruct_data(keyspace, lsn_range, reconstruct_data, ctx)
    1754        10210 :                     .await
    1755              :             }
    1756           74 :             Image(i) => {
    1757           74 :                 i.get_values_reconstruct_data(keyspace, reconstruct_data, ctx)
    1758         1222 :                     .await
    1759              :             }
    1760              :         }
    1761          228 :     }
    1762              : 
    1763           16 :     async fn load_key_values(
    1764           16 :         &self,
    1765           16 :         owner: &Arc<LayerInner>,
    1766           16 :         ctx: &RequestContext,
    1767           16 :     ) -> anyhow::Result<Vec<(Key, Lsn, crate::repository::Value)>> {
    1768           16 :         use LayerKind::*;
    1769           16 : 
    1770           16 :         match self.get(owner, ctx).await? {
    1771            8 :             Delta(d) => d.load_key_values(ctx).await,
    1772            8 :             Image(i) => i.load_key_values(ctx).await,
    1773              :         }
    1774           16 :     }
    1775              : 
    1776            4 :     async fn dump(&self, owner: &Arc<LayerInner>, ctx: &RequestContext) -> anyhow::Result<()> {
    1777            4 :         use LayerKind::*;
    1778            4 :         match self.get(owner, ctx).await? {
    1779            4 :             Delta(d) => d.dump(ctx).await?,
    1780            0 :             Image(i) => i.dump(ctx).await?,
    1781              :         }
    1782              : 
    1783            4 :         Ok(())
    1784            4 :     }
    1785              : }
    1786              : 
    1787              : /// Wrapper around an actual layer implementation.
    1788              : #[derive(Debug)]
    1789              : enum LayerKind {
    1790              :     Delta(delta_layer::DeltaLayerInner),
    1791              :     Image(image_layer::ImageLayerInner),
    1792              : }
    1793              : 
    1794              : /// Guard for forcing a layer be resident while it exists.
    1795              : #[derive(Clone)]
    1796              : pub(crate) struct ResidentLayer {
    1797              :     owner: Layer,
    1798              :     downloaded: Arc<DownloadedLayer>,
    1799              : }
    1800              : 
    1801              : impl std::fmt::Display for ResidentLayer {
    1802         1880 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    1803         1880 :         write!(f, "{}", self.owner)
    1804         1880 :     }
    1805              : }
    1806              : 
    1807              : impl std::fmt::Debug for ResidentLayer {
    1808            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    1809            0 :         write!(f, "{}", self.owner)
    1810            0 :     }
    1811              : }
    1812              : 
    1813              : impl ResidentLayer {
    1814              :     /// Release the eviction guard, converting back into a plain [`Layer`].
    1815              :     ///
    1816              :     /// You can access the [`Layer`] also by using `as_ref`.
    1817          420 :     pub(crate) fn drop_eviction_guard(self) -> Layer {
    1818          420 :         self.into()
    1819          420 :     }
    1820              : 
    1821              :     /// Loads all keys stored in the layer. Returns key, lsn and value size.
    1822          804 :     #[tracing::instrument(level = tracing::Level::DEBUG, skip_all, fields(layer=%self))]
    1823              :     pub(crate) async fn load_keys<'a>(
    1824              :         &'a self,
    1825              :         ctx: &RequestContext,
    1826              :     ) -> anyhow::Result<Vec<DeltaEntry<'a>>> {
    1827              :         use LayerKind::*;
    1828              : 
    1829              :         let owner = &self.owner.0;
    1830              :         match self.downloaded.get(owner, ctx).await? {
    1831              :             Delta(ref d) => {
    1832              :                 // this is valid because the DownloadedLayer::kind is a OnceCell, not a
    1833              :                 // Mutex<OnceCell>, so we cannot go and deinitialize the value with OnceCell::take
    1834              :                 // while it's being held.
    1835              :                 owner
    1836              :                     .access_stats
    1837              :                     .record_access(LayerAccessKind::KeyIter, ctx);
    1838              : 
    1839              :                 delta_layer::DeltaLayerInner::load_keys(d, ctx)
    1840              :                     .await
    1841            0 :                     .with_context(|| format!("Layer index is corrupted for {self}"))
    1842              :             }
    1843              :             Image(_) => anyhow::bail!(format!("cannot load_keys on a image layer {self}")),
    1844              :         }
    1845              :     }
    1846              : 
    1847              :     /// Read all they keys in this layer which match the ShardIdentity, and write them all to
    1848              :     /// the provided writer.  Return the number of keys written.
    1849           16 :     #[tracing::instrument(level = tracing::Level::DEBUG, skip_all, fields(layer=%self))]
    1850              :     pub(crate) async fn filter<'a>(
    1851              :         &'a self,
    1852              :         shard_identity: &ShardIdentity,
    1853              :         writer: &mut ImageLayerWriter,
    1854              :         ctx: &RequestContext,
    1855              :     ) -> anyhow::Result<usize> {
    1856              :         use LayerKind::*;
    1857              : 
    1858              :         match self.downloaded.get(&self.owner.0, ctx).await? {
    1859              :             Delta(_) => anyhow::bail!(format!("cannot filter() on a delta layer {self}")),
    1860              :             Image(i) => i.filter(shard_identity, writer, ctx).await,
    1861              :         }
    1862              :     }
    1863              : 
    1864              :     /// Returns the amount of keys and values written to the writer.
    1865           10 :     pub(crate) async fn copy_delta_prefix(
    1866           10 :         &self,
    1867           10 :         writer: &mut super::delta_layer::DeltaLayerWriter,
    1868           10 :         until: Lsn,
    1869           10 :         ctx: &RequestContext,
    1870           10 :     ) -> anyhow::Result<usize> {
    1871           10 :         use LayerKind::*;
    1872           10 : 
    1873           10 :         let owner = &self.owner.0;
    1874           10 : 
    1875           10 :         match self.downloaded.get(owner, ctx).await? {
    1876           10 :             Delta(ref d) => d
    1877           10 :                 .copy_prefix(writer, until, ctx)
    1878           13 :                 .await
    1879           10 :                 .with_context(|| format!("copy_delta_prefix until {until} of {self}")),
    1880            0 :             Image(_) => anyhow::bail!(format!("cannot copy_lsn_prefix of image layer {self}")),
    1881              :         }
    1882           10 :     }
    1883              : 
    1884         1565 :     pub(crate) fn local_path(&self) -> &Utf8Path {
    1885         1565 :         &self.owner.0.path
    1886         1565 :     }
    1887              : 
    1888         1498 :     pub(crate) fn metadata(&self) -> LayerFileMetadata {
    1889         1498 :         self.owner.metadata()
    1890         1498 :     }
    1891              : 
    1892              :     #[cfg(test)]
    1893           34 :     pub(crate) async fn get_as_delta(
    1894           34 :         &self,
    1895           34 :         ctx: &RequestContext,
    1896           34 :     ) -> anyhow::Result<&delta_layer::DeltaLayerInner> {
    1897           34 :         use LayerKind::*;
    1898           34 :         match self.downloaded.get(&self.owner.0, ctx).await? {
    1899           34 :             Delta(ref d) => Ok(d),
    1900            0 :             Image(_) => Err(anyhow::anyhow!("image layer")),
    1901              :         }
    1902           34 :     }
    1903              : 
    1904              :     #[cfg(test)]
    1905            2 :     pub(crate) async fn get_as_image(
    1906            2 :         &self,
    1907            2 :         ctx: &RequestContext,
    1908            2 :     ) -> anyhow::Result<&image_layer::ImageLayerInner> {
    1909            2 :         use LayerKind::*;
    1910            2 :         match self.downloaded.get(&self.owner.0, ctx).await? {
    1911            2 :             Image(ref d) => Ok(d),
    1912            0 :             Delta(_) => Err(anyhow::anyhow!("delta layer")),
    1913              :         }
    1914            2 :     }
    1915              : }
    1916              : 
    1917              : impl AsLayerDesc for ResidentLayer {
    1918         5269 :     fn layer_desc(&self) -> &PersistentLayerDesc {
    1919         5269 :         self.owner.layer_desc()
    1920         5269 :     }
    1921              : }
    1922              : 
    1923              : impl AsRef<Layer> for ResidentLayer {
    1924         1850 :     fn as_ref(&self) -> &Layer {
    1925         1850 :         &self.owner
    1926         1850 :     }
    1927              : }
    1928              : 
    1929              : /// Drop the eviction guard.
    1930              : impl From<ResidentLayer> for Layer {
    1931          420 :     fn from(value: ResidentLayer) -> Self {
    1932          420 :         value.owner
    1933          420 :     }
    1934              : }
    1935              : 
    1936              : use metrics::IntCounter;
    1937              : 
    1938              : pub(crate) struct LayerImplMetrics {
    1939              :     started_evictions: IntCounter,
    1940              :     completed_evictions: IntCounter,
    1941              :     cancelled_evictions: enum_map::EnumMap<EvictionCancelled, IntCounter>,
    1942              : 
    1943              :     started_deletes: IntCounter,
    1944              :     completed_deletes: IntCounter,
    1945              :     failed_deletes: enum_map::EnumMap<DeleteFailed, IntCounter>,
    1946              : 
    1947              :     rare_counters: enum_map::EnumMap<RareEvent, IntCounter>,
    1948              :     inits_cancelled: metrics::core::GenericCounter<metrics::core::AtomicU64>,
    1949              :     redownload_after: metrics::Histogram,
    1950              :     time_to_evict: metrics::Histogram,
    1951              : }
    1952              : 
    1953              : impl Default for LayerImplMetrics {
    1954           36 :     fn default() -> Self {
    1955           36 :         use enum_map::Enum;
    1956           36 : 
    1957           36 :         // reminder: these will be pageserver_layer_* with "_total" suffix
    1958           36 : 
    1959           36 :         let started_evictions = metrics::register_int_counter!(
    1960              :             "pageserver_layer_started_evictions",
    1961              :             "Evictions started in the Layer implementation"
    1962              :         )
    1963           36 :         .unwrap();
    1964           36 :         let completed_evictions = metrics::register_int_counter!(
    1965              :             "pageserver_layer_completed_evictions",
    1966              :             "Evictions completed in the Layer implementation"
    1967              :         )
    1968           36 :         .unwrap();
    1969           36 : 
    1970           36 :         let cancelled_evictions = metrics::register_int_counter_vec!(
    1971              :             "pageserver_layer_cancelled_evictions_count",
    1972              :             "Different reasons for evictions to have been cancelled or failed",
    1973              :             &["reason"]
    1974              :         )
    1975           36 :         .unwrap();
    1976           36 : 
    1977          324 :         let cancelled_evictions = enum_map::EnumMap::from_array(std::array::from_fn(|i| {
    1978          324 :             let reason = EvictionCancelled::from_usize(i);
    1979          324 :             let s = reason.as_str();
    1980          324 :             cancelled_evictions.with_label_values(&[s])
    1981          324 :         }));
    1982           36 : 
    1983           36 :         let started_deletes = metrics::register_int_counter!(
    1984              :             "pageserver_layer_started_deletes",
    1985              :             "Deletions on drop pending in the Layer implementation"
    1986              :         )
    1987           36 :         .unwrap();
    1988           36 :         let completed_deletes = metrics::register_int_counter!(
    1989              :             "pageserver_layer_completed_deletes",
    1990              :             "Deletions on drop completed in the Layer implementation"
    1991              :         )
    1992           36 :         .unwrap();
    1993           36 : 
    1994           36 :         let failed_deletes = metrics::register_int_counter_vec!(
    1995              :             "pageserver_layer_failed_deletes_count",
    1996              :             "Different reasons for deletions on drop to have failed",
    1997              :             &["reason"]
    1998              :         )
    1999           36 :         .unwrap();
    2000           36 : 
    2001           72 :         let failed_deletes = enum_map::EnumMap::from_array(std::array::from_fn(|i| {
    2002           72 :             let reason = DeleteFailed::from_usize(i);
    2003           72 :             let s = reason.as_str();
    2004           72 :             failed_deletes.with_label_values(&[s])
    2005           72 :         }));
    2006           36 : 
    2007           36 :         let rare_counters = metrics::register_int_counter_vec!(
    2008              :             "pageserver_layer_assumed_rare_count",
    2009              :             "Times unexpected or assumed rare event happened",
    2010              :             &["event"]
    2011              :         )
    2012           36 :         .unwrap();
    2013           36 : 
    2014          252 :         let rare_counters = enum_map::EnumMap::from_array(std::array::from_fn(|i| {
    2015          252 :             let event = RareEvent::from_usize(i);
    2016          252 :             let s = event.as_str();
    2017          252 :             rare_counters.with_label_values(&[s])
    2018          252 :         }));
    2019           36 : 
    2020           36 :         let inits_cancelled = metrics::register_int_counter!(
    2021              :             "pageserver_layer_inits_cancelled_count",
    2022              :             "Times Layer initialization was cancelled",
    2023              :         )
    2024           36 :         .unwrap();
    2025           36 : 
    2026           36 :         let redownload_after = {
    2027           36 :             let minute = 60.0;
    2028           36 :             let hour = 60.0 * minute;
    2029              :             metrics::register_histogram!(
    2030              :                 "pageserver_layer_redownloaded_after",
    2031              :                 "Time between evicting and re-downloading.",
    2032              :                 vec![
    2033              :                     10.0,
    2034              :                     30.0,
    2035              :                     minute,
    2036              :                     5.0 * minute,
    2037              :                     15.0 * minute,
    2038              :                     30.0 * minute,
    2039              :                     hour,
    2040              :                     12.0 * hour,
    2041              :                 ]
    2042              :             )
    2043           36 :             .unwrap()
    2044           36 :         };
    2045           36 : 
    2046           36 :         let time_to_evict = metrics::register_histogram!(
    2047              :             "pageserver_layer_eviction_held_permit_seconds",
    2048              :             "Time eviction held the permit.",
    2049              :             vec![0.001, 0.010, 0.100, 0.500, 1.000, 5.000]
    2050              :         )
    2051           36 :         .unwrap();
    2052           36 : 
    2053           36 :         Self {
    2054           36 :             started_evictions,
    2055           36 :             completed_evictions,
    2056           36 :             cancelled_evictions,
    2057           36 : 
    2058           36 :             started_deletes,
    2059           36 :             completed_deletes,
    2060           36 :             failed_deletes,
    2061           36 : 
    2062           36 :             rare_counters,
    2063           36 :             inits_cancelled,
    2064           36 :             redownload_after,
    2065           36 :             time_to_evict,
    2066           36 :         }
    2067           36 :     }
    2068              : }
    2069              : 
    2070              : impl LayerImplMetrics {
    2071           26 :     fn inc_started_evictions(&self) {
    2072           26 :         self.started_evictions.inc();
    2073           26 :     }
    2074           18 :     fn inc_completed_evictions(&self) {
    2075           18 :         self.completed_evictions.inc();
    2076           18 :     }
    2077            8 :     fn inc_eviction_cancelled(&self, reason: EvictionCancelled) {
    2078            8 :         self.cancelled_evictions[reason].inc()
    2079            8 :     }
    2080              : 
    2081          434 :     fn inc_started_deletes(&self) {
    2082          434 :         self.started_deletes.inc();
    2083          434 :     }
    2084          432 :     fn inc_completed_deletes(&self) {
    2085          432 :         self.completed_deletes.inc();
    2086          432 :     }
    2087            0 :     fn inc_deletes_failed(&self, reason: DeleteFailed) {
    2088            0 :         self.failed_deletes[reason].inc();
    2089            0 :     }
    2090              : 
    2091              :     /// Counted separatedly from failed layer deletes because we will complete the layer deletion
    2092              :     /// attempt regardless of failure to delete local file.
    2093            0 :     fn inc_delete_removes_failed(&self) {
    2094            0 :         self.rare_counters[RareEvent::RemoveOnDropFailed].inc();
    2095            0 :     }
    2096              : 
    2097              :     /// Expected rare just as cancellations are rare, but we could have cancellations separate from
    2098              :     /// the single caller which can start the download, so use this counter to separte them.
    2099            0 :     fn inc_init_completed_without_requester(&self) {
    2100            0 :         self.rare_counters[RareEvent::InitCompletedWithoutRequester].inc();
    2101            0 :     }
    2102              : 
    2103              :     /// Expected rare because cancellations are unexpected, and failures are unexpected
    2104            0 :     fn inc_download_failed_without_requester(&self) {
    2105            0 :         self.rare_counters[RareEvent::DownloadFailedWithoutRequester].inc();
    2106            0 :     }
    2107              : 
    2108              :     /// The Weak in ResidentOrWantedEvicted::WantedEvicted was successfully upgraded.
    2109              :     ///
    2110              :     /// If this counter is always zero, we should replace ResidentOrWantedEvicted type with an
    2111              :     /// Option.
    2112            0 :     fn inc_raced_wanted_evicted_accesses(&self) {
    2113            0 :         self.rare_counters[RareEvent::UpgradedWantedEvicted].inc();
    2114            0 :     }
    2115              : 
    2116              :     /// These are only expected for [`Self::inc_init_cancelled`] amount when
    2117              :     /// running with remote storage.
    2118            6 :     fn inc_init_needed_no_download(&self) {
    2119            6 :         self.rare_counters[RareEvent::InitWithoutDownload].inc();
    2120            6 :     }
    2121              : 
    2122              :     /// Expected rare because all layer files should be readable and good
    2123            0 :     fn inc_permanent_loading_failures(&self) {
    2124            0 :         self.rare_counters[RareEvent::PermanentLoadingFailure].inc();
    2125            0 :     }
    2126              : 
    2127            0 :     fn inc_init_cancelled(&self) {
    2128            0 :         self.inits_cancelled.inc()
    2129            0 :     }
    2130              : 
    2131            6 :     fn record_redownloaded_after(&self, duration: std::time::Duration) {
    2132            6 :         self.redownload_after.observe(duration.as_secs_f64())
    2133            6 :     }
    2134              : 
    2135              :     /// This would be bad if it ever happened, or mean extreme disk pressure. We should probably
    2136              :     /// instead cancel eviction if we would have read waiters. We cannot however separate reads
    2137              :     /// from other evictions, so this could have noise as well.
    2138            0 :     fn inc_evicted_with_waiters(&self) {
    2139            0 :         self.rare_counters[RareEvent::EvictedWithWaiters].inc();
    2140            0 :     }
    2141              : 
    2142              :     /// Recorded at least initially as the permit is now acquired in async context before
    2143              :     /// spawn_blocking action.
    2144           18 :     fn record_time_to_evict(&self, duration: std::time::Duration) {
    2145           18 :         self.time_to_evict.observe(duration.as_secs_f64())
    2146           18 :     }
    2147              : }
    2148              : 
    2149              : #[derive(Debug, Clone, Copy, enum_map::Enum)]
    2150              : enum EvictionCancelled {
    2151              :     LayerGone,
    2152              :     TimelineGone,
    2153              :     VersionCheckFailed,
    2154              :     FileNotFound,
    2155              :     RemoveFailed,
    2156              :     AlreadyReinitialized,
    2157              :     /// Not evicted because of a pending reinitialization
    2158              :     LostToDownload,
    2159              :     /// After eviction, there was a new layer access which cancelled the eviction.
    2160              :     UpgradedBackOnAccess,
    2161              :     UnexpectedEvictedState,
    2162              : }
    2163              : 
    2164              : impl EvictionCancelled {
    2165          324 :     fn as_str(&self) -> &'static str {
    2166          324 :         match self {
    2167           36 :             EvictionCancelled::LayerGone => "layer_gone",
    2168           36 :             EvictionCancelled::TimelineGone => "timeline_gone",
    2169           36 :             EvictionCancelled::VersionCheckFailed => "version_check_fail",
    2170           36 :             EvictionCancelled::FileNotFound => "file_not_found",
    2171           36 :             EvictionCancelled::RemoveFailed => "remove_failed",
    2172           36 :             EvictionCancelled::AlreadyReinitialized => "already_reinitialized",
    2173           36 :             EvictionCancelled::LostToDownload => "lost_to_download",
    2174           36 :             EvictionCancelled::UpgradedBackOnAccess => "upgraded_back_on_access",
    2175           36 :             EvictionCancelled::UnexpectedEvictedState => "unexpected_evicted_state",
    2176              :         }
    2177          324 :     }
    2178              : }
    2179              : 
    2180              : #[derive(enum_map::Enum)]
    2181              : enum DeleteFailed {
    2182              :     TimelineGone,
    2183              :     DeleteSchedulingFailed,
    2184              : }
    2185              : 
    2186              : impl DeleteFailed {
    2187           72 :     fn as_str(&self) -> &'static str {
    2188           72 :         match self {
    2189           36 :             DeleteFailed::TimelineGone => "timeline_gone",
    2190           36 :             DeleteFailed::DeleteSchedulingFailed => "delete_scheduling_failed",
    2191              :         }
    2192           72 :     }
    2193              : }
    2194              : 
    2195              : #[derive(enum_map::Enum)]
    2196              : enum RareEvent {
    2197              :     RemoveOnDropFailed,
    2198              :     InitCompletedWithoutRequester,
    2199              :     DownloadFailedWithoutRequester,
    2200              :     UpgradedWantedEvicted,
    2201              :     InitWithoutDownload,
    2202              :     PermanentLoadingFailure,
    2203              :     EvictedWithWaiters,
    2204              : }
    2205              : 
    2206              : impl RareEvent {
    2207          252 :     fn as_str(&self) -> &'static str {
    2208          252 :         use RareEvent::*;
    2209          252 : 
    2210          252 :         match self {
    2211           36 :             RemoveOnDropFailed => "remove_on_drop_failed",
    2212           36 :             InitCompletedWithoutRequester => "init_completed_without",
    2213           36 :             DownloadFailedWithoutRequester => "download_failed_without",
    2214           36 :             UpgradedWantedEvicted => "raced_wanted_evicted",
    2215           36 :             InitWithoutDownload => "init_needed_no_download",
    2216           36 :             PermanentLoadingFailure => "permanent_loading_failure",
    2217           36 :             EvictedWithWaiters => "evicted_with_waiters",
    2218              :         }
    2219          252 :     }
    2220              : }
    2221              : 
    2222              : pub(crate) static LAYER_IMPL_METRICS: once_cell::sync::Lazy<LayerImplMetrics> =
    2223              :     once_cell::sync::Lazy::new(LayerImplMetrics::default);
        

Generated by: LCOV version 2.1-beta