LCOV - code coverage report
Current view: top level - pageserver/src/tenant - storage_layer.rs (source / functions) Coverage Total Hit
Test: 5e392a02abbad1ab595f4dba672e219a49f7f539.info Lines: 83.3 % 568 473
Test Date: 2025-04-11 22:43:24 Functions: 80.2 % 86 69

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

Generated by: LCOV version 2.1-beta