LCOV - code coverage report
Current view: top level - pageserver/src/tenant/storage_layer - image_layer.rs (source / functions) Coverage Total Hit
Test: a43a77853355b937a79c57b07a8f05607cf29e6c.info Lines: 79.8 % 920 734
Test Date: 2024-09-19 12:04:32 Functions: 55.8 % 86 48

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

Generated by: LCOV version 2.1-beta