LCOV - code coverage report
Current view: top level - pageserver/src/tenant/storage_layer - image_layer.rs (source / functions) Coverage Total Hit
Test: 1e20c4f2b28aa592527961bb32170ebbd2c9172f.info Lines: 80.0 % 956 765
Test Date: 2025-07-16 12:29:03 Functions: 61.9 % 84 52

            Line data    Source code
       1              : //! An ImageLayer represents an image or a snapshot of a key-range at
       2              : //! one particular LSN.
       3              : //!
       4              : //! It contains an image of all key-value pairs in its key-range. Any key
       5              : //! that falls into the image layer's range but does not exist in the layer,
       6              : //! does not exist.
       7              : //!
       8              : //! An image layer is stored in a file on disk. The file is stored in
       9              : //! timelines/<timeline_id> directory.  Currently, there are no
      10              : //! subdirectories, and each image layer file is named like this:
      11              : //!
      12              : //! ```text
      13              : //!    <key start>-<key end>__<LSN>
      14              : //! ```
      15              : //!
      16              : //! For example:
      17              : //!
      18              : //! ```text
      19              : //!    000000067F000032BE0000400000000070B6-000000067F000032BE0000400000000080B6__00000000346BC568
      20              : //! ```
      21              : //!
      22              : //! Every image layer file consists of three parts: "summary",
      23              : //! "index", and "values".  The summary is a fixed size header at the
      24              : //! beginning of the file, and it contains basic information about the
      25              : //! layer, and offsets to the other parts. The "index" is a B-tree,
      26              : //! mapping from Key to an offset in the "values" part.  The
      27              : //! actual page images are stored in the "values" part.
      28              : use std::collections::{HashMap, VecDeque};
      29              : use std::fs::File;
      30              : use std::ops::Range;
      31              : use std::os::unix::prelude::FileExt;
      32              : use std::str::FromStr;
      33              : use std::sync::Arc;
      34              : use std::sync::atomic::AtomicU64;
      35              : 
      36              : use anyhow::{Context, Result, bail, ensure};
      37              : use bytes::Bytes;
      38              : use camino::{Utf8Path, Utf8PathBuf};
      39              : use hex;
      40              : use itertools::Itertools;
      41              : use pageserver_api::config::MaxVectoredReadBytes;
      42              : use pageserver_api::key::{DBDIR_KEY, KEY_SIZE, Key};
      43              : use pageserver_api::keyspace::KeySpace;
      44              : use pageserver_api::shard::{ShardIdentity, TenantShardId};
      45              : use serde::{Deserialize, Serialize};
      46              : use tokio::sync::OnceCell;
      47              : use tokio_stream::StreamExt;
      48              : use tokio_util::sync::CancellationToken;
      49              : use tracing::*;
      50              : use utils::bin_ser::BeSer;
      51              : use utils::bin_ser::SerializeError;
      52              : use utils::id::{TenantId, TimelineId};
      53              : use utils::lsn::Lsn;
      54              : use wal_decoder::models::value::Value;
      55              : 
      56              : use super::errors::PutError;
      57              : use super::layer_name::ImageLayerName;
      58              : use super::{
      59              :     AsLayerDesc, LayerName, OnDiskValue, OnDiskValueIo, PersistentLayerDesc, ResidentLayer,
      60              :     ValuesReconstructState,
      61              : };
      62              : use crate::config::PageServerConf;
      63              : use crate::context::{PageContentKind, RequestContext, RequestContextBuilder};
      64              : use crate::page_cache::{self, FileId, PAGE_SZ};
      65              : use crate::tenant::blob_io::BlobWriter;
      66              : use crate::tenant::block_io::{BlockBuf, FileBlockReader};
      67              : use crate::tenant::disk_btree::{
      68              :     DiskBtreeBuilder, DiskBtreeIterator, DiskBtreeReader, VisitDirection,
      69              : };
      70              : use crate::tenant::timeline::GetVectoredError;
      71              : use crate::tenant::vectored_blob_io::{
      72              :     BlobFlag, BufView, StreamingVectoredReadPlanner, VectoredBlobReader, VectoredRead,
      73              :     VectoredReadPlanner,
      74              : };
      75              : use crate::virtual_file::TempVirtualFile;
      76              : use crate::virtual_file::owned_buffers_io::io_buf_ext::IoBufExt;
      77              : use crate::virtual_file::owned_buffers_io::write::{Buffer, BufferedWriterShutdownMode};
      78              : use crate::virtual_file::{self, IoBuffer, IoBufferMut, MaybeFatalIo, VirtualFile};
      79              : use crate::{IMAGE_FILE_MAGIC, STORAGE_FORMAT_VERSION, TEMP_FILE_SUFFIX};
      80              : 
      81              : ///
      82              : /// Header stored in the beginning of the file
      83              : ///
      84              : /// After this comes the 'values' part, starting on block 1. After that,
      85              : /// the 'index' starts at the block indicated by 'index_start_blk'
      86              : ///
      87            0 : #[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]
      88              : pub struct Summary {
      89              :     /// Magic value to identify this as a neon image file. Always IMAGE_FILE_MAGIC.
      90              :     pub magic: u16,
      91              :     pub format_version: u16,
      92              : 
      93              :     pub tenant_id: TenantId,
      94              :     pub timeline_id: TimelineId,
      95              :     pub key_range: Range<Key>,
      96              :     pub lsn: Lsn,
      97              : 
      98              :     /// Block number where the 'index' part of the file begins.
      99              :     pub index_start_blk: u32,
     100              :     /// Block within the 'index', where the B-tree root page is stored
     101              :     pub index_root_blk: u32,
     102              :     // the 'values' part starts after the summary header, on block 1.
     103              : }
     104              : 
     105              : impl From<&ImageLayer> for Summary {
     106            0 :     fn from(layer: &ImageLayer) -> Self {
     107            0 :         Self::expected(
     108            0 :             layer.desc.tenant_shard_id.tenant_id,
     109            0 :             layer.desc.timeline_id,
     110            0 :             layer.desc.key_range.clone(),
     111            0 :             layer.lsn,
     112              :         )
     113            0 :     }
     114              : }
     115              : 
     116              : impl Summary {
     117              :     /// Serializes the summary header into an aligned buffer of lenth `PAGE_SZ`.
     118          193 :     pub fn ser_into_page(&self) -> Result<IoBuffer, SerializeError> {
     119          193 :         let mut buf = IoBufferMut::with_capacity(PAGE_SZ);
     120          193 :         Self::ser_into(self, &mut buf)?;
     121              :         // Pad zeroes to the buffer so the length is a multiple of the alignment.
     122          193 :         buf.extend_with(0, buf.capacity() - buf.len());
     123          193 :         Ok(buf.freeze())
     124          193 :     }
     125              : 
     126           75 :     pub(super) fn expected(
     127           75 :         tenant_id: TenantId,
     128           75 :         timeline_id: TimelineId,
     129           75 :         key_range: Range<Key>,
     130           75 :         lsn: Lsn,
     131           75 :     ) -> Self {
     132           75 :         Self {
     133           75 :             magic: IMAGE_FILE_MAGIC,
     134           75 :             format_version: STORAGE_FORMAT_VERSION,
     135           75 :             tenant_id,
     136           75 :             timeline_id,
     137           75 :             key_range,
     138           75 :             lsn,
     139           75 : 
     140           75 :             index_start_blk: 0,
     141           75 :             index_root_blk: 0,
     142           75 :         }
     143           75 :     }
     144              : }
     145              : 
     146              : /// This is used only from `pagectl`. Within pageserver, all layers are
     147              : /// [`crate::tenant::storage_layer::Layer`], which can hold an [`ImageLayerInner`].
     148              : pub struct ImageLayer {
     149              :     path: Utf8PathBuf,
     150              :     pub desc: PersistentLayerDesc,
     151              :     // This entry contains an image of all pages as of this LSN, should be the same as desc.lsn
     152              :     pub lsn: Lsn,
     153              :     inner: OnceCell<ImageLayerInner>,
     154              : }
     155              : 
     156              : impl std::fmt::Debug for ImageLayer {
     157            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     158              :         use super::RangeDisplayDebug;
     159              : 
     160            0 :         f.debug_struct("ImageLayer")
     161            0 :             .field("key_range", &RangeDisplayDebug(&self.desc.key_range))
     162            0 :             .field("file_size", &self.desc.file_size)
     163            0 :             .field("lsn", &self.lsn)
     164            0 :             .field("inner", &self.inner)
     165            0 :             .finish()
     166            0 :     }
     167              : }
     168              : 
     169              : /// ImageLayer is the in-memory data structure associated with an on-disk image
     170              : /// file.
     171              : pub struct ImageLayerInner {
     172              :     // values copied from summary
     173              :     index_start_blk: u32,
     174              :     index_root_blk: u32,
     175              : 
     176              :     key_range: Range<Key>,
     177              :     lsn: Lsn,
     178              : 
     179              :     file: Arc<VirtualFile>,
     180              :     file_id: FileId,
     181              : 
     182              :     max_vectored_read_bytes: Option<MaxVectoredReadBytes>,
     183              : }
     184              : 
     185              : impl ImageLayerInner {
     186            0 :     pub(crate) fn layer_dbg_info(&self) -> String {
     187            0 :         format!(
     188            0 :             "image {}..{} {}",
     189            0 :             self.key_range().start,
     190            0 :             self.key_range().end,
     191            0 :             self.lsn()
     192              :         )
     193            0 :     }
     194              : }
     195              : 
     196              : impl std::fmt::Debug for ImageLayerInner {
     197            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     198            0 :         f.debug_struct("ImageLayerInner")
     199            0 :             .field("index_start_blk", &self.index_start_blk)
     200            0 :             .field("index_root_blk", &self.index_root_blk)
     201            0 :             .finish()
     202            0 :     }
     203              : }
     204              : 
     205              : impl ImageLayerInner {
     206            0 :     pub(super) async fn dump(&self, ctx: &RequestContext) -> anyhow::Result<()> {
     207            0 :         let block_reader = FileBlockReader::new(&self.file, self.file_id);
     208            0 :         let tree_reader = DiskBtreeReader::<_, KEY_SIZE>::new(
     209            0 :             self.index_start_blk,
     210            0 :             self.index_root_blk,
     211            0 :             block_reader,
     212              :         );
     213              : 
     214            0 :         tree_reader.dump(ctx).await?;
     215              : 
     216            0 :         tree_reader
     217            0 :             .visit(
     218            0 :                 &[0u8; KEY_SIZE],
     219            0 :                 VisitDirection::Forwards,
     220            0 :                 |key, value| {
     221            0 :                     println!("key: {} offset {}", hex::encode(key), value);
     222            0 :                     true
     223            0 :                 },
     224            0 :                 ctx,
     225              :             )
     226            0 :             .await?;
     227              : 
     228            0 :         Ok(())
     229            0 :     }
     230              : }
     231              : 
     232              : /// Boilerplate to implement the Layer trait, always use layer_desc for persistent layers.
     233              : impl std::fmt::Display for ImageLayer {
     234            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     235            0 :         write!(f, "{}", self.layer_desc().short_id())
     236            0 :     }
     237              : }
     238              : 
     239              : impl AsLayerDesc for ImageLayer {
     240            0 :     fn layer_desc(&self) -> &PersistentLayerDesc {
     241            0 :         &self.desc
     242            0 :     }
     243              : }
     244              : 
     245              : impl ImageLayer {
     246            0 :     pub async fn dump(&self, verbose: bool, ctx: &RequestContext) -> Result<()> {
     247            0 :         self.desc.dump();
     248              : 
     249            0 :         if !verbose {
     250            0 :             return Ok(());
     251            0 :         }
     252              : 
     253            0 :         let inner = self.load(ctx).await?;
     254              : 
     255            0 :         inner.dump(ctx).await?;
     256              : 
     257            0 :         Ok(())
     258            0 :     }
     259              : 
     260          368 :     fn temp_path_for(
     261          368 :         conf: &PageServerConf,
     262          368 :         timeline_id: TimelineId,
     263          368 :         tenant_shard_id: TenantShardId,
     264          368 :         fname: &ImageLayerName,
     265          368 :     ) -> Utf8PathBuf {
     266              :         // TempVirtualFile requires us to never reuse a filename while an old
     267              :         // instance of TempVirtualFile created with that filename is not done dropping yet.
     268              :         // So, we use a monotonic counter to disambiguate the filenames.
     269              :         static NEXT_TEMP_DISAMBIGUATOR: AtomicU64 = AtomicU64::new(1);
     270          368 :         let filename_disambiguator =
     271          368 :             NEXT_TEMP_DISAMBIGUATOR.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
     272              : 
     273          368 :         conf.timeline_path(&tenant_shard_id, &timeline_id)
     274          368 :             .join(format!(
     275          368 :                 "{fname}.{filename_disambiguator:x}.{TEMP_FILE_SUFFIX}"
     276          368 :             ))
     277          368 :     }
     278              : 
     279              :     ///
     280              :     /// Open the underlying file and read the metadata into memory, if it's
     281              :     /// not loaded already.
     282              :     ///
     283            0 :     async fn load(&self, ctx: &RequestContext) -> Result<&ImageLayerInner> {
     284            0 :         self.inner
     285            0 :             .get_or_try_init(|| self.load_inner(ctx))
     286            0 :             .await
     287            0 :             .with_context(|| format!("Failed to load image layer {}", self.path()))
     288            0 :     }
     289              : 
     290            0 :     async fn load_inner(&self, ctx: &RequestContext) -> Result<ImageLayerInner> {
     291            0 :         let path = self.path();
     292              : 
     293            0 :         let loaded =
     294            0 :             ImageLayerInner::load(&path, self.desc.image_layer_lsn(), None, None, ctx).await?;
     295              : 
     296              :         // not production code
     297            0 :         let actual_layer_name = LayerName::from_str(path.file_name().unwrap()).unwrap();
     298            0 :         let expected_layer_name = self.layer_desc().layer_name();
     299              : 
     300            0 :         if actual_layer_name != expected_layer_name {
     301            0 :             println!("warning: filename does not match what is expected from in-file summary");
     302            0 :             println!("actual: {:?}", actual_layer_name.to_string());
     303            0 :             println!("expected: {:?}", expected_layer_name.to_string());
     304            0 :         }
     305              : 
     306            0 :         Ok(loaded)
     307            0 :     }
     308              : 
     309              :     /// Create an ImageLayer struct representing an existing file on disk.
     310              :     ///
     311              :     /// This variant is only used for debugging purposes, by the 'pagectl' binary.
     312            0 :     pub fn new_for_path(path: &Utf8Path, file: File) -> Result<ImageLayer> {
     313            0 :         let mut summary_buf = vec![0; PAGE_SZ];
     314            0 :         file.read_exact_at(&mut summary_buf, 0)?;
     315            0 :         let summary = Summary::des_prefix(&summary_buf)?;
     316            0 :         let metadata = file
     317            0 :             .metadata()
     318            0 :             .context("get file metadata to determine size")?;
     319              : 
     320              :         // This function is never used for constructing layers in a running pageserver,
     321              :         // so it does not need an accurate TenantShardId.
     322            0 :         let tenant_shard_id = TenantShardId::unsharded(summary.tenant_id);
     323              : 
     324            0 :         Ok(ImageLayer {
     325            0 :             path: path.to_path_buf(),
     326            0 :             desc: PersistentLayerDesc::new_img(
     327            0 :                 tenant_shard_id,
     328            0 :                 summary.timeline_id,
     329            0 :                 summary.key_range,
     330            0 :                 summary.lsn,
     331            0 :                 metadata.len(),
     332            0 :             ), // Now we assume image layer ALWAYS covers the full range. This may change in the future.
     333            0 :             lsn: summary.lsn,
     334            0 :             inner: OnceCell::new(),
     335            0 :         })
     336            0 :     }
     337              : 
     338            0 :     fn path(&self) -> Utf8PathBuf {
     339            0 :         self.path.clone()
     340            0 :     }
     341              : }
     342              : 
     343              : #[derive(thiserror::Error, Debug)]
     344              : pub enum RewriteSummaryError {
     345              :     #[error("magic mismatch")]
     346              :     MagicMismatch,
     347              :     #[error(transparent)]
     348              :     Other(#[from] anyhow::Error),
     349              : }
     350              : 
     351              : impl From<std::io::Error> for RewriteSummaryError {
     352            0 :     fn from(e: std::io::Error) -> Self {
     353            0 :         Self::Other(anyhow::anyhow!(e))
     354            0 :     }
     355              : }
     356              : 
     357              : impl ImageLayer {
     358            0 :     pub async fn rewrite_summary<F>(
     359            0 :         path: &Utf8Path,
     360            0 :         rewrite: F,
     361            0 :         ctx: &RequestContext,
     362            0 :     ) -> Result<(), RewriteSummaryError>
     363            0 :     where
     364            0 :         F: Fn(Summary) -> Summary,
     365            0 :     {
     366            0 :         let file = VirtualFile::open_with_options_v2(
     367            0 :             path,
     368            0 :             virtual_file::OpenOptions::new().read(true).write(true),
     369            0 :             ctx,
     370            0 :         )
     371            0 :         .await
     372            0 :         .with_context(|| format!("Failed to open file '{path}'"))?;
     373            0 :         let file_id = page_cache::next_file_id();
     374            0 :         let block_reader = FileBlockReader::new(&file, file_id);
     375            0 :         let summary_blk = block_reader.read_blk(0, ctx).await?;
     376            0 :         let actual_summary = Summary::des_prefix(summary_blk.as_ref()).context("deserialize")?;
     377            0 :         if actual_summary.magic != IMAGE_FILE_MAGIC {
     378            0 :             return Err(RewriteSummaryError::MagicMismatch);
     379            0 :         }
     380              : 
     381            0 :         let new_summary = rewrite(actual_summary);
     382              : 
     383            0 :         let buf = new_summary.ser_into_page().context("serialize")?;
     384            0 :         let (_buf, res) = file.write_all_at(buf.slice_len(), 0, ctx).await;
     385            0 :         res?;
     386            0 :         Ok(())
     387            0 :     }
     388              : }
     389              : 
     390              : impl ImageLayerInner {
     391           70 :     pub(crate) fn key_range(&self) -> &Range<Key> {
     392           70 :         &self.key_range
     393           70 :     }
     394              : 
     395           70 :     pub(crate) fn lsn(&self) -> Lsn {
     396           70 :         self.lsn
     397           70 :     }
     398              : 
     399           75 :     pub(super) async fn load(
     400           75 :         path: &Utf8Path,
     401           75 :         lsn: Lsn,
     402           75 :         summary: Option<Summary>,
     403           75 :         max_vectored_read_bytes: Option<MaxVectoredReadBytes>,
     404           75 :         ctx: &RequestContext,
     405           75 :     ) -> anyhow::Result<Self> {
     406           75 :         let file = Arc::new(
     407           75 :             VirtualFile::open_v2(path, ctx)
     408           75 :                 .await
     409           75 :                 .context("open layer file")?,
     410              :         );
     411           75 :         let file_id = page_cache::next_file_id();
     412           75 :         let block_reader = FileBlockReader::new(&file, file_id);
     413           75 :         let summary_blk = block_reader
     414           75 :             .read_blk(0, ctx)
     415           75 :             .await
     416           75 :             .context("read first block")?;
     417              : 
     418              :         // length is the only way how this could fail, so it's not actually likely at all unless
     419              :         // read_blk returns wrong sized block.
     420              :         //
     421              :         // TODO: confirm and make this into assertion
     422           75 :         let actual_summary =
     423           75 :             Summary::des_prefix(summary_blk.as_ref()).context("deserialize first block")?;
     424              : 
     425           75 :         if let Some(mut expected_summary) = summary {
     426              :             // production code path
     427           75 :             expected_summary.index_start_blk = actual_summary.index_start_blk;
     428           75 :             expected_summary.index_root_blk = actual_summary.index_root_blk;
     429              :             // mask out the timeline_id, but still require the layers to be from the same tenant
     430           75 :             expected_summary.timeline_id = actual_summary.timeline_id;
     431              : 
     432           75 :             if actual_summary != expected_summary {
     433            0 :                 bail!(
     434            0 :                     "in-file summary does not match expected summary. actual = {:?} expected = {:?}",
     435              :                     actual_summary,
     436              :                     expected_summary
     437              :                 );
     438           75 :             }
     439            0 :         }
     440              : 
     441           75 :         Ok(ImageLayerInner {
     442           75 :             index_start_blk: actual_summary.index_start_blk,
     443           75 :             index_root_blk: actual_summary.index_root_blk,
     444           75 :             lsn,
     445           75 :             file,
     446           75 :             file_id,
     447           75 :             max_vectored_read_bytes,
     448           75 :             key_range: actual_summary.key_range,
     449           75 :         })
     450           75 :     }
     451              : 
     452              :     // Look up the keys in the provided keyspace and update
     453              :     // the reconstruct state with whatever is found.
     454        14128 :     pub(super) async fn get_values_reconstruct_data(
     455        14128 :         &self,
     456        14128 :         this: ResidentLayer,
     457        14128 :         keyspace: KeySpace,
     458        14128 :         reconstruct_state: &mut ValuesReconstructState,
     459        14128 :         ctx: &RequestContext,
     460        14128 :     ) -> Result<(), GetVectoredError> {
     461        14128 :         let reads = self
     462        14128 :             .plan_reads(keyspace, None, ctx)
     463        14128 :             .await
     464        14128 :             .map_err(GetVectoredError::Other)?;
     465              : 
     466        14128 :         self.do_reads_and_update_state(this, reads, reconstruct_state, ctx)
     467        14128 :             .await;
     468              : 
     469        14128 :         reconstruct_state.on_image_layer_visited(&self.key_range);
     470              : 
     471        14128 :         Ok(())
     472        14128 :     }
     473              : 
     474              :     /// Traverse the layer's index to build read operations on the overlap of the input keyspace
     475              :     /// and the keys in this layer.
     476              :     ///
     477              :     /// If shard_identity is provided, it will be used to filter keys down to those stored on
     478              :     /// this shard.
     479        14132 :     async fn plan_reads(
     480        14132 :         &self,
     481        14132 :         keyspace: KeySpace,
     482        14132 :         shard_identity: Option<&ShardIdentity>,
     483        14132 :         ctx: &RequestContext,
     484        14132 :     ) -> anyhow::Result<Vec<VectoredRead>> {
     485        14132 :         let mut planner = VectoredReadPlanner::new(
     486        14132 :             self.max_vectored_read_bytes
     487        14132 :                 .expect("Layer is loaded with max vectored bytes config")
     488        14132 :                 .0
     489        14132 :                 .into(),
     490              :         );
     491              : 
     492        14132 :         let block_reader = FileBlockReader::new(&self.file, self.file_id);
     493        14132 :         let tree_reader =
     494        14132 :             DiskBtreeReader::new(self.index_start_blk, self.index_root_blk, block_reader);
     495              : 
     496        14132 :         let ctx = RequestContextBuilder::from(ctx)
     497        14132 :             .page_content_kind(PageContentKind::ImageLayerBtreeNode)
     498        14132 :             .attached_child();
     499              : 
     500        21431 :         for range in keyspace.ranges.iter() {
     501        21431 :             let mut range_end_handled = false;
     502        21431 :             let mut search_key: [u8; KEY_SIZE] = [0u8; KEY_SIZE];
     503        21431 :             range.start.write_to_byte_slice(&mut search_key);
     504              : 
     505        21431 :             let index_stream = tree_reader.clone().into_stream(&search_key, &ctx);
     506        21431 :             let mut index_stream = std::pin::pin!(index_stream);
     507              : 
     508        97797 :             while let Some(index_entry) = index_stream.next().await {
     509        97415 :                 let (raw_key, offset) = index_entry?;
     510              : 
     511        97415 :                 let key = Key::from_slice(&raw_key[..KEY_SIZE]);
     512        97415 :                 assert!(key >= range.start);
     513              : 
     514        97415 :                 let flag = if let Some(shard_identity) = shard_identity {
     515        32768 :                     if shard_identity.is_key_disposable(&key) {
     516        24576 :                         BlobFlag::Ignore
     517              :                     } else {
     518         8192 :                         BlobFlag::None
     519              :                     }
     520              :                 } else {
     521        64647 :                     BlobFlag::None
     522              :                 };
     523              : 
     524        97415 :                 if key >= range.end {
     525        21049 :                     planner.handle_range_end(offset);
     526        21049 :                     range_end_handled = true;
     527        21049 :                     break;
     528        76366 :                 } else {
     529        76366 :                     planner.handle(key, self.lsn, offset, flag);
     530        76366 :                 }
     531              :             }
     532              : 
     533        21431 :             if !range_end_handled {
     534          382 :                 let payload_end = self.index_start_blk as u64 * PAGE_SZ as u64;
     535          382 :                 planner.handle_range_end(payload_end);
     536        21049 :             }
     537              :         }
     538              : 
     539        14132 :         Ok(planner.finish())
     540        14132 :     }
     541              : 
     542              :     /// Given a key range, select the parts of that range that should be retained by the ShardIdentity,
     543              :     /// then execute vectored GET operations, passing the results of all read keys into the writer.
     544            4 :     pub(super) async fn filter(
     545            4 :         &self,
     546            4 :         shard_identity: &ShardIdentity,
     547            4 :         writer: &mut ImageLayerWriter,
     548            4 :         ctx: &RequestContext,
     549            4 :     ) -> anyhow::Result<usize> {
     550              :         // Fragment the range into the regions owned by this ShardIdentity
     551            4 :         let plan = self
     552            4 :             .plan_reads(
     553            4 :                 KeySpace {
     554            4 :                     // If asked for the total key space, plan_reads will give us all the keys in the layer
     555            4 :                     ranges: vec![Key::MIN..Key::MAX],
     556            4 :                 },
     557            4 :                 Some(shard_identity),
     558            4 :                 ctx,
     559            4 :             )
     560            4 :             .await?;
     561              : 
     562            4 :         let vectored_blob_reader = VectoredBlobReader::new(&self.file);
     563            4 :         let mut key_count = 0;
     564            4 :         for read in plan.into_iter() {
     565            4 :             let buf_size = read.size();
     566              : 
     567            4 :             let buf = IoBufferMut::with_capacity(buf_size);
     568            4 :             let blobs_buf = vectored_blob_reader.read_blobs(&read, buf, ctx).await?;
     569              : 
     570            4 :             let view = BufView::new_slice(&blobs_buf.buf);
     571              : 
     572         8192 :             for meta in blobs_buf.blobs.iter() {
     573              :                 // Just read the raw header+data and pass it through to the target layer, without
     574              :                 // decoding and recompressing it.
     575         8192 :                 let raw = meta.raw_with_header(&view);
     576         8192 :                 key_count += 1;
     577         8192 :                 writer
     578         8192 :                     .put_image_raw(meta.meta.key, raw.into_bytes(), ctx)
     579         8192 :                     .await
     580         8192 :                     .context(format!("Storing key {}", meta.meta.key))?;
     581              :             }
     582              :         }
     583              : 
     584            4 :         Ok(key_count)
     585            4 :     }
     586              : 
     587        14128 :     async fn do_reads_and_update_state(
     588        14128 :         &self,
     589        14128 :         this: ResidentLayer,
     590        14128 :         reads: Vec<VectoredRead>,
     591        14128 :         reconstruct_state: &mut ValuesReconstructState,
     592        14128 :         ctx: &RequestContext,
     593        14128 :     ) {
     594        14128 :         let max_vectored_read_bytes = self
     595        14128 :             .max_vectored_read_bytes
     596        14128 :             .expect("Layer is loaded with max vectored bytes config")
     597        14128 :             .0
     598        14128 :             .into();
     599              : 
     600        16273 :         for read in reads.into_iter() {
     601        16273 :             let mut ios: HashMap<(Key, Lsn), OnDiskValueIo> = Default::default();
     602        43598 :             for (_, blob_meta) in read.blobs_at.as_slice() {
     603        43598 :                 let io = reconstruct_state.update_key(&blob_meta.key, blob_meta.lsn, true);
     604        43598 :                 ios.insert((blob_meta.key, blob_meta.lsn), io);
     605        43598 :             }
     606              : 
     607        16273 :             let buf_size = read.size();
     608              : 
     609        16273 :             if buf_size > max_vectored_read_bytes {
     610              :                 // If the read is oversized, it should only contain one key.
     611            0 :                 let offenders = read
     612            0 :                     .blobs_at
     613            0 :                     .as_slice()
     614            0 :                     .iter()
     615            0 :                     .filter_map(|(_, blob_meta)| {
     616            0 :                         if blob_meta.key.is_rel_dir_key()
     617            0 :                             || blob_meta.key == DBDIR_KEY
     618            0 :                             || blob_meta.key.is_aux_file_key()
     619              :                         {
     620              :                             // The size of values for these keys is unbounded and can
     621              :                             // grow very large in pathological cases.
     622            0 :                             None
     623              :                         } else {
     624            0 :                             Some(format!("{}@{}", blob_meta.key, blob_meta.lsn))
     625              :                         }
     626            0 :                     })
     627            0 :                     .join(", ");
     628              : 
     629            0 :                 if !offenders.is_empty() {
     630            0 :                     tracing::warn!(
     631            0 :                         "Oversized vectored read ({} > {}) for keys {}",
     632              :                         buf_size,
     633              :                         max_vectored_read_bytes,
     634              :                         offenders
     635              :                     );
     636            0 :                 }
     637        16273 :             }
     638              : 
     639        16273 :             let read_extend_residency = this.clone();
     640        16273 :             let read_from = self.file.clone();
     641        16273 :             let read_ctx = ctx.attached_child();
     642        16273 :             reconstruct_state
     643        16273 :                 .spawn_io(async move {
     644        16273 :                     let buf = IoBufferMut::with_capacity(buf_size);
     645        16273 :                     let vectored_blob_reader = VectoredBlobReader::new(&read_from);
     646        16273 :                     let res = vectored_blob_reader.read_blobs(&read, buf, &read_ctx).await;
     647              : 
     648        16273 :                     match res {
     649        16273 :                         Ok(blobs_buf) => {
     650        16273 :                             let view = BufView::new_slice(&blobs_buf.buf);
     651        43598 :                             for meta in blobs_buf.blobs.iter() {
     652        43598 :                                 let io: OnDiskValueIo =
     653        43598 :                                     ios.remove(&(meta.meta.key, meta.meta.lsn)).unwrap();
     654        43598 :                                 let img_buf = meta.read(&view).await;
     655              : 
     656        43598 :                                 let img_buf = match img_buf {
     657        43598 :                                     Ok(img_buf) => img_buf,
     658            0 :                                     Err(e) => {
     659            0 :                                         io.complete(Err(e));
     660            0 :                                         continue;
     661              :                                     }
     662              :                                 };
     663              : 
     664        43598 :                                 io.complete(Ok(OnDiskValue::RawImage(img_buf.into_bytes())));
     665              :                             }
     666              : 
     667        16273 :                             assert!(ios.is_empty());
     668              :                         }
     669            0 :                         Err(err) => {
     670            0 :                             for (_, io) in ios {
     671            0 :                                 io.complete(Err(std::io::Error::new(
     672            0 :                                     err.kind(),
     673            0 :                                     "vec read failed",
     674            0 :                                 )));
     675            0 :                             }
     676              :                         }
     677              :                     }
     678              : 
     679              :                     // keep layer resident until this IO is done; this spawned IO future generally outlives the
     680              :                     // call to `self` / the `Arc<DownloadedLayer>` / the `ResidentLayer` that guarantees residency
     681        16273 :                     drop(read_extend_residency);
     682        16273 :                 })
     683        16273 :                 .await;
     684              :         }
     685        14128 :     }
     686              : 
     687           63 :     pub(crate) fn iter_with_options<'a>(
     688           63 :         &'a self,
     689           63 :         ctx: &'a RequestContext,
     690           63 :         max_read_size: u64,
     691           63 :         max_batch_size: usize,
     692           63 :     ) -> ImageLayerIterator<'a> {
     693           63 :         let block_reader = FileBlockReader::new(&self.file, self.file_id);
     694           63 :         let tree_reader =
     695           63 :             DiskBtreeReader::new(self.index_start_blk, self.index_root_blk, block_reader);
     696           63 :         ImageLayerIterator {
     697           63 :             image_layer: self,
     698           63 :             ctx,
     699           63 :             index_iter: tree_reader.iter(&[0; KEY_SIZE], ctx),
     700           63 :             key_values_batch: VecDeque::new(),
     701           63 :             is_end: false,
     702           63 :             planner: StreamingVectoredReadPlanner::new(max_read_size, max_batch_size),
     703           63 :         }
     704           63 :     }
     705              : 
     706              :     /// NB: not super efficient, but not terrible either. Should prob be an iterator.
     707              :     //
     708              :     // We're reusing the index traversal logical in plan_reads; would be nice to
     709              :     // factor that out.
     710            0 :     pub(crate) async fn load_keys(&self, ctx: &RequestContext) -> anyhow::Result<Vec<Key>> {
     711            0 :         let plan = self
     712            0 :             .plan_reads(KeySpace::single(self.key_range.clone()), None, ctx)
     713            0 :             .await?;
     714            0 :         Ok(plan
     715            0 :             .into_iter()
     716            0 :             .flat_map(|read| read.blobs_at)
     717            0 :             .map(|(_, blob_meta)| blob_meta.key)
     718            0 :             .collect())
     719            0 :     }
     720              : }
     721              : 
     722              : /// A builder object for constructing a new image layer.
     723              : ///
     724              : /// Usage:
     725              : ///
     726              : /// 1. Create the ImageLayerWriter by calling ImageLayerWriter::new(...)
     727              : ///
     728              : /// 2. Write the contents by calling `put_page_image` for every key-value
     729              : ///    pair in the key range.
     730              : ///
     731              : /// 3. Call `finish`.
     732              : ///
     733              : struct ImageLayerWriterInner {
     734              :     conf: &'static PageServerConf,
     735              :     path: Utf8PathBuf,
     736              :     timeline_id: TimelineId,
     737              :     tenant_shard_id: TenantShardId,
     738              :     key_range: Range<Key>,
     739              :     lsn: Lsn,
     740              : 
     741              :     // Total uncompressed bytes passed into put_image
     742              :     uncompressed_bytes: u64,
     743              : 
     744              :     // Like `uncompressed_bytes`,
     745              :     // but only of images we might consider for compression
     746              :     uncompressed_bytes_eligible: u64,
     747              : 
     748              :     // Like `uncompressed_bytes`, but only of images
     749              :     // where we have chosen their compressed form
     750              :     uncompressed_bytes_chosen: u64,
     751              : 
     752              :     // Number of keys in the layer.
     753              :     num_keys: usize,
     754              : 
     755              :     blob_writer: BlobWriter<TempVirtualFile>,
     756              :     tree: DiskBtreeBuilder<BlockBuf, KEY_SIZE>,
     757              : 
     758              :     #[cfg(feature = "testing")]
     759              :     last_written_key: Key,
     760              : }
     761              : 
     762              : impl ImageLayerWriterInner {
     763              :     ///
     764              :     /// Start building a new image layer.
     765              :     ///
     766              :     #[allow(clippy::too_many_arguments)]
     767          368 :     async fn new(
     768          368 :         conf: &'static PageServerConf,
     769          368 :         timeline_id: TimelineId,
     770          368 :         tenant_shard_id: TenantShardId,
     771          368 :         key_range: &Range<Key>,
     772          368 :         lsn: Lsn,
     773          368 :         gate: &utils::sync::gate::Gate,
     774          368 :         cancel: CancellationToken,
     775          368 :         ctx: &RequestContext,
     776          368 :     ) -> anyhow::Result<Self> {
     777              :         // Create the file initially with a temporary filename.
     778              :         // We'll atomically rename it to the final name when we're done.
     779          368 :         let path = ImageLayer::temp_path_for(
     780          368 :             conf,
     781          368 :             timeline_id,
     782          368 :             tenant_shard_id,
     783          368 :             &ImageLayerName {
     784          368 :                 key_range: key_range.clone(),
     785          368 :                 lsn,
     786          368 :             },
     787              :         );
     788          368 :         trace!("creating image layer {}", path);
     789          368 :         let file = TempVirtualFile::new(
     790          368 :             VirtualFile::open_with_options_v2(
     791          368 :                 &path,
     792          368 :                 virtual_file::OpenOptions::new()
     793          368 :                     .create_new(true)
     794          368 :                     .write(true),
     795          368 :                 ctx,
     796          368 :             )
     797          368 :             .await?,
     798          368 :             gate.enter()?,
     799              :         );
     800              : 
     801              :         // Start at `PAGE_SZ` to make room for the header block.
     802          368 :         let blob_writer = BlobWriter::new(
     803          368 :             file,
     804          368 :             PAGE_SZ as u64,
     805          368 :             gate,
     806          368 :             cancel,
     807          368 :             ctx,
     808          368 :             info_span!(parent: None, "image_layer_writer_flush_task", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), timeline_id=%timeline_id, path = %path),
     809            0 :         )?;
     810              : 
     811              :         // Initialize the b-tree index builder
     812          368 :         let block_buf = BlockBuf::new();
     813          368 :         let tree_builder = DiskBtreeBuilder::new(block_buf);
     814              : 
     815          368 :         let writer = Self {
     816          368 :             conf,
     817          368 :             path,
     818          368 :             timeline_id,
     819          368 :             tenant_shard_id,
     820          368 :             key_range: key_range.clone(),
     821          368 :             lsn,
     822          368 :             tree: tree_builder,
     823          368 :             blob_writer,
     824          368 :             uncompressed_bytes: 0,
     825          368 :             uncompressed_bytes_eligible: 0,
     826          368 :             uncompressed_bytes_chosen: 0,
     827          368 :             num_keys: 0,
     828          368 :             #[cfg(feature = "testing")]
     829          368 :             last_written_key: Key::MIN,
     830          368 :         };
     831              : 
     832          368 :         Ok(writer)
     833          368 :     }
     834              : 
     835              :     ///
     836              :     /// Write next value to the file.
     837              :     ///
     838              :     /// The page versions must be appended in blknum order.
     839              :     ///
     840        19590 :     async fn put_image(
     841        19590 :         &mut self,
     842        19590 :         key: Key,
     843        19590 :         img: Bytes,
     844        19590 :         ctx: &RequestContext,
     845        19590 :     ) -> Result<(), PutError> {
     846        19590 :         if !self.key_range.contains(&key) {
     847            0 :             return Err(PutError::Other(anyhow::anyhow!(
     848            0 :                 "key {:?} not in range {:?}",
     849            0 :                 key,
     850            0 :                 self.key_range
     851            0 :             )));
     852        19590 :         }
     853        19590 :         let compression = self.conf.image_compression;
     854        19590 :         let uncompressed_len = img.len() as u64;
     855        19590 :         self.uncompressed_bytes += uncompressed_len;
     856        19590 :         self.num_keys += 1;
     857        19590 :         let (_img, res) = self
     858        19590 :             .blob_writer
     859        19590 :             .write_blob_maybe_compressed(img.slice_len(), ctx, compression)
     860        19590 :             .await;
     861              :         // TODO: re-use the buffer for `img` further upstack
     862        19590 :         let (off, compression_info) = res.map_err(PutError::WriteBlob)?;
     863        19590 :         if compression_info.compressed_size.is_some() {
     864         4001 :             // The image has been considered for compression at least
     865         4001 :             self.uncompressed_bytes_eligible += uncompressed_len;
     866        15589 :         }
     867        19590 :         if compression_info.written_compressed {
     868            0 :             // The image has been compressed
     869            0 :             self.uncompressed_bytes_chosen += uncompressed_len;
     870        19590 :         }
     871              : 
     872        19590 :         let mut keybuf: [u8; KEY_SIZE] = [0u8; KEY_SIZE];
     873        19590 :         key.write_to_byte_slice(&mut keybuf);
     874        19590 :         self.tree
     875        19590 :             .append(&keybuf, off)
     876        19590 :             .map_err(anyhow::Error::new)
     877        19590 :             .map_err(PutError::Other)?;
     878              : 
     879              :         #[cfg(feature = "testing")]
     880        19590 :         {
     881        19590 :             self.last_written_key = key;
     882        19590 :         }
     883              : 
     884        19590 :         Ok(())
     885        19590 :     }
     886              : 
     887              :     ///
     888              :     /// Write the next image to the file, as a raw blob header and data.
     889              :     ///
     890              :     /// The page versions must be appended in blknum order.
     891              :     ///
     892         8192 :     async fn put_image_raw(
     893         8192 :         &mut self,
     894         8192 :         key: Key,
     895         8192 :         raw_with_header: Bytes,
     896         8192 :         ctx: &RequestContext,
     897         8192 :     ) -> anyhow::Result<()> {
     898         8192 :         ensure!(self.key_range.contains(&key));
     899              : 
     900              :         // NB: we don't update the (un)compressed metrics, since we can't determine them without
     901              :         // decompressing the image. This seems okay.
     902         8192 :         self.num_keys += 1;
     903              : 
     904         8192 :         let (_, res) = self
     905         8192 :             .blob_writer
     906         8192 :             .write_blob_raw(raw_with_header.slice_len(), ctx)
     907         8192 :             .await;
     908         8192 :         let offset = res?;
     909              : 
     910         8192 :         let mut keybuf: [u8; KEY_SIZE] = [0u8; KEY_SIZE];
     911         8192 :         key.write_to_byte_slice(&mut keybuf);
     912         8192 :         self.tree.append(&keybuf, offset)?;
     913              : 
     914              :         #[cfg(feature = "testing")]
     915         8192 :         {
     916         8192 :             self.last_written_key = key;
     917         8192 :         }
     918              : 
     919         8192 :         Ok(())
     920         8192 :     }
     921              : 
     922              :     ///
     923              :     /// Finish writing the image layer.
     924              :     ///
     925          193 :     async fn finish(
     926          193 :         self,
     927          193 :         ctx: &RequestContext,
     928          193 :         end_key: Option<Key>,
     929          193 :     ) -> anyhow::Result<(PersistentLayerDesc, Utf8PathBuf)> {
     930          193 :         let index_start_blk = self.blob_writer.size().div_ceil(PAGE_SZ as u64) as u32;
     931              : 
     932              :         // Calculate compression ratio
     933          193 :         let compressed_size = self.blob_writer.size() - PAGE_SZ as u64; // Subtract PAGE_SZ for header
     934          193 :         crate::metrics::COMPRESSION_IMAGE_INPUT_BYTES.inc_by(self.uncompressed_bytes);
     935          193 :         crate::metrics::COMPRESSION_IMAGE_INPUT_BYTES_CONSIDERED
     936          193 :             .inc_by(self.uncompressed_bytes_eligible);
     937          193 :         crate::metrics::COMPRESSION_IMAGE_INPUT_BYTES_CHOSEN.inc_by(self.uncompressed_bytes_chosen);
     938              : 
     939              :         // NB: filter() may pass through raw pages from a different layer, without looking at
     940              :         // whether these are compressed or not. We don't track metrics for these, so avoid
     941              :         // increasing `COMPRESSION_IMAGE_OUTPUT_BYTES` in this case too.
     942          193 :         if self.uncompressed_bytes > 0 {
     943          190 :             crate::metrics::COMPRESSION_IMAGE_OUTPUT_BYTES.inc_by(compressed_size);
     944          190 :         };
     945              : 
     946          193 :         let file = self
     947          193 :             .blob_writer
     948          193 :             .shutdown(
     949          193 :                 BufferedWriterShutdownMode::ZeroPadToNextMultiple(PAGE_SZ),
     950          193 :                 ctx,
     951          193 :             )
     952          193 :             .await?;
     953              : 
     954              :         // Write out the index
     955          193 :         let mut offset = index_start_blk as u64 * PAGE_SZ as u64;
     956          193 :         let (index_root_blk, block_buf) = self.tree.finish()?;
     957              : 
     958              :         // TODO(yuchen): https://github.com/neondatabase/neon/issues/10092
     959              :         // Should we just replace BlockBuf::blocks with one big buffer?
     960          402 :         for buf in block_buf.blocks {
     961          209 :             let (_buf, res) = file.write_all_at(buf.slice_len(), offset, ctx).await;
     962          209 :             res?;
     963          209 :             offset += PAGE_SZ as u64;
     964              :         }
     965              : 
     966          193 :         let final_key_range = if let Some(end_key) = end_key {
     967          152 :             self.key_range.start..end_key
     968              :         } else {
     969           41 :             self.key_range.clone()
     970              :         };
     971              : 
     972              :         // Fill in the summary on blk 0
     973          193 :         let summary = Summary {
     974          193 :             magic: IMAGE_FILE_MAGIC,
     975          193 :             format_version: STORAGE_FORMAT_VERSION,
     976          193 :             tenant_id: self.tenant_shard_id.tenant_id,
     977          193 :             timeline_id: self.timeline_id,
     978          193 :             key_range: final_key_range.clone(),
     979          193 :             lsn: self.lsn,
     980          193 :             index_start_blk,
     981          193 :             index_root_blk,
     982          193 :         };
     983              : 
     984              :         // Writes summary at the first block (offset 0).
     985          193 :         let buf = summary.ser_into_page()?;
     986          193 :         let (_buf, res) = file.write_all_at(buf.slice_len(), 0, ctx).await;
     987          193 :         res?;
     988              : 
     989          193 :         let metadata = file
     990          193 :             .metadata()
     991          193 :             .await
     992          193 :             .context("get metadata to determine file size")?;
     993              : 
     994          193 :         let desc = PersistentLayerDesc::new_img(
     995          193 :             self.tenant_shard_id,
     996          193 :             self.timeline_id,
     997          193 :             final_key_range,
     998          193 :             self.lsn,
     999          193 :             metadata.len(),
    1000              :         );
    1001              : 
    1002              :         #[cfg(feature = "testing")]
    1003          193 :         if let Some(end_key) = end_key {
    1004          152 :             assert!(
    1005          152 :                 self.last_written_key < end_key,
    1006            0 :                 "written key violates end_key range"
    1007              :             );
    1008           41 :         }
    1009              : 
    1010              :         // Note: Because we open the file in write-only mode, we cannot
    1011              :         // reuse the same VirtualFile for reading later. That's why we don't
    1012              :         // set inner.file here. The first read will have to re-open it.
    1013              : 
    1014              :         // fsync the file
    1015          193 :         file.sync_all()
    1016          193 :             .await
    1017          193 :             .maybe_fatal_err("image_layer sync_all")?;
    1018              : 
    1019          193 :         trace!("created image layer {}", self.path);
    1020              : 
    1021              :         // The gate guard stored in `destination_file` is dropped. Callers (e.g.. flush loop or compaction)
    1022              :         // keep the gate open also, so that it's safe for them to rename the file to its final destination.
    1023          193 :         file.disarm_into_inner();
    1024              : 
    1025          193 :         Ok((desc, self.path))
    1026          193 :     }
    1027              : }
    1028              : 
    1029              : /// A builder object for constructing a new image layer.
    1030              : ///
    1031              : /// Usage:
    1032              : ///
    1033              : /// 1. Create the ImageLayerWriter by calling ImageLayerWriter::new(...)
    1034              : ///
    1035              : /// 2. Write the contents by calling `put_page_image` for every key-value
    1036              : ///    pair in the key range.
    1037              : ///
    1038              : /// 3. Call `finish`.
    1039              : ///
    1040              : /// # Note
    1041              : ///
    1042              : /// As described in <https://github.com/neondatabase/neon/issues/2650>, it's
    1043              : /// possible for the writer to drop before `finish` is actually called. So this
    1044              : /// could lead to odd temporary files in the directory, exhausting file system.
    1045              : /// This structure wraps `ImageLayerWriterInner` and also contains `Drop`
    1046              : /// implementation that cleans up the temporary file in failure. It's not
    1047              : /// possible to do this directly in `ImageLayerWriterInner` since `finish` moves
    1048              : /// out some fields, making it impossible to implement `Drop`.
    1049              : ///
    1050              : #[must_use]
    1051              : pub struct ImageLayerWriter {
    1052              :     inner: Option<ImageLayerWriterInner>,
    1053              : }
    1054              : 
    1055              : impl ImageLayerWriter {
    1056              :     ///
    1057              :     /// Start building a new image layer.
    1058              :     ///
    1059              :     #[allow(clippy::too_many_arguments)]
    1060          368 :     pub async fn new(
    1061          368 :         conf: &'static PageServerConf,
    1062          368 :         timeline_id: TimelineId,
    1063          368 :         tenant_shard_id: TenantShardId,
    1064          368 :         key_range: &Range<Key>,
    1065          368 :         lsn: Lsn,
    1066          368 :         gate: &utils::sync::gate::Gate,
    1067          368 :         cancel: CancellationToken,
    1068          368 :         ctx: &RequestContext,
    1069          368 :     ) -> anyhow::Result<ImageLayerWriter> {
    1070              :         Ok(Self {
    1071              :             inner: Some(
    1072          368 :                 ImageLayerWriterInner::new(
    1073          368 :                     conf,
    1074          368 :                     timeline_id,
    1075          368 :                     tenant_shard_id,
    1076          368 :                     key_range,
    1077          368 :                     lsn,
    1078          368 :                     gate,
    1079          368 :                     cancel,
    1080          368 :                     ctx,
    1081          368 :                 )
    1082          368 :                 .await?,
    1083              :             ),
    1084              :         })
    1085          368 :     }
    1086              : 
    1087              :     ///
    1088              :     /// Write next value to the file.
    1089              :     ///
    1090              :     /// The page versions must be appended in blknum order.
    1091              :     ///
    1092        19590 :     pub async fn put_image(
    1093        19590 :         &mut self,
    1094        19590 :         key: Key,
    1095        19590 :         img: Bytes,
    1096        19590 :         ctx: &RequestContext,
    1097        19590 :     ) -> Result<(), PutError> {
    1098        19590 :         self.inner.as_mut().unwrap().put_image(key, img, ctx).await
    1099        19590 :     }
    1100              : 
    1101              :     ///
    1102              :     /// Write the next value to the file, as a raw header and data. This allows passing through a
    1103              :     /// raw, potentially compressed image from a different layer file without recompressing it.
    1104              :     ///
    1105              :     /// The page versions must be appended in blknum order.
    1106              :     ///
    1107         8192 :     pub async fn put_image_raw(
    1108         8192 :         &mut self,
    1109         8192 :         key: Key,
    1110         8192 :         raw_with_header: Bytes,
    1111         8192 :         ctx: &RequestContext,
    1112         8192 :     ) -> anyhow::Result<()> {
    1113         8192 :         self.inner
    1114         8192 :             .as_mut()
    1115         8192 :             .unwrap()
    1116         8192 :             .put_image_raw(key, raw_with_header, ctx)
    1117         8192 :             .await
    1118         8192 :     }
    1119              : 
    1120              :     /// Estimated size of the image layer.
    1121         4277 :     pub(crate) fn estimated_size(&self) -> u64 {
    1122         4277 :         let inner = self.inner.as_ref().unwrap();
    1123         4277 :         inner.blob_writer.size() + inner.tree.borrow_writer().size() + PAGE_SZ as u64
    1124         4277 :     }
    1125              : 
    1126         4326 :     pub(crate) fn num_keys(&self) -> usize {
    1127         4326 :         self.inner.as_ref().unwrap().num_keys
    1128         4326 :     }
    1129              : 
    1130              :     ///
    1131              :     /// Finish writing the image layer.
    1132              :     ///
    1133           41 :     pub(crate) async fn finish(
    1134           41 :         mut self,
    1135           41 :         ctx: &RequestContext,
    1136           41 :     ) -> anyhow::Result<(PersistentLayerDesc, Utf8PathBuf)> {
    1137           41 :         self.inner.take().unwrap().finish(ctx, None).await
    1138           41 :     }
    1139              : 
    1140              :     /// Finish writing the image layer with an end key, used in [`super::batch_split_writer::SplitImageLayerWriter`]. The end key determines the end of the image layer's covered range and is exclusive.
    1141          152 :     pub(super) async fn finish_with_end_key(
    1142          152 :         mut self,
    1143          152 :         end_key: Key,
    1144          152 :         ctx: &RequestContext,
    1145          152 :     ) -> anyhow::Result<(PersistentLayerDesc, Utf8PathBuf)> {
    1146          152 :         self.inner.take().unwrap().finish(ctx, Some(end_key)).await
    1147          152 :     }
    1148              : }
    1149              : 
    1150              : pub struct ImageLayerIterator<'a> {
    1151              :     image_layer: &'a ImageLayerInner,
    1152              :     ctx: &'a RequestContext,
    1153              :     planner: StreamingVectoredReadPlanner,
    1154              :     index_iter: DiskBtreeIterator<'a>,
    1155              :     key_values_batch: VecDeque<(Key, Lsn, Value)>,
    1156              :     is_end: bool,
    1157              : }
    1158              : 
    1159              : impl ImageLayerIterator<'_> {
    1160            0 :     pub(crate) fn layer_dbg_info(&self) -> String {
    1161            0 :         self.image_layer.layer_dbg_info()
    1162            0 :     }
    1163              : 
    1164              :     /// Retrieve a batch of key-value pairs into the iterator buffer.
    1165         9565 :     async fn next_batch(&mut self) -> anyhow::Result<()> {
    1166         9565 :         assert!(self.key_values_batch.is_empty());
    1167         9565 :         assert!(!self.is_end);
    1168              : 
    1169         9565 :         let plan = loop {
    1170        14537 :             if let Some(res) = self.index_iter.next().await {
    1171        14488 :                 let (raw_key, offset) = res?;
    1172        14488 :                 if let Some(batch_plan) = self.planner.handle(
    1173        14488 :                     Key::from_slice(&raw_key[..KEY_SIZE]),
    1174        14488 :                     self.image_layer.lsn,
    1175        14488 :                     offset,
    1176        14488 :                     true,
    1177        14488 :                 ) {
    1178         9516 :                     break batch_plan;
    1179         4972 :                 }
    1180              :             } else {
    1181           49 :                 self.is_end = true;
    1182           49 :                 let payload_end = self.image_layer.index_start_blk as u64 * PAGE_SZ as u64;
    1183           49 :                 if let Some(item) = self.planner.handle_range_end(payload_end) {
    1184           49 :                     break item;
    1185              :                 } else {
    1186            0 :                     return Ok(()); // TODO: a test case on empty iterator
    1187              :                 }
    1188              :             }
    1189              :         };
    1190         9565 :         let vectored_blob_reader = VectoredBlobReader::new(&self.image_layer.file);
    1191         9565 :         let mut next_batch = std::collections::VecDeque::new();
    1192         9565 :         let buf_size = plan.size();
    1193         9565 :         let buf = IoBufferMut::with_capacity(buf_size);
    1194         9565 :         let blobs_buf = vectored_blob_reader
    1195         9565 :             .read_blobs(&plan, buf, self.ctx)
    1196         9565 :             .await?;
    1197         9565 :         let view = BufView::new_slice(&blobs_buf.buf);
    1198        14474 :         for meta in blobs_buf.blobs.iter() {
    1199        14474 :             let img_buf = meta.read(&view).await?;
    1200        14474 :             next_batch.push_back((
    1201        14474 :                 meta.meta.key,
    1202        14474 :                 self.image_layer.lsn,
    1203        14474 :                 Value::Image(img_buf.into_bytes()),
    1204        14474 :             ));
    1205              :         }
    1206         9565 :         self.key_values_batch = next_batch;
    1207         9565 :         Ok(())
    1208         9565 :     }
    1209              : 
    1210        14414 :     pub async fn next(&mut self) -> anyhow::Result<Option<(Key, Lsn, Value)>> {
    1211        14414 :         if self.key_values_batch.is_empty() {
    1212         9604 :             if self.is_end {
    1213           81 :                 return Ok(None);
    1214         9523 :             }
    1215         9523 :             self.next_batch().await?;
    1216         4810 :         }
    1217        14333 :         Ok(Some(
    1218        14333 :             self.key_values_batch
    1219        14333 :                 .pop_front()
    1220        14333 :                 .expect("should not be empty"),
    1221        14333 :         ))
    1222        14414 :     }
    1223              : }
    1224              : 
    1225              : #[cfg(test)]
    1226              : mod test {
    1227              :     use std::sync::Arc;
    1228              :     use std::time::Duration;
    1229              : 
    1230              :     use bytes::Bytes;
    1231              :     use itertools::Itertools;
    1232              :     use pageserver_api::key::Key;
    1233              :     use pageserver_api::shard::{ShardCount, ShardIdentity, ShardNumber, ShardStripeSize};
    1234              :     use utils::generation::Generation;
    1235              :     use utils::id::{TenantId, TimelineId};
    1236              :     use utils::lsn::Lsn;
    1237              :     use wal_decoder::models::value::Value;
    1238              : 
    1239              :     use super::{ImageLayerIterator, ImageLayerWriter};
    1240              :     use crate::DEFAULT_PG_VERSION;
    1241              :     use crate::context::RequestContext;
    1242              :     use crate::tenant::harness::{TIMELINE_ID, TenantHarness};
    1243              :     use crate::tenant::storage_layer::{Layer, ResidentLayer};
    1244              :     use crate::tenant::{TenantShard, Timeline};
    1245              : 
    1246              :     #[tokio::test]
    1247            1 :     async fn image_layer_rewrite() {
    1248            1 :         let tenant_conf = pageserver_api::models::TenantConfig {
    1249            1 :             gc_period: Some(Duration::ZERO),
    1250            1 :             compaction_period: Some(Duration::ZERO),
    1251            1 :             ..Default::default()
    1252            1 :         };
    1253            1 :         let tenant_id = TenantId::generate();
    1254            1 :         let mut gen_ = Generation::new(0xdead0001);
    1255            5 :         let mut get_next_gen = || {
    1256            5 :             let ret = gen_;
    1257            5 :             gen_ = gen_.next();
    1258            5 :             ret
    1259            5 :         };
    1260              :         // The LSN at which we will create an image layer to filter
    1261            1 :         let lsn = Lsn(0xdeadbeef0000);
    1262            1 :         let timeline_id = TimelineId::generate();
    1263              : 
    1264              :         //
    1265              :         // Create an unsharded parent with a layer.
    1266              :         //
    1267              : 
    1268            1 :         let harness = TenantHarness::create_custom(
    1269            1 :             "test_image_layer_rewrite--parent",
    1270            1 :             tenant_conf.clone(),
    1271            1 :             tenant_id,
    1272            1 :             ShardIdentity::unsharded(),
    1273            1 :             get_next_gen(),
    1274            1 :         )
    1275            1 :         .await
    1276            1 :         .unwrap();
    1277            1 :         let (tenant, ctx) = harness.load().await;
    1278            1 :         let timeline = tenant
    1279            1 :             .create_test_timeline(timeline_id, lsn, DEFAULT_PG_VERSION, &ctx)
    1280            1 :             .await
    1281            1 :             .unwrap();
    1282              : 
    1283              :         // This key range contains several 0x8000 page stripes, only one of which belongs to shard zero
    1284            1 :         let input_start = Key::from_hex("000000067f00000001000000ae0000000000").unwrap();
    1285            1 :         let input_end = Key::from_hex("000000067f00000001000000ae0000002000").unwrap();
    1286            1 :         let range = input_start..input_end;
    1287              : 
    1288              :         // Build an image layer to filter
    1289            1 :         let resident = {
    1290            1 :             let mut writer = ImageLayerWriter::new(
    1291            1 :                 harness.conf,
    1292            1 :                 timeline_id,
    1293            1 :                 harness.tenant_shard_id,
    1294            1 :                 &range,
    1295            1 :                 lsn,
    1296            1 :                 &timeline.gate,
    1297            1 :                 timeline.cancel.clone(),
    1298            1 :                 &ctx,
    1299            1 :             )
    1300            1 :             .await
    1301            1 :             .unwrap();
    1302              : 
    1303            1 :             let foo_img = Bytes::from_static(&[1, 2, 3, 4]);
    1304            1 :             let mut key = range.start;
    1305         8193 :             while key < range.end {
    1306         8192 :                 writer.put_image(key, foo_img.clone(), &ctx).await.unwrap();
    1307              : 
    1308         8192 :                 key = key.next();
    1309              :             }
    1310            1 :             let (desc, path) = writer.finish(&ctx).await.unwrap();
    1311            1 :             Layer::finish_creating(tenant.conf, &timeline, desc, &path).unwrap()
    1312              :         };
    1313            1 :         let original_size = resident.metadata().file_size;
    1314              : 
    1315              :         //
    1316              :         // Create child shards and do the rewrite, exercising filter().
    1317              :         // TODO: abstraction in TenantHarness for splits.
    1318              :         //
    1319              : 
    1320              :         // Filter for various shards: this exercises cases like values at start of key range, end of key
    1321              :         // range, middle of key range.
    1322            1 :         let shard_count = ShardCount::new(4);
    1323            4 :         for shard_number in 0..shard_count.count() {
    1324            1 :             //
    1325            1 :             // mimic the shard split
    1326            1 :             //
    1327            4 :             let shard_identity = ShardIdentity::new(
    1328            4 :                 ShardNumber(shard_number),
    1329            4 :                 shard_count,
    1330            4 :                 ShardStripeSize(0x800),
    1331            1 :             )
    1332            4 :             .unwrap();
    1333            4 :             let harness = TenantHarness::create_custom(
    1334            4 :                 Box::leak(Box::new(format!(
    1335            4 :                     "test_image_layer_rewrite--child{}",
    1336            4 :                     shard_identity.shard_slug()
    1337            4 :                 ))),
    1338            4 :                 tenant_conf.clone(),
    1339            4 :                 tenant_id,
    1340            4 :                 shard_identity,
    1341            4 :                 // NB: in reality, the shards would each fork off their own gen number sequence from the parent.
    1342            4 :                 // But here, all we care about is that the gen number is unique.
    1343            4 :                 get_next_gen(),
    1344            4 :             )
    1345            4 :             .await
    1346            4 :             .unwrap();
    1347            4 :             let (tenant, ctx) = harness.load().await;
    1348            4 :             let timeline = tenant
    1349            4 :                 .create_test_timeline(timeline_id, lsn, DEFAULT_PG_VERSION, &ctx)
    1350            4 :                 .await
    1351            4 :                 .unwrap();
    1352            1 : 
    1353            1 :             //
    1354            1 :             // use filter() and make assertions
    1355            1 :             //
    1356            1 : 
    1357            4 :             let mut filtered_writer = ImageLayerWriter::new(
    1358            4 :                 harness.conf,
    1359            4 :                 timeline_id,
    1360            4 :                 harness.tenant_shard_id,
    1361            4 :                 &range,
    1362            4 :                 lsn,
    1363            4 :                 &timeline.gate,
    1364            4 :                 timeline.cancel.clone(),
    1365            4 :                 &ctx,
    1366            4 :             )
    1367            4 :             .await
    1368            4 :             .unwrap();
    1369            1 : 
    1370            4 :             let wrote_keys = resident
    1371            4 :                 .filter(&shard_identity, &mut filtered_writer, &ctx)
    1372            4 :                 .await
    1373            4 :                 .unwrap();
    1374            4 :             let replacement = if wrote_keys > 0 {
    1375            3 :                 let (desc, path) = filtered_writer.finish(&ctx).await.unwrap();
    1376            3 :                 let resident = Layer::finish_creating(tenant.conf, &timeline, desc, &path).unwrap();
    1377            3 :                 Some(resident)
    1378            1 :             } else {
    1379            1 :                 None
    1380            1 :             };
    1381            1 : 
    1382            1 :             // This exact size and those below will need updating as/when the layer encoding changes, but
    1383            1 :             // should be deterministic for a given version of the format, as we used no randomness generating the input.
    1384            4 :             assert_eq!(original_size, 122880);
    1385            1 : 
    1386            4 :             match shard_number {
    1387            1 :                 0 => {
    1388            1 :                     // We should have written out just one stripe for our shard identity
    1389            1 :                     assert_eq!(wrote_keys, 0x800);
    1390            1 :                     let replacement = replacement.unwrap();
    1391            1 : 
    1392            1 :                     // We should have dropped some of the data
    1393            1 :                     assert!(replacement.metadata().file_size < original_size);
    1394            1 :                     assert!(replacement.metadata().file_size > 0);
    1395            1 : 
    1396            1 :                     // Assert that we dropped ~3/4 of the data.
    1397            1 :                     assert_eq!(replacement.metadata().file_size, 49152);
    1398            1 :                 }
    1399            1 :                 1 => {
    1400            1 :                     // Shard 1 has no keys in our input range
    1401            1 :                     assert_eq!(wrote_keys, 0x0);
    1402            1 :                     assert!(replacement.is_none());
    1403            1 :                 }
    1404            1 :                 2 => {
    1405            1 :                     // Shard 2 has one stripes in the input range
    1406            1 :                     assert_eq!(wrote_keys, 0x800);
    1407            1 :                     let replacement = replacement.unwrap();
    1408            1 :                     assert!(replacement.metadata().file_size < original_size);
    1409            1 :                     assert!(replacement.metadata().file_size > 0);
    1410            1 :                     assert_eq!(replacement.metadata().file_size, 49152);
    1411            1 :                 }
    1412            1 :                 3 => {
    1413            1 :                     // Shard 3 has two stripes in the input range
    1414            1 :                     assert_eq!(wrote_keys, 0x1000);
    1415            1 :                     let replacement = replacement.unwrap();
    1416            1 :                     assert!(replacement.metadata().file_size < original_size);
    1417            1 :                     assert!(replacement.metadata().file_size > 0);
    1418            1 :                     assert_eq!(replacement.metadata().file_size, 73728);
    1419            1 :                 }
    1420            1 :                 _ => unreachable!(),
    1421            1 :             }
    1422            1 :         }
    1423            1 :     }
    1424              : 
    1425            1 :     async fn produce_image_layer(
    1426            1 :         tenant: &TenantShard,
    1427            1 :         tline: &Arc<Timeline>,
    1428            1 :         mut images: Vec<(Key, Bytes)>,
    1429            1 :         lsn: Lsn,
    1430            1 :         ctx: &RequestContext,
    1431            1 :     ) -> anyhow::Result<ResidentLayer> {
    1432            1 :         images.sort();
    1433            1 :         let (key_start, _) = images.first().unwrap();
    1434            1 :         let (key_last, _) = images.last().unwrap();
    1435            1 :         let key_end = key_last.next();
    1436            1 :         let key_range = *key_start..key_end;
    1437            1 :         let mut writer = ImageLayerWriter::new(
    1438            1 :             tenant.conf,
    1439            1 :             tline.timeline_id,
    1440            1 :             tenant.tenant_shard_id,
    1441            1 :             &key_range,
    1442            1 :             lsn,
    1443            1 :             &tline.gate,
    1444            1 :             tline.cancel.clone(),
    1445            1 :             ctx,
    1446            1 :         )
    1447            1 :         .await?;
    1448              : 
    1449         1001 :         for (key, img) in images {
    1450         1000 :             writer.put_image(key, img, ctx).await?;
    1451              :         }
    1452            1 :         let (desc, path) = writer.finish(ctx).await?;
    1453            1 :         let img_layer = Layer::finish_creating(tenant.conf, tline, desc, &path)?;
    1454              : 
    1455            1 :         Ok::<_, anyhow::Error>(img_layer)
    1456            1 :     }
    1457              : 
    1458           14 :     async fn assert_img_iter_equal(
    1459           14 :         img_iter: &mut ImageLayerIterator<'_>,
    1460           14 :         expect: &[(Key, Bytes)],
    1461           14 :         expect_lsn: Lsn,
    1462           14 :     ) {
    1463           14 :         let mut expect_iter = expect.iter();
    1464              :         loop {
    1465        14014 :             let o1 = img_iter.next().await.unwrap();
    1466        14014 :             let o2 = expect_iter.next();
    1467        14014 :             match (o1, o2) {
    1468           14 :                 (None, None) => break,
    1469        14000 :                 (Some((k1, l1, v1)), Some((k2, i2))) => {
    1470        14000 :                     let Value::Image(i1) = v1 else {
    1471            0 :                         panic!("expect Value::Image")
    1472              :                     };
    1473        14000 :                     assert_eq!(&k1, k2);
    1474        14000 :                     assert_eq!(l1, expect_lsn);
    1475        14000 :                     assert_eq!(&i1, i2);
    1476              :                 }
    1477            0 :                 (o1, o2) => panic!("iterators length mismatch: {o1:?}, {o2:?}"),
    1478              :             }
    1479              :         }
    1480           14 :     }
    1481              : 
    1482              :     #[tokio::test]
    1483            1 :     async fn image_layer_iterator() {
    1484            1 :         let harness = TenantHarness::create("image_layer_iterator").await.unwrap();
    1485            1 :         let (tenant, ctx) = harness.load().await;
    1486              : 
    1487            1 :         let tline = tenant
    1488            1 :             .create_test_timeline(TIMELINE_ID, Lsn(0x10), DEFAULT_PG_VERSION, &ctx)
    1489            1 :             .await
    1490            1 :             .unwrap();
    1491              : 
    1492         1000 :         fn get_key(id: u32) -> Key {
    1493         1000 :             let mut key = Key::from_hex("000000000033333333444444445500000000").unwrap();
    1494         1000 :             key.field6 = id;
    1495         1000 :             key
    1496         1000 :         }
    1497              :         const N: usize = 1000;
    1498            1 :         let test_imgs = (0..N)
    1499         1000 :             .map(|idx| (get_key(idx as u32), Bytes::from(format!("img{idx:05}"))))
    1500            1 :             .collect_vec();
    1501            1 :         let resident_layer =
    1502            1 :             produce_image_layer(&tenant, &tline, test_imgs.clone(), Lsn(0x10), &ctx)
    1503            1 :                 .await
    1504            1 :                 .unwrap();
    1505            1 :         let img_layer = resident_layer.get_as_image(&ctx).await.unwrap();
    1506            3 :         for max_read_size in [1, 1024] {
    1507           16 :             for batch_size in [1, 2, 4, 8, 3, 7, 13] {
    1508           14 :                 println!("running with batch_size={batch_size} max_read_size={max_read_size}");
    1509            1 :                 // Test if the batch size is correctly determined
    1510           14 :                 let mut iter = img_layer.iter_with_options(&ctx, max_read_size, batch_size);
    1511           14 :                 let mut num_items = 0;
    1512           56 :                 for _ in 0..3 {
    1513           42 :                     iter.next_batch().await.unwrap();
    1514           42 :                     num_items += iter.key_values_batch.len();
    1515           42 :                     if max_read_size == 1 {
    1516            1 :                         // every key should be a batch b/c the value is larger than max_read_size
    1517           21 :                         assert_eq!(iter.key_values_batch.len(), 1);
    1518            1 :                     } else {
    1519           21 :                         assert!(iter.key_values_batch.len() <= batch_size);
    1520            1 :                     }
    1521           42 :                     if num_items >= N {
    1522            1 :                         break;
    1523           42 :                     }
    1524           42 :                     iter.key_values_batch.clear();
    1525            1 :                 }
    1526            1 :                 // Test if the result is correct
    1527           14 :                 let mut iter = img_layer.iter_with_options(&ctx, max_read_size, batch_size);
    1528           14 :                 assert_img_iter_equal(&mut iter, &test_imgs, Lsn(0x10)).await;
    1529            1 :             }
    1530            1 :         }
    1531            1 :     }
    1532              : }
        

Generated by: LCOV version 2.1-beta