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

Generated by: LCOV version 2.1-beta