diff --git a/crates/cli/examples/segbuild_status.rs b/crates/cli/examples/segbuild_status.rs new file mode 100644 index 00000000..e0e92f8f --- /dev/null +++ b/crates/cli/examples/segbuild_status.rs @@ -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 [--trie-dir DIR] [--engine flatdb|rocksdb] +//! ``` +//! +//! `--trie-dir` defaults to `/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 = 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 = std::env::args() + .skip(1) + .take_while(|a| !a.starts_with("--")) + .collect(); + if positional.len() != 2 { + eprintln!( + "usage: segbuild_status \ + [--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(()) +} diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 402531c5..3bd9c778 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -3121,19 +3121,49 @@ async fn run(local_offset: Option) -> 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 { @@ -3150,6 +3180,40 @@ async fn run(local_offset: Option) -> 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", @@ -3530,10 +3594,14 @@ async fn run(local_offset: Option) -> 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 @@ -3584,7 +3652,24 @@ async fn run(local_offset: Option) -> 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" diff --git a/crates/execution/src/segment_build.rs b/crates/execution/src/segment_build.rs index 2bfd8b48..2db3bb50 100644 --- a/crates/execution/src/segment_build.rs +++ b/crates/execution/src/segment_build.rs @@ -72,6 +72,14 @@ const REROOT_EVERY: u64 = 500; /// costs minutes rather than hours. const CHECKPOINT_EVERY: u64 = 20_000; +/// Blocks between progress lines. +/// +/// A segment is ~90,000 blocks and runs at order 100 blk/s, so without this a +/// build is a quarter of an hour of silence between "Building" and "Built" -- +/// and an operator cannot tell a slow build from a stuck one. Nine lines per +/// segment is enough to see the rate and cheap enough to ignore. +const PROGRESS_EVERY: u64 = 10_000; + #[derive(Clone, Debug)] pub struct BuildConfig { /// Directory holding the segment set. The segment is created inside it. @@ -292,7 +300,7 @@ pub fn build_range( // replay their own first block (§11.3a) and why segment 097 needed // repairing after the fact. win.put(seed.as_slice(), &data); - debug!( + info!( target: "rustock::segbuild", "Seeded #{start}..#{end} from #{} root {seed:?}", parent.number ); @@ -357,6 +365,16 @@ pub fn build_range( if done.is_multiple_of(CHECKPOINT_EVERY) { window.checkpoint(n, root_hash.as_slice())?; } + if done.is_multiple_of(PROGRESS_EVERY) { + let secs = t0.elapsed().as_secs_f64(); + info!( + target: "rustock::segbuild", + "Building #{start}..#{end}: at #{n}, {done} of {} blocks, {:.0} blk/s, {} MB sealed", + end - first + 1, + done as f64 / secs.max(0.001), + window.sealed_bytes.load(std::sync::atomic::Ordering::Relaxed) / (1 << 20) + ); + } } window.finish()?; @@ -487,6 +505,11 @@ impl SegmentBuilder { /// following the chain. pub fn tick(&self, head: u64, cancel: &(dyn Fn() -> bool + Sync)) -> Tick { if let Some(reason) = self.boundaries.halted() { + // Already halted. Said at `debug` because the caller is expected to + // report the state at its own rate -- every 30 seconds for as long + // as a human takes to respond would be thousands of identical + // lines. + debug!(target: "rustock::segbuild", "Still halted, building nothing: {reason}"); return Tick::Halted(reason); } @@ -498,7 +521,18 @@ impl SegmentBuilder { match self.boundaries.verify_built_still_canonical(|h| { blocks.canonical_hash(h).ok().flatten().map(|hash| hash.into()) }) { - Ok(Some(reason)) => return Tick::Halted(reason), + Ok(Some(reason)) => { + // The moment it happens, and the loudest line this module has. + // A reorg deeper than the lag means settled history was + // rewritten; the builder stops and stays stopped, and an + // operator who never sees this has no way to know why the set + // stopped growing. + error!( + target: "rustock::segbuild", + "HALTING segment building: {reason} Nothing will be built until a human investigates and removes the HALTED file. The node is unaffected and keeps following the chain." + ); + return Tick::Halted(reason); + } Ok(None) => {} Err(e) => { warn!( diff --git a/crates/storage/src/segbuild_boundaries.rs b/crates/storage/src/segbuild_boundaries.rs index e0664f4b..c181799f 100644 --- a/crates/storage/src/segbuild_boundaries.rs +++ b/crates/storage/src/segbuild_boundaries.rs @@ -172,10 +172,26 @@ impl SegmentBoundaries { /// Only ever cuts at a block boundary, because a segment that ended /// mid-block would cover part of a block's writes and claim the block. pub fn end_block(&self, block: u64) -> Result> { - let acc = self.counter.load(Ordering::Relaxed); - if acc < self.target_bytes { + if self.counter.load(Ordering::Relaxed) < self.target_bytes { return Ok(None); } + self.cut_at(block) + } + + /// Record a boundary at `block` whatever the counter says. + /// + /// For a cut that is not about size: a node starting with the set behind + /// its executed head closes that catch-up as a range of its own, rather + /// than leaving it to be merged into the next size-driven segment. Merging + /// it would mean the gap waited a gigabyte of writes -- about a month of + /// chain -- before anything tried to build it, by which time its + /// collection bound would have gone stale and the state would be gone. + /// + /// Still refuses a boundary at or below the last one, for the same reason + /// `end_block` does: ranges are derived by walking boundaries in order, so + /// one that goes backwards produces a range with `start > end`. + pub fn cut_at(&self, block: u64) -> Result> { + let acc = self.counter.load(Ordering::Relaxed); // Reset first: if appending fails, the next block tries again rather // than this one cutting repeatedly. self.counter.store(0, Ordering::Relaxed);