LCOV - code coverage report
Current view: top level - pageserver/src/tenant - storage_layer.rs (source / functions) Coverage Total Hit
Test: 472031e0b71f3195f7f21b1f2b20de09fd07bb56.info Lines: 85.2 % 569 485
Test Date: 2025-05-26 10:37:33 Functions: 79.1 % 86 68

            Line data    Source code
       1              : //! Common traits and structs for layers
       2              : 
       3              : pub mod batch_split_writer;
       4              : pub mod delta_layer;
       5              : pub mod errors;
       6              : pub mod filter_iterator;
       7              : pub mod image_layer;
       8              : pub mod inmemory_layer;
       9              : pub(crate) mod layer;
      10              : mod layer_desc;
      11              : mod layer_name;
      12              : pub mod merge_iterator;
      13              : 
      14              : use std::cmp::Ordering;
      15              : use std::collections::hash_map::Entry;
      16              : use std::collections::{BinaryHeap, HashMap};
      17              : use std::ops::Range;
      18              : use std::pin::Pin;
      19              : use std::sync::Arc;
      20              : use std::sync::atomic::AtomicUsize;
      21              : use std::time::{Duration, SystemTime, UNIX_EPOCH};
      22              : 
      23              : use crate::PERF_TRACE_TARGET;
      24              : pub use batch_split_writer::{BatchLayerWriter, SplitDeltaLayerWriter, SplitImageLayerWriter};
      25              : use bytes::Bytes;
      26              : pub use delta_layer::{DeltaLayer, DeltaLayerWriter, ValueRef};
      27              : use futures::StreamExt;
      28              : use futures::stream::FuturesUnordered;
      29              : pub use image_layer::{ImageLayer, ImageLayerWriter};
      30              : pub use inmemory_layer::InMemoryLayer;
      31              : pub(crate) use layer::{EvictionError, Layer, ResidentLayer};
      32              : pub use layer_desc::{PersistentLayerDesc, PersistentLayerKey};
      33              : pub use layer_name::{DeltaLayerName, ImageLayerName, LayerName};
      34              : use pageserver_api::config::GetVectoredConcurrentIo;
      35              : use pageserver_api::key::Key;
      36              : use pageserver_api::keyspace::{KeySpace, KeySpaceRandomAccum};
      37              : use pageserver_api::record::NeonWalRecord;
      38              : use pageserver_api::value::Value;
      39              : use tracing::{Instrument, info_span, trace};
      40              : use utils::lsn::Lsn;
      41              : use utils::sync::gate::GateGuard;
      42              : 
      43              : use self::inmemory_layer::InMemoryLayerFileId;
      44              : use super::PageReconstructError;
      45              : use super::layer_map::InMemoryLayerDesc;
      46              : use super::timeline::{GetVectoredError, ReadPath};
      47              : use crate::context::{
      48              :     AccessStatsBehavior, PerfInstrumentFutureExt, RequestContext, RequestContextBuilder,
      49              : };
      50              : 
      51            0 : pub fn range_overlaps<T>(a: &Range<T>, b: &Range<T>) -> bool
      52            0 : where
      53            0 :     T: PartialOrd<T>,
      54            0 : {
      55            0 :     if a.start < b.start {
      56            0 :         a.end > b.start
      57              :     } else {
      58            0 :         b.end > a.start
      59              :     }
      60            0 : }
      61              : 
      62              : /// Struct used to communicate across calls to 'get_value_reconstruct_data'.
      63              : ///
      64              : /// Before first call, you can fill in 'page_img' if you have an older cached
      65              : /// version of the page available. That can save work in
      66              : /// 'get_value_reconstruct_data', as it can stop searching for page versions
      67              : /// when all the WAL records going back to the cached image have been collected.
      68              : ///
      69              : /// When get_value_reconstruct_data returns Complete, 'img' is set to an image
      70              : /// of the page, or the oldest WAL record in 'records' is a will_init-type
      71              : /// record that initializes the page without requiring a previous image.
      72              : ///
      73              : /// If 'get_page_reconstruct_data' returns Continue, some 'records' may have
      74              : /// been collected, but there are more records outside the current layer. Pass
      75              : /// the same ValueReconstructState struct in the next 'get_value_reconstruct_data'
      76              : /// call, to collect more records.
      77              : ///
      78              : #[derive(Debug, Default)]
      79              : pub(crate) struct ValueReconstructState {
      80              :     pub(crate) records: Vec<(Lsn, NeonWalRecord)>,
      81              :     pub(crate) img: Option<(Lsn, Bytes)>,
      82              : }
      83              : 
      84              : impl ValueReconstructState {
      85              :     /// Returns the number of page deltas applied to the page image.
      86       727038 :     pub fn num_deltas(&self) -> usize {
      87       727038 :         match self.img {
      88       699570 :             Some(_) => self.records.len(),
      89        27468 :             None => self.records.len() - 1, // omit will_init record
      90              :         }
      91       727038 :     }
      92              : }
      93              : 
      94              : #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
      95              : pub(crate) enum ValueReconstructSituation {
      96              :     Complete,
      97              :     #[default]
      98              :     Continue,
      99              : }
     100              : 
     101              : /// On disk representation of a value loaded in a buffer
     102              : #[derive(Debug)]
     103              : pub(crate) enum OnDiskValue {
     104              :     /// Unencoded [`Value::Image`]
     105              :     RawImage(Bytes),
     106              :     /// Encoded [`Value`]. Can deserialize into an image or a WAL record
     107              :     WalRecordOrImage(Bytes),
     108              : }
     109              : 
     110              : /// Reconstruct data accumulated for a single key during a vectored get
     111              : #[derive(Debug, Default)]
     112              : pub(crate) struct VectoredValueReconstructState {
     113              :     pub(crate) on_disk_values: Vec<(Lsn, OnDiskValueIoWaiter)>,
     114              : 
     115              :     pub(crate) situation: ValueReconstructSituation,
     116              : }
     117              : 
     118              : #[derive(Debug)]
     119              : pub(crate) struct OnDiskValueIoWaiter {
     120              :     rx: tokio::sync::oneshot::Receiver<OnDiskValueIoResult>,
     121              : }
     122              : 
     123              : #[derive(Debug)]
     124              : #[must_use]
     125              : pub(crate) enum OnDiskValueIo {
     126              :     /// Traversal identified this IO as required to complete the vectored get.
     127              :     Required {
     128              :         num_active_ios: Arc<AtomicUsize>,
     129              :         tx: tokio::sync::oneshot::Sender<OnDiskValueIoResult>,
     130              :     },
     131              :     /// Sparse keyspace reads always read all the values for a given key,
     132              :     /// even though only the first value is needed.
     133              :     ///
     134              :     /// This variant represents the unnecessary IOs for those values at lower LSNs
     135              :     /// that aren't needed, but are currently still being done.
     136              :     ///
     137              :     /// The execution of unnecessary IOs was a pre-existing behavior before concurrent IO.
     138              :     /// We added this explicit representation here so that we can drop
     139              :     /// unnecessary IO results immediately, instead of buffering them in
     140              :     /// `oneshot` channels inside [`VectoredValueReconstructState`] until
     141              :     /// [`VectoredValueReconstructState::collect_pending_ios`] gets called.
     142              :     Unnecessary,
     143              : }
     144              : 
     145              : type OnDiskValueIoResult = Result<OnDiskValue, std::io::Error>;
     146              : 
     147              : impl OnDiskValueIo {
     148      1789070 :     pub(crate) fn complete(self, res: OnDiskValueIoResult) {
     149      1789070 :         match self {
     150      1753075 :             OnDiskValueIo::Required { num_active_ios, tx } => {
     151      1753075 :                 num_active_ios.fetch_sub(1, std::sync::atomic::Ordering::Release);
     152      1753075 :                 let _ = tx.send(res);
     153      1753075 :             }
     154        35995 :             OnDiskValueIo::Unnecessary => {
     155        35995 :                 // Nobody cared, see variant doc comment.
     156        35995 :             }
     157              :         }
     158      1789070 :     }
     159              : }
     160              : 
     161              : #[derive(Debug, thiserror::Error)]
     162              : pub(crate) enum WaitCompletionError {
     163              :     #[error("OnDiskValueIo was dropped without completing, likely the sidecar task panicked")]
     164              :     IoDropped,
     165              : }
     166              : 
     167              : impl OnDiskValueIoWaiter {
     168      1753074 :     pub(crate) async fn wait_completion(self) -> Result<OnDiskValueIoResult, WaitCompletionError> {
     169      1753074 :         // NB: for Unnecessary IOs, this method never gets called because we don't add them to `on_disk_values`.
     170      1753074 :         self.rx.await.map_err(|_| WaitCompletionError::IoDropped)
     171      1753074 :     }
     172              : }
     173              : 
     174              : impl VectoredValueReconstructState {
     175              :     /// # Cancel-Safety
     176              :     ///
     177              :     /// Technically fine to stop polling this future, but, the IOs will still
     178              :     /// be executed to completion by the sidecar task and hold on to / consume resources.
     179              :     /// Better not do it to make reasonsing about the system easier.
     180       363554 :     pub(crate) async fn collect_pending_ios(
     181       363554 :         self,
     182       363554 :     ) -> Result<ValueReconstructState, PageReconstructError> {
     183              :         use utils::bin_ser::BeSer;
     184              : 
     185       363554 :         let mut res = Ok(ValueReconstructState::default());
     186              : 
     187              :         // We should try hard not to bail early, so that by the time we return from this
     188              :         // function, all IO for this value is done. It's not required -- we could totally
     189              :         // stop polling the IO futures in the sidecar task, they need to support that,
     190              :         // but just stopping to poll doesn't reduce the IO load on the disk. It's easier
     191              :         // to reason about the system if we just wait for all IO to complete, even if
     192              :         // we're no longer interested in the result.
     193              :         //
     194              :         // Revisit this when IO futures are replaced with a more sophisticated IO system
     195              :         // and an IO scheduler, where we know which IOs were submitted and which ones
     196              :         // just queued. Cf the comment on IoConcurrency::spawn_io.
     197      2116628 :         for (lsn, waiter) in self.on_disk_values {
     198      1753074 :             let value_recv_res = waiter
     199      1753074 :                 .wait_completion()
     200      1753074 :                 // we rely on the caller to poll us to completion, so this is not a bail point
     201      1753074 :                 .await;
     202              :             // Force not bailing early by wrapping the code into a closure.
     203              :             #[allow(clippy::redundant_closure_call)]
     204      1753074 :             let _: () = (|| {
     205      1753074 :                 match (&mut res, value_recv_res) {
     206            0 :                     (Err(_), _) => {
     207            0 :                         // We've already failed, no need to process more.
     208            0 :                     }
     209            0 :                     (Ok(_), Err(wait_err)) => {
     210            0 :                         // This shouldn't happen - likely the sidecar task panicked.
     211            0 :                         res = Err(PageReconstructError::Other(wait_err.into()));
     212            0 :                     }
     213            0 :                     (Ok(_), Ok(Err(err))) => {
     214            0 :                         let err: std::io::Error = err;
     215            0 :                         // TODO: returning IO error here will fail a compute query.
     216            0 :                         // Probably not what we want, we're not doing `maybe_fatal_err`
     217            0 :                         // in the IO futures.
     218            0 :                         // But it's been like that for a long time, not changing it
     219            0 :                         // as part of concurrent IO.
     220            0 :                         // => https://github.com/neondatabase/neon/issues/10454
     221            0 :                         res = Err(PageReconstructError::Other(err.into()));
     222            0 :                     }
     223        27888 :                     (Ok(ok), Ok(Ok(OnDiskValue::RawImage(img)))) => {
     224        27888 :                         assert!(ok.img.is_none());
     225        27888 :                         ok.img = Some((lsn, img));
     226              :                     }
     227      1725186 :                     (Ok(ok), Ok(Ok(OnDiskValue::WalRecordOrImage(buf)))) => {
     228      1725186 :                         match Value::des(&buf) {
     229      1403254 :                             Ok(Value::WalRecord(rec)) => {
     230      1403254 :                                 ok.records.push((lsn, rec));
     231      1403254 :                             }
     232       321932 :                             Ok(Value::Image(img)) => {
     233       321932 :                                 assert!(ok.img.is_none());
     234       321932 :                                 ok.img = Some((lsn, img));
     235              :                             }
     236            0 :                             Err(err) => {
     237            0 :                                 res = Err(PageReconstructError::Other(err.into()));
     238            0 :                             }
     239              :                         }
     240              :                     }
     241              :                 }
     242      1753074 :             })();
     243      1753074 :         }
     244              : 
     245       363554 :         res
     246       363554 :     }
     247              : }
     248              : 
     249              : /// Bag of data accumulated during a vectored get..
     250              : pub(crate) struct ValuesReconstructState {
     251              :     /// The keys will be removed after `get_vectored` completes. The caller outside `Timeline`
     252              :     /// should not expect to get anything from this hashmap.
     253              :     pub(crate) keys: HashMap<Key, VectoredValueReconstructState>,
     254              :     /// The keys which are already retrieved
     255              :     keys_done: KeySpaceRandomAccum,
     256              : 
     257              :     /// The keys covered by the image layers
     258              :     keys_with_image_coverage: Option<Range<Key>>,
     259              : 
     260              :     // Statistics that are still accessible as a caller of `get_vectored_impl`.
     261              :     layers_visited: u32,
     262              :     delta_layers_visited: u32,
     263              : 
     264              :     pub(crate) io_concurrency: IoConcurrency,
     265              :     num_active_ios: Arc<AtomicUsize>,
     266              : 
     267              :     pub(crate) read_path: Option<ReadPath>,
     268              : }
     269              : 
     270              : /// The level of IO concurrency to be used on the read path
     271              : ///
     272              : /// The desired end state is that we always do parallel IO.
     273              : /// This struct and the dispatching in the impl will be removed once
     274              : /// we've built enough confidence.
     275              : pub(crate) enum IoConcurrency {
     276              :     Sequential,
     277              :     SidecarTask {
     278              :         task_id: usize,
     279              :         ios_tx: tokio::sync::mpsc::UnboundedSender<IoFuture>,
     280              :     },
     281              : }
     282              : 
     283              : type IoFuture = Pin<Box<dyn Send + Future<Output = ()>>>;
     284              : 
     285              : pub(crate) enum SelectedIoConcurrency {
     286              :     Sequential,
     287              :     SidecarTask(GateGuard),
     288              : }
     289              : 
     290              : impl std::fmt::Debug for IoConcurrency {
     291            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     292            0 :         match self {
     293            0 :             IoConcurrency::Sequential => write!(f, "Sequential"),
     294            0 :             IoConcurrency::SidecarTask { .. } => write!(f, "SidecarTask"),
     295              :         }
     296            0 :     }
     297              : }
     298              : 
     299              : impl std::fmt::Debug for SelectedIoConcurrency {
     300           17 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     301           17 :         match self {
     302            0 :             SelectedIoConcurrency::Sequential => write!(f, "Sequential"),
     303           17 :             SelectedIoConcurrency::SidecarTask(_) => write!(f, "SidecarTask"),
     304              :         }
     305           17 :     }
     306              : }
     307              : 
     308              : impl IoConcurrency {
     309              :     /// Force sequential IO. This is a temporary workaround until we have
     310              :     /// moved plumbing-through-the-call-stack
     311              :     /// of IoConcurrency into `RequestContextq.
     312              :     ///
     313              :     /// DO NOT USE for new code.
     314              :     ///
     315              :     /// Tracking issue: <https://github.com/neondatabase/neon/issues/10460>.
     316       301276 :     pub(crate) fn sequential() -> Self {
     317       301276 :         Self::spawn(SelectedIoConcurrency::Sequential)
     318       301276 :     }
     319              : 
     320          267 :     pub(crate) fn spawn_from_conf(
     321          267 :         conf: GetVectoredConcurrentIo,
     322          267 :         gate_guard: GateGuard,
     323          267 :     ) -> IoConcurrency {
     324          267 :         let selected = match conf {
     325            0 :             GetVectoredConcurrentIo::Sequential => SelectedIoConcurrency::Sequential,
     326          267 :             GetVectoredConcurrentIo::SidecarTask => SelectedIoConcurrency::SidecarTask(gate_guard),
     327              :         };
     328          267 :         Self::spawn(selected)
     329          267 :     }
     330              : 
     331       301560 :     pub(crate) fn spawn(io_concurrency: SelectedIoConcurrency) -> Self {
     332       301560 :         match io_concurrency {
     333       301276 :             SelectedIoConcurrency::Sequential => IoConcurrency::Sequential,
     334          284 :             SelectedIoConcurrency::SidecarTask(gate_guard) => {
     335          284 :                 let (ios_tx, ios_rx) = tokio::sync::mpsc::unbounded_channel();
     336              :                 static TASK_ID: AtomicUsize = AtomicUsize::new(0);
     337          284 :                 let task_id = TASK_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     338              :                 // TODO: enrich the span with more context (tenant,shard,timeline) + (basebackup|pagestream|...)
     339          284 :                 let span =
     340          284 :                     tracing::info_span!(parent: None, "IoConcurrency_sidecar", task_id = task_id);
     341          284 :                 trace!(task_id, "spawning sidecar task");
     342          284 :                 tokio::spawn(async move {
     343          283 :                     trace!("start");
     344          283 :                     scopeguard::defer!{ trace!("end") };
     345              :                     type IosRx = tokio::sync::mpsc::UnboundedReceiver<IoFuture>;
     346              :                     enum State {
     347              :                         Waiting {
     348              :                             // invariant: is_empty(), but we recycle the allocation
     349              :                             empty_futures: FuturesUnordered<IoFuture>,
     350              :                             ios_rx: IosRx,
     351              :                         },
     352              :                         Executing {
     353              :                             futures: FuturesUnordered<IoFuture>,
     354              :                             ios_rx: IosRx,
     355              :                         },
     356              :                         ShuttingDown {
     357              :                             futures: FuturesUnordered<IoFuture>,
     358              :                         },
     359              :                     }
     360          283 :                     let mut state = State::Waiting {
     361          283 :                         empty_futures: FuturesUnordered::new(),
     362          283 :                         ios_rx,
     363          283 :                     };
     364              :                     loop {
     365        23688 :                         match state {
     366              :                             State::Waiting {
     367        10301 :                                 empty_futures,
     368        10301 :                                 mut ios_rx,
     369        10301 :                             } => {
     370        10301 :                                 assert!(empty_futures.is_empty());
     371        10301 :                                 tokio::select! {
     372        10301 :                                     fut = ios_rx.recv() => {
     373        10282 :                                         if let Some(fut) = fut {
     374        10081 :                                             trace!("received new io future");
     375        10081 :                                             empty_futures.push(fut);
     376        10081 :                                             state = State::Executing { futures: empty_futures, ios_rx };
     377              :                                         } else {
     378          201 :                                             state = State::ShuttingDown { futures: empty_futures }
     379              :                                         }
     380              :                                     }
     381              :                                 }
     382              :                             }
     383              :                             State::Executing {
     384        13123 :                                 mut futures,
     385        13123 :                                 mut ios_rx,
     386        13123 :                             } => {
     387        13123 :                                 tokio::select! {
     388        13123 :                                     res = futures.next() => {
     389        11539 :                                         trace!("io future completed");
     390        11539 :                                         assert!(res.is_some());
     391        11539 :                                         if futures.is_empty() {
     392        10018 :                                             state = State::Waiting { empty_futures: futures, ios_rx};
     393        10018 :                                         } else {
     394         1521 :                                             state = State::Executing { futures, ios_rx };
     395         1521 :                                         }
     396              :                                     }
     397        13123 :                                     fut = ios_rx.recv() => {
     398         1584 :                                         if let Some(fut) = fut {
     399         1521 :                                             trace!("received new io future");
     400         1521 :                                             futures.push(fut);
     401         1521 :                                             state =  State::Executing { futures, ios_rx};
     402           63 :                                         } else {
     403           63 :                                             state = State::ShuttingDown { futures };
     404           63 :                                         }
     405              :                                     }
     406              :                                 }
     407              :                             }
     408              :                             State::ShuttingDown {
     409          264 :                                 mut futures,
     410          264 :                             } => {
     411          264 :                                 trace!("shutting down");
     412          327 :                                 while let Some(()) = futures.next().await {
     413           63 :                                     trace!("io future completed (shutdown)");
     414              :                                     // drain
     415              :                                 }
     416          264 :                                 trace!("shutdown complete");
     417          264 :                                 break;
     418          264 :                             }
     419          264 :                         }
     420          264 :                     }
     421          264 :                     drop(gate_guard); // drop it right before we exit
     422          284 :                 }.instrument(span));
     423          284 :                 IoConcurrency::SidecarTask { task_id, ios_tx }
     424              :             }
     425              :         }
     426       301560 :     }
     427              : 
     428        19129 :     pub(crate) fn clone(&self) -> Self {
     429        19129 :         match self {
     430            0 :             IoConcurrency::Sequential => IoConcurrency::Sequential,
     431        19129 :             IoConcurrency::SidecarTask { task_id, ios_tx } => IoConcurrency::SidecarTask {
     432        19129 :                 task_id: *task_id,
     433        19129 :                 ios_tx: ios_tx.clone(),
     434        19129 :             },
     435              :         }
     436        19129 :     }
     437              : 
     438              :     /// Submit an IO to be executed in the background. DEADLOCK RISK, read the full doc string.
     439              :     ///
     440              :     /// The IO is represented as an opaque future.
     441              :     /// IO completion must be handled inside the future, e.g., through a oneshot channel.
     442              :     ///
     443              :     /// The API seems simple but there are multiple **pitfalls** involving
     444              :     /// DEADLOCK RISK.
     445              :     ///
     446              :     /// First, there are no guarantees about the exexecution of the IO.
     447              :     /// It may be `await`ed in-place before this function returns.
     448              :     /// It may be polled partially by this task and handed off to another task to be finished.
     449              :     /// It may be polled and then dropped before returning ready.
     450              :     ///
     451              :     /// This means that submitted IOs must not be interedependent.
     452              :     /// Interdependence may be through shared limited resources, e.g.,
     453              :     /// - VirtualFile file descriptor cache slot acquisition
     454              :     /// - tokio-epoll-uring slot
     455              :     ///
     456              :     /// # Why current usage is safe from deadlocks
     457              :     ///
     458              :     /// Textbook condition for a deadlock is that _all_ of the following be given
     459              :     /// - Mutual exclusion
     460              :     /// - Hold and wait
     461              :     /// - No preemption
     462              :     /// - Circular wait
     463              :     ///
     464              :     /// The current usage is safe because:
     465              :     /// - Mutual exclusion: IO futures definitely use mutexes, no way around that for now
     466              :     /// - Hold and wait: IO futures currently hold two kinds of locks/resources while waiting
     467              :     ///   for acquisition of other resources:
     468              :     ///    - VirtualFile file descriptor cache slot tokio mutex
     469              :     ///    - tokio-epoll-uring slot (uses tokio notify => wait queue, much like mutex)
     470              :     /// - No preemption: there's no taking-away of acquired locks/resources => given
     471              :     /// - Circular wait: this is the part of the condition that isn't met: all IO futures
     472              :     ///   first acquire VirtualFile mutex, then tokio-epoll-uring slot.
     473              :     ///   There is no IO future that acquires slot before VirtualFile.
     474              :     ///   Hence there can be no circular waiting.
     475              :     ///   Hence there cannot be a deadlock.
     476              :     ///
     477              :     /// This is a very fragile situation and must be revisited whenver any code called from
     478              :     /// inside the IO futures is changed.
     479              :     ///
     480              :     /// We will move away from opaque IO futures towards well-defined IOs at some point in
     481              :     /// the future when we have shipped this first version of concurrent IO to production
     482              :     /// and are ready to retire the Sequential mode which runs the futures in place.
     483              :     /// Right now, while brittle, the opaque IO approach allows us to ship the feature
     484              :     /// with minimal changes to the code and minimal changes to existing behavior in Sequential mode.
     485              :     ///
     486              :     /// Also read the comment in `collect_pending_ios`.
     487       409694 :     pub(crate) async fn spawn_io<F>(&mut self, fut: F)
     488       409694 :     where
     489       409694 :         F: std::future::Future<Output = ()> + Send + 'static,
     490       409694 :     {
     491       409694 :         match self {
     492       398092 :             IoConcurrency::Sequential => fut.await,
     493        11602 :             IoConcurrency::SidecarTask { ios_tx, .. } => {
     494        11602 :                 let fut = Box::pin(fut);
     495        11602 :                 // NB: experiments showed that doing an opportunistic poll of `fut` here was bad for throughput
     496        11602 :                 // while insignificant for latency.
     497        11602 :                 // It would make sense to revisit the tokio-epoll-uring API in the future such that we can try
     498        11602 :                 // a submission here, but never poll the future. That way, io_uring can make proccess while
     499        11602 :                 // the future sits in the ios_tx queue.
     500        11602 :                 match ios_tx.send(fut) {
     501        11602 :                     Ok(()) => {}
     502              :                     Err(_) => {
     503            0 :                         unreachable!("the io task must have exited, likely it panicked")
     504              :                     }
     505              :                 }
     506              :             }
     507              :         }
     508       409694 :     }
     509              : 
     510              :     #[cfg(test)]
     511           17 :     pub(crate) fn spawn_for_test() -> impl std::ops::DerefMut<Target = Self> {
     512              :         use std::ops::{Deref, DerefMut};
     513              : 
     514              :         use tracing::info;
     515              :         use utils::sync::gate::Gate;
     516              : 
     517              :         // Spawn needs a Gate, give it one.
     518              :         struct Wrapper {
     519              :             inner: IoConcurrency,
     520              :             #[allow(dead_code)]
     521              :             gate: Box<Gate>,
     522              :         }
     523              :         impl Deref for Wrapper {
     524              :             type Target = IoConcurrency;
     525              : 
     526         9246 :             fn deref(&self) -> &Self::Target {
     527         9246 :                 &self.inner
     528         9246 :             }
     529              :         }
     530              :         impl DerefMut for Wrapper {
     531            0 :             fn deref_mut(&mut self) -> &mut Self::Target {
     532            0 :                 &mut self.inner
     533            0 :             }
     534              :         }
     535           17 :         let gate = Box::new(Gate::default());
     536              : 
     537              :         // The default behavior when running Rust unit tests without any further
     538              :         // flags is to use the new behavior.
     539              :         // The CI uses the following environment variable to unit test both old
     540              :         // and new behavior.
     541              :         // NB: the Python regression & perf tests take the `else` branch
     542              :         // below and have their own defaults management.
     543           17 :         let selected = {
     544              :             // The pageserver_api::config type is unsuitable because it's internally tagged.
     545            0 :             #[derive(serde::Deserialize)]
     546              :             #[serde(rename_all = "kebab-case")]
     547              :             enum TestOverride {
     548              :                 Sequential,
     549              :                 SidecarTask,
     550              :             }
     551              :             use once_cell::sync::Lazy;
     552           17 :             static TEST_OVERRIDE: Lazy<TestOverride> = Lazy::new(|| {
     553           17 :                 utils::env::var_serde_json_string(
     554           17 :                     "NEON_PAGESERVER_UNIT_TEST_GET_VECTORED_CONCURRENT_IO",
     555           17 :                 )
     556           17 :                 .unwrap_or(TestOverride::SidecarTask)
     557           17 :             });
     558              : 
     559           17 :             match *TEST_OVERRIDE {
     560            0 :                 TestOverride::Sequential => SelectedIoConcurrency::Sequential,
     561              :                 TestOverride::SidecarTask => {
     562           17 :                     SelectedIoConcurrency::SidecarTask(gate.enter().expect("just created it"))
     563              :                 }
     564              :             }
     565              :         };
     566              : 
     567           17 :         info!(?selected, "get_vectored_concurrent_io test");
     568              : 
     569           17 :         Wrapper {
     570           17 :             inner: Self::spawn(selected),
     571           17 :             gate,
     572           17 :         }
     573           17 :     }
     574              : }
     575              : 
     576              : /// Make noise in case the [`ValuesReconstructState`] gets dropped while
     577              : /// there are still IOs in flight.
     578              : /// Refer to `collect_pending_ios` for why we prefer not to do that.
     579              : //
     580              : /// We log from here instead of from the sidecar task because the [`ValuesReconstructState`]
     581              : /// gets dropped in a tracing span with more context.
     582              : /// We repeat the sidecar tasks's `task_id` so we can correlate what we emit here with
     583              : /// the logs / panic handler logs from the sidecar task, which also logs the `task_id`.
     584              : impl Drop for ValuesReconstructState {
     585       312355 :     fn drop(&mut self) {
     586       312355 :         let num_active_ios = self
     587       312355 :             .num_active_ios
     588       312355 :             .load(std::sync::atomic::Ordering::Acquire);
     589       312355 :         if num_active_ios == 0 {
     590       312354 :             return;
     591            1 :         }
     592            1 :         let sidecar_task_id = match &self.io_concurrency {
     593            0 :             IoConcurrency::Sequential => None,
     594            1 :             IoConcurrency::SidecarTask { task_id, .. } => Some(*task_id),
     595              :         };
     596            1 :         tracing::warn!(
     597              :             num_active_ios,
     598              :             ?sidecar_task_id,
     599            0 :             backtrace=%std::backtrace::Backtrace::force_capture(),
     600            0 :             "dropping ValuesReconstructState while some IOs have not been completed",
     601              :         );
     602       312355 :     }
     603              : }
     604              : 
     605              : impl ValuesReconstructState {
     606       312355 :     pub(crate) fn new(io_concurrency: IoConcurrency) -> Self {
     607       312355 :         Self {
     608       312355 :             keys: HashMap::new(),
     609       312355 :             keys_done: KeySpaceRandomAccum::new(),
     610       312355 :             keys_with_image_coverage: None,
     611       312355 :             layers_visited: 0,
     612       312355 :             delta_layers_visited: 0,
     613       312355 :             io_concurrency,
     614       312355 :             num_active_ios: Arc::new(AtomicUsize::new(0)),
     615       312355 :             read_path: None,
     616       312355 :         }
     617       312355 :     }
     618              : 
     619              :     /// Absolutely read [`IoConcurrency::spawn_io`] to learn about assumptions & pitfalls.
     620       409694 :     pub(crate) async fn spawn_io<F>(&mut self, fut: F)
     621       409694 :     where
     622       409694 :         F: std::future::Future<Output = ()> + Send + 'static,
     623       409694 :     {
     624       409694 :         self.io_concurrency.spawn_io(fut).await;
     625       409694 :     }
     626              : 
     627       440597 :     pub(crate) fn on_layer_visited(&mut self, layer: &ReadableLayer) {
     628       440597 :         self.layers_visited += 1;
     629       440597 :         if let ReadableLayer::PersistentLayer(layer) = layer {
     630       133393 :             if layer.layer_desc().is_delta() {
     631       118273 :                 self.delta_layers_visited += 1;
     632       118273 :             }
     633       307204 :         }
     634       440597 :     }
     635              : 
     636          121 :     pub(crate) fn get_delta_layers_visited(&self) -> u32 {
     637          121 :         self.delta_layers_visited
     638          121 :     }
     639              : 
     640       312340 :     pub(crate) fn get_layers_visited(&self) -> u32 {
     641       312340 :         self.layers_visited
     642       312340 :     }
     643              : 
     644              :     /// On hitting image layer, we can mark all keys in this range as done, because
     645              :     /// if the image layer does not contain a key, it is deleted/never added.
     646        15126 :     pub(crate) fn on_image_layer_visited(&mut self, key_range: &Range<Key>) {
     647        15126 :         let prev_val = self.keys_with_image_coverage.replace(key_range.clone());
     648        15126 :         assert_eq!(
     649              :             prev_val, None,
     650            0 :             "should consume the keyspace before the next iteration"
     651              :         );
     652        15126 :     }
     653              : 
     654              :     /// Update the state collected for a given key.
     655              :     /// Returns true if this was the last value needed for the key and false otherwise.
     656              :     ///
     657              :     /// If the key is done after the update, mark it as such.
     658              :     ///
     659              :     /// If the key is in the sparse keyspace (i.e., aux files), we do not track them in
     660              :     /// `key_done`.
     661              :     // TODO: rename this method & update description.
     662      1789070 :     pub(crate) fn update_key(&mut self, key: &Key, lsn: Lsn, completes: bool) -> OnDiskValueIo {
     663      1789070 :         let state = self.keys.entry(*key).or_default();
     664      1789070 : 
     665      1789070 :         let is_sparse_key = key.is_sparse();
     666              : 
     667      1789070 :         let required_io = match state.situation {
     668              :             ValueReconstructSituation::Complete => {
     669        35995 :                 if is_sparse_key {
     670              :                     // Sparse keyspace might be visited multiple times because
     671              :                     // we don't track unmapped keyspaces.
     672        35995 :                     return OnDiskValueIo::Unnecessary;
     673              :                 } else {
     674            0 :                     unreachable!()
     675              :                 }
     676              :             }
     677              :             ValueReconstructSituation::Continue => {
     678      1753075 :                 self.num_active_ios
     679      1753075 :                     .fetch_add(1, std::sync::atomic::Ordering::Release);
     680      1753075 :                 let (tx, rx) = tokio::sync::oneshot::channel();
     681      1753075 :                 state.on_disk_values.push((lsn, OnDiskValueIoWaiter { rx }));
     682      1753075 :                 OnDiskValueIo::Required {
     683      1753075 :                     tx,
     684      1753075 :                     num_active_ios: Arc::clone(&self.num_active_ios),
     685      1753075 :                 }
     686      1753075 :             }
     687      1753075 :         };
     688      1753075 : 
     689      1753075 :         if completes && state.situation == ValueReconstructSituation::Continue {
     690       363555 :             state.situation = ValueReconstructSituation::Complete;
     691       363555 :             if !is_sparse_key {
     692       331669 :                 self.keys_done.add_key(*key);
     693       331669 :             }
     694      1389520 :         }
     695              : 
     696      1753075 :         required_io
     697      1789070 :     }
     698              : 
     699              :     /// Returns the key space describing the keys that have
     700              :     /// been marked as completed since the last call to this function.
     701              :     /// Returns individual keys done, and the image layer coverage.
     702       440597 :     pub(crate) fn consume_done_keys(&mut self) -> (KeySpace, Option<Range<Key>>) {
     703       440597 :         (
     704       440597 :             self.keys_done.consume_keyspace(),
     705       440597 :             self.keys_with_image_coverage.take(),
     706       440597 :         )
     707       440597 :     }
     708              : }
     709              : 
     710              : /// A key that uniquely identifies a layer in a timeline
     711              : #[derive(Debug, PartialEq, Eq, Clone, Hash)]
     712              : pub(crate) enum LayerId {
     713              :     PersitentLayerId(PersistentLayerKey),
     714              :     InMemoryLayerId(InMemoryLayerFileId),
     715              : }
     716              : 
     717              : /// Uniquely identify a layer visit by the layer
     718              : /// and LSN range of the reads. Note that the end of the range is exclusive.
     719              : ///
     720              : /// The layer itself is not enough since we may have different LSN lower
     721              : /// bounds for delta layer reads. Scenarios where this can happen are:
     722              : ///
     723              : /// 1. Layer overlaps: imagine an image layer inside and in-memory layer
     724              : ///    and a query that only partially hits the image layer. Part of the query
     725              : ///    needs to read the whole in-memory layer and the other part needs to read
     726              : ///    only up to the image layer. Hence, they'll have different LSN floor values
     727              : ///    for the read.
     728              : ///
     729              : /// 2. Scattered reads: the read path supports starting at different LSNs. Imagine
     730              : ///    The start LSN for one range is inside a layer and the start LSN for another range
     731              : ///    Is above the layer (includes all of it). Both ranges need to read the layer all the
     732              : ///    Way to the end but starting at different points. Hence, they'll have different LSN
     733              : ///    Ceil values.
     734              : ///
     735              : /// The implication is that we might visit the same layer multiple times
     736              : /// in order to read different LSN ranges from it. In practice, this isn't very concerning
     737              : /// because:
     738              : /// 1. Layer overlaps are rare and generally not intended
     739              : /// 2. Scattered reads will stabilise after the first few layers provided their starting LSNs
     740              : ///    are grouped tightly enough (likely the case).
     741              : #[derive(Debug, PartialEq, Eq, Clone, Hash)]
     742              : struct LayerToVisitId {
     743              :     layer_id: LayerId,
     744              :     lsn_floor: Lsn,
     745              :     lsn_ceil: Lsn,
     746              : }
     747              : 
     748              : #[derive(Debug, PartialEq, Eq, Hash)]
     749              : pub enum ReadableLayerWeak {
     750              :     PersistentLayer(Arc<PersistentLayerDesc>),
     751              :     InMemoryLayer(InMemoryLayerDesc),
     752              : }
     753              : 
     754              : /// Layer wrapper for the read path. Note that it is valid
     755              : /// to use these layers even after external operations have
     756              : /// been performed on them (compaction, freeze, etc.).
     757              : #[derive(Debug)]
     758              : pub(crate) enum ReadableLayer {
     759              :     PersistentLayer(Layer),
     760              :     InMemoryLayer(Arc<InMemoryLayer>),
     761              : }
     762              : 
     763              : /// A partial description of a read to be done.
     764              : #[derive(Debug, Clone)]
     765              : struct LayerVisit {
     766              :     /// An id used to resolve the readable layer within the fringe
     767              :     layer_to_visit_id: LayerToVisitId,
     768              :     /// Lsn range for the read, used for selecting the next read
     769              :     lsn_range: Range<Lsn>,
     770              : }
     771              : 
     772              : /// Data structure which maintains a fringe of layers for the
     773              : /// read path. The fringe is the set of layers which intersects
     774              : /// the current keyspace that the search is descending on.
     775              : /// Each layer tracks the keyspace that intersects it.
     776              : ///
     777              : /// The fringe must appear sorted by Lsn. Hence, it uses
     778              : /// a two layer indexing scheme.
     779              : #[derive(Debug)]
     780              : pub(crate) struct LayerFringe {
     781              :     planned_visits_by_lsn: BinaryHeap<LayerVisit>,
     782              :     visit_reads: HashMap<LayerToVisitId, LayerVisitReads>,
     783              : }
     784              : 
     785              : #[derive(Debug)]
     786              : struct LayerVisitReads {
     787              :     layer: ReadableLayer,
     788              :     target_keyspace: KeySpaceRandomAccum,
     789              : }
     790              : 
     791              : impl LayerFringe {
     792       424842 :     pub(crate) fn new() -> Self {
     793       424842 :         LayerFringe {
     794       424842 :             planned_visits_by_lsn: BinaryHeap::new(),
     795       424842 :             visit_reads: HashMap::new(),
     796       424842 :         }
     797       424842 :     }
     798              : 
     799       865439 :     pub(crate) fn next_layer(&mut self) -> Option<(ReadableLayer, KeySpace, Range<Lsn>)> {
     800       865439 :         let read_desc = self.planned_visits_by_lsn.pop()?;
     801              : 
     802       440597 :         let removed = self.visit_reads.remove_entry(&read_desc.layer_to_visit_id);
     803       440597 : 
     804       440597 :         match removed {
     805              :             Some((
     806              :                 _,
     807              :                 LayerVisitReads {
     808       440597 :                     layer,
     809       440597 :                     mut target_keyspace,
     810       440597 :                 },
     811       440597 :             )) => Some((
     812       440597 :                 layer,
     813       440597 :                 target_keyspace.consume_keyspace(),
     814       440597 :                 read_desc.lsn_range,
     815       440597 :             )),
     816            0 :             None => unreachable!("fringe internals are always consistent"),
     817              :         }
     818       865439 :     }
     819              : 
     820       454884 :     pub(crate) fn update(
     821       454884 :         &mut self,
     822       454884 :         layer: ReadableLayer,
     823       454884 :         keyspace: KeySpace,
     824       454884 :         lsn_range: Range<Lsn>,
     825       454884 :     ) {
     826       454884 :         let layer_to_visit_id = LayerToVisitId {
     827       454884 :             layer_id: layer.id(),
     828       454884 :             lsn_floor: lsn_range.start,
     829       454884 :             lsn_ceil: lsn_range.end,
     830       454884 :         };
     831       454884 : 
     832       454884 :         let entry = self.visit_reads.entry(layer_to_visit_id.clone());
     833       454884 :         match entry {
     834        14287 :             Entry::Occupied(mut entry) => {
     835        14287 :                 entry.get_mut().target_keyspace.add_keyspace(keyspace);
     836        14287 :             }
     837       440597 :             Entry::Vacant(entry) => {
     838       440597 :                 self.planned_visits_by_lsn.push(LayerVisit {
     839       440597 :                     lsn_range,
     840       440597 :                     layer_to_visit_id: layer_to_visit_id.clone(),
     841       440597 :                 });
     842       440597 :                 let mut accum = KeySpaceRandomAccum::new();
     843       440597 :                 accum.add_keyspace(keyspace);
     844       440597 :                 entry.insert(LayerVisitReads {
     845       440597 :                     layer,
     846       440597 :                     target_keyspace: accum,
     847       440597 :                 });
     848       440597 :             }
     849              :         }
     850       454884 :     }
     851              : }
     852              : 
     853              : impl Default for LayerFringe {
     854            0 :     fn default() -> Self {
     855            0 :         Self::new()
     856            0 :     }
     857              : }
     858              : 
     859              : impl Ord for LayerVisit {
     860        89258 :     fn cmp(&self, other: &Self) -> Ordering {
     861        89258 :         let ord = self.lsn_range.end.cmp(&other.lsn_range.end);
     862        89258 :         if ord == std::cmp::Ordering::Equal {
     863         7165 :             self.lsn_range.start.cmp(&other.lsn_range.start).reverse()
     864              :         } else {
     865        82093 :             ord
     866              :         }
     867        89258 :     }
     868              : }
     869              : 
     870              : impl PartialOrd for LayerVisit {
     871        89258 :     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
     872        89258 :         Some(self.cmp(other))
     873        89258 :     }
     874              : }
     875              : 
     876              : impl PartialEq for LayerVisit {
     877            0 :     fn eq(&self, other: &Self) -> bool {
     878            0 :         self.lsn_range == other.lsn_range
     879            0 :     }
     880              : }
     881              : 
     882              : impl Eq for LayerVisit {}
     883              : 
     884              : impl ReadableLayer {
     885       454884 :     pub(crate) fn id(&self) -> LayerId {
     886       454884 :         match self {
     887       143840 :             Self::PersistentLayer(layer) => LayerId::PersitentLayerId(layer.layer_desc().key()),
     888       311044 :             Self::InMemoryLayer(layer) => LayerId::InMemoryLayerId(layer.file_id()),
     889              :         }
     890       454884 :     }
     891              : 
     892       440597 :     pub(crate) async fn get_values_reconstruct_data(
     893       440597 :         &self,
     894       440597 :         keyspace: KeySpace,
     895       440597 :         lsn_range: Range<Lsn>,
     896       440597 :         reconstruct_state: &mut ValuesReconstructState,
     897       440597 :         ctx: &RequestContext,
     898       440597 :     ) -> Result<(), GetVectoredError> {
     899       440597 :         match self {
     900       133393 :             ReadableLayer::PersistentLayer(layer) => {
     901       133393 :                 let ctx = RequestContextBuilder::from(ctx)
     902       133393 :                     .perf_span(|crnt_perf_span| {
     903            0 :                         info_span!(
     904              :                             target: PERF_TRACE_TARGET,
     905            0 :                             parent: crnt_perf_span,
     906              :                             "PLAN_LAYER",
     907              :                             layer = %layer
     908              :                         )
     909       133393 :                     })
     910       133393 :                     .attached_child();
     911       133393 : 
     912       133393 :                 layer
     913       133393 :                     .get_values_reconstruct_data(keyspace, lsn_range, reconstruct_state, &ctx)
     914       133393 :                     .maybe_perf_instrument(&ctx, |crnt_perf_span| crnt_perf_span.clone())
     915       133393 :                     .await
     916              :             }
     917       307204 :             ReadableLayer::InMemoryLayer(layer) => {
     918       307204 :                 let ctx = RequestContextBuilder::from(ctx)
     919       307204 :                     .perf_span(|crnt_perf_span| {
     920            0 :                         info_span!(
     921              :                             target: PERF_TRACE_TARGET,
     922            0 :                             parent: crnt_perf_span,
     923              :                             "PLAN_LAYER",
     924              :                             layer = %layer
     925              :                         )
     926       307204 :                     })
     927       307204 :                     .attached_child();
     928       307204 : 
     929       307204 :                 layer
     930       307204 :                     .get_values_reconstruct_data(keyspace, lsn_range, reconstruct_state, &ctx)
     931       307204 :                     .maybe_perf_instrument(&ctx, |crnt_perf_span| crnt_perf_span.clone())
     932       307204 :                     .await
     933              :             }
     934              :         }
     935       440597 :     }
     936              : }
     937              : 
     938              : /// Layers contain a hint indicating whether they are likely to be used for reads.
     939              : ///
     940              : /// This is a hint rather than an authoritative value, so that we do not have to update it synchronously
     941              : /// when changing the visibility of layers (for example when creating a branch that makes some previously
     942              : /// covered layers visible).  It should be used for cache management but not for correctness-critical checks.
     943              : #[derive(Debug, Clone, PartialEq, Eq)]
     944              : pub enum LayerVisibilityHint {
     945              :     /// A Visible layer might be read while serving a read, because there is not an image layer between it
     946              :     /// and a readable LSN (the tip of the branch or a child's branch point)
     947              :     Visible,
     948              :     /// A Covered layer probably won't be read right now, but _can_ be read in future if someone creates
     949              :     /// a branch or ephemeral endpoint at an LSN below the layer that covers this.
     950              :     Covered,
     951              : }
     952              : 
     953              : pub(crate) struct LayerAccessStats(std::sync::atomic::AtomicU64);
     954              : 
     955            0 : #[derive(Clone, Copy, strum_macros::EnumString)]
     956              : pub(crate) enum LayerAccessStatsReset {
     957              :     NoReset,
     958              :     AllStats,
     959              : }
     960              : 
     961              : impl Default for LayerAccessStats {
     962          978 :     fn default() -> Self {
     963          978 :         // Default value is to assume resident since creation time, and visible.
     964          978 :         let (_mask, mut value) = Self::to_low_res_timestamp(Self::RTIME_SHIFT, SystemTime::now());
     965          978 :         value |= 0x1 << Self::VISIBILITY_SHIFT;
     966          978 : 
     967          978 :         Self(std::sync::atomic::AtomicU64::new(value))
     968          978 :     }
     969              : }
     970              : 
     971              : // Efficient store of two very-low-resolution timestamps and some bits.  Used for storing last access time and
     972              : // last residence change time.
     973              : impl LayerAccessStats {
     974              :     // How many high bits to drop from a u32 timestamp?
     975              :     // - Only storing up to a u32 timestamp will work fine until 2038 (if this code is still in use
     976              :     //   after that, this software has been very successful!)
     977              :     // - Dropping the top bit is implicitly safe because unix timestamps are meant to be
     978              :     // stored in an i32, so they never used it.
     979              :     // - Dropping the next two bits is safe because this code is only running on systems in
     980              :     // years >= 2024, and these bits have been 1 since 2021
     981              :     //
     982              :     // Therefore we may store only 28 bits for a timestamp with one second resolution.  We do
     983              :     // this truncation to make space for some flags in the high bits of our u64.
     984              :     const TS_DROP_HIGH_BITS: u32 = u32::count_ones(Self::TS_ONES) + 1;
     985              :     const TS_MASK: u32 = 0x1f_ff_ff_ff;
     986              :     const TS_ONES: u32 = 0x60_00_00_00;
     987              : 
     988              :     const ATIME_SHIFT: u32 = 0;
     989              :     const RTIME_SHIFT: u32 = 32 - Self::TS_DROP_HIGH_BITS;
     990              :     const VISIBILITY_SHIFT: u32 = 64 - 2 * Self::TS_DROP_HIGH_BITS;
     991              : 
     992       133474 :     fn write_bits(&self, mask: u64, value: u64) -> u64 {
     993       133474 :         self.0
     994       133474 :             .fetch_update(
     995       133474 :                 // TODO: decide what orderings are correct
     996       133474 :                 std::sync::atomic::Ordering::Relaxed,
     997       133474 :                 std::sync::atomic::Ordering::Relaxed,
     998       133474 :                 |v| Some((v & !mask) | (value & mask)),
     999       133474 :             )
    1000       133474 :             .expect("Inner function is infallible")
    1001       133474 :     }
    1002              : 
    1003       134262 :     fn to_low_res_timestamp(shift: u32, time: SystemTime) -> (u64, u64) {
    1004       134262 :         // Drop the low three bits of the timestamp, for an ~8s accuracy
    1005       134262 :         let timestamp = time.duration_since(UNIX_EPOCH).unwrap().as_secs() & (Self::TS_MASK as u64);
    1006       134262 : 
    1007       134262 :         ((Self::TS_MASK as u64) << shift, timestamp << shift)
    1008       134262 :     }
    1009              : 
    1010           73 :     fn read_low_res_timestamp(&self, shift: u32) -> Option<SystemTime> {
    1011           73 :         let read = self.0.load(std::sync::atomic::Ordering::Relaxed);
    1012           73 : 
    1013           73 :         let ts_bits = (read & ((Self::TS_MASK as u64) << shift)) >> shift;
    1014           73 :         if ts_bits == 0 {
    1015           33 :             None
    1016              :         } else {
    1017           40 :             Some(UNIX_EPOCH + Duration::from_secs(ts_bits | (Self::TS_ONES as u64)))
    1018              :         }
    1019           73 :     }
    1020              : 
    1021              :     /// Record a change in layer residency.
    1022              :     ///
    1023              :     /// Recording the event must happen while holding the layer map lock to
    1024              :     /// ensure that latest-activity-threshold-based layer eviction (eviction_task.rs)
    1025              :     /// can do an "imitate access" to this layer, before it observes `now-latest_activity() > threshold`.
    1026              :     ///
    1027              :     /// If we instead recorded the residence event with a timestamp from before grabbing the layer map lock,
    1028              :     /// the following race could happen:
    1029              :     ///
    1030              :     /// - Compact: Write out an L1 layer from several L0 layers. This records residence event LayerCreate with the current timestamp.
    1031              :     /// - Eviction: imitate access logical size calculation. This accesses the L0 layers because the L1 layer is not yet in the layer map.
    1032              :     /// - Compact: Grab layer map lock, add the new L1 to layer map and remove the L0s, release layer map lock.
    1033              :     /// - Eviction: observes the new L1 layer whose only activity timestamp is the LayerCreate event.
    1034           25 :     pub(crate) fn record_residence_event_at(&self, now: SystemTime) {
    1035           25 :         let (mask, value) = Self::to_low_res_timestamp(Self::RTIME_SHIFT, now);
    1036           25 :         self.write_bits(mask, value);
    1037           25 :     }
    1038              : 
    1039           24 :     pub(crate) fn record_residence_event(&self) {
    1040           24 :         self.record_residence_event_at(SystemTime::now())
    1041           24 :     }
    1042              : 
    1043       133259 :     fn record_access_at(&self, now: SystemTime) -> bool {
    1044       133259 :         let (mut mask, mut value) = Self::to_low_res_timestamp(Self::ATIME_SHIFT, now);
    1045       133259 : 
    1046       133259 :         // A layer which is accessed must be visible.
    1047       133259 :         mask |= 0x1 << Self::VISIBILITY_SHIFT;
    1048       133259 :         value |= 0x1 << Self::VISIBILITY_SHIFT;
    1049       133259 : 
    1050       133259 :         let old_bits = self.write_bits(mask, value);
    1051            1 :         !matches!(
    1052       133259 :             self.decode_visibility(old_bits),
    1053              :             LayerVisibilityHint::Visible
    1054              :         )
    1055       133259 :     }
    1056              : 
    1057              :     /// Returns true if we modified the layer's visibility to set it to Visible implicitly
    1058              :     /// as a result of this access
    1059       133399 :     pub(crate) fn record_access(&self, ctx: &RequestContext) -> bool {
    1060       133399 :         if ctx.access_stats_behavior() == AccessStatsBehavior::Skip {
    1061          143 :             return false;
    1062       133256 :         }
    1063       133256 : 
    1064       133256 :         self.record_access_at(SystemTime::now())
    1065       133399 :     }
    1066              : 
    1067            0 :     fn as_api_model(
    1068            0 :         &self,
    1069            0 :         reset: LayerAccessStatsReset,
    1070            0 :     ) -> pageserver_api::models::LayerAccessStats {
    1071            0 :         let ret = pageserver_api::models::LayerAccessStats {
    1072            0 :             access_time: self
    1073            0 :                 .read_low_res_timestamp(Self::ATIME_SHIFT)
    1074            0 :                 .unwrap_or(UNIX_EPOCH),
    1075            0 :             residence_time: self
    1076            0 :                 .read_low_res_timestamp(Self::RTIME_SHIFT)
    1077            0 :                 .unwrap_or(UNIX_EPOCH),
    1078            0 :             visible: matches!(self.visibility(), LayerVisibilityHint::Visible),
    1079              :         };
    1080            0 :         match reset {
    1081            0 :             LayerAccessStatsReset::NoReset => {}
    1082            0 :             LayerAccessStatsReset::AllStats => {
    1083            0 :                 self.write_bits((Self::TS_MASK as u64) << Self::ATIME_SHIFT, 0x0);
    1084            0 :                 self.write_bits((Self::TS_MASK as u64) << Self::RTIME_SHIFT, 0x0);
    1085            0 :             }
    1086              :         }
    1087            0 :         ret
    1088            0 :     }
    1089              : 
    1090              :     /// Get the latest access timestamp, falling back to latest residence event.  The latest residence event
    1091              :     /// will be this Layer's construction time, if its residence hasn't changed since then.
    1092           21 :     pub(crate) fn latest_activity(&self) -> SystemTime {
    1093           21 :         if let Some(t) = self.read_low_res_timestamp(Self::ATIME_SHIFT) {
    1094            3 :             t
    1095              :         } else {
    1096           18 :             self.read_low_res_timestamp(Self::RTIME_SHIFT)
    1097           18 :                 .expect("Residence time is set on construction")
    1098              :         }
    1099           21 :     }
    1100              : 
    1101              :     /// Whether this layer has been accessed (excluding in [`AccessStatsBehavior::Skip`]).
    1102              :     ///
    1103              :     /// This indicates whether the layer has been used for some purpose that would motivate
    1104              :     /// us to keep it on disk, such as for serving a getpage request.
    1105           17 :     fn accessed(&self) -> bool {
    1106           17 :         // Consider it accessed if the most recent access is more recent than
    1107           17 :         // the most recent change in residence status.
    1108           17 :         match (
    1109           17 :             self.read_low_res_timestamp(Self::ATIME_SHIFT),
    1110           17 :             self.read_low_res_timestamp(Self::RTIME_SHIFT),
    1111              :         ) {
    1112           15 :             (None, _) => false,
    1113            0 :             (Some(_), None) => true,
    1114            2 :             (Some(a), Some(r)) => a >= r,
    1115              :         }
    1116           17 :     }
    1117              : 
    1118              :     /// Helper for extracting the visibility hint from the literal value of our inner u64
    1119       133849 :     fn decode_visibility(&self, bits: u64) -> LayerVisibilityHint {
    1120       133849 :         match (bits >> Self::VISIBILITY_SHIFT) & 0x1 {
    1121       133837 :             1 => LayerVisibilityHint::Visible,
    1122           12 :             0 => LayerVisibilityHint::Covered,
    1123            0 :             _ => unreachable!(),
    1124              :         }
    1125       133849 :     }
    1126              : 
    1127              :     /// Returns the old value which has been replaced
    1128          190 :     pub(crate) fn set_visibility(&self, visibility: LayerVisibilityHint) -> LayerVisibilityHint {
    1129          190 :         let value = match visibility {
    1130          164 :             LayerVisibilityHint::Visible => 0x1 << Self::VISIBILITY_SHIFT,
    1131           26 :             LayerVisibilityHint::Covered => 0x0,
    1132              :         };
    1133              : 
    1134          190 :         let old_bits = self.write_bits(0x1 << Self::VISIBILITY_SHIFT, value);
    1135          190 :         self.decode_visibility(old_bits)
    1136          190 :     }
    1137              : 
    1138          400 :     pub(crate) fn visibility(&self) -> LayerVisibilityHint {
    1139          400 :         let read = self.0.load(std::sync::atomic::Ordering::Relaxed);
    1140          400 :         self.decode_visibility(read)
    1141          400 :     }
    1142              : }
    1143              : 
    1144              : /// Get a layer descriptor from a layer.
    1145              : pub(crate) trait AsLayerDesc {
    1146              :     /// Get the layer descriptor.
    1147              :     fn layer_desc(&self) -> &PersistentLayerDesc;
    1148              : }
    1149              : 
    1150              : pub mod tests {
    1151              :     use pageserver_api::shard::TenantShardId;
    1152              :     use utils::id::TimelineId;
    1153              : 
    1154              :     use super::*;
    1155              : 
    1156              :     impl From<DeltaLayerName> for PersistentLayerDesc {
    1157           11 :         fn from(value: DeltaLayerName) -> Self {
    1158           11 :             PersistentLayerDesc::new_delta(
    1159           11 :                 TenantShardId::from([0; 18]),
    1160           11 :                 TimelineId::from_array([0; 16]),
    1161           11 :                 value.key_range,
    1162           11 :                 value.lsn_range,
    1163           11 :                 233,
    1164           11 :             )
    1165           11 :         }
    1166              :     }
    1167              : 
    1168              :     impl From<ImageLayerName> for PersistentLayerDesc {
    1169           12 :         fn from(value: ImageLayerName) -> Self {
    1170           12 :             PersistentLayerDesc::new_img(
    1171           12 :                 TenantShardId::from([0; 18]),
    1172           12 :                 TimelineId::from_array([0; 16]),
    1173           12 :                 value.key_range,
    1174           12 :                 value.lsn,
    1175           12 :                 233,
    1176           12 :             )
    1177           12 :         }
    1178              :     }
    1179              : 
    1180              :     impl From<LayerName> for PersistentLayerDesc {
    1181           23 :         fn from(value: LayerName) -> Self {
    1182           23 :             match value {
    1183           11 :                 LayerName::Delta(d) => Self::from(d),
    1184           12 :                 LayerName::Image(i) => Self::from(i),
    1185              :             }
    1186           23 :         }
    1187              :     }
    1188              : }
    1189              : 
    1190              : /// Range wrapping newtype, which uses display to render Debug.
    1191              : ///
    1192              : /// Useful with `Key`, which has too verbose `{:?}` for printing multiple layers.
    1193              : struct RangeDisplayDebug<'a, T: std::fmt::Display>(&'a Range<T>);
    1194              : 
    1195              : impl<T: std::fmt::Display> std::fmt::Debug for RangeDisplayDebug<'_, T> {
    1196            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    1197            0 :         write!(f, "{}..{}", self.0.start, self.0.end)
    1198            0 :     }
    1199              : }
    1200              : 
    1201              : #[cfg(test)]
    1202              : mod tests2 {
    1203              :     use pageserver_api::key::DBDIR_KEY;
    1204              :     use tracing::info;
    1205              : 
    1206              :     use super::*;
    1207              :     use crate::tenant::storage_layer::IoConcurrency;
    1208              : 
    1209              :     /// TODO: currently this test relies on manual visual inspection of the --no-capture output.
    1210              :     /// Should look like so:
    1211              :     /// ```text
    1212              :     /// RUST_LOG=trace cargo nextest run  --features testing  --no-capture test_io_concurrency_noise
    1213              :     /// running 1 test
    1214              :     /// 2025-01-21T17:42:01.335679Z  INFO get_vectored_concurrent_io test selected=SidecarTask
    1215              :     /// 2025-01-21T17:42:01.335680Z TRACE spawning sidecar task task_id=0
    1216              :     /// 2025-01-21T17:42:01.335937Z TRACE IoConcurrency_sidecar{task_id=0}: start
    1217              :     /// 2025-01-21T17:42:01.335972Z TRACE IoConcurrency_sidecar{task_id=0}: received new io future
    1218              :     /// 2025-01-21T17:42:01.335999Z  INFO IoConcurrency_sidecar{task_id=0}: waiting for signal to complete IO
    1219              :     /// 2025-01-21T17:42:01.336229Z  WARN dropping ValuesReconstructState while some IOs have not been completed num_active_ios=1 sidecar_task_id=Some(0) backtrace=   0: <pageserver::tenant::storage_layer::ValuesReconstructState as core::ops::drop::Drop>::drop
    1220              :     ///              at ./src/tenant/storage_layer.rs:553:24
    1221              :     ///    1: core::ptr::drop_in_place<pageserver::tenant::storage_layer::ValuesReconstructState>
    1222              :     ///              at /home/christian/.rustup/toolchains/1.84.0-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mod.rs:521:1
    1223              :     ///    2: core::mem::drop
    1224              :     ///              at /home/christian/.rustup/toolchains/1.84.0-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/mem/mod.rs:942:24
    1225              :     ///    3: pageserver::tenant::storage_layer::tests2::test_io_concurrency_noise::{{closure}}
    1226              :     ///              at ./src/tenant/storage_layer.rs:1159:9
    1227              :     ///   ...
    1228              :     ///   49: <unknown>
    1229              :     /// 2025-01-21T17:42:01.452293Z  INFO IoConcurrency_sidecar{task_id=0}: completing IO
    1230              :     /// 2025-01-21T17:42:01.452357Z TRACE IoConcurrency_sidecar{task_id=0}: io future completed
    1231              :     /// 2025-01-21T17:42:01.452473Z TRACE IoConcurrency_sidecar{task_id=0}: end
    1232              :     /// test tenant::storage_layer::tests2::test_io_concurrency_noise ... ok
    1233              :     ///
    1234              :     /// ```
    1235              :     #[tokio::test]
    1236            1 :     async fn test_io_concurrency_noise() {
    1237            1 :         crate::tenant::harness::setup_logging();
    1238            1 : 
    1239            1 :         let io_concurrency = IoConcurrency::spawn_for_test();
    1240            1 :         match *io_concurrency {
    1241            1 :             IoConcurrency::Sequential => {
    1242            1 :                 // This test asserts behavior in sidecar mode, doesn't make sense in sequential mode.
    1243            1 :                 return;
    1244            1 :             }
    1245            1 :             IoConcurrency::SidecarTask { .. } => {}
    1246            1 :         }
    1247            1 :         let mut reconstruct_state = ValuesReconstructState::new(io_concurrency.clone());
    1248            1 : 
    1249            1 :         let (io_fut_is_waiting_tx, io_fut_is_waiting) = tokio::sync::oneshot::channel();
    1250            1 :         let (do_complete_io, should_complete_io) = tokio::sync::oneshot::channel();
    1251            1 :         let (io_fut_exiting_tx, io_fut_exiting) = tokio::sync::oneshot::channel();
    1252            1 : 
    1253            1 :         let io = reconstruct_state.update_key(&DBDIR_KEY, Lsn(8), true);
    1254            1 :         reconstruct_state
    1255            1 :             .spawn_io(async move {
    1256            1 :                 info!("waiting for signal to complete IO");
    1257            1 :                 io_fut_is_waiting_tx.send(()).unwrap();
    1258            1 :                 should_complete_io.await.unwrap();
    1259            1 :                 info!("completing IO");
    1260            1 :                 io.complete(Ok(OnDiskValue::RawImage(Bytes::new())));
    1261            1 :                 io_fut_exiting_tx.send(()).unwrap();
    1262            1 :             })
    1263            1 :             .await;
    1264            1 : 
    1265            1 :         io_fut_is_waiting.await.unwrap();
    1266            1 : 
    1267            1 :         // this is what makes the noise
    1268            1 :         drop(reconstruct_state);
    1269            1 : 
    1270            1 :         do_complete_io.send(()).unwrap();
    1271            1 : 
    1272            1 :         io_fut_exiting.await.unwrap();
    1273            1 :     }
    1274              : }
        

Generated by: LCOV version 2.1-beta