LCOV - code coverage report
Current view: top level - pageserver/src/tenant/storage_layer - layer.rs (source / functions) Coverage Total Hit
Test: 65975feb441523e1ae5866ecbec0610188cb8ce3.info Lines: 78.4 % 1308 1025
Test Date: 2025-02-12 20:31:43 Functions: 79.0 % 143 113

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

Generated by: LCOV version 2.1-beta