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/docs/graphman.md b/docs/graphman.md
index 8c857703dda..8523fa6e088 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,118 @@ 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 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; 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, 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
+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, 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 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`. 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`, 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
+ 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
+- `--jobs`: how many batches to write at once, each on a connection of its own. The default is 4
+
+### EXAMPLES
+
+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 28cedcd4e28..0d753069b3e 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::{
- 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)]
@@ -555,6 +568,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 +623,31 @@ 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,
+ /// 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,
+ /// 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,
+}
+
#[derive(Clone, Debug, Subcommand)]
pub enum CallCacheCommand {
/// Remove the call cache of the specified chain.
@@ -1153,12 +1203,14 @@ 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
+ 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(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);
}
}
}
@@ -1539,6 +1591,20 @@ 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,
+ vacuum_every,
+ jobs,
+ } => run(chain_store, compression, max_rate, vacuum_every, jobs).await,
+ Status => status(chain_store).await,
+ }
+ }
Truncate { chain_name, force } => {
use commands::check_blocks::truncate;
let chain_store = ctx.chain_store(&chain_name).await?;
@@ -1804,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()?))
}
@@ -1820,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));
+ }
+}
diff --git a/node/src/manager/commands/compress_blocks.rs b/node/src/manager/commands/compress_blocks.rs
new file mode 100644
index 00000000000..a5a235956ad
--- /dev/null
+++ b/node/src/manager/commands/compress_blocks.rs
@@ -0,0 +1,135 @@
+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;
+const GB: u64 = 1_000_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,
+ 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: jobs as usize,
+ };
+ let progress = chain_store
+ .compress_blocks(&req, &mut Reporter::new())
+ .await?;
+ println!(
+ "stored the blocks for {} with {}",
+ chain_store.chain, progress.compression
+ );
+ 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
+ );
+ }
+ left_as_they_were(&progress);
+ }
+ CompressBlocksStatus::Finished(progress) => {
+ println!(
+ "finished; all blocks up to {} are stored with {}",
+ progress.last_block, progress.compression
+ );
+ 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/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/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/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..a1cb8ce8de2 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};
@@ -123,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 {
@@ -303,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";
@@ -421,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")
}
@@ -1095,6 +1122,29 @@ 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
@@ -1113,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
@@ -1142,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,
@@ -3234,6 +3292,51 @@ 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?;
+ 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
+ /// with `req.compression`
+ pub async fn compress_blocks(
+ &self,
+ req: &CompressBlocksRequest,
+ reporter: &mut dyn CompressBlocksReporter,
+ ) -> Result {
+ let (compressor, conn) = self.blocks_compressor().await?;
+ 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
+ }
+
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..3d110d041a6
--- /dev/null
+++ b/store/postgres/src/compress_blocks.rs
@@ -0,0 +1,2324 @@
+//! Compress blocks that are already in the block cache by rewriting each block
+//! 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::{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;
+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};
+use crate::pool::PermittedConnection;
+use crate::vid_batcher::AdaptiveBatchSize;
+use crate::{AsyncPgConnection, ConnectionPool, advisory_lock, catalog, copy};
+
+/// 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);
+
+/// 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);
+
+/// 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);
+
+/// 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;
+/// 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);
+/// 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 */";
+
+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);
+/// 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
+ /// uncompressed
+ 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 many batches to write at once, each on a connection of its own
+ 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 {
+ /// 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 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
+ pub old_bytes: u64,
+ pub new_bytes: u64,
+ /// How much WAL the database wrote while this process ran
+ 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),
+ /// Our VACUUM gave way to these sessions that waited for a lock
+ VacuumGaveWay { table: String, waiters: Vec },
+ /// Adding the column for compressed blocks failed with `error`
+ NoColumn { table: String, error: String },
+}
+
+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::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::NoColumn { table, error } => write!(
+ f,
+ "could not add the column {ZSTD} to {table}: {error}; trying again in {}s",
+ PAUSE_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 },
+ /// 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,
+ /// The user pressed Ctrl-C, and we are about to clean up
+ Stopping,
+}
+
+#[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(())
+ }
+}
+
+#[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,
+ #[diesel(sql_type = BigInt)]
+ failed: i64,
+}
+
+#[derive(QueryableByName)]
+struct Running {
+ #[diesel(sql_type = Bool)]
+ running: bool,
+}
+
+#[derive(QueryableByName)]
+struct Number {
+ #[diesel(sql_type = Nullable)]
+ number: Option,
+}
+
+#[derive(QueryableByName)]
+struct Hash {
+ #[diesel(sql_type = Bytea)]
+ 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 {
+ #[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)
+}
+
+/// 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 {
+ 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),
+ looked: None,
+ owed: Duration::ZERO,
+ }
+ }
+
+ fn batch_size(&self) -> i64 {
+ self.batch_size.size
+ }
+
+ /// 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);
+ }
+
+ /// 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)
+ }
+}
+
+/// Which blocks to rewrite
+enum Batch<'a> {
+ Numbers { first: i64, last: i64 },
+ Hashes(&'a [Vec]),
+}
+
+/// What we wrote for a batch
+#[derive(Default)]
+struct Done {
+ blocks: usize,
+ old_bytes: u64,
+ new_bytes: u64,
+ /// 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
+ elapsed: Duration,
+}
+
+/// 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 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
+ 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
+/// 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, in how many rows, we rewrote since the last
+ /// VACUUM
+ since_vacuum: u64,
+ rows_since_vacuum: u64,
+ /// Whether the server counts the dead rows VACUUM leaves behind as it ends
+ 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,
+ /// 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,
+ /// 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.
+/// 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 unless it was closed
+ fn release(mut self) {
+ self.0.take();
+ }
+
+ /// 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) {
+ 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
+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(
+ 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: PROGRESS_TABLE.to_string(),
+ nsp,
+ blocks,
+ storage,
+ logger,
+ pool,
+ vacuum_pid: AtomicI32::new(0),
+ workers: Mutex::new(Vec::new()),
+ })
+ }
+
+ fn lock_id(&self) -> Result {
+ lock_id(&self.nsp)
+ }
+
+ 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, 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? {
+ 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,
+ }
+ }
+
+ /// 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;
+ 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()),
+ }
+ }
+
+ pub(crate) async fn status(
+ &self,
+ conn: &mut AsyncPgConnection,
+ ) -> Result {
+ self.check_progress_table(conn).await?;
+ 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),
+ })
+ }
+
+ /// 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()
+ }
+
+ /// 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 = match self.check_pool(req.jobs) {
+ Ok(()) => self.run_on(&mut conn, req, reporter).await,
+ Err(e) => Err(e),
+ };
+ conn.release();
+ 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 {
+ self.check_pool(req.jobs)?;
+ let mut conn = CloseOnDrop(Some(conn));
+ conn.get()
+ .batch_execute(&format!("set role \"{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 CloseOnDrop,
+ req: &CompressBlocksRequest,
+ reporter: &mut dyn CompressBlocksReporter,
+ ) -> Result {
+ self.lock(conn.get()).await?;
+ let res = tokio::select! {
+ res = self.run_locked(conn.get(), req, reporter) => res,
+ () = interrupted(&self.logger) => {
+ return self.stop_after_interrupt(conn, reporter).await;
+ }
+ };
+ self.unlock(conn.get(), res).await
+ }
+
+ /// 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; how far the run got is saved, and running the command again \
+ continues from there";
+ let cleanup = async {
+ reporter.reached(CompressBlocksStep::Stopping).await?;
+ 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
+ };
+ 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(
+ &self,
+ conn: &mut AsyncPgConnection,
+ req: &CompressBlocksRequest,
+ 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));
+ 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?;
+ 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);
+ if state.progress.next_block <= state.progress.last_block {
+ self.rewrite_all(conn, req, reporter, &mut state, &mut pace)
+ .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 where namespace = $2",
+ self.progress
+ ))
+ .bind::(state.progress.next_block)
+ .bind::(&self.nsp)
+ .execute(conn)
+ .await?;
+ reporter.progress(&state.progress);
+ }
+
+ 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, &mut 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"
+ ));
+ }
+ }
+ // 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)
+ }
+
+ /// 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
+ /// 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: &mut Pace,
+ state: &mut State,
+ ) -> Result<(), StoreError> {
+ 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()),
+ }
+ }
+
+ /// Run VACUUM on the blocks table so that later writes reuse the space
+ /// 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,
+ reporter: &mut dyn CompressBlocksReporter,
+ pace: &mut Pace,
+ state: &mut State,
+ truncate: bool,
+ ) -> 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 waiters = self.try_vacuum(conn, reporter, truncate).await?;
+ if waiters.is_empty() {
+ 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,
+ };
+ self.pause_for_wal(conn, pace, state).await?;
+ return Ok(held);
+ }
+
+ 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 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,
+ reporter: &mut dyn CompressBlocksReporter,
+ truncate: bool,
+ ) -> Result, StoreError> {
+ 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}';
+ set vacuum_cost_delay = {VACUUM_COST_DELAY_MS};
+ 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 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) => {
+ 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;
+ 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
+ }
+
+ /// 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
+ /// 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)
+ }
+
+ /// 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}%'"
+ ))
+ .bind::(pid)
+ .execute(conn)
+ .await?;
+ 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. 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> {
+ 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(())
+ }
+
+ /// 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 {
+ 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| {
+ sql_query(format!(
+ "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(())
+ })
+ .await?;
+ self.load(conn)
+ .await?
+ .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 {} where namespace = $1",
+ self.progress
+ ))
+ .bind::(&self.nsp)
+ .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,
+ failed: row.failed as usize,
+ ..Default::default()
+ };
+ Ok(Some(State {
+ progress,
+ retry: row.retry,
+ vacuum_every: MIN_VACUUM_EVERY,
+ since_vacuum: 0,
+ rows_since_vacuum: 0,
+ counts_dead_rows: false,
+ }))
+ }
+
+ 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)
+ }
+
+ /// Wait until nothing keeps us from writing more
+ async fn wait_until_clear(
+ &self,
+ conn: &mut AsyncPgConnection,
+ reporter: &mut dyn CompressBlocksReporter,
+ ) -> Result<(), StoreError> {
+ self.wait_for_replicas(conn, reporter).await
+ }
+
+ /// 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,
+ "select current_setting('server_version_num')::int >= 150000
+ and current_setting('track_counts')::bool as res"
+ .to_string(),
+ )
+ .await?;
+ 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)
+ }
+
+ /// 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,
+ 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(
+ &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(())
+ }
+
+ /// 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()?;
+ 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, size));
+ 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);
+ 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(size, done.elapsed);
+ state.wrote(&done);
+ batches.written.insert(first, done);
+ }
+ Err(e) => {
+ batches.failed = Some(batches.failed.map_or(first, |f| f.min(first)));
+ // 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?;
+ }
+ }
+ }
+ }
+
+ /// 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 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;
+ Ok(pause)
+ }
+
+ /// 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,
+ from: i64,
+ to: i64,
+ 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::(from)
+ .bind::(to)
+ .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(
+ &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 => 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({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`
+ async fn rewrite(
+ &self,
+ conn: &mut AsyncPgConnection,
+ compression: BlockCompression,
+ reporter: &mut dyn CompressBlocksReporter,
+ batch: &Batch<'_>,
+ ) -> 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().saturating_sub(waited);
+ 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<(Vec, usize), 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, problems.len()))
+ }
+
+ /// 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 need to be tried again
+ async fn write(
+ &self,
+ conn: &mut AsyncPgConnection,
+ rewrites: Vec,
+ failed: usize,
+ ) -> Result {
+ #[derive(QueryableByName)]
+ struct Updated {
+ #[diesel(sql_type = Bytea)]
+ hash: Vec,
+ #[diesel(sql_type = BigInt)]
+ size: i64,
+ }
+
+ conn.transaction::<_, StoreError, _>(async |conn| {
+ 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 {
+ failed,
+ ..Default::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), {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",
+ 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?
+ };
+ 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();
+ if !not_written.is_empty() {
+ done.retry = sql_query(format!(
+ "select hash from {} where hash = any($1)",
+ self.blocks
+ ))
+ .bind::, _>(¬_written)
+ .load::(conn)
+ .await?
+ .into_iter()
+ .map(|h| h.hash)
+ .collect();
+ }
+ Ok(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: &mut 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(RETRY_BATCH_SIZE) {
+ self.wait_until_clear(conn, reporter).await?;
+ let batch = Batch::Hashes(hashes);
+ let done = self
+ .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);
+ self.pause_for_wal(conn, pace, state).await?;
+ self.vacuum_if_due(conn, reporter, pace, state).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 where namespace = $2",
+ self.progress
+ ))
+ .bind::(skipped as i64)
+ .bind::(&self.nsp)
+ .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 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);
+ // 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!((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));
+
+ let adapt = |pace: &mut Pace, elapsed| pace.adapt(pace.batch_size(), elapsed);
+ assert_eq!(INITIAL_BATCH_SIZE, pace.batch_size());
+ adapt(&mut pace, secs(0.5));
+ assert_eq!(2 * INITIAL_BATCH_SIZE, pace.batch_size());
+ adapt(&mut pace, secs(1.0));
+ assert_eq!(2 * INITIAL_BATCH_SIZE, pace.batch_size());
+ // Slow batches get smaller, but never empty
+ adapt(&mut pace, secs(4.0));
+ assert_eq!(INITIAL_BATCH_SIZE / 2, pace.batch_size());
+ for _ in 0..10 {
+ 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 {
+ 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, 10));
+ batches.written.insert(20, Done::default());
+ 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());
+ 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]
+ fn lock_id_is_number_of_chain() {
+ assert_eq!(17, lock_id("chain17").unwrap());
+ lock_id("public").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/postgres/src/pool/mod.rs b/store/postgres/src/pool/mod.rs
index c479c2263a2..b71d780eb83 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.
@@ -502,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 956b79ca13d..91319c86622 100644
--- a/store/test-store/tests/postgres/chain_head.rs
+++ b/store/test-store/tests/postgres/chain_head.rs
@@ -7,13 +7,15 @@ 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 std::time::{Duration, Instant};
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 +23,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 +707,216 @@ 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,
+ 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,
+) -> 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!("delete from public.compress_blocks_progress where namespace = '{namespace}'"),
+ )
+ .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 +1386,1625 @@ 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 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()
+ 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;
+
+ // The run tells us that it could not uncompress a block
+ let mut reporter = TestReporter::default();
+ let err = store
+ .compress_blocks(&compress_request(BlockCompression::None), &mut reporter)
+ .await
+ .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);
+ }
+ 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 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 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 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 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 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];
+ 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];
+ 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");
+ };
+ // 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!(33, progress.blocks);
+ assert!(
+ matches!(
+ reporter.steps[0],
+ CompressBlocksStep::Read { first: 107, .. }
+ ),
+ "{:?}",
+ reporter.steps
+ );
+ assert_eq!(43, count_compressed(&store, &nsp).await);
+ assert_eq!(first_blocks, xmins(&store, &nsp, 107).await);
+ execute(
+ &store,
+ format!("delete from {nsp}.blocks where number >= 100"),
+ )
+ .await;
+ reset_compress_blocks(&store, &nsp).await;
+ })
+}
+
+#[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;
+ })
+}
+
+/// 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);
+ })
+}
+
+/// 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:?}");
+ })
+}
+
+#[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];
+ 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 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];
+ 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 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 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, 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 what we rewrite between two VACUUMs
+ 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!(20_003, progress.blocks);
+ assert!(!raw.is_compressed());
+ })
+}
+
+#[test]
+fn compress_small_blocks_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;
+ // 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;
+ add_blocks(&store, &nsp, 100, 1_000, 16_000).await;
+ execute(&store, format!("vacuum full {nsp}.blocks")).await;
+
+ // 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")
+ .await
+ .unwrap();
+ let req = CompressBlocksRequest {
+ vacuum_every: Some(64 * 1024),
+ ..compress_request(BlockCompression::Zstd(1))
+ };
+ 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;
+ let compressed = count_compressed(&store, &nsp).await;
+ reset_compress_blocks(&store, &nsp).await;
+
+ 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);
+ })
+}
+
#[test]
fn receipts_of_compressed_block() {
let chain = vec![&*GENESIS_BLOCK, &*BLOCK_ONE, &*BLOCK_TWO];