From 6a87c519d1bbfc07c4255b873a419e2f829c4694 Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Thu, 3 Dec 2026 22:04:24 +0100 Subject: [PATCH 01/24] feat(store): rewrite cached blocks in place to compress them Nodes can store new blocks compressed, but blocks already in the cache stay as they were. Add graphman chain compress-blocks run and status, which rewrite them in place in batches while the chain is in use, keep any block a node changes meanwhile, and resume where a run stopped. --- docs/config.md | 3 +- node/src/bin/manager.rs | 45 +- node/src/manager/commands/compress_blocks.rs | 126 ++ node/src/manager/commands/mod.rs | 1 + store/postgres/src/advisory_lock.rs | 24 +- store/postgres/src/chain_store.rs | 34 + store/postgres/src/compress_blocks.rs | 1152 +++++++++++++++++ store/postgres/src/copy.rs | 6 +- store/postgres/src/lib.rs | 5 + store/test-store/tests/postgres/chain_head.rs | 500 ++++++- 10 files changed, 1884 insertions(+), 12 deletions(-) create mode 100644 node/src/manager/commands/compress_blocks.rs create mode 100644 store/postgres/src/compress_blocks.rs diff --git a/docs/config.md b/docs/config.md index 904fc1ed634..14f4361927e 100644 --- a/docs/config.md +++ b/docs/config.md @@ -132,7 +132,8 @@ can not get that lock within 2 seconds, it tries again later and stores blocks uncompressed until that succeeds. Only blocks that are written after changing this setting are affected; blocks -that are already in the cache can be read regardless of the setting. Before +that are already in the cache can be read regardless of the setting. They can be +compressed with `graphman chain compress-blocks`. Before setting this to anything other than `"none"`, all nodes must run a version of `graph-node` that can read compressed blocks, as older versions will fetch compressed blocks from the chain's provider again each time they need them. diff --git a/node/src/bin/manager.rs b/node/src/bin/manager.rs index 28cedcd4e28..1ce9d402bfb 100644 --- a/node/src/bin/manager.rs +++ b/node/src/bin/manager.rs @@ -28,8 +28,8 @@ use graph_node::{ MetricsContext, manager::deployment::DeploymentSearch, store_builder::StoreBuilder, }; use graph_store_postgres::{ - BlockStore, ChainStore, ConnectionPool, NotificationSender, PRIMARY_SHARD, PoolCoordinator, - Shard, Store, SubgraphStore, SubscriptionManager, + BlockCompression, BlockStore, ChainStore, ConnectionPool, NotificationSender, PRIMARY_SHARD, + PoolCoordinator, Shard, Store, SubgraphStore, SubscriptionManager, }; use itertools::Itertools; use lazy_static::lazy_static; @@ -555,6 +555,18 @@ pub enum ChainCommand { force: bool, }, + /// Compress blocks that are already in the block cache + /// + /// This can be run while the chain is in use. All nodes must be able to + /// read compressed blocks + CompressBlocks { + /// Chain name (must be an existing chain, see 'chain list') + #[clap(value_parser = clap::builder::NonEmptyStringValueParser::new())] + chain_name: String, + #[clap(subcommand)] + method: CompressBlocksCommand, + }, + /// Update the genesis block hash for a chain UpdateGenesis { #[clap(long, short)] @@ -598,6 +610,23 @@ pub enum ChainCommand { }, } +#[derive(Clone, Debug, Subcommand)] +pub enum CompressBlocksCommand { + /// Rewrite the blocks with the given compression, or continue a run that + /// did not finish + Run { + /// How to store the blocks, see 'block_compression' in config.md; + /// 'none' uncompresses blocks + #[clap(long, default_value = "zstd:1")] + compression: BlockCompression, + /// How many MB of WAL to write per second at most + #[clap(long, default_value = "20", value_parser = clap::value_parser!(u64).range(1..))] + max_rate: u64, + }, + /// Show how far the last run got + Status, +} + #[derive(Clone, Debug, Subcommand)] pub enum CallCacheCommand { /// Remove the call cache of the specified chain. @@ -1539,6 +1568,18 @@ async fn main() -> anyhow::Result<()> { } } } + CompressBlocks { chain_name, method } => { + use CompressBlocksCommand::*; + use commands::compress_blocks::{run, status}; + let chain_store = ctx.chain_store(&chain_name).await?; + match method { + Run { + compression, + max_rate, + } => run(chain_store, compression, max_rate).await, + Status => status(chain_store).await, + } + } Truncate { chain_name, force } => { use commands::check_blocks::truncate; let chain_store = ctx.chain_store(&chain_name).await?; diff --git a/node/src/manager/commands/compress_blocks.rs b/node/src/manager/commands/compress_blocks.rs new file mode 100644 index 00000000000..fe79c4ae017 --- /dev/null +++ b/node/src/manager/commands/compress_blocks.rs @@ -0,0 +1,126 @@ +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use graph::prelude::anyhow::Error; +use graph_store_postgres::{ + BlockCompression, ChainStore, CompressBlocksProgress, CompressBlocksReporter, + CompressBlocksRequest, CompressBlocksStatus, +}; + +const MB: u64 = 1_000_000; + +/// How often to print progress +const REPORT_INTERVAL: Duration = Duration::from_secs(10); + +struct Reporter { + start: Instant, + last_report: Option, +} + +impl Reporter { + fn new() -> Self { + Reporter { + start: Instant::now(), + last_report: None, + } + } + + /// Return `true` if enough time has passed since we last printed progress + fn is_due(&mut self) -> bool { + let due = self + .last_report + .is_none_or(|last| last.elapsed() >= REPORT_INTERVAL); + if due { + self.last_report = Some(Instant::now()); + } + due + } +} + +impl CompressBlocksReporter for Reporter { + fn message(&mut self, msg: &str) { + println!("{msg}"); + } + + fn progress(&mut self, progress: &CompressBlocksProgress) { + let done = progress.next_block > progress.last_block; + if !self.is_due() && !done { + return; + } + let secs = self.start.elapsed().as_secs_f64().max(1.0); + println!( + "rewrote blocks up to {} of {}: {} blocks that took up {} MB and now take up {} MB, \ + {} MB of WAL, {:.0} blocks/s", + progress.next_block - 1, + progress.last_block, + progress.blocks, + progress.old_bytes / MB, + progress.new_bytes / MB, + progress.wal_bytes / MB, + progress.blocks as f64 / secs + ); + if progress.retry > 0 { + println!( + "{} blocks were locked or changed and will be tried again at the end", + progress.retry + ); + } + } +} + +pub async fn run( + chain_store: Arc, + compression: BlockCompression, + max_rate: u64, +) -> Result<(), Error> { + let req = CompressBlocksRequest { + compression, + max_wal_rate: max_rate * MB, + }; + let progress = chain_store + .compress_blocks(&req, &mut Reporter::new()) + .await?; + println!( + "stored the blocks for {} with {}", + chain_store.chain, progress.compression + ); + if progress.skipped > 0 { + println!( + "{} blocks were left as they were since they were locked or changed each time; \ + run this again to rewrite them", + progress.skipped + ); + } + Ok(()) +} + +pub async fn status(chain_store: Arc) -> Result<(), Error> { + match chain_store.compress_blocks_status().await? { + CompressBlocksStatus::NotStarted => println!("not started"), + CompressBlocksStatus::Unfinished(progress) => { + println!( + "unfinished; storing blocks with {}, all blocks before {} of {} are done", + progress.compression, progress.next_block, progress.last_block + ); + if progress.retry > 0 { + println!( + "{} blocks were locked or changed and still need to be tried again", + progress.retry + ); + } + } + CompressBlocksStatus::Finished(progress) => { + println!( + "finished; all blocks up to {} are stored with {}", + progress.last_block, progress.compression + ); + if progress.skipped > 0 { + println!( + "{} blocks were left as they were since they were locked or changed each time", + progress.skipped + ); + } + } + } + Ok(()) +} diff --git a/node/src/manager/commands/mod.rs b/node/src/manager/commands/mod.rs index 9e5ba8e0b95..8b193fc097c 100644 --- a/node/src/manager/commands/mod.rs +++ b/node/src/manager/commands/mod.rs @@ -1,6 +1,7 @@ pub mod assign; pub mod chain; pub mod check_blocks; +pub mod compress_blocks; pub mod config; pub mod copy; pub mod create; diff --git a/store/postgres/src/advisory_lock.rs b/store/postgres/src/advisory_lock.rs index 6e9b9fbf0ac..e1787fd3150 100644 --- a/store/postgres/src/advisory_lock.rs +++ b/store/postgres/src/advisory_lock.rs @@ -11,6 +11,9 @@ //! We use the following 2x 32-bit locks //! * 1, n: to lock copying of the deployment with id n in the destination shard //! * 2, n: to lock the deployment with id n to make sure only one write happens to it +//! * 4, n: to lock the blocks table in the namespace `chain{n}` while compressing its blocks + +use std::fmt::Display; use diesel::sql_query; use diesel::sql_types::Bool; @@ -34,7 +37,7 @@ impl Scope { async fn try_lock( &self, conn: &mut AsyncPgConnection, - id: DeploymentId, + id: impl Display, ) -> Result { #[derive(QueryableByName)] struct Locked { @@ -66,7 +69,7 @@ impl Scope { async fn unlock( &self, conn: &mut AsyncPgConnection, - id: DeploymentId, + id: impl Display, ) -> Result<(), StoreError> { sql_query(format!("select pg_advisory_unlock({}, {id})", self.id)) .execute(conn) @@ -79,6 +82,7 @@ impl Scope { const COPY: Scope = Scope { id: 1 }; const WRITE: Scope = Scope { id: 2 }; const PRUNE: Scope = Scope { id: 3 }; +const COMPRESS: Scope = Scope { id: 4 }; /// Block until we can get the migration lock, then run `f` and unlock when /// it is done. This is used to make sure that only one node runs setup at a @@ -160,6 +164,22 @@ pub(crate) async fn try_lock_pruning( PRUNE.try_lock(conn, site.id).await } +/// Try to take the lock used to prevent two processes from compressing blocks +/// in the namespace `chain{id}` at the same time +pub(crate) async fn try_lock_compressing( + conn: &mut AsyncPgConnection, + id: i32, +) -> Result { + COMPRESS.try_lock(conn, id).await +} + +pub(crate) async fn unlock_compressing( + conn: &mut AsyncPgConnection, + id: i32, +) -> Result<(), StoreError> { + COMPRESS.unlock(conn, id).await +} + pub(crate) async fn unlock_pruning( conn: &mut AsyncPgConnection, site: &Site, diff --git a/store/postgres/src/chain_store.rs b/store/postgres/src/chain_store.rs index 04fa7f75c27..0dbc9f4745a 100644 --- a/store/postgres/src/chain_store.rs +++ b/store/postgres/src/chain_store.rs @@ -39,6 +39,10 @@ use graph::{ensure, internal_error}; use self::recent_blocks_cache::RecentBlocksCache; use crate::AsyncPgConnection; use crate::block_compression::BlockCompression; +use crate::compress_blocks::{ + BlocksCompressor, CompressBlocksProgress, CompressBlocksReporter, CompressBlocksRequest, + CompressBlocksStatus, +}; use crate::vid_batcher::AdaptiveBatchSize; use crate::{chain_head_listener::ChainHeadUpdateSender, pool::ConnectionPool}; @@ -3234,6 +3238,36 @@ impl ChainStore { Ok(()) } + /// Return what we need for compressing the blocks that are already stored + async fn blocks_compressor( + &self, + ) -> Result<(BlocksCompressor, crate::pool::PermittedConnection), StoreError> { + if self.storage.is_shared() { + return Err(StoreError::from(anyhow!( + "can not compress blocks for {} since its storage is shared with other chains", + self.chain + ))); + } + let conn = self.pool.get_permitted().await?; + Ok((BlocksCompressor::new(&self.storage.to_string()), conn)) + } + + /// Rewrite the blocks that are already stored so that they are stored + /// with `req.compression` + pub async fn compress_blocks( + &self, + req: &CompressBlocksRequest, + reporter: &mut dyn CompressBlocksReporter, + ) -> Result { + let (compressor, mut conn) = self.blocks_compressor().await?; + compressor.run(&mut conn, req, reporter).await + } + + pub async fn compress_blocks_status(&self) -> Result { + let (compressor, mut conn) = self.blocks_compressor().await?; + compressor.status(&mut conn).await + } + async fn blocks_from_store( self: &Arc, hashes: Vec, diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs new file mode 100644 index 00000000000..a36f9584cfb --- /dev/null +++ b/store/postgres/src/compress_blocks.rs @@ -0,0 +1,1152 @@ +//! Compress blocks that are already in the block cache by rewriting each block +//! where it is stored, a batch at a time, while the chain is in use. A block +//! that a node changes while we work on it keeps what the node wrote + +use std::collections::HashSet; +use std::fmt; +use std::time::{Duration, Instant}; + +use anyhow::anyhow; +use async_trait::async_trait; +use diesel::sql_query; +use diesel::sql_types::{Array, BigInt, Bool, Bytea, Jsonb, Nullable, Text}; +use diesel_async::{AsyncConnection as _, RunQueryDsl as _, SimpleAsyncConnection as _}; +use graph::prelude::{Error, StoreError, serde_json as json}; + +use crate::block_compression::{BlockCompression, decompress, is_placeholder}; +use crate::vid_batcher::AdaptiveBatchSize; +use crate::{AsyncPgConnection, advisory_lock, catalog, copy}; + +/// Blocks can be large, and we hold a whole batch in memory +const MAX_BATCH_SIZE: i64 = 100; +const INITIAL_BATCH_SIZE: i64 = 10; +/// How long we want one batch to take +const BATCH_DURATION: Duration = Duration::from_secs(1); + +/// Queries that need a conflicting lock wait while we wait for a lock, so give +/// up quickly and try again later. This must be longer than the default +/// `deadlock_timeout` of 1s, or Postgres won't cancel autovacuum for us +const LOCK_TIMEOUT: Duration = Duration::from_secs(2); +const LOCK_RETRY_INTERVAL: Duration = Duration::from_secs(5); +const MAX_LOCK_ATTEMPTS: usize = 60; + +/// How often to try again to rewrite blocks that were locked or changed when +/// we first tried, and how long to wait before each new attempt +const RETRY_ATTEMPTS: usize = 3; +const RETRY_INTERVAL: Duration = Duration::from_secs(10); + +/// The setting in which SQL tells us why it could not take a lock +const LOCK_FAILURE_SETTING: &str = "graph_node.compress_blocks_lock_failure"; + +pub struct CompressBlocksRequest { + /// How to store the blocks. With `None`, compressed blocks are + /// uncompressed + pub compression: BlockCompression, + /// How many bytes of WAL to write per second at most + pub max_wal_rate: u64, +} + +/// How far compressing blocks has gotten +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CompressBlocksProgress { + /// How the blocks are being stored + pub compression: BlockCompression, + /// All blocks with a smaller number have been rewritten + pub next_block: i64, + /// The last block that needs to be rewritten + pub last_block: i64, + /// How many blocks were locked or changed when we wanted to rewrite them + /// and still need to be tried again + pub retry: usize, + /// How many blocks were left as they were because they were locked or + /// changed every time we tried to rewrite them + pub skipped: usize, + /// How many blocks this process rewrote + pub blocks: usize, + /// How much space these blocks took up before and after + pub old_bytes: u64, + pub new_bytes: u64, + /// How much WAL the database wrote while we rewrote these blocks + pub wal_bytes: u64, +} + +/// What is known about compressing the blocks of a chain +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CompressBlocksStatus { + NotStarted, + Unfinished(CompressBlocksProgress), + Finished(CompressBlocksProgress), +} + +/// Why a run pauses +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CompressBlocksPause { + /// Replicas lag behind by this much + ReplicaLag(Duration), + /// We could not lock the table, and have tried this many times + Locked { + table: String, + why: String, + attempts: usize, + }, +} + +impl fmt::Display for CompressBlocksPause { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + CompressBlocksPause::ReplicaLag(lag) => write!( + f, + "replicas are lagging by {}s; waiting for them to catch up", + lag.as_secs() + ), + CompressBlocksPause::Locked { + table, + why, + attempts, + } => write!( + f, + "could not lock {table} ({why}) after {attempts} attempts; trying again in {}s", + LOCK_RETRY_INTERVAL.as_secs() + ), + } + } +} + +/// Points in a run at which tests can change the database +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CompressBlocksStep { + /// The blocks with numbers from `first` to `last` were read but not + /// written yet + Read { first: i64, last: i64 }, + /// All blocks before `next_block` have been rewritten + Written { next_block: i64 }, + /// We are about to try again to rewrite blocks that were locked or + /// changed + Retry { attempt: usize, blocks: usize }, +} + +#[async_trait] +pub trait CompressBlocksReporter: Send { + fn message(&mut self, msg: &str); + + fn progress(&mut self, progress: &CompressBlocksProgress); + + /// The run pauses because of `pause` and checks again in a while. + /// Returning an error stops the run + fn paused(&mut self, pause: &CompressBlocksPause) -> Result<(), StoreError> { + self.message(&format!("pausing: {pause}")); + Ok(()) + } + + /// The run reached `step`. Tests use this to change the database at + /// that point; returning an error stops the run + async fn reached(&mut self, _step: CompressBlocksStep) -> Result<(), StoreError> { + Ok(()) + } +} + +/// Why we could not take a lock +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum LockFailure { + Timeout, + Deadlock, +} + +impl LockFailure { + /// Classify an error by its SQLSTATE. The database driver only tells us + /// the error message, which depends on the language of the server, and + /// SQL therefore classifies errors for us + fn from_sqlstate(sqlstate: &str) -> Option { + match sqlstate { + // lock_not_available + "55P03" => Some(LockFailure::Timeout), + // deadlock_detected + "40P01" => Some(LockFailure::Deadlock), + _ => None, + } + } +} + +impl fmt::Display for LockFailure { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + LockFailure::Timeout => write!(f, "it stayed locked for {}s", LOCK_TIMEOUT.as_secs()), + LockFailure::Deadlock => write!(f, "there was a deadlock"), + } + } +} + +#[derive(QueryableByName)] +struct BlockRow { + #[diesel(sql_type = Bytea)] + hash: Vec, + #[diesel(sql_type = BigInt)] + number: i64, + /// The row's `xmin`, which changes whenever the row is written + #[diesel(sql_type = Text)] + xmin: String, + #[diesel(sql_type = Jsonb)] + data: json::Value, + #[diesel(sql_type = Nullable)] + data_zstd: Option>, + /// How much space `data` and `data_zstd` take up + #[diesel(sql_type = BigInt)] + size: i64, +} + +/// How to rewrite a row +#[derive(Debug, PartialEq)] +struct Rewrite { + hash: Vec, + xmin: String, + /// The new `data`, or `None` to keep it as it is + data: Option, + data_zstd: Option>, + /// How much space the row's data took up before + old_size: u64, +} + +impl BlockRow { + /// Return how to rewrite the row so that the block is stored with + /// `compression`, or `None` if it does not need to be rewritten. Without + /// compression, `data_zstd` must have been read + fn rewrite(self, compression: BlockCompression) -> Result, Error> { + let BlockRow { + hash, + xmin, + data, + data_zstd, + size, + .. + } = self; + let (data, data_zstd) = match compression { + BlockCompression::Zstd(_) => { + if is_placeholder(&data) { + return Ok(None); + } + let Some((placeholder, bytes)) = compression.encode(&data)? else { + return Ok(None); + }; + anyhow::ensure!( + json::from_slice::(&decompress(&bytes)?)? == data, + "uncompressing the block produces different data" + ); + (Some(placeholder), Some(bytes)) + } + BlockCompression::None => { + if is_placeholder(&data) { + let bytes = data_zstd.ok_or_else(|| anyhow!("there is no compressed data"))?; + let block: json::Value = json::from_slice(&decompress(&bytes)?)?; + (Some(block), None) + } else if data_zstd.is_some() { + // Code that does not know about compressed blocks left an + // outdated value behind that readers ignore + (None, None) + } else { + return Ok(None); + } + } + }; + Ok(Some(Rewrite { + hash, + xmin, + data, + data_zstd, + old_size: size as u64, + })) + } +} + +#[derive(QueryableByName)] +struct ProgressRow { + #[diesel(sql_type = BigInt)] + next_block: i64, + #[diesel(sql_type = BigInt)] + last_block: i64, + #[diesel(sql_type = Text)] + compression: String, + #[diesel(sql_type = Array)] + retry: Vec>, + #[diesel(sql_type = BigInt)] + skipped: i64, +} + +#[derive(QueryableByName)] +struct Number { + #[diesel(sql_type = Nullable)] + number: Option, +} + +#[derive(QueryableByName)] +struct Hash { + #[diesel(sql_type = Bytea)] + hash: Vec, +} + +async fn is_true(conn: &mut AsyncPgConnection, query: String) -> Result { + #[derive(QueryableByName)] + struct Res { + #[diesel(sql_type = Bool)] + res: bool, + } + + Ok(sql_query(query).get_result::(conn).await?.res) +} + +async fn text(conn: &mut AsyncPgConnection, query: String) -> Result { + #[derive(QueryableByName)] + struct Res { + #[diesel(sql_type = Text)] + res: String, + } + + Ok(sql_query(query).get_result::(conn).await?.res) +} + +async fn number(conn: &mut AsyncPgConnection, query: String) -> Result, StoreError> { + Ok(sql_query(query).get_result::(conn).await?.number) +} + +/// Run `stmt`, which takes a lock, and give up if that takes longer than +/// `LOCK_TIMEOUT`. Return why we could not take the lock. Must run in a +/// transaction, which keeps the lock and the timeout +async fn try_lock( + conn: &mut AsyncPgConnection, + stmt: &str, +) -> Result, StoreError> { + conn.batch_execute(&format!( + "set local lock_timeout = {timeout}; + do $$ + begin + {stmt}; + exception when lock_not_available or deadlock_detected then + perform set_config('{LOCK_FAILURE_SETTING}', sqlstate, true); + end $$", + timeout = LOCK_TIMEOUT.as_millis() + )) + .await?; + let sqlstate = text( + conn, + format!("select coalesce(current_setting('{LOCK_FAILURE_SETTING}', true), '') as res"), + ) + .await?; + if sqlstate.is_empty() { + return Ok(None); + } + LockFailure::from_sqlstate(&sqlstate) + .map(Some) + .ok_or_else(|| anyhow!("unexpected SQLSTATE {sqlstate} while taking a lock").into()) +} + +/// How much to do at once, and how long to pause after that +struct Pace { + batch_size: AdaptiveBatchSize, + max_wal_rate: u64, +} + +impl Pace { + fn new(max_wal_rate: u64) -> Self { + let mut batch_size = AdaptiveBatchSize::with_size(INITIAL_BATCH_SIZE); + batch_size.target = BATCH_DURATION; + Pace { + batch_size, + max_wal_rate: max_wal_rate.max(1), + } + } + + fn batch_size(&self) -> i64 { + self.batch_size.size + } + + /// How long to pause after something that took `elapsed` while the + /// database wrote `wal_bytes` of WAL so that it writes no more than + /// `max_wal_rate` bytes per second on average + fn pause(&self, elapsed: Duration, wal_bytes: u64) -> Duration { + Duration::from_secs_f64(wal_bytes as f64 / self.max_wal_rate as f64).saturating_sub(elapsed) + } + + /// Adjust the batch size after a batch that took `elapsed` while the + /// database wrote `wal_bytes`, and return how long to pause + fn adapt(&mut self, elapsed: Duration, wal_bytes: u64) -> Duration { + self.batch_size.adapt(elapsed); + self.batch_size.size = self.batch_size.size.clamp(1, MAX_BATCH_SIZE); + self.pause(elapsed, wal_bytes) + } +} + +/// Which blocks to rewrite +enum Batch<'a> { + Numbers { first: i64, last: i64 }, + Hashes(&'a [Vec]), +} + +/// What happened when we tried to write a batch +enum Written { + /// We could not lock the table, and wrote nothing + Locked(LockFailure), + Done(Done), +} + +/// What we wrote for a batch +#[derive(Default)] +struct Done { + blocks: usize, + old_bytes: u64, + new_bytes: u64, + /// The blocks that still need to be tried again + retry: Vec>, + /// How long the batch took, and how much WAL the database wrote + elapsed: Duration, + wal_bytes: u64, +} + +/// The progress of a run and the blocks it needs to try again +struct State { + progress: CompressBlocksProgress, + retry: Vec>, +} + +/// Compress the blocks in the table `{nsp}.blocks` +pub(crate) struct BlocksCompressor { + nsp: String, + /// The table with the blocks + blocks: String, + /// How far we got + progress: String, +} + +impl BlocksCompressor { + pub(crate) fn new(nsp: &str) -> Self { + BlocksCompressor { + nsp: nsp.to_string(), + blocks: format!("{nsp}.blocks"), + progress: format!("{nsp}.compress_blocks_progress"), + } + } + + /// The number in the name of the namespace, which is unique in a database + fn lock_id(&self) -> Result { + self.nsp + .trim_start_matches(|c: char| !c.is_ascii_digit()) + .parse() + .map_err(|_| anyhow!("unexpected name for a namespace: {}", self.nsp).into()) + } + + async fn exists(&self, conn: &mut AsyncPgConnection, table: &str) -> Result { + is_true( + conn, + format!("select to_regclass('{table}') is not null as res"), + ) + .await + } + + /// Make sure that nobody else compresses these blocks + async fn lock(&self, conn: &mut AsyncPgConnection) -> Result<(), StoreError> { + if advisory_lock::try_lock_compressing(conn, self.lock_id()?).await? { + Ok(()) + } else { + Err(anyhow!("another process is compressing {}", self.blocks).into()) + } + } + + /// Release the lock from `lock` and return `res` + async fn unlock( + &self, + conn: &mut AsyncPgConnection, + res: Result, + ) -> Result { + let unlocked = advisory_lock::unlock_compressing(conn, self.lock_id()?).await; + match (res, unlocked) { + (Ok(res), Ok(())) => Ok(res), + (Ok(_), Err(e)) | (Err(e), Ok(())) => Err(e), + (Err(e), Err(unlock)) => { + Err(anyhow!("{e:#}; releasing the lock failed, too: {unlock:#}").into()) + } + } + } + + pub(crate) async fn status( + &self, + conn: &mut AsyncPgConnection, + ) -> Result { + if !self.exists(conn, &self.progress).await? { + return Ok(CompressBlocksStatus::NotStarted); + } + Ok(match self.load(conn).await? { + None => CompressBlocksStatus::NotStarted, + Some(state) if Self::is_unfinished(&state) => { + CompressBlocksStatus::Unfinished(state.progress) + } + Some(state) => CompressBlocksStatus::Finished(state.progress), + }) + } + + fn is_unfinished(state: &State) -> bool { + state.progress.next_block <= state.progress.last_block || !state.retry.is_empty() + } + + /// Store all blocks with `req.compression`. If an earlier run with the + /// same compression did not finish, continue it + pub(crate) async fn run( + &self, + conn: &mut AsyncPgConnection, + req: &CompressBlocksRequest, + reporter: &mut dyn CompressBlocksReporter, + ) -> Result { + self.lock(conn).await?; + let res = self.run_locked(conn, req, reporter).await; + self.unlock(conn, res).await + } + + async fn run_locked( + &self, + conn: &mut AsyncPgConnection, + req: &CompressBlocksRequest, + reporter: &mut dyn CompressBlocksReporter, + ) -> Result { + if !catalog::table_has_column(conn, &self.nsp, "blocks", "data_zstd").await? { + if req.compression == BlockCompression::None { + reporter.message(&format!("{} has no compressed blocks", self.blocks)); + return Ok(CompressBlocksProgress { + last_block: -1, + ..Default::default() + }); + } + self.add_zstd_column(conn, reporter).await?; + } + + let mut state = self.start(conn, req.compression, reporter).await?; + let mut pace = Pace::new(req.max_wal_rate); + while state.progress.next_block <= state.progress.last_block { + self.wait_for_replicas(conn, reporter).await?; + + // Skip over gaps in the block numbers + let first = number( + conn, + format!( + "select min(number) as number from {} where number >= {}", + self.blocks, state.progress.next_block + ), + ) + .await?; + let Some(first) = first.filter(|first| *first <= state.progress.last_block) else { + break; + }; + let last = (first + pace.batch_size() - 1).min(state.progress.last_block); + + let batch = Batch::Numbers { first, last }; + let done = self + .rewrite(conn, req.compression, reporter, &batch, &mut state) + .await?; + state.progress.next_block = last + 1; + reporter.progress(&state.progress); + reporter + .reached(CompressBlocksStep::Written { + next_block: last + 1, + }) + .await?; + tokio::time::sleep(pace.adapt(done.elapsed, done.wal_bytes)).await; + } + + // The last blocks might have been deleted while we were working + if state.progress.next_block <= state.progress.last_block { + state.progress.next_block = state.progress.last_block + 1; + sql_query(format!("update {} set next_block = $1", self.progress)) + .bind::(state.progress.next_block) + .execute(conn) + .await?; + reporter.progress(&state.progress); + } + + self.retry(conn, req, reporter, &mut state, &pace).await?; + Ok(state.progress) + } + + /// Add the column for compressed blocks, and try that several times if + /// the table is locked + async fn add_zstd_column( + &self, + conn: &mut AsyncPgConnection, + reporter: &mut dyn CompressBlocksReporter, + ) -> Result<(), StoreError> { + let stmt = format!( + "alter table {} add column if not exists data_zstd bytea, \ + alter column data_zstd set storage external", + self.blocks + ); + let mut attempts = 0; + loop { + let failure = conn + .transaction::<_, StoreError, _>(async |conn| try_lock(conn, &stmt).await) + .await?; + let Some(failure) = failure else { + reporter.message(&format!("added the column data_zstd to {}", self.blocks)); + return Ok(()); + }; + attempts += 1; + self.locked(reporter, failure, attempts).await?; + } + } + + /// Tell the reporter that we could not lock the table, and wait or fail if + /// we tried too often + async fn locked( + &self, + reporter: &mut dyn CompressBlocksReporter, + failure: LockFailure, + attempts: usize, + ) -> Result<(), StoreError> { + if attempts >= MAX_LOCK_ATTEMPTS { + return Err(anyhow!( + "could not lock {} ({failure}); giving up after {attempts} attempts", + self.blocks + ) + .into()); + } + reporter.paused(&CompressBlocksPause::Locked { + table: self.blocks.clone(), + why: failure.to_string(), + attempts, + })?; + tokio::time::sleep(LOCK_RETRY_INTERVAL).await; + Ok(()) + } + + /// Return the progress of the run to continue, or of a new run + async fn start( + &self, + conn: &mut AsyncPgConnection, + compression: BlockCompression, + reporter: &mut dyn CompressBlocksReporter, + ) -> Result { + conn.batch_execute(&format!( + "create table if not exists {} ( + next_block int8 not null, + last_block int8 not null, + compression text not null, + retry bytea[] not null default '{{}}', + skipped int8 not null default 0 + )", + self.progress + )) + .await?; + if let Some(state) = self.load(conn).await? + && state.progress.compression == compression + && Self::is_unfinished(&state) + { + reporter.message(&format!( + "continuing the earlier run at block {}", + state.progress.next_block + )); + return Ok(state); + } + + conn.transaction::<_, StoreError, _>(async |conn| { + conn.batch_execute(&format!("delete from {}", self.progress)) + .await?; + sql_query(format!( + "insert into {}(next_block, last_block, compression) + select coalesce(min(number), 0), coalesce(max(number), -1), $1 from {}", + self.progress, self.blocks + )) + .bind::(compression.to_string()) + .execute(conn) + .await?; + Ok(()) + }) + .await?; + self.load(conn) + .await? + .ok_or_else(|| anyhow!("{} is empty", self.progress).into()) + } + + async fn load(&self, conn: &mut AsyncPgConnection) -> Result, StoreError> { + let row = sql_query(format!( + "select next_block, last_block, compression, retry, skipped from {}", + self.progress + )) + .load::(conn) + .await? + .into_iter() + .next(); + let Some(row) = row else { + return Ok(None); + }; + let progress = CompressBlocksProgress { + compression: row.compression.parse()?, + next_block: row.next_block, + last_block: row.last_block, + retry: row.retry.len(), + skipped: row.skipped as usize, + ..Default::default() + }; + Ok(Some(State { + progress, + retry: row.retry, + })) + } + + async fn wal_lsn(&self, conn: &mut AsyncPgConnection) -> Result { + let lsn = number( + conn, + "select pg_wal_lsn_diff(pg_current_wal_lsn(), '0/0')::int8 as number".to_string(), + ) + .await?; + Ok(lsn.unwrap_or(0) as u64) + } + + async fn wait_for_replicas( + &self, + conn: &mut AsyncPgConnection, + reporter: &mut dyn CompressBlocksReporter, + ) -> Result<(), StoreError> { + let mut lag = catalog::replication_lag(conn).await?; + if lag > copy::MAX_REPLICATION_LAG { + while lag > copy::ACCEPTABLE_REPLICATION_LAG { + reporter.paused(&CompressBlocksPause::ReplicaLag(lag))?; + tokio::time::sleep(copy::REPLICATION_SLEEP).await; + lag = catalog::replication_lag(conn).await?; + } + } + Ok(()) + } + + /// Read the blocks in `batch` with what we need to rewrite them with + /// `compression` + async fn read( + &self, + conn: &mut AsyncPgConnection, + batch: &Batch<'_>, + compression: BlockCompression, + ) -> Result, StoreError> { + // Compressing a block replaces `data_zstd`, and we therefore only + // need it to uncompress blocks + let data_zstd = match compression { + BlockCompression::Zstd(_) => "null::bytea", + BlockCompression::None => "data_zstd", + }; + let select = format!( + "select hash, number, xmin::text as xmin, data, {data_zstd} as data_zstd, + (pg_column_size(data) + coalesce(pg_column_size(data_zstd), 0))::int8 as size + from {}", + self.blocks + ); + let rows = match batch { + Batch::Numbers { first, last } => { + sql_query(format!("{select} where number between $1 and $2")) + .bind::(first) + .bind::(last) + .load::(conn) + .await? + } + Batch::Hashes(hashes) => { + sql_query(format!("{select} where hash = any($1)")) + .bind::, _>(hashes) + .load::(conn) + .await? + } + }; + Ok(rows) + } + + /// Rewrite the blocks in `batch` with `compression` and update the progress + /// of the run. If the table is locked, wait and read the blocks again + async fn rewrite( + &self, + conn: &mut AsyncPgConnection, + compression: BlockCompression, + reporter: &mut dyn CompressBlocksReporter, + batch: &Batch<'_>, + state: &mut State, + ) -> Result { + let mut attempts = 0; + loop { + let start = Instant::now(); + let wal_start = self.wal_lsn(conn).await?; + + let rows = self.read(conn, batch, compression).await?; + if let Batch::Numbers { first, last } = batch { + reporter + .reached(CompressBlocksStep::Read { + first: *first, + last: *last, + }) + .await?; + } + // Blocks we try again leave the list of blocks to try again unless + // they need to be tried once more + let tried: HashSet> = match batch { + Batch::Numbers { .. } => rows.iter().map(|row| row.hash.clone()).collect(), + Batch::Hashes(hashes) => hashes.iter().cloned().collect(), + }; + let rewrites = Self::plan(rows, compression, reporter).await?; + let next_block = match batch { + Batch::Numbers { last, .. } => Some(last + 1), + Batch::Hashes(_) => None, + }; + + match self + .write(conn, rewrites, next_block, &state.retry, &tried) + .await? + { + Written::Locked(failure) => { + attempts += 1; + self.locked(reporter, failure, attempts).await?; + } + Written::Done(mut done) => { + done.elapsed = start.elapsed(); + done.wal_bytes = self.wal_lsn(conn).await?.saturating_sub(wal_start); + state.retry = std::mem::take(&mut done.retry); + let progress = &mut state.progress; + progress.retry = state.retry.len(); + progress.blocks += done.blocks; + progress.old_bytes += done.old_bytes; + progress.new_bytes += done.new_bytes; + progress.wal_bytes += done.wal_bytes; + return Ok(done); + } + } + } + } + + /// Work out how to rewrite `rows`. Compressing blocks can take a while, + /// and we therefore do that on another thread + async fn plan( + rows: Vec, + compression: BlockCompression, + reporter: &mut dyn CompressBlocksReporter, + ) -> Result, StoreError> { + let (rewrites, problems) = graph::spawn_blocking_allow_panic(move || { + let mut rewrites = Vec::new(); + let mut problems = Vec::new(); + for row in rows { + let number = row.number; + match row.rewrite(compression) { + Ok(Some(rewrite)) => rewrites.push(rewrite), + Ok(None) => {} + Err(e) => problems.push(format!("left block {number} as it was: {e:#}")), + } + } + (rewrites, problems) + }) + .await + .map_err(|e| anyhow!("compressing blocks panicked: {e}"))?; + for problem in &problems { + reporter.message(problem); + } + Ok(rewrites) + } + + /// Write `rewrites` in one short transaction without waiting for row locks, + /// changing only rows nobody changed since we read them. Rows we could not + /// write are tried again; the blocks in `tried` leave the list `retry` + async fn write( + &self, + conn: &mut AsyncPgConnection, + rewrites: Vec, + next_block: Option, + retry: &[Vec], + tried: &HashSet>, + ) -> Result { + #[derive(QueryableByName)] + struct Updated { + #[diesel(sql_type = Bytea)] + hash: Vec, + #[diesel(sql_type = BigInt)] + size: i64, + } + + conn.transaction::<_, StoreError, _>(async |conn| { + let lock = format!("lock table {} in row exclusive mode", self.blocks); + if let Some(failure) = try_lock(conn, &lock).await? { + return Ok(Written::Locked(failure)); + } + + let hashes: Vec<&[u8]> = rewrites.iter().map(|r| r.hash.as_slice()).collect(); + let locked: HashSet> = if hashes.is_empty() { + HashSet::new() + } else { + sql_query(format!( + "select hash from {} where hash = any($1) for update skip locked", + self.blocks + )) + .bind::, _>(&hashes) + .load::(conn) + .await? + .into_iter() + .map(|h| h.hash) + .collect() + }; + + let mut done = Done::default(); + let mut old_sizes = std::collections::HashMap::new(); + let mut hashes = Vec::new(); + let mut xmins = Vec::new(); + let mut datas = Vec::new(); + let mut data_zstds = Vec::new(); + let mut not_written = HashSet::new(); + for rewrite in rewrites { + not_written.insert(rewrite.hash.clone()); + if !locked.contains(&rewrite.hash) { + continue; + } + old_sizes.insert(rewrite.hash.clone(), rewrite.old_size); + hashes.push(rewrite.hash); + xmins.push(rewrite.xmin); + datas.push(rewrite.data); + data_zstds.push(rewrite.data_zstd); + } + let updated = if hashes.is_empty() { + Vec::new() + } else { + sql_query(format!( + "update {blocks} b + set data = coalesce(v.data, b.data), data_zstd = v.data_zstd + from unnest($1, $2, $3, $4) as v(hash, xmin, data, data_zstd) + where b.hash = v.hash and b.xmin = v.xmin::xid + returning b.hash, + (pg_column_size(b.data) + + coalesce(pg_column_size(b.data_zstd), 0))::int8 as size", + blocks = self.blocks + )) + .bind::, _>(&hashes) + .bind::, _>(&xmins) + .bind::>, _>(&datas) + .bind::>, _>(&data_zstds) + .load::(conn) + .await? + }; + for row in updated { + not_written.remove(&row.hash); + done.blocks += 1; + done.old_bytes += old_sizes.get(&row.hash).copied().unwrap_or(0); + done.new_bytes += row.size as u64; + } + + // Blocks that were deleted since we read them need no retry + let not_written: Vec<_> = not_written.into_iter().collect(); + let still_there: Vec> = if not_written.is_empty() { + Vec::new() + } else { + sql_query(format!( + "select hash from {} where hash = any($1)", + self.blocks + )) + .bind::, _>(¬_written) + .load::(conn) + .await? + .into_iter() + .map(|h| h.hash) + .collect() + }; + done.retry = retry + .iter() + .filter(|hash| !tried.contains(*hash)) + .cloned() + .chain(still_there) + .collect(); + + sql_query(format!( + "update {} set next_block = coalesce($1, next_block), retry = $2", + self.progress + )) + .bind::, _>(next_block) + .bind::, _>(&done.retry) + .execute(conn) + .await?; + Ok(Written::Done(done)) + }) + .await + } + + /// Try again to rewrite the blocks that were locked or changed, and give + /// up on those that still are after a few attempts + async fn retry( + &self, + conn: &mut AsyncPgConnection, + req: &CompressBlocksRequest, + reporter: &mut dyn CompressBlocksReporter, + state: &mut State, + pace: &Pace, + ) -> Result<(), StoreError> { + for attempt in 1..=RETRY_ATTEMPTS { + if state.retry.is_empty() { + return Ok(()); + } + if attempt > 1 { + tokio::time::sleep(RETRY_INTERVAL).await; + } + reporter.message(&format!( + "trying again to rewrite {} blocks that were locked or changed", + state.retry.len() + )); + reporter + .reached(CompressBlocksStep::Retry { + attempt, + blocks: state.retry.len(), + }) + .await?; + let hashes = state.retry.clone(); + for hashes in hashes.chunks(MAX_BATCH_SIZE as usize) { + self.wait_for_replicas(conn, reporter).await?; + let batch = Batch::Hashes(hashes); + let done = self + .rewrite(conn, req.compression, reporter, &batch, state) + .await?; + reporter.progress(&state.progress); + tokio::time::sleep(pace.pause(done.elapsed, done.wal_bytes)).await; + } + } + + if !state.retry.is_empty() { + let skipped = state.retry.len(); + reporter.message(&format!( + "left {skipped} blocks as they were since they were locked or changed \ + each time we tried to rewrite them; run this again to rewrite them" + )); + sql_query(format!( + "update {} set retry = '{{}}', skipped = $1", + self.progress + )) + .bind::(skipped as i64) + .execute(conn) + .await?; + state.retry.clear(); + state.progress.retry = 0; + state.progress.skipped = skipped; + reporter.progress(&state.progress); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use json::json; + + fn row(data: json::Value, data_zstd: Option>) -> BlockRow { + BlockRow { + hash: vec![1], + number: 1, + xmin: "7".to_string(), + data, + data_zstd, + size: 100, + } + } + + fn uncompress(bytes: &[u8]) -> json::Value { + json::from_slice(&decompress(bytes).unwrap()).unwrap() + } + + #[test] + fn rewrite_compresses_blocks() { + let compression = BlockCompression::Zstd(1); + let block = json!({ "block": { "timestamp": "0x1" }, "transaction_receipts": [] }); + + // Outdated compressed data is replaced + let rewrite = row(block.clone(), Some(vec![1, 2, 3])) + .rewrite(compression) + .unwrap() + .unwrap(); + assert!(is_placeholder(rewrite.data.as_ref().unwrap())); + assert_eq!(block, uncompress(rewrite.data_zstd.as_ref().unwrap())); + assert_eq!(("7", 100), (rewrite.xmin.as_str(), rewrite.old_size)); + + // Compressed blocks stay as they are, even with another level + let compressed = row(rewrite.data.unwrap(), rewrite.data_zstd); + assert_eq!(None, compressed.rewrite(BlockCompression::Zstd(9)).unwrap()); + + // Blocks without a timestamp are left alone + let block = json!({ "block": { "number": "0x1" } }); + assert_eq!(None, row(block, None).rewrite(compression).unwrap()); + } + + #[test] + fn rewrite_uncompresses_blocks() { + let block = json!({ "block": { "timestamp": "0x1" }, "transaction_receipts": [] }); + let (placeholder, bytes) = BlockCompression::Zstd(1).encode(&block).unwrap().unwrap(); + + let rewrite = row(placeholder.clone(), Some(bytes)) + .rewrite(BlockCompression::None) + .unwrap() + .unwrap(); + assert_eq!( + (Some(block.clone()), None), + (rewrite.data, rewrite.data_zstd) + ); + + // Outdated compressed data is removed, and the block kept + let rewrite = row(block.clone(), Some(vec![1, 2, 3])) + .rewrite(BlockCompression::None) + .unwrap() + .unwrap(); + assert_eq!((None, None), (rewrite.data, rewrite.data_zstd)); + + // Uncompressed blocks stay as they are + assert_eq!( + None, + row(block, None).rewrite(BlockCompression::None).unwrap() + ); + + // Damaged blocks are left as they are + row(placeholder.clone(), Some(vec![1, 2, 3])) + .rewrite(BlockCompression::None) + .unwrap_err(); + row(placeholder, None) + .rewrite(BlockCompression::None) + .unwrap_err(); + } + + #[test] + fn classify_lock_failures_by_sqlstate() { + assert_eq!( + Some(LockFailure::Timeout), + LockFailure::from_sqlstate("55P03") + ); + assert_eq!( + Some(LockFailure::Deadlock), + LockFailure::from_sqlstate("40P01") + ); + // query_canceled, serialization_failure, and nothing at all + for sqlstate in ["57014", "40001", ""] { + assert_eq!(None, LockFailure::from_sqlstate(sqlstate), "{sqlstate}"); + } + } + + #[test] + fn pace_by_wal() { + const MB: u64 = 1_000_000; + let secs = Duration::from_secs_f64; + + let mut pace = Pace::new(20 * MB); + assert_eq!(INITIAL_BATCH_SIZE, pace.batch_size()); + // Writing 40 MB of WAL in 0.5s needs a pause of 1.5s for 20 MB/s + assert_eq!(secs(1.5), pace.adapt(secs(0.5), 40 * MB)); + assert_eq!(2 * INITIAL_BATCH_SIZE, pace.batch_size()); + // Writing less than the limit needs no pause + assert_eq!(Duration::ZERO, pace.adapt(secs(1.0), 10 * MB)); + // Slow batches get smaller, but never empty + pace.adapt(secs(4.0), 0); + assert_eq!(INITIAL_BATCH_SIZE / 2, pace.batch_size()); + for _ in 0..10 { + pace.adapt(secs(100.0), 0); + } + assert_eq!(1, pace.batch_size()); + // Fast batches get bigger, but no bigger than the maximum + for _ in 0..10 { + pace.adapt(secs(0.001), 0); + } + assert_eq!(MAX_BATCH_SIZE, pace.batch_size()); + // Pausing after a VACUUM does not change the batch size + assert_eq!(secs(2.0), pace.pause(Duration::ZERO, 40 * MB)); + assert_eq!(MAX_BATCH_SIZE, pace.batch_size()); + } + + #[test] + fn lock_id_is_number_of_chain() { + assert_eq!(17, BlocksCompressor::new("chain17").lock_id().unwrap()); + BlocksCompressor::new("public").lock_id().unwrap_err(); + } +} diff --git a/store/postgres/src/copy.rs b/store/postgres/src/copy.rs index fd076ab0e1b..81501a2b616 100644 --- a/store/postgres/src/copy.rs +++ b/store/postgres/src/copy.rs @@ -50,13 +50,13 @@ const LOG_INTERVAL: Duration = Duration::from_secs(3 * 60); /// If replicas are lagging by more than this, the copying code will pause /// for a while to allow replicas to catch up -const MAX_REPLICATION_LAG: Duration = Duration::from_secs(60); +pub(crate) const MAX_REPLICATION_LAG: Duration = Duration::from_secs(60); /// If replicas need to catch up, do not resume copying until the lag is /// less than this -const ACCEPTABLE_REPLICATION_LAG: Duration = Duration::from_secs(30); +pub(crate) const ACCEPTABLE_REPLICATION_LAG: Duration = Duration::from_secs(30); /// When replicas are lagging too much, sleep for this long before checking /// the lag again -const REPLICATION_SLEEP: Duration = Duration::from_secs(10); +pub(crate) const REPLICATION_SLEEP: Duration = Duration::from_secs(10); lazy_static! { pub(crate) static ref BATCH_STATEMENT_TIMEOUT: Option = ENV_VARS diff --git a/store/postgres/src/lib.rs b/store/postgres/src/lib.rs index 2940c033ef3..556323c7ded 100644 --- a/store/postgres/src/lib.rs +++ b/store/postgres/src/lib.rs @@ -16,6 +16,7 @@ mod block_store; mod catalog; mod chain_head_listener; mod chain_store; +mod compress_blocks; mod copy; mod deployment; mod deployment_store; @@ -62,6 +63,10 @@ pub use self::block_store::primary::{add_chain, find_chain, update_chain_name}; pub use self::block_store::{BlockStore, ChainStoreConfig}; pub use self::chain_head_listener::ChainHeadUpdateListener; pub use self::chain_store::{ChainStore, ChainStoreMetrics, Storage}; +pub use self::compress_blocks::{ + CompressBlocksPause, CompressBlocksProgress, CompressBlocksReporter, CompressBlocksRequest, + CompressBlocksStatus, CompressBlocksStep, +}; pub use self::detail::DeploymentDetail; pub use self::jobs::register as register_jobs; pub use self::notification_listener::NotificationSender; diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index 956b79ca13d..15b1c36ba55 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -7,13 +7,14 @@ use graph::data::store::ethereum::call; use graph::data::store::scalar::Bytes; use graph::env::ENV_VARS; use graph::futures03::executor; +use graph::futures03::future::{BoxFuture, FutureExt as _}; use graph::prelude::alloy::primitives::{Address, B256}; use std::future::Future; use std::sync::Arc; use graph::cheap_clone::CheapClone; use graph::prelude::alloy; -use graph::prelude::{BlockNumber, MetricsRegistry, QueryStoreManager, QueryTarget}; +use graph::prelude::{BlockNumber, MetricsRegistry, QueryStoreManager, QueryTarget, StoreError}; use graph::prelude::{anyhow::Error, anyhow::anyhow}; use graph::{components::store::BlockStore as _, prelude::DeploymentHash}; use graph::{ @@ -21,14 +22,17 @@ use graph::{ prelude::EthereumCallCache as _, }; use graph_store_postgres::Store as DieselStore; -use graph_store_postgres::{BlockCompression, ChainStoreMetrics}; +use graph_store_postgres::{ + BlockCompression, ChainStoreMetrics, CompressBlocksPause, CompressBlocksProgress, + CompressBlocksReporter, CompressBlocksRequest, CompressBlocksStatus, CompressBlocksStep, +}; use graph_store_postgres::{ChainStore as DieselChainStore, layout_for_tests::FAKE_NETWORK_SHARED}; use test_store::block_store::{ BLOCK_FIVE, BLOCK_FIVE_AFTER_SKIP, BLOCK_FOUR, BLOCK_FOUR_SKIPPED_2_AND_3, BLOCK_ONE, BLOCK_ONE_NO_PARENT, BLOCK_ONE_SIBLING, BLOCK_THREE, BLOCK_THREE_NO_PARENT, - BLOCK_THREE_TIMESTAMP, BLOCK_THREE_TIMESTAMP_FIREHOSE, BLOCK_TWO, BLOCK_TWO_NO_PARENT, - FakeBlock, FakeBlockList, GENESIS_BLOCK, NO_PARENT, + BLOCK_THREE_NO_TIMESTAMP, BLOCK_THREE_TIMESTAMP, BLOCK_THREE_TIMESTAMP_FIREHOSE, BLOCK_TWO, + BLOCK_TWO_NO_PARENT, FakeBlock, FakeBlockList, GENESIS_BLOCK, NO_PARENT, }; use test_store::*; @@ -702,6 +706,196 @@ async fn restore_column(store: &DieselChainStore, namespace: &str) { .await; } +/// What a test does when a run reaches a step +type StepHook = + Box BoxFuture<'static, Result<(), StoreError>> + Send>; + +/// A reporter that remembers what happened, turns pauses into errors unless +/// told otherwise, and lets a test change the database during a run +#[derive(Default)] +struct TestReporter { + messages: Vec, + pauses: Vec, + steps: Vec, + allow_pauses: bool, + hook: Option, +} + +impl TestReporter { + fn with_hook( + hook: impl FnMut(CompressBlocksStep) -> BoxFuture<'static, Result<(), StoreError>> + + Send + + 'static, + ) -> Self { + TestReporter { + hook: Some(Box::new(hook)), + ..Default::default() + } + } +} + +#[async_trait::async_trait] +impl CompressBlocksReporter for TestReporter { + fn message(&mut self, msg: &str) { + self.messages.push(msg.to_string()); + } + + fn progress(&mut self, _: &CompressBlocksProgress) {} + + fn paused(&mut self, pause: &CompressBlocksPause) -> Result<(), StoreError> { + self.pauses.push(pause.clone()); + if self.allow_pauses { + Ok(()) + } else { + Err(anyhow!("paused: {pause}").into()) + } + } + + async fn reached(&mut self, step: CompressBlocksStep) -> Result<(), StoreError> { + self.steps.push(step); + match self.hook.as_mut() { + Some(hook) => hook(step).await, + None => Ok(()), + } + } +} + +fn compress_request(compression: BlockCompression) -> CompressBlocksRequest { + CompressBlocksRequest { + compression, + max_wal_rate: 1_000_000_000_000, + } +} + +async fn compress_blocks( + store: &DieselChainStore, + compression: BlockCompression, +) -> Result { + store + .compress_blocks(&compress_request(compression), &mut TestReporter::default()) + .await +} + +/// Forget earlier runs so that the next run starts with the first block +async fn reset_compress_blocks(store: &DieselChainStore, namespace: &str) { + execute( + store, + format!("drop table if exists {namespace}.compress_blocks_progress"), + ) + .await; +} + +/// Read blocks through a chain store that has nothing cached in memory +async fn read_stored_blocks(store: &DieselChainStore, blocks: &[&FakeBlock]) -> Vec { + let store = compressing_store(store, BlockCompression::None); + let hashes = blocks.iter().map(|block| block.block_hash()).collect(); + let mut blocks: Vec<_> = store + .blocks(hashes) + .await + .unwrap() + .iter() + .map(|block| format!("{block:?}")) + .collect(); + blocks.sort(); + blocks +} + +fn uncompress(data_zstd: Option<&Vec>) -> serde_json::Value { + let bytes = zstd::stream::decode_all(data_zstd.expect("the block is compressed").as_slice()); + serde_json::from_slice(&bytes.unwrap()).unwrap() +} + +#[derive(diesel::QueryableByName)] +struct Name { + #[diesel(sql_type = diesel::sql_types::Text)] + name: String, +} + +async fn names(store: &DieselChainStore, query: String) -> Vec { + let mut conn = store.get_conn_for_test().await.unwrap(); + diesel::sql_query(query) + .load::(&mut conn) + .await + .unwrap() + .into_iter() + .map(|name| name.name) + .collect() +} + +/// The tables and views in `namespace` +async fn tables(store: &DieselChainStore, namespace: &str) -> Vec { + names( + store, + format!( + "select relname::text as name from pg_class + where relnamespace = '{namespace}'::regnamespace + and relkind in ('r', 'p', 'v', 'm', 'f') + order by relname" + ), + ) + .await +} + +/// The file in which the blocks table is stored +async fn blocks_file(store: &DieselChainStore, namespace: &str) -> Vec { + names( + store, + format!("select pg_relation_filepath('{namespace}.blocks') as name"), + ) + .await +} + +/// The `xmin` of the blocks with a number below `number` +async fn xmins(store: &DieselChainStore, namespace: &str, number: i64) -> Vec { + names( + store, + format!( + "select xmin::text as name from {namespace}.blocks + where number < {number} order by number" + ), + ) + .await +} + +async fn count_compressed(store: &DieselChainStore, namespace: &str) -> usize { + names( + store, + format!( + "select hash::text as name from {namespace}.blocks + where data ? '__zstd' and data_zstd is not null" + ), + ) + .await + .len() +} + +/// Add `count` copies of `BLOCK_ONE` with numbers from `first` on, each with +/// its own hash and about `pad` bytes of hex digits in `extraData` +async fn add_blocks(store: &DieselChainStore, namespace: &str, first: i64, count: i64, pad: i64) { + use diesel::sql_types::{BigInt, Jsonb}; + + let mut conn = store.get_conn_for_test().await.unwrap(); + diesel::sql_query(format!( + "insert into {namespace}.blocks(hash, number, parent_hash, data) + select decode(lpad(to_hex(n), 64, '0'), 'hex'), n, + decode(lpad(to_hex(n - 1), 64, '0'), 'hex'), + jsonb_set(jsonb_set(jsonb_set($1, + '{{block,hash}}', to_jsonb('0x' || lpad(to_hex(n), 64, '0'))), + '{{block,number}}', to_jsonb('0x' || to_hex(n))), + '{{block,extraData}}', to_jsonb('0x' || coalesce( + (select string_agg(md5(n || '-' || i), '') + from generate_series(1, $4) i), ''))) + from generate_series($2, $2 + $3 - 1) n" + )) + .bind::(BLOCK_ONE.data().unwrap()) + .bind::(first) + .bind::(count) + .bind::(pad / 32) + .execute(&mut conn) + .await + .unwrap(); +} + /// Return the storage type of the column for compressed blocks if it exists async fn column_storage(store: &DieselChainStore, namespace: &str) -> Option { use diesel::OptionalExtension as _; @@ -1171,6 +1365,304 @@ fn store_blocks_uncompressed_while_column_is_missing() { }) } +#[test] +fn compress_blocks_in_place() { + let chain = vec![ + &*GENESIS_BLOCK, + &*BLOCK_ONE, + &*BLOCK_TWO, + &*BLOCK_THREE_NO_TIMESTAMP, + &*BLOCK_FOUR, + ]; + run_test_async(chain.clone(), move |store, _, _| { + let chain = chain.clone(); + async move { + let Some(nsp) = private_namespace(&store).await else { + compress_blocks(&store, BlockCompression::Zstd(1)) + .await + .unwrap_err(); + return; + }; + reset_compress_blocks(&store, &nsp).await; + let compressible = [&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO, &*BLOCK_FOUR]; + let mut stored = Vec::new(); + for block in compressible { + stored.push(raw_block(&store, &nsp, block).await.data); + } + let read = read_stored_blocks(&store, &chain).await; + let tables_before = tables(&store, &nsp).await; + let file = blocks_file(&store, &nsp).await; + + let progress = compress_blocks(&store, BlockCompression::Zstd(1)) + .await + .unwrap(); + assert_eq!( + (4, 0, 0), + (progress.blocks, progress.retry, progress.skipped) + ); + for (block, data) in compressible.into_iter().zip(stored) { + let raw = raw_block(&store, &nsp, block).await; + assert!(raw.is_compressed(), "{} is not compressed", block.number); + assert_eq!(data, uncompress(raw.data_zstd.as_ref())); + } + let raw = raw_block(&store, &nsp, &BLOCK_THREE_NO_TIMESTAMP).await; + assert_eq!(BLOCK_THREE_NO_TIMESTAMP.data().unwrap(), raw.data); + assert_eq!(None, raw.data_zstd); + assert_eq!(read, read_stored_blocks(&store, &chain).await); + + // The blocks stay where they are, and only the progress is new + let mut exp = tables_before; + exp.push("compress_blocks_progress".to_string()); + exp.sort(); + assert_eq!(exp, tables(&store, &nsp).await); + assert_eq!(file, blocks_file(&store, &nsp).await); + let CompressBlocksStatus::Finished(status) = + store.compress_blocks_status().await.unwrap() + else { + panic!("compressing blocks did not finish"); + }; + assert_eq!((5, 4), (status.next_block, status.last_block)); + + // Running again finds nothing to do + let progress = compress_blocks(&store, BlockCompression::Zstd(1)) + .await + .unwrap(); + assert_eq!(0, progress.blocks); + reset_compress_blocks(&store, &nsp).await; + } + }) +} + +#[test] +fn keep_blocks_that_nodes_change() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + + // A node rewrites block 1 after we read it and before we write it + let node = store.cheap_clone(); + let change = format!( + "update {nsp}.blocks + set data = jsonb_set(data, '{{block,extraData}}', '\"0x17\"') + where number = 1" + ); + let mut changed = false; + let mut reporter = TestReporter::with_hook(move |step| { + let now = !changed + && matches!(step, CompressBlocksStep::Read { first, last } + if first <= 1 && 1 <= last); + changed |= now; + let (node, change) = (node.cheap_clone(), change.clone()); + async move { + if now { + execute(&node, change).await; + } + Ok(()) + } + .boxed() + }); + let progress = store + .compress_blocks(&compress_request(BlockCompression::Zstd(1)), &mut reporter) + .await + .unwrap(); + + // We left the block alone and compressed what the node wrote later + let retry = CompressBlocksStep::Retry { + attempt: 1, + blocks: 1, + }; + assert!(reporter.steps.contains(&retry), "{:?}", reporter.steps); + assert_eq!((3, 0), (progress.blocks, progress.skipped)); + let raw = raw_block(&store, &nsp, &BLOCK_ONE).await; + assert!(raw.is_compressed()); + let block = uncompress(raw.data_zstd.as_ref()); + assert_eq!("0x17", block["block"]["extraData"]); + reset_compress_blocks(&store, &nsp).await; + }) +} + +#[test] +fn retry_blocks_that_are_locked() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + use diesel_async::SimpleAsyncConnection as _; + + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + + // Another transaction locks block 2 until we try it again + let mut holder = store.get_conn_for_test().await.unwrap(); + holder + .batch_execute(&format!( + "begin; select 1 from {nsp}.blocks where number = 2 for update" + )) + .await + .unwrap(); + let holder = Arc::new(tokio::sync::Mutex::new(Some(holder))); + let release = holder.clone(); + let mut reporter = TestReporter::with_hook(move |step| { + let release = release.clone(); + async move { + if let CompressBlocksStep::Retry { .. } = step + && let Some(mut conn) = release.lock().await.take() + { + conn.batch_execute("commit").await.unwrap(); + } + Ok(()) + } + .boxed() + }); + let res = store + .compress_blocks(&compress_request(BlockCompression::Zstd(1)), &mut reporter) + .await; + if let Some(mut conn) = holder.lock().await.take() { + conn.batch_execute("rollback").await.unwrap(); + } + + let progress = res.unwrap(); + let retry = CompressBlocksStep::Retry { + attempt: 1, + blocks: 1, + }; + assert!(reporter.steps.contains(&retry), "{:?}", reporter.steps); + assert_eq!((3, 0), (progress.blocks, progress.skipped)); + assert!(raw_block(&store, &nsp, &BLOCK_TWO).await.is_compressed()); + reset_compress_blocks(&store, &nsp).await; + }) +} + +#[test] +fn uncompress_blocks() { + let chain = vec![ + &*GENESIS_BLOCK, + &*BLOCK_ONE, + &*BLOCK_TWO, + &*BLOCK_THREE_NO_TIMESTAMP, + &*BLOCK_FOUR, + ]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + let restored = [&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + let mut stored = Vec::new(); + for block in restored { + stored.push(raw_block(&store, &nsp, block).await.data); + } + let read = read_stored_blocks(&store, &restored).await; + + compress_blocks(&store, BlockCompression::Zstd(1)) + .await + .unwrap(); + // Code that does not know about compression overwrote block 3, and + // block 4 is damaged + execute( + &store, + format!("update {nsp}.blocks set data_zstd = '\\x0102' where number = 3"), + ) + .await; + execute( + &store, + format!("update {nsp}.blocks set data_zstd = '\\xdead' where number = 4"), + ) + .await; + + let mut reporter = TestReporter::default(); + let progress = store + .compress_blocks(&compress_request(BlockCompression::None), &mut reporter) + .await + .unwrap(); + assert_eq!(BlockCompression::None, progress.compression); + assert_eq!(4, progress.blocks); + for (block, data) in restored.into_iter().zip(stored) { + let raw = raw_block(&store, &nsp, block).await; + assert_eq!((data, None), (raw.data, raw.data_zstd), "{}", block.number); + } + assert_eq!(read, read_stored_blocks(&store, &restored).await); + let raw = raw_block(&store, &nsp, &BLOCK_THREE_NO_TIMESTAMP).await; + assert_eq!(BLOCK_THREE_NO_TIMESTAMP.data().unwrap(), raw.data); + assert_eq!(None, raw.data_zstd); + + // The damaged block stays as it is, and we hear about it + let raw = raw_block(&store, &nsp, &BLOCK_FOUR).await; + assert_eq!(Some(vec![0xde, 0xad]), raw.data_zstd); + assert!( + reporter + .messages + .iter() + .any(|msg| msg.contains("left block 4 as it was")), + "{:?}", + reporter.messages + ); + reset_compress_blocks(&store, &nsp).await; + }) +} + +#[test] +fn resume_compressing_blocks() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + add_blocks(&store, &nsp, 100, 40, 0).await; + let req = compress_request(BlockCompression::Zstd(1)); + + // Stop after the first batch + let mut reporter = TestReporter::with_hook(|step| { + async move { + match step { + CompressBlocksStep::Written { .. } => Err(anyhow!("stopped").into()), + _ => Ok(()), + } + } + .boxed() + }); + let err = store + .compress_blocks(&req, &mut reporter) + .await + .unwrap_err(); + assert!(err.to_string().contains("stopped"), "{err}"); + let CompressBlocksStatus::Unfinished(status) = + store.compress_blocks_status().await.unwrap() + else { + panic!("compressing blocks did not stop"); + }; + assert_eq!((10, 139), (status.next_block, status.last_block)); + assert_eq!(3, count_compressed(&store, &nsp).await); + let first_blocks = xmins(&store, &nsp, 10).await; + + // Continuing starts where the first run stopped and compresses every + // other block once + let mut reporter = TestReporter::default(); + let progress = store.compress_blocks(&req, &mut reporter).await.unwrap(); + assert_eq!(40, progress.blocks); + assert!( + matches!( + reporter.steps[0], + CompressBlocksStep::Read { first: 100, .. } + ), + "{:?}", + reporter.steps + ); + assert_eq!(43, count_compressed(&store, &nsp).await); + assert_eq!(first_blocks, xmins(&store, &nsp, 10).await); + execute( + &store, + format!("delete from {nsp}.blocks where number >= 100"), + ) + .await; + reset_compress_blocks(&store, &nsp).await; + }) +} + #[test] fn receipts_of_compressed_block() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; From 24d79f38656a06b64f54ef5a5ebf38b3d7ff62fb Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Thu, 3 Dec 2026 22:07:40 +0100 Subject: [PATCH 02/24] feat(store): run VACUUM while compressing blocks and give way to others Rewritten blocks leave old versions behind, and autovacuum waits until a fifth of a table is dead. Run VACUUM every 1 GiB or so on its own connection, stop it when anyone waits over a second for a lock on the table, and pause if the table still grows more than that allows. --- node/src/bin/manager.rs | 7 +- node/src/manager/commands/compress_blocks.rs | 3 + store/postgres/src/chain_store.rs | 5 +- store/postgres/src/compress_blocks.rs | 451 +++++++++++++++++- store/test-store/tests/postgres/chain_head.rs | 86 ++++ 5 files changed, 537 insertions(+), 15 deletions(-) diff --git a/node/src/bin/manager.rs b/node/src/bin/manager.rs index 1ce9d402bfb..614736ec072 100644 --- a/node/src/bin/manager.rs +++ b/node/src/bin/manager.rs @@ -622,6 +622,10 @@ pub enum CompressBlocksCommand { /// How many MB of WAL to write per second at most #[clap(long, default_value = "20", value_parser = clap::value_parser!(u64).range(1..))] max_rate: u64, + /// Run VACUUM after rewriting this many GB of blocks. By default, the + /// size of the index of the TOAST table, but at least 1 GiB + #[clap(long, value_parser = clap::value_parser!(u64).range(1..))] + vacuum_every: Option, }, /// Show how far the last run got Status, @@ -1576,7 +1580,8 @@ async fn main() -> anyhow::Result<()> { Run { compression, max_rate, - } => run(chain_store, compression, max_rate).await, + vacuum_every, + } => run(chain_store, compression, max_rate, vacuum_every).await, Status => status(chain_store).await, } } diff --git a/node/src/manager/commands/compress_blocks.rs b/node/src/manager/commands/compress_blocks.rs index fe79c4ae017..6a0337c7472 100644 --- a/node/src/manager/commands/compress_blocks.rs +++ b/node/src/manager/commands/compress_blocks.rs @@ -8,6 +8,7 @@ use graph_store_postgres::{ }; const MB: u64 = 1_000_000; +const GB: u64 = 1_000_000_000; /// How often to print progress const REPORT_INTERVAL: Duration = Duration::from_secs(10); @@ -72,10 +73,12 @@ pub async fn run( chain_store: Arc, compression: BlockCompression, max_rate: u64, + vacuum_every: Option, ) -> Result<(), Error> { let req = CompressBlocksRequest { compression, max_wal_rate: max_rate * MB, + vacuum_every: vacuum_every.map(|gb| gb * GB), }; let progress = chain_store .compress_blocks(&req, &mut Reporter::new()) diff --git a/store/postgres/src/chain_store.rs b/store/postgres/src/chain_store.rs index 0dbc9f4745a..16cd1e89e8a 100644 --- a/store/postgres/src/chain_store.rs +++ b/store/postgres/src/chain_store.rs @@ -3249,7 +3249,10 @@ impl ChainStore { ))); } let conn = self.pool.get_permitted().await?; - Ok((BlocksCompressor::new(&self.storage.to_string()), conn)) + Ok(( + BlocksCompressor::new(&self.storage.to_string(), self.pool.clone()), + conn, + )) } /// Rewrite the blocks that are already stored so that they are stored diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index a36f9584cfb..c00848897f8 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -2,20 +2,20 @@ //! where it is stored, a batch at a time, while the chain is in use. A block //! that a node changes while we work on it keeps what the node wrote -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::fmt; use std::time::{Duration, Instant}; use anyhow::anyhow; use async_trait::async_trait; use diesel::sql_query; -use diesel::sql_types::{Array, BigInt, Bool, Bytea, Jsonb, Nullable, Text}; +use diesel::sql_types::{Array, BigInt, Bool, Bytea, Integer, Jsonb, Nullable, Text}; use diesel_async::{AsyncConnection as _, RunQueryDsl as _, SimpleAsyncConnection as _}; use graph::prelude::{Error, StoreError, serde_json as json}; use crate::block_compression::{BlockCompression, decompress, is_placeholder}; use crate::vid_batcher::AdaptiveBatchSize; -use crate::{AsyncPgConnection, advisory_lock, catalog, copy}; +use crate::{AsyncPgConnection, ConnectionPool, advisory_lock, catalog, copy}; /// Blocks can be large, and we hold a whole batch in memory const MAX_BATCH_SIZE: i64 = 100; @@ -35,6 +35,25 @@ const MAX_LOCK_ATTEMPTS: usize = 60; const RETRY_ATTEMPTS: usize = 3; const RETRY_INTERVAL: Duration = Duration::from_secs(10); +/// We run VACUUM after rewriting this many bytes of blocks at least, and no +/// less than the size of the index of the TOAST table since VACUUM reads it all +const MIN_VACUUM_EVERY: u64 = 1 << 30; +/// How often our VACUUM checks whether others wait for a lock on the table, +/// and how long they may wait before it gives way and we try again later +const VACUUM_WATCH_INTERVAL: Duration = Duration::from_secs(1); +const MAX_LOCK_WAIT: Duration = Duration::from_secs(1); +const VACUUM_RETRY_INTERVAL: Duration = Duration::from_secs(10); +/// Settings for our VACUUM. A short cost delay keeps it from hogging I/O +const VACUUM_MEMORY: &str = "1GB"; +const VACUUM_COST_DELAY_MS: u64 = 2; +/// Marks the statement of our VACUUM so that we never cancel anything else +const VACUUM_MARKER: &str = "/* graph-node compress-blocks */"; + +const MB: u64 = 1_000_000; + +/// How long to wait before checking whether a reason to pause went away +const PAUSE_INTERVAL: Duration = Duration::from_secs(10); + /// The setting in which SQL tells us why it could not take a lock const LOCK_FAILURE_SETTING: &str = "graph_node.compress_blocks_lock_failure"; @@ -44,6 +63,9 @@ pub struct CompressBlocksRequest { pub compression: BlockCompression, /// How many bytes of WAL to write per second at most pub max_wal_rate: u64, + /// Run VACUUM after rewriting this many bytes of blocks. By default, the + /// size of the index of the TOAST table, but at least 1 GiB + pub vacuum_every: Option, } /// How far compressing blocks has gotten @@ -89,6 +111,18 @@ pub enum CompressBlocksPause { why: String, attempts: usize, }, + /// Our VACUUM gave way to these sessions that waited for a lock + VacuumGaveWay { table: String, waiters: Vec }, + /// A VACUUM that prevents transaction ID wraparound runs on the table + Wraparound { table: String, pids: Vec }, + /// The table grew by more than we allow, which happens when VACUUM can + /// not clean up after us + Growth { + table: String, + start: u64, + size: u64, + limit: u64, + }, } impl fmt::Display for CompressBlocksPause { @@ -108,6 +142,30 @@ impl fmt::Display for CompressBlocksPause { "could not lock {table} ({why}) after {attempts} attempts; trying again in {}s", LOCK_RETRY_INTERVAL.as_secs() ), + CompressBlocksPause::VacuumGaveWay { table, waiters } => write!( + f, + "stopped VACUUM of {table} since others waited for a lock on it: {}; \ + trying again once nobody waits", + waiters.join(", ") + ), + CompressBlocksPause::Growth { + table, + start, + size, + limit, + } => write!( + f, + "{table} grew from {} MB to {} MB, more than the {} MB we allow; \ + something may keep VACUUM from cleaning up", + start / MB, + size / MB, + limit / MB + ), + CompressBlocksPause::Wraparound { table, pids } => write!( + f, + "a VACUUM that prevents transaction ID wraparound runs on {table} (pid {pids:?}); \ + waiting for it to finish" + ), } } } @@ -123,6 +181,8 @@ pub enum CompressBlocksStep { /// We are about to try again to rewrite blocks that were locked or /// changed Retry { attempt: usize, blocks: usize }, + /// We are about to run VACUUM on the blocks table + Vacuum, } #[async_trait] @@ -283,6 +343,15 @@ struct Hash { hash: Vec, } +/// A session that waits for a lock +#[derive(QueryableByName)] +struct Waiter { + #[diesel(sql_type = Integer)] + pid: i32, + #[diesel(sql_type = Text)] + what: String, +} + async fn is_true(conn: &mut AsyncPgConnection, query: String) -> Result { #[derive(QueryableByName)] struct Res { @@ -404,6 +473,12 @@ struct Done { struct State { progress: CompressBlocksProgress, retry: Vec>, + /// Run VACUUM after rewriting this many bytes of blocks + vacuum_every: u64, + /// How many bytes of blocks we rewrote since the last VACUUM + since_vacuum: u64, + /// The size of the table when we started + start_size: u64, } /// Compress the blocks in the table `{nsp}.blocks` @@ -413,23 +488,29 @@ pub(crate) struct BlocksCompressor { blocks: String, /// How far we got progress: String, + /// Where VACUUM gets its connection + pool: ConnectionPool, +} + +/// The number in the name of the namespace, which is unique in a database +fn lock_id(nsp: &str) -> Result { + nsp.trim_start_matches(|c: char| !c.is_ascii_digit()) + .parse() + .map_err(|_| anyhow!("unexpected name for a namespace: {nsp}").into()) } impl BlocksCompressor { - pub(crate) fn new(nsp: &str) -> Self { + pub(crate) fn new(nsp: &str, pool: ConnectionPool) -> Self { BlocksCompressor { nsp: nsp.to_string(), blocks: format!("{nsp}.blocks"), progress: format!("{nsp}.compress_blocks_progress"), + pool, } } - /// The number in the name of the namespace, which is unique in a database fn lock_id(&self) -> Result { - self.nsp - .trim_start_matches(|c: char| !c.is_ascii_digit()) - .parse() - .map_err(|_| anyhow!("unexpected name for a namespace: {}", self.nsp).into()) + lock_id(&self.nsp) } async fn exists(&self, conn: &mut AsyncPgConnection, table: &str) -> Result { @@ -514,11 +595,14 @@ impl BlocksCompressor { } self.add_zstd_column(conn, reporter).await?; } + self.check_owner(conn).await?; let mut state = self.start(conn, req.compression, reporter).await?; + state.vacuum_every = self.vacuum_every(conn, req).await?; + state.start_size = self.total_size(conn).await?; let mut pace = Pace::new(req.max_wal_rate); while state.progress.next_block <= state.progress.last_block { - self.wait_for_replicas(conn, reporter).await?; + self.wait_until_clear(conn, reporter, &state).await?; // Skip over gaps in the block numbers let first = number( @@ -546,6 +630,8 @@ impl BlocksCompressor { }) .await?; tokio::time::sleep(pace.adapt(done.elapsed, done.wal_bytes)).await; + self.vacuum_if_due(conn, reporter, &pace, &mut state) + .await?; } // The last blocks might have been deleted while we were working @@ -559,9 +645,294 @@ impl BlocksCompressor { } self.retry(conn, req, reporter, &mut state, &pace).await?; + // Make the space of the last blocks we rewrote available, too + if state.since_vacuum > 0 { + self.vacuum(conn, reporter, &pace, &mut state, false) + .await?; + } Ok(state.progress) } + /// Only the owner can run VACUUM on the table, and VACUUM silently skips + /// tables that the user may not vacuum + async fn check_owner(&self, conn: &mut AsyncPgConnection) -> Result<(), StoreError> { + let owner = text( + conn, + format!( + "select case when r.rolsuper or pg_has_role(current_user, c.relowner, 'USAGE') + then '' else pg_get_userbyid(c.relowner)::text end as res + from pg_class c, pg_roles r + where c.oid = '{}'::regclass and r.rolname = current_user", + self.blocks + ), + ) + .await?; + if owner.is_empty() { + Ok(()) + } else { + Err(anyhow!( + "can not compress {}: only its owner {owner} can run VACUUM on it", + self.blocks + ) + .into()) + } + } + + /// How many bytes of blocks to rewrite between two runs of VACUUM + async fn vacuum_every( + &self, + conn: &mut AsyncPgConnection, + req: &CompressBlocksRequest, + ) -> Result { + if let Some(bytes) = req.vacuum_every { + return Ok(bytes.max(1)); + } + let index = number( + conn, + format!( + "select coalesce(sum(pg_relation_size(i.indexrelid)), 0)::int8 as number + from pg_class c join pg_index i on i.indrelid = c.reltoastrelid + where c.oid = '{}'::regclass", + self.blocks + ), + ) + .await?; + Ok((index.unwrap_or(0) as u64).max(MIN_VACUUM_EVERY)) + } + + async fn vacuum_if_due( + &self, + conn: &mut AsyncPgConnection, + reporter: &mut dyn CompressBlocksReporter, + pace: &Pace, + state: &mut State, + ) -> Result<(), StoreError> { + if state.since_vacuum >= state.vacuum_every { + self.vacuum(conn, reporter, pace, state, false).await?; + } + Ok(()) + } + + /// Run VACUUM on the blocks table so that later writes reuse the space + /// that rewritten blocks took up, and truncate the empty end of its files + /// if `truncate` is set. VACUUM gives way to anybody who needs a lock + async fn vacuum( + &self, + conn: &mut AsyncPgConnection, + reporter: &mut dyn CompressBlocksReporter, + pace: &Pace, + state: &mut State, + truncate: bool, + ) -> Result<(), StoreError> { + loop { + self.wait_for_wraparound_vacuum(conn, reporter).await?; + reporter.reached(CompressBlocksStep::Vacuum).await?; + + let start = Instant::now(); + let wal_start = self.wal_lsn(conn).await?; + let waiters = self.try_vacuum(conn, truncate).await?; + let wal_bytes = self.wal_lsn(conn).await?.saturating_sub(wal_start); + state.progress.wal_bytes += wal_bytes; + if waiters.is_empty() { + state.since_vacuum = 0; + reporter.message(&format!( + "ran VACUUM on {} in {}s", + self.blocks, + start.elapsed().as_secs() + )); + tokio::time::sleep(pace.pause(start.elapsed(), wal_bytes)).await; + return Ok(()); + } + + reporter.paused(&CompressBlocksPause::VacuumGaveWay { + table: self.blocks.clone(), + waiters, + })?; + while !self.lock_waiters(conn, 0).await?.is_empty() { + tokio::time::sleep(VACUUM_WATCH_INTERVAL).await; + } + tokio::time::sleep(VACUUM_RETRY_INTERVAL).await; + } + } + + /// Run VACUUM on another connection, and cancel it when anybody waited + /// for a lock on the table for longer than `MAX_LOCK_WAIT` since a VACUUM + /// we start does not give way like autovacuum. Return who waited + async fn try_vacuum( + &self, + conn: &mut AsyncPgConnection, + truncate: bool, + ) -> Result, StoreError> { + #[derive(QueryableByName)] + struct Session { + #[diesel(sql_type = Integer)] + pid: i32, + #[diesel(sql_type = Text)] + maintenance_work_mem: String, + #[diesel(sql_type = Text)] + vacuum_cost_delay: String, + #[diesel(sql_type = Text)] + statement_timeout: String, + } + + let mut vacuum_conn = self.pool.get_permitted().await?; + let session: Session = sql_query( + "select pg_backend_pid() as pid, + current_setting('maintenance_work_mem') as maintenance_work_mem, + current_setting('vacuum_cost_delay') as vacuum_cost_delay, + current_setting('statement_timeout') as statement_timeout", + ) + .get_result(&mut vacuum_conn) + .await?; + vacuum_conn + .batch_execute(&format!( + "set maintenance_work_mem = '{VACUUM_MEMORY}'; + set vacuum_cost_delay = {VACUUM_COST_DELAY_MS}; + set statement_timeout = 0" + )) + .await?; + + let vacuum = format!( + "{VACUUM_MARKER} vacuum (index_cleanup on, truncate {}) {}", + if truncate { "on" } else { "off" }, + self.blocks + ); + let mut waiting_since: HashMap = HashMap::new(); + let mut gave_way = Vec::new(); + let res = { + let vacuum = vacuum_conn.batch_execute(&vacuum); + tokio::pin!(vacuum); + loop { + tokio::select! { + res = &mut vacuum => break res, + _ = tokio::time::sleep(VACUUM_WATCH_INTERVAL) => { + if !gave_way.is_empty() { + continue; + } + let waiters = self.lock_waiters(conn, session.pid).await?; + let now = Instant::now(); + waiting_since.retain(|pid, _| waiters.iter().any(|w| w.pid == *pid)); + let mut waited = false; + for waiter in &waiters { + let since = *waiting_since.entry(waiter.pid).or_insert(now); + waited |= now.duration_since(since) >= MAX_LOCK_WAIT; + } + if waited { + self.cancel_vacuum(conn, session.pid).await?; + gave_way = waiters.into_iter().map(|w| w.what).collect(); + } + } + } + } + }; + + // The connection goes back to the pool + let restored = sql_query( + "select set_config('maintenance_work_mem', $1, false), + set_config('vacuum_cost_delay', $2, false), + set_config('statement_timeout', $3, false)", + ) + .bind::(&session.maintenance_work_mem) + .bind::(&session.vacuum_cost_delay) + .bind::(&session.statement_timeout) + .execute(&mut vacuum_conn) + .await; + match res { + Ok(()) => restored.map(|_| Vec::new()).map_err(StoreError::from), + Err(_) if !gave_way.is_empty() => restored.map(|_| gave_way).map_err(StoreError::from), + Err(e) => Err(e.into()), + } + } + + /// The sessions other than `vacuum_pid` that wait for a lock on the + /// blocks table or its TOAST table + async fn lock_waiters( + &self, + conn: &mut AsyncPgConnection, + vacuum_pid: i32, + ) -> Result, StoreError> { + let waiters = sql_query(format!( + "select l.pid, + format('session %s (user %s, application %s) waiting for %s', + l.pid, coalesce(a.usename::text, '?'), + coalesce(a.application_name, '?'), l.mode) as what + from pg_locks l left join pg_stat_activity a on a.pid = l.pid + where l.locktype = 'relation' and not l.granted + and l.database = (select oid from pg_database where datname = current_database()) + and l.relation in (select oid from pg_class where oid = '{blocks}'::regclass + union all + select reltoastrelid from pg_class + where oid = '{blocks}'::regclass) + and l.pid <> $1 and l.pid <> pg_backend_pid() + order by l.pid", + blocks = self.blocks + )) + .bind::(vacuum_pid) + .load::(conn) + .await?; + Ok(waiters) + } + + async fn cancel_vacuum( + &self, + conn: &mut AsyncPgConnection, + pid: i32, + ) -> Result<(), StoreError> { + sql_query(format!( + "select pg_cancel_backend(pid) from pg_stat_activity + where pid = $1 and state = 'active' and query like '{VACUUM_MARKER}%'" + )) + .bind::(pid) + .execute(conn) + .await?; + Ok(()) + } + + /// An anti-wraparound autovacuum does not give way to us, and a VACUUM + /// we start would just wait for it. Without the privileges to see what + /// autovacuum does, assume it prevents wraparound if the table is due + async fn wait_for_wraparound_vacuum( + &self, + conn: &mut AsyncPgConnection, + reporter: &mut dyn CompressBlocksReporter, + ) -> Result<(), StoreError> { + loop { + let pids: Vec = sql_query(format!( + "with rels as (select oid from pg_class where oid = '{blocks}'::regclass + union all + select reltoastrelid from pg_class where oid = '{blocks}'::regclass), + due as (select bool_or(age(c.relfrozenxid) + > current_setting('autovacuum_freeze_max_age')::int8 + or mxid_age(c.relminmxid) + > current_setting('autovacuum_multixact_freeze_max_age')::int8) + as due + from pg_class c where c.oid in (select oid from rels)) + select l.pid::int8 as number + from pg_locks l left join pg_stat_activity a on a.pid = l.pid, due + where l.locktype = 'relation' and l.granted + and l.mode = 'ShareUpdateExclusiveLock' + and l.relation in (select oid from rels) and l.pid <> pg_backend_pid() + and case when a.backend_type is null then coalesce(due.due, false) + else a.backend_type = 'autovacuum worker' + and a.query like '%(to prevent wraparound)%' end", + blocks = self.blocks + )) + .load::(conn) + .await? + .into_iter() + .filter_map(|n| n.number) + .collect(); + if pids.is_empty() { + return Ok(()); + } + reporter.paused(&CompressBlocksPause::Wraparound { + table: self.blocks.clone(), + pids, + })?; + tokio::time::sleep(PAUSE_INTERVAL).await; + } + } + /// Add the column for compressed blocks, and try that several times if /// the table is locked async fn add_zstd_column( @@ -683,6 +1054,9 @@ impl BlocksCompressor { Ok(Some(State { progress, retry: row.retry, + vacuum_every: MIN_VACUUM_EVERY, + since_vacuum: 0, + start_size: 0, })) } @@ -695,6 +1069,55 @@ impl BlocksCompressor { Ok(lsn.unwrap_or(0) as u64) } + /// Wait until nothing keeps us from writing more + async fn wait_until_clear( + &self, + conn: &mut AsyncPgConnection, + reporter: &mut dyn CompressBlocksReporter, + state: &State, + ) -> Result<(), StoreError> { + self.wait_for_replicas(conn, reporter).await?; + self.wait_for_growth(conn, reporter, state).await + } + + async fn total_size(&self, conn: &mut AsyncPgConnection) -> Result { + let size = number( + conn, + format!( + "select pg_total_relation_size('{}')::int8 as number", + self.blocks + ), + ) + .await?; + Ok(size.unwrap_or(0) as u64) + } + + /// The table should grow by no more than what we rewrite between two + /// runs of VACUUM. If it grows by much more, VACUUM is not doing its job + async fn wait_for_growth( + &self, + conn: &mut AsyncPgConnection, + reporter: &mut dyn CompressBlocksReporter, + state: &State, + ) -> Result<(), StoreError> { + let limit = state + .start_size + .saturating_add(state.vacuum_every.saturating_mul(2)); + loop { + let size = self.total_size(conn).await?; + if size <= limit { + return Ok(()); + } + reporter.paused(&CompressBlocksPause::Growth { + table: self.blocks.clone(), + start: state.start_size, + size, + limit, + })?; + tokio::time::sleep(PAUSE_INTERVAL).await; + } + } + async fn wait_for_replicas( &self, conn: &mut AsyncPgConnection, @@ -803,6 +1226,7 @@ impl BlocksCompressor { progress.old_bytes += done.old_bytes; progress.new_bytes += done.new_bytes; progress.wal_bytes += done.wal_bytes; + state.since_vacuum += done.old_bytes; return Ok(done); } } @@ -988,13 +1412,14 @@ impl BlocksCompressor { .await?; let hashes = state.retry.clone(); for hashes in hashes.chunks(MAX_BATCH_SIZE as usize) { - self.wait_for_replicas(conn, reporter).await?; + self.wait_until_clear(conn, reporter, state).await?; let batch = Batch::Hashes(hashes); let done = self .rewrite(conn, req.compression, reporter, &batch, state) .await?; reporter.progress(&state.progress); tokio::time::sleep(pace.pause(done.elapsed, done.wal_bytes)).await; + self.vacuum_if_due(conn, reporter, pace, state).await?; } } @@ -1146,7 +1571,7 @@ mod tests { #[test] fn lock_id_is_number_of_chain() { - assert_eq!(17, BlocksCompressor::new("chain17").lock_id().unwrap()); - BlocksCompressor::new("public").lock_id().unwrap_err(); + assert_eq!(17, lock_id("chain17").unwrap()); + lock_id("public").unwrap_err(); } } diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index 15b1c36ba55..0cacb875cea 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -11,6 +11,7 @@ use graph::futures03::future::{BoxFuture, FutureExt as _}; use graph::prelude::alloy::primitives::{Address, B256}; use std::future::Future; use std::sync::Arc; +use std::time::{Duration, Instant}; use graph::cheap_clone::CheapClone; use graph::prelude::alloy; @@ -764,6 +765,7 @@ fn compress_request(compression: BlockCompression) -> CompressBlocksRequest { CompressBlocksRequest { compression, max_wal_rate: 1_000_000_000_000, + vacuum_every: None, } } @@ -1663,6 +1665,90 @@ fn resume_compressing_blocks() { }) } +#[test] +fn vacuum_gives_way_to_others() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + use diesel_async::SimpleAsyncConnection as _; + + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + + // Our VACUUM has to wait for a lock, and then somebody else asks for + // a lock that conflicts with it + let mut holder = store.get_conn_for_test().await.unwrap(); + holder + .batch_execute(&format!( + "begin; lock table {nsp}.blocks in share update exclusive mode" + )) + .await + .unwrap(); + let asked: Arc>> = Default::default(); + let task: Arc>>> = Default::default(); + let mut reporter = TestReporter::with_hook({ + let (store, nsp, asked, task) = ( + store.cheap_clone(), + nsp.clone(), + asked.clone(), + task.clone(), + ); + move |step| { + let mut task = task.lock().unwrap(); + if step == CompressBlocksStep::Vacuum && task.is_none() { + let (store, nsp, asked) = (store.cheap_clone(), nsp.clone(), asked.clone()); + *task = Some(tokio::spawn(async move { + let mut conn = store.get_conn_for_test().await.unwrap(); + tokio::time::sleep(Duration::from_millis(200)).await; + *asked.lock().unwrap() = Some(Instant::now()); + conn.batch_execute(&format!( + "begin; + set local application_name = 'compress-test-waiter'; + lock table {nsp}.blocks in access exclusive mode; + rollback" + )) + .await + .unwrap(); + })); + } + async { Ok(()) }.boxed() + } + }); + let req = CompressBlocksRequest { + vacuum_every: Some(1), + ..compress_request(BlockCompression::Zstd(1)) + }; + let res = tokio::time::timeout( + Duration::from_secs(15), + store.compress_blocks(&req, &mut reporter), + ) + .await; + let stopped = Instant::now(); + holder.batch_execute("rollback").await.unwrap(); + let waiter = task.lock().unwrap().take(); + waiter.expect("VACUUM started").await.unwrap(); + + let err = res + .expect("VACUUM did not give way within 15s") + .unwrap_err() + .to_string(); + assert!(err.contains("compress-test-waiter"), "{err}"); + let asked = asked.lock().unwrap().expect("the waiter asked for a lock"); + let waited = stopped.duration_since(asked); + assert!(waited < Duration::from_secs(5), "waited for {waited:?}"); + let running = names( + &store, + "select pid::text as name from pg_stat_activity + where state = 'active' and query like '/* graph-node compress-blocks */%'" + .to_string(), + ) + .await; + assert_eq!(Vec::::new(), running); + reset_compress_blocks(&store, &nsp).await; + }) +} + #[test] fn receipts_of_compressed_block() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; From 4e04d5e2af100f0f6ff032cdde9591247b211ffa Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Thu, 3 Dec 2026 22:08:23 +0100 Subject: [PATCH 03/24] docs(graphman): describe compressing cached blocks in place The block_compression setting only affects new blocks. Explain how compress-blocks run and status rewrite the cached ones, what they need, what they cost in WAL, time and disk, and how to undo them. --- docs/graphman.md | 80 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/docs/graphman.md b/docs/graphman.md index 8c857703dda..6ad679fcffc 100644 --- a/docs/graphman.md +++ b/docs/graphman.md @@ -7,6 +7,7 @@ - [Unused Remove](#unused-remove) - [Drop](#drop) - [Chain Check Blocks](#check-blocks) +- [Chain Compress Blocks](#chain-compress-blocks) - [Chain Call Cache Remove](#chain-call-cache-remove) @@ -364,6 +365,85 @@ Inspect all blocks after block `13000000`: graphman --config config.toml chain check-blocks mainnet by-range --from 13000000 + +# ⌘ Chain Compress Blocks + +### SYNOPSIS + + Compress blocks that are already in the block cache + + USAGE: + graphman --config chain compress-blocks + + ARGS: + Chain name (must be an existing chain, see 'chain list') + + SUBCOMMANDS: + run Rewrite the blocks with the given compression, or continue a run that did not finish + status Show how far the last run got + +### DESCRIPTION + +The `block_compression` setting (see [config.md](config.md)) only affects blocks that are written after it has +been set. The `compress-blocks` command compresses the blocks that are already in the block cache. It can be run +while the chain is in use. Set `block_compression` first so that new blocks are compressed, too. + +Before running it, make sure that every node that uses the chain runs a version of `graph-node` that can read +compressed blocks, and that the database user `graphman` connects as owns the chain's `blocks` table, since only +the owner can run `VACUUM` on it. The command adds the column `data_zstd` to the `blocks` table if it is +missing, which locks the table for a moment. Do not drop that column by hand while a node is running, since the +node might use it. + +`run` rewrites each block where it is stored, a batch at a time and in order of block number, and records how far +it got. It can be stopped at any point; running it again continues where it left off, unless it is run with a +different compression, which starts again from the first block. Every compressed block is checked to uncompress to +the original before it is written. A block that a node changes or locks while the command works on it keeps what +the node wrote, and is tried again at the end; blocks that are still locked or changed after a few attempts are +left as they are, and running the command again rewrites them. `status` shows how far the last run got. + +Rewriting blocks frees the space that the old blocks took up inside the table, and the command runs `VACUUM` every +so often so that later writes reuse that space. The table therefore grows by at most about twice the amount of +blocks rewritten between two runs of `VACUUM`; if it grows by more, the command pauses and says so. The files of +the table do not get smaller, but the space inside them is reused for new blocks. + +To limit the load on the database, the command limits how much WAL the server writes per second while it works, +and pauses while replicas fall behind. That limit counts all WAL the server writes, not only the command's own. +The `VACUUM` it runs stops when another session waits more than a second for a lock on the table, and tries +again once nobody waits. Writing a batch never waits for a block that a node has locked. + +### COSTS + +- Rewriting blocks writes much more WAL than the compressed blocks take up: about 1.6 times the old size of the + rewritten blocks in a test with 20 GB of blocks. Replicas, WAL archives and backups that keep WAL get all of it. +- At the default `--max-rate` of 20 MB/s that means about 22 hours per TB of blocks, again measured on test + data: the time is roughly the old size of the blocks times 1.6, divided by `--max-rate`. +- The disk needs room for the table to grow by up to twice `--vacuum-every`, and `pg_wal` room for the WAL + written until the next checkpoint and for any WAL that replication slots or archiving hold back. +- Filesystem snapshots and incremental backups keep the old blocks, so the space on their disks is only freed + once they expire. + +### UNDO + +Set `block_compression = "none"` on every node so that new blocks are stored uncompressed, then run +`run --compression none`, which writes compressed blocks back uncompressed. That needs room for the uncompressed +blocks again. + +### OPTIONS + +`run` has these options: + +- `--compression`: how to store the blocks, see `block_compression`; `none` uncompresses compressed blocks. + The default is `zstd:1` +- `--max-rate`: how many MB of WAL the server may write per second at most. The default is 20 +- `--vacuum-every`: run `VACUUM` after rewriting this many GB of blocks. The default is the size of the index of + the TOAST table of the `blocks` table, but at least 1 GiB, since each `VACUUM` reads all of that index + +### EXAMPLES + +Compress all blocks for mainnet: + + graphman --config config.toml chain compress-blocks mainnet run + # ⌘ Chain Call Cache Remove From 121a36f66dd431440ba1ff3d35fa45bf5dd3e8f1 Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Thu, 3 Dec 2026 22:18:19 +0100 Subject: [PATCH 04/24] refactor(store): add the column for compressed blocks the way nodes do Compressing cached blocks had its own copy of the code that adds the column for compressed blocks. Use the chain store's instead, so both share one lock timeout, backoff and column state. --- store/postgres/src/chain_store.rs | 36 ++++++++-- store/postgres/src/compress_blocks.rs | 70 +++++++++++-------- store/test-store/tests/postgres/chain_head.rs | 28 ++++++++ 3 files changed, 101 insertions(+), 33 deletions(-) diff --git a/store/postgres/src/chain_store.rs b/store/postgres/src/chain_store.rs index 16cd1e89e8a..30b3bb36d53 100644 --- a/store/postgres/src/chain_store.rs +++ b/store/postgres/src/chain_store.rs @@ -127,6 +127,7 @@ mod public { } pub use data::Storage; +pub(crate) use data::ZSTD_COLUMN; /// Encapuslate access to the blocks table for a chain. mod data { @@ -307,6 +308,9 @@ mod data { state: Arc>, } + /// The name of the column for compressed blocks + pub(crate) const ZSTD_COLUMN: &str = ZstdColumn::NAME; + impl ZstdColumn { const NAME: &'static str = "data_zstd"; @@ -1099,10 +1103,33 @@ mod data { } } + /// The name of the blocks table including its schema, unless the + /// chain's blocks are in shared tables + pub(crate) fn blocks_qname(&self) -> Option<&str> { + match self { + Storage::Shared => None, + Storage::Private(Schema { blocks, .. }) => Some(&blocks.qname), + } + } + + /// Ask the database whether the blocks table has the column for + /// compressed blocks + pub(crate) async fn has_zstd_column( + &self, + conn: &mut AsyncPgConnection, + ) -> Result { + match self { + Storage::Shared => Ok(false), + Storage::Private(Schema { blocks, .. }) => { + blocks.zstd_column.check(conn, &blocks.namespace).await + } + } + } + /// Make it possible to store compressed blocks by adding the column for /// them. Return `false` if that does not work right now and blocks need /// to be stored uncompressed - pub(super) async fn prepare_compression( + pub(crate) async fn prepare_compression( &self, logger: &Logger, conn: &mut AsyncPgConnection, @@ -3249,10 +3276,9 @@ impl ChainStore { ))); } let conn = self.pool.get_permitted().await?; - Ok(( - BlocksCompressor::new(&self.storage.to_string(), self.pool.clone()), - conn, - )) + let compressor = + BlocksCompressor::new(self.storage.clone(), self.logger.clone(), self.pool.clone())?; + Ok((compressor, conn)) } /// Rewrite the blocks that are already stored so that they are stored diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index c00848897f8..93577ef8744 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -11,9 +11,10 @@ use async_trait::async_trait; use diesel::sql_query; use diesel::sql_types::{Array, BigInt, Bool, Bytea, Integer, Jsonb, Nullable, Text}; use diesel_async::{AsyncConnection as _, RunQueryDsl as _, SimpleAsyncConnection as _}; -use graph::prelude::{Error, StoreError, serde_json as json}; +use graph::prelude::{Error, Logger, StoreError, serde_json as json}; use crate::block_compression::{BlockCompression, decompress, is_placeholder}; +use crate::chain_store::{Storage, ZSTD_COLUMN as ZSTD}; use crate::vid_batcher::AdaptiveBatchSize; use crate::{AsyncPgConnection, ConnectionPool, advisory_lock, catalog, copy}; @@ -115,6 +116,8 @@ pub enum CompressBlocksPause { VacuumGaveWay { table: String, waiters: Vec }, /// A VACUUM that prevents transaction ID wraparound runs on the table Wraparound { table: String, pids: Vec }, + /// We could not add the column for compressed blocks yet + NoColumn { table: String }, /// The table grew by more than we allow, which happens when VACUUM can /// not clean up after us Growth { @@ -148,6 +151,10 @@ impl fmt::Display for CompressBlocksPause { trying again once nobody waits", waiters.join(", ") ), + CompressBlocksPause::NoColumn { table } => write!( + f, + "could not add the column {ZSTD} to {table} yet; trying again later" + ), CompressBlocksPause::Growth { table, start, @@ -481,13 +488,16 @@ struct State { start_size: u64, } -/// Compress the blocks in the table `{nsp}.blocks` +/// Compress the blocks of a chain that has its own schema pub(crate) struct BlocksCompressor { nsp: String, /// The table with the blocks blocks: String, /// How far we got progress: String, + /// What the chain store knows about the blocks table + storage: Storage, + logger: Logger, /// Where VACUUM gets its connection pool: ConnectionPool, } @@ -500,13 +510,24 @@ fn lock_id(nsp: &str) -> Result { } impl BlocksCompressor { - pub(crate) fn new(nsp: &str, pool: ConnectionPool) -> Self { - BlocksCompressor { - nsp: nsp.to_string(), - blocks: format!("{nsp}.blocks"), + pub(crate) fn new( + storage: Storage, + logger: Logger, + pool: ConnectionPool, + ) -> Result { + let nsp = storage.to_string(); + let blocks = storage + .blocks_qname() + .ok_or_else(|| anyhow!("the blocks in {nsp} are shared with other chains"))? + .to_string(); + Ok(BlocksCompressor { progress: format!("{nsp}.compress_blocks_progress"), + nsp, + blocks, + storage, + logger, pool, - } + }) } fn lock_id(&self) -> Result { @@ -585,7 +606,7 @@ impl BlocksCompressor { req: &CompressBlocksRequest, reporter: &mut dyn CompressBlocksReporter, ) -> Result { - if !catalog::table_has_column(conn, &self.nsp, "blocks", "data_zstd").await? { + if !self.storage.has_zstd_column(conn).await? { if req.compression == BlockCompression::None { reporter.message(&format!("{} has no compressed blocks", self.blocks)); return Ok(CompressBlocksProgress { @@ -935,28 +956,21 @@ impl BlocksCompressor { /// Add the column for compressed blocks, and try that several times if /// the table is locked + /// Add the column for compressed blocks the way nodes do, and wait while + /// that is not possible async fn add_zstd_column( &self, conn: &mut AsyncPgConnection, reporter: &mut dyn CompressBlocksReporter, ) -> Result<(), StoreError> { - let stmt = format!( - "alter table {} add column if not exists data_zstd bytea, \ - alter column data_zstd set storage external", - self.blocks - ); - let mut attempts = 0; - loop { - let failure = conn - .transaction::<_, StoreError, _>(async |conn| try_lock(conn, &stmt).await) - .await?; - let Some(failure) = failure else { - reporter.message(&format!("added the column data_zstd to {}", self.blocks)); - return Ok(()); - }; - attempts += 1; - self.locked(reporter, failure, attempts).await?; + while !self.storage.prepare_compression(&self.logger, conn).await? { + reporter.paused(&CompressBlocksPause::NoColumn { + table: self.blocks.clone(), + })?; + tokio::time::sleep(PAUSE_INTERVAL).await; } + reporter.message(&format!("{} has the column {ZSTD}", self.blocks)); + Ok(()) } /// Tell the reporter that we could not lock the table, and wait or fail if @@ -1146,11 +1160,11 @@ impl BlocksCompressor { // need it to uncompress blocks let data_zstd = match compression { BlockCompression::Zstd(_) => "null::bytea", - BlockCompression::None => "data_zstd", + BlockCompression::None => ZSTD, }; let select = format!( "select hash, number, xmin::text as xmin, data, {data_zstd} as data_zstd, - (pg_column_size(data) + coalesce(pg_column_size(data_zstd), 0))::int8 as size + (pg_column_size(data) + coalesce(pg_column_size({ZSTD}), 0))::int8 as size from {}", self.blocks ); @@ -1325,12 +1339,12 @@ impl BlocksCompressor { } else { sql_query(format!( "update {blocks} b - set data = coalesce(v.data, b.data), data_zstd = v.data_zstd + set data = coalesce(v.data, b.data), {ZSTD} = v.data_zstd from unnest($1, $2, $3, $4) as v(hash, xmin, data, data_zstd) where b.hash = v.hash and b.xmin = v.xmin::xid returning b.hash, (pg_column_size(b.data) - + coalesce(pg_column_size(b.data_zstd), 0))::int8 as size", + + coalesce(pg_column_size(b.{ZSTD}), 0))::int8 as size", blocks = self.blocks )) .bind::, _>(&hashes) diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index 0cacb875cea..4dccdd3bfe2 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -1749,6 +1749,34 @@ fn vacuum_gives_way_to_others() { }) } +#[test] +fn compress_blocks_adds_column() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, diesel_store, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + let store = store_without_column(&store, &diesel_store, &nsp).await; + + // Compressing blocks adds the column the way nodes do + let res = store + .compress_blocks( + &compress_request(BlockCompression::Zstd(1)), + &mut TestReporter::default(), + ) + .await; + let storage = column_storage(&store, &nsp).await; + let compressed = raw_block(&store, &nsp, &BLOCK_ONE).await.is_compressed(); + reset_compress_blocks(&store, &nsp).await; + restore_column(&store, &nsp).await; + + res.unwrap(); + assert_eq!(Some("e".to_string()), storage); + assert!(compressed); + }) +} + #[test] fn receipts_of_compressed_block() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; From 2224d88429b527d8f6bb327641aa27bfba0f5677 Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Thu, 3 Dec 2026 22:22:55 +0100 Subject: [PATCH 05/24] refactor(store): stop compressing blocks rather than queue for a lock Each batch locked the table first and read why a lock failed through a server-side trick, and a run waited for anti-wraparound autovacuum. Give every statement a 2 second lock timeout instead, so the run stops with an error rather than make others queue behind it, and drop the rest. --- docs/graphman.md | 4 +- store/postgres/src/compress_blocks.rs | 323 ++++-------------- store/test-store/tests/postgres/chain_head.rs | 60 ++++ 3 files changed, 133 insertions(+), 254 deletions(-) diff --git a/docs/graphman.md b/docs/graphman.md index 6ad679fcffc..83cf15c3747 100644 --- a/docs/graphman.md +++ b/docs/graphman.md @@ -409,7 +409,9 @@ the table do not get smaller, but the space inside them is reused for new blocks To limit the load on the database, the command limits how much WAL the server writes per second while it works, and pauses while replicas fall behind. That limit counts all WAL the server writes, not only the command's own. The `VACUUM` it runs stops when another session waits more than a second for a lock on the table, and tries -again once nobody waits. Writing a batch never waits for a block that a node has locked. +again once nobody waits. Writing a batch never waits for a block that a node has locked, and the command stops +with an error rather than wait more than 2 seconds for a lock on the table, since everybody who needs a +conflicting lock would have to wait behind it; running it again continues where it stopped. ### COSTS diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index 93577ef8744..70dd7d5ca3b 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -24,12 +24,10 @@ const INITIAL_BATCH_SIZE: i64 = 10; /// How long we want one batch to take const BATCH_DURATION: Duration = Duration::from_secs(1); -/// Queries that need a conflicting lock wait while we wait for a lock, so give -/// up quickly and try again later. This must be longer than the default +/// Queries that need a conflicting lock queue behind us while we wait for a +/// lock, so give up quickly. This must be longer than the default /// `deadlock_timeout` of 1s, or Postgres won't cancel autovacuum for us const LOCK_TIMEOUT: Duration = Duration::from_secs(2); -const LOCK_RETRY_INTERVAL: Duration = Duration::from_secs(5); -const MAX_LOCK_ATTEMPTS: usize = 60; /// How often to try again to rewrite blocks that were locked or changed when /// we first tried, and how long to wait before each new attempt @@ -55,9 +53,6 @@ const MB: u64 = 1_000_000; /// How long to wait before checking whether a reason to pause went away const PAUSE_INTERVAL: Duration = Duration::from_secs(10); -/// The setting in which SQL tells us why it could not take a lock -const LOCK_FAILURE_SETTING: &str = "graph_node.compress_blocks_lock_failure"; - pub struct CompressBlocksRequest { /// How to store the blocks. With `None`, compressed blocks are /// uncompressed @@ -106,16 +101,8 @@ pub enum CompressBlocksStatus { pub enum CompressBlocksPause { /// Replicas lag behind by this much ReplicaLag(Duration), - /// We could not lock the table, and have tried this many times - Locked { - table: String, - why: String, - attempts: usize, - }, /// Our VACUUM gave way to these sessions that waited for a lock VacuumGaveWay { table: String, waiters: Vec }, - /// A VACUUM that prevents transaction ID wraparound runs on the table - Wraparound { table: String, pids: Vec }, /// We could not add the column for compressed blocks yet NoColumn { table: String }, /// The table grew by more than we allow, which happens when VACUUM can @@ -136,15 +123,6 @@ impl fmt::Display for CompressBlocksPause { "replicas are lagging by {}s; waiting for them to catch up", lag.as_secs() ), - CompressBlocksPause::Locked { - table, - why, - attempts, - } => write!( - f, - "could not lock {table} ({why}) after {attempts} attempts; trying again in {}s", - LOCK_RETRY_INTERVAL.as_secs() - ), CompressBlocksPause::VacuumGaveWay { table, waiters } => write!( f, "stopped VACUUM of {table} since others waited for a lock on it: {}; \ @@ -168,11 +146,6 @@ impl fmt::Display for CompressBlocksPause { size / MB, limit / MB ), - CompressBlocksPause::Wraparound { table, pids } => write!( - f, - "a VACUUM that prevents transaction ID wraparound runs on {table} (pid {pids:?}); \ - waiting for it to finish" - ), } } } @@ -212,37 +185,6 @@ pub trait CompressBlocksReporter: Send { } } -/// Why we could not take a lock -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum LockFailure { - Timeout, - Deadlock, -} - -impl LockFailure { - /// Classify an error by its SQLSTATE. The database driver only tells us - /// the error message, which depends on the language of the server, and - /// SQL therefore classifies errors for us - fn from_sqlstate(sqlstate: &str) -> Option { - match sqlstate { - // lock_not_available - "55P03" => Some(LockFailure::Timeout), - // deadlock_detected - "40P01" => Some(LockFailure::Deadlock), - _ => None, - } - } -} - -impl fmt::Display for LockFailure { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - LockFailure::Timeout => write!(f, "it stayed locked for {}s", LOCK_TIMEOUT.as_secs()), - LockFailure::Deadlock => write!(f, "there was a deadlock"), - } - } -} - #[derive(QueryableByName)] struct BlockRow { #[diesel(sql_type = Bytea)] @@ -383,37 +325,6 @@ async fn number(conn: &mut AsyncPgConnection, query: String) -> Result(conn).await?.number) } -/// Run `stmt`, which takes a lock, and give up if that takes longer than -/// `LOCK_TIMEOUT`. Return why we could not take the lock. Must run in a -/// transaction, which keeps the lock and the timeout -async fn try_lock( - conn: &mut AsyncPgConnection, - stmt: &str, -) -> Result, StoreError> { - conn.batch_execute(&format!( - "set local lock_timeout = {timeout}; - do $$ - begin - {stmt}; - exception when lock_not_available or deadlock_detected then - perform set_config('{LOCK_FAILURE_SETTING}', sqlstate, true); - end $$", - timeout = LOCK_TIMEOUT.as_millis() - )) - .await?; - let sqlstate = text( - conn, - format!("select coalesce(current_setting('{LOCK_FAILURE_SETTING}', true), '') as res"), - ) - .await?; - if sqlstate.is_empty() { - return Ok(None); - } - LockFailure::from_sqlstate(&sqlstate) - .map(Some) - .ok_or_else(|| anyhow!("unexpected SQLSTATE {sqlstate} while taking a lock").into()) -} - /// How much to do at once, and how long to pause after that struct Pace { batch_size: AdaptiveBatchSize, @@ -456,13 +367,6 @@ enum Batch<'a> { Hashes(&'a [Vec]), } -/// What happened when we tried to write a batch -enum Written { - /// We could not lock the table, and wrote nothing - Locked(LockFailure), - Done(Done), -} - /// What we wrote for a batch #[derive(Default)] struct Done { @@ -542,28 +446,45 @@ impl BlocksCompressor { .await } - /// Make sure that nobody else compresses these blocks + /// Make sure that nobody else compresses these blocks, and that none of + /// our statements waits long for a lock on the table, since queries that + /// need a conflicting lock would queue behind it async fn lock(&self, conn: &mut AsyncPgConnection) -> Result<(), StoreError> { - if advisory_lock::try_lock_compressing(conn, self.lock_id()?).await? { - Ok(()) - } else { - Err(anyhow!("another process is compressing {}", self.blocks).into()) + if !advisory_lock::try_lock_compressing(conn, self.lock_id()?).await? { + return Err(anyhow!("another process is compressing {}", self.blocks).into()); + } + let timeout = format!("set lock_timeout = {}", LOCK_TIMEOUT.as_millis()); + match conn.batch_execute(&timeout).await { + Ok(()) => Ok(()), + Err(e) => self.unlock(conn, Err(e.into())).await, } } - /// Release the lock from `lock` and return `res` + /// Undo `lock` and return `res` async fn unlock( &self, conn: &mut AsyncPgConnection, res: Result, ) -> Result { + let reset = conn + .batch_execute("reset lock_timeout") + .await + .map_err(StoreError::from); let unlocked = advisory_lock::unlock_compressing(conn, self.lock_id()?).await; - match (res, unlocked) { - (Ok(res), Ok(())) => Ok(res), - (Ok(_), Err(e)) | (Err(e), Ok(())) => Err(e), - (Err(e), Err(unlock)) => { - Err(anyhow!("{e:#}; releasing the lock failed, too: {unlock:#}").into()) - } + let mut failures = Vec::new(); + for (what, e) in [ + ("resetting the lock timeout", reset), + ("releasing the lock", unlocked), + ] + .into_iter() + .filter_map(|(what, r)| r.err().map(|e| (what, e))) + { + failures.push(format!("{what} failed: {e:#}")); + } + match (res, failures.is_empty()) { + (res, true) => res, + (Ok(_), false) => Err(anyhow!("{}", failures.join("; ")).into()), + (Err(e), false) => Err(anyhow!("{e:#}; {}", failures.join("; ")).into()), } } @@ -746,7 +667,6 @@ impl BlocksCompressor { truncate: bool, ) -> Result<(), StoreError> { loop { - self.wait_for_wraparound_vacuum(conn, reporter).await?; reporter.reached(CompressBlocksStep::Vacuum).await?; let start = Instant::now(); @@ -909,53 +829,6 @@ impl BlocksCompressor { Ok(()) } - /// An anti-wraparound autovacuum does not give way to us, and a VACUUM - /// we start would just wait for it. Without the privileges to see what - /// autovacuum does, assume it prevents wraparound if the table is due - async fn wait_for_wraparound_vacuum( - &self, - conn: &mut AsyncPgConnection, - reporter: &mut dyn CompressBlocksReporter, - ) -> Result<(), StoreError> { - loop { - let pids: Vec = sql_query(format!( - "with rels as (select oid from pg_class where oid = '{blocks}'::regclass - union all - select reltoastrelid from pg_class where oid = '{blocks}'::regclass), - due as (select bool_or(age(c.relfrozenxid) - > current_setting('autovacuum_freeze_max_age')::int8 - or mxid_age(c.relminmxid) - > current_setting('autovacuum_multixact_freeze_max_age')::int8) - as due - from pg_class c where c.oid in (select oid from rels)) - select l.pid::int8 as number - from pg_locks l left join pg_stat_activity a on a.pid = l.pid, due - where l.locktype = 'relation' and l.granted - and l.mode = 'ShareUpdateExclusiveLock' - and l.relation in (select oid from rels) and l.pid <> pg_backend_pid() - and case when a.backend_type is null then coalesce(due.due, false) - else a.backend_type = 'autovacuum worker' - and a.query like '%(to prevent wraparound)%' end", - blocks = self.blocks - )) - .load::(conn) - .await? - .into_iter() - .filter_map(|n| n.number) - .collect(); - if pids.is_empty() { - return Ok(()); - } - reporter.paused(&CompressBlocksPause::Wraparound { - table: self.blocks.clone(), - pids, - })?; - tokio::time::sleep(PAUSE_INTERVAL).await; - } - } - - /// Add the column for compressed blocks, and try that several times if - /// the table is locked /// Add the column for compressed blocks the way nodes do, and wait while /// that is not possible async fn add_zstd_column( @@ -973,30 +846,6 @@ impl BlocksCompressor { Ok(()) } - /// Tell the reporter that we could not lock the table, and wait or fail if - /// we tried too often - async fn locked( - &self, - reporter: &mut dyn CompressBlocksReporter, - failure: LockFailure, - attempts: usize, - ) -> Result<(), StoreError> { - if attempts >= MAX_LOCK_ATTEMPTS { - return Err(anyhow!( - "could not lock {} ({failure}); giving up after {attempts} attempts", - self.blocks - ) - .into()); - } - reporter.paused(&CompressBlocksPause::Locked { - table: self.blocks.clone(), - why: failure.to_string(), - attempts, - })?; - tokio::time::sleep(LOCK_RETRY_INTERVAL).await; - Ok(()) - } - /// Return the progress of the run to continue, or of a new run async fn start( &self, @@ -1187,7 +1036,7 @@ impl BlocksCompressor { } /// Rewrite the blocks in `batch` with `compression` and update the progress - /// of the run. If the table is locked, wait and read the blocks again + /// of the run async fn rewrite( &self, conn: &mut AsyncPgConnection, @@ -1196,55 +1045,44 @@ impl BlocksCompressor { batch: &Batch<'_>, state: &mut State, ) -> Result { - let mut attempts = 0; - loop { - let start = Instant::now(); - let wal_start = self.wal_lsn(conn).await?; - - let rows = self.read(conn, batch, compression).await?; - if let Batch::Numbers { first, last } = batch { - reporter - .reached(CompressBlocksStep::Read { - first: *first, - last: *last, - }) - .await?; - } - // Blocks we try again leave the list of blocks to try again unless - // they need to be tried once more - let tried: HashSet> = match batch { - Batch::Numbers { .. } => rows.iter().map(|row| row.hash.clone()).collect(), - Batch::Hashes(hashes) => hashes.iter().cloned().collect(), - }; - let rewrites = Self::plan(rows, compression, reporter).await?; - let next_block = match batch { - Batch::Numbers { last, .. } => Some(last + 1), - Batch::Hashes(_) => None, - }; + let start = Instant::now(); + let wal_start = self.wal_lsn(conn).await?; - match self - .write(conn, rewrites, next_block, &state.retry, &tried) - .await? - { - Written::Locked(failure) => { - attempts += 1; - self.locked(reporter, failure, attempts).await?; - } - Written::Done(mut done) => { - done.elapsed = start.elapsed(); - done.wal_bytes = self.wal_lsn(conn).await?.saturating_sub(wal_start); - state.retry = std::mem::take(&mut done.retry); - let progress = &mut state.progress; - progress.retry = state.retry.len(); - progress.blocks += done.blocks; - progress.old_bytes += done.old_bytes; - progress.new_bytes += done.new_bytes; - progress.wal_bytes += done.wal_bytes; - state.since_vacuum += done.old_bytes; - return Ok(done); - } - } + let rows = self.read(conn, batch, compression).await?; + if let Batch::Numbers { first, last } = batch { + reporter + .reached(CompressBlocksStep::Read { + first: *first, + last: *last, + }) + .await?; } + // Blocks we try again leave the list of blocks to try again unless + // they need to be tried once more + let tried: HashSet> = match batch { + Batch::Numbers { .. } => rows.iter().map(|row| row.hash.clone()).collect(), + Batch::Hashes(hashes) => hashes.iter().cloned().collect(), + }; + let rewrites = Self::plan(rows, compression, reporter).await?; + let next_block = match batch { + Batch::Numbers { last, .. } => Some(last + 1), + Batch::Hashes(_) => None, + }; + + let mut done = self + .write(conn, rewrites, next_block, &state.retry, &tried) + .await?; + done.elapsed = start.elapsed(); + done.wal_bytes = self.wal_lsn(conn).await?.saturating_sub(wal_start); + state.retry = std::mem::take(&mut done.retry); + let progress = &mut state.progress; + progress.retry = state.retry.len(); + progress.blocks += done.blocks; + progress.old_bytes += done.old_bytes; + progress.new_bytes += done.new_bytes; + progress.wal_bytes += done.wal_bytes; + state.since_vacuum += done.old_bytes; + Ok(done) } /// Work out how to rewrite `rows`. Compressing blocks can take a while, @@ -1285,7 +1123,7 @@ impl BlocksCompressor { next_block: Option, retry: &[Vec], tried: &HashSet>, - ) -> Result { + ) -> Result { #[derive(QueryableByName)] struct Updated { #[diesel(sql_type = Bytea)] @@ -1295,11 +1133,6 @@ impl BlocksCompressor { } conn.transaction::<_, StoreError, _>(async |conn| { - let lock = format!("lock table {} in row exclusive mode", self.blocks); - if let Some(failure) = try_lock(conn, &lock).await? { - return Ok(Written::Locked(failure)); - } - let hashes: Vec<&[u8]> = rewrites.iter().map(|r| r.hash.as_slice()).collect(); let locked: HashSet> = if hashes.is_empty() { HashSet::new() @@ -1392,7 +1225,7 @@ impl BlocksCompressor { .bind::, _>(&done.retry) .execute(conn) .await?; - Ok(Written::Done(done)) + Ok(done) }) .await } @@ -1538,22 +1371,6 @@ mod tests { .unwrap_err(); } - #[test] - fn classify_lock_failures_by_sqlstate() { - assert_eq!( - Some(LockFailure::Timeout), - LockFailure::from_sqlstate("55P03") - ); - assert_eq!( - Some(LockFailure::Deadlock), - LockFailure::from_sqlstate("40P01") - ); - // query_canceled, serialization_failure, and nothing at all - for sqlstate in ["57014", "40001", ""] { - assert_eq!(None, LockFailure::from_sqlstate(sqlstate), "{sqlstate}"); - } - } - #[test] fn pace_by_wal() { const MB: u64 = 1_000_000; diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index 4dccdd3bfe2..415c8613271 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -1777,6 +1777,66 @@ fn compress_blocks_adds_column() { }) } +#[test] +fn give_up_rather_than_queue_for_the_table() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + use diesel_async::SimpleAsyncConnection as _; + + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + + // One session reads the table, and another waits for an exclusive + // lock on it; whatever touches the table next has to queue behind + // that and holds up everybody after it + let mut holder = store.get_conn_for_test().await.unwrap(); + holder + .batch_execute(&format!("begin; select count(*) from {nsp}.blocks")) + .await + .unwrap(); + let waiter = tokio::spawn({ + let (store, nsp) = (store.cheap_clone(), nsp.clone()); + async move { + let mut conn = store.get_conn_for_test().await.unwrap(); + conn.batch_execute(&format!( + "begin; lock table {nsp}.blocks in access exclusive mode; rollback" + )) + .await + } + }); + let waiting = format!( + "select pid::text as name from pg_locks + where relation = '{nsp}.blocks'::regclass and not granted" + ); + while names(&store, waiting.clone()).await.is_empty() { + tokio::time::sleep(Duration::from_millis(50)).await; + } + + let start = Instant::now(); + let res = tokio::time::timeout( + Duration::from_secs(15), + store.compress_blocks( + &compress_request(BlockCompression::Zstd(1)), + &mut TestReporter::default(), + ), + ) + .await; + let waited = start.elapsed(); + holder.batch_execute("rollback").await.unwrap(); + waiter.await.unwrap().unwrap(); + + let err = res + .expect("the run queued behind the exclusive lock") + .unwrap_err() + .to_string(); + assert!(err.contains("lock timeout"), "{err}"); + assert!(waited < Duration::from_secs(5), "gave up after {waited:?}"); + reset_compress_blocks(&store, &nsp).await; + }) +} + #[test] fn receipts_of_compressed_block() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; From fa4548c37b9622494411aa93db2362543c6beb88 Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Thu, 3 Dec 2026 22:25:43 +0100 Subject: [PATCH 06/24] fix(store): fail a compress run that left blocks as they were A run that could not convert some blocks, or gave up on blocks that stayed locked, still ended as if it succeeded. Count both in its progress, show them in status, and end with an error that says how many blocks were left and why. --- docs/graphman.md | 6 +- node/src/manager/commands/compress_blocks.rs | 30 +++++---- store/postgres/src/compress_blocks.rs | 67 ++++++++++++++++--- store/test-store/tests/postgres/chain_head.rs | 15 +++-- 4 files changed, 90 insertions(+), 28 deletions(-) diff --git a/docs/graphman.md b/docs/graphman.md index 83cf15c3747..9c36d7864e5 100644 --- a/docs/graphman.md +++ b/docs/graphman.md @@ -398,8 +398,10 @@ node might use it. it got. It can be stopped at any point; running it again continues where it left off, unless it is run with a different compression, which starts again from the first block. Every compressed block is checked to uncompress to the original before it is written. A block that a node changes or locks while the command works on it keeps what -the node wrote, and is tried again at the end; blocks that are still locked or changed after a few attempts are -left as they are, and running the command again rewrites them. `status` shows how far the last run got. +the node wrote, and is tried again at the end. Blocks that are still locked or changed after a few attempts, and +blocks that can not be converted, for example because their compressed data is damaged, are left as they are; +the command then ends with an error that says how many there are, and running it again tries them again. +`status` shows how far the last run got, and how many blocks it left as they were. Rewriting blocks frees the space that the old blocks took up inside the table, and the command runs `VACUUM` every so often so that later writes reuse that space. The table therefore grows by at most about twice the amount of diff --git a/node/src/manager/commands/compress_blocks.rs b/node/src/manager/commands/compress_blocks.rs index 6a0337c7472..84ee3e7eb78 100644 --- a/node/src/manager/commands/compress_blocks.rs +++ b/node/src/manager/commands/compress_blocks.rs @@ -87,13 +87,6 @@ pub async fn run( "stored the blocks for {} with {}", chain_store.chain, progress.compression ); - if progress.skipped > 0 { - println!( - "{} blocks were left as they were since they were locked or changed each time; \ - run this again to rewrite them", - progress.skipped - ); - } Ok(()) } @@ -111,19 +104,30 @@ pub async fn status(chain_store: Arc) -> Result<(), Error> { progress.retry ); } + left_as_they_were(&progress); } CompressBlocksStatus::Finished(progress) => { println!( "finished; all blocks up to {} are stored with {}", progress.last_block, progress.compression ); - if progress.skipped > 0 { - println!( - "{} blocks were left as they were since they were locked or changed each time", - progress.skipped - ); - } + left_as_they_were(&progress); } } Ok(()) } + +fn left_as_they_were(progress: &CompressBlocksProgress) { + if progress.failed > 0 { + println!( + "{} blocks were left as they were since they could not be converted", + progress.failed + ); + } + if progress.skipped > 0 { + println!( + "{} blocks were left as they were since they were locked or changed each time", + progress.skipped + ); + } +} diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index 70dd7d5ca3b..4d3ad8c0b49 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -79,6 +79,9 @@ pub struct CompressBlocksProgress { /// How many blocks were left as they were because they were locked or /// changed every time we tried to rewrite them pub skipped: usize, + /// How many blocks were left as they were because they could not be + /// converted, for example since their compressed data was damaged + pub failed: usize, /// How many blocks this process rewrote pub blocks: usize, /// How much space these blocks took up before and after @@ -278,6 +281,8 @@ struct ProgressRow { retry: Vec>, #[diesel(sql_type = BigInt)] skipped: i64, + #[diesel(sql_type = BigInt)] + failed: i64, } #[derive(QueryableByName)] @@ -375,6 +380,8 @@ struct Done { new_bytes: u64, /// The blocks that still need to be tried again retry: Vec>, + /// How many blocks we could not convert + failed: usize, /// How long the batch took, and how much WAL the database wrote elapsed: Duration, wal_bytes: u64, @@ -592,7 +599,40 @@ impl BlocksCompressor { self.vacuum(conn, reporter, &pace, &mut state, false) .await?; } - Ok(state.progress) + Self::left_as_they_were(state.progress) + } + + /// Fail if blocks were left as they were, since they are not stored the + /// way we were asked to + fn left_as_they_were( + progress: CompressBlocksProgress, + ) -> Result { + let CompressBlocksProgress { + failed, skipped, .. + } = progress; + if failed + skipped == 0 { + return Ok(progress); + } + let mut why = Vec::new(); + if failed > 0 { + why.push(format!( + "{failed} could not be converted, as the messages above say" + )); + } + if skipped > 0 { + why.push(format!( + "{skipped} were locked or changed each time we tried" + )); + } + let count = match failed + skipped { + 1 => "1 block as it was".to_string(), + n => format!("{n} blocks as they were"), + }; + Err(anyhow!( + "left {count}: {}; running the command again tries them again", + why.join(" and ") + ) + .into()) } /// Only the owner can run VACUUM on the table, and VACUUM silently skips @@ -859,7 +899,8 @@ impl BlocksCompressor { last_block int8 not null, compression text not null, retry bytea[] not null default '{{}}', - skipped int8 not null default 0 + skipped int8 not null default 0, + failed int8 not null default 0 )", self.progress )) @@ -896,7 +937,7 @@ impl BlocksCompressor { async fn load(&self, conn: &mut AsyncPgConnection) -> Result, StoreError> { let row = sql_query(format!( - "select next_block, last_block, compression, retry, skipped from {}", + "select next_block, last_block, compression, retry, skipped, failed from {}", self.progress )) .load::(conn) @@ -912,6 +953,7 @@ impl BlocksCompressor { last_block: row.last_block, retry: row.retry.len(), skipped: row.skipped as usize, + failed: row.failed as usize, ..Default::default() }; Ok(Some(State { @@ -1063,14 +1105,14 @@ impl BlocksCompressor { Batch::Numbers { .. } => rows.iter().map(|row| row.hash.clone()).collect(), Batch::Hashes(hashes) => hashes.iter().cloned().collect(), }; - let rewrites = Self::plan(rows, compression, reporter).await?; + let (rewrites, failed) = Self::plan(rows, compression, reporter).await?; let next_block = match batch { Batch::Numbers { last, .. } => Some(last + 1), Batch::Hashes(_) => None, }; let mut done = self - .write(conn, rewrites, next_block, &state.retry, &tried) + .write(conn, rewrites, failed, next_block, &state.retry, &tried) .await?; done.elapsed = start.elapsed(); done.wal_bytes = self.wal_lsn(conn).await?.saturating_sub(wal_start); @@ -1078,6 +1120,7 @@ impl BlocksCompressor { let progress = &mut state.progress; progress.retry = state.retry.len(); progress.blocks += done.blocks; + progress.failed += done.failed; progress.old_bytes += done.old_bytes; progress.new_bytes += done.new_bytes; progress.wal_bytes += done.wal_bytes; @@ -1091,7 +1134,7 @@ impl BlocksCompressor { rows: Vec, compression: BlockCompression, reporter: &mut dyn CompressBlocksReporter, - ) -> Result, StoreError> { + ) -> Result<(Vec, usize), StoreError> { let (rewrites, problems) = graph::spawn_blocking_allow_panic(move || { let mut rewrites = Vec::new(); let mut problems = Vec::new(); @@ -1110,7 +1153,7 @@ impl BlocksCompressor { for problem in &problems { reporter.message(problem); } - Ok(rewrites) + Ok((rewrites, problems.len())) } /// Write `rewrites` in one short transaction without waiting for row locks, @@ -1120,6 +1163,7 @@ impl BlocksCompressor { &self, conn: &mut AsyncPgConnection, rewrites: Vec, + failed: usize, next_block: Option, retry: &[Vec], tried: &HashSet>, @@ -1149,7 +1193,10 @@ impl BlocksCompressor { .collect() }; - let mut done = Done::default(); + let mut done = Done { + failed, + ..Default::default() + }; let mut old_sizes = std::collections::HashMap::new(); let mut hashes = Vec::new(); let mut xmins = Vec::new(); @@ -1218,11 +1265,13 @@ impl BlocksCompressor { .collect(); sql_query(format!( - "update {} set next_block = coalesce($1, next_block), retry = $2", + "update {} set next_block = coalesce($1, next_block), retry = $2, + failed = failed + $3", self.progress )) .bind::, _>(next_block) .bind::, _>(&done.retry) + .bind::(failed as i64) .execute(conn) .await?; Ok(done) diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index 415c8613271..7892054af42 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -1575,13 +1575,20 @@ fn uncompress_blocks() { ) .await; + // The run tells us that it could not uncompress a block let mut reporter = TestReporter::default(); - let progress = store + let err = store .compress_blocks(&compress_request(BlockCompression::None), &mut reporter) .await - .unwrap(); - assert_eq!(BlockCompression::None, progress.compression); - assert_eq!(4, progress.blocks); + .unwrap_err() + .to_string(); + assert!(err.contains("left 1 block as it was"), "{err}"); + let CompressBlocksStatus::Finished(status) = store.compress_blocks_status().await.unwrap() + else { + panic!("uncompressing blocks did not finish"); + }; + assert_eq!(BlockCompression::None, status.compression); + assert_eq!((1, 0), (status.failed, status.skipped)); for (block, data) in restored.into_iter().zip(stored) { let raw = raw_block(&store, &nsp, block).await; assert_eq!((data, None), (raw.data, raw.data_zstd), "{}", block.number); From 8ed618f88872cbf3cce109e0e0984f521ca48272 Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Thu, 3 Dec 2026 22:28:42 +0100 Subject: [PATCH 07/24] feat(store): keep the progress of compressing blocks in a migrated table A run created a table for its progress in the chain's schema when it started. Create one table for all chains in a database migration instead, and say how to apply it when graphman finds it missing, since graphman does not run migrations itself. --- docs/graphman.md | 8 +- .../down.sql | 1 + .../up.sql | 16 ++++ store/postgres/src/compress_blocks.rs | 78 ++++++++++++------- store/test-store/tests/postgres/chain_head.rs | 48 ++++++++++-- 5 files changed, 114 insertions(+), 37 deletions(-) create mode 100644 store/postgres/migrations/2026-12-03-120000_compress_blocks_progress/down.sql create mode 100644 store/postgres/migrations/2026-12-03-120000_compress_blocks_progress/up.sql diff --git a/docs/graphman.md b/docs/graphman.md index 9c36d7864e5..92a8f65288a 100644 --- a/docs/graphman.md +++ b/docs/graphman.md @@ -390,9 +390,11 @@ while the chain is in use. Set `block_compression` first so that new blocks are Before running it, make sure that every node that uses the chain runs a version of `graph-node` that can read compressed blocks, and that the database user `graphman` connects as owns the chain's `blocks` table, since only -the owner can run `VACUUM` on it. The command adds the column `data_zstd` to the `blocks` table if it is -missing, which locks the table for a moment. Do not drop that column by hand while a node is running, since the -node might use it. +the owner can run `VACUUM` on it. The command keeps track of how far it got in a table that the database +migrations of this version of `graph-node` create; `graphman` does not run migrations itself, so start a node of +this version, or run `graphman database migrate`, first. The command adds the column `data_zstd` to the +`blocks` table if it is missing, which locks the table for a moment. Do not drop that column by hand while a +node is running, since the node might use it. `run` rewrites each block where it is stored, a batch at a time and in order of block number, and records how far it got. It can be stopped at any point; running it again continues where it left off, unless it is run with a diff --git a/store/postgres/migrations/2026-12-03-120000_compress_blocks_progress/down.sql b/store/postgres/migrations/2026-12-03-120000_compress_blocks_progress/down.sql new file mode 100644 index 00000000000..61fca142c18 --- /dev/null +++ b/store/postgres/migrations/2026-12-03-120000_compress_blocks_progress/down.sql @@ -0,0 +1 @@ +drop table public.compress_blocks_progress; diff --git a/store/postgres/migrations/2026-12-03-120000_compress_blocks_progress/up.sql b/store/postgres/migrations/2026-12-03-120000_compress_blocks_progress/up.sql new file mode 100644 index 00000000000..3d646122940 --- /dev/null +++ b/store/postgres/migrations/2026-12-03-120000_compress_blocks_progress/up.sql @@ -0,0 +1,16 @@ +-- How far `graphman chain compress-blocks` got for the blocks of a chain +create table public.compress_blocks_progress( + -- the schema that holds the chain's blocks, like chain7 + namespace text primary key, + -- how the blocks are being stored, like 'zstd:1' or 'none' + compression text not null, + -- all blocks with a smaller number have been rewritten + next_block int8 not null, + last_block int8 not null, + -- blocks that were locked or changed and need to be tried again + retry bytea[] not null default '{}', + -- blocks left as they were since they were locked or changed each time + skipped int8 not null default 0, + -- blocks left as they were since they could not be converted + failed int8 not null default 0 +); diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index 4d3ad8c0b49..4c3c464510a 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -50,6 +50,10 @@ const VACUUM_MARKER: &str = "/* graph-node compress-blocks */"; const MB: u64 = 1_000_000; +/// The table that a database migration creates for the progress of each +/// chain's run +const PROGRESS_TABLE: &str = "public.compress_blocks_progress"; + /// How long to wait before checking whether a reason to pause went away const PAUSE_INTERVAL: Duration = Duration::from_secs(10); @@ -432,7 +436,7 @@ impl BlocksCompressor { .ok_or_else(|| anyhow!("the blocks in {nsp} are shared with other chains"))? .to_string(); Ok(BlocksCompressor { - progress: format!("{nsp}.compress_blocks_progress"), + progress: PROGRESS_TABLE.to_string(), nsp, blocks, storage, @@ -499,9 +503,7 @@ impl BlocksCompressor { &self, conn: &mut AsyncPgConnection, ) -> Result { - if !self.exists(conn, &self.progress).await? { - return Ok(CompressBlocksStatus::NotStarted); - } + self.check_progress_table(conn).await?; Ok(match self.load(conn).await? { None => CompressBlocksStatus::NotStarted, Some(state) if Self::is_unfinished(&state) => { @@ -511,6 +513,22 @@ impl BlocksCompressor { }) } + /// graphman does not run database migrations, and the table for the + /// progress is missing until something else does + async fn check_progress_table(&self, conn: &mut AsyncPgConnection) -> Result<(), StoreError> { + if self.exists(conn, &self.progress).await? { + return Ok(()); + } + Err(anyhow!( + "the table {} is missing since the database migrations of this version of \ + graph-node have not run yet; graphman does not run them itself, so run \ + `graphman --config database migrate` or start a graph-node of this \ + version first", + self.progress + ) + .into()) + } + fn is_unfinished(state: &State) -> bool { state.progress.next_block <= state.progress.last_block || !state.retry.is_empty() } @@ -534,6 +552,7 @@ impl BlocksCompressor { req: &CompressBlocksRequest, reporter: &mut dyn CompressBlocksReporter, ) -> Result { + self.check_progress_table(conn).await?; if !self.storage.has_zstd_column(conn).await? { if req.compression == BlockCompression::None { reporter.message(&format!("{} has no compressed blocks", self.blocks)); @@ -586,10 +605,14 @@ impl BlocksCompressor { // The last blocks might have been deleted while we were working if state.progress.next_block <= state.progress.last_block { state.progress.next_block = state.progress.last_block + 1; - sql_query(format!("update {} set next_block = $1", self.progress)) - .bind::(state.progress.next_block) - .execute(conn) - .await?; + sql_query(format!( + "update {} set next_block = $1 where namespace = $2", + self.progress + )) + .bind::(state.progress.next_block) + .bind::(&self.nsp) + .execute(conn) + .await?; reporter.progress(&state.progress); } @@ -893,18 +916,6 @@ impl BlocksCompressor { compression: BlockCompression, reporter: &mut dyn CompressBlocksReporter, ) -> Result { - conn.batch_execute(&format!( - "create table if not exists {} ( - next_block int8 not null, - last_block int8 not null, - compression text not null, - retry bytea[] not null default '{{}}', - skipped int8 not null default 0, - failed int8 not null default 0 - )", - self.progress - )) - .await?; if let Some(state) = self.load(conn).await? && state.progress.compression == compression && Self::is_unfinished(&state) @@ -917,14 +928,20 @@ impl BlocksCompressor { } conn.transaction::<_, StoreError, _>(async |conn| { - conn.batch_execute(&format!("delete from {}", self.progress)) - .await?; sql_query(format!( - "insert into {}(next_block, last_block, compression) - select coalesce(min(number), 0), coalesce(max(number), -1), $1 from {}", + "delete from {} where namespace = $1", + self.progress + )) + .bind::(&self.nsp) + .execute(conn) + .await?; + sql_query(format!( + "insert into {}(namespace, next_block, last_block, compression) + select $2, coalesce(min(number), 0), coalesce(max(number), -1), $1 from {}", self.progress, self.blocks )) .bind::(compression.to_string()) + .bind::(&self.nsp) .execute(conn) .await?; Ok(()) @@ -932,14 +949,16 @@ impl BlocksCompressor { .await?; self.load(conn) .await? - .ok_or_else(|| anyhow!("{} is empty", self.progress).into()) + .ok_or_else(|| anyhow!("{} has no row for {}", self.progress, self.nsp).into()) } async fn load(&self, conn: &mut AsyncPgConnection) -> Result, StoreError> { let row = sql_query(format!( - "select next_block, last_block, compression, retry, skipped, failed from {}", + "select next_block, last_block, compression, retry, skipped, failed + from {} where namespace = $1", self.progress )) + .bind::(&self.nsp) .load::(conn) .await? .into_iter() @@ -1266,12 +1285,14 @@ impl BlocksCompressor { sql_query(format!( "update {} set next_block = coalesce($1, next_block), retry = $2, - failed = failed + $3", + failed = failed + $3 + where namespace = $4", self.progress )) .bind::, _>(next_block) .bind::, _>(&done.retry) .bind::(failed as i64) + .bind::(&self.nsp) .execute(conn) .await?; Ok(done) @@ -1326,10 +1347,11 @@ impl BlocksCompressor { each time we tried to rewrite them; run this again to rewrite them" )); sql_query(format!( - "update {} set retry = '{{}}', skipped = $1", + "update {} set retry = '{{}}', skipped = $1 where namespace = $2", self.progress )) .bind::(skipped as i64) + .bind::(&self.nsp) .execute(conn) .await?; state.retry.clear(); diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index 7892054af42..df948cecae2 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -782,7 +782,7 @@ async fn compress_blocks( async fn reset_compress_blocks(store: &DieselChainStore, namespace: &str) { execute( store, - format!("drop table if exists {namespace}.compress_blocks_progress"), + format!("delete from public.compress_blocks_progress where namespace = '{namespace}'"), ) .await; } @@ -1412,11 +1412,9 @@ fn compress_blocks_in_place() { assert_eq!(None, raw.data_zstd); assert_eq!(read, read_stored_blocks(&store, &chain).await); - // The blocks stay where they are, and only the progress is new - let mut exp = tables_before; - exp.push("compress_blocks_progress".to_string()); - exp.sort(); - assert_eq!(exp, tables(&store, &nsp).await); + // The blocks stay where they are, and nothing is added to the + // chain's schema + assert_eq!(tables_before, tables(&store, &nsp).await); assert_eq!(file, blocks_file(&store, &nsp).await); let CompressBlocksStatus::Finished(status) = store.compress_blocks_status().await.unwrap() @@ -1844,6 +1842,44 @@ fn give_up_rather_than_queue_for_the_table() { }) } +#[test] +fn compress_blocks_needs_migration() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + + // graphman does not run database migrations, so the table for the + // progress can be missing + execute( + &store, + "alter table public.compress_blocks_progress rename to compress_blocks_progress_hidden" + .to_string(), + ) + .await; + let run = store + .compress_blocks( + &compress_request(BlockCompression::Zstd(1)), + &mut TestReporter::default(), + ) + .await; + let status = store.compress_blocks_status().await; + execute( + &store, + "alter table public.compress_blocks_progress_hidden rename to compress_blocks_progress" + .to_string(), + ) + .await; + + for err in [run.unwrap_err(), status.unwrap_err()] { + assert!(err.to_string().contains("database migrate"), "{err}"); + } + assert!(!raw_block(&store, &nsp, &BLOCK_ONE).await.is_compressed()); + }) +} + #[test] fn receipts_of_compressed_block() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; From cbb5809ef38a61d915b814522ef5b2cc4948b897 Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Thu, 3 Dec 2026 22:34:47 +0100 Subject: [PATCH 08/24] fix(store): let the table grow by what uncompressed blocks add The pause for a table that grows too much allowed only twice what is rewritten between VACUUMs, so uncompressing blocks always paused. Also allow the bytes new values add over old ones, read after Postgres stores them, and count a batch that runs past the VACUUM interval. --- docs/graphman.md | 8 ++- store/postgres/src/compress_blocks.rs | 51 +++++++++++--- store/test-store/tests/postgres/chain_head.rs | 70 +++++++++++++++++++ 3 files changed, 118 insertions(+), 11 deletions(-) diff --git a/docs/graphman.md b/docs/graphman.md index 92a8f65288a..43ed2ed40aa 100644 --- a/docs/graphman.md +++ b/docs/graphman.md @@ -407,8 +407,9 @@ the command then ends with an error that says how many there are, and running it Rewriting blocks frees the space that the old blocks took up inside the table, and the command runs `VACUUM` every so often so that later writes reuse that space. The table therefore grows by at most about twice the amount of -blocks rewritten between two runs of `VACUUM`; if it grows by more, the command pauses and says so. The files of -the table do not get smaller, but the space inside them is reused for new blocks. +blocks rewritten between two runs of `VACUUM`, plus whatever the new blocks take up beyond the old ones, which is +nothing when compressing and can be a lot when uncompressing; if it grows by more, the command pauses and says +so. The files of the table do not get smaller, but the space inside them is reused for new blocks. To limit the load on the database, the command limits how much WAL the server writes per second while it works, and pauses while replicas fall behind. That limit counts all WAL the server writes, not only the command's own. @@ -423,7 +424,8 @@ conflicting lock would have to wait behind it; running it again continues where rewritten blocks in a test with 20 GB of blocks. Replicas, WAL archives and backups that keep WAL get all of it. - At the default `--max-rate` of 20 MB/s that means about 22 hours per TB of blocks, again measured on test data: the time is roughly the old size of the blocks times 1.6, divided by `--max-rate`. -- The disk needs room for the table to grow by up to twice `--vacuum-every`, and `pg_wal` room for the WAL +- The disk needs room for the table to grow by up to twice `--vacuum-every` (plus, when uncompressing, the + difference between the uncompressed and compressed size of the blocks), and `pg_wal` room for the WAL written until the next checkpoint and for any WAL that replication slots or archiving hold back. - Filesystem snapshots and incremental backups keep the old blocks, so the space on their disks is only freed once they expire. diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index 4c3c464510a..39480a38c2e 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -399,6 +399,9 @@ struct State { vacuum_every: u64, /// How many bytes of blocks we rewrote since the last VACUUM since_vacuum: u64, + /// The most bytes of blocks we rewrote between two runs of VACUUM, which + /// can be more than `vacuum_every` since we only check after each batch + most_between_vacuums: u64, /// The size of the table when we started start_size: u64, } @@ -738,6 +741,7 @@ impl BlocksCompressor { let wal_bytes = self.wal_lsn(conn).await?.saturating_sub(wal_start); state.progress.wal_bytes += wal_bytes; if waiters.is_empty() { + state.most_between_vacuums = state.most_between_vacuums.max(state.since_vacuum); state.since_vacuum = 0; reporter.message(&format!( "ran VACUUM on {} in {}s", @@ -980,6 +984,7 @@ impl BlocksCompressor { retry: row.retry, vacuum_every: MIN_VACUUM_EVERY, since_vacuum: 0, + most_between_vacuums: 0, start_size: 0, })) } @@ -1016,17 +1021,32 @@ impl BlocksCompressor { Ok(size.unwrap_or(0) as u64) } - /// The table should grow by no more than what we rewrite between two - /// runs of VACUUM. If it grows by much more, VACUUM is not doing its job + /// The table should grow by no more than the bytes our new values add + /// over the old ones, which is nothing when we compress, plus twice what + /// we rewrite between two runs of VACUUM. If it grows by much more, + /// VACUUM is not doing its job + fn growth_limit(state: &State) -> u64 { + let added = state + .progress + .new_bytes + .saturating_sub(state.progress.old_bytes); + let between_vacuums = state + .vacuum_every + .max(state.most_between_vacuums) + .max(state.since_vacuum); + state + .start_size + .saturating_add(added) + .saturating_add(between_vacuums.saturating_mul(2)) + } + async fn wait_for_growth( &self, conn: &mut AsyncPgConnection, reporter: &mut dyn CompressBlocksReporter, state: &State, ) -> Result<(), StoreError> { - let limit = state - .start_size - .saturating_add(state.vacuum_every.saturating_mul(2)); + let limit = Self::growth_limit(state); loop { let size = self.total_size(conn).await?; if size <= limit { @@ -1241,15 +1261,30 @@ impl BlocksCompressor { set data = coalesce(v.data, b.data), {ZSTD} = v.data_zstd from unnest($1, $2, $3, $4) as v(hash, xmin, data, data_zstd) where b.hash = v.hash and b.xmin = v.xmin::xid - returning b.hash, - (pg_column_size(b.data) - + coalesce(pg_column_size(b.{ZSTD}), 0))::int8 as size", + returning b.hash", blocks = self.blocks )) .bind::, _>(&hashes) .bind::, _>(&xmins) .bind::>, _>(&datas) .bind::>, _>(&data_zstds) + .load::(conn) + .await? + }; + // `returning` shows the new values before Postgres compresses + // them or moves them out of line, so read their size afterwards + let updated: Vec> = updated.into_iter().map(|h| h.hash).collect(); + let updated = if updated.is_empty() { + Vec::new() + } else { + sql_query(format!( + "select hash, + (pg_column_size(data) + + coalesce(pg_column_size({ZSTD}), 0))::int8 as size + from {} where hash = any($1)", + self.blocks + )) + .bind::, _>(&updated) .load::(conn) .await? }; diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index df948cecae2..bfc8551c5bb 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -1880,6 +1880,76 @@ fn compress_blocks_needs_migration() { }) } +#[test] +fn undo_grows_the_table_without_pausing() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + add_blocks(&store, &nsp, 100, 200, 16_000).await; + compress_blocks(&store, BlockCompression::Zstd(1)) + .await + .unwrap(); + // Leave no free space in the table, so uncompressing the blocks has + // to grow it by much more than twice what we rewrite between two + // runs of VACUUM + execute(&store, format!("vacuum full {nsp}.blocks")).await; + + let req = CompressBlocksRequest { + vacuum_every: Some(64 * 1024), + ..compress_request(BlockCompression::None) + }; + let res = store + .compress_blocks(&req, &mut TestReporter::default()) + .await; + let raw = raw_block(&store, &nsp, &BLOCK_ONE).await; + reset_compress_blocks(&store, &nsp).await; + + let progress = res.unwrap(); + assert_eq!(203, progress.blocks); + assert!(!raw.is_compressed()); + }) +} + +#[test] +fn pause_when_the_table_grows_too_much() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + use diesel_async::SimpleAsyncConnection as _; + + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + // Enough blocks that what we write is much more than twice a batch + add_blocks(&store, &nsp, 100, 1_000, 16_000).await; + // Free space that earlier tests left in the table would hide growth + execute(&store, format!("vacuum full {nsp}.blocks")).await; + + // An old snapshot keeps VACUUM from removing the blocks we rewrite, + // and the table grows by everything we write + let mut holder = store.get_conn_for_test().await.unwrap(); + holder + .batch_execute("begin isolation level repeatable read; select 1") + .await + .unwrap(); + let req = CompressBlocksRequest { + vacuum_every: Some(64 * 1024), + ..compress_request(BlockCompression::Zstd(1)) + }; + let res = store + .compress_blocks(&req, &mut TestReporter::default()) + .await; + holder.batch_execute("commit").await.unwrap(); + reset_compress_blocks(&store, &nsp).await; + + let err = res.unwrap_err().to_string(); + assert!(err.contains("grew from"), "{err}"); + }) +} + #[test] fn receipts_of_compressed_block() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; From fa2f1446696596ca47f2b60c7afe3e6f4014fc45 Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Thu, 3 Dec 2026 22:58:14 +0100 Subject: [PATCH 09/24] fix(store): never leave a VACUUM running after compressing stops A compress run stopped by Ctrl-C, an error while watching its VACUUM or a dead process left that VACUUM running on the server. Cancel it in each case, have the server check that we are still there, and close a dropped run's connections so that its lock goes with them. --- docs/graphman.md | 5 +- store/postgres/src/chain_store.rs | 4 +- store/postgres/src/compress_blocks.rs | 281 ++++++++++++++---- store/postgres/src/pool/mod.rs | 6 + store/test-store/tests/postgres/chain_head.rs | 204 +++++++++++++ 5 files changed, 434 insertions(+), 66 deletions(-) diff --git a/docs/graphman.md b/docs/graphman.md index 43ed2ed40aa..7583c1ab30e 100644 --- a/docs/graphman.md +++ b/docs/graphman.md @@ -416,7 +416,10 @@ and pauses while replicas fall behind. That limit counts all WAL the server writ The `VACUUM` it runs stops when another session waits more than a second for a lock on the table, and tries again once nobody waits. Writing a batch never waits for a block that a node has locked, and the command stops with an error rather than wait more than 2 seconds for a lock on the table, since everybody who needs a -conflicting lock would have to wait behind it; running it again continues where it stopped. +conflicting lock would have to wait behind it; running it again continues where it stopped. Pressing Ctrl-C +stops the command after it has cancelled its `VACUUM`; each batch saves its progress when it is written, so +nothing more is lost than the batch being written. If the command dies without cancelling it, the server stops +the `VACUUM` within a few seconds on systems where Postgres supports `client_connection_check_interval`. ### COSTS diff --git a/store/postgres/src/chain_store.rs b/store/postgres/src/chain_store.rs index 30b3bb36d53..bca70ffb163 100644 --- a/store/postgres/src/chain_store.rs +++ b/store/postgres/src/chain_store.rs @@ -3288,8 +3288,8 @@ impl ChainStore { req: &CompressBlocksRequest, reporter: &mut dyn CompressBlocksReporter, ) -> Result { - let (compressor, mut conn) = self.blocks_compressor().await?; - compressor.run(&mut conn, req, reporter).await + let (compressor, conn) = self.blocks_compressor().await?; + compressor.run(conn, req, reporter).await } pub async fn compress_blocks_status(&self) -> Result { diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index 39480a38c2e..cdf1a018641 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -4,6 +4,7 @@ use std::collections::{HashMap, HashSet}; use std::fmt; +use std::sync::atomic::{AtomicI32, Ordering}; use std::time::{Duration, Instant}; use anyhow::anyhow; @@ -11,10 +12,11 @@ use async_trait::async_trait; use diesel::sql_query; use diesel::sql_types::{Array, BigInt, Bool, Bytea, Integer, Jsonb, Nullable, Text}; use diesel_async::{AsyncConnection as _, RunQueryDsl as _, SimpleAsyncConnection as _}; -use graph::prelude::{Error, Logger, StoreError, serde_json as json}; +use graph::prelude::{Error, Logger, StoreError, serde_json as json, warn}; use crate::block_compression::{BlockCompression, decompress, is_placeholder}; use crate::chain_store::{Storage, ZSTD_COLUMN as ZSTD}; +use crate::pool::PermittedConnection; use crate::vid_batcher::AdaptiveBatchSize; use crate::{AsyncPgConnection, ConnectionPool, advisory_lock, catalog, copy}; @@ -45,6 +47,10 @@ const VACUUM_RETRY_INTERVAL: Duration = Duration::from_secs(10); /// Settings for our VACUUM. A short cost delay keeps it from hogging I/O const VACUUM_MEMORY: &str = "1GB"; const VACUUM_COST_DELAY_MS: u64 = 2; +/// How often the server checks during our VACUUM whether we are still +/// there, and how long we wait for our VACUUM to stop after cancelling it +const CLIENT_CHECK_INTERVAL: Duration = Duration::from_secs(2); +const CANCEL_WAIT: Duration = Duration::from_secs(10); /// Marks the statement of our VACUUM so that we never cancel anything else const VACUUM_MARKER: &str = "/* graph-node compress-blocks */"; @@ -170,6 +176,9 @@ pub enum CompressBlocksStep { Retry { attempt: usize, blocks: usize }, /// We are about to run VACUUM on the blocks table Vacuum, + /// Our VACUUM is running, and we are about to check whether it needs to + /// give way + VacuumRunning, } #[async_trait] @@ -289,6 +298,12 @@ struct ProgressRow { failed: i64, } +#[derive(QueryableByName)] +struct Running { + #[diesel(sql_type = Bool)] + running: bool, +} + #[derive(QueryableByName)] struct Number { #[diesel(sql_type = Nullable)] @@ -418,6 +433,44 @@ pub(crate) struct BlocksCompressor { logger: Logger, /// Where VACUUM gets its connection pool: ConnectionPool, + /// The process id of our VACUUM while it runs, and 0 otherwise + vacuum_pid: AtomicI32, +} + +/// The connection of a run, which holds the lock that keeps two runs apart. +/// If the run is dropped before it ends, close the connection rather than +/// put it back in the pool, so that the lock does not outlive the run +struct CloseOnDrop(Option); + +impl CloseOnDrop { + fn get(&mut self) -> &mut AsyncPgConnection { + self.0 + .as_mut() + .expect("the connection is there until released") + } + + /// Put the connection back in the pool + fn release(mut self) { + self.0.take(); + } +} + +impl Drop for CloseOnDrop { + fn drop(&mut self) { + if let Some(conn) = self.0.take() { + drop(conn.detach()); + } + } +} + +/// Resolve when the user presses Ctrl-C. Listening for it replaces the +/// default of ending the process, so if listening fails, never resolve +async fn interrupted(logger: &Logger) { + if let Err(e) = tokio::signal::ctrl_c().await { + warn!(logger, "can not listen for Ctrl-C to stop compressing blocks cleanly"; + "error" => e.to_string()); + std::future::pending::<()>().await; + } } /// The number in the name of the namespace, which is unique in a database @@ -445,6 +498,7 @@ impl BlocksCompressor { storage, logger, pool, + vacuum_pid: AtomicI32::new(0), }) } @@ -539,13 +593,37 @@ impl BlocksCompressor { /// Store all blocks with `req.compression`. If an earlier run with the /// same compression did not finish, continue it pub(crate) async fn run( + &self, + conn: PermittedConnection, + req: &CompressBlocksRequest, + reporter: &mut dyn CompressBlocksReporter, + ) -> Result { + let mut conn = CloseOnDrop(Some(conn)); + let res = self.run_on(conn.get(), req, reporter).await; + conn.release(); + res + } + + async fn run_on( &self, conn: &mut AsyncPgConnection, req: &CompressBlocksRequest, reporter: &mut dyn CompressBlocksReporter, ) -> Result { self.lock(conn).await?; - let res = self.run_locked(conn, req, reporter).await; + let res = tokio::select! { + res = self.run_locked(conn, req, reporter) => res, + () = interrupted(&self.logger) => { + // Every batch saves the progress as it is written, so only + // a VACUUM can be left to stop + let msg = "interrupted; the progress of every batch written so far is saved, \ + and running the command again continues from there"; + match self.cancel_dropped_vacuum().await { + Ok(()) => Err(anyhow!(msg).into()), + Err(e) => Err(anyhow!("{msg}; cancelling our VACUUM failed: {e:#}").into()), + } + } + }; self.unlock(conn, res).await } @@ -737,7 +815,7 @@ impl BlocksCompressor { let start = Instant::now(); let wal_start = self.wal_lsn(conn).await?; - let waiters = self.try_vacuum(conn, truncate).await?; + let waiters = self.try_vacuum(conn, reporter, truncate).await?; let wal_bytes = self.wal_lsn(conn).await?.saturating_sub(wal_start); state.progress.wal_bytes += wal_bytes; if waiters.is_empty() { @@ -765,33 +843,22 @@ impl BlocksCompressor { /// Run VACUUM on another connection, and cancel it when anybody waited /// for a lock on the table for longer than `MAX_LOCK_WAIT` since a VACUUM - /// we start does not give way like autovacuum. Return who waited + /// we start does not give way like autovacuum. Return who waited. The + /// connection leaves the pool and is closed afterwards, so that a VACUUM + /// we stop watching never holds up whoever gets the connection next async fn try_vacuum( &self, conn: &mut AsyncPgConnection, + reporter: &mut dyn CompressBlocksReporter, truncate: bool, ) -> Result, StoreError> { - #[derive(QueryableByName)] - struct Session { - #[diesel(sql_type = Integer)] - pid: i32, - #[diesel(sql_type = Text)] - maintenance_work_mem: String, - #[diesel(sql_type = Text)] - vacuum_cost_delay: String, - #[diesel(sql_type = Text)] - statement_timeout: String, - } - - let mut vacuum_conn = self.pool.get_permitted().await?; - let session: Session = sql_query( - "select pg_backend_pid() as pid, - current_setting('maintenance_work_mem') as maintenance_work_mem, - current_setting('vacuum_cost_delay') as vacuum_cost_delay, - current_setting('statement_timeout') as statement_timeout", - ) - .get_result(&mut vacuum_conn) - .await?; + let mut vacuum_conn = self.pool.get_permitted().await?.detach(); + let pid = sql_query("select pg_backend_pid()::int8 as number") + .get_result::(&mut vacuum_conn) + .await? + .number + .ok_or_else(|| anyhow!("could not read the process id of our VACUUM"))? + as i32; vacuum_conn .batch_execute(&format!( "set maintenance_work_mem = '{VACUUM_MEMORY}'; @@ -799,57 +866,96 @@ impl BlocksCompressor { set statement_timeout = 0" )) .await?; + // If we die without cancelling it, the server stops our VACUUM once + // it notices that we are gone. Not every platform can notice + let check = format!( + "set client_connection_check_interval = {}", + CLIENT_CHECK_INTERVAL.as_millis() + ); + if let Err(e) = vacuum_conn.batch_execute(&check).await { + reporter.message(&format!( + "the server can not stop our VACUUM by itself if this process dies, since \ + setting client_connection_check_interval failed: {e}" + )); + } let vacuum = format!( "{VACUUM_MARKER} vacuum (index_cleanup on, truncate {}) {}", if truncate { "on" } else { "off" }, self.blocks ); + /// How watching our VACUUM ended + enum Watched { + Finished(Result<(), diesel::result::Error>), + GiveWay(Vec), + Failed(StoreError), + } + + self.vacuum_pid.store(pid, Ordering::SeqCst); + let vacuum = vacuum_conn.batch_execute(&vacuum); + tokio::pin!(vacuum); let mut waiting_since: HashMap = HashMap::new(); - let mut gave_way = Vec::new(); - let res = { - let vacuum = vacuum_conn.batch_execute(&vacuum); - tokio::pin!(vacuum); - loop { - tokio::select! { - res = &mut vacuum => break res, - _ = tokio::time::sleep(VACUUM_WATCH_INTERVAL) => { - if !gave_way.is_empty() { - continue; - } - let waiters = self.lock_waiters(conn, session.pid).await?; - let now = Instant::now(); - waiting_since.retain(|pid, _| waiters.iter().any(|w| w.pid == *pid)); - let mut waited = false; - for waiter in &waiters { - let since = *waiting_since.entry(waiter.pid).or_insert(now); - waited |= now.duration_since(since) >= MAX_LOCK_WAIT; - } - if waited { - self.cancel_vacuum(conn, session.pid).await?; - gave_way = waiters.into_iter().map(|w| w.what).collect(); - } + let watched = loop { + tokio::select! { + res = &mut vacuum => break Watched::Finished(res), + _ = tokio::time::sleep(VACUUM_WATCH_INTERVAL) => { + match self.watch_vacuum(conn, reporter, pid, &mut waiting_since).await { + Ok(None) => {} + Ok(Some(waiters)) => break Watched::GiveWay(waiters), + Err(e) => break Watched::Failed(e), + } + } + } + }; + let res = match watched { + Watched::Finished(res) => res.map(|()| Vec::new()).map_err(StoreError::from), + Watched::GiveWay(waiters) => match self.cancel_vacuum(conn, pid).await { + Ok(()) => match vacuum.await { + Ok(()) => Ok(Vec::new()), + Err(_) => Ok(waiters), + }, + Err(e) => Err(e), + }, + // Never leave our VACUUM running when we stop watching it + Watched::Failed(e) => { + let cancelled = self.cancel_vacuum(conn, pid).await; + let ended = tokio::time::timeout(CANCEL_WAIT, &mut vacuum).await; + match (cancelled, ended) { + (Ok(()), Ok(_)) => Err(e), + (Err(cancel), _) => { + Err(anyhow!("{e:#}; cancelling our VACUUM failed, too: {cancel:#}").into()) } + (Ok(()), Err(_)) => Err(anyhow!( + "{e:#}; our VACUUM did not stop within {}s of cancelling it", + CANCEL_WAIT.as_secs() + ) + .into()), } } }; + self.vacuum_pid.store(0, Ordering::SeqCst); + res + } - // The connection goes back to the pool - let restored = sql_query( - "select set_config('maintenance_work_mem', $1, false), - set_config('vacuum_cost_delay', $2, false), - set_config('statement_timeout', $3, false)", - ) - .bind::(&session.maintenance_work_mem) - .bind::(&session.vacuum_cost_delay) - .bind::(&session.statement_timeout) - .execute(&mut vacuum_conn) - .await; - match res { - Ok(()) => restored.map(|_| Vec::new()).map_err(StoreError::from), - Err(_) if !gave_way.is_empty() => restored.map(|_| gave_way).map_err(StoreError::from), - Err(e) => Err(e.into()), + /// Check whether our VACUUM, running as `pid`, needs to give way, and + /// return who waited for it if it does + async fn watch_vacuum( + &self, + conn: &mut AsyncPgConnection, + reporter: &mut dyn CompressBlocksReporter, + pid: i32, + waiting_since: &mut HashMap, + ) -> Result>, StoreError> { + reporter.reached(CompressBlocksStep::VacuumRunning).await?; + let waiters = self.lock_waiters(conn, pid).await?; + let now = Instant::now(); + waiting_since.retain(|pid, _| waiters.iter().any(|w| w.pid == *pid)); + let mut waited = false; + for waiter in &waiters { + let since = *waiting_since.entry(waiter.pid).or_insert(now); + waited |= now.duration_since(since) >= MAX_LOCK_WAIT; } + Ok(waited.then(|| waiters.into_iter().map(|w| w.what).collect())) } /// The sessions other than `vacuum_pid` that wait for a lock on the @@ -881,11 +987,28 @@ impl BlocksCompressor { Ok(waiters) } + /// Cancel our VACUUM, running as `pid`. If that fails on `conn`, which + /// may be what failed in the first place, try again on a new connection async fn cancel_vacuum( &self, conn: &mut AsyncPgConnection, pid: i32, ) -> Result<(), StoreError> { + match Self::cancel_backend(conn, pid).await { + Ok(()) => Ok(()), + Err(e) => { + let mut fresh = self.pool.get_permitted().await.map_err(|e2| { + anyhow!("{e:#}; getting another connection to cancel it failed: {e2:#}") + })?; + Self::cancel_backend(&mut fresh, pid).await + } + } + } + + async fn cancel_backend(conn: &mut C, pid: i32) -> Result<(), StoreError> + where + C: diesel_async::AsyncConnection + Send, + { sql_query(format!( "select pg_cancel_backend(pid) from pg_stat_activity where pid = $1 and state = 'active' and query like '{VACUUM_MARKER}%'" @@ -896,6 +1019,38 @@ impl BlocksCompressor { Ok(()) } + /// Cancel our VACUUM if one runs, for when the work that watched it was + /// dropped, and wait until it has stopped + async fn cancel_dropped_vacuum(&self) -> Result<(), StoreError> { + let pid = self.vacuum_pid.swap(0, Ordering::SeqCst); + if pid == 0 { + return Ok(()); + } + let mut conn = self.pool.get_permitted().await?; + Self::cancel_backend(&mut conn, pid).await?; + let start = Instant::now(); + let running = format!( + "select count(*) > 0 as running from pg_stat_activity + where pid = $1 and query like '{VACUUM_MARKER}%'" + ); + while sql_query(&running) + .bind::(pid) + .get_result::(&mut conn) + .await? + .running + { + if start.elapsed() > CANCEL_WAIT { + return Err(anyhow!( + "our VACUUM (process {pid}) did not stop within {}s of cancelling it", + CANCEL_WAIT.as_secs() + ) + .into()); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + Ok(()) + } + /// Add the column for compressed blocks the way nodes do, and wait while /// that is not possible async fn add_zstd_column( diff --git a/store/postgres/src/pool/mod.rs b/store/postgres/src/pool/mod.rs index c479c2263a2..8dd87461a8a 100644 --- a/store/postgres/src/pool/mod.rs +++ b/store/postgres/src/pool/mod.rs @@ -131,6 +131,12 @@ impl PermittedConnection { TransactionBuilder::new(self) } + /// Take the connection out of the pool, so that it is closed when it is + /// dropped rather than handed out again, even with a query still running + pub(crate) fn detach(self) -> diesel_async::AsyncPgConnection { + deadpool::managed::Object::take(self.conn) + } + /// Run `callback` inside a transaction on this connection. Commits on /// `Ok`, rolls back on `Err`. The callback receives `&mut PermittedConnection`; /// pass it to functions needing `&mut AsyncPgConnection` via deref coercion. diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index bfc8551c5bb..7f8b6321d89 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -1754,6 +1754,210 @@ fn vacuum_gives_way_to_others() { }) } +/// Whether our VACUUM still runs on the server +async fn vacuum_backends(store: &DieselChainStore) -> Vec { + names( + store, + "select pid::text as name from pg_stat_activity + where query like '/* graph-node compress-blocks */%' and pid <> pg_backend_pid()" + .to_string(), + ) + .await +} + +/// Wait up to `limit` for our VACUUM to stop on the server, and return the +/// backends still running it. A connection that went back to the pool while +/// it still ran VACUUM can not answer, so give up after a while +async fn wait_for_vacuum_to_stop(store: &DieselChainStore, limit: Duration) -> Vec { + let wait = async { + let start = Instant::now(); + loop { + let running = vacuum_backends(store).await; + if running.is_empty() || start.elapsed() > limit { + return running; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + }; + tokio::time::timeout(limit + Duration::from_secs(5), wait) + .await + .unwrap_or_else(|_| vec!["no answer; a connection in the pool still runs VACUUM".into()]) +} + +/// Hold a lock that keeps our VACUUM waiting until the transaction ends +async fn block_vacuum( + store: &DieselChainStore, + nsp: &str, +) -> impl diesel_async::SimpleAsyncConnection { + use diesel_async::SimpleAsyncConnection as _; + + let mut holder = store.get_conn_for_test().await.unwrap(); + holder + .batch_execute(&format!( + "begin; lock table {nsp}.blocks in share update exclusive mode" + )) + .await + .unwrap(); + holder +} + +#[test] +fn stop_vacuum_when_the_client_dies() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + use diesel_async::SimpleAsyncConnection as _; + + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + let mut holder = block_vacuum(&store, &nsp).await; + + // The run dies while its VACUUM waits for the lock, like a process + // that was killed + let (running_tx, running_rx) = tokio::sync::oneshot::channel(); + let running_tx = Arc::new(std::sync::Mutex::new(Some(running_tx))); + let mut reporter = TestReporter::with_hook(move |step| { + if step == CompressBlocksStep::VacuumRunning + && let Some(tx) = running_tx.lock().unwrap().take() + { + tx.send(()).unwrap(); + } + async { Ok(()) }.boxed() + }); + let run = tokio::spawn({ + let store = store.cheap_clone(); + async move { + let req = CompressBlocksRequest { + vacuum_every: Some(1), + ..compress_request(BlockCompression::Zstd(1)) + }; + store.compress_blocks(&req, &mut reporter).await + } + }); + tokio::time::timeout(Duration::from_secs(15), running_rx) + .await + .expect("VACUUM did not start") + .unwrap(); + run.abort(); + let _ = run.await; + + let running = wait_for_vacuum_to_stop(&store, Duration::from_secs(10)).await; + holder.batch_execute("rollback").await.unwrap(); + // The lock that keeps two runs apart went with the dead run + let locks = names( + &store, + "select pid::text as name from pg_locks + where locktype = 'advisory' and classid = 4 and objsubid = 2" + .to_string(), + ) + .await; + reset_compress_blocks(&store, &nsp).await; + assert_eq!(Vec::::new(), running); + assert_eq!(Vec::::new(), locks); + }) +} + +#[test] +fn stop_vacuum_when_watching_it_fails() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + use diesel_async::SimpleAsyncConnection as _; + + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + let mut holder = block_vacuum(&store, &nsp).await; + + let mut reporter = TestReporter::with_hook(|step| { + async move { + if step == CompressBlocksStep::VacuumRunning { + Err(StoreError::Unknown(anyhow!("watching VACUUM failed"))) + } else { + Ok(()) + } + } + .boxed() + }); + let req = CompressBlocksRequest { + vacuum_every: Some(1), + ..compress_request(BlockCompression::Zstd(1)) + }; + let res = tokio::time::timeout( + Duration::from_secs(15), + store.compress_blocks(&req, &mut reporter), + ) + .await; + + // We cancel the VACUUM before we return, so it is gone right away + let running = wait_for_vacuum_to_stop(&store, Duration::ZERO).await; + holder.batch_execute("rollback").await.unwrap(); + reset_compress_blocks(&store, &nsp).await; + let err = res.expect("the run did not end").unwrap_err().to_string(); + assert!(err.contains("watching VACUUM failed"), "{err}"); + assert_eq!(Vec::::new(), running); + }) +} + +#[cfg(unix)] +#[test] +fn stop_vacuum_on_ctrl_c() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + use diesel_async::SimpleAsyncConnection as _; + + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + let mut holder = block_vacuum(&store, &nsp).await; + + // Press Ctrl-C while our VACUUM waits for the lock. The run listens + // for it by then, so the signal does not end the test process + let mut reporter = TestReporter::with_hook(|step| { + async move { + if step == CompressBlocksStep::VacuumRunning { + let pid = std::process::id().to_string(); + let status = std::process::Command::new("kill") + .args(["-INT", &pid]) + .status() + .unwrap(); + assert!(status.success()); + } + Ok(()) + } + .boxed() + }); + let req = CompressBlocksRequest { + vacuum_every: Some(1), + ..compress_request(BlockCompression::Zstd(1)) + }; + let res = tokio::time::timeout( + Duration::from_secs(15), + store.compress_blocks(&req, &mut reporter), + ) + .await; + + let running = wait_for_vacuum_to_stop(&store, Duration::ZERO).await; + holder.batch_execute("rollback").await.unwrap(); + let progress = names( + &store, + format!( + "select next_block::text as name from public.compress_blocks_progress + where namespace = '{nsp}'" + ), + ) + .await; + reset_compress_blocks(&store, &nsp).await; + let err = res.expect("the run did not end").unwrap_err().to_string(); + assert!(err.contains("interrupted"), "{err}"); + assert_eq!(Vec::::new(), running); + // All blocks were written before VACUUM ran, and that was saved + assert_eq!(vec!["3".to_string()], progress); + }) +} + #[test] fn compress_blocks_adds_column() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; From facd97634227bb16213a9cae628e67c1b19d955f Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Fri, 4 Dec 2026 01:43:51 +0100 Subject: [PATCH 10/24] fix(store): stop compressing when VACUUM can not clean up after us A limit on the table's size stood in for this, its pause never ended, and it tripped on undos, small blocks and busy chains. After each VACUUM, stop with an error when the dead rows it left outnumber the blocks rewritten since the VACUUM before; running the command again continues. --- docs/graphman.md | 13 +- store/postgres/src/compress_blocks.rs | 213 ++++++++++-------- store/test-store/tests/postgres/chain_head.rs | 122 ++++++++-- 3 files changed, 234 insertions(+), 114 deletions(-) diff --git a/docs/graphman.md b/docs/graphman.md index 7583c1ab30e..c3dd4b4e06b 100644 --- a/docs/graphman.md +++ b/docs/graphman.md @@ -406,10 +406,15 @@ the command then ends with an error that says how many there are, and running it `status` shows how far the last run got, and how many blocks it left as they were. Rewriting blocks frees the space that the old blocks took up inside the table, and the command runs `VACUUM` every -so often so that later writes reuse that space. The table therefore grows by at most about twice the amount of -blocks rewritten between two runs of `VACUUM`, plus whatever the new blocks take up beyond the old ones, which is -nothing when compressing and can be a lot when uncompressing; if it grows by more, the command pauses and says -so. The files of the table do not get smaller, but the space inside them is reused for new blocks. +so often so that later writes reuse that space. The table therefore grows by about twice the amount of blocks +rewritten between two runs of `VACUUM`, plus whatever the new blocks take up beyond the old ones, which is little +when compressing and can be a lot when uncompressing. After each `VACUUM`, the command checks how many dead rows +it could not remove. More than the blocks rewritten since the `VACUUM` before means that something holds back its +cleanup, such as a long-running transaction, a replication slot or a prepared transaction, and the table would +keep growing; the command then stops with an error that says where to look, and running it again once that is +resolved continues where it stopped. That check needs Postgres 15 or later; on older versions the command says +when it starts that it can not check. The files of the table do not get smaller, but the space inside them is +reused for new blocks. To limit the load on the database, the command limits how much WAL the server writes per second while it works, and pauses while replicas fall behind. That limit counts all WAL the server writes, not only the command's own. diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index cdf1a018641..aaa55ce30ff 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -54,8 +54,6 @@ const CANCEL_WAIT: Duration = Duration::from_secs(10); /// Marks the statement of our VACUUM so that we never cancel anything else const VACUUM_MARKER: &str = "/* graph-node compress-blocks */"; -const MB: u64 = 1_000_000; - /// The table that a database migration creates for the progress of each /// chain's run const PROGRESS_TABLE: &str = "public.compress_blocks_progress"; @@ -118,14 +116,6 @@ pub enum CompressBlocksPause { VacuumGaveWay { table: String, waiters: Vec }, /// We could not add the column for compressed blocks yet NoColumn { table: String }, - /// The table grew by more than we allow, which happens when VACUUM can - /// not clean up after us - Growth { - table: String, - start: u64, - size: u64, - limit: u64, - }, } impl fmt::Display for CompressBlocksPause { @@ -146,19 +136,6 @@ impl fmt::Display for CompressBlocksPause { f, "could not add the column {ZSTD} to {table} yet; trying again later" ), - CompressBlocksPause::Growth { - table, - start, - size, - limit, - } => write!( - f, - "{table} grew from {} MB to {} MB, more than the {} MB we allow; \ - something may keep VACUUM from cleaning up", - start / MB, - size / MB, - limit / MB - ), } } } @@ -406,19 +383,28 @@ struct Done { wal_bytes: u64, } +/// How many rows of a table were ever updated or deleted, and how many are +/// dead, as the statistics count them +#[derive(QueryableByName)] +struct RowStats { + #[diesel(sql_type = BigInt)] + changed: i64, + #[diesel(sql_type = BigInt)] + dead: i64, +} + /// The progress of a run and the blocks it needs to try again struct State { progress: CompressBlocksProgress, retry: Vec>, /// Run VACUUM after rewriting this many bytes of blocks vacuum_every: u64, - /// How many bytes of blocks we rewrote since the last VACUUM + /// How many bytes of blocks, in how many rows, we rewrote since the last + /// VACUUM since_vacuum: u64, - /// The most bytes of blocks we rewrote between two runs of VACUUM, which - /// can be more than `vacuum_every` since we only check after each batch - most_between_vacuums: u64, - /// The size of the table when we started - start_size: u64, + rows_since_vacuum: u64, + /// Whether the server counts the dead rows VACUUM leaves behind as it ends + counts_dead_rows: bool, } /// Compress the blocks of a chain that has its own schema @@ -648,10 +634,10 @@ impl BlocksCompressor { let mut state = self.start(conn, req.compression, reporter).await?; state.vacuum_every = self.vacuum_every(conn, req).await?; - state.start_size = self.total_size(conn).await?; + state.counts_dead_rows = self.counts_dead_rows(conn, reporter).await?; let mut pace = Pace::new(req.max_wal_rate); while state.progress.next_block <= state.progress.last_block { - self.wait_until_clear(conn, reporter, &state).await?; + self.wait_until_clear(conn, reporter).await?; // Skip over gaps in the block numbers let first = number( @@ -698,10 +684,17 @@ impl BlocksCompressor { } self.retry(conn, req, reporter, &mut state, &pace).await?; - // Make the space of the last blocks we rewrote available, too + // Make the space of the last blocks we rewrote available, too. Stopping + // now would not keep the table from growing if state.since_vacuum > 0 { - self.vacuum(conn, reporter, &pace, &mut state, false) + let held = self + .vacuum(conn, reporter, &pace, &mut state, false) .await?; + if let Some(held) = held { + reporter.message(&format!( + "{held}; their space is reused once that is resolved and VACUUM runs again" + )); + } } Self::left_as_they_were(state.progress) } @@ -793,15 +786,23 @@ impl BlocksCompressor { pace: &Pace, state: &mut State, ) -> Result<(), StoreError> { - if state.since_vacuum >= state.vacuum_every { - self.vacuum(conn, reporter, pace, state, false).await?; + if state.since_vacuum < state.vacuum_every { + return Ok(()); + } + match self.vacuum(conn, reporter, pace, state, false).await? { + None => Ok(()), + Some(held) => Err(anyhow!( + "{held}. Stopped so that the table does not keep growing; every batch written \ + so far is saved, and running the command again once that is resolved \ + continues from where it stopped" + ) + .into()), } - Ok(()) } /// Run VACUUM on the blocks table so that later writes reuse the space - /// that rewritten blocks took up, and truncate the empty end of its files - /// if `truncate` is set. VACUUM gives way to anybody who needs a lock + /// that rewritten blocks took up, truncating its files if `truncate` is + /// set. Return what to look for if something holds back its cleanup async fn vacuum( &self, conn: &mut AsyncPgConnection, @@ -809,9 +810,18 @@ impl BlocksCompressor { pace: &Pace, state: &mut State, truncate: bool, - ) -> Result<(), StoreError> { + ) -> Result, StoreError> { loop { reporter.reached(CompressBlocksStep::Vacuum).await?; + let before = if state.counts_dead_rows { + // Count the rows we made dead before VACUUM counts what it left + sql_query("select pg_stat_force_next_flush()") + .execute(conn) + .await?; + Some(self.row_stats(conn).await?) + } else { + None + }; let start = Instant::now(); let wal_start = self.wal_lsn(conn).await?; @@ -819,15 +829,20 @@ impl BlocksCompressor { let wal_bytes = self.wal_lsn(conn).await?.saturating_sub(wal_start); state.progress.wal_bytes += wal_bytes; if waiters.is_empty() { - state.most_between_vacuums = state.most_between_vacuums.max(state.since_vacuum); + let rewritten = state.rows_since_vacuum; state.since_vacuum = 0; + state.rows_since_vacuum = 0; reporter.message(&format!( "ran VACUUM on {} in {}s", self.blocks, start.elapsed().as_secs() )); + let held = match before { + Some(before) => self.held_back(conn, &before, rewritten).await?, + None => None, + }; tokio::time::sleep(pace.pause(start.elapsed(), wal_bytes)).await; - return Ok(()); + return Ok(held); } reporter.paused(&CompressBlocksPause::VacuumGaveWay { @@ -841,11 +856,9 @@ impl BlocksCompressor { } } - /// Run VACUUM on another connection, and cancel it when anybody waited - /// for a lock on the table for longer than `MAX_LOCK_WAIT` since a VACUUM - /// we start does not give way like autovacuum. Return who waited. The - /// connection leaves the pool and is closed afterwards, so that a VACUUM - /// we stop watching never holds up whoever gets the connection next + /// Run VACUUM and cancel it once anybody waited `MAX_LOCK_WAIT` for a lock + /// on the table; return who waited. Its connection leaves the pool, so a + /// VACUUM we stop watching never holds up whoever gets that connection next async fn try_vacuum( &self, conn: &mut AsyncPgConnection, @@ -1139,8 +1152,8 @@ impl BlocksCompressor { retry: row.retry, vacuum_every: MIN_VACUUM_EVERY, since_vacuum: 0, - most_between_vacuums: 0, - start_size: 0, + rows_since_vacuum: 0, + counts_dead_rows: false, })) } @@ -1158,63 +1171,72 @@ impl BlocksCompressor { &self, conn: &mut AsyncPgConnection, reporter: &mut dyn CompressBlocksReporter, - state: &State, ) -> Result<(), StoreError> { - self.wait_for_replicas(conn, reporter).await?; - self.wait_for_growth(conn, reporter, state).await + self.wait_for_replicas(conn, reporter).await } - async fn total_size(&self, conn: &mut AsyncPgConnection) -> Result { - let size = number( + /// Whether VACUUM counts the dead rows it could not remove as it ends, + /// which Postgres does from version 15 on while it tracks table statistics + async fn counts_dead_rows( + &self, + conn: &mut AsyncPgConnection, + reporter: &mut dyn CompressBlocksReporter, + ) -> Result { + let counts = is_true( conn, - format!( - "select pg_total_relation_size('{}')::int8 as number", - self.blocks - ), + "select current_setting('server_version_num')::int >= 150000 + and current_setting('track_counts')::bool as res" + .to_string(), ) .await?; - Ok(size.unwrap_or(0) as u64) - } - - /// The table should grow by no more than the bytes our new values add - /// over the old ones, which is nothing when we compress, plus twice what - /// we rewrite between two runs of VACUUM. If it grows by much more, - /// VACUUM is not doing its job - fn growth_limit(state: &State) -> u64 { - let added = state - .progress - .new_bytes - .saturating_sub(state.progress.old_bytes); - let between_vacuums = state - .vacuum_every - .max(state.most_between_vacuums) - .max(state.since_vacuum); - state - .start_size - .saturating_add(added) - .saturating_add(between_vacuums.saturating_mul(2)) + if !counts { + reporter.message(&format!( + "can not tell whether something holds back the cleanup of {}, which needs \ + Postgres 15 or later with track_counts on; watch its size while this runs", + self.blocks + )); + } + Ok(counts) } - async fn wait_for_growth( + /// If the VACUUM that just ended left more dead rows than the `rewritten` + /// rows we made dead since the VACUUM before, something holds back its + /// cleanup; say what to look for + async fn held_back( &self, conn: &mut AsyncPgConnection, - reporter: &mut dyn CompressBlocksReporter, - state: &State, - ) -> Result<(), StoreError> { - let limit = Self::growth_limit(state); - loop { - let size = self.total_size(conn).await?; - if size <= limit { - return Ok(()); - } - reporter.paused(&CompressBlocksPause::Growth { - table: self.blocks.clone(), - start: state.start_size, - size, - limit, - })?; - tokio::time::sleep(PAUSE_INTERVAL).await; + before: &RowStats, + rewritten: u64, + ) -> Result, StoreError> { + let after = self.row_stats(conn).await?; + // Others' counts can reach the server after VACUUM counted what it + // left, so leave out the rows they changed since it started + let others = after.changed.saturating_sub(before.changed).max(0); + let left = after.dead.saturating_sub(others).max(0) as u64; + if left <= rewritten { + return Ok(None); } + Ok(Some(format!( + "VACUUM could not remove {left} dead rows from {}, more than the {rewritten} blocks \ + we rewrote since the VACUUM before, so something holds back its cleanup: a \ + long-running transaction (see backend_xmin in pg_stat_activity), a replication \ + slot (pg_replication_slots), a prepared transaction (pg_prepared_xacts) or a \ + replica with hot_standby_feedback", + self.blocks + ))) + } + + /// What the statistics say about the rows of the blocks table + async fn row_stats(&self, conn: &mut AsyncPgConnection) -> Result { + let stats = sql_query(format!( + "select coalesce(n_tup_upd + n_tup_del, 0)::int8 as changed, + coalesce(n_dead_tup, 0)::int8 as dead + from pg_stat_all_tables where relid = '{}'::regclass", + self.blocks + )) + .get_result::(conn) + .await?; + Ok(stats) } async fn wait_for_replicas( @@ -1319,6 +1341,7 @@ impl BlocksCompressor { progress.new_bytes += done.new_bytes; progress.wal_bytes += done.wal_bytes; state.since_vacuum += done.old_bytes; + state.rows_since_vacuum += done.blocks as u64; Ok(done) } @@ -1519,7 +1542,7 @@ impl BlocksCompressor { .await?; let hashes = state.retry.clone(); for hashes in hashes.chunks(MAX_BATCH_SIZE as usize) { - self.wait_until_clear(conn, reporter, state).await?; + self.wait_until_clear(conn, reporter).await?; let batch = Batch::Hashes(hashes); let done = self .rewrite(conn, req.compression, reporter, &batch, state) diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index 7f8b6321d89..9171d17d95c 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -2085,20 +2085,19 @@ fn compress_blocks_needs_migration() { } #[test] -fn undo_grows_the_table_without_pausing() { +fn undo_grows_the_table_without_stopping() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; run_test_async(chain, |store, _, _| async move { let Some(nsp) = private_namespace(&store).await else { return; }; reset_compress_blocks(&store, &nsp).await; - add_blocks(&store, &nsp, 100, 200, 16_000).await; + add_blocks(&store, &nsp, 100, 20_000, 4_000).await; compress_blocks(&store, BlockCompression::Zstd(1)) .await .unwrap(); // Leave no free space in the table, so uncompressing the blocks has - // to grow it by much more than twice what we rewrite between two - // runs of VACUUM + // to grow it by much more than what we rewrite between two VACUUMs execute(&store, format!("vacuum full {nsp}.blocks")).await; let req = CompressBlocksRequest { @@ -2112,28 +2111,103 @@ fn undo_grows_the_table_without_pausing() { reset_compress_blocks(&store, &nsp).await; let progress = res.unwrap(); - assert_eq!(203, progress.blocks); + assert_eq!(20_003, progress.blocks); assert!(!raw.is_compressed()); }) } #[test] -fn pause_when_the_table_grows_too_much() { +fn compress_small_blocks_without_stopping() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; run_test_async(chain, |store, _, _| async move { - use diesel_async::SimpleAsyncConnection as _; + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + // Blocks of about 2 KB are kept in the TOAST table, but compressed + // they fit in the row, so the table's main part grows by them while + // the space they free in the TOAST table can not hold them + add_blocks(&store, &nsp, 100, 5_000, 2_000).await; + execute(&store, format!("vacuum full {nsp}.blocks")).await; + + let req = CompressBlocksRequest { + vacuum_every: Some(64 * 1024), + ..compress_request(BlockCompression::Zstd(1)) + }; + let res = store + .compress_blocks(&req, &mut TestReporter::default()) + .await; + let compressed = count_compressed(&store, &nsp).await; + reset_compress_blocks(&store, &nsp).await; + + let progress = res.unwrap(); + assert_eq!(5_003, progress.blocks); + assert_eq!(5_003, compressed); + }) +} +#[test] +fn blocks_that_nodes_add_do_not_stop_the_run() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { let Some(nsp) = private_namespace(&store).await else { return; }; reset_compress_blocks(&store, &nsp).await; - // Enough blocks that what we write is much more than twice a batch add_blocks(&store, &nsp, 100, 1_000, 16_000).await; - // Free space that earlier tests left in the table would hide growth execute(&store, format!("vacuum full {nsp}.blocks")).await; - // An old snapshot keeps VACUUM from removing the blocks we rewrite, - // and the table grows by everything we write + // While we work, nodes add many more blocks than we rewrite between + // two runs of VACUUM + let node = store.cheap_clone(); + let node_nsp = nsp.clone(); + let mut added = false; + let mut reporter = TestReporter::with_hook(move |step| { + let now = !added && matches!(step, CompressBlocksStep::Written { .. }); + added |= now; + let (node, nsp) = (node.cheap_clone(), node_nsp.clone()); + async move { + if now { + add_blocks(&node, &nsp, 1_000_000, 2_000, 16_000).await; + } + Ok(()) + } + .boxed() + }); + let req = CompressBlocksRequest { + vacuum_every: Some(64 * 1024), + ..compress_request(BlockCompression::Zstd(1)) + }; + let res = store.compress_blocks(&req, &mut reporter).await; + let added = names( + &store, + format!("select hash::text as name from {nsp}.blocks where number >= 1000000"), + ) + .await + .len(); + reset_compress_blocks(&store, &nsp).await; + + let progress = res.unwrap(); + assert_eq!(1_003, progress.blocks); + assert_eq!(2_000, added); + }) +} + +#[test] +fn stop_when_vacuum_can_not_clean_up() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + use diesel_async::SimpleAsyncConnection as _; + + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + // Enough blocks for many runs of VACUUM + add_blocks(&store, &nsp, 100, 2_000, 16_000).await; + + // An old snapshot keeps VACUUM from removing the rows we rewrite. + // Like graphman, let the run carry on after pauses let mut holder = store.get_conn_for_test().await.unwrap(); holder .batch_execute("begin isolation level repeatable read; select 1") @@ -2143,14 +2217,32 @@ fn pause_when_the_table_grows_too_much() { vacuum_every: Some(64 * 1024), ..compress_request(BlockCompression::Zstd(1)) }; - let res = store + let mut reporter = TestReporter { + allow_pauses: true, + ..Default::default() + }; + let res = tokio::time::timeout( + Duration::from_secs(120), + store.compress_blocks(&req, &mut reporter), + ) + .await; + holder.batch_execute("commit").await.unwrap(); + let stopped_at = count_compressed(&store, &nsp).await; + + // Once the snapshot is gone, running again continues where the + // first run stopped + let rerun = store .compress_blocks(&req, &mut TestReporter::default()) .await; - holder.batch_execute("commit").await.unwrap(); + let compressed = count_compressed(&store, &nsp).await; reset_compress_blocks(&store, &nsp).await; - let err = res.unwrap_err().to_string(); - assert!(err.contains("grew from"), "{err}"); + let err = res.expect("the run did not stop").unwrap_err().to_string(); + assert!(err.contains("holds back"), "{err}"); + assert!(err.contains("running the command again"), "{err}"); + assert!(0 < stopped_at && stopped_at < 2_003, "{stopped_at}"); + assert_eq!(2_003 - stopped_at, rerun.unwrap().blocks); + assert_eq!(2_003, compressed); }) } From 5e80cf410f22657fd4f3fa0eccdca7b546115527 Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Fri, 4 Dec 2026 00:42:57 +0100 Subject: [PATCH 11/24] fix(store): tell a non-owner at once that it can not add the column Adding the column reused the node's code, which hides errors and backs off for up to an hour, so a run by a user who does not own the table paused forever. The run now checks the owner first, and gets the real error back, trying for about a minute before it stops with it. --- docs/graphman.md | 3 +- store/postgres/src/chain_store.rs | 74 ++++++++++++++----- store/postgres/src/compress_blocks.rs | 49 ++++++++++-- store/test-store/tests/postgres/chain_head.rs | 50 +++++++++++++ 4 files changed, 150 insertions(+), 26 deletions(-) diff --git a/docs/graphman.md b/docs/graphman.md index c3dd4b4e06b..53f3122ddd6 100644 --- a/docs/graphman.md +++ b/docs/graphman.md @@ -393,7 +393,8 @@ compressed blocks, and that the database user `graphman` connects as owns the ch the owner can run `VACUUM` on it. The command keeps track of how far it got in a table that the database migrations of this version of `graph-node` create; `graphman` does not run migrations itself, so start a node of this version, or run `graphman database migrate`, first. The command adds the column `data_zstd` to the -`blocks` table if it is missing, which locks the table for a moment. Do not drop that column by hand while a +`blocks` table if it is missing, which locks the table for a moment; if that keeps failing for about a minute, for +example because nodes hold locks on the table, the command stops and says why. Do not drop that column by hand while a node is running, since the node might use it. `run` rewrites each block where it is stored, a batch at a time and in order of block number, and records how far diff --git a/store/postgres/src/chain_store.rs b/store/postgres/src/chain_store.rs index bca70ffb163..a1cb8ce8de2 100644 --- a/store/postgres/src/chain_store.rs +++ b/store/postgres/src/chain_store.rs @@ -429,6 +429,25 @@ mod data { self.table.clone() } + /// Add the column for compressed blocks, but never wait long for the + /// lock, since all other queries on the table queue behind us + async fn add_zstd_column(&self, conn: &mut AsyncPgConnection) -> Result<(), StoreError> { + conn.transaction::<_, StoreError, _>(async |conn| { + conn.batch_execute(&format!( + "set local lock_timeout = {timeout}; \ + alter table {qname} \ + add column if not exists {name} bytea, \ + alter column {name} set storage external", + timeout = ZstdColumn::LOCK_TIMEOUT.as_millis(), + qname = self.qname, + name = ZstdColumn::NAME + )) + .await?; + Ok(()) + }) + .await + } + fn hash(&self) -> DynColumn { self.table.column::("hash") } @@ -1129,7 +1148,7 @@ mod data { /// Make it possible to store compressed blocks by adding the column for /// them. Return `false` if that does not work right now and blocks need /// to be stored uncompressed - pub(crate) async fn prepare_compression( + pub(super) async fn prepare_compression( &self, logger: &Logger, conn: &mut AsyncPgConnection, @@ -1144,22 +1163,7 @@ mod data { if !column.start_attempt() { return Ok(false); } - let res = conn - .transaction::<_, StoreError, _>(async |conn| { - conn.batch_execute(&format!( - "set local lock_timeout = {timeout}; \ - alter table {qname} \ - add column if not exists {name} bytea, \ - alter column {name} set storage external", - timeout = ZstdColumn::LOCK_TIMEOUT.as_millis(), - qname = blocks.qname, - name = ZstdColumn::NAME - )) - .await?; - Ok(()) - }) - .await; - match res { + match blocks.add_zstd_column(conn).await { Ok(()) => { info!(logger, "Added column for compressed blocks"; "table" => &blocks.qname); column.check(conn, &blocks.namespace).await @@ -1173,6 +1177,29 @@ mod data { } } + /// Add the column for compressed blocks now, however long ago nodes + /// last tried, and return why if that does not work + pub(crate) async fn add_zstd_column( + &self, + conn: &mut AsyncPgConnection, + ) -> Result<(), StoreError> { + let Storage::Private(Schema { blocks, .. }) = self else { + return Err(internal_error!( + "blocks in shared tables are never compressed" + )); + }; + blocks.add_zstd_column(conn).await?; + if blocks.zstd_column.check(conn, &blocks.namespace).await? { + Ok(()) + } else { + Err(internal_error!( + "the column {} is missing from {} after adding it", + ZstdColumn::NAME, + blocks.qname + )) + } + } + pub(super) async fn block_ptrs_by_numbers( &self, conn: &mut AsyncPgConnection, @@ -3292,6 +3319,19 @@ impl ChainStore { compressor.run(conn, req, reporter).await } + /// Compress blocks as `role` to see what users without some privileges + /// get + #[cfg(debug_assertions)] + pub async fn compress_blocks_as_for_tests( + &self, + role: &str, + req: &CompressBlocksRequest, + reporter: &mut dyn CompressBlocksReporter, + ) -> Result { + let (compressor, conn) = self.blocks_compressor().await?; + compressor.run_as_for_tests(conn, role, req, reporter).await + } + pub async fn compress_blocks_status(&self) -> Result { let (compressor, mut conn) = self.blocks_compressor().await?; compressor.status(&mut conn).await diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index aaa55ce30ff..dad3ea71bd3 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -60,6 +60,9 @@ const PROGRESS_TABLE: &str = "public.compress_blocks_progress"; /// How long to wait before checking whether a reason to pause went away const PAUSE_INTERVAL: Duration = Duration::from_secs(10); +/// How often we try to add the column for compressed blocks, `PAUSE_INTERVAL` +/// apart, before we give up +const COLUMN_ATTEMPTS: usize = 6; pub struct CompressBlocksRequest { /// How to store the blocks. With `None`, compressed blocks are @@ -114,8 +117,8 @@ pub enum CompressBlocksPause { ReplicaLag(Duration), /// Our VACUUM gave way to these sessions that waited for a lock VacuumGaveWay { table: String, waiters: Vec }, - /// We could not add the column for compressed blocks yet - NoColumn { table: String }, + /// Adding the column for compressed blocks failed with `error` + NoColumn { table: String, error: String }, } impl fmt::Display for CompressBlocksPause { @@ -132,9 +135,10 @@ impl fmt::Display for CompressBlocksPause { trying again once nobody waits", waiters.join(", ") ), - CompressBlocksPause::NoColumn { table } => write!( + CompressBlocksPause::NoColumn { table, error } => write!( f, - "could not add the column {ZSTD} to {table} yet; trying again later" + "could not add the column {ZSTD} to {table}: {error}; trying again in {}s", + PAUSE_INTERVAL.as_secs() ), } } @@ -590,6 +594,25 @@ impl BlocksCompressor { res } + /// Run as `role` to see what users without some privileges get + #[cfg(debug_assertions)] + pub(crate) async fn run_as_for_tests( + &self, + conn: PermittedConnection, + role: &str, + req: &CompressBlocksRequest, + reporter: &mut dyn CompressBlocksReporter, + ) -> Result { + let mut conn = CloseOnDrop(Some(conn)); + conn.get() + .batch_execute(&format!("set role \"{role}\"")) + .await?; + let res = self.run_on(conn.get(), req, reporter).await; + conn.get().batch_execute("reset role").await?; + conn.release(); + res + } + async fn run_on( &self, conn: &mut AsyncPgConnection, @@ -620,6 +643,7 @@ impl BlocksCompressor { reporter: &mut dyn CompressBlocksReporter, ) -> Result { self.check_progress_table(conn).await?; + self.check_owner(conn).await?; if !self.storage.has_zstd_column(conn).await? { if req.compression == BlockCompression::None { reporter.message(&format!("{} has no compressed blocks", self.blocks)); @@ -630,7 +654,6 @@ impl BlocksCompressor { } self.add_zstd_column(conn, reporter).await?; } - self.check_owner(conn).await?; let mut state = self.start(conn, req.compression, reporter).await?; state.vacuum_every = self.vacuum_every(conn, req).await?; @@ -1064,18 +1087,28 @@ impl BlocksCompressor { Ok(()) } - /// Add the column for compressed blocks the way nodes do, and wait while - /// that is not possible + /// Add the column for compressed blocks. A node might hold a lock that + /// keeps us from doing that for a moment, so try a few times async fn add_zstd_column( &self, conn: &mut AsyncPgConnection, reporter: &mut dyn CompressBlocksReporter, ) -> Result<(), StoreError> { - while !self.storage.prepare_compression(&self.logger, conn).await? { + let mut attempt = 1; + while let Err(e) = self.storage.add_zstd_column(conn).await { + if attempt >= COLUMN_ATTEMPTS { + return Err(anyhow!( + "could not add the column {ZSTD} to {} in {attempt} attempts: {e:#}", + self.blocks + ) + .into()); + } reporter.paused(&CompressBlocksPause::NoColumn { table: self.blocks.clone(), + error: format!("{e:#}"), })?; tokio::time::sleep(PAUSE_INTERVAL).await; + attempt += 1; } reporter.message(&format!("{} has the column {ZSTD}", self.blocks)); Ok(()) diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index 9171d17d95c..0cb7f321acf 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -1986,6 +1986,56 @@ fn compress_blocks_adds_column() { }) } +#[test] +fn only_the_owner_can_add_the_column() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, diesel_store, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + let store = store_without_column(&store, &diesel_store, &nsp).await; + + // A user who may write the blocks table but does not own it can not + // add the column, and learns why at once. Like graphman, let the run + // carry on after pauses + let role = "compress_blocks_not_owner"; + execute(&store, format!("drop role if exists {role}")).await; + execute(&store, format!("create role {role}")).await; + execute(&store, format!("grant usage on schema {nsp} to {role}")).await; + execute( + &store, + format!("grant select, update on {nsp}.blocks to {role}"), + ) + .await; + let mut reporter = TestReporter { + allow_pauses: true, + ..Default::default() + }; + let start = Instant::now(); + let res = tokio::time::timeout( + Duration::from_secs(30), + store.compress_blocks_as_for_tests( + role, + &compress_request(BlockCompression::Zstd(1)), + &mut reporter, + ), + ) + .await; + let waited = start.elapsed(); + execute(&store, format!("drop owned by {role}")).await; + execute(&store, format!("drop role {role}")).await; + let storage = column_storage(&store, &nsp).await; + reset_compress_blocks(&store, &nsp).await; + restore_column(&store, &nsp).await; + + let err = res.expect("the run did not end").unwrap_err().to_string(); + assert!(err.contains("only its owner"), "{err}"); + assert!(waited < Duration::from_secs(5), "failed after {waited:?}"); + assert_eq!(None, storage); + }) +} + #[test] fn give_up_rather_than_queue_for_the_table() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; From a19e867a405062ad1f004364f48e1dfdfe225ac8 Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Fri, 4 Dec 2026 00:48:53 +0100 Subject: [PATCH 12/24] fix(store): stop at once on a second Ctrl-C or a hung clean-up After Ctrl-C, cancelling the VACUUM and releasing the lock had no time limit, and later presses were ignored, so a dead database left graphman hanging for about 15 minutes. Cleaning up now stops after 30s or on a second Ctrl-C, closing the connection so the server releases the lock. --- docs/graphman.md | 6 +- store/postgres/src/compress_blocks.rs | 75 +++++++++---- store/test-store/tests/postgres/chain_head.rs | 105 ++++++++++++++++++ 3 files changed, 165 insertions(+), 21 deletions(-) diff --git a/docs/graphman.md b/docs/graphman.md index 53f3122ddd6..0cb3127108e 100644 --- a/docs/graphman.md +++ b/docs/graphman.md @@ -424,8 +424,10 @@ again once nobody waits. Writing a batch never waits for a block that a node has with an error rather than wait more than 2 seconds for a lock on the table, since everybody who needs a conflicting lock would have to wait behind it; running it again continues where it stopped. Pressing Ctrl-C stops the command after it has cancelled its `VACUUM`; each batch saves its progress when it is written, so -nothing more is lost than the batch being written. If the command dies without cancelling it, the server stops -the `VACUUM` within a few seconds on systems where Postgres supports `client_connection_check_interval`. +nothing more is lost than the batch being written. If cleaning up takes more than 30 seconds, for example because +the database does not answer, or Ctrl-C is pressed again, the command stops at once and closes its connection. If +the command dies without cancelling its `VACUUM`, the server stops it within a few seconds on systems where +Postgres supports `client_connection_check_interval`. ### COSTS diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index dad3ea71bd3..b341991525f 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -51,6 +51,8 @@ const VACUUM_COST_DELAY_MS: u64 = 2; /// there, and how long we wait for our VACUUM to stop after cancelling it const CLIENT_CHECK_INTERVAL: Duration = Duration::from_secs(2); const CANCEL_WAIT: Duration = Duration::from_secs(10); +/// How long we clean up after the user pressed Ctrl-C at most +const STOP_TIMEOUT: Duration = Duration::from_secs(30); /// Marks the statement of our VACUUM so that we never cancel anything else const VACUUM_MARKER: &str = "/* graph-node compress-blocks */"; @@ -160,6 +162,8 @@ pub enum CompressBlocksStep { /// Our VACUUM is running, and we are about to check whether it needs to /// give way VacuumRunning, + /// The user pressed Ctrl-C, and we are about to clean up + Stopping, } #[async_trait] @@ -439,20 +443,25 @@ impl CloseOnDrop { .expect("the connection is there until released") } - /// Put the connection back in the pool + /// Put the connection back in the pool unless it was closed fn release(mut self) { self.0.take(); } -} -impl Drop for CloseOnDrop { - fn drop(&mut self) { + /// Close the connection now + fn close(&mut self) { if let Some(conn) = self.0.take() { drop(conn.detach()); } } } +impl Drop for CloseOnDrop { + fn drop(&mut self) { + self.close(); + } +} + /// Resolve when the user presses Ctrl-C. Listening for it replaces the /// default of ending the process, so if listening fails, never resolve async fn interrupted(logger: &Logger) { @@ -589,7 +598,7 @@ impl BlocksCompressor { reporter: &mut dyn CompressBlocksReporter, ) -> Result { let mut conn = CloseOnDrop(Some(conn)); - let res = self.run_on(conn.get(), req, reporter).await; + let res = self.run_on(&mut conn, req, reporter).await; conn.release(); res } @@ -607,33 +616,61 @@ impl BlocksCompressor { conn.get() .batch_execute(&format!("set role \"{role}\"")) .await?; - let res = self.run_on(conn.get(), req, reporter).await; - conn.get().batch_execute("reset role").await?; + let res = self.run_on(&mut conn, req, reporter).await; + if let Some(open) = conn.0.as_mut() { + open.batch_execute("reset role").await?; + } conn.release(); res } async fn run_on( &self, - conn: &mut AsyncPgConnection, + conn: &mut CloseOnDrop, req: &CompressBlocksRequest, reporter: &mut dyn CompressBlocksReporter, ) -> Result { - self.lock(conn).await?; + self.lock(conn.get()).await?; let res = tokio::select! { - res = self.run_locked(conn, req, reporter) => res, + res = self.run_locked(conn.get(), req, reporter) => res, () = interrupted(&self.logger) => { - // Every batch saves the progress as it is written, so only - // a VACUUM can be left to stop - let msg = "interrupted; the progress of every batch written so far is saved, \ - and running the command again continues from there"; - match self.cancel_dropped_vacuum().await { - Ok(()) => Err(anyhow!(msg).into()), - Err(e) => Err(anyhow!("{msg}; cancelling our VACUUM failed: {e:#}").into()), - } + return self.stop_after_interrupt(conn, reporter).await; } }; - self.unlock(conn, res).await + self.unlock(conn.get(), res).await + } + + /// Cancel our VACUUM and release the lock after the user pressed Ctrl-C; + /// every batch saved its progress when it was written. If that takes too + /// long or the user presses Ctrl-C again, close the connection instead + async fn stop_after_interrupt( + &self, + conn: &mut CloseOnDrop, + reporter: &mut dyn CompressBlocksReporter, + ) -> Result { + let msg = "interrupted; the progress of every batch written so far is saved, and \ + running the command again continues from there"; + let cleanup = async { + reporter.reached(CompressBlocksStep::Stopping).await?; + let res = match self.cancel_dropped_vacuum().await { + Ok(()) => Err(anyhow!(msg).into()), + Err(e) => Err(anyhow!("{msg}; cancelling our VACUUM failed: {e:#}").into()), + }; + self.unlock(conn.get(), res).await + }; + let gave_up = tokio::select! { + res = tokio::time::timeout(STOP_TIMEOUT, cleanup) => match res { + Ok(res) => return res, + Err(_) => format!("cleaning up took more than {}s", STOP_TIMEOUT.as_secs()), + }, + () = interrupted(&self.logger) => "Ctrl-C was pressed again".to_string(), + }; + conn.close(); + Err(anyhow!( + "{msg}; {gave_up}, so we closed the connection without cleaning up, and the \ + server releases our lock and stops our VACUUM once it notices" + ) + .into()) } async fn run_locked( diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index 0cb7f321acf..eb64db5967e 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -1958,6 +1958,111 @@ fn stop_vacuum_on_ctrl_c() { }) } +/// Send SIGINT to this process, which a run that listens for Ctrl-C catches +#[cfg(unix)] +fn press_ctrl_c() { + let pid = std::process::id().to_string(); + let status = std::process::Command::new("kill") + .args(["-INT", &pid]) + .status() + .unwrap(); + assert!(status.success()); +} + +/// Press Ctrl-C once the first batch is written, and keep the run from going +/// on until it notices. Then do `stopping` while it cleans up +#[cfg(unix)] +fn interrupt_after_first_batch( + stopping: impl Fn() -> BoxFuture<'static, Result<(), StoreError>> + Send + 'static, +) -> TestReporter { + let mut pressed = false; + TestReporter::with_hook(move |step| match step { + CompressBlocksStep::Written { .. } if !pressed => { + pressed = true; + press_ctrl_c(); + tokio::time::sleep(Duration::from_secs(60)).map(Ok).boxed() + } + CompressBlocksStep::Stopping => stopping(), + _ => async { Ok(()) }.boxed(), + }) +} + +#[cfg(unix)] +#[test] +fn give_up_cleaning_up_after_ctrl_c() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + + // Cleaning up hangs, as it does when the database stops answering + let mut reporter = interrupt_after_first_batch(|| std::future::pending().boxed()); + let start = Instant::now(); + let res = tokio::time::timeout( + Duration::from_secs(60), + store.compress_blocks(&compress_request(BlockCompression::Zstd(1)), &mut reporter), + ) + .await; + let waited = start.elapsed(); + + // Closing the connection released the lock, so another run works + let mut rerun = Err(StoreError::Unknown(anyhow!("never ran"))); + for _ in 0..50 { + rerun = compress_blocks(&store, BlockCompression::Zstd(1)).await; + if !rerun + .as_ref() + .is_err_and(|e| e.to_string().contains("another process")) + { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + reset_compress_blocks(&store, &nsp).await; + + let err = res.expect("the run did not end").unwrap_err().to_string(); + assert!(err.contains("interrupted"), "{err}"); + assert!(err.contains("30s"), "{err}"); + assert!(waited < Duration::from_secs(40), "stopped after {waited:?}"); + rerun.unwrap(); + }) +} + +#[cfg(unix)] +#[test] +fn ctrl_c_twice_stops_at_once() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + + // Cleaning up hangs, and the user presses Ctrl-C again + let mut reporter = interrupt_after_first_batch(|| { + async { + tokio::time::sleep(Duration::from_secs(1)).await; + press_ctrl_c(); + std::future::pending().await + } + .boxed() + }); + let start = Instant::now(); + let res = tokio::time::timeout( + Duration::from_secs(20), + store.compress_blocks(&compress_request(BlockCompression::Zstd(1)), &mut reporter), + ) + .await; + let waited = start.elapsed(); + reset_compress_blocks(&store, &nsp).await; + + let err = res.expect("the run did not end").unwrap_err().to_string(); + assert!(err.contains("Ctrl-C was pressed again"), "{err}"); + assert!(waited < Duration::from_secs(10), "stopped after {waited:?}"); + }) +} + #[test] fn compress_blocks_adds_column() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; From 0fff3ab57a37875099c024edb346c15bb7582070 Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Fri, 4 Dec 2026 00:51:23 +0100 Subject: [PATCH 13/24] fix(store): wait for a VACUUM that a failed cancel left running When VACUUM gave way to others and cancelling it failed, the run returned at once and left the VACUUM to the server's client check. It now waits up to 10s for it, as the other paths do. --- store/postgres/src/compress_blocks.rs | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index b341991525f..b68146c7884 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -982,13 +982,21 @@ impl BlocksCompressor { }; let res = match watched { Watched::Finished(res) => res.map(|()| Vec::new()).map_err(StoreError::from), - Watched::GiveWay(waiters) => match self.cancel_vacuum(conn, pid).await { - Ok(()) => match vacuum.await { - Ok(()) => Ok(Vec::new()), - Err(_) => Ok(waiters), - }, - Err(e) => Err(e), - }, + Watched::GiveWay(waiters) => { + let cancelled = self.cancel_vacuum(conn, pid).await; + let ended = tokio::time::timeout(CANCEL_WAIT, &mut vacuum).await; + match (cancelled, ended) { + // Our VACUUM finished before the cancel reached it + (Ok(()), Ok(Ok(()))) => Ok(Vec::new()), + (Ok(()), Ok(Err(_))) => Ok(waiters), + (Err(e), _) => Err(e), + (Ok(()), Err(_)) => Err(anyhow!( + "our VACUUM did not stop within {}s of cancelling it", + CANCEL_WAIT.as_secs() + ) + .into()), + } + } // Never leave our VACUUM running when we stop watching it Watched::Failed(e) => { let cancelled = self.cancel_vacuum(conn, pid).await; From d2375e5b9944f17530e845c5eea104b462ca9704 Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Fri, 4 Dec 2026 00:51:39 +0100 Subject: [PATCH 14/24] docs(graphman): give the default of --vacuum-every in the disk costs The disk room that compress-blocks needs is given in multiples of --vacuum-every, so say what it is by default: the larger of 1 GiB and the size of the TOAST table's index. --- docs/graphman.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/graphman.md b/docs/graphman.md index 0cb3127108e..f277530ae12 100644 --- a/docs/graphman.md +++ b/docs/graphman.md @@ -435,9 +435,11 @@ Postgres supports `client_connection_check_interval`. rewritten blocks in a test with 20 GB of blocks. Replicas, WAL archives and backups that keep WAL get all of it. - At the default `--max-rate` of 20 MB/s that means about 22 hours per TB of blocks, again measured on test data: the time is roughly the old size of the blocks times 1.6, divided by `--max-rate`. -- The disk needs room for the table to grow by up to twice `--vacuum-every` (plus, when uncompressing, the - difference between the uncompressed and compressed size of the blocks), and `pg_wal` room for the WAL - written until the next checkpoint and for any WAL that replication slots or archiving hold back. +- The disk needs room for the table to grow by up to twice `--vacuum-every`, which by default is the larger of + 1 GiB and the size of the index of the `blocks` table's TOAST table, or half again as much for blocks of a few + KB, whose TOAST chunks leave some space unused (plus, when uncompressing, the difference between the + uncompressed and compressed size of the blocks), and `pg_wal` room for the WAL written until the next + checkpoint and for any WAL that replication slots or archiving hold back. - Filesystem snapshots and incremental backups keep the old blocks, so the space on their disks is only freed once they expire. From ef2a8cc2f3e05d214c1d82fb815a13d40f0d3834 Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Fri, 4 Dec 2026 20:51:20 +0100 Subject: [PATCH 15/24] perf(store): batch blocks to compress by count, not by number range A batch covered at most 100 block numbers, so where numbers are sparse it held about 1 block and a run rewrote about 90 blocks a second. Batches now take the next blocks by count, up to 10,000 and 32 MiB as stored, and always take every block of the numbers they cover. --- store/postgres/src/compress_blocks.rs | 69 ++++++--- store/test-store/tests/postgres/chain_head.rs | 132 +++++++++++++++++- 2 files changed, 179 insertions(+), 22 deletions(-) diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index b68146c7884..a00b7d9fc4d 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -20,9 +20,13 @@ use crate::pool::PermittedConnection; use crate::vid_batcher::AdaptiveBatchSize; use crate::{AsyncPgConnection, ConnectionPool, advisory_lock, catalog, copy}; -/// Blocks can be large, and we hold a whole batch in memory -const MAX_BATCH_SIZE: i64 = 100; +/// We hold a whole batch in memory, so a batch has at most this many blocks, +/// and ends once its blocks take up this many bytes as they are stored +const MAX_BATCH_SIZE: i64 = 10_000; +const MAX_BATCH_BYTES: i64 = 32 << 20; const INITIAL_BATCH_SIZE: i64 = 10; +/// Blocks we try again are few, and we look them up by hash +const RETRY_BATCH_SIZE: usize = 100; /// How long we want one batch to take const BATCH_DURATION: Duration = Duration::from_secs(1); @@ -699,20 +703,12 @@ impl BlocksCompressor { while state.progress.next_block <= state.progress.last_block { self.wait_until_clear(conn, reporter).await?; - // Skip over gaps in the block numbers - let first = number( - conn, - format!( - "select min(number) as number from {} where number >= {}", - self.blocks, state.progress.next_block - ), - ) - .await?; - let Some(first) = first.filter(|first| *first <= state.progress.last_block) else { + let Some((first, last)) = self + .next_batch(conn, &state.progress, pace.batch_size()) + .await? + else { break; }; - let last = (first + pace.batch_size() - 1).min(state.progress.last_block); - let batch = Batch::Numbers { first, last }; let done = self .rewrite(conn, req.compression, reporter, &batch, &mut state) @@ -1333,6 +1329,47 @@ impl BlocksCompressor { Ok(()) } + /// The numbers of the first and last of the next `size` blocks to rewrite, + /// fewer if they take up more than `MAX_BATCH_BYTES`. Counting blocks + /// rather than numbers keeps batches full where block numbers are sparse + async fn next_batch( + &self, + conn: &mut AsyncPgConnection, + progress: &CompressBlocksProgress, + size: i64, + ) -> Result, StoreError> { + #[derive(QueryableByName)] + struct Range { + #[diesel(sql_type = Nullable)] + first: Option, + #[diesel(sql_type = Nullable)] + last: Option, + } + + let range = sql_query(format!( + "select min(number) as first, max(number) as last + from (select number, + sum(size) over (order by number + rows between unbounded preceding + and 1 preceding) as before + from (select number, + pg_column_size(data) + + coalesce(pg_column_size({ZSTD}), 0) as size + from {} where number between $1 and $2 + order by number limit $3) b) s + where coalesce(before, 0) < $4", + self.blocks + )) + .bind::(progress.next_block) + .bind::(progress.last_block) + .bind::(size) + .bind::(MAX_BATCH_BYTES) + .get_result::(conn) + .await?; + // A batch covers every block with the numbers in it + Ok(range.first.zip(range.last)) + } + /// Read the blocks in `batch` with what we need to rewrite them with /// `compression` async fn read( @@ -1619,7 +1656,7 @@ impl BlocksCompressor { }) .await?; let hashes = state.retry.clone(); - for hashes in hashes.chunks(MAX_BATCH_SIZE as usize) { + for hashes in hashes.chunks(RETRY_BATCH_SIZE) { self.wait_until_clear(conn, reporter).await?; let batch = Batch::Hashes(hashes); let done = self @@ -1753,7 +1790,7 @@ mod tests { } assert_eq!(1, pace.batch_size()); // Fast batches get bigger, but no bigger than the maximum - for _ in 0..10 { + for _ in 0..20 { pace.adapt(secs(0.001), 0); } assert_eq!(MAX_BATCH_SIZE, pace.batch_size()); diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index eb64db5967e..dd61a9563d8 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -1611,6 +1611,125 @@ fn uncompress_blocks() { }) } +#[test] +fn compress_sparse_blocks_in_few_batches() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + // 2,000 blocks spread over 20,000,000 numbers, like the early blocks + // of a chain that nodes only fetched here and there + add_blocks(&store, &nsp, 100, 2_000, 0).await; + execute( + &store, + format!( + "update {nsp}.blocks set number = 100 + (number - 100) * 10000 + where number >= 100" + ), + ) + .await; + + let mut reporter = TestReporter::default(); + let progress = store + .compress_blocks(&compress_request(BlockCompression::Zstd(1)), &mut reporter) + .await + .unwrap(); + let batches = reporter + .steps + .iter() + .filter(|step| matches!(step, CompressBlocksStep::Read { .. })) + .count(); + let compressed = count_compressed(&store, &nsp).await; + reset_compress_blocks(&store, &nsp).await; + + assert_eq!(2_003, progress.blocks); + assert_eq!(2_003, compressed); + // Batches start small and grow while they are quick, whatever the + // gaps between the numbers of their blocks + assert!(batches <= 50, "{batches} batches"); + }) +} + +#[test] +fn keep_blocks_with_the_same_number_in_one_batch() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + // Every number from 100 to 139 has 2 blocks, so the first batch ends + // at a number that 2 blocks share + add_blocks(&store, &nsp, 100, 40, 0).await; + execute( + &store, + format!( + "insert into {nsp}.blocks(hash, number, parent_hash, data) + select sha256(hash), number, parent_hash, data + from {nsp}.blocks where number >= 100" + ), + ) + .await; + + let mut reporter = TestReporter::default(); + let progress = store + .compress_blocks(&compress_request(BlockCompression::Zstd(1)), &mut reporter) + .await + .unwrap(); + let reads: Vec<(i64, i64)> = reporter + .steps + .iter() + .filter_map(|step| match step { + CompressBlocksStep::Read { first, last } => Some((*first, *last)), + _ => None, + }) + .collect(); + let compressed = count_compressed(&store, &nsp).await; + reset_compress_blocks(&store, &nsp).await; + + assert_eq!(83, progress.blocks); + assert_eq!(83, compressed); + let end = reads[0].1; + assert!((100..140).contains(&end), "{reads:?}"); + assert!(reads[1].0 > end, "{reads:?}"); + }) +} + +#[test] +fn split_big_blocks_into_small_batches() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + // 10 blocks of 10 MB each are too much to hold in memory at once, + // even though a batch of 10 blocks is small by count + add_blocks(&store, &nsp, 100, 10, 10_000_000).await; + + let mut reporter = TestReporter::default(); + let progress = store + .compress_blocks(&compress_request(BlockCompression::Zstd(1)), &mut reporter) + .await + .unwrap(); + let with_100 = reporter.steps.iter().find_map(|step| match step { + CompressBlocksStep::Read { first, last } if *first <= 100 && 100 <= *last => { + Some(*last) + } + _ => None, + }); + let compressed = count_compressed(&store, &nsp).await; + reset_compress_blocks(&store, &nsp).await; + + assert_eq!(13, progress.blocks); + assert_eq!(13, compressed); + let last = with_100.expect("a batch held block 100"); + assert!(last < 106, "the batch with block 100 ended at {last}"); + }) +} + #[test] fn resume_compressing_blocks() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; @@ -1642,25 +1761,26 @@ fn resume_compressing_blocks() { else { panic!("compressing blocks did not stop"); }; - assert_eq!((10, 139), (status.next_block, status.last_block)); - assert_eq!(3, count_compressed(&store, &nsp).await); - let first_blocks = xmins(&store, &nsp, 10).await; + // The first batch holds 10 blocks: 0 to 2 and 100 to 106 + assert_eq!((107, 139), (status.next_block, status.last_block)); + assert_eq!(10, count_compressed(&store, &nsp).await); + let first_blocks = xmins(&store, &nsp, 107).await; // Continuing starts where the first run stopped and compresses every // other block once let mut reporter = TestReporter::default(); let progress = store.compress_blocks(&req, &mut reporter).await.unwrap(); - assert_eq!(40, progress.blocks); + assert_eq!(33, progress.blocks); assert!( matches!( reporter.steps[0], - CompressBlocksStep::Read { first: 100, .. } + CompressBlocksStep::Read { first: 107, .. } ), "{:?}", reporter.steps ); assert_eq!(43, count_compressed(&store, &nsp).await); - assert_eq!(first_blocks, xmins(&store, &nsp, 10).await); + assert_eq!(first_blocks, xmins(&store, &nsp, 107).await); execute( &store, format!("delete from {nsp}.blocks where number >= 100"), From dd7efbab6d29bf5bcf2b0b35ce83a02340f0111c Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Fri, 4 Dec 2026 23:26:26 +0100 Subject: [PATCH 16/24] perf(store): write batches of blocks on several connections at once A run read, compressed and wrote each batch in turn on 1 connection, waiting on the disk each time. Workers now write batches at once on connections of their own, and the saved progress stops before the first batch not yet written. The WAL limit now covers the server's WAL overall. --- node/src/manager/commands/compress_blocks.rs | 1 + store/postgres/src/compress_blocks.rs | 704 ++++++++++++++---- store/postgres/src/pool/mod.rs | 5 + store/test-store/tests/postgres/chain_head.rs | 329 ++++++++ 4 files changed, 904 insertions(+), 135 deletions(-) diff --git a/node/src/manager/commands/compress_blocks.rs b/node/src/manager/commands/compress_blocks.rs index 84ee3e7eb78..4aae83566ed 100644 --- a/node/src/manager/commands/compress_blocks.rs +++ b/node/src/manager/commands/compress_blocks.rs @@ -79,6 +79,7 @@ pub async fn run( compression, max_wal_rate: max_rate * MB, vacuum_every: vacuum_every.map(|gb| gb * GB), + jobs: 1, }; let progress = chain_store .compress_blocks(&req, &mut Reporter::new()) diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index a00b7d9fc4d..7c212a2f145 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -1,10 +1,11 @@ //! Compress blocks that are already in the block cache by rewriting each block -//! where it is stored, a batch at a time, while the chain is in use. A block -//! that a node changes while we work on it keeps what the node wrote +//! where it is stored, in batches that several connections write at once, while +//! the chain is in use. A block that a node changes meanwhile keeps its changes -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::fmt; use std::sync::atomic::{AtomicI32, Ordering}; +use std::sync::{Mutex, MutexGuard}; use std::time::{Duration, Instant}; use anyhow::anyhow; @@ -12,7 +13,9 @@ use async_trait::async_trait; use diesel::sql_query; use diesel::sql_types::{Array, BigInt, Bool, Bytea, Integer, Jsonb, Nullable, Text}; use diesel_async::{AsyncConnection as _, RunQueryDsl as _, SimpleAsyncConnection as _}; +use graph::futures03::future::{join, join_all}; use graph::prelude::{Error, Logger, StoreError, serde_json as json, warn}; +use tokio::sync::{mpsc, oneshot}; use crate::block_compression::{BlockCompression, decompress, is_placeholder}; use crate::chain_store::{Storage, ZSTD_COLUMN as ZSTD}; @@ -79,6 +82,8 @@ pub struct CompressBlocksRequest { /// Run VACUUM after rewriting this many bytes of blocks. By default, the /// size of the index of the TOAST table, but at least 1 GiB pub vacuum_every: Option, + /// How many batches to write at once, each on a connection of its own + pub jobs: usize, } /// How far compressing blocks has gotten @@ -104,7 +109,7 @@ pub struct CompressBlocksProgress { /// How much space these blocks took up before and after pub old_bytes: u64, pub new_bytes: u64, - /// How much WAL the database wrote while we rewrote these blocks + /// How much WAL the database wrote while this process ran pub wal_bytes: u64, } @@ -338,10 +343,15 @@ async fn number(conn: &mut AsyncPgConnection, query: String) -> Result(conn).await?.number) } -/// How much to do at once, and how long to pause after that +/// How much to do at once, and how long to pause so that the server writes +/// no more WAL than we allow struct Pace { batch_size: AdaptiveBatchSize, max_wal_rate: u64, + /// When we last looked at the server's WAL position, and where it was + looked: Option<(Instant, u64)>, + /// How long we still need to pause for the WAL written until then + owed: Duration, } impl Pace { @@ -351,6 +361,8 @@ impl Pace { Pace { batch_size, max_wal_rate: max_wal_rate.max(1), + looked: None, + owed: Duration::ZERO, } } @@ -358,19 +370,23 @@ impl Pace { self.batch_size.size } - /// How long to pause after something that took `elapsed` while the - /// database wrote `wal_bytes` of WAL so that it writes no more than - /// `max_wal_rate` bytes per second on average - fn pause(&self, elapsed: Duration, wal_bytes: u64) -> Duration { - Duration::from_secs_f64(wal_bytes as f64 / self.max_wal_rate as f64).saturating_sub(elapsed) - } - - /// Adjust the batch size after a batch that took `elapsed` while the - /// database wrote `wal_bytes`, and return how long to pause - fn adapt(&mut self, elapsed: Duration, wal_bytes: u64) -> Duration { + /// Adjust the batch size after a batch that took `elapsed` + fn adapt(&mut self, elapsed: Duration) { self.batch_size.adapt(elapsed); self.batch_size.size = self.batch_size.size.clamp(1, MAX_BATCH_SIZE); - self.pause(elapsed, wal_bytes) + } + + /// The server's WAL is at `lsn` at `now`. Return how much it wrote since + /// we last looked, and how long to pause so that it writes no more than + /// `max_wal_rate` bytes a second; writing less for a while earns nothing + fn wal(&mut self, now: Instant, lsn: u64) -> (u64, Duration) { + let Some((then, last)) = self.looked.replace((now, lsn)) else { + return (0, Duration::ZERO); + }; + let written = lsn.saturating_sub(last); + let needed = Duration::from_secs_f64(written as f64 / self.max_wal_rate as f64); + self.owed = (self.owed + needed).saturating_sub(now.saturating_duration_since(then)); + (written, self.owed) } } @@ -386,13 +402,99 @@ struct Done { blocks: usize, old_bytes: u64, new_bytes: u64, - /// The blocks that still need to be tried again + /// The blocks of the batch that need to be tried again retry: Vec>, /// How many blocks we could not convert failed: usize, - /// How long the batch took, and how much WAL the database wrote + /// How long the batch took elapsed: Duration, - wal_bytes: u64, +} + +/// What a worker tells the run +enum Event { + /// The worker reached a step, and waits until the reporter saw it + Step(CompressBlocksStep, oneshot::Sender>), + Message(String), + /// The worker is done with the batch that starts with block `first` + Done { + worker: usize, + first: i64, + res: Result, + }, +} + +/// Passes what a worker reports on to the run, which has the reporter +struct WorkerReporter { + events: mpsc::UnboundedSender, + logger: Logger, +} + +#[async_trait] +impl CompressBlocksReporter for WorkerReporter { + fn message(&mut self, msg: &str) { + // Nobody reads the events of a run that ended, so log the message + if self.events.send(Event::Message(msg.to_string())).is_err() { + warn!(self.logger, "{msg}"); + } + } + + fn progress(&mut self, _: &CompressBlocksProgress) {} + + async fn reached(&mut self, step: CompressBlocksStep) -> Result<(), StoreError> { + let stopped = || StoreError::from(anyhow!("the run stopped before it saw {step:?}")); + let (seen, wait) = oneshot::channel(); + self.events + .send(Event::Step(step, seen)) + .map_err(|_| stopped())?; + wait.await.map_err(|_| stopped())? + } +} + +/// The batches handed out to workers, and those of them whose progress we +/// still need to save +#[derive(Default)] +struct Batches { + /// Batches being written, by their first block, with their last + running: BTreeMap, + /// Batches written while an earlier one still ran, by their first block + written: BTreeMap, + /// The first block of the first batch that failed + failed: Option, +} + +impl Batches { + /// How many batches are past the progress we saved + fn len(&self) -> usize { + self.running.len() + self.written.len() + } + + /// The first block that is not written yet, when the batches handed out + /// so far end just before `next` + fn written_up_to(&self, next: i64) -> i64 { + self.running + .keys() + .copied() + .chain(self.failed) + .fold(next, i64::min) + } + + /// Take the written batches that start before `block` + fn take_before(&mut self, block: i64) -> Vec { + let later = self.written.split_off(&block); + std::mem::replace(&mut self.written, later) + .into_values() + .collect() + } +} + +/// A session of the database, which the microsecond it started at tells +/// apart from later sessions with the same process id +#[derive(QueryableByName)] +struct Session { + #[diesel(sql_type = Integer)] + pid: i32, + #[diesel(sql_type = BigInt)] + started: i64, } /// How many rows of a table were ever updated or deleted, and how many are @@ -419,6 +521,18 @@ struct State { counts_dead_rows: bool, } +impl State { + /// Count the blocks that a batch rewrote + fn wrote(&mut self, done: &Done) { + let progress = &mut self.progress; + progress.blocks += done.blocks; + progress.old_bytes += done.old_bytes; + progress.new_bytes += done.new_bytes; + self.since_vacuum += done.old_bytes; + self.rows_since_vacuum += done.blocks as u64; + } +} + /// Compress the blocks of a chain that has its own schema pub(crate) struct BlocksCompressor { nsp: String, @@ -433,6 +547,8 @@ pub(crate) struct BlocksCompressor { pool: ConnectionPool, /// The process id of our VACUUM while it runs, and 0 otherwise vacuum_pid: AtomicI32, + /// The sessions of our workers while they run + workers: Mutex>, } /// The connection of a run, which holds the lock that keeps two runs apart. @@ -502,6 +618,7 @@ impl BlocksCompressor { logger, pool, vacuum_pid: AtomicI32::new(0), + workers: Mutex::new(Vec::new()), }) } @@ -602,7 +719,10 @@ impl BlocksCompressor { reporter: &mut dyn CompressBlocksReporter, ) -> Result { let mut conn = CloseOnDrop(Some(conn)); - let res = self.run_on(&mut conn, req, reporter).await; + let res = match self.check_pool(req.jobs) { + Ok(()) => self.run_on(&mut conn, req, reporter).await, + Err(e) => Err(e), + }; conn.release(); res } @@ -616,6 +736,7 @@ impl BlocksCompressor { req: &CompressBlocksRequest, reporter: &mut dyn CompressBlocksReporter, ) -> Result { + self.check_pool(req.jobs)?; let mut conn = CloseOnDrop(Some(conn)); conn.get() .batch_execute(&format!("set role \"{role}\"")) @@ -644,21 +765,28 @@ impl BlocksCompressor { self.unlock(conn.get(), res).await } - /// Cancel our VACUUM and release the lock after the user pressed Ctrl-C; - /// every batch saved its progress when it was written. If that takes too - /// long or the user presses Ctrl-C again, close the connection instead + /// Stop what our workers and our VACUUM still do and release the lock + /// after the user pressed Ctrl-C; the run saved its progress as batches + /// were written. If that takes too long or Ctrl-C comes again, close async fn stop_after_interrupt( &self, conn: &mut CloseOnDrop, reporter: &mut dyn CompressBlocksReporter, ) -> Result { - let msg = "interrupted; the progress of every batch written so far is saved, and \ - running the command again continues from there"; + let msg = "interrupted; how far the run got is saved, and running the command again \ + continues from there"; let cleanup = async { reporter.reached(CompressBlocksStep::Stopping).await?; - let res = match self.cancel_dropped_vacuum().await { - Ok(()) => Err(anyhow!(msg).into()), - Err(e) => Err(anyhow!("{msg}; cancelling our VACUUM failed: {e:#}").into()), + let mut failures = Vec::new(); + if let Err(e) = self.cancel_dropped_workers().await { + failures.push(format!("stopping our workers failed: {e:#}")); + } + if let Err(e) = self.cancel_dropped_vacuum().await { + failures.push(format!("cancelling our VACUUM failed: {e:#}")); + } + let res = match failures.is_empty() { + true => Err(anyhow!(msg).into()), + false => Err(anyhow!("{msg}; {}", failures.join("; ")).into()), }; self.unlock(conn.get(), res).await }; @@ -700,28 +828,8 @@ impl BlocksCompressor { state.vacuum_every = self.vacuum_every(conn, req).await?; state.counts_dead_rows = self.counts_dead_rows(conn, reporter).await?; let mut pace = Pace::new(req.max_wal_rate); - while state.progress.next_block <= state.progress.last_block { - self.wait_until_clear(conn, reporter).await?; - - let Some((first, last)) = self - .next_batch(conn, &state.progress, pace.batch_size()) - .await? - else { - break; - }; - let batch = Batch::Numbers { first, last }; - let done = self - .rewrite(conn, req.compression, reporter, &batch, &mut state) - .await?; - state.progress.next_block = last + 1; - reporter.progress(&state.progress); - reporter - .reached(CompressBlocksStep::Written { - next_block: last + 1, - }) - .await?; - tokio::time::sleep(pace.adapt(done.elapsed, done.wal_bytes)).await; - self.vacuum_if_due(conn, reporter, &pace, &mut state) + if state.progress.next_block <= state.progress.last_block { + self.rewrite_all(conn, req, reporter, &mut state, &mut pace) .await?; } @@ -739,12 +847,13 @@ impl BlocksCompressor { reporter.progress(&state.progress); } - self.retry(conn, req, reporter, &mut state, &pace).await?; + self.retry(conn, req, reporter, &mut state, &mut pace) + .await?; // Make the space of the last blocks we rewrote available, too. Stopping // now would not keep the table from growing if state.since_vacuum > 0 { let held = self - .vacuum(conn, reporter, &pace, &mut state, false) + .vacuum(conn, reporter, &mut pace, &mut state, false) .await?; if let Some(held) = held { reporter.message(&format!( @@ -839,7 +948,7 @@ impl BlocksCompressor { &self, conn: &mut AsyncPgConnection, reporter: &mut dyn CompressBlocksReporter, - pace: &Pace, + pace: &mut Pace, state: &mut State, ) -> Result<(), StoreError> { if state.since_vacuum < state.vacuum_every { @@ -863,7 +972,7 @@ impl BlocksCompressor { &self, conn: &mut AsyncPgConnection, reporter: &mut dyn CompressBlocksReporter, - pace: &Pace, + pace: &mut Pace, state: &mut State, truncate: bool, ) -> Result, StoreError> { @@ -880,10 +989,7 @@ impl BlocksCompressor { }; let start = Instant::now(); - let wal_start = self.wal_lsn(conn).await?; let waiters = self.try_vacuum(conn, reporter, truncate).await?; - let wal_bytes = self.wal_lsn(conn).await?.saturating_sub(wal_start); - state.progress.wal_bytes += wal_bytes; if waiters.is_empty() { let rewritten = state.rows_since_vacuum; state.since_vacuum = 0; @@ -897,7 +1003,7 @@ impl BlocksCompressor { Some(before) => self.held_back(conn, &before, rewritten).await?, None => None, }; - tokio::time::sleep(pace.pause(start.elapsed(), wal_bytes)).await; + self.pause_for_wal(conn, pace, state).await?; return Ok(held); } @@ -1329,13 +1435,353 @@ impl BlocksCompressor { Ok(()) } - /// The numbers of the first and last of the next `size` blocks to rewrite, - /// fewer if they take up more than `MAX_BATCH_BYTES`. Counting blocks - /// rather than numbers keeps batches full where block numbers are sparse + /// Make sure the pool has a connection for the run, 1 for each worker and + /// 1 for VACUUM. With fewer, getting one fails partway through the run once + /// the pool's timeout passes + fn check_pool(&self, jobs: usize) -> Result<(), StoreError> { + let needed = jobs.max(1) + 2; + let size = self.pool.max_size()?; + if size >= needed { + return Ok(()); + } + Err(anyhow!( + "running {jobs} jobs needs {needed} connections, but the connection pool for {} \ + has only {size}; raise graphman's --pool-size to {needed} or more, or, with \ + --pool-size 0, the pool_size of its shard in the configuration", + self.blocks + ) + .into()) + } + + fn worker_sessions(&self) -> MutexGuard<'_, Vec> { + self.workers.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Rewrite the blocks from where the run stands, in batches that + /// `req.jobs` workers write at once, each on a connection of its own. The + /// progress we save never passes a batch that has not been written + async fn rewrite_all( + &self, + conn: &mut AsyncPgConnection, + req: &CompressBlocksRequest, + reporter: &mut dyn CompressBlocksReporter, + state: &mut State, + pace: &mut Pace, + ) -> Result<(), StoreError> { + let workers = match self.open_workers(conn, req.jobs.max(1), reporter).await { + Ok(workers) => workers, + Err(e) => { + self.worker_sessions().clear(); + return Err(e); + } + }; + let (events, received) = mpsc::unbounded_channel(); + let mut jobs = Vec::new(); + let mut runs = Vec::new(); + for (worker, worker_conn) in workers.into_iter().enumerate() { + let (job, next_job) = mpsc::channel(1); + jobs.push(job); + runs.push(self.work( + worker, + worker_conn, + next_job, + events.clone(), + req.compression, + state.counts_dead_rows, + )); + } + drop(events); + let handed_out = self.hand_out(conn, reporter, state, pace, jobs, received); + let (res, _) = join(handed_out, join_all(runs)).await; + self.worker_sessions().clear(); + res + } + + /// Open a connection for each of `jobs` workers that acts like `conn`: it + /// runs as the same role and waits as briefly for locks, and the server + /// stops what it does once we are gone + async fn open_workers( + &self, + conn: &mut AsyncPgConnection, + jobs: usize, + reporter: &mut dyn CompressBlocksReporter, + ) -> Result, StoreError> { + let role = text( + conn, + "select case when current_user = session_user then '' + else current_user::text end as res" + .to_string(), + ) + .await?; + let mut setup = format!("set lock_timeout = {}", LOCK_TIMEOUT.as_millis()); + if !role.is_empty() { + setup.push_str(&format!("; set role \"{role}\"")); + } + let check = format!( + "set client_connection_check_interval = {}", + CLIENT_CHECK_INTERVAL.as_millis() + ); + let mut check_failed = None; + let mut workers = Vec::with_capacity(jobs); + for _ in 0..jobs { + let mut worker = CloseOnDrop(Some(self.pool.get_permitted().await?)); + worker.get().batch_execute(&setup).await?; + if let Err(e) = worker.get().batch_execute(&check).await { + check_failed = Some(e); + } + let session = sql_query( + "select pid, (extract(epoch from backend_start) * 1000000)::int8 as started + from pg_stat_activity where pid = pg_backend_pid()", + ) + .get_result::(worker.get()) + .await?; + self.worker_sessions().push(session); + workers.push(worker); + } + if let Some(e) = check_failed { + reporter.message(&format!( + "the server can not stop our workers by itself if this process dies, since \ + setting client_connection_check_interval failed: {e}" + )); + } + Ok(workers) + } + + /// Write the batches that `jobs` hands us on `conn` until there are no + /// more, and tell the run about each through `events` + async fn work( + &self, + worker: usize, + mut conn: CloseOnDrop, + mut jobs: mpsc::Receiver<(i64, i64)>, + events: mpsc::UnboundedSender, + compression: BlockCompression, + flush_stats: bool, + ) { + let mut reporter = WorkerReporter { + events: events.clone(), + logger: self.logger.clone(), + }; + while let Some((first, last)) = jobs.recv().await { + let batch = Batch::Numbers { first, last }; + let mut res = self + .rewrite(conn.get(), compression, &mut reporter, &batch) + .await; + // VACUUM counts the dead rows it leaves as it ends, and by then + // needs to know about every row we made dead + if flush_stats && res.is_ok() { + let flushed = sql_query("select pg_stat_force_next_flush()") + .execute(conn.get()) + .await; + if let Err(e) = flushed { + res = Err(e.into()); + } + } + if events.send(Event::Done { worker, first, res }).is_err() { + break; + } + } + // Our settings must not reach whoever would get the connection next + conn.close(); + } + + /// Hand out batches in order of block number to the workers behind `jobs`, + /// with no more batches past the saved progress than there are workers. + /// Once VACUUM is due, wait for the batches handed out and then run it + async fn hand_out( + &self, + conn: &mut AsyncPgConnection, + reporter: &mut dyn CompressBlocksReporter, + state: &mut State, + pace: &mut Pace, + jobs: Vec>, + mut events: mpsc::UnboundedReceiver, + ) -> Result<(), StoreError> { + let mut idle: Vec = (0..jobs.len()).rev().collect(); + let mut batches = Batches::default(); + let mut next = state.progress.next_block; + let mut more = true; + let mut error = None; + loop { + while more + && error.is_none() + && batches.len() < jobs.len() + && state.since_vacuum < state.vacuum_every + && let Some(&worker) = idle.last() + { + self.wait_until_clear(conn, reporter).await?; + self.pause_for_wal(conn, pace, state).await?; + let size = pace.batch_size(); + let to = state.progress.last_block; + let Some((first, last)) = self.next_batch(conn, next, to, size).await? else { + more = false; + break; + }; + jobs[worker] + .send((first, last)) + .await + .map_err(|_| anyhow!("worker {worker} stopped"))?; + idle.pop(); + batches.running.insert(first, last); + next = last + 1; + } + if idle.len() == jobs.len() { + if let Some(e) = error { + return Err(e); + } + if state.since_vacuum >= state.vacuum_every { + self.vacuum_if_due(conn, reporter, pace, state).await?; + continue; + } + return Ok(()); + } + + let event = events + .recv() + .await + .ok_or_else(|| anyhow!("every worker stopped while it wrote a batch"))?; + match event { + Event::Message(msg) => reporter.message(&msg), + Event::Step(step, seen) => { + // A worker that stopped waiting has no use for the answer + let _ = seen.send(reporter.reached(step).await); + } + Event::Done { worker, first, res } => { + idle.push(worker); + batches.running.remove(&first); + match res { + Ok(done) => { + pace.adapt(done.elapsed); + state.wrote(&done); + batches.written.insert(first, done); + } + Err(e) => { + batches.failed = Some(batches.failed.map_or(first, |f| f.min(first))); + error.get_or_insert(e); + } + } + self.save(conn, reporter, state, &mut batches, next).await?; + } + } + } + } + + /// Save the progress of the batches written before the first that still + /// runs or failed, with the blocks they need to try again + async fn save( + &self, + conn: &mut AsyncPgConnection, + reporter: &mut dyn CompressBlocksReporter, + state: &mut State, + batches: &mut Batches, + next: i64, + ) -> Result<(), StoreError> { + let up_to = batches.written_up_to(next); + if up_to <= state.progress.next_block { + reporter.progress(&state.progress); + return Ok(()); + } + let mut failed = 0; + for done in batches.take_before(up_to) { + state.retry.extend(done.retry); + failed += done.failed; + } + state.progress.next_block = up_to; + state.progress.retry = state.retry.len(); + state.progress.failed += failed; + self.save_progress(conn, state, failed).await?; + reporter.progress(&state.progress); + reporter + .reached(CompressBlocksStep::Written { next_block: up_to }) + .await + } + + /// Save how far the run got and which blocks it needs to try again, and + /// count `failed` more blocks that could not be converted + async fn save_progress( + &self, + conn: &mut AsyncPgConnection, + state: &State, + failed: usize, + ) -> Result<(), StoreError> { + sql_query(format!( + "update {} set next_block = $1, retry = $2, failed = failed + $3 + where namespace = $4", + self.progress + )) + .bind::(state.progress.next_block) + .bind::, _>(&state.retry) + .bind::(failed as i64) + .bind::(&self.nsp) + .execute(conn) + .await?; + Ok(()) + } + + /// Pause as long as it takes to keep the server's WAL within our limit, + /// and count the WAL it wrote since we last looked + async fn pause_for_wal( + &self, + conn: &mut AsyncPgConnection, + pace: &mut Pace, + state: &mut State, + ) -> Result<(), StoreError> { + let lsn = self.wal_lsn(conn).await?; + let (written, pause) = pace.wal(Instant::now(), lsn); + state.progress.wal_bytes += written; + tokio::time::sleep(pause).await; + Ok(()) + } + + /// Stop what our workers still do, for when the work that drove them was + /// dropped, which closed their connections, and wait until their sessions + /// have ended + async fn cancel_dropped_workers(&self) -> Result<(), StoreError> { + let sessions = std::mem::take(&mut *self.worker_sessions()); + if sessions.is_empty() { + return Ok(()); + } + let pids: Vec = sessions.iter().map(|s| s.pid).collect(); + let started: Vec = sessions.iter().map(|s| s.started).collect(); + let ours = "from pg_stat_activity a + join unnest($1::int4[], $2::int8[]) as w(pid, started) + on a.pid = w.pid + and (extract(epoch from a.backend_start) * 1000000)::int8 = w.started"; + let mut conn = self.pool.get_permitted().await?; + sql_query(format!("select pg_cancel_backend(a.pid) {ours}")) + .bind::, _>(&pids) + .bind::, _>(&started) + .execute(&mut conn) + .await?; + let start = Instant::now(); + while sql_query(format!("select count(*) > 0 as running {ours}")) + .bind::, _>(&pids) + .bind::, _>(&started) + .get_result::(&mut conn) + .await? + .running + { + if start.elapsed() > CANCEL_WAIT { + return Err(anyhow!( + "the sessions of our workers ({pids:?}) did not end within {}s of \ + cancelling them", + CANCEL_WAIT.as_secs() + ) + .into()); + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + Ok(()) + } + + /// The numbers of the first and last of the next `size` blocks from `from` + /// to `to`, fewer if they take up more than `MAX_BATCH_BYTES`. Counting + /// blocks rather than numbers keeps batches full where numbers are sparse async fn next_batch( &self, conn: &mut AsyncPgConnection, - progress: &CompressBlocksProgress, + from: i64, + to: i64, size: i64, ) -> Result, StoreError> { #[derive(QueryableByName)] @@ -1360,8 +1806,8 @@ impl BlocksCompressor { where coalesce(before, 0) < $4", self.blocks )) - .bind::(progress.next_block) - .bind::(progress.last_block) + .bind::(from) + .bind::(to) .bind::(size) .bind::(MAX_BATCH_BYTES) .get_result::(conn) @@ -1408,19 +1854,15 @@ impl BlocksCompressor { Ok(rows) } - /// Rewrite the blocks in `batch` with `compression` and update the progress - /// of the run + /// Rewrite the blocks in `batch` with `compression` async fn rewrite( &self, conn: &mut AsyncPgConnection, compression: BlockCompression, reporter: &mut dyn CompressBlocksReporter, batch: &Batch<'_>, - state: &mut State, ) -> Result { let start = Instant::now(); - let wal_start = self.wal_lsn(conn).await?; - let rows = self.read(conn, batch, compression).await?; if let Batch::Numbers { first, last } = batch { reporter @@ -1430,33 +1872,9 @@ impl BlocksCompressor { }) .await?; } - // Blocks we try again leave the list of blocks to try again unless - // they need to be tried once more - let tried: HashSet> = match batch { - Batch::Numbers { .. } => rows.iter().map(|row| row.hash.clone()).collect(), - Batch::Hashes(hashes) => hashes.iter().cloned().collect(), - }; let (rewrites, failed) = Self::plan(rows, compression, reporter).await?; - let next_block = match batch { - Batch::Numbers { last, .. } => Some(last + 1), - Batch::Hashes(_) => None, - }; - - let mut done = self - .write(conn, rewrites, failed, next_block, &state.retry, &tried) - .await?; + let mut done = self.write(conn, rewrites, failed).await?; done.elapsed = start.elapsed(); - done.wal_bytes = self.wal_lsn(conn).await?.saturating_sub(wal_start); - state.retry = std::mem::take(&mut done.retry); - let progress = &mut state.progress; - progress.retry = state.retry.len(); - progress.blocks += done.blocks; - progress.failed += done.failed; - progress.old_bytes += done.old_bytes; - progress.new_bytes += done.new_bytes; - progress.wal_bytes += done.wal_bytes; - state.since_vacuum += done.old_bytes; - state.rows_since_vacuum += done.blocks as u64; Ok(done) } @@ -1490,15 +1908,12 @@ impl BlocksCompressor { /// Write `rewrites` in one short transaction without waiting for row locks, /// changing only rows nobody changed since we read them. Rows we could not - /// write are tried again; the blocks in `tried` leave the list `retry` + /// write need to be tried again async fn write( &self, conn: &mut AsyncPgConnection, rewrites: Vec, failed: usize, - next_block: Option, - retry: &[Vec], - tried: &HashSet>, ) -> Result { #[derive(QueryableByName)] struct Updated { @@ -1590,10 +2005,8 @@ impl BlocksCompressor { // Blocks that were deleted since we read them need no retry let not_written: Vec<_> = not_written.into_iter().collect(); - let still_there: Vec> = if not_written.is_empty() { - Vec::new() - } else { - sql_query(format!( + if !not_written.is_empty() { + done.retry = sql_query(format!( "select hash from {} where hash = any($1)", self.blocks )) @@ -1602,27 +2015,8 @@ impl BlocksCompressor { .await? .into_iter() .map(|h| h.hash) - .collect() - }; - done.retry = retry - .iter() - .filter(|hash| !tried.contains(*hash)) - .cloned() - .chain(still_there) .collect(); - - sql_query(format!( - "update {} set next_block = coalesce($1, next_block), retry = $2, - failed = failed + $3 - where namespace = $4", - self.progress - )) - .bind::, _>(next_block) - .bind::, _>(&done.retry) - .bind::(failed as i64) - .bind::(&self.nsp) - .execute(conn) - .await?; + } Ok(done) }) .await @@ -1636,7 +2030,7 @@ impl BlocksCompressor { req: &CompressBlocksRequest, reporter: &mut dyn CompressBlocksReporter, state: &mut State, - pace: &Pace, + pace: &mut Pace, ) -> Result<(), StoreError> { for attempt in 1..=RETRY_ATTEMPTS { if state.retry.is_empty() { @@ -1660,10 +2054,18 @@ impl BlocksCompressor { self.wait_until_clear(conn, reporter).await?; let batch = Batch::Hashes(hashes); let done = self - .rewrite(conn, req.compression, reporter, &batch, state) + .rewrite(conn, req.compression, reporter, &batch) .await?; + state.wrote(&done); + // Blocks we tried leave the list unless they need another try + let tried: HashSet<&Vec> = hashes.iter().collect(); + state.retry.retain(|hash| !tried.contains(hash)); + state.retry.extend(done.retry); + state.progress.retry = state.retry.len(); + state.progress.failed += done.failed; + self.save_progress(conn, state, done.failed).await?; reporter.progress(&state.progress); - tokio::time::sleep(pace.pause(done.elapsed, done.wal_bytes)).await; + self.pause_for_wal(conn, pace, state).await?; self.vacuum_if_due(conn, reporter, pace, state).await?; } } @@ -1774,29 +2176,61 @@ mod tests { fn pace_by_wal() { const MB: u64 = 1_000_000; let secs = Duration::from_secs_f64; + let start = Instant::now(); + let at = |s: f64| start + secs(s); let mut pace = Pace::new(20 * MB); - assert_eq!(INITIAL_BATCH_SIZE, pace.batch_size()); + // The first look only tells us where the WAL is + assert_eq!((0, Duration::ZERO), pace.wal(at(0.0), 100 * MB)); // Writing 40 MB of WAL in 0.5s needs a pause of 1.5s for 20 MB/s - assert_eq!(secs(1.5), pace.adapt(secs(0.5), 40 * MB)); + assert_eq!((40 * MB, secs(1.5)), pace.wal(at(0.5), 140 * MB)); + // After that pause, writing less than the limit needs no pause + assert_eq!((0, Duration::ZERO), pace.wal(at(2.0), 140 * MB)); + assert_eq!((10 * MB, Duration::ZERO), pace.wal(at(3.0), 150 * MB)); + // Writing nothing for a while does not allow writing more later + assert_eq!((0, Duration::ZERO), pace.wal(at(100.0), 150 * MB)); + assert_eq!((40 * MB, secs(1.5)), pace.wal(at(100.5), 190 * MB)); + + assert_eq!(INITIAL_BATCH_SIZE, pace.batch_size()); + pace.adapt(secs(0.5)); + assert_eq!(2 * INITIAL_BATCH_SIZE, pace.batch_size()); + pace.adapt(secs(1.0)); assert_eq!(2 * INITIAL_BATCH_SIZE, pace.batch_size()); - // Writing less than the limit needs no pause - assert_eq!(Duration::ZERO, pace.adapt(secs(1.0), 10 * MB)); // Slow batches get smaller, but never empty - pace.adapt(secs(4.0), 0); + pace.adapt(secs(4.0)); assert_eq!(INITIAL_BATCH_SIZE / 2, pace.batch_size()); for _ in 0..10 { - pace.adapt(secs(100.0), 0); + pace.adapt(secs(100.0)); } assert_eq!(1, pace.batch_size()); // Fast batches get bigger, but no bigger than the maximum for _ in 0..20 { - pace.adapt(secs(0.001), 0); + pace.adapt(secs(0.001)); } assert_eq!(MAX_BATCH_SIZE, pace.batch_size()); - // Pausing after a VACUUM does not change the batch size - assert_eq!(secs(2.0), pace.pause(Duration::ZERO, 40 * MB)); - assert_eq!(MAX_BATCH_SIZE, pace.batch_size()); + } + + #[test] + fn save_progress_up_to_the_first_unwritten_batch() { + let mut batches = Batches::default(); + batches.running.insert(10, 19); + batches.written.insert(20, Done::default()); + batches.running.insert(30, 39); + // Nothing before the batch that still runs + assert_eq!(10, batches.written_up_to(40)); + assert_eq!(0, batches.take_before(10).len()); + assert_eq!(3, batches.len()); + // Up to the next batch that runs once it is written + batches.running.remove(&10); + assert_eq!(30, batches.written_up_to(40)); + assert_eq!(1, batches.take_before(30).len()); + // A batch that failed stops the progress for good + batches.running.remove(&30); + batches.failed = Some(30); + assert_eq!(30, batches.written_up_to(40)); + batches.failed = None; + assert_eq!(40, batches.written_up_to(40)); + assert_eq!(0, batches.len()); } #[test] diff --git a/store/postgres/src/pool/mod.rs b/store/postgres/src/pool/mod.rs index 8dd87461a8a..b71d780eb83 100644 --- a/store/postgres/src/pool/mod.rs +++ b/store/postgres/src/pool/mod.rs @@ -508,6 +508,11 @@ impl ConnectionPool { self.get_ready()?.get_permitted().await } + /// The most connections this pool opens at once + pub(crate) fn max_size(&self) -> Result { + Ok(self.get_ready()?.pool.status().max_size) + } + /// Get a connection from the pool for foreign data wrapper access; /// since that pool can be very contended, periodically log that we are /// still waiting for a connection diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index dd61a9563d8..ba617071421 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -766,9 +766,28 @@ fn compress_request(compression: BlockCompression) -> CompressBlocksRequest { compression, max_wal_rate: 1_000_000_000_000, vacuum_every: None, + jobs: 1, } } +/// Store the blocks with `compression` in a new run with `jobs` workers +async fn compress_with_jobs( + store: &DieselChainStore, + namespace: &str, + jobs: usize, + compression: BlockCompression, +) -> CompressBlocksProgress { + reset_compress_blocks(store, namespace).await; + let req = CompressBlocksRequest { + jobs, + ..compress_request(compression) + }; + store + .compress_blocks(&req, &mut TestReporter::default()) + .await + .unwrap() +} + async fn compress_blocks( store: &DieselChainStore, compression: BlockCompression, @@ -1730,6 +1749,226 @@ fn split_big_blocks_into_small_batches() { }) } +#[test] +fn several_jobs_store_blocks_like_one() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + add_blocks(&store, &nsp, 100, 2_000, 1_000).await; + let stored = format!( + "select encode(hash, 'hex') || ' ' || md5(data::text) || ' ' + || coalesce(md5(data_zstd), '-') as name + from {nsp}.blocks order by hash" + ); + let original = names(&store, stored.clone()).await; + + let four = compress_with_jobs(&store, &nsp, 4, BlockCompression::Zstd(1)).await; + let with_four = names(&store, stored.clone()).await; + let undone = compress_with_jobs(&store, &nsp, 4, BlockCompression::None).await; + let uncompressed = names(&store, stored.clone()).await; + let one = compress_with_jobs(&store, &nsp, 1, BlockCompression::Zstd(1)).await; + let with_one = names(&store, stored).await; + execute( + &store, + format!("delete from {nsp}.blocks where number >= 100"), + ) + .await; + reset_compress_blocks(&store, &nsp).await; + + assert_eq!( + (2_003, 2_003, 2_003), + (four.blocks, undone.blocks, one.blocks) + ); + assert_ne!(original, with_four); + assert_eq!(with_one, with_four); + assert_eq!(original, uncompressed); + }) +} + +#[test] +fn batches_are_written_at_the_same_time() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + add_blocks(&store, &nsp, 100, 100, 0).await; + + // Writing a batch waits until another batch is being written, too + execute(&store, format!("create sequence {nsp}.arrivals")).await; + execute( + &store, + format!( + "create function {nsp}.meet() returns trigger language plpgsql as $$ + declare + deadline timestamptz := clock_timestamp() + interval '20 seconds'; + begin + if current_setting('compress_test.arrived', true) is distinct from 'yes' then + perform set_config('compress_test.arrived', 'yes', true); + perform nextval('{nsp}.arrivals'); + end if; + while (select case when is_called then last_value else 0 end + from {nsp}.arrivals) < 2 loop + if clock_timestamp() > deadline then + raise exception 'no other batch was written at the same time'; + end if; + perform pg_sleep(0.01); + end loop; + return new; + end $$" + ), + ) + .await; + execute( + &store, + format!( + "create trigger meet before update on {nsp}.blocks + for each row execute function {nsp}.meet()" + ), + ) + .await; + + let req = CompressBlocksRequest { + jobs: 2, + ..compress_request(BlockCompression::Zstd(1)) + }; + let res = store + .compress_blocks(&req, &mut TestReporter::default()) + .await; + execute(&store, format!("drop trigger meet on {nsp}.blocks")).await; + execute(&store, format!("drop function {nsp}.meet()")).await; + execute(&store, format!("drop sequence {nsp}.arrivals")).await; + let compressed = count_compressed(&store, &nsp).await; + execute( + &store, + format!("delete from {nsp}.blocks where number >= 100"), + ) + .await; + reset_compress_blocks(&store, &nsp).await; + + assert_eq!(103, res.unwrap().blocks); + assert_eq!(103, compressed); + }) +} + +#[test] +fn keep_progress_before_a_batch_that_failed() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + add_blocks(&store, &nsp, 100, 400, 1_000).await; + + // Writing block 150 fails once another worker wrote a later batch + execute( + &store, + format!( + "create function {nsp}.fail_150() returns trigger language plpgsql as $$ + declare + deadline timestamptz := clock_timestamp() + interval '20 seconds'; + begin + if new.number = 150 then + while not exists ( + select 1 from {nsp}.blocks + where number > 150 and data ? '__zstd' + and xmin::text::int8 + <> pg_current_xact_id()::text::int8 % 4294967296) + and clock_timestamp() < deadline loop + perform pg_sleep(0.01); + end loop; + raise exception 'writing block 150 failed'; + end if; + return new; + end $$" + ), + ) + .await; + execute( + &store, + format!( + "create trigger fail_150 before update on {nsp}.blocks + for each row execute function {nsp}.fail_150()" + ), + ) + .await; + + let req = CompressBlocksRequest { + jobs: 4, + ..compress_request(BlockCompression::Zstd(1)) + }; + let res = store + .compress_blocks(&req, &mut TestReporter::default()) + .await; + let later = names( + &store, + format!( + "select number::text as name from {nsp}.blocks + where number > 150 and data ? '__zstd'" + ), + ) + .await + .len(); + let status = store.compress_blocks_status().await.unwrap(); + execute(&store, format!("drop trigger fail_150 on {nsp}.blocks")).await; + execute(&store, format!("drop function {nsp}.fail_150()")).await; + + // Running again continues before the batch that failed + let rerun = store + .compress_blocks(&req, &mut TestReporter::default()) + .await; + let compressed = count_compressed(&store, &nsp).await; + execute( + &store, + format!("delete from {nsp}.blocks where number >= 100"), + ) + .await; + reset_compress_blocks(&store, &nsp).await; + + let err = res.unwrap_err().to_string(); + assert!(err.contains("writing block 150 failed"), "{err}"); + assert!(later > 0, "no later batch was written"); + let CompressBlocksStatus::Unfinished(status) = status else { + panic!("the run did not stop: {status:?}"); + }; + assert!(status.next_block <= 150, "saved {}", status.next_block); + rerun.unwrap(); + assert_eq!(403, compressed); + }) +} + +#[test] +fn refuse_more_jobs_than_the_pool_has_connections_for() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + + let req = CompressBlocksRequest { + jobs: 1_000, + ..compress_request(BlockCompression::Zstd(1)) + }; + let res = tokio::time::timeout( + Duration::from_secs(30), + store.compress_blocks(&req, &mut TestReporter::default()), + ) + .await; + let status = store.compress_blocks_status().await.unwrap(); + + let err = res.expect("the run did not end").unwrap_err().to_string(); + assert!(err.contains("needs 1002 connections"), "{err}"); + assert!(err.contains("--pool-size"), "{err}"); + assert_eq!(CompressBlocksStatus::NotStarted, status); + }) +} + #[test] fn resume_compressing_blocks() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; @@ -2183,6 +2422,96 @@ fn ctrl_c_twice_stops_at_once() { }) } +#[cfg(unix)] +#[test] +fn ctrl_c_stops_every_worker() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + add_blocks(&store, &nsp, 100, 100, 0).await; + + // Writing a batch hangs + execute( + &store, + format!( + "create function {nsp}.hang() returns trigger language plpgsql as $$ + begin + perform pg_sleep(20); + return new; + end $$" + ), + ) + .await; + execute( + &store, + format!( + "create trigger hang before update on {nsp}.blocks + for each row execute function {nsp}.hang()" + ), + ) + .await; + let hanging = "select pid::text as name from pg_stat_activity + where wait_event = 'PgSleep' and query like 'update%'" + .to_string(); + + // Once the first batch hangs, press Ctrl-C as the second batch is read + let mut reads = 0; + let mut reporter = TestReporter::with_hook({ + let (store, hanging) = (store.cheap_clone(), hanging.clone()); + move |step| { + if !matches!(step, CompressBlocksStep::Read { .. }) { + return async { Ok(()) }.boxed(); + } + reads += 1; + if reads != 2 { + return async { Ok(()) }.boxed(); + } + let (store, hanging) = (store.cheap_clone(), hanging.clone()); + async move { + for _ in 0..100 { + if !names(&store, hanging.clone()).await.is_empty() { + break; + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + press_ctrl_c(); + tokio::time::sleep(Duration::from_secs(60)).await; + Ok(()) + } + .boxed() + } + }); + let req = CompressBlocksRequest { + jobs: 2, + ..compress_request(BlockCompression::Zstd(1)) + }; + let start = Instant::now(); + let res = tokio::time::timeout( + Duration::from_secs(40), + store.compress_blocks(&req, &mut reporter), + ) + .await; + let waited = start.elapsed(); + let still_hanging = names(&store, hanging).await; + execute(&store, format!("drop trigger hang on {nsp}.blocks")).await; + execute(&store, format!("drop function {nsp}.hang()")).await; + execute( + &store, + format!("delete from {nsp}.blocks where number >= 100"), + ) + .await; + reset_compress_blocks(&store, &nsp).await; + + let err = res.expect("the run did not end").unwrap_err().to_string(); + assert!(err.contains("interrupted"), "{err}"); + assert_eq!(Vec::::new(), still_hanging); + assert!(waited < Duration::from_secs(15), "stopped after {waited:?}"); + }) +} + #[test] fn compress_blocks_adds_column() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; From 20ebed6fab26a97f504681bede50eea8ac050e5c Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Fri, 4 Dec 2026 23:30:51 +0100 Subject: [PATCH 17/24] feat(graphman): add --jobs to compress-blocks run, 4 by default graphman ran compress-blocks on 1 connection. --jobs sets how many connections write batches at once; graphman raises --pool-size to fit them, and the docs explain both. --- docs/graphman.md | 41 +++++++++++++------- node/src/bin/manager.rs | 38 +++++++++++++++--- node/src/manager/commands/compress_blocks.rs | 3 +- store/postgres/src/compress_blocks.rs | 15 +++++-- 4 files changed, 71 insertions(+), 26 deletions(-) diff --git a/docs/graphman.md b/docs/graphman.md index f277530ae12..1fd4b8990a1 100644 --- a/docs/graphman.md +++ b/docs/graphman.md @@ -397,14 +397,15 @@ this version, or run `graphman database migrate`, first. The command adds the co example because nodes hold locks on the table, the command stops and says why. Do not drop that column by hand while a node is running, since the node might use it. -`run` rewrites each block where it is stored, a batch at a time and in order of block number, and records how far -it got. It can be stopped at any point; running it again continues where it left off, unless it is run with a -different compression, which starts again from the first block. Every compressed block is checked to uncompress to -the original before it is written. A block that a node changes or locks while the command works on it keeps what -the node wrote, and is tried again at the end. Blocks that are still locked or changed after a few attempts, and -blocks that can not be converted, for example because their compressed data is damaged, are left as they are; -the command then ends with an error that says how many there are, and running it again tries them again. -`status` shows how far the last run got, and how many blocks it left as they were. +`run` rewrites each block where it is stored, in batches in order of block number that `--jobs` connections write +at once, and records how far it got: up to the first batch that is not written yet. It can be stopped at any point; +running it again continues where it left off, writing again at most the `--jobs` batches that came after that, +unless it is run with a different compression, which starts again from the first block. Every compressed block is +checked to uncompress to the original before it is written. A block that a node changes or locks while the command +works on it keeps what the node wrote, and is tried again at the end. Blocks that are still locked or changed after +a few attempts, and blocks that can not be converted, for example because their compressed data is damaged, are +left as they are; the command then ends with an error that says how many there are, and running it again tries them +again. `status` shows how far the last run got, and how many blocks it left as they were. Rewriting blocks frees the space that the old blocks took up inside the table, and the command runs `VACUUM` every so often so that later writes reuse that space. The table therefore grows by about twice the amount of blocks @@ -418,23 +419,28 @@ when it starts that it can not check. The files of the table do not get smaller, reused for new blocks. To limit the load on the database, the command limits how much WAL the server writes per second while it works, -and pauses while replicas fall behind. That limit counts all WAL the server writes, not only the command's own. +and pauses while replicas fall behind. That limit counts all WAL the server writes, not only the command's own, and +holds for all its connections together. Besides its `--jobs` connections, the command uses 1 connection of its own +and 1 for `VACUUM`, all from the connection pool of the chain's shard; `graphman` raises `--pool-size` to make +room for them, and with `--pool-size 0` the command stops before it starts if the shard's `pool_size` in the +configuration is too small. The `VACUUM` it runs stops when another session waits more than a second for a lock on the table, and tries again once nobody waits. Writing a batch never waits for a block that a node has locked, and the command stops with an error rather than wait more than 2 seconds for a lock on the table, since everybody who needs a conflicting lock would have to wait behind it; running it again continues where it stopped. Pressing Ctrl-C -stops the command after it has cancelled its `VACUUM`; each batch saves its progress when it is written, so -nothing more is lost than the batch being written. If cleaning up takes more than 30 seconds, for example because -the database does not answer, or Ctrl-C is pressed again, the command stops at once and closes its connection. If -the command dies without cancelling its `VACUUM`, the server stops it within a few seconds on systems where -Postgres supports `client_connection_check_interval`. +stops the command after it has cancelled what its connections were doing, including its `VACUUM`; nothing more is +lost than the batches being written. If cleaning up takes more than 30 seconds, for example because the database +does not answer, or Ctrl-C is pressed again, the command stops at once and closes its connections. If the command +dies without cancelling what its connections were doing, the server stops that within a few seconds on systems +where Postgres supports `client_connection_check_interval`. ### COSTS - Rewriting blocks writes much more WAL than the compressed blocks take up: about 1.6 times the old size of the rewritten blocks in a test with 20 GB of blocks. Replicas, WAL archives and backups that keep WAL get all of it. - At the default `--max-rate` of 20 MB/s that means about 22 hours per TB of blocks, again measured on test - data: the time is roughly the old size of the blocks times 1.6, divided by `--max-rate`. + data: the time is roughly the old size of the blocks times 1.6, divided by `--max-rate`. That needs enough + `--jobs` to reach `--max-rate`, since each job waits for the disk while it reads and writes a batch. - The disk needs room for the table to grow by up to twice `--vacuum-every`, which by default is the larger of 1 GiB and the size of the index of the `blocks` table's TOAST table, or half again as much for blocks of a few KB, whose TOAST chunks leave some space unused (plus, when uncompressing, the difference between the @@ -458,6 +464,7 @@ blocks again. - `--max-rate`: how many MB of WAL the server may write per second at most. The default is 20 - `--vacuum-every`: run `VACUUM` after rewriting this many GB of blocks. The default is the size of the index of the TOAST table of the `blocks` table, but at least 1 GiB, since each `VACUUM` reads all of that index +- `--jobs`: how many batches to write at once, each on a connection of its own. The default is 4 ### EXAMPLES @@ -465,6 +472,10 @@ Compress all blocks for mainnet: graphman --config config.toml chain compress-blocks mainnet run +Compress them with 8 connections, letting the server write up to 100 MB of WAL a second: + + graphman --config config.toml chain compress-blocks mainnet run --jobs 8 --max-rate 100 + # ⌘ Chain Call Cache Remove diff --git a/node/src/bin/manager.rs b/node/src/bin/manager.rs index 614736ec072..4f70735c995 100644 --- a/node/src/bin/manager.rs +++ b/node/src/bin/manager.rs @@ -28,8 +28,9 @@ use graph_node::{ MetricsContext, manager::deployment::DeploymentSearch, store_builder::StoreBuilder, }; use graph_store_postgres::{ - BlockCompression, BlockStore, ChainStore, ConnectionPool, NotificationSender, PRIMARY_SHARD, - PoolCoordinator, Shard, Store, SubgraphStore, SubscriptionManager, + BlockCompression, BlockStore, ChainStore, CompressBlocksRequest, ConnectionPool, + NotificationSender, PRIMARY_SHARD, PoolCoordinator, Shard, Store, SubgraphStore, + SubscriptionManager, }; use itertools::Itertools; use lazy_static::lazy_static; @@ -374,6 +375,18 @@ impl Command { fn use_configured_pool_size(&self) -> bool { matches!(self, Command::Config(_)) } + + /// How many connections to a shard the command uses at once, if that is + /// more than one + fn connections_needed(&self) -> Option { + match self { + Command::Chain(ChainCommand::CompressBlocks { + method: CompressBlocksCommand::Run { jobs, .. }, + .. + }) => Some(CompressBlocksRequest::connections_for(*jobs as usize) as u32), + _ => None, + } + } } #[derive(Clone, Debug, Subcommand)] @@ -626,6 +639,10 @@ pub enum CompressBlocksCommand { /// size of the index of the TOAST table, but at least 1 GiB #[clap(long, value_parser = clap::value_parser!(u64).range(1..))] vacuum_every: Option, + /// How many batches to write at once, each on a connection of its own; + /// --pool-size is raised to make room for them + #[clap(long, default_value = "4", value_parser = clap::value_parser!(u64).range(1..=1000))] + jobs: u64, }, /// Show how far the last run got Status, @@ -1187,11 +1204,19 @@ async fn main() -> anyhow::Result<()> { let mut config = Cfg::load(&logger, &opt.clone().into()).context("Configuration error")?; if opt.pool_size > 0 && !opt.cmd.use_configured_pool_size() { - // Override pool size from configuration + // Override pool size from configuration, with room for every + // connection the command uses at once + let pool_size = match opt.cmd.connections_needed() { + Some(needed) if needed > opt.pool_size => { + println!("raising --pool-size to {needed}, which this command needs"); + needed + } + _ => opt.pool_size, + }; for shard in config.stores.values_mut() { - shard.pool_size = PoolSize::Fixed(opt.pool_size); + shard.pool_size = PoolSize::Fixed(pool_size); for replica in shard.replicas.values_mut() { - replica.pool_size = PoolSize::Fixed(opt.pool_size); + replica.pool_size = PoolSize::Fixed(pool_size); } } } @@ -1581,7 +1606,8 @@ async fn main() -> anyhow::Result<()> { compression, max_rate, vacuum_every, - } => run(chain_store, compression, max_rate, vacuum_every).await, + jobs, + } => run(chain_store, compression, max_rate, vacuum_every, jobs).await, Status => status(chain_store).await, } } diff --git a/node/src/manager/commands/compress_blocks.rs b/node/src/manager/commands/compress_blocks.rs index 4aae83566ed..a5a235956ad 100644 --- a/node/src/manager/commands/compress_blocks.rs +++ b/node/src/manager/commands/compress_blocks.rs @@ -74,12 +74,13 @@ pub async fn run( compression: BlockCompression, max_rate: u64, vacuum_every: Option, + jobs: u64, ) -> Result<(), Error> { let req = CompressBlocksRequest { compression, max_wal_rate: max_rate * MB, vacuum_every: vacuum_every.map(|gb| gb * GB), - jobs: 1, + jobs: jobs as usize, }; let progress = chain_store .compress_blocks(&req, &mut Reporter::new()) diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index 7c212a2f145..3bd1f26cbc9 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -86,6 +86,14 @@ pub struct CompressBlocksRequest { pub jobs: usize, } +impl CompressBlocksRequest { + /// How many connections a run with `jobs` workers uses at once: 1 for + /// each worker, 1 of its own and 1 for VACUUM + pub fn connections_for(jobs: usize) -> usize { + jobs.max(1) + 2 + } +} + /// How far compressing blocks has gotten #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct CompressBlocksProgress { @@ -1435,11 +1443,10 @@ impl BlocksCompressor { Ok(()) } - /// Make sure the pool has a connection for the run, 1 for each worker and - /// 1 for VACUUM. With fewer, getting one fails partway through the run once - /// the pool's timeout passes + /// Make sure the pool has every connection the run needs, since it waits + /// for them without end fn check_pool(&self, jobs: usize) -> Result<(), StoreError> { - let needed = jobs.max(1) + 2; + let needed = CompressBlocksRequest::connections_for(jobs); let size = self.pool.max_size()?; if size >= needed { return Ok(()); From 599fefeb3bd4e9d4defbe7e1102700d3b758f5cb Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Fri, 4 Dec 2026 23:58:52 +0100 Subject: [PATCH 18/24] test(graphman): cover the pool size raise for compress-blocks run graphman raises --pool-size for compress-blocks run so that every job gets a connection. That choice now sits in a function of its own, and a test checks it for several option values. --- node/src/bin/manager.rs | 59 ++++++++++++++++++++++++++++++++++------- 1 file changed, 49 insertions(+), 10 deletions(-) diff --git a/node/src/bin/manager.rs b/node/src/bin/manager.rs index 4f70735c995..0d753069b3e 100644 --- a/node/src/bin/manager.rs +++ b/node/src/bin/manager.rs @@ -1203,16 +1203,10 @@ async fn main() -> anyhow::Result<()> { ); let mut config = Cfg::load(&logger, &opt.clone().into()).context("Configuration error")?; - if opt.pool_size > 0 && !opt.cmd.use_configured_pool_size() { - // Override pool size from configuration, with room for every - // connection the command uses at once - let pool_size = match opt.cmd.connections_needed() { - Some(needed) if needed > opt.pool_size => { - println!("raising --pool-size to {needed}, which this command needs"); - needed - } - _ => opt.pool_size, - }; + if let Some(pool_size) = pool_size_override(opt.pool_size, &opt.cmd) { + if pool_size > opt.pool_size { + println!("raising --pool-size to {pool_size}, which this command needs"); + } for shard in config.stores.values_mut() { shard.pool_size = PoolSize::Fixed(pool_size); for replica in shard.replicas.values_mut() { @@ -1876,6 +1870,18 @@ async fn main() -> anyhow::Result<()> { } } +/// The size that `--pool-size` gives every pool, raised to the connections the +/// command uses at once, or `None` to keep the sizes in the configuration +fn pool_size_override(pool_size: u32, cmd: &Command) -> Option { + if pool_size == 0 || cmd.use_configured_pool_size() { + return None; + } + Some( + cmd.connections_needed() + .map_or(pool_size, |needed| needed.max(pool_size)), + ) +} + fn parse_duration_in_secs(s: &str) -> Result { Ok(Duration::from_secs(s.parse()?)) } @@ -1892,3 +1898,36 @@ fn make_deployment_selector( DeploymentSearch::Deployment { namespace } => Schema(namespace), } } + +#[cfg(test)] +mod tests { + use super::*; + + /// The pool size graphman uses when it is run with `args` + fn pool_size(args: &[&str]) -> Option { + let opt = Opt::try_parse_from(["graphman", "--config", "config.toml"].iter().chain(args)) + .unwrap(); + pool_size_override(opt.pool_size, &opt.cmd) + } + + #[test] + fn compress_blocks_run_raises_the_pool_size() { + let run = ["chain", "compress-blocks", "mainnet", "run"]; + let with = |extra: &[&'static str]| [&run[..], extra].concat(); + + // A connection for each of the 4 jobs by default, 1 for the run and + // 1 for VACUUM + assert_eq!(Some(6), pool_size(&run)); + assert_eq!(Some(10), pool_size(&with(&["--jobs", "8"]))); + assert_eq!(Some(3), pool_size(&with(&["--jobs", "1"]))); + // A larger --pool-size stays, and 0 keeps the configured sizes + assert_eq!( + Some(20), + pool_size(&[&["--pool-size", "20"], &run[..]].concat()) + ); + assert_eq!(None, pool_size(&[&["--pool-size", "0"], &run[..]].concat())); + // Other commands get --pool-size as it is + let status = ["chain", "compress-blocks", "mainnet", "status"]; + assert_eq!(Some(3), pool_size(&status)); + } +} From 30112c1d928150e5019a9298aabe060be01ee57d Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Sat, 5 Dec 2026 00:19:02 +0100 Subject: [PATCH 19/24] fix(store): size each batch from the size it was handed out at With several jobs a batch ends after later ones went out at other sizes, so one timing changed the size several times over and batches swung between tiny and huge. The next size now starts from the size of the batch that ended. --- store/postgres/src/compress_blocks.rs | 70 +++++++++++++++++++++------ 1 file changed, 56 insertions(+), 14 deletions(-) diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index 3bd1f26cbc9..20373d46978 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -378,8 +378,11 @@ impl Pace { self.batch_size.size } - /// Adjust the batch size after a batch that took `elapsed` - fn adapt(&mut self, elapsed: Duration) { + /// Adjust the batch size after a batch of `size` blocks took `elapsed`. + /// With several jobs, batches end long after later ones were handed out + /// at other sizes, so start from the size this batch had + fn adapt(&mut self, size: i64, elapsed: Duration) { + self.batch_size.size = size; self.batch_size.adapt(elapsed); self.batch_size.size = self.batch_size.size.clamp(1, MAX_BATCH_SIZE); } @@ -462,8 +465,9 @@ impl CompressBlocksReporter for WorkerReporter { /// still need to save #[derive(Default)] struct Batches { - /// Batches being written, by their first block, with their last - running: BTreeMap, + /// Batches being written, by their first block, with their last block and + /// the size they were handed out at + running: BTreeMap, /// Batches written while an earlier one still ran, by their first block written: BTreeMap, /// The first block of the first batch that failed @@ -1629,7 +1633,7 @@ impl BlocksCompressor { .await .map_err(|_| anyhow!("worker {worker} stopped"))?; idle.pop(); - batches.running.insert(first, last); + batches.running.insert(first, (last, size)); next = last + 1; } if idle.len() == jobs.len() { @@ -1655,10 +1659,14 @@ impl BlocksCompressor { } Event::Done { worker, first, res } => { idle.push(worker); - batches.running.remove(&first); + let Some((_, size)) = batches.running.remove(&first) else { + return Err( + anyhow!("worker {worker} wrote a batch it was not given").into() + ); + }; match res { Ok(done) => { - pace.adapt(done.elapsed); + pace.adapt(size, done.elapsed); state.wrote(&done); batches.written.insert(first, done); } @@ -2198,31 +2206,65 @@ mod tests { assert_eq!((0, Duration::ZERO), pace.wal(at(100.0), 150 * MB)); assert_eq!((40 * MB, secs(1.5)), pace.wal(at(100.5), 190 * MB)); + let adapt = |pace: &mut Pace, elapsed| pace.adapt(pace.batch_size(), elapsed); assert_eq!(INITIAL_BATCH_SIZE, pace.batch_size()); - pace.adapt(secs(0.5)); + adapt(&mut pace, secs(0.5)); assert_eq!(2 * INITIAL_BATCH_SIZE, pace.batch_size()); - pace.adapt(secs(1.0)); + adapt(&mut pace, secs(1.0)); assert_eq!(2 * INITIAL_BATCH_SIZE, pace.batch_size()); // Slow batches get smaller, but never empty - pace.adapt(secs(4.0)); + adapt(&mut pace, secs(4.0)); assert_eq!(INITIAL_BATCH_SIZE / 2, pace.batch_size()); for _ in 0..10 { - pace.adapt(secs(100.0)); + adapt(&mut pace, secs(100.0)); } assert_eq!(1, pace.batch_size()); // Fast batches get bigger, but no bigger than the maximum for _ in 0..20 { - pace.adapt(secs(0.001)); + adapt(&mut pace, secs(0.001)); } assert_eq!(MAX_BATCH_SIZE, pace.batch_size()); } + #[test] + fn batch_size_settles_with_several_jobs() { + // Hand out batches to 4 workers like the run does, where a batch takes + // 5ms plus 1ms per block, and finish them in the order they end + let ms = |n: i64| Duration::from_millis(n as u64); + let mut pace = Pace::new(u64::MAX); + let mut now = Duration::ZERO; + // When each running batch started, and its size + let mut running: Vec<(Duration, i64)> = Vec::new(); + let mut took = Vec::new(); + for _ in 0..400 { + while running.len() < 4 { + running.push((now, pace.batch_size())); + } + let ends = |(start, size): &(Duration, i64)| *start + ms(5 + size); + let first = (0..running.len()) + .min_by_key(|i| ends(&running[*i])) + .unwrap(); + let (start, size) = running.remove(first); + now = start + ms(5 + size); + pace.adapt(size, now - start); + took.push(now - start); + } + // Once settled, every batch takes about the 1s we aim for + for elapsed in &took[200..] { + assert!( + (ms(800)..=ms(1250)).contains(elapsed), + "{elapsed:?} in {:?}", + &took[200..] + ); + } + } + #[test] fn save_progress_up_to_the_first_unwritten_batch() { let mut batches = Batches::default(); - batches.running.insert(10, 19); + batches.running.insert(10, (19, 10)); batches.written.insert(20, Done::default()); - batches.running.insert(30, 39); + batches.running.insert(30, (39, 10)); // Nothing before the batch that still runs assert_eq!(10, batches.written_up_to(40)); assert_eq!(0, batches.take_before(10).len()); From 6386c13a7d6a88f8d3aa6d8d8debbba0b0dbfb8e Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Sat, 5 Dec 2026 00:20:23 +0100 Subject: [PATCH 20/24] fix(store): leave the wait for the run out of a batch's time A worker waits after reading its batch until the run answers, which can take long while the run pauses for the WAL limit or for replicas. Counting that wait shrank batches for no reason; the time of a batch now covers only its own work. --- store/postgres/src/compress_blocks.rs | 7 ++- store/test-store/tests/postgres/chain_head.rs | 50 +++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index 20373d46978..073ef10743d 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -1879,17 +1879,22 @@ impl BlocksCompressor { ) -> Result { let start = Instant::now(); let rows = self.read(conn, batch, compression).await?; + // A worker waits here until the run has time for it, which says + // nothing about how big the next batch can be + let mut waited = Duration::ZERO; if let Batch::Numbers { first, last } = batch { + let asked = Instant::now(); reporter .reached(CompressBlocksStep::Read { first: *first, last: *last, }) .await?; + waited = asked.elapsed(); } let (rewrites, failed) = Self::plan(rows, compression, reporter).await?; let mut done = self.write(conn, rewrites, failed).await?; - done.elapsed = start.elapsed(); + done.elapsed = start.elapsed().saturating_sub(waited); Ok(done) } diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index ba617071421..8a2cdcdfbc7 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -1855,6 +1855,56 @@ fn batches_are_written_at_the_same_time() { }) } +#[test] +fn time_only_the_work_of_a_batch() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + add_blocks(&store, &nsp, 100, 100, 1_000).await; + + // The run takes 2s to answer that the first batch was read + let mut held = false; + let mut reporter = TestReporter::with_hook(move |step| { + let now = !held && matches!(step, CompressBlocksStep::Read { .. }); + held |= now; + async move { + if now { + tokio::time::sleep(Duration::from_secs(2)).await; + } + Ok(()) + } + .boxed() + }); + let res = store + .compress_blocks(&compress_request(BlockCompression::Zstd(1)), &mut reporter) + .await; + execute( + &store, + format!("delete from {nsp}.blocks where number >= 100"), + ) + .await; + reset_compress_blocks(&store, &nsp).await; + res.unwrap(); + + // The first batch has 10 blocks, 0 to 2 and 100 to 106, and waiting + // for the run must not make the next one smaller + let reads: Vec<(i64, i64)> = reporter + .steps + .iter() + .filter_map(|step| match step { + CompressBlocksStep::Read { first, last } => Some((*first, *last)), + _ => None, + }) + .collect(); + assert_eq!((0, 106), reads[0], "{reads:?}"); + let (first, last) = reads[1]; + assert!(last - first + 1 >= 10, "{reads:?}"); + }) +} + #[test] fn keep_progress_before_a_batch_that_failed() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; From d57fa142a14c871c51e2460fd7afb9d2226a64fc Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Sat, 5 Dec 2026 00:21:47 +0100 Subject: [PATCH 21/24] feat(store): say at the end how much WAL the server wrote during a run Progress lines count WAL only up to the batch before them, so the WAL of the last batches and the last VACUUM never showed. The run now counts it at the end and prints the total. --- store/postgres/src/compress_blocks.rs | 25 ++++++++++- store/test-store/tests/postgres/chain_head.rs | 45 +++++++++++++++++++ 2 files changed, 68 insertions(+), 2 deletions(-) diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index 073ef10743d..7f3dc310f0c 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -63,6 +63,8 @@ const STOP_TIMEOUT: Duration = Duration::from_secs(30); /// Marks the statement of our VACUUM so that we never cancel anything else const VACUUM_MARKER: &str = "/* graph-node compress-blocks */"; +const MB: u64 = 1_000_000; + /// The table that a database migration creates for the progress of each /// chain's run const PROGRESS_TABLE: &str = "public.compress_blocks_progress"; @@ -873,6 +875,13 @@ impl BlocksCompressor { )); } } + // The last report of our progress came before the last batches and + // VACUUM wrote their WAL + self.meter_wal(conn, &mut pace, &mut state).await?; + reporter.message(&format!( + "the server wrote {} MB of WAL during the run", + state.progress.wal_bytes / MB + )); Self::left_as_they_were(state.progress) } @@ -1741,11 +1750,23 @@ impl BlocksCompressor { pace: &mut Pace, state: &mut State, ) -> Result<(), StoreError> { + let pause = self.meter_wal(conn, pace, state).await?; + tokio::time::sleep(pause).await; + Ok(()) + } + + /// Count the WAL the server wrote since we last looked, and return how + /// long to pause to keep it within our limit + async fn meter_wal( + &self, + conn: &mut AsyncPgConnection, + pace: &mut Pace, + state: &mut State, + ) -> Result { let lsn = self.wal_lsn(conn).await?; let (written, pause) = pace.wal(Instant::now(), lsn); state.progress.wal_bytes += written; - tokio::time::sleep(pause).await; - Ok(()) + Ok(pause) } /// Stop what our workers still do, for when the work that drove them was diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index 8a2cdcdfbc7..ba93551061d 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -1905,6 +1905,51 @@ fn time_only_the_work_of_a_batch() { }) } +#[test] +fn report_the_wal_of_the_whole_run() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + add_blocks(&store, &nsp, 100, 200, 4_000).await; + let lsn = async || { + let query = "select pg_wal_lsn_diff(pg_current_wal_lsn(), '0/0')::int8::text as name"; + names(&store, query.to_string()).await[0] + .parse::() + .unwrap() + }; + + let before = lsn().await; + let mut reporter = TestReporter::default(); + let res = store + .compress_blocks(&compress_request(BlockCompression::Zstd(1)), &mut reporter) + .await; + let run = lsn().await - before; + execute( + &store, + format!("delete from {nsp}.blocks where number >= 100"), + ) + .await; + reset_compress_blocks(&store, &nsp).await; + + // The total covers the WAL up to the end of the run, after its last + // VACUUM, and a message says what it is + let wal = res.unwrap().wal_bytes; + assert!(wal <= run && wal + 100_000 >= run, "{wal} of {run}"); + let total = format!( + "the server wrote {} MB of WAL during the run", + wal / 1_000_000 + ); + assert!( + reporter.messages.contains(&total), + "{:?}", + reporter.messages + ); + }) +} + #[test] fn keep_progress_before_a_batch_that_failed() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; From 0980491ab3970426923898135413d26997824f9e Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Sat, 5 Dec 2026 00:22:48 +0100 Subject: [PATCH 22/24] fix(store): report every batch that fails, not only the first When several workers fail at once, the run ended with the first error and said nothing about the others. It still ends with the first, and now prints each of the others as it arrives. --- store/postgres/src/compress_blocks.rs | 9 ++- store/test-store/tests/postgres/chain_head.rs | 60 +++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index 7f3dc310f0c..3a53ed9238c 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -1681,7 +1681,14 @@ impl BlocksCompressor { } Err(e) => { batches.failed = Some(batches.failed.map_or(first, |f| f.min(first))); - error.get_or_insert(e); + // Only the first error ends the run, so say what the + // others were + match &error { + None => error = Some(e), + Some(_) => reporter.message(&format!( + "writing the batch from block {first} on failed, too: {e}" + )), + } } } self.save(conn, reporter, state, &mut batches, next).await?; diff --git a/store/test-store/tests/postgres/chain_head.rs b/store/test-store/tests/postgres/chain_head.rs index ba93551061d..91319c86622 100644 --- a/store/test-store/tests/postgres/chain_head.rs +++ b/store/test-store/tests/postgres/chain_head.rs @@ -1950,6 +1950,66 @@ fn report_the_wal_of_the_whole_run() { }) } +#[test] +fn report_every_batch_that_failed() { + let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; + run_test_async(chain, |store, _, _| async move { + let Some(nsp) = private_namespace(&store).await else { + return; + }; + reset_compress_blocks(&store, &nsp).await; + add_blocks(&store, &nsp, 100, 100, 1_000).await; + + // Of the first 4 batches of 10 blocks, the second and third fail + execute( + &store, + format!( + "create function {nsp}.fail_some() returns trigger language plpgsql as $$ + begin + if new.number in (110, 120) then + raise exception 'writing block % failed', new.number; + end if; + return new; + end $$" + ), + ) + .await; + execute( + &store, + format!( + "create trigger fail_some before update on {nsp}.blocks + for each row execute function {nsp}.fail_some()" + ), + ) + .await; + + let req = CompressBlocksRequest { + jobs: 4, + ..compress_request(BlockCompression::Zstd(1)) + }; + let mut reporter = TestReporter::default(); + let res = store.compress_blocks(&req, &mut reporter).await; + execute(&store, format!("drop trigger fail_some on {nsp}.blocks")).await; + execute(&store, format!("drop function {nsp}.fail_some()")).await; + execute( + &store, + format!("delete from {nsp}.blocks where number >= 100"), + ) + .await; + reset_compress_blocks(&store, &nsp).await; + + // The run fails with 1 of the errors and reports the other + let err = res.unwrap_err().to_string(); + let said = format!("{err}\n{}", reporter.messages.join("\n")); + for block in [110, 120] { + assert!( + said.contains(&format!("writing block {block} failed")), + "{said}" + ); + } + }) +} + #[test] fn keep_progress_before_a_batch_that_failed() { let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO]; From 92dcf9031a9a90f1e2e909583cc784761280fcde Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Sat, 5 Dec 2026 00:23:08 +0100 Subject: [PATCH 23/24] docs(graphman): count the batches still running in the disk room needed Once a run has rewritten --vacuum-every of blocks, the batches other jobs are writing still finish before VACUUM runs, so the table can grow by up to --jobs minus 1 batches more. --- docs/graphman.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/graphman.md b/docs/graphman.md index 1fd4b8990a1..8523fa6e088 100644 --- a/docs/graphman.md +++ b/docs/graphman.md @@ -441,7 +441,8 @@ where Postgres supports `client_connection_check_interval`. - At the default `--max-rate` of 20 MB/s that means about 22 hours per TB of blocks, again measured on test data: the time is roughly the old size of the blocks times 1.6, divided by `--max-rate`. That needs enough `--jobs` to reach `--max-rate`, since each job waits for the disk while it reads and writes a batch. -- The disk needs room for the table to grow by up to twice `--vacuum-every`, which by default is the larger of +- The disk needs room for the table to grow by up to twice `--vacuum-every`, plus the batches still being written + when that is reached: up to `--jobs` minus 1 of at most 32 MiB each. `--vacuum-every` is by default the larger of 1 GiB and the size of the index of the `blocks` table's TOAST table, or half again as much for blocks of a few KB, whose TOAST chunks leave some space unused (plus, when uncompressing, the difference between the uncompressed and compressed size of the blocks), and `pg_wal` room for the WAL written until the next From 6ac43e9398383ff8ab004c768219ccd4cb979348 Mon Sep 17 00:00:00 2001 From: Samuel Metcalfe Date: Sat, 5 Dec 2026 00:23:22 +0100 Subject: [PATCH 24/24] docs(store): say how long getting a connection for a run can wait The comment on the pool check said a run waits without end for its connections. It waits without end only for a permit, and then gives up after GRAPH_STORE_CONNECTION_TIMEOUT. --- store/postgres/src/compress_blocks.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/store/postgres/src/compress_blocks.rs b/store/postgres/src/compress_blocks.rs index 3a53ed9238c..3d110d041a6 100644 --- a/store/postgres/src/compress_blocks.rs +++ b/store/postgres/src/compress_blocks.rs @@ -1456,8 +1456,9 @@ impl BlocksCompressor { Ok(()) } - /// Make sure the pool has every connection the run needs, since it waits - /// for them without end + /// Make sure the pool has every connection the run needs. With fewer, getting + /// one waits without end for a permit, and then fails once it waited longer than + /// GRAPH_STORE_CONNECTION_TIMEOUT for a connection, which marks the pool unavailable fn check_pool(&self, jobs: usize) -> Result<(), StoreError> { let needed = CompressBlocksRequest::connections_for(jobs); let size = self.pool.max_size()?;