LCOV - code coverage report
Current view: top level - pageserver/src/tenant/storage_layer - layer.rs (source / functions) Coverage Total Hit
Test: 6df3fc19ec669bcfbbf9aba41d1338898d24eaa0.info Lines: 78.2 % 1319 1031
Test Date: 2025-03-12 18:28:53 Functions: 79.2 % 144 114

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

Generated by: LCOV version 2.1-beta