Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
6a87c51
feat(store): rewrite cached blocks in place to compress them
MoonBoi9001 Dec 3, 2026
24d79f3
feat(store): run VACUUM while compressing blocks and give way to others
MoonBoi9001 Dec 3, 2026
4e04d5e
docs(graphman): describe compressing cached blocks in place
MoonBoi9001 Dec 3, 2026
121a36f
refactor(store): add the column for compressed blocks the way nodes do
MoonBoi9001 Dec 3, 2026
2224d88
refactor(store): stop compressing blocks rather than queue for a lock
MoonBoi9001 Dec 3, 2026
fa4548c
fix(store): fail a compress run that left blocks as they were
MoonBoi9001 Dec 3, 2026
8ed618f
feat(store): keep the progress of compressing blocks in a migrated table
MoonBoi9001 Dec 3, 2026
cbb5809
fix(store): let the table grow by what uncompressed blocks add
MoonBoi9001 Dec 3, 2026
fa2f144
fix(store): never leave a VACUUM running after compressing stops
MoonBoi9001 Dec 3, 2026
facd976
fix(store): stop compressing when VACUUM can not clean up after us
MoonBoi9001 Dec 4, 2026
5e80cf4
fix(store): tell a non-owner at once that it can not add the column
MoonBoi9001 Dec 3, 2026
a19e867
fix(store): stop at once on a second Ctrl-C or a hung clean-up
MoonBoi9001 Dec 3, 2026
0fff3ab
fix(store): wait for a VACUUM that a failed cancel left running
MoonBoi9001 Dec 3, 2026
d2375e5
docs(graphman): give the default of --vacuum-every in the disk costs
MoonBoi9001 Dec 3, 2026
ef2a8cc
perf(store): batch blocks to compress by count, not by number range
MoonBoi9001 Dec 4, 2026
dd7efba
perf(store): write batches of blocks on several connections at once
MoonBoi9001 Dec 4, 2026
20ebed6
feat(graphman): add --jobs to compress-blocks run, 4 by default
MoonBoi9001 Dec 4, 2026
599fefe
test(graphman): cover the pool size raise for compress-blocks run
MoonBoi9001 Dec 4, 2026
30112c1
fix(store): size each batch from the size it was handed out at
MoonBoi9001 Dec 4, 2026
6386c13
fix(store): leave the wait for the run out of a batch's time
MoonBoi9001 Dec 4, 2026
d57fa14
feat(store): say at the end how much WAL the server wrote during a run
MoonBoi9001 Dec 4, 2026
0980491
fix(store): report every batch that fails, not only the first
MoonBoi9001 Dec 4, 2026
92dcf90
docs(graphman): count the batches still running in the disk room needed
MoonBoi9001 Dec 4, 2026
6ac43e9
docs(store): say how long getting a connection for a run can wait
MoonBoi9001 Dec 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
113 changes: 113 additions & 0 deletions docs/graphman.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

<a id="info"></a>
Expand Down Expand Up @@ -364,6 +365,118 @@ Inspect all blocks after block `13000000`:

graphman --config config.toml chain check-blocks mainnet by-range --from 13000000

<a id="chain-compress-blocks"></a>
# ⌘ Chain Compress Blocks

### SYNOPSIS

Compress blocks that are already in the block cache

USAGE:
graphman --config <config> chain compress-blocks <chain-name> <SUBCOMMAND>

ARGS:
<chain-name> 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

<a id="chain-call-cache-remove"></a>
# ⌘ Chain Call Cache Remove

Expand Down
123 changes: 117 additions & 6 deletions node/src/bin/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<u32> {
match self {
Command::Chain(ChainCommand::CompressBlocks {
method: CompressBlocksCommand::Run { jobs, .. },
..
}) => Some(CompressBlocksRequest::connections_for(*jobs as usize) as u32),
_ => None,
}
}
}

#[derive(Clone, Debug, Subcommand)]
Expand Down Expand Up @@ -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)]
Expand Down Expand Up @@ -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<u64>,
/// 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.
Expand Down Expand Up @@ -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);
}
}
}
Expand Down Expand Up @@ -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?;
Expand Down Expand Up @@ -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<u32> {
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<Duration, ParseIntError> {
Ok(Duration::from_secs(s.parse()?))
}
Expand All @@ -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<u32> {
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));
}
}
Loading
Loading