Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
206 changes: 206 additions & 0 deletions crates/cli/examples/segbuild_status.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
//! Can this node extend the segbuild set, or is there a gap?
//!
//! Three numbers answer it, and all three are already on disk:
//!
//! - where the **set** ends, from the `NNN-start-end` directory names;
//! - where the node has **executed** to, from the block store's `exec_head`;
//! - the collection **watermark**, from the epoch store's `collected-below`.
//!
//! This exists because answering that took eight commands otherwise: no tool
//! printed the executed head's *number* (`height_peek` prints its hash), so it
//! had to be bisected out of `block_info`. The question is two comparisons, and
//! it should cost one command.
//!
//! The distinction the output insists on: a gap between the set and the
//! executed head is a gap in **coverage**, which says nothing about whether the
//! blocks can still be built. Whether they can is what the watermark answers --
//! beneath it a missing node was taken by the collector and is not recoverable
//! here; at or above it, the nodes are still in an unswept epoch. A node that
//! was stopped for a week has a gap of thousands of blocks whose nodes are all
//! present, because nothing swept while it was down.
//!
//! Read-only, and safe to run against a live node.
//!
//! ```text
//! segbuild_status <data-dir> <segbuild-dir> [--trie-dir DIR] [--engine flatdb|rocksdb]
//! ```
//!
//! `--trie-dir` defaults to `<data-dir>/trie-epochs-flat` and `--engine` to
//! `flatdb`, which is what the mainnet node runs. The trie store is opened only
//! to read the watermark; pass an engine that does not match the store and it
//! says so rather than guessing.

use anyhow::{Context, Result};
use rustock_storage::epoch_store::{EpochConfig, EpochTrieStore};
use rustock_storage::segbuild_boundaries::SegmentBoundaries;
use rustock_storage::BlockStore;

fn flag(name: &str, default: &str) -> String {
let args: Vec<String> = std::env::args().collect();
args.windows(2)
.find(|w| w[0] == format!("--{name}"))
.map(|w| w[1].clone())
.unwrap_or_else(|| default.to_string())
}

fn main() -> Result<()> {
let positional: Vec<String> = std::env::args()
.skip(1)
.take_while(|a| !a.starts_with("--"))
.collect();
if positional.len() != 2 {
eprintln!(
"usage: segbuild_status <data-dir> <segbuild-dir> \
[--trie-dir DIR] [--engine flatdb|rocksdb]"
);
std::process::exit(64);
}
let data_dir = positional[0].clone();
let segbuild_dir = positional[1].clone();
let trie_dir = flag("trie-dir", &format!("{data_dir}/trie-epochs-flat"));
let engine = flag("engine", "flatdb");

let store = BlockStore::open_read_only(&data_dir)
.with_context(|| format!("opening {data_dir} read-only"))?;

let exec_head = match store.exec_head()? {
Some((hash, _)) => store.header(hash)?.map(|h| h.number),
None => None,
};
let canonical_tip = store.head()?.and_then(|h| store.header(h).ok().flatten()).map(|h| h.number);
let set_end = rustock_execution::segment_build::set_end(std::path::Path::new(&segbuild_dir))?;

// The watermark. Opened read-only and only for this one value, so a store
// that cannot be opened is reported rather than fatal: the two block
// numbers above are still worth printing.
let engine_parsed = rustock_storage::TrieEngine::parse(&engine)?;
let config = EpochConfig::default();
let expected = rustock_storage::epoch_backend::keys_for_rotation(config.rotate_bytes);
let opened = EpochTrieStore::open_read_only_with(
std::path::Path::new(&trie_dir),
config,
engine_parsed.factory(expected),
);
let watermark = match &opened {
Ok(es) => Ok(es.collected_below()),
Err(e) => Err(anyhow::anyhow!("{e:#}")),
};

// The seed a gap's build would start from: the state root the set's last
// block declares. One lookup, and it is the only part of a gap that the
// watermark cannot settle -- those nodes were written below it, so whether
// they survived depends on whether they were still live when the sweep
// drained. Checking it costs a single read and replaces the one unknown in
// deciding whether to build a gap.
//
// A present root proves the top node is there, not the whole trie beneath
// it, so this is a necessary condition and not a sufficient one.
let seed = match (&opened, set_end) {
(Ok(es), Some(end)) => {
let root = store
.canonical_hash(end)?
.and_then(|h| store.header(h).ok().flatten())
.map(|h| h.state_root);
root.map(|r| (end, r, rustock_trie::TrieStore::get(es, r.as_slice()).is_some()))
}
_ => None,
};

println!("block store {data_dir}");
println!("segment set {segbuild_dir}");
println!("trie store {trie_dir} ({engine})");
println!();
match set_end {
Some(n) => println!(" set ends at #{n}"),
None => println!(" set ends at (no NNN-start-end segment: nothing to extend)"),
}
match exec_head {
Some(n) => println!(" executed head #{n}"),
None => println!(" executed head (none: this node has executed nothing)"),
}
if let Some(n) = canonical_tip {
println!(" canonical tip #{n}");
}
match &watermark {
Ok(Some(n)) => println!(" collected below #{n}"),
Ok(None) => println!(" collected below (no sweep has completed)"),
Err(e) => println!(" collected below unreadable: {e:#}"),
}
if let Some((end, root, present)) = &seed {
println!(
" seed root at #{end} {} ({root:?})",
if *present { "PRESENT" } else { "ABSENT" }
);
}

// What is pending, if the logs exist yet.
let logs = SegmentBoundaries::open(&segbuild_dir, u64::MAX);
if let Ok(logs) = &logs {
let boundaries = logs.boundaries();
println!();
println!(" boundaries recorded {}", boundaries.len());
println!(" ranges built {}", logs.built_count());
if let Some(reason) = logs.halted() {
println!(" HALTED {reason}");
}
for u in logs.uncovered() {
println!(" uncovered #{}..#{} {}", u.start, u.end, u.reason);
}
if let Some(first) = set_end {
if let Some(bound) = logs.collection_bound(first + 1) {
println!(" collection bound #{bound}");
}
}
}

println!();
let (Some(set_end), Some(exec_head)) = (set_end, exec_head) else {
println!("Cannot extend: the set or the executed head is missing (see above).");
std::process::exit(1);
};

let gap = exec_head.saturating_sub(set_end);
if gap == 0 {
println!("No gap: the set is current with the executed head. --segbuild-out will start.");
return Ok(());
}

println!("Coverage gap: #{}..#{exec_head} is {gap} blocks.", set_end + 1);
// The gap's blocks wrote at or after set_end + 1, so those writes are
// intact unless the collector has been at or above there.
match watermark {
Ok(Some(w)) if w > set_end + 1 => {
println!(
"NOT buildable from this store: the collector swept beneath #{w}, which is \
above the gap's first block. Those nodes are gone. Fill the gap with the \
offline tool against an archive trie."
);
std::process::exit(2);
}
Ok(Some(w)) => println!(
"Buildable: the watermark (#{w}) is {} blocks below the gap, so every node the \
gap's blocks wrote is still in an unswept epoch. The seed state at #{set_end} \
is the one part nothing can promise -- it was written below the watermark and \
was not pinned -- so a build may still fail on a missing node, loudly.",
(set_end + 1).saturating_sub(w)
),
Ok(None) => println!("Buildable: no sweep has completed, so nothing has been collected."),
Err(_) => println!(
"Buildability unknown: the watermark could not be read (see above). Check \
--trie-dir and --engine against what the node runs."
),
}
match seed {
Some((end, _, true)) => println!(
"The seed state root at #{end} is present, so a build has somewhere to \
start. That is the top node, not proof of the whole trie beneath it."
),
Some((end, _, false)) => println!(
"The seed state root at #{end} is ABSENT. A build would fail on its first \
read. Seed it from that segment's own sealed store instead -- it holds \
the verified state at its end block."
),
None => {}
}
Ok(())
}
113 changes: 99 additions & 14 deletions crates/cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3121,19 +3121,49 @@ async fn run(local_offset: Option<time::UtcOffset>) -> Result<()> {
rustock_execution::segment_build::UNITRIE_FROM
)
})?;
// A gap between the set and the node is unbuildable from here: the
// node's store is garbage-collected, so the state those ranges read
// is gone. Saying so now beats recording ranges that must fail.
if exec_head > set_end + args.segbuild_lag {
anyhow::bail!(
"--segbuild-out {} ends at #{set_end}, but this node has executed to \
#{exec_head}. The {} blocks in between cannot be built from a \
garbage-collected store. Fill #{}..#{exec_head} with the offline tool \
against an archive trie first, or point --segbuild-out at a set that \
is current.",
dir.display(),
exec_head - set_end,
set_end + 1
// A gap between where the set ends and where the node has executed
// is a gap in *coverage*. Whether it can still be built is a
// different question, and the store answers it: the collection
// watermark is the height beneath which a missing node was taken by
// the collector and is not recoverable here.
//
// Distance from the head does not answer it, and an earlier version
// of this check used distance -- the same mistake §7.3 corrects
// inside the builder. A node stopped for a week has a gap of
// thousands of blocks whose nodes are all still present, because
// nothing swept while it was down.
let watermark = epoch_store.as_ref().and_then(|es| es.collected_below());
let gap = exec_head.saturating_sub(set_end);
if gap > 0 {
// The gap's blocks wrote at or after set_end + 1. Those writes
// are intact unless the collector has been at or above there.
if watermark.is_some_and(|w| w > set_end + 1) {
anyhow::bail!(
"--segbuild-out {} ends at #{set_end}, this node has executed to \
#{exec_head}, and the collector has already swept beneath \
#{}. The {gap} blocks in between wrote nodes this store can no \
longer return, so they cannot be rebuilt from here. Fill \
#{}..#{exec_head} with the offline tool against an archive trie \
first, or point --segbuild-out at a set that is current.",
dir.display(),
watermark.unwrap_or(0),
set_end + 1
);
}
warn!(
"segbuild: the set ends at #{set_end} and this node has executed to \
#{exec_head}, a gap of {gap} blocks. The collector has not been \
beneath it ({}), so it is still buildable, and all but the last {} \
blocks of it are cut as a range of their own now. Its seed state at \
#{set_end} is the one \
part nothing can promise -- it was written below the watermark and \
was not pinned while the node ran -- so the build may fail on a \
missing node, loudly, leaving no segment.",
match watermark {
Some(w) => format!("watermark #{w}"),
None => "no sweep has completed".into(),
},
args.segbuild_lag
);
}
if exec_head < set_end {
Expand All @@ -3150,6 +3180,40 @@ async fn run(local_offset: Option<time::UtcOffset>) -> Result<()> {
if let Some(reason) = boundaries.halted() {
warn!("segbuild is halted and will build nothing: {reason}");
}
// Close the catch-up as its own range. Left to the size-driven cut
// it would wait a gigabyte of writes -- about a month of chain --
// before anything tried to build it, and its collection bound would
// go stale long before that.
//
// Cut `lag` blocks *below* the executed head, not at it. A boundary
// at the head is zero blocks settled, so `ready` would hold the
// range for another `lag` blocks -- eight hours at mainnet's block
// time -- before building state the node already has. One block
// lower than that and it is ready on the first tick. The `lag`
// blocks left over stay in the open range and are absorbed by the
// next size-driven cut, which is what would have happened to all of
// them anyway.
let catch_up_end = exec_head.saturating_sub(args.segbuild_lag);
if gap > 0 && catch_up_end > set_end {
match boundaries.cut_at(catch_up_end) {
Ok(Some(b)) => info!(
"segbuild: recorded a boundary at #{} so #{}..#{} is built as a \
range of its own, starting on the next tick -- it is already \
{} blocks settled",
b.block,
set_end + 1,
b.block,
args.segbuild_lag
),
Ok(None) => debug!(
"segbuild: a boundary at or above #{catch_up_end} is already recorded"
),
Err(e) => warn!(
"segbuild: could not record the catch-up boundary at \
#{catch_up_end}: {e:#}"
),
}
}
info!(
"segbuild: extending {} from #{}, cutting every ~{} MB, building {} blocks \
behind the executed head",
Expand Down Expand Up @@ -3530,10 +3594,14 @@ async fn run(local_offset: Option<time::UtcOffset>) -> Result<()> {
first_block,
));
let store_for_segbuild = store.clone();
let segbuild_dir_for_log = args.segbuild_out.clone().expect("checked above");
tokio::spawn(async move {
// Deliberately slow. A boundary is one decision per gigabyte of
// written state, and a build is minutes of work; polling faster
// would only read `exec_head` more often.
// One reminder an hour while halted, at a 30-second tick.
const HALT_REMINDER_TICKS: u64 = 120;
let mut halted_ticks: u64 = 0;
let mut tick = tokio::time::interval(std::time::Duration::from_secs(30));
// A build runs for minutes, so ticks are missed while it does.
// Delay rather than burst through the backlog afterwards: the
Expand Down Expand Up @@ -3584,7 +3652,24 @@ async fn run(local_offset: Option<time::UtcOffset>) -> Result<()> {
// which is the whole point of keeping this out of the node's
// path.
match tokio::task::spawn_blocking(move || b.tick(head, &|| false)).await {
Ok(_) => {}
// Each outcome has already said what it did, at the level
// it deserved, except being halted: that persists, so it is
// the one state worth repeating. A node halted for a week
// should say so in a log an operator reads today, without
// writing the same line every 30 seconds.
Ok(rustock_execution::segment_build::Tick::Halted(reason)) => {
if halted_ticks.is_multiple_of(HALT_REMINDER_TICKS) {
warn!(
target: "rustock::segbuild",
"Segment building is halted and is extending nothing: \
{reason} Remove the HALTED file under {} once the set has \
been checked.",
segbuild_dir_for_log.display()
);
}
halted_ticks += 1;
}
Ok(_) => halted_ticks = 0,
Err(e) => warn!(
target: "rustock::segbuild",
"The segment builder stopped with {e}; it will be tried again"
Expand Down
Loading
Loading