LCOV - code coverage report
Current view: top level - pageserver/src - walredo.rs (source / functions) Coverage Total Hit
Test: 3eba1babe267649f8cebefc91c236589db030548.info Lines: 68.7 % 386 265
Test Date: 2024-11-22 12:36:12 Functions: 65.2 % 46 30

            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 anyhow::Context;
      33              : use bytes::{Bytes, BytesMut};
      34              : use pageserver_api::key::Key;
      35              : use pageserver_api::models::{WalRedoManagerProcessStatus, WalRedoManagerStatus};
      36              : use pageserver_api::record::NeonWalRecord;
      37              : use pageserver_api::shard::TenantShardId;
      38              : use std::future::Future;
      39              : use std::sync::Arc;
      40              : use std::time::Duration;
      41              : use std::time::Instant;
      42              : use tracing::*;
      43              : use utils::lsn::Lsn;
      44              : use utils::sync::gate::GateError;
      45              : use utils::sync::heavier_once_cell;
      46              : 
      47              : /// The real implementation that uses a Postgres process to
      48              : /// perform WAL replay.
      49              : ///
      50              : /// Only one thread can use the process at a time, that is controlled by the
      51              : /// Mutex. In the future, we might want to launch a pool of processes to allow
      52              : /// concurrent replay of multiple records.
      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              :     process: process::WalRedoProcess,
     111              :     /// This field is last in this struct so the guard gets dropped _after_ [`Self::process`].
     112              :     /// (Reminder: dropping [`Self::process`] synchronously sends SIGKILL and then `wait()`s for it to exit).
     113              :     _launched_processes_guard: utils::sync::gate::GateGuard,
     114              : }
     115              : 
     116              : impl std::ops::Deref for Process {
     117              :     type Target = process::WalRedoProcess;
     118              : 
     119           20 :     fn deref(&self) -> &Self::Target {
     120           20 :         &self.process
     121           20 :     }
     122              : }
     123              : 
     124            0 : #[derive(Debug, thiserror::Error)]
     125              : pub enum Error {
     126              :     #[error("cancelled")]
     127              :     Cancelled,
     128              :     #[error(transparent)]
     129              :     Other(#[from] anyhow::Error),
     130              : }
     131              : 
     132              : macro_rules! bail {
     133              :     ($($arg:tt)*) => {
     134              :         return Err($crate::walredo::Error::Other(::anyhow::anyhow!($($arg)*)));
     135              :     }
     136              : }
     137              : 
     138              : ///
     139              : /// Public interface of WAL redo manager
     140              : ///
     141              : impl PostgresRedoManager {
     142              :     ///
     143              :     /// Request the WAL redo manager to apply some WAL records
     144              :     ///
     145              :     /// The WAL redo is handled by a separate thread, so this just sends a request
     146              :     /// to the thread and waits for response.
     147              :     ///
     148              :     /// # Cancel-Safety
     149              :     ///
     150              :     /// This method is cancellation-safe.
     151            6 :     pub async fn request_redo(
     152            6 :         &self,
     153            6 :         key: Key,
     154            6 :         lsn: Lsn,
     155            6 :         base_img: Option<(Lsn, Bytes)>,
     156            6 :         records: Vec<(Lsn, NeonWalRecord)>,
     157            6 :         pg_version: u32,
     158            6 :     ) -> Result<Bytes, Error> {
     159            6 :         if records.is_empty() {
     160            0 :             bail!("invalid WAL redo request with no records");
     161            6 :         }
     162            6 : 
     163            6 :         let base_img_lsn = base_img.as_ref().map(|p| p.0).unwrap_or(Lsn::INVALID);
     164            6 :         let mut img = base_img.map(|p| p.1);
     165            6 :         let mut batch_neon = apply_neon::can_apply_in_neon(&records[0].1);
     166            6 :         let mut batch_start = 0;
     167            6 :         for (i, record) in records.iter().enumerate().skip(1) {
     168            6 :             let rec_neon = apply_neon::can_apply_in_neon(&record.1);
     169            6 : 
     170            6 :             if rec_neon != batch_neon {
     171            0 :                 let result = if batch_neon {
     172            0 :                     self.apply_batch_neon(key, lsn, img, &records[batch_start..i])
     173              :                 } else {
     174            0 :                     self.apply_batch_postgres(
     175            0 :                         key,
     176            0 :                         lsn,
     177            0 :                         img,
     178            0 :                         base_img_lsn,
     179            0 :                         &records[batch_start..i],
     180            0 :                         self.conf.wal_redo_timeout,
     181            0 :                         pg_version,
     182            0 :                     )
     183            0 :                     .await
     184              :                 };
     185            0 :                 img = Some(result?);
     186              : 
     187            0 :                 batch_neon = rec_neon;
     188            0 :                 batch_start = i;
     189            6 :             }
     190              :         }
     191              :         // last batch
     192            6 :         if batch_neon {
     193            0 :             self.apply_batch_neon(key, lsn, img, &records[batch_start..])
     194              :         } else {
     195            6 :             self.apply_batch_postgres(
     196            6 :                 key,
     197            6 :                 lsn,
     198            6 :                 img,
     199            6 :                 base_img_lsn,
     200            6 :                 &records[batch_start..],
     201            6 :                 self.conf.wal_redo_timeout,
     202            6 :                 pg_version,
     203            6 :             )
     204           16 :             .await
     205              :         }
     206            6 :     }
     207              : 
     208              :     /// Do a ping request-response roundtrip.
     209              :     ///
     210              :     /// Not used in production, but by Rust benchmarks.
     211              :     ///
     212              :     /// # Cancel-Safety
     213              :     ///
     214              :     /// This method is cancellation-safe.
     215            2 :     pub async fn ping(&self, pg_version: u32) -> Result<(), Error> {
     216            2 :         self.do_with_walredo_process(pg_version, |proc| async move {
     217            2 :             proc.ping(Duration::from_secs(1))
     218            4 :                 .await
     219            2 :                 .map_err(Error::Other)
     220            2 :         })
     221            4 :         .await
     222            2 :     }
     223              : 
     224            0 :     pub fn status(&self) -> WalRedoManagerStatus {
     225            0 :         WalRedoManagerStatus {
     226            0 :             last_redo_at: {
     227            0 :                 let at = *self.last_redo_at.lock().unwrap();
     228            0 :                 at.and_then(|at| {
     229            0 :                     let age = at.elapsed();
     230            0 :                     // map any chrono errors silently to None here
     231            0 :                     chrono::Utc::now().checked_sub_signed(chrono::Duration::from_std(age).ok()?)
     232            0 :                 })
     233            0 :             },
     234            0 :             process: self.redo_process.get().and_then(|p| match &*p {
     235            0 :                 ProcessOnceCell::Spawned(p) => Some(WalRedoManagerProcessStatus { pid: p.id() }),
     236            0 :                 ProcessOnceCell::ManagerShutDown => None,
     237            0 :             }),
     238            0 :         }
     239            0 :     }
     240              : }
     241              : 
     242              : impl PostgresRedoManager {
     243              :     ///
     244              :     /// Create a new PostgresRedoManager.
     245              :     ///
     246            8 :     pub fn new(
     247            8 :         conf: &'static PageServerConf,
     248            8 :         tenant_shard_id: TenantShardId,
     249            8 :     ) -> PostgresRedoManager {
     250            8 :         // The actual process is launched lazily, on first request.
     251            8 :         PostgresRedoManager {
     252            8 :             tenant_shard_id,
     253            8 :             conf,
     254            8 :             last_redo_at: std::sync::Mutex::default(),
     255            8 :             redo_process: heavier_once_cell::OnceCell::default(),
     256            8 :             launched_processes: utils::sync::gate::Gate::default(),
     257            8 :         }
     258            8 :     }
     259              : 
     260              :     /// Shut down the WAL redo manager.
     261              :     ///
     262              :     /// Returns `true` if this call was the one that initiated shutdown.
     263              :     /// `true` may be observed by no caller if the first caller stops polling.
     264              :     ///
     265              :     /// After this future completes
     266              :     /// - no redo process is running
     267              :     /// - no new redo process will be spawned
     268              :     /// - redo requests that need walredo process will fail with [`Error::Cancelled`]
     269              :     /// - [`apply_neon`]-only redo requests may still work, but this may change in the future
     270              :     ///
     271              :     /// # Cancel-Safety
     272              :     ///
     273              :     /// This method is cancellation-safe.
     274            0 :     pub async fn shutdown(&self) -> bool {
     275              :         // prevent new processes from being spawned
     276            0 :         let maybe_permit = match self.redo_process.get_or_init_detached().await {
     277            0 :             Ok(guard) => {
     278            0 :                 if matches!(&*guard, ProcessOnceCell::ManagerShutDown) {
     279            0 :                     None
     280              :                 } else {
     281            0 :                     let (proc, permit) = guard.take_and_deinit();
     282            0 :                     drop(proc); // this just drops the Arc, its refcount may not be zero yet
     283            0 :                     Some(permit)
     284              :                 }
     285              :             }
     286            0 :             Err(permit) => Some(permit),
     287              :         };
     288            0 :         let it_was_us = if let Some(permit) = maybe_permit {
     289            0 :             self.redo_process
     290            0 :                 .set(ProcessOnceCell::ManagerShutDown, permit);
     291            0 :             true
     292              :         } else {
     293            0 :             false
     294              :         };
     295              :         // wait for ongoing requests to drain and the refcounts of all Arc<WalRedoProcess> that
     296              :         // we ever launched to drop to zero, which when it happens synchronously kill()s & wait()s
     297              :         // for the underlying process.
     298            0 :         self.launched_processes.close().await;
     299            0 :         it_was_us
     300            0 :     }
     301              : 
     302              :     /// This type doesn't have its own background task to check for idleness: we
     303              :     /// rely on our owner calling this function periodically in its own housekeeping
     304              :     /// loops.
     305            0 :     pub(crate) fn maybe_quiesce(&self, idle_timeout: Duration) {
     306            0 :         if let Ok(g) = self.last_redo_at.try_lock() {
     307            0 :             if let Some(last_redo_at) = *g {
     308            0 :                 if last_redo_at.elapsed() >= idle_timeout {
     309            0 :                     drop(g);
     310            0 :                     drop(self.redo_process.get().map(|guard| guard.take_and_deinit()));
     311            0 :                 }
     312            0 :             }
     313            0 :         }
     314            0 :     }
     315              : 
     316              :     /// # Cancel-Safety
     317              :     ///
     318              :     /// This method is cancel-safe iff `closure` is cancel-safe.
     319           10 :     async fn do_with_walredo_process<
     320           10 :         F: FnOnce(Arc<Process>) -> Fut,
     321           10 :         Fut: Future<Output = Result<O, Error>>,
     322           10 :         O,
     323           10 :     >(
     324           10 :         &self,
     325           10 :         pg_version: u32,
     326           10 :         closure: F,
     327           10 :     ) -> Result<O, Error> {
     328           10 :         let proc: Arc<Process> = match self.redo_process.get_or_init_detached().await {
     329            0 :             Ok(guard) => match &*guard {
     330            0 :                 ProcessOnceCell::Spawned(proc) => Arc::clone(proc),
     331              :                 ProcessOnceCell::ManagerShutDown => {
     332            0 :                     return Err(Error::Cancelled);
     333              :                 }
     334              :             },
     335           10 :             Err(permit) => {
     336           10 :                 let start = Instant::now();
     337              :                 // acquire guard before spawning process, so that we don't spawn new processes
     338              :                 // if the gate is already closed.
     339           10 :                 let _launched_processes_guard = match self.launched_processes.enter() {
     340           10 :                     Ok(guard) => guard,
     341            0 :                     Err(GateError::GateClosed) => unreachable!(
     342            0 :                         "shutdown sets the once cell to `ManagerShutDown` state before closing the gate"
     343            0 :                     ),
     344              :                 };
     345           10 :                 let proc = Arc::new(Process {
     346           10 :                     process: process::WalRedoProcess::launch(
     347           10 :                         self.conf,
     348           10 :                         self.tenant_shard_id,
     349           10 :                         pg_version,
     350           10 :                     )
     351           10 :                     .context("launch walredo process")?,
     352           10 :                     _launched_processes_guard,
     353           10 :                 });
     354           10 :                 let duration = start.elapsed();
     355           10 :                 WAL_REDO_PROCESS_LAUNCH_DURATION_HISTOGRAM.observe(duration.as_secs_f64());
     356           10 :                 info!(
     357            0 :                     elapsed_ms = duration.as_millis(),
     358            0 :                     pid = proc.id(),
     359            0 :                     "launched walredo process"
     360              :                 );
     361           10 :                 self.redo_process
     362           10 :                     .set(ProcessOnceCell::Spawned(Arc::clone(&proc)), permit);
     363           10 :                 proc
     364              :             }
     365              :         };
     366              : 
     367              :         // async closures are unstable, would support &Process
     368           20 :         let result = closure(proc.clone()).await;
     369              : 
     370           10 :         if result.is_err() {
     371              :             // Avoid concurrent callers hitting the same issue by taking `proc` out of the rotation.
     372              :             // Note that there may be other tasks concurrent with us that also hold `proc`.
     373              :             // We have to deal with that here.
     374              :             // Also read the doc comment on field `self.redo_process`.
     375              :             //
     376              :             // NB: there may still be other concurrent threads using `proc`.
     377              :             // The last one will send SIGKILL when the underlying Arc reaches refcount 0.
     378              :             //
     379              :             // NB: the drop impl blocks the dropping thread with a wait() system call for
     380              :             // the child process. In some ways the blocking is actually good: if we
     381              :             // deferred the waiting into the background / to tokio if we used `tokio::process`,
     382              :             // it could happen that if walredo always fails immediately, we spawn processes faster
     383              :             // than we can SIGKILL & `wait` for them to exit. By doing it the way we do here,
     384              :             // we limit this risk of run-away to at most $num_runtimes * $num_executor_threads.
     385              :             // This probably needs revisiting at some later point.
     386            4 :             match self.redo_process.get() {
     387            0 :                 None => (),
     388            4 :                 Some(guard) => {
     389            4 :                     match &*guard {
     390            0 :                         ProcessOnceCell::ManagerShutDown => {}
     391            4 :                         ProcessOnceCell::Spawned(guard_proc) => {
     392            4 :                             if Arc::ptr_eq(&proc, guard_proc) {
     393            4 :                                 // We're the first to observe an error from `proc`, it's our job to take it out of rotation.
     394            4 :                                 guard.take_and_deinit();
     395            4 :                             } else {
     396            0 :                                 // Another task already spawned another redo process (further up in this method)
     397            0 :                                 // and put it into `redo_process`. Do nothing, our view of the world is behind.
     398            0 :                             }
     399              :                         }
     400              :                     }
     401              :                 }
     402              :             }
     403              :             // The last task that does this `drop()` of `proc` will do a blocking `wait()` syscall.
     404            4 :             drop(proc);
     405            6 :         }
     406              : 
     407           10 :         result
     408           10 :     }
     409              : 
     410              :     ///
     411              :     /// Process one request for WAL redo using wal-redo postgres
     412              :     ///
     413              :     /// # Cancel-Safety
     414              :     ///
     415              :     /// Cancellation safe.
     416              :     #[allow(clippy::too_many_arguments)]
     417            6 :     async fn apply_batch_postgres(
     418            6 :         &self,
     419            6 :         key: Key,
     420            6 :         lsn: Lsn,
     421            6 :         base_img: Option<Bytes>,
     422            6 :         base_img_lsn: Lsn,
     423            6 :         records: &[(Lsn, NeonWalRecord)],
     424            6 :         wal_redo_timeout: Duration,
     425            6 :         pg_version: u32,
     426            6 :     ) -> Result<Bytes, Error> {
     427            6 :         *(self.last_redo_at.lock().unwrap()) = Some(Instant::now());
     428              : 
     429            6 :         let (rel, blknum) = key.to_rel_block().context("invalid record")?;
     430              :         const MAX_RETRY_ATTEMPTS: u32 = 1;
     431            6 :         let mut n_attempts = 0u32;
     432            8 :         loop {
     433            8 :             let base_img = &base_img;
     434            8 :             let closure = |proc: Arc<Process>| async move {
     435            8 :                 let started_at = std::time::Instant::now();
     436              : 
     437              :                 // Relational WAL records are applied using wal-redo-postgres
     438            8 :                 let result = proc
     439            8 :                     .apply_wal_records(rel, blknum, base_img, records, wal_redo_timeout)
     440           16 :                     .await
     441            8 :                     .context("apply_wal_records");
     442            8 : 
     443            8 :                 let duration = started_at.elapsed();
     444            8 : 
     445            8 :                 let len = records.len();
     446           16 :                 let nbytes = records.iter().fold(0, |acumulator, record| {
     447           16 :                     acumulator
     448           16 :                         + match &record.1 {
     449           16 :                             NeonWalRecord::Postgres { rec, .. } => rec.len(),
     450            0 :                             _ => unreachable!("Only PostgreSQL records are accepted in this batch"),
     451              :                         }
     452           16 :                 });
     453            8 : 
     454            8 :                 WAL_REDO_TIME.observe(duration.as_secs_f64());
     455            8 :                 WAL_REDO_RECORDS_HISTOGRAM.observe(len as f64);
     456            8 :                 WAL_REDO_BYTES_HISTOGRAM.observe(nbytes as f64);
     457            8 : 
     458            8 :                 debug!(
     459            0 :                     "postgres applied {} WAL records ({} bytes) in {} us to reconstruct page image at LSN {}",
     460            0 :                     len,
     461            0 :                     nbytes,
     462            0 :                     duration.as_micros(),
     463              :                     lsn
     464              :                 );
     465              : 
     466            8 :                 if let Err(e) = result.as_ref() {
     467            4 :                     error!(
     468            0 :                         "error applying {} WAL records {}..{} ({} bytes) to key {key}, from base image with LSN {} to reconstruct page image at LSN {} n_attempts={}: {:?}",
     469            0 :                         records.len(),
     470            4 :                         records.first().map(|p| p.0).unwrap_or(Lsn(0)),
     471            4 :                         records.last().map(|p| p.0).unwrap_or(Lsn(0)),
     472              :                         nbytes,
     473              :                         base_img_lsn,
     474              :                         lsn,
     475              :                         n_attempts,
     476              :                         e,
     477              :                     );
     478            4 :                 }
     479              : 
     480            8 :                 result.map_err(Error::Other)
     481            8 :             };
     482           16 :             let result = self.do_with_walredo_process(pg_version, closure).await;
     483              : 
     484            8 :             if result.is_ok() && n_attempts != 0 {
     485            0 :                 info!(n_attempts, "retried walredo succeeded");
     486            8 :             }
     487            8 :             n_attempts += 1;
     488            8 :             if n_attempts > MAX_RETRY_ATTEMPTS || result.is_ok() {
     489            6 :                 return result;
     490            2 :             }
     491              :         }
     492            6 :     }
     493              : 
     494              :     ///
     495              :     /// Process a batch of WAL records using bespoken Neon code.
     496              :     ///
     497            0 :     fn apply_batch_neon(
     498            0 :         &self,
     499            0 :         key: Key,
     500            0 :         lsn: Lsn,
     501            0 :         base_img: Option<Bytes>,
     502            0 :         records: &[(Lsn, NeonWalRecord)],
     503            0 :     ) -> Result<Bytes, Error> {
     504            0 :         let start_time = Instant::now();
     505            0 : 
     506            0 :         let mut page = BytesMut::new();
     507            0 :         if let Some(fpi) = base_img {
     508            0 :             // If full-page image is provided, then use it...
     509            0 :             page.extend_from_slice(&fpi[..]);
     510            0 :         } else {
     511              :             // All the current WAL record types that we can handle require a base image.
     512            0 :             bail!("invalid neon WAL redo request with no base image");
     513              :         }
     514              : 
     515              :         // Apply all the WAL records in the batch
     516            0 :         for (record_lsn, record) in records.iter() {
     517            0 :             self.apply_record_neon(key, &mut page, *record_lsn, record)?;
     518              :         }
     519              :         // Success!
     520            0 :         let duration = start_time.elapsed();
     521            0 :         // FIXME: using the same metric here creates a bimodal distribution by default, and because
     522            0 :         // there could be multiple batch sizes this would be N+1 modal.
     523            0 :         WAL_REDO_TIME.observe(duration.as_secs_f64());
     524            0 : 
     525            0 :         debug!(
     526            0 :             "neon applied {} WAL records in {} us to reconstruct page image at LSN {}",
     527            0 :             records.len(),
     528            0 :             duration.as_micros(),
     529              :             lsn
     530              :         );
     531              : 
     532            0 :         Ok(page.freeze())
     533            0 :     }
     534              : 
     535            0 :     fn apply_record_neon(
     536            0 :         &self,
     537            0 :         key: Key,
     538            0 :         page: &mut BytesMut,
     539            0 :         record_lsn: Lsn,
     540            0 :         record: &NeonWalRecord,
     541            0 :     ) -> anyhow::Result<()> {
     542            0 :         apply_neon::apply_in_neon(record, record_lsn, key, page)?;
     543              : 
     544            0 :         Ok(())
     545            0 :     }
     546              : }
     547              : 
     548              : #[cfg(test)]
     549              : mod tests {
     550              :     use super::PostgresRedoManager;
     551              :     use crate::config::PageServerConf;
     552              :     use bytes::Bytes;
     553              :     use pageserver_api::key::Key;
     554              :     use pageserver_api::record::NeonWalRecord;
     555              :     use pageserver_api::shard::TenantShardId;
     556              :     use std::str::FromStr;
     557              :     use tracing::Instrument;
     558              :     use utils::{id::TenantId, lsn::Lsn};
     559              : 
     560              :     #[tokio::test]
     561            2 :     async fn test_ping() {
     562            2 :         let h = RedoHarness::new().unwrap();
     563            2 : 
     564            2 :         h.manager
     565            2 :             .ping(14)
     566            2 :             .instrument(h.span())
     567            4 :             .await
     568            2 :             .expect("ping should work");
     569            2 :     }
     570              : 
     571              :     #[tokio::test]
     572            2 :     async fn short_v14_redo() {
     573            2 :         let expected = std::fs::read("test_data/short_v14_redo.page").unwrap();
     574            2 : 
     575            2 :         let h = RedoHarness::new().unwrap();
     576            2 : 
     577            2 :         let page = h
     578            2 :             .manager
     579            2 :             .request_redo(
     580            2 :                 Key {
     581            2 :                     field1: 0,
     582            2 :                     field2: 1663,
     583            2 :                     field3: 13010,
     584            2 :                     field4: 1259,
     585            2 :                     field5: 0,
     586            2 :                     field6: 0,
     587            2 :                 },
     588            2 :                 Lsn::from_str("0/16E2408").unwrap(),
     589            2 :                 None,
     590            2 :                 short_records(),
     591            2 :                 14,
     592            2 :             )
     593            2 :             .instrument(h.span())
     594            4 :             .await
     595            2 :             .unwrap();
     596            2 : 
     597            2 :         assert_eq!(&expected, &*page);
     598            2 :     }
     599              : 
     600              :     #[tokio::test]
     601            2 :     async fn short_v14_fails_for_wrong_key_but_returns_zero_page() {
     602            2 :         let h = RedoHarness::new().unwrap();
     603            2 : 
     604            2 :         let page = h
     605            2 :             .manager
     606            2 :             .request_redo(
     607            2 :                 Key {
     608            2 :                     field1: 0,
     609            2 :                     field2: 1663,
     610            2 :                     // key should be 13010
     611            2 :                     field3: 13130,
     612            2 :                     field4: 1259,
     613            2 :                     field5: 0,
     614            2 :                     field6: 0,
     615            2 :                 },
     616            2 :                 Lsn::from_str("0/16E2408").unwrap(),
     617            2 :                 None,
     618            2 :                 short_records(),
     619            2 :                 14,
     620            2 :             )
     621            2 :             .instrument(h.span())
     622            4 :             .await
     623            2 :             .unwrap();
     624            2 : 
     625            2 :         // TODO: there will be some stderr printout, which is forwarded to tracing that could
     626            2 :         // perhaps be captured as long as it's in the same thread.
     627            2 :         assert_eq!(page, crate::ZERO_PAGE);
     628            2 :     }
     629              : 
     630              :     #[tokio::test]
     631            2 :     async fn test_stderr() {
     632            2 :         let h = RedoHarness::new().unwrap();
     633            2 :         h
     634            2 :             .manager
     635            2 :             .request_redo(
     636            2 :                 Key::from_i128(0),
     637            2 :                 Lsn::INVALID,
     638            2 :                 None,
     639            2 :                 short_records(),
     640            2 :                 16, /* 16 currently produces stderr output on startup, which adds a nice extra edge */
     641            2 :             )
     642            2 :             .instrument(h.span())
     643            8 :             .await
     644            2 :             .unwrap_err();
     645            2 :     }
     646              : 
     647              :     #[allow(clippy::octal_escapes)]
     648            6 :     fn short_records() -> Vec<(Lsn, NeonWalRecord)> {
     649            6 :         vec![
     650            6 :             (
     651            6 :                 Lsn::from_str("0/16A9388").unwrap(),
     652            6 :                 NeonWalRecord::Postgres {
     653            6 :                     will_init: true,
     654            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")
     655            6 :                 }
     656            6 :             ),
     657            6 :             (
     658            6 :                 Lsn::from_str("0/16D4080").unwrap(),
     659            6 :                 NeonWalRecord::Postgres {
     660            6 :                     will_init: false,
     661            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")
     662            6 :                 }
     663            6 :             )
     664            6 :         ]
     665            6 :     }
     666              : 
     667              :     struct RedoHarness {
     668              :         // underscored because unused, except for removal at drop
     669              :         _repo_dir: camino_tempfile::Utf8TempDir,
     670              :         manager: PostgresRedoManager,
     671              :         tenant_shard_id: TenantShardId,
     672              :     }
     673              : 
     674              :     impl RedoHarness {
     675            8 :         fn new() -> anyhow::Result<Self> {
     676            8 :             crate::tenant::harness::setup_logging();
     677              : 
     678            8 :             let repo_dir = camino_tempfile::tempdir()?;
     679            8 :             let conf = PageServerConf::dummy_conf(repo_dir.path().to_path_buf());
     680            8 :             let conf = Box::leak(Box::new(conf));
     681            8 :             let tenant_shard_id = TenantShardId::unsharded(TenantId::generate());
     682            8 : 
     683            8 :             let manager = PostgresRedoManager::new(conf, tenant_shard_id);
     684            8 : 
     685            8 :             Ok(RedoHarness {
     686            8 :                 _repo_dir: repo_dir,
     687            8 :                 manager,
     688            8 :                 tenant_shard_id,
     689            8 :             })
     690            8 :         }
     691            8 :         fn span(&self) -> tracing::Span {
     692            8 :             tracing::info_span!("RedoHarness", tenant_id=%self.tenant_shard_id.tenant_id, shard_id=%self.tenant_shard_id.shard_slug())
     693            8 :         }
     694              :     }
     695              : }
        

Generated by: LCOV version 2.1-beta