LCOV - code coverage report
Current view: top level - pageserver/src - walredo.rs (source / functions) Coverage Total Hit
Test: e402c46de0a007db6b48dddbde450ddbb92e6ceb.info Lines: 65.6 % 343 225
Test Date: 2024-06-25 10:31:23 Functions: 52.9 % 34 18

            Line data    Source code
       1              : //!
       2              : //! WAL redo. This service runs PostgreSQL in a special wal_redo mode
       3              : //! to apply given WAL records over an old page image and return new
       4              : //! page image.
       5              : //!
       6              : //! We rely on Postgres to perform WAL redo for us. We launch a
       7              : //! postgres process in special "wal redo" mode that's similar to
       8              : //! single-user mode. We then pass the previous page image, if any,
       9              : //! and all the WAL records we want to apply, to the postgres
      10              : //! process. Then we get the page image back. Communication with the
      11              : //! postgres process happens via stdin/stdout
      12              : //!
      13              : //! See pgxn/neon_walredo/walredoproc.c for the other side of
      14              : //! this communication.
      15              : //!
      16              : //! The Postgres process is assumed to be secure against malicious WAL
      17              : //! records. It achieves it by dropping privileges before replaying
      18              : //! any WAL records, so that even if an attacker hijacks the Postgres
      19              : //! process, he cannot escape out of it.
      20              : 
      21              : /// Process lifecycle and abstracction for the IPC protocol.
      22              : mod process;
      23              : 
      24              : /// Code to apply [`NeonWalRecord`]s.
      25              : pub(crate) mod apply_neon;
      26              : 
      27              : use crate::config::PageServerConf;
      28              : use crate::metrics::{
      29              :     WAL_REDO_BYTES_HISTOGRAM, WAL_REDO_PROCESS_LAUNCH_DURATION_HISTOGRAM,
      30              :     WAL_REDO_RECORDS_HISTOGRAM, WAL_REDO_TIME,
      31              : };
      32              : use crate::repository::Key;
      33              : use crate::walrecord::NeonWalRecord;
      34              : use anyhow::Context;
      35              : use bytes::{Bytes, BytesMut};
      36              : use pageserver_api::models::{WalRedoManagerProcessStatus, WalRedoManagerStatus};
      37              : use pageserver_api::shard::TenantShardId;
      38              : use std::sync::Arc;
      39              : use std::time::Duration;
      40              : use std::time::Instant;
      41              : use tracing::*;
      42              : use utils::lsn::Lsn;
      43              : use utils::sync::gate::GateError;
      44              : use utils::sync::heavier_once_cell;
      45              : 
      46              : ///
      47              : /// This is the real implementation that uses a Postgres process to
      48              : /// perform WAL replay. Only one thread can use the process at a time,
      49              : /// that is controlled by the Mutex. In the future, we might want to
      50              : /// launch a pool of processes to allow concurrent replay of multiple
      51              : /// records.
      52              : ///
      53              : pub struct PostgresRedoManager {
      54              :     tenant_shard_id: TenantShardId,
      55              :     conf: &'static PageServerConf,
      56              :     last_redo_at: std::sync::Mutex<Option<Instant>>,
      57              :     /// We use [`heavier_once_cell`] for
      58              :     ///
      59              :     /// 1. coalescing the lazy spawning of walredo processes ([`ProcessOnceCell::Spawned`])
      60              :     /// 2. prevent new processes from being spawned on [`Self::shutdown`] (=> [`ProcessOnceCell::ManagerShutDown`]).
      61              :     ///
      62              :     /// # Spawning
      63              :     ///
      64              :     /// Redo requests use the once cell to coalesce onto one call to [`process::WalRedoProcess::launch`].
      65              :     ///
      66              :     /// Notably, requests don't use the [`heavier_once_cell::Guard`] to keep ahold of the
      67              :     /// their process object; we use [`Arc::clone`] for that.
      68              :     ///
      69              :     /// This is primarily because earlier implementations that didn't  use [`heavier_once_cell`]
      70              :     /// had that behavior; it's probably unnecessary.
      71              :     /// The only merit of it is that if one walredo process encounters an error,
      72              :     /// it can take it out of rotation (= using [`heavier_once_cell::Guard::take_and_deinit`].
      73              :     /// and retry redo, thereby starting the new process, while other redo tasks might
      74              :     /// still be using the old redo process. But, those other tasks will most likely
      75              :     /// encounter an error as well, and errors are an unexpected condition anyway.
      76              :     /// So, probably we could get rid of the `Arc` in the future.
      77              :     ///
      78              :     /// # Shutdown
      79              :     ///
      80              :     /// See [`Self::launched_processes`].
      81              :     redo_process: heavier_once_cell::OnceCell<ProcessOnceCell>,
      82              : 
      83              :     /// Gate that is entered when launching a walredo process and held open
      84              :     /// until the process has been `kill()`ed and `wait()`ed upon.
      85              :     ///
      86              :     /// Manager shutdown waits for this gate to close after setting the
      87              :     /// [`ProcessOnceCell::ManagerShutDown`] state in [`Self::redo_process`].
      88              :     ///
      89              :     /// This type of usage is a bit unusual because gates usually keep track of
      90              :     /// concurrent operations, e.g., every [`Self::request_redo`] that is inflight.
      91              :     /// But we use it here to keep track of the _processes_ that we have launched,
      92              :     /// which may outlive any individual redo request because
      93              :     /// - we keep walredo process around until its quiesced to amortize spawn cost and
      94              :     /// - the Arc may be held by multiple concurrent redo requests, so, just because
      95              :     ///   you replace the [`Self::redo_process`] cell's content doesn't mean the
      96              :     ///   process gets killed immediately.
      97              :     ///
      98              :     /// We could simplify this by getting rid of the [`Arc`].
      99              :     /// See the comment on [`Self::redo_process`] for more details.
     100              :     launched_processes: utils::sync::gate::Gate,
     101              : }
     102              : 
     103              : /// See [`PostgresRedoManager::redo_process`].
     104              : enum ProcessOnceCell {
     105              :     Spawned(Arc<Process>),
     106              :     ManagerShutDown,
     107              : }
     108              : 
     109              : struct Process {
     110              :     _launched_processes_guard: utils::sync::gate::GateGuard,
     111              :     process: process::WalRedoProcess,
     112              : }
     113              : 
     114              : impl std::ops::Deref for Process {
     115              :     type Target = process::WalRedoProcess;
     116              : 
     117           16 :     fn deref(&self) -> &Self::Target {
     118           16 :         &self.process
     119           16 :     }
     120              : }
     121              : 
     122            0 : #[derive(Debug, thiserror::Error)]
     123              : pub enum Error {
     124              :     #[error("cancelled")]
     125              :     Cancelled,
     126              :     #[error(transparent)]
     127              :     Other(#[from] anyhow::Error),
     128              : }
     129              : 
     130              : macro_rules! bail {
     131              :     ($($arg:tt)*) => {
     132              :         return Err($crate::walredo::Error::Other(::anyhow::anyhow!($($arg)*)));
     133              :     }
     134              : }
     135              : 
     136              : ///
     137              : /// Public interface of WAL redo manager
     138              : ///
     139              : impl PostgresRedoManager {
     140              :     ///
     141              :     /// Request the WAL redo manager to apply some WAL records
     142              :     ///
     143              :     /// The WAL redo is handled by a separate thread, so this just sends a request
     144              :     /// to the thread and waits for response.
     145              :     ///
     146              :     /// # Cancel-Safety
     147              :     ///
     148              :     /// This method is cancellation-safe.
     149            6 :     pub async fn request_redo(
     150            6 :         &self,
     151            6 :         key: Key,
     152            6 :         lsn: Lsn,
     153            6 :         base_img: Option<(Lsn, Bytes)>,
     154            6 :         records: Vec<(Lsn, NeonWalRecord)>,
     155            6 :         pg_version: u32,
     156            6 :     ) -> Result<Bytes, Error> {
     157            6 :         if records.is_empty() {
     158            0 :             bail!("invalid WAL redo request with no records");
     159            6 :         }
     160            6 : 
     161            6 :         let base_img_lsn = base_img.as_ref().map(|p| p.0).unwrap_or(Lsn::INVALID);
     162            6 :         let mut img = base_img.map(|p| p.1);
     163            6 :         let mut batch_neon = apply_neon::can_apply_in_neon(&records[0].1);
     164            6 :         let mut batch_start = 0;
     165            6 :         for (i, record) in records.iter().enumerate().skip(1) {
     166            6 :             let rec_neon = apply_neon::can_apply_in_neon(&record.1);
     167            6 : 
     168            6 :             if rec_neon != batch_neon {
     169            0 :                 let result = if batch_neon {
     170            0 :                     self.apply_batch_neon(key, lsn, img, &records[batch_start..i])
     171              :                 } else {
     172            0 :                     self.apply_batch_postgres(
     173            0 :                         key,
     174            0 :                         lsn,
     175            0 :                         img,
     176            0 :                         base_img_lsn,
     177            0 :                         &records[batch_start..i],
     178            0 :                         self.conf.wal_redo_timeout,
     179            0 :                         pg_version,
     180            0 :                     )
     181            0 :                     .await
     182              :                 };
     183            0 :                 img = Some(result?);
     184              : 
     185            0 :                 batch_neon = rec_neon;
     186            0 :                 batch_start = i;
     187            6 :             }
     188              :         }
     189              :         // last batch
     190            6 :         if batch_neon {
     191            0 :             self.apply_batch_neon(key, lsn, img, &records[batch_start..])
     192              :         } else {
     193            6 :             self.apply_batch_postgres(
     194            6 :                 key,
     195            6 :                 lsn,
     196            6 :                 img,
     197            6 :                 base_img_lsn,
     198            6 :                 &records[batch_start..],
     199            6 :                 self.conf.wal_redo_timeout,
     200            6 :                 pg_version,
     201            6 :             )
     202           16 :             .await
     203              :         }
     204            6 :     }
     205              : 
     206            0 :     pub fn status(&self) -> WalRedoManagerStatus {
     207            0 :         WalRedoManagerStatus {
     208            0 :             last_redo_at: {
     209            0 :                 let at = *self.last_redo_at.lock().unwrap();
     210            0 :                 at.and_then(|at| {
     211            0 :                     let age = at.elapsed();
     212            0 :                     // map any chrono errors silently to None here
     213            0 :                     chrono::Utc::now().checked_sub_signed(chrono::Duration::from_std(age).ok()?)
     214            0 :                 })
     215            0 :             },
     216            0 :             process: self.redo_process.get().and_then(|p| match &*p {
     217            0 :                 ProcessOnceCell::Spawned(p) => Some(WalRedoManagerProcessStatus { pid: p.id() }),
     218            0 :                 ProcessOnceCell::ManagerShutDown => None,
     219            0 :             }),
     220            0 :         }
     221            0 :     }
     222              : }
     223              : 
     224              : impl PostgresRedoManager {
     225              :     ///
     226              :     /// Create a new PostgresRedoManager.
     227              :     ///
     228            6 :     pub fn new(
     229            6 :         conf: &'static PageServerConf,
     230            6 :         tenant_shard_id: TenantShardId,
     231            6 :     ) -> PostgresRedoManager {
     232            6 :         // The actual process is launched lazily, on first request.
     233            6 :         PostgresRedoManager {
     234            6 :             tenant_shard_id,
     235            6 :             conf,
     236            6 :             last_redo_at: std::sync::Mutex::default(),
     237            6 :             redo_process: heavier_once_cell::OnceCell::default(),
     238            6 :             launched_processes: utils::sync::gate::Gate::default(),
     239            6 :         }
     240            6 :     }
     241              : 
     242              :     /// Shut down the WAL redo manager.
     243              :     ///
     244              :     /// After this future completes
     245              :     /// - no redo process is running
     246              :     /// - no new redo process will be spawned
     247              :     /// - redo requests that need walredo process will fail with [`Error::Cancelled`]
     248              :     /// - [`apply_neon`]-only redo requests may still work, but this may change in the future
     249              :     ///
     250              :     /// # Cancel-Safety
     251              :     ///
     252              :     /// This method is cancellation-safe.
     253            0 :     pub async fn shutdown(&self) {
     254              :         // prevent new processes from being spawned
     255            0 :         let permit = match self.redo_process.get_or_init_detached().await {
     256            0 :             Ok(guard) => {
     257            0 :                 let (proc, permit) = guard.take_and_deinit();
     258            0 :                 drop(proc); // this just drops the Arc, its refcount may not be zero yet
     259            0 :                 permit
     260              :             }
     261            0 :             Err(permit) => permit,
     262              :         };
     263            0 :         self.redo_process
     264            0 :             .set(ProcessOnceCell::ManagerShutDown, permit);
     265            0 :         // wait for ongoing requests to drain and the refcounts of all Arc<WalRedoProcess> that
     266            0 :         // we ever launched to drop to zero, which when it happens synchronously kill()s & wait()s
     267            0 :         // for the underlying process.
     268            0 :         self.launched_processes.close().await;
     269            0 :     }
     270              : 
     271              :     /// This type doesn't have its own background task to check for idleness: we
     272              :     /// rely on our owner calling this function periodically in its own housekeeping
     273              :     /// loops.
     274            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     275            0 :         if let Ok(g) = self.last_redo_at.try_lock() {
     276            0 :             if let Some(last_redo_at) = *g {
     277            0 :                 if last_redo_at.elapsed() >= idle_timeout {
     278            0 :                     drop(g);
     279            0 :                     drop(self.redo_process.get().map(|guard| guard.take_and_deinit()));
     280            0 :                 }
     281            0 :             }
     282            0 :         }
     283            0 :     }
     284              : 
     285              :     ///
     286              :     /// Process one request for WAL redo using wal-redo postgres
     287              :     ///
     288              :     /// # Cancel-Safety
     289              :     ///
     290              :     /// Cancellation safe.
     291              :     #[allow(clippy::too_many_arguments)]
     292            6 :     async fn apply_batch_postgres(
     293            6 :         &self,
     294            6 :         key: Key,
     295            6 :         lsn: Lsn,
     296            6 :         base_img: Option<Bytes>,
     297            6 :         base_img_lsn: Lsn,
     298            6 :         records: &[(Lsn, NeonWalRecord)],
     299            6 :         wal_redo_timeout: Duration,
     300            6 :         pg_version: u32,
     301            6 :     ) -> Result<Bytes, Error> {
     302            6 :         *(self.last_redo_at.lock().unwrap()) = Some(Instant::now());
     303              : 
     304            6 :         let (rel, blknum) = key.to_rel_block().context("invalid record")?;
     305              :         const MAX_RETRY_ATTEMPTS: u32 = 1;
     306            6 :         let mut n_attempts = 0u32;
     307              :         loop {
     308            8 :             let proc: Arc<Process> = match self.redo_process.get_or_init_detached().await {
     309            0 :                 Ok(guard) => match &*guard {
     310            0 :                     ProcessOnceCell::Spawned(proc) => Arc::clone(proc),
     311              :                     ProcessOnceCell::ManagerShutDown => {
     312            0 :                         return Err(Error::Cancelled);
     313              :                     }
     314              :                 },
     315            8 :                 Err(permit) => {
     316            8 :                     let start = Instant::now();
     317            8 :                     let proc = Arc::new(Process {
     318            8 :                             _launched_processes_guard: match self.launched_processes.enter() {
     319            8 :                                 Ok(guard) => guard,
     320            0 :                                 Err(GateError::GateClosed) => unreachable!(
     321            0 :                                     "shutdown sets the once cell to `ManagerShutDown` state before closing the gate"
     322            0 :                                 ),
     323              :                             },
     324            8 :                             process: process::WalRedoProcess::launch(
     325            8 :                                 self.conf,
     326            8 :                                 self.tenant_shard_id,
     327            8 :                                 pg_version,
     328            8 :                             )
     329            8 :                             .context("launch walredo process")?,
     330              :                         });
     331            8 :                     let duration = start.elapsed();
     332            8 :                     WAL_REDO_PROCESS_LAUNCH_DURATION_HISTOGRAM.observe(duration.as_secs_f64());
     333            8 :                     info!(
     334            0 :                         duration_ms = duration.as_millis(),
     335            0 :                         pid = proc.id(),
     336            0 :                         "launched walredo process"
     337              :                     );
     338            8 :                     self.redo_process
     339            8 :                         .set(ProcessOnceCell::Spawned(Arc::clone(&proc)), permit);
     340            8 :                     proc
     341              :                 }
     342              :             };
     343              : 
     344            8 :             let started_at = std::time::Instant::now();
     345              : 
     346              :             // Relational WAL records are applied using wal-redo-postgres
     347            8 :             let result = proc
     348            8 :                 .apply_wal_records(rel, blknum, &base_img, records, wal_redo_timeout)
     349           16 :                 .await
     350            8 :                 .context("apply_wal_records");
     351            8 : 
     352            8 :             let duration = started_at.elapsed();
     353            8 : 
     354            8 :             let len = records.len();
     355           16 :             let nbytes = records.iter().fold(0, |acumulator, record| {
     356           16 :                 acumulator
     357           16 :                     + match &record.1 {
     358           16 :                         NeonWalRecord::Postgres { rec, .. } => rec.len(),
     359            0 :                         _ => unreachable!("Only PostgreSQL records are accepted in this batch"),
     360              :                     }
     361           16 :             });
     362            8 : 
     363            8 :             WAL_REDO_TIME.observe(duration.as_secs_f64());
     364            8 :             WAL_REDO_RECORDS_HISTOGRAM.observe(len as f64);
     365            8 :             WAL_REDO_BYTES_HISTOGRAM.observe(nbytes as f64);
     366            8 : 
     367            8 :             debug!(
     368            0 :                 "postgres applied {} WAL records ({} bytes) in {} us to reconstruct page image at LSN {}",
     369            0 :                 len,
     370            0 :                 nbytes,
     371            0 :                 duration.as_micros(),
     372              :                 lsn
     373              :             );
     374              : 
     375              :             // If something went wrong, don't try to reuse the process. Kill it, and
     376              :             // next request will launch a new one.
     377            8 :             if let Err(e) = result.as_ref() {
     378            4 :                 error!(
     379            0 :                     "error applying {} WAL records {}..{} ({} bytes) to key {key}, from base image with LSN {} to reconstruct page image at LSN {} n_attempts={}: {:?}",
     380            0 :                     records.len(),
     381            4 :                     records.first().map(|p| p.0).unwrap_or(Lsn(0)),
     382            4 :                     records.last().map(|p| p.0).unwrap_or(Lsn(0)),
     383              :                     nbytes,
     384              :                     base_img_lsn,
     385              :                     lsn,
     386              :                     n_attempts,
     387              :                     e,
     388              :                 );
     389              :                 // Avoid concurrent callers hitting the same issue by taking `proc` out of the rotation.
     390              :                 // Note that there may be other tasks concurrent with us that also hold `proc`.
     391              :                 // We have to deal with that here.
     392              :                 // Also read the doc comment on field `self.redo_process`.
     393              :                 //
     394              :                 // NB: there may still be other concurrent threads using `proc`.
     395              :                 // The last one will send SIGKILL when the underlying Arc reaches refcount 0.
     396              :                 //
     397              :                 // NB: the drop impl blocks the dropping thread with a wait() system call for
     398              :                 // the child process. In some ways the blocking is actually good: if we
     399              :                 // deferred the waiting into the background / to tokio if we used `tokio::process`,
     400              :                 // it could happen that if walredo always fails immediately, we spawn processes faster
     401              :                 // than we can SIGKILL & `wait` for them to exit. By doing it the way we do here,
     402              :                 // we limit this risk of run-away to at most $num_runtimes * $num_executor_threads.
     403              :                 // This probably needs revisiting at some later point.
     404            4 :                 match self.redo_process.get() {
     405            0 :                     None => (),
     406            4 :                     Some(guard) => {
     407            4 :                         match &*guard {
     408            0 :                             ProcessOnceCell::ManagerShutDown => {}
     409            4 :                             ProcessOnceCell::Spawned(guard_proc) => {
     410            4 :                                 if Arc::ptr_eq(&proc, guard_proc) {
     411            4 :                                     // We're the first to observe an error from `proc`, it's our job to take it out of rotation.
     412            4 :                                     guard.take_and_deinit();
     413            4 :                                 } else {
     414            0 :                                     // Another task already spawned another redo process (further up in this method)
     415            0 :                                     // and put it into `redo_process`. Do nothing, our view of the world is behind.
     416            0 :                                 }
     417              :                             }
     418              :                         }
     419              :                     }
     420              :                 }
     421              :                 // The last task that does this `drop()` of `proc` will do a blocking `wait()` syscall.
     422            4 :                 drop(proc);
     423            4 :             } else if n_attempts != 0 {
     424            0 :                 info!(n_attempts, "retried walredo succeeded");
     425            4 :             }
     426            8 :             n_attempts += 1;
     427            8 :             if n_attempts > MAX_RETRY_ATTEMPTS || result.is_ok() {
     428            6 :                 return result.map_err(Error::Other);
     429            2 :             }
     430              :         }
     431            6 :     }
     432              : 
     433              :     ///
     434              :     /// Process a batch of WAL records using bespoken Neon code.
     435              :     ///
     436            0 :     fn apply_batch_neon(
     437            0 :         &self,
     438            0 :         key: Key,
     439            0 :         lsn: Lsn,
     440            0 :         base_img: Option<Bytes>,
     441            0 :         records: &[(Lsn, NeonWalRecord)],
     442            0 :     ) -> Result<Bytes, Error> {
     443            0 :         let start_time = Instant::now();
     444            0 : 
     445            0 :         let mut page = BytesMut::new();
     446            0 :         if let Some(fpi) = base_img {
     447            0 :             // If full-page image is provided, then use it...
     448            0 :             page.extend_from_slice(&fpi[..]);
     449            0 :         } else {
     450              :             // All the current WAL record types that we can handle require a base image.
     451            0 :             bail!("invalid neon WAL redo request with no base image");
     452              :         }
     453              : 
     454              :         // Apply all the WAL records in the batch
     455            0 :         for (record_lsn, record) in records.iter() {
     456            0 :             self.apply_record_neon(key, &mut page, *record_lsn, record)?;
     457              :         }
     458              :         // Success!
     459            0 :         let duration = start_time.elapsed();
     460            0 :         // FIXME: using the same metric here creates a bimodal distribution by default, and because
     461            0 :         // there could be multiple batch sizes this would be N+1 modal.
     462            0 :         WAL_REDO_TIME.observe(duration.as_secs_f64());
     463            0 : 
     464            0 :         debug!(
     465            0 :             "neon applied {} WAL records in {} us to reconstruct page image at LSN {}",
     466            0 :             records.len(),
     467            0 :             duration.as_micros(),
     468              :             lsn
     469              :         );
     470              : 
     471            0 :         Ok(page.freeze())
     472            0 :     }
     473              : 
     474            0 :     fn apply_record_neon(
     475            0 :         &self,
     476            0 :         key: Key,
     477            0 :         page: &mut BytesMut,
     478            0 :         record_lsn: Lsn,
     479            0 :         record: &NeonWalRecord,
     480            0 :     ) -> anyhow::Result<()> {
     481            0 :         apply_neon::apply_in_neon(record, record_lsn, key, page)?;
     482              : 
     483            0 :         Ok(())
     484            0 :     }
     485              : }
     486              : 
     487              : #[cfg(test)]
     488              : mod tests {
     489              :     use super::PostgresRedoManager;
     490              :     use crate::repository::Key;
     491              :     use crate::{config::PageServerConf, walrecord::NeonWalRecord};
     492              :     use bytes::Bytes;
     493              :     use pageserver_api::shard::TenantShardId;
     494              :     use std::str::FromStr;
     495              :     use tracing::Instrument;
     496              :     use utils::{id::TenantId, lsn::Lsn};
     497              : 
     498              :     #[tokio::test]
     499            2 :     async fn short_v14_redo() {
     500            2 :         let expected = std::fs::read("test_data/short_v14_redo.page").unwrap();
     501            2 : 
     502            2 :         let h = RedoHarness::new().unwrap();
     503            2 : 
     504            2 :         let page = h
     505            2 :             .manager
     506            2 :             .request_redo(
     507            2 :                 Key {
     508            2 :                     field1: 0,
     509            2 :                     field2: 1663,
     510            2 :                     field3: 13010,
     511            2 :                     field4: 1259,
     512            2 :                     field5: 0,
     513            2 :                     field6: 0,
     514            2 :                 },
     515            2 :                 Lsn::from_str("0/16E2408").unwrap(),
     516            2 :                 None,
     517            2 :                 short_records(),
     518            2 :                 14,
     519            2 :             )
     520            2 :             .instrument(h.span())
     521            4 :             .await
     522            2 :             .unwrap();
     523            2 : 
     524            2 :         assert_eq!(&expected, &*page);
     525            2 :     }
     526              : 
     527              :     #[tokio::test]
     528            2 :     async fn short_v14_fails_for_wrong_key_but_returns_zero_page() {
     529            2 :         let h = RedoHarness::new().unwrap();
     530            2 : 
     531            2 :         let page = h
     532            2 :             .manager
     533            2 :             .request_redo(
     534            2 :                 Key {
     535            2 :                     field1: 0,
     536            2 :                     field2: 1663,
     537            2 :                     // key should be 13010
     538            2 :                     field3: 13130,
     539            2 :                     field4: 1259,
     540            2 :                     field5: 0,
     541            2 :                     field6: 0,
     542            2 :                 },
     543            2 :                 Lsn::from_str("0/16E2408").unwrap(),
     544            2 :                 None,
     545            2 :                 short_records(),
     546            2 :                 14,
     547            2 :             )
     548            2 :             .instrument(h.span())
     549            4 :             .await
     550            2 :             .unwrap();
     551            2 : 
     552            2 :         // TODO: there will be some stderr printout, which is forwarded to tracing that could
     553            2 :         // perhaps be captured as long as it's in the same thread.
     554            2 :         assert_eq!(page, crate::ZERO_PAGE);
     555            2 :     }
     556              : 
     557              :     #[tokio::test]
     558            2 :     async fn test_stderr() {
     559            2 :         let h = RedoHarness::new().unwrap();
     560            2 :         h
     561            2 :             .manager
     562            2 :             .request_redo(
     563            2 :                 Key::from_i128(0),
     564            2 :                 Lsn::INVALID,
     565            2 :                 None,
     566            2 :                 short_records(),
     567            2 :                 16, /* 16 currently produces stderr output on startup, which adds a nice extra edge */
     568            2 :             )
     569            2 :             .instrument(h.span())
     570            8 :             .await
     571            2 :             .unwrap_err();
     572            2 :     }
     573              : 
     574              :     #[allow(clippy::octal_escapes)]
     575            6 :     fn short_records() -> Vec<(Lsn, NeonWalRecord)> {
     576            6 :         vec![
     577            6 :             (
     578            6 :                 Lsn::from_str("0/16A9388").unwrap(),
     579            6 :                 NeonWalRecord::Postgres {
     580            6 :                     will_init: true,
     581            6 :                     rec: Bytes::from_static(b"j\x03\0\0\0\x04\0\0\xe8\x7fj\x01\0\0\0\0\0\n\0\0\xd0\x16\x13Y\0\x10\0\04\x03\xd4\0\x05\x7f\x06\0\0\xd22\0\0\xeb\x04\0\0\0\0\0\0\xff\x03\0\0\0\0\x80\xeca\x01\0\0\x01\0\xd4\0\xa0\x1d\0 \x04 \0\0\0\0/\0\x01\0\xa0\x9dX\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0.\0\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\00\x9f\x9a\x01P\x9e\xb2\x01\0\x04\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x02\0!\0\x01\x08 \xff\xff\xff?\0\0\0\0\0\0@\0\0another_table\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x98\x08\0\0\x02@\0\0\0\0\0\0\n\0\0\0\x02\0\0\0\0@\0\0\0\0\0\0\0\0\0\0\0\0\x80\xbf\0\0\0\0\0\0\0\0\0\0pr\x01\0\0\0\0\0\0\0\0\x01d\0\0\0\0\0\0\x04\0\0\x01\0\0\0\0\0\0\0\x0c\x02\0\0\0\0\0\0\0\0\0\0\0\0\0\0/\0!\x80\x03+ \xff\xff\xff\x7f\0\0\0\0\0\xdf\x04\0\0pg_type\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x0b\0\0\0G\0\0\0\0\0\0\0\n\0\0\0\x02\0\0\0\0\0\0\0\0\0\0\0\x0e\0\0\0\0@\x16D\x0e\0\0\0K\x10\0\0\x01\0pr \0\0\0\0\0\0\0\0\x01n\0\0\0\0\0\xd6\x02\0\0\x01\0\0\0[\x01\0\0\0\0\0\0\0\t\x04\0\0\x02\0\0\0\x01\0\0\0\n\0\0\0\n\0\0\0\x7f\0\0\0\0\0\0\0\n\0\0\0\x02\0\0\0\0\0\0C\x01\0\0\x15\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\0.\0!\x80\x03+ \xff\xff\xff\x7f\0\0\0\0\0;\n\0\0pg_statistic\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x0b\0\0\0\xfd.\0\0\0\0\0\0\n\0\0\0\x02\0\0\0;\n\0\0\0\0\0\0\x13\0\0\0\0\0\xcbC\x13\0\0\0\x18\x0b\0\0\x01\0pr\x1f\0\0\0\0\0\0\0\0\x01n\0\0\0\0\0\xd6\x02\0\0\x01\0\0\0C\x01\0\0\0\0\0\0\0\t\x04\0\0\x01\0\0\0\x01\0\0\0\n\0\0\0\n\0\0\0\x7f\0\0\0\0\0\0\x02\0\x01")
     582            6 :                 }
     583            6 :             ),
     584            6 :             (
     585            6 :                 Lsn::from_str("0/16D4080").unwrap(),
     586            6 :                 NeonWalRecord::Postgres {
     587            6 :                     will_init: false,
     588            6 :                     rec: Bytes::from_static(b"\xbc\0\0\0\0\0\0\0h?m\x01\0\0\0\0p\n\0\09\x08\xa3\xea\0 \x8c\0\x7f\x06\0\0\xd22\0\0\xeb\x04\0\0\0\0\0\0\xff\x02\0@\0\0another_table\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x98\x08\0\0\x02@\0\0\0\0\0\0\n\0\0\0\x02\0\0\0\0@\0\0\0\0\0\0\x05\0\0\0\0@zD\x05\0\0\0\0\0\0\0\0\0pr\x01\0\0\0\0\0\0\0\0\x01d\0\0\0\0\0\0\x04\0\0\x01\0\0\0\x02\0")
     589            6 :                 }
     590            6 :             )
     591            6 :         ]
     592            6 :     }
     593              : 
     594              :     struct RedoHarness {
     595              :         // underscored because unused, except for removal at drop
     596              :         _repo_dir: camino_tempfile::Utf8TempDir,
     597              :         manager: PostgresRedoManager,
     598              :         tenant_shard_id: TenantShardId,
     599              :     }
     600              : 
     601              :     impl RedoHarness {
     602            6 :         fn new() -> anyhow::Result<Self> {
     603            6 :             crate::tenant::harness::setup_logging();
     604              : 
     605            6 :             let repo_dir = camino_tempfile::tempdir()?;
     606            6 :             let conf = PageServerConf::dummy_conf(repo_dir.path().to_path_buf());
     607            6 :             let conf = Box::leak(Box::new(conf));
     608            6 :             let tenant_shard_id = TenantShardId::unsharded(TenantId::generate());
     609            6 : 
     610            6 :             let manager = PostgresRedoManager::new(conf, tenant_shard_id);
     611            6 : 
     612            6 :             Ok(RedoHarness {
     613            6 :                 _repo_dir: repo_dir,
     614            6 :                 manager,
     615            6 :                 tenant_shard_id,
     616            6 :             })
     617            6 :         }
     618            6 :         fn span(&self) -> tracing::Span {
     619            6 :             tracing::info_span!("RedoHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
     620            6 :         }
     621              :     }
     622              : }
        

Generated by: LCOV version 2.1-beta