LCOV - code coverage report
Current view: top level - pageserver/src/tenant/storage_layer - layer.rs (source / functions) Coverage Total Hit
Test: 86c536b7fe84b2afe03c3bb264199e9c319ae0f8.info Lines: 79.2 % 1286 1018
Test Date: 2024-06-24 16:38:41 Functions: 76.9 % 156 120

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

Generated by: LCOV version 2.1-beta