diff --git a/crates/cli/examples/batch_read_bench.rs b/crates/cli/examples/batch_read_bench.rs index d51ae3b9..dff1802b 100644 --- a/crates/cli/examples/batch_read_bench.rs +++ b/crates/cli/examples/batch_read_bench.rs @@ -103,6 +103,7 @@ fn main() -> Result<()> { epochs: 4, burial_depth: 4000, rotate_bytes: 1 << 30, + ..Default::default() }; if flatdb { Arc::new(rustock_storage::epoch_store::EpochTrieStore::open_read_only_with( diff --git a/crates/cli/examples/btc_cache_bench.rs b/crates/cli/examples/btc_cache_bench.rs index a29d96df..91200109 100644 --- a/crates/cli/examples/btc_cache_bench.rs +++ b/crates/cli/examples/btc_cache_bench.rs @@ -70,7 +70,7 @@ fn main() -> Result<()> { // The epoch config only affects rotation and sweeping, neither of which a // read-only store performs; the values just have to pass validation. - let cfg = EpochConfig { epochs: 4, burial_depth: 4_000, rotate_bytes: 1 << 30 }; + let cfg = EpochConfig { epochs: 4, burial_depth: 4_000, rotate_bytes: 1 << 30, ..Default::default() }; let epochs = EpochTrieStore::open_read_only(&trie_dir, cfg) .with_context(|| format!("opening {trie_dir} read-only"))?; let raw: Arc = Arc::new(epochs); diff --git a/crates/cli/examples/gc_bench.rs b/crates/cli/examples/gc_bench.rs index 76a10a28..f6045fa6 100644 --- a/crates/cli/examples/gc_bench.rs +++ b/crates/cli/examples/gc_bench.rs @@ -122,6 +122,7 @@ fn main() -> Result<()> { epochs: args.epochs, burial_depth: args.burial, rotate_bytes: args.rotate_mb * (1 << 20), + ..Default::default() }, // The benchmark drives block heights itself from an empty store. None, diff --git a/crates/cli/examples/read_bench.rs b/crates/cli/examples/read_bench.rs index 6ab6a0c5..5e258762 100644 --- a/crates/cli/examples/read_bench.rs +++ b/crates/cli/examples/read_bench.rs @@ -103,7 +103,7 @@ fn main() -> Result<()> { let store: Box = if backend == "epoch" { Box::new(EpochTrieStore::open( &dir, - EpochConfig { epochs: 4, burial_depth: 0, rotate_bytes: u64::MAX }, + EpochConfig { epochs: 4, burial_depth: 0, rotate_bytes: u64::MAX, ..Default::default() }, // A read benchmark never collects, so there is nothing to close. None, )?) @@ -124,7 +124,7 @@ fn main() -> Result<()> { let store: Box = if backend == "epoch" { Box::new(EpochTrieStore::open( &dir, - EpochConfig { epochs: 4, burial_depth: 0, rotate_bytes: u64::MAX }, + EpochConfig { epochs: 4, burial_depth: 0, rotate_bytes: u64::MAX, ..Default::default() }, // A read benchmark never collects, so there is nothing to close. None, )?) diff --git a/crates/cli/examples/resume_point.rs b/crates/cli/examples/resume_point.rs index 93486f39..feeaae48 100644 --- a/crates/cli/examples/resume_point.rs +++ b/crates/cli/examples/resume_point.rs @@ -60,7 +60,7 @@ fn main() -> Result<()> { println!("Opening READ-ONLY: {data_dir} and {trie_dir} ({engine})\n"); let store = BlockStore::open_read_only(&data_dir)?; - let cfg = EpochConfig { epochs: 4, burial_depth: 4_000, rotate_bytes: 1 << 30 }; + let cfg = EpochConfig { epochs: 4, burial_depth: 4_000, rotate_bytes: 1 << 30, ..Default::default() }; let factory: std::sync::Arc = match rustock_storage::TrieEngine::parse(&engine)? { rustock_storage::TrieEngine::RocksDb => std::sync::Arc::new( diff --git a/crates/cli/src/config_file.rs b/crates/cli/src/config_file.rs index 5c05cd08..f765f770 100644 --- a/crates/cli/src/config_file.rs +++ b/crates/cli/src/config_file.rs @@ -45,6 +45,8 @@ pub struct FileConfig { #[serde(default)] pub gc: GcSection, #[serde(default)] + pub segbuild: SegbuildSection, + #[serde(default)] pub prune: PruneSection, #[serde(default)] pub mining: MiningSection, @@ -248,6 +250,36 @@ pub struct GcSection { pub rotate_mb: Option, pub burial: Option, pub check_secs: Option, + /// Ignore a collection bound that has fallen this far behind the head. + /// + /// A bound is a consumer saying "do not discard what blocks after this + /// wrote" -- currently a segment build that has not run yet. It blocks + /// collection while held, so a consumer that is stuck would otherwise hold + /// the floor down until the disk filled. + pub max_bound_lag: Option, +} + +/// Extending the segbuild segment set while syncing. +/// +/// The node counts the bytes each block writes, records where segments should +/// end, and re-executes each range once it has settled. See +/// `docs/segbuild-continuous-design.md`. +#[derive(Debug, Default, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct SegbuildSection { + /// The segment set to extend. Unset means the feature is off. + /// + /// Must already hold a `NNN-start-end` segment and be current with this + /// node's executed head, or the node refuses to start: a gap cannot be + /// built from a garbage-collected store. + pub out: Option, + /// Written state a segment accumulates before it is cut. + pub target_mb: Option, + /// Blocks to wait after a boundary before building its range. + pub lag: Option, + /// Memory one of the builder's two in-memory tables may hold. The + /// builder's budget, not the segment size. + pub seal_mb: Option, } #[derive(Debug, Default, Deserialize, Serialize)] @@ -592,6 +624,11 @@ pub const CONFIGURABLE: &[&str] = &[ "gc_rotate_mb", "gc_burial", "gc_check_secs", + "gc_max_bound_lag", + "segbuild_out", + "segbuild_target_mb", + "segbuild_lag", + "segbuild_seal_mb", "prune_keep_depth", "prune_max_batch", "prune_blocks", diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 7650ae04..402531c5 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -1029,6 +1029,19 @@ struct Args { #[arg(long, default_value_t = 4_000)] gc_burial: u64, + /// Ignore a collection bound that has fallen this many blocks behind the + /// head (default 12,000). + /// + /// A bound is a consumer saying "do not discard what blocks after this + /// wrote" -- currently a segment build that has not run yet. It blocks + /// collection while it is held, so a consumer that is stuck, crashed or + /// simply far behind would otherwise hold the floor down until the disk + /// filled. Past this distance the bound is ignored and the override + /// logged: an incomplete segment set is a thing to repair later, a node + /// out of disk is not. + #[arg(long, default_value_t = 12_000)] + gc_max_bound_lag: u64, + /// Entries in the BTC stored-block cache, or 0 to disable it. /// /// Answering "which BTC block is at height H?" costs one trie read per @@ -1488,6 +1501,58 @@ struct Args { #[arg(long, default_value_t = false)] allow_chain_overrides: bool, + /// Extend the segbuild segment set into this directory while syncing. + /// + /// The node syncs normally into its own store. Each executed block adds the + /// bytes it wrote to a counter, and when enough has accumulated the block + /// number is recorded as a segment boundary. Once the head is + /// --segbuild-lag blocks past a boundary, a background task builds that + /// range by re-executing it from the node's own store. + /// + /// Blocks are therefore executed twice. At the tip that is close to free -- + /// a 1,000-block range is about ten seconds of work per eight hours of + /// chain -- and it buys a segment that is exactly its range's read set, + /// with no state from blocks executed beside the chain that never became + /// canonical. See docs/segbuild-continuous-design.md. + #[arg(long, value_name = "DIR")] + segbuild_out: Option, + + /// Written state a segment should accumulate before being cut (default + /// 1024 MB). + /// + /// Bytes rather than a block count: cost per block varies tenfold across + /// eras, so equal block counts give segments from 0.2 GB to over 2 GB, + /// while equal bytes give segments a consumer can hold in memory -- which + /// is what makes replaying one fast. Advisory: a cut lands on the block + /// that crosses the target. + #[arg(long, value_name = "MB", default_value_t = 1024)] + segbuild_target_mb: u64, + + /// Blocks to wait after a boundary before building its range (default + /// 1000). + /// + /// Also how far behind the tip the node may be and still extend the set. + /// A pending range is protected from the collector while it waits -- by a + /// bound, which keeps what its blocks wrote, and a pin on the state it + /// seeds from -- so the wait itself is safe for as long as the builder + /// keeps up. A builder that falls more than `--gc-max-bound-lag` behind + /// has its protection released, and its ranges then fail on missing nodes: + /// loudly, leaving no segment rather than an incomplete one. + #[arg(long, value_name = "BLOCKS", default_value_t = 1000)] + segbuild_lag: u64, + + /// Memory one of the builder's two in-memory tables may hold before it is + /// written out (default 256 MB, so ~512 MB resident). + /// + /// This is the builder's memory budget, not the segment size: a segment is + /// the whole range, and sealing a table merely flushes it into the + /// segment's store. Sizing it like the segment target would mean ~2 GB + /// resident on a box that also has to run the node -- three builders at + /// 700 MB x 2 tables was the measured ceiling on a 7.7 GB machine, and a + /// fourth was slower than three. + #[arg(long, value_name = "MB", default_value_t = 256)] + segbuild_seal_mb: u64, + /// Import the blocks of an rskj `ExportBlocks` file (`number,hash,td,rlp` /// per line, plain or .gz) on top of this node's best block, through the /// validation and execution follow mode uses, then exit. Stops with a @@ -1684,6 +1749,12 @@ fn apply_file_config( apply(matches, "gc_rotate_mb", f.gc.rotate_mb.as_ref(), &mut a.gc_rotate_mb); apply(matches, "gc_burial", f.gc.burial.as_ref(), &mut a.gc_burial); apply(matches, "gc_check_secs", f.gc.check_secs.as_ref(), &mut a.gc_check_secs); + apply(matches, "gc_max_bound_lag", f.gc.max_bound_lag.as_ref(), &mut a.gc_max_bound_lag); + + apply_opt(matches, "segbuild_out", f.segbuild.out.as_ref(), &mut a.segbuild_out); + apply(matches, "segbuild_target_mb", f.segbuild.target_mb.as_ref(), &mut a.segbuild_target_mb); + apply(matches, "segbuild_lag", f.segbuild.lag.as_ref(), &mut a.segbuild_lag); + apply(matches, "segbuild_seal_mb", f.segbuild.seal_mb.as_ref(), &mut a.segbuild_seal_mb); apply(matches, "read_threads", f.trie.read_threads.as_ref(), &mut a.read_threads); @@ -3023,6 +3094,85 @@ async fn run(local_offset: Option) -> Result<()> { ..rustock_sync::SnapConfig::default() }; + // Extending the segbuild segment set while syncing. + // + // Two halves, neither of them in the execution path: a counter that wraps + // the store execution writes through, and a background task that cuts + // boundaries and re-executes settled ranges + // (docs/segbuild-continuous-design.md). + // + // Only the handle given to the block processor is wrapped. The readers' + // handle is not: an `eth_call` writes speculative state through the same + // store, and counting it would cut segments early for no reason. + let segbuild = match &args.segbuild_out { + Some(dir) => { + let exec_head = match store.exec_head()? { + Some((hash, _)) => store.header(hash)?.map(|h| h.number).unwrap_or(0), + None => 0, + }; + let set_end = rustock_execution::segment_build::set_end(dir)?.ok_or_else(|| { + anyhow::anyhow!( + "--segbuild-out {} holds no NNN-start-end segment. A continuous builder \ + extends an existing set; it cannot bootstrap one, because the ranges \ + below #{} cannot be verified against their headers and the ones above \ + it are no longer in this node's store. Build the initial set with the \ + offline tool (docs/generating-segbuild.md).", + dir.display(), + 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 + ); + } + if exec_head < set_end { + info!( + "segbuild: the set already covers #{set_end}, past this node's executed \ + head #{exec_head}. Nothing will be cut until the node passes it." + ); + } + let boundaries = + Arc::new(rustock_storage::segbuild_boundaries::SegmentBoundaries::open( + dir, + args.segbuild_target_mb * (1 << 20), + )?); + if let Some(reason) = boundaries.halted() { + warn!("segbuild is halted and will build nothing: {reason}"); + } + info!( + "segbuild: extending {} from #{}, cutting every ~{} MB, building {} blocks \ + behind the executed head", + dir.display(), + set_end + 1, + args.segbuild_target_mb, + args.segbuild_lag + ); + Some((boundaries, set_end + 1)) + } + None => None, + }; + + // The handle execution writes through. Counting is one relaxed atomic add + // per write batch. + let trie_store_for_blocks: Arc = match &segbuild { + Some((boundaries, _)) => Arc::new(rustock_storage::segbuild_boundaries::CountingWrites::new( + trie_store_for_exec.clone(), + boundaries.clone(), + )), + None => trie_store_for_exec.clone(), + }; + // Background collection. Kept out of the block-processing path on purpose: // mark and drain only read the oldest epoch and write the newest, and block // processing also writes the newest, so the two need no coordination beyond @@ -3038,6 +3188,7 @@ async fn run(local_offset: Option) -> Result<()> { // moves. Empty when serving is off, and then collection is exactly // what it was. let snap_for_gc = snap_config.clone(); + let segbuild_for_gc = segbuild.clone(); tokio::spawn(async move { loop { tokio::time::sleep(every).await; @@ -3079,18 +3230,57 @@ async fn run(local_offset: Option) -> Result<()> { ); continue; } - let pins = rustock_sync::snap_servable_roots(&store_for_gc, &snap_for_gc); - if pins.is_empty() { + let mut pins = rustock_sync::snap_servable_roots(&store_for_gc, &snap_for_gc); + let snap_pins = pins.len(); + // A pending segment range needs both halves: a bound, which + // keeps what the range's blocks wrote -- including nodes + // created and destroyed inside it, which no state reaches -- + // and a pin on the state the range seeds from, which the bound + // cannot keep because it was written below it. See + // `SegmentBoundaries::collection_bound`. + let bounds: Vec = segbuild_for_gc + .as_ref() + .and_then(|(b, first)| b.collection_bound(*first)) + .into_iter() + .collect(); + for &bound in &bounds { + match store_for_gc + .canonical_hash(bound) + .ok() + .flatten() + .and_then(|h| store_for_gc.header(h).ok().flatten()) + { + Some(header) => pins.push(header.state_root), + // Without the seed pin the bound alone would let the + // range's starting state be collected, and the build + // would fail on a missing node rather than be + // protected. Say so rather than collect as if the + // range were safe. + None => warn!( + target: "rustock::gc", + "Segment build bound at #{bound} has no canonical header, so its seed state cannot be pinned. The pending range may have to be rebuilt from an archive." + ), + } + } + if pins.is_empty() && bounds.is_empty() { info!(target: "rustock::gc", "Collecting against #{at} ({root:?})"); } else { info!( target: "rustock::gc", - "Collecting against #{at} ({root:?}), pinning {} snapshot state(s)", - pins.len() + "Collecting against #{at} ({root:?}), pinning {snap_pins} snapshot state(s){}", + bounds + .first() + .map(|b| format!( + " and holding the floor at #{b} for a pending segment" + )) + .unwrap_or_default() ); } - match es.collect_pinned(root, &pins, at, head_now) { + match es.collect_bounded(root, &pins, &bounds, at, head_now) { Ok(stats) => { + // A floor held by a bound is reported by the store + // itself and is not a failure; nothing more to say + // here. for lost in &stats.unservable { warn!( target: "rustock::gc", @@ -3288,6 +3478,122 @@ async fn run(local_offset: Option) -> Result<()> { sync_handler.attach_snap_server(snap_server); } + // The builder. One range at a time, on a blocking thread, and every + // failure stays inside it: extending the set is a by-product of syncing, + // and nothing here is a reason to stop following the chain. + if let Some((boundaries, first_block)) = segbuild.clone() { + let out_root = args.segbuild_out.clone().expect("checked above"); + // The builder's own processor, configured like the node's: chain + // config, fork detection and Bridge constants all change what a block + // computes, and a replay under different rules is not a replay. The + // caches are shared because they are shared state, not per-processor + // state. The legacy event store is deliberately left out: the builder + // re-executes blocks whose peg events have already been recorded, and + // recording them again would double every entry. + let mut segbuild_processor = rule_keeping_processor(&hardfork_cfg, &store, &config); + if let Some(cache) = &btc_block_cache { + segbuild_processor = segbuild_processor.with_btc_block_cache(cache.clone()); + } + if let Some(cache) = &sender_cache { + segbuild_processor = segbuild_processor.with_sender_cache(cache.clone()); + } + if config.genesis_spec.is_some() { + segbuild_processor = segbuild_processor.with_bridge_constants( + rustock_execution::bridge::constants::BridgeConstants::rskj_regtest(), + ); + } + let builder = Arc::new(rustock_execution::segment_build::SegmentBuilder::new( + boundaries.clone(), + store.clone(), + // The unwrapped store: the builder only reads it, and its window + // must not feed the counter. + trie_store_for_exec.clone(), + Arc::new(segbuild_processor), + // The collection watermark, when there is a collector. A range the + // collector has already swept beneath cannot be built from this + // store, and the builder writes it off rather than replaying into + // a hole. + epoch_store.clone().map(|es| { + Arc::new(move || es.collected_below()) + as rustock_execution::segment_build::CollectedBelow + }), + rustock_execution::segment_build::BuildConfig { + out_root, + // The builder's memory budget, not the segment size: two + // tables of this, flushed into the segment's store as they + // fill. Memory, not core count, is what the measurements + // bounded. + seal_bytes: args.segbuild_seal_mb * (1 << 20), + tables: 2, + }, + args.segbuild_lag, + first_block, + )); + let store_for_segbuild = store.clone(); + 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. + 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 + // next thing to do is the same either way, and bursting would + // only read the executed head several times in a row. + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + tick.tick().await; + + // The executed head, not the best header: a segment can only + // be built from state that exists, and only executed blocks + // have any. This is also why the boundary is cut here rather + // than inside the execution loop -- polling the executed head + // cannot name a block that has not been executed, and it needs + // no hook in the hot path. The cut lands on the first poll + // after the target is crossed instead of exactly on it, which + // sizes being advisory is what makes acceptable. + let head = match store_for_segbuild.exec_head() { + Ok(Some((hash, _))) => match store_for_segbuild.header(hash) { + Ok(Some(h)) => h.number, + _ => continue, + }, + Ok(None) => continue, + Err(e) => { + debug!(target: "rustock::segbuild", "No executed head to cut at: {e:#}"); + continue; + } + }; + + if head >= first_block { + match boundaries.end_block(head) { + Ok(Some(b)) => info!( + target: "rustock::segbuild", + "Segment boundary at #{} ({} MB accumulated)", + b.block, b.approx_bytes / (1 << 20) + ), + Ok(None) => {} + Err(e) => warn!( + target: "rustock::segbuild", + "Could not record a segment boundary at #{head}: {e:#}" + ), + } + } + + let b = builder.clone(); + // A build is CPU-bound for minutes; it must not sit on the + // runtime. A panic inside it is logged and the loop continues, + // 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(_) => {} + Err(e) => warn!( + target: "rustock::segbuild", + "The segment builder stopped with {e}; it will be tried again" + ), + } + } + }); + } + let best_block_listeners = rustock_sync::BestBlockListeners::new(); let mut sync_service = SyncService::new(sync_manager.clone(), peer_store.clone(), event_rx) .with_best_block_listeners(best_block_listeners.clone()) @@ -3308,7 +3614,7 @@ async fn run(local_offset: Option) -> Result<()> { if !args.spv { sync_service = sync_service.with_block_processor( block_processor, - trie_store_for_exec, + trie_store_for_blocks, initial_state_root, ); } @@ -3920,6 +4226,16 @@ async fn run(local_offset: Option) -> Result<()> { let snap = snap_config.clone(); Some(Arc::new(move || rustock_sync::snap_servable_roots(&store, &snap))) }, + gc_bounds: { + // The lowest block a pending segment build still needs. A + // forced collection honours it for the same reason the + // background one does: an operator asking to reclaim disk is + // not asking to break a build in progress. + segbuild.clone().map(|(boundaries, first)| { + Arc::new(move || boundaries.collection_bound(first).into_iter().collect()) + as Arc Vec + Send + Sync> + }) + }, prune_keep_depth: args.prune_keep_depth, prune_max_batch: args.prune_max_batch, logs_max_blocks: args.rpc_logs_max_blocks, @@ -4472,6 +4788,7 @@ fn trie_layout(args: &Args) -> Result { epochs: args.gc_epochs, burial_depth: args.gc_burial, rotate_bytes: args.gc_rotate_mb * (1 << 20), + max_bound_lag: args.gc_max_bound_lag, }; let rotate_bytes = gc_config.rotate_bytes; let backend = rustock_storage::epoch_store::TrieBackend::parse(&args.trie_backend, gc_config)?; diff --git a/crates/execution/src/lib.rs b/crates/execution/src/lib.rs index d4242921..c8bc01d2 100644 --- a/crates/execution/src/lib.rs +++ b/crates/execution/src/lib.rs @@ -14,6 +14,7 @@ pub mod precompiles; pub mod processor; pub mod raw_storage; pub mod remasc; +pub mod segment_build; pub mod sender_cache; pub mod rsk_handler; pub mod rsk_instructions; diff --git a/crates/execution/src/segment_build.rs b/crates/execution/src/segment_build.rs new file mode 100644 index 00000000..2bfd8b48 --- /dev/null +++ b/crates/execution/src/segment_build.rs @@ -0,0 +1,681 @@ +//! Build one segbuild segment by re-executing the block range it covers. +//! +//! This is the deferred half of `docs/segbuild-continuous-design.md`: the node +//! syncs normally and records *where* segments should end (a counter and an +//! append-only log, in `rustock_storage::segbuild_boundaries`), and this builds +//! them afterwards by replaying a settled range out of the node's own store. +//! +//! It is the library form of the `build_segments` example that built the +//! existing 161 GB set, reduced to the one case a running node needs: a single +//! range, no chunk claiming, no worker pool, no baseline. Everything that made +//! that tool correct is kept, and the comments say which measurement each piece +//! comes from, because every one of them was learnt by getting it wrong first. +//! +//! # Either a correct segment or no segment +//! +//! A segment that under-covers its range is the worst outcome available: a +//! missing trie node is indistinguishable at the API from a genuine absence +//! (§6.9d), so a consumer reads a wrong answer rather than an error. Two things +//! prevent it here. +//! +//! **Every state root is verified.** From #1,591,000 every header carries a +//! Unitrie root, so the replay checks itself at every block and stops at the +//! first mismatch. +//! +//! **The segment is built under a name no reader recognises**, and renamed only +//! after the range has been replayed to its end and the window sealed. A build +//! that fails, or is killed, leaves `.building--`, which +//! `NNN-start-end` parsing rejects. There is no window in which a half-built +//! segment is visible as a segment. +//! +//! # What it reads +//! +//! The node's block store, and the node's trie store as the fallback under a +//! sliding window of in-memory tables. The trie store is garbage-collected, so +//! whether the nodes are still there is not an accident: the builder's range +//! holds a collection bound and a pin while it is pending +//! (`SegmentBoundaries::collection_bound`). A node that was collected anyway +//! surfaces here as a failed build, which is the honest outcome. + +use crate::processor::BlockProcessor; +use anyhow::{bail, Context, Result}; +use rustock_core::Block; +use rustock_storage::segbuild_boundaries::SegmentBoundaries; +use rustock_storage::window_store::{WindowConfig, WindowStore}; +use rustock_storage::BlockStore; +use rustock_trie::{TrieNode, TrieStore}; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Instant; +use tracing::{debug, error, info, warn}; + +/// First block whose header carries a Unitrie root. Below this a header +/// declares an Orchid root, which names no node in a Unitrie store: such a +/// range can neither be seeded from its parent header nor verified against it, +/// and is built by the offline tool with a baseline instead. +pub const UNITRIE_FROM: u64 = 1_591_000; + +/// Blocks between dropping the materialized trie tree and re-rooting from the +/// hash. +/// +/// `execute_block` returns a `TrieNode` whose children are materialized as +/// execution touches them, and carrying it forward accumulates the whole +/// touched subtree in memory: measured at ~800 MB against a 145 MB window, +/// i.e. the tree was five times the cache it was supposed to be feeding. Every +/// one of those nodes is already in the window store, so the tree is pure +/// duplication -- re-rooting from the hash makes it lazy again and the nodes +/// fault back in from memory. +const REROOT_EVERY: u64 = 500; + +/// Blocks between checkpoints. Each one seals the resident window, so it costs +/// a refill afterwards; rare enough not to matter, frequent enough that a kill +/// costs minutes rather than hours. +const CHECKPOINT_EVERY: u64 = 20_000; + +#[derive(Clone, Debug)] +pub struct BuildConfig { + /// Directory holding the segment set. The segment is created inside it. + pub out_root: PathBuf, + /// Bytes an in-memory table accumulates before it is sealed to disk. + pub seal_bytes: u64, + /// In-memory tables kept resident. Memory, not core count, is the limit: + /// three workers at 700 MB x 2 tables was the measured ceiling on a 7.7 GB + /// box, and a fourth was *worse* than three. + pub tables: usize, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BuildOutcome { + /// Final name of the segment directory, relative to `out_root`. + pub name: String, + pub start: u64, + pub end: u64, + /// Blocks replayed. Less than the range when a build resumed from a + /// checkpoint. + pub blocks: u64, + /// State roots checked against a header. Equal to `blocks` for any range + /// this builder accepts. + pub verified: u64, + pub segments: usize, + /// Canonical hash at `end` when the build ran. The caller records it, and + /// it is the only way to notice later that the chain reorganised below a + /// segment that already exists. + pub end_hash: [u8; 32], +} + +/// The directory a build in progress uses. Deliberately not parseable as +/// `NNN-start-end`, so no reader can mistake it for a segment. +pub fn pending_dir(out_root: &Path, start: u64, end: u64) -> PathBuf { + out_root.join(format!(".building-{start}-{end}")) +} + +/// The next segment index: one above the highest already present. +/// +/// Only a name that is exactly `NNN-start-end` counts. A suffixed name is a +/// retired segment and must not influence numbering -- two abandoned +/// directories sharing an index is what made §11 of `trie-segments-design.md` +/// hard to diagnose. An index that repeats stops indicating order, which is the +/// whole reason the index is in the name. +pub fn next_index(out_root: &Path) -> Result { + let mut highest: Option = None; + let dir = match std::fs::read_dir(out_root) { + Ok(d) => d, + // No set yet is not an error: the first build creates it. + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0), + Err(e) => return Err(e).context(format!("reading {}", out_root.display())), + }; + for entry in dir { + let entry = entry?; + if !entry.file_type()?.is_dir() { + continue; + } + let name = entry.file_name().to_string_lossy().to_string(); + if let Some(idx) = parse_index(&name) { + highest = Some(highest.map_or(idx, |h: u64| h.max(idx))); + } + } + Ok(highest.map_or(0, |h| h + 1)) +} + +/// The highest block any segment in the set covers, or `None` for an empty +/// set. +/// +/// This is where a continuous builder picks up: the first range it is +/// responsible for starts one block later. Deriving it from the directory names +/// rather than configuring it means a set cannot be extended from the wrong +/// place by a mistyped flag. +/// +/// Only an exact `NNN-start-end` name counts. The production set holds +/// `000-1-1591000.superseded-by-900-908-20261120` and +/// `012-2938787-3081559.abandoned-empty-superseded-20261120`; a retired segment +/// covers nothing. +pub fn set_end(out_root: &Path) -> Result> { + let dir = match std::fs::read_dir(out_root) { + Ok(d) => d, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e).context(format!("reading {}", out_root.display())), + }; + let mut highest: Option = None; + for entry in dir { + let entry = entry?; + if !entry.file_type()?.is_dir() { + continue; + } + let name = entry.file_name().to_string_lossy().to_string(); + if let Some((_, end)) = parse_range(&name) { + highest = Some(highest.map_or(end, |h: u64| h.max(end))); + } + } + Ok(highest) +} + +/// `NNN-start-end`, and nothing else. +fn parse_range(name: &str) -> Option<(u64, u64)> { + let parts: Vec<&str> = name.split('-').collect(); + if parts.len() != 3 { + return None; + } + parts[0].parse::().ok()?; + Some((parts[1].parse().ok()?, parts[2].parse().ok()?)) +} + +/// The index of a `NNN-start-end` name. +fn parse_index(name: &str) -> Option { + parse_range(name)?; + name.split('-').next()?.parse().ok() +} + +/// Re-execute `[start, end]` and seal the segment it reads. +/// +/// `source` is the node's own trie store, read-only as far as this is +/// concerned: every node read is copied into the window, and the window is what +/// is written. `cancel` is polled once per block so a shutdown does not have to +/// wait for a range to finish; a cancelled build leaves its pending directory +/// and resumes from the last checkpoint. +/// +/// `processor` must be configured like the node's own, or the replay is not a +/// replay: chain config, fork detection and Bridge constants all change what a +/// block computes, and a segment built under different rules would fail its +/// own verification rather than be silently wrong -- but failing every build on +/// a chain with custom Bridge constants is not a useful outcome either. What it +/// must *not* carry is the legacy event store: re-executing a block that has +/// already been recorded would record its peg events twice. +pub fn build_range( + blocks: Arc, + source: Arc, + processor: &BlockProcessor, + config: &BuildConfig, + start: u64, + end: u64, + cancel: &(dyn Fn() -> bool + Sync), +) -> Result> { + if start > end { + bail!("range #{start}..#{end} is not a range"); + } + if start < UNITRIE_FROM { + bail!( + "refusing to build #{start}..#{end}: below #{UNITRIE_FROM} a header declares an \ + Orchid root, which names no node in a Unitrie store. The range can be neither \ + seeded from its parent header nor verified against it. Build the pre-fork era \ + with the offline tool and a baseline." + ); + } + + let end_hash = blocks + .canonical_hash(end)? + .with_context(|| format!("no canonical block at #{end}; refusing to build to there"))?; + + std::fs::create_dir_all(&config.out_root) + .with_context(|| format!("creating {}", config.out_root.display()))?; + let pending = pending_dir(&config.out_root, start, end); + + let window = Arc::new(WindowStore::new( + WindowConfig { + seal_bytes: config.seal_bytes, + tables: config.tables, + dir: pending.clone(), + }, + Some(source.clone()), + )?); + let win: Arc = window.clone(); + + // Resume a build this range already started. The pending directory's name + // is derived from the range, so a restart finds its own work. + let mut first = start; + let mut root: Option = None; + if let Some((last, root_bytes)) = WindowStore::read_checkpoint(&pending) { + if last >= start && last < end { + match win.get(&root_bytes).or_else(|| source.get(&root_bytes)) { + Some(data) => { + info!( + target: "rustock::segbuild", + "Resuming the build of #{start}..#{end} at #{}", last + 1 + ); + root = Some(TrieNode::from_message(&data, win.as_ref())); + first = last + 1; + } + None => warn!( + target: "rustock::segbuild", + "The checkpoint at #{last} names a root that is no longer readable; \ + building #{start}..#{end} from the start" + ), + } + } + } + + // Seed from the parent's state. + let mut root = match root { + Some(r) => r, + None => { + let hash = blocks + .canonical_hash(first)? + .with_context(|| format!("no canonical block at #{first}"))?; + let header = blocks + .header(hash)? + .with_context(|| format!("no header for the canonical block at #{first}"))?; + let parent = blocks + .header(header.parent_hash)? + .with_context(|| format!("no parent header for #{first}"))?; + let seed = parent.state_root; + let data = source.get(seed.as_slice()).with_context(|| { + format!( + "the state root {seed:?} of #{} is not in the node's store. The range's \ + seed state has been collected -- either the build lag is deeper than \ + the collector's bound, or a bound was overridden as stale. This range \ + has to be filled from an archive.", + parent.number + ) + })?; + // Put the seed into the window as well as reading it. This read is + // the one in the whole build that bypasses copy-on-read, and + // leaving it out is why 96 of the original 97 chunks could not + // replay their own first block (§11.3a) and why segment 097 needed + // repairing after the fact. + win.put(seed.as_slice(), &data); + debug!( + target: "rustock::segbuild", + "Seeded #{start}..#{end} from #{} root {seed:?}", parent.number + ); + TrieNode::from_message(&data, source.as_ref()) + } + }; + + let t0 = Instant::now(); + let mut done = 0u64; + let mut verified = 0u64; + + for n in first..=end { + if cancel() { + info!( + target: "rustock::segbuild", + "Cancelled building #{start}..#{end} at #{n}; the partial build is kept and \ + will resume from its last checkpoint" + ); + window.finish()?; + return Ok(None); + } + window.set_block(n); + + let hash = blocks + .canonical_hash(n)? + .with_context(|| format!("no canonical hash at #{n} while building #{start}..#{end}"))?; + let header = blocks.header(hash)?.with_context(|| format!("no header at #{n}"))?; + let (txs, ommers) = blocks.body(hash)?.with_context(|| format!("no body at #{n}"))?; + let header_root = header.state_root; + + let processed = processor + .execute_block(&Block { header, transactions: txs, ommers }, &root, win.clone()) + .with_context(|| format!("executing #{n}"))?; + + if processed.state_root_hash != header_root { + // Stop here and keep nothing. The window is sealed so the partial + // work is not lost to a later diagnosis, but it stays under the + // pending name, which no reader will treat as a segment. + window.finish()?; + bail!( + "state root mismatch at #{n} while building #{start}..#{end}: computed {:?}, \ + header says {header_root:?}. No segment was produced.", + processed.state_root_hash + ); + } + verified += 1; + + let root_hash = processed.state_root_hash; + root = processed.new_state_root; + done += 1; + + if done.is_multiple_of(REROOT_EVERY) { + match win.get(root_hash.as_slice()) { + Some(data) => root = TrieNode::from_message(&data, win.as_ref()), + None => warn!( + target: "rustock::segbuild", + "Re-root at #{n}: {root_hash:?} is not readable; keeping the \ + materialized tree, which costs memory but not correctness" + ), + } + } + if done.is_multiple_of(CHECKPOINT_EVERY) { + window.checkpoint(n, root_hash.as_slice())?; + } + } + + window.finish()?; + let segments = window.segment_count(); + drop(window); + + // Only now does the segment exist. The rename is the commit. + let index = next_index(&config.out_root)?; + let name = format!("{index:03}-{start}-{end}"); + let final_dir = config.out_root.join(&name); + if final_dir.exists() { + bail!( + "{} already exists; refusing to replace a segment. The build is in {}", + final_dir.display(), + pending.display() + ); + } + std::fs::rename(&pending, &final_dir).with_context(|| { + format!("renaming {} to {}", pending.display(), final_dir.display()) + })?; + + let secs = t0.elapsed().as_secs_f64(); + info!( + target: "rustock::segbuild", + "Built {name}: {done} blocks, {verified} state roots verified, {segments} table(s), \ + {:.0} blk/s", + done as f64 / secs.max(0.001) + ); + + Ok(Some(BuildOutcome { + name, + start, + end, + blocks: done, + verified, + segments, + end_hash: end_hash.into(), + })) +} + +/// Attempts at one range before it is written off. +/// +/// Three rather than one because the commonest failures are transient -- a disk +/// that was momentarily full, a store that was mid-collection -- and three +/// rather than for ever because a range that cannot be built must not starve +/// every later range (§3.1). +pub const MAX_ATTEMPTS: u32 = 3; + +/// How the builder asks the store what it has already collected. +/// +/// `Some(n)` means a node missing beneath block `n` is expected rather than +/// damage: the collector took it and this store cannot get it back. `None` +/// means no sweep has completed, so nothing has been collected yet. A store +/// with no collector at all supplies no callback and nothing is ever skipped. +pub type CollectedBelow = Arc Option + Send + Sync>; + +/// What one tick of the builder did. Every variant is a normal outcome; none +/// is a reason for the caller to stop the node. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Tick { + /// Building is halted and will stay halted until a human clears it. + Halted(String), + /// Nothing is ready: no boundary is `lag` blocks settled yet. + Idle, + /// A segment was built and recorded. + Built(BuildOutcome), + /// A build was interrupted. The partial work is kept and resumes. + Cancelled, + /// A build failed. `uncovered` is set when it was the last attempt and the + /// range has been written off. + Failed { start: u64, end: u64, attempt: u32, uncovered: bool }, + /// The range was written off without being attempted, because the + /// collector has already swept beneath its start. Replaying it would read + /// nodes this store cannot return. + Unbuildable { start: u64, end: u64, collected_below: u64 }, +} + +/// Drives the deferred builder: one range per tick, nothing concurrent. +/// +/// The caller polls [`Self::tick`] from a background task. One range at a time +/// is deliberate -- two concurrent builds double the memory and compete for the +/// same store, and the measured ceiling on a 7.7 GB box was three workers at +/// 700 MB x 2 tables, with a fourth *slower* than three. +pub struct SegmentBuilder { + boundaries: Arc, + blocks: Arc, + source: Arc, + /// Built once and shared across builds. See [`build_range`] for what it + /// must and must not be configured with. + processor: Arc, + /// The collection watermark, when the source store has one. + collected_below: Option, + config: BuildConfig, + /// Blocks to wait after a boundary before building its range. + lag: u64, + /// First block of the ranges this builder is responsible for: where the + /// set it is extending leaves off. + first_block: u64, +} + +impl SegmentBuilder { + pub fn new( + boundaries: Arc, + blocks: Arc, + source: Arc, + processor: Arc, + collected_below: Option, + config: BuildConfig, + lag: u64, + first_block: u64, + ) -> Self { + Self { + boundaries, + blocks, + source, + processor, + collected_below, + config, + lag, + first_block, + } + } + + /// Do at most one range's worth of work. + /// + /// Returns rather than propagates every failure: extending the segment set + /// is a by-product of syncing, and nothing here is a reason to stop + /// following the chain. + pub fn tick(&self, head: u64, cancel: &(dyn Fn() -> bool + Sync)) -> Tick { + if let Some(reason) = self.boundaries.halted() { + return Tick::Halted(reason); + } + + // Has the chain moved under a segment that already exists? Only a + // reorg deeper than the lag can do that -- on mainnet, more than a + // thousand blocks -- which is not an operational event to recover from. + // `verify_built_still_canonical` halts durably if so. + let blocks = self.blocks.clone(); + 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(None) => {} + Err(e) => { + warn!( + target: "rustock::segbuild", + "Could not check whether built segments are still canonical: {e:#}" + ); + return Tick::Idle; + } + } + + let ready = self.boundaries.ready(head, self.lag, self.first_block); + let Some(range) = ready.first().copied() else { return Tick::Idle }; + + // Has the collector already been beneath this range? If so the replay + // would read nodes the store cannot return, and the honest thing is to + // say so now rather than find out after minutes of work -- or, worse, + // three times over. + // + // The watermark is a recorded fact, not an inference from how far + // behind the builder is: a node missing beneath it was taken by the + // collector and is not recoverable here, while a node missing above it + // is damage. Distance from the head would only say the range *lost its + // protection*, which is not the same as having been collected -- the + // range is still buildable until a sweep actually reaches it. + if let Some(below) = self.collected_below.as_ref().and_then(|f| f()) { + if below >= range.start { + let reason = format!( + "the collector has swept beneath block {below}, at or above this range's start, so the nodes its blocks wrote are not recoverable from this store" + ); + error!( + target: "rustock::segbuild", + "Writing off #{}..#{} without attempting it: {reason}. The segment set has a known hole over that range, recorded in UNCOVERED; it can be filled from an archive. Building continues with later ranges.", + range.start, range.end + ); + if let Err(e) = self.boundaries.mark_uncovered(range.start, range.end, &reason) { + warn!( + target: "rustock::segbuild", + "Could not record #{}..#{} as uncovered: {e:#}", + range.start, range.end + ); + } + return Tick::Unbuildable { + start: range.start, + end: range.end, + collected_below: below, + }; + } + } + + info!( + target: "rustock::segbuild", + "Building #{}..#{} ({} MB accumulated), {} range(s) pending", + range.start, range.end, range.approx_bytes / (1 << 20), ready.len() + ); + + match build_range( + self.blocks.clone(), + self.source.clone(), + self.processor.as_ref(), + &self.config, + range.start, + range.end, + cancel, + ) { + Ok(Some(outcome)) => { + if let Err(e) = + self.boundaries.mark_built(outcome.start, outcome.end, outcome.end_hash) + { + // The segment is on disk and correct; only the record of it + // failed. Saying so is all that can be done here -- the + // next tick will offer the range again, see the directory + // already there, and refuse rather than overwrite it. + warn!( + target: "rustock::segbuild", + "Built {} but could not record it: {e:#}", outcome.name + ); + } + Tick::Built(outcome) + } + Ok(None) => Tick::Cancelled, + Err(e) => { + let attempt = self.boundaries.record_failure(range.start, range.end); + let reason = format!("{e:#}"); + if attempt >= MAX_ATTEMPTS { + error!( + target: "rustock::segbuild", + "Giving up on #{}..#{} after {attempt} attempts: {reason}. The segment \ + set now has a known hole over that range, recorded in UNCOVERED; it \ + can be filled from an archive. Building continues with later ranges.", + range.start, range.end + ); + if let Err(e) = self.boundaries.mark_uncovered(range.start, range.end, &reason) + { + warn!( + target: "rustock::segbuild", + "Could not record #{}..#{} as uncovered: {e:#}", + range.start, range.end + ); + } + Tick::Failed { start: range.start, end: range.end, attempt, uncovered: true } + } else { + warn!( + target: "rustock::segbuild", + "Build of #{}..#{} failed (attempt {attempt} of {MAX_ATTEMPTS}): \ + {reason}", + range.start, range.end + ); + Tick::Failed { start: range.start, end: range.end, attempt, uncovered: false } + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_next_index_continues_past_the_highest_and_ignores_retired_names() { + let d = tempfile::tempdir().unwrap(); + assert_eq!(next_index(d.path()).unwrap(), 0, "an empty set starts at 000"); + + for name in ["000-1-100", "097-1-2", "908-5-6"] { + std::fs::create_dir(d.path().join(name)).unwrap(); + } + assert_eq!(next_index(d.path()).unwrap(), 909, "one above the highest"); + + // A suffixed name is retired, and a build in progress is not a segment. + // Neither may move the index -- an index that repeats stops indicating + // order, and that is what the index is for. + std::fs::create_dir(d.path().join("999-7-8.abandoned")).unwrap(); + std::fs::create_dir(d.path().join(".building-9-10")).unwrap(); + assert_eq!(next_index(d.path()).unwrap(), 909); + } + + #[test] + fn the_set_end_is_where_a_continuous_builder_picks_up() { + let d = tempfile::tempdir().unwrap(); + assert_eq!(set_end(d.path()).unwrap(), None, "an empty set has no end"); + + // The shapes the production set actually holds. + for name in [ + "000-1-1591000.superseded-by-900-908-20261120", + "012-2938787-3081559.abandoned-empty-superseded-20261120", + "096-9229944-9230008", + "097-9230009-9420000", + ".building-9420001-9500000", + ] { + std::fs::create_dir(d.path().join(name)).unwrap(); + } + assert_eq!( + set_end(d.path()).unwrap(), + Some(9_420_000), + "a retired segment covers nothing, and a build in progress is not a segment" + ); + } + + #[test] + fn the_index_survives_a_missing_directory() { + let d = tempfile::tempdir().unwrap(); + let absent = d.path().join("not-created-yet"); + assert_eq!( + next_index(&absent).unwrap(), + 0, + "the first build creates the set, so an absent root is not an error" + ); + } + + #[test] + fn a_pending_name_is_not_a_segment_name() { + let p = pending_dir(Path::new("/x"), 10, 20); + let name = p.file_name().unwrap().to_string_lossy().to_string(); + assert_eq!( + parse_index(&name), + None, + "a build in progress must not parse as NNN-start-end" + ); + } +} diff --git a/crates/execution/tests/segment_build_from_store.rs b/crates/execution/tests/segment_build_from_store.rs new file mode 100644 index 00000000..40aa38b3 --- /dev/null +++ b/crates/execution/tests/segment_build_from_store.rs @@ -0,0 +1,411 @@ +//! Build a real segment out of real blocks. +//! +//! `segment_build` replays a settled canonical range and seals the trie nodes +//! it reads. Every property that matters about it -- that the seed is found, +//! that each header's state root verifies, that the sealed segment is the +//! range's read set and nothing else, that a partial build is not visible as a +//! segment -- is a property of real chain data. A unit test over a synthetic +//! trie would check the plumbing and none of that. +//! +//! Ignored by default. It needs this node's own block store and a trie store +//! that covers the range: +//! +//! ```sh +//! RUSTOCK_BLOCKS_DB=/var/lib/rustock \ +//! RUSTOCK_TRIE_DB=/mnt/import/rustock-trie \ +//! TMPDIR=/mnt/import/paseo/tmp \ +//! cargo test --release -p rustock-execution --test segment_build_from_store \ +//! -- --ignored --nocapture +//! ``` +//! +//! `RUSTOCK_SEGBUILD_START` and `RUSTOCK_SEGBUILD_BLOCKS` move and resize the +//! range; the defaults are a short recent one, because cost per block rises +//! tenfold across the chain's history and a recent range is the expensive case. + +use rustock_execution::hardfork::RskHardforkConfig; +use rustock_execution::processor::BlockProcessor; +use rustock_execution::segment_build::{ + build_range, BuildConfig, CollectedBelow, SegmentBuilder, Tick, +}; +use rustock_storage::segbuild_boundaries::SegmentBoundaries; +use rustock_storage::{BlockStore, RocksDbTrieStore}; +use rustock_trie::TrieStore; +use std::sync::Arc; + +fn env(name: &str) -> Option { + std::env::var(name).ok() +} + +fn env_u64(name: &str, default: u64) -> u64 { + env(name).and_then(|v| v.parse().ok()).unwrap_or(default) +} + +struct Fixture { + blocks: Arc, + trie: Arc, + start: u64, + end: u64, +} + +/// `None` when the stores are not configured, so the test skips rather than +/// fails on a machine that has no chain. +fn fixture() -> Option { + let (Some(blocks_db), Some(trie_db)) = (env("RUSTOCK_BLOCKS_DB"), env("RUSTOCK_TRIE_DB")) + else { + eprintln!("RUSTOCK_BLOCKS_DB and RUSTOCK_TRIE_DB not both set; skipping"); + return None; + }; + let blocks = Arc::new(BlockStore::open_read_only(&blocks_db).expect("open block store")); + let trie: Arc = + Arc::new(RocksDbTrieStore::open_read_only(&trie_db).expect("open trie store")); + let start = env_u64("RUSTOCK_SEGBUILD_START", 9_000_000); + let blocks_n = env_u64("RUSTOCK_SEGBUILD_BLOCKS", 200); + Some(Fixture { blocks, trie, start, end: start + blocks_n - 1 }) +} + +fn config(out_root: &std::path::Path) -> BuildConfig { + BuildConfig { + out_root: out_root.to_path_buf(), + // Small enough that a short range still exercises sealing a table and + // reading back through it, which is where the window's lookup order + // matters. + seal_bytes: 8 * 1024 * 1024, + tables: 2, + } +} + +/// Mainnet rules, as the node runs them. +fn processor(blocks: Arc) -> BlockProcessor { + BlockProcessor::new(RskHardforkConfig::mainnet(), blocks) +} + +#[test] +#[ignore = "requires a block store and a trie store (RUSTOCK_BLOCKS_DB, RUSTOCK_TRIE_DB)"] +fn a_range_builds_into_a_segment_that_verifies_every_block() { + let Some(f) = fixture() else { return }; + let out = tempfile::tempdir().expect("tempdir"); + + let outcome = build_range( + f.blocks.clone(), + f.trie.clone(), + &processor(f.blocks.clone()), + &config(out.path()), + f.start, + f.end, + &|| false, + ) + .expect("the build must succeed") + .expect("an uncancelled build produces a segment"); + + let expected = f.end - f.start + 1; + assert_eq!(outcome.blocks, expected, "every block in the range was replayed"); + assert_eq!( + outcome.verified, expected, + "and every one of them had its state root checked against its header -- an \ + unverified block in a segment is state nothing has checked" + ); + assert_eq!(outcome.name, format!("000-{}-{}", f.start, f.end)); + assert_eq!( + outcome.end_hash, + <[u8; 32]>::from(f.blocks.canonical_hash(f.end).unwrap().unwrap()), + "the recorded hash must be the chain's, or a later reorg check is meaningless" + ); + + let dir = out.path().join(&outcome.name); + assert!(dir.join("sealed").exists(), "the segment holds a sealed store"); + assert!( + !out.path().join(format!(".building-{}-{}", f.start, f.end)).exists(), + "the pending directory is renamed, not copied" + ); + + // The seed is the node the original build missed for 96 of 97 chunks: the + // state at start-1, read straight from the fallback and so never copied + // into the segment. Without it the segment cannot replay its own first + // block, and nothing about the build itself notices. + let parent_root = { + let hash = f.blocks.canonical_hash(f.start).unwrap().unwrap(); + let header = f.blocks.header(hash).unwrap().unwrap(); + f.blocks.header(header.parent_hash).unwrap().unwrap().state_root + }; + let sealed = RocksDbTrieStore::open_read_only(dir.join("sealed").to_str().unwrap()) + .expect("open the sealed segment"); + assert!( + sealed.get(parent_root.as_slice()).is_some(), + "the segment must contain the state root of #{} it seeded from", + f.start - 1 + ); + + // And the range's own roots are in it, which is what makes it the read set + // of its range rather than a cache of whatever was touched. + for n in [f.start, (f.start + f.end) / 2, f.end] { + let hash = f.blocks.canonical_hash(n).unwrap().unwrap(); + let root = f.blocks.header(hash).unwrap().unwrap().state_root; + assert!( + sealed.get(root.as_slice()).is_some(), + "the segment must contain the state root of #{n}" + ); + } +} + +#[test] +#[ignore = "requires a block store and a trie store (RUSTOCK_BLOCKS_DB, RUSTOCK_TRIE_DB)"] +fn a_cancelled_build_leaves_no_segment_and_resumes() { + let Some(f) = fixture() else { return }; + let out = tempfile::tempdir().expect("tempdir"); + let cfg = config(out.path()); + + // Stop after a few blocks. + let seen = std::sync::atomic::AtomicU64::new(0); + let stop_after = 5u64; + let p = processor(f.blocks.clone()); + let outcome = + build_range(f.blocks.clone(), f.trie.clone(), &p, &cfg, f.start, f.end, &|| { + seen.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= stop_after + }) + .expect("a cancelled build is not a failure"); + assert_eq!(outcome, None, "a cancelled build produces no segment"); + + // Nothing a reader would take for a segment. + let names: Vec = std::fs::read_dir(out.path()) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().to_string()) + .collect(); + assert_eq!( + names, + vec![format!(".building-{}-{}", f.start, f.end)], + "the partial build is kept, under a name that does not parse as a segment: {names:?}" + ); + + // Run it again to completion: it must produce the same segment as a build + // that was never interrupted. + let outcome = + build_range(f.blocks.clone(), f.trie.clone(), &p, &cfg, f.start, f.end, &|| false) + .expect("the resumed build must succeed") + .expect("and must produce a segment"); + assert_eq!(outcome.name, format!("000-{}-{}", f.start, f.end)); + assert_eq!( + outcome.verified, + outcome.blocks, + "every block the resumed build replayed was verified" + ); +} + +#[test] +#[ignore = "requires a block store and a trie store (RUSTOCK_BLOCKS_DB, RUSTOCK_TRIE_DB)"] +fn the_pre_unitrie_era_is_refused_rather_than_built_unverified() { + let Some(f) = fixture() else { return }; + let out = tempfile::tempdir().expect("tempdir"); + // Below #1,591,000 a header declares an Orchid root. Replaying such a range + // against header roots would verify nothing, and a segment built out of + // unchecked state is exactly what must not exist. + let p = processor(f.blocks.clone()); + let err = build_range( + f.blocks, + f.trie, + &p, + &config(out.path()), + 1_000_000, + 1_000_100, + &|| false, + ) + .expect_err("the pre-fork era must be refused"); + let msg = format!("{err:#}"); + assert!(msg.contains("Orchid root"), "{msg}"); + assert_eq!( + std::fs::read_dir(out.path()).unwrap().count(), + 0, + "and nothing is created on the way to refusing" + ); +} + +/// The whole loop, which the individual pieces do not cover: a boundary is cut +/// at the executed head, stays unbuilt until it is `lag` blocks settled, builds +/// into a recorded segment, and then stops holding the collector's floor. +/// +/// This is the part a node actually runs. `build_range` can be right while the +/// driver never offers it a range, offers one twice, or leaves the floor held +/// after a successful build -- and the last of those would quietly stop the +/// collector for ever. +#[test] +#[ignore = "requires a block store and a trie store (RUSTOCK_BLOCKS_DB, RUSTOCK_TRIE_DB)"] +fn the_loop_cuts_a_boundary_builds_it_and_then_releases_the_floor() { + let Some(f) = fixture() else { return }; + let out = tempfile::tempdir().expect("tempdir"); + let lag = 1_000u64; + + // Target one byte, so the first accounted write crosses it. Where to cut + // is not what this test is about. + let boundaries = Arc::new(SegmentBoundaries::open(out.path(), 1).expect("open the logs")); + let builder = SegmentBuilder::new( + boundaries.clone(), + f.blocks.clone(), + f.trie.clone(), + Arc::new(processor(f.blocks.clone())), + // No collector on the source store here, so nothing is ever skipped. + None, + config(out.path()), + lag, + f.start, + ); + + // Before any boundary: nothing to build, and the floor sits at the block + // the first range will seed from. + assert_eq!(builder.tick(f.start, &|| false), Tick::Idle); + assert_eq!( + boundaries.collection_bound(f.start), + Some(f.start - 1), + "the open range needs its seed kept from the start" + ); + + // A block's writes cross the target, and the cut lands on the executed + // head -- which is how the node does it, so the boundary is always a block + // that has been executed. + boundaries.add_bytes(64); + let boundary = boundaries + .end_block(f.end) + .expect("recording a boundary") + .expect("the target was crossed"); + assert_eq!(boundary.block, f.end); + + // Inside the lag, the range is not offered: a reorg could still reach it. + assert_eq!( + builder.tick(f.end, &|| false), + Tick::Idle, + "a boundary that is not yet settled must not be built" + ); + assert_eq!(boundaries.built_count(), 0); + + // Settled, it builds. + let outcome = match builder.tick(f.end + lag, &|| false) { + Tick::Built(o) => o, + other => panic!("expected a build, got {other:?}"), + }; + assert_eq!((outcome.start, outcome.end), (f.start, f.end)); + assert_eq!(outcome.name, format!("000-{}-{}", f.start, f.end)); + assert_eq!(outcome.verified, outcome.blocks, "every block was checked"); + assert!(out.path().join(&outcome.name).join("sealed").exists()); + + // Recorded against the chain's hash, which is what makes a later deep + // reorg detectable at all. + let built = boundaries.built(); + assert_eq!(built.len(), 1); + assert_eq!((built[0].start, built[0].end), (f.start, f.end)); + assert_eq!( + built[0].end_hash, + Some(<[u8; 32]>::from(f.blocks.canonical_hash(f.end).unwrap().unwrap())) + ); + + // The floor moves up to the next range's seed. If it did not, one built + // segment would hold the collector down for ever. + assert_eq!( + boundaries.collection_bound(f.start), + Some(f.end), + "a built range must stop holding the collector's floor" + ); + + // And there is nothing left to do: a range is built once. + assert_eq!(builder.tick(f.end + lag, &|| false), Tick::Idle); + assert_eq!(boundaries.built_count(), 1); + assert!(boundaries.halted().is_none(), "nothing here is a reason to halt"); + assert!(boundaries.uncovered().is_empty(), "and nothing was written off"); +} + +/// A range the collector has already swept beneath is written off without +/// being attempted. +/// +/// The watermark is the store's record of what it took: a node missing beneath +/// it was collected and is not recoverable here. Replaying such a range would +/// read into that hole -- possibly after minutes of work, and three times over +/// before the attempt counter gave up. The honest move is to record the hole +/// now and go on to the ranges that can still be built. +#[test] +#[ignore = "requires a block store and a trie store (RUSTOCK_BLOCKS_DB, RUSTOCK_TRIE_DB)"] +fn a_range_the_collector_swept_beneath_is_written_off_unattempted() { + let Some(f) = fixture() else { return }; + let out = tempfile::tempdir().expect("tempdir"); + let lag = 1_000u64; + + let boundaries = Arc::new(SegmentBoundaries::open(out.path(), 1).expect("open the logs")); + // A watermark at the range's own start: the collector has been here. + let watermark = f.start; + let builder = SegmentBuilder::new( + boundaries.clone(), + f.blocks.clone(), + f.trie.clone(), + Arc::new(processor(f.blocks.clone())), + Some(Arc::new(move || Some(watermark)) as CollectedBelow), + config(out.path()), + lag, + f.start, + ); + + boundaries.add_bytes(64); + boundaries.end_block(f.end).unwrap().expect("a boundary"); + + let tick = builder.tick(f.end + lag, &|| false); + assert_eq!( + tick, + Tick::Unbuildable { start: f.start, end: f.end, collected_below: watermark }, + "the range must be written off rather than attempted" + ); + + // Nothing was built, and nothing was even started: no pending directory, + // because the replay never began. + assert_eq!(boundaries.built_count(), 0); + assert!( + !out.path().join(format!(".building-{}-{}", f.start, f.end)).exists(), + "a range that cannot be built must not be opened for building" + ); + + // The hole is recorded, with a reason an operator can act on. + let uncovered = boundaries.uncovered(); + assert_eq!(uncovered.len(), 1); + assert_eq!((uncovered[0].start, uncovered[0].end), (f.start, f.end)); + assert!( + uncovered[0].reason.contains("not recoverable from this store"), + "{}", + uncovered[0].reason + ); + + // It stops holding the collector's floor -- holding it for a range that + // will never be built is how the disk fills -- and it is not offered again. + assert_eq!(boundaries.collection_bound(f.start), Some(f.end)); + assert_eq!(builder.tick(f.end + lag, &|| false), Tick::Idle); + assert!(boundaries.halted().is_none(), "writing off a range is not a halt"); +} + +/// The same builder, with the watermark just below the range, builds it. +/// +/// Without this the test above would pass for a builder that skipped +/// everything. +#[test] +#[ignore = "requires a block store and a trie store (RUSTOCK_BLOCKS_DB, RUSTOCK_TRIE_DB)"] +fn a_watermark_below_the_range_does_not_stop_it() { + let Some(f) = fixture() else { return }; + let out = tempfile::tempdir().expect("tempdir"); + let lag = 1_000u64; + + let boundaries = Arc::new(SegmentBoundaries::open(out.path(), 1).expect("open the logs")); + // One block below the start: everything this range's blocks wrote is still + // above what the collector took. + let watermark = f.start - 1; + let builder = SegmentBuilder::new( + boundaries.clone(), + f.blocks.clone(), + f.trie.clone(), + Arc::new(processor(f.blocks.clone())), + Some(Arc::new(move || Some(watermark)) as CollectedBelow), + config(out.path()), + lag, + f.start, + ); + + boundaries.add_bytes(64); + boundaries.end_block(f.end).unwrap().expect("a boundary"); + + match builder.tick(f.end + lag, &|| false) { + Tick::Built(o) => assert_eq!((o.start, o.end), (f.start, f.end)), + other => panic!("a watermark below the range must not stop it: {other:?}"), + } + assert!(boundaries.uncovered().is_empty()); +} diff --git a/crates/rpc/src/admin.rs b/crates/rpc/src/admin.rs index 0996057c..a0fb4de7 100644 --- a/crates/rpc/src/admin.rs +++ b/crates/rpc/src/admin.rs @@ -35,6 +35,7 @@ pub fn rsk_collect_trie( epoch_store: &Option>, burial: u64, pins: Vec, + bounds: Vec, ) -> JsonRpcResponse { let Some(es) = epoch_store.clone() else { return JsonRpcResponse::error( @@ -89,9 +90,13 @@ pub fn rsk_collect_trie( .unwrap_or(at); let store_for_task = es.clone(); let pin_count = pins.len(); + // A forced collection honours the same bounds as a background cycle. An + // operator asking for a cycle is asking to reclaim what is reclaimable, + // not to overrule a consumer that is still reading history. + let bound_count = bounds.len(); tokio::spawn(async move { match tokio::task::spawn_blocking(move || { - store_for_task.collect_pinned(root, &pins, at, head_now) + store_for_task.collect_bounded(root, &pins, &bounds, at, head_now) }) .await { @@ -106,9 +111,9 @@ pub fn rsk_collect_trie( tracing::info!( target: "rustock::gc", "Forced collection complete: marked {} ({} held by {} pin(s)), drained {}, \ - reclaimed {} MB", + reclaimed {} MB, {} bound(s) honoured", s.marked, s.pinned, pin_count, s.drained, - s.reclaimed_bytes / (1 << 20) + s.reclaimed_bytes / (1 << 20), bound_count ) } Ok(Err(e)) => tracing::error!(target: "rustock::gc", "Forced collection failed: {e:?}"), @@ -148,6 +153,10 @@ pub fn rsk_collect_trie_status( "markSeconds": s.mark_secs, "drainSeconds": s.drain_secs, "sweepSeconds": s.sweep_secs, + // Set when a registered bound held the floor, so the cycle did + // nothing on purpose. Without it a held cycle is indistinguishable + // from one that found nothing to reclaim. + "heldByBound": s.held_by_bound, }) }); JsonRpcResponse::success( @@ -277,6 +286,7 @@ pub fn rsk_storage_status( "reclaimedBytes": s.reclaimed_bytes, "markSeconds": s.mark_secs, "sweepSeconds": s.sweep_secs, + "heldByBound": s.held_by_bound, }) }); json!({ diff --git a/crates/rpc/src/server.rs b/crates/rpc/src/server.rs index 1c6cf733..756248b5 100644 --- a/crates/rpc/src/server.rs +++ b/crates/rpc/src/server.rs @@ -161,6 +161,16 @@ pub struct RpcState { /// the answer has to be the one true at the moment of the cycle. Absent, /// or empty, means nothing to pin. pub gc_pins: Option Vec + Send + Sync>>, + /// Block numbers a collection must not discard state above -- the start of + /// each range the segment builder has not re-executed yet, minus one. + /// + /// A **bound** protects a *range of blocks*, which a pin cannot: a node + /// created and destroyed inside the range is reachable from no state. It + /// travels with a pin on the state root at the same block, which covers + /// the other half (the seed trie the build starts from). A closure for the + /// same reason `gc_pins` is one: a range stops holding the floor the moment + /// it is built. + pub gc_bounds: Option Vec + Send + Sync>>, /// Blocks kept below the head when a prune request names no block. pub prune_keep_depth: u64, /// Most blocks one prune sweep may remove. @@ -545,6 +555,7 @@ async fn route(state: &RpcState, req: JsonRpcRequest) -> JsonRpcResponse { &state.epoch_store, state.gc_burial, state.gc_pins.as_ref().map(|f| f()).unwrap_or_default(), + state.gc_bounds.as_ref().map(|f| f()).unwrap_or_default(), ), "rsk_collectTrieStatus" => admin::rsk_collect_trie_status(id, &state.epoch_store), "rsk_flush" => admin::rsk_flush(id, state), diff --git a/crates/rpc/src/tests.rs b/crates/rpc/src/tests.rs index 14db7e03..5b51aa53 100644 --- a/crates/rpc/src/tests.rs +++ b/crates/rpc/src/tests.rs @@ -384,6 +384,7 @@ fn setup_state_with(store: impl FnOnce(BlockStore) -> BlockStore) -> (RpcState, account_search_enabled: true, gc_burial: 4000, gc_pins: None, + gc_bounds: None, snapshots: None, gas_estimator_binary_search: false, logs_max_blocks: crate::logs::DEFAULT_MAX_BLOCK_RANGE, @@ -1031,6 +1032,7 @@ async fn test_eth_send_raw_transaction_with_submitter() { account_search_enabled: true, gc_burial: 4000, gc_pins: None, + gc_bounds: None, snapshots: None, gas_estimator_binary_search: false, logs_max_blocks: crate::logs::DEFAULT_MAX_BLOCK_RANGE, @@ -1095,6 +1097,7 @@ async fn test_eth_send_raw_transaction_invalid_hex() { account_search_enabled: true, gc_burial: 4000, gc_pins: None, + gc_bounds: None, snapshots: None, gas_estimator_binary_search: false, logs_max_blocks: crate::logs::DEFAULT_MAX_BLOCK_RANGE, @@ -1292,6 +1295,7 @@ fn setup_state_with_trie() -> (RpcState, tempfile::TempDir) { account_search_enabled: true, gc_burial: 4000, gc_pins: None, + gc_bounds: None, snapshots: None, gas_estimator_binary_search: false, logs_max_blocks: crate::logs::DEFAULT_MAX_BLOCK_RANGE, @@ -1435,6 +1439,7 @@ fn setup_state_with_tx() -> (RpcState, tempfile::TempDir, B256) { account_search_enabled: true, gc_burial: 4000, gc_pins: None, + gc_bounds: None, snapshots: None, gas_estimator_binary_search: false, logs_max_blocks: crate::logs::DEFAULT_MAX_BLOCK_RANGE, @@ -1533,6 +1538,7 @@ async fn reported_tx_hash_is_the_one_that_can_be_looked_up() { account_search_enabled: true, gc_burial: 4000, gc_pins: None, + gc_bounds: None, snapshots: None, gas_estimator_binary_search: false, logs_max_blocks: crate::logs::DEFAULT_MAX_BLOCK_RANGE, @@ -1729,6 +1735,7 @@ fn setup_state_with_logs() -> (RpcState, tempfile::TempDir) { account_search_enabled: true, gc_burial: 4000, gc_pins: None, + gc_bounds: None, snapshots: None, gas_estimator_binary_search: false, logs_max_blocks: crate::logs::DEFAULT_MAX_BLOCK_RANGE, @@ -2178,6 +2185,7 @@ async fn test_receipt_dto_failed_status() { account_search_enabled: true, gc_burial: 4000, gc_pins: None, + gc_bounds: None, snapshots: None, gas_estimator_binary_search: false, logs_max_blocks: crate::logs::DEFAULT_MAX_BLOCK_RANGE, @@ -3142,6 +3150,7 @@ fn setup_state_with_receipts( account_search_enabled: true, gc_burial: 4000, gc_pins: None, + gc_bounds: None, snapshots: None, gas_estimator_binary_search: false, logs_max_blocks: crate::logs::DEFAULT_MAX_BLOCK_RANGE, @@ -3419,6 +3428,7 @@ async fn test_eth_bridge_state_hashes_have_no_0x_prefix() { account_search_enabled: true, gc_burial: 4000, gc_pins: None, + gc_bounds: None, snapshots: None, gas_estimator_binary_search: false, logs_max_blocks: crate::logs::DEFAULT_MAX_BLOCK_RANGE, @@ -4488,6 +4498,7 @@ fn setup_state_for_tracing() -> (RpcState, tempfile::TempDir, B256, Address, Add account_search_enabled: true, gc_burial: 4000, gc_pins: None, + gc_bounds: None, snapshots: None, gas_estimator_binary_search: false, logs_max_blocks: crate::logs::DEFAULT_MAX_BLOCK_RANGE, @@ -6193,6 +6204,7 @@ fn setup_state_with_varied_logs() -> (RpcState, tempfile::TempDir, Vec
, account_search_enabled: true, gc_burial: 4000, gc_pins: None, + gc_bounds: None, snapshots: None, gas_estimator_binary_search: false, logs_max_blocks: crate::logs::DEFAULT_MAX_BLOCK_RANGE, @@ -9258,6 +9270,7 @@ mod witness_search_tests { account_search_enabled: true, gc_burial: 4000, gc_pins: None, + gc_bounds: None, snapshots: None, gas_estimator_binary_search: false, logs_max_blocks: crate::logs::DEFAULT_MAX_BLOCK_RANGE, diff --git a/crates/storage/src/epoch_backend.rs b/crates/storage/src/epoch_backend.rs index 6e008664..b97834e6 100644 --- a/crates/storage/src/epoch_backend.rs +++ b/crates/storage/src/epoch_backend.rs @@ -819,7 +819,7 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let store = EpochTrieStore::open_with( dir.path(), - EpochConfig { epochs: 3, burial_depth: 10, rotate_bytes: 64 * 1024 }, + EpochConfig { epochs: 3, burial_depth: 10, rotate_bytes: 64 * 1024, ..Default::default() }, None, // Small segments: they are reserved whole, so a production // 512 MiB one does not belong in a temporary directory. @@ -897,7 +897,7 @@ mod tests { dir.path(), // Tiny, so writing forces rotations and the entries spread // over several epochs. - EpochConfig { epochs: 4, burial_depth: 5, rotate_bytes: 8 * 1024 }, + EpochConfig { epochs: 4, burial_depth: 5, rotate_bytes: 8 * 1024, ..Default::default() }, None, Arc::new(FlatFactory::new(4096).with_segment_size(1 << 20)), ) diff --git a/crates/storage/src/epoch_store.rs b/crates/storage/src/epoch_store.rs index fb680f0e..ff1fd237 100644 --- a/crates/storage/src/epoch_store.rs +++ b/crates/storage/src/epoch_store.rs @@ -66,11 +66,21 @@ pub struct EpochConfig { /// Rotate once the newest epoch reaches this many bytes. Size-based rather /// than time- or block-based, because it is the size that has to be bounded. pub rotate_bytes: u64, + /// How far below the head a collection bound may hold the floor before it + /// is overridden. + /// + /// A bound blocks collection, so a consumer that stops advancing one -- + /// stuck, crashed, or far behind -- would otherwise grow the store without + /// limit. Past this distance the bound is ignored and the override logged + /// at warning level. The trade is deliberate and matches an unservable + /// pin: whatever the bound was protecting becomes a gap to repair, which + /// is a better outcome than a node out of disk. + pub max_bound_lag: u64, } impl Default for EpochConfig { fn default() -> Self { - Self { epochs: 4, burial_depth: 4_000, rotate_bytes: 1 << 30 } + Self { epochs: 4, burial_depth: 4_000, rotate_bytes: 1 << 30, max_bound_lag: 12_000 } } } @@ -211,6 +221,11 @@ pub struct CollectStats { /// Pinned roots that could not be marked in full, so whatever they /// describe is already incomplete and cannot be served. pub unservable: Vec, + /// Set when a registered bound held the floor below the oldest epoch's + /// writes, so the cycle did nothing. Not a failure: a consumer is still + /// reading history the collector wanted to reclaim, and it will be + /// reclaimed once that consumer moves on. The value is the floor. + pub held_by_bound: Option, } /// A trie store split into epochs, with wholesale reclamation of the oldest. @@ -537,6 +552,65 @@ impl EpochTrieStore { self.collect_pinned(root_hash, &[], root_block, current_block) } + /// As [`Self::collect_pinned`], but also refuses to sweep any epoch holding + /// writes above the lowest of `bounds`. + /// + /// A **bound** is a block number a consumer needs kept: "do not discard + /// what blocks after this wrote." It is the right shape for protecting a + /// *range* of blocks, which a pin cannot do -- a pin keeps what is + /// reachable from one state, and a node created and destroyed inside a + /// range is reachable from neither end of it. Epochs are already tagged + /// with the highest block they received, so a bound composes with the + /// collector's own floor by taking the minimum. + /// + /// A bound further than [`EpochConfig::max_bound_lag`] below + /// `current_block` is ignored and the override logged: a bound that stops + /// advancing would otherwise block collection for ever. + pub fn collect_bounded( + &self, + root_hash: B256, + pins: &[B256], + bounds: &[u64], + root_block: u64, + current_block: u64, + ) -> Result { + let floor = self.effective_floor(bounds, root_block, current_block); + self.collect_at_floor(root_hash, pins, root_block, current_block, floor) + } + + /// The block above which no epoch may be swept. + /// + /// `root_block` is the collector's own bound; a registered bound simply + /// joins it, and the minimum wins. + fn effective_floor(&self, bounds: &[u64], root_block: u64, current_block: u64) -> u64 { + let mut floor = root_block; + for &b in bounds { + if current_block.saturating_sub(b) > self.config.max_bound_lag { + warn!( + target: "rustock::gc", + "Ignoring collection bound at block {b}: it is {} blocks below the head \ + at {current_block}, past the {} limit. Whatever it protects may be \ + collected and will have to be rebuilt.", + current_block.saturating_sub(b), + self.config.max_bound_lag + ); + continue; + } + if b < floor { + floor = b; + } + } + if floor < root_block { + info!( + target: "rustock::gc", + "Collection floor held at block {floor} by a registered bound, {} blocks \ + below the collection root at {root_block}", + root_block.saturating_sub(floor) + ); + } + floor + } + /// As [`Self::collect`], but also keeps everything reachable from `pins`. /// /// A pin is a state the node must keep for a reason the chain does not @@ -547,12 +621,29 @@ impl EpochTrieStore { /// [`CollectStats::unservable`] and does not stop the cycle: its state was /// already incomplete, and refusing to reclaim would only turn one broken /// thing into two. + /// + /// A pin protects a *state*; it cannot protect a *range* of blocks. For + /// that, see [`Self::collect_bounded`]. pub fn collect_pinned( &self, root_hash: B256, pins: &[B256], root_block: u64, current_block: u64, + ) -> Result { + self.collect_at_floor(root_hash, pins, root_block, current_block, root_block) + } + + /// The shared body. `floor` is the block above which no epoch may be + /// swept; without registered bounds it is `root_block`, which is what + /// every existing caller gets. + fn collect_at_floor( + &self, + root_hash: B256, + pins: &[B256], + root_block: u64, + current_block: u64, + floor: u64, ) -> Result { // One cycle at a time. Two concurrent cycles would each drain and sweep // the oldest epoch, and the second would delete an epoch the first had @@ -564,7 +655,7 @@ impl EpochTrieStore { { bail!("a collection cycle is already running"); } - let result = self.collect_inner(root_hash, pins, root_block, current_block); + let result = self.collect_inner(root_hash, pins, root_block, current_block, floor); self.collecting.store(false, Ordering::SeqCst); if let Ok(stats) = &result { *self.last_collect.write().unwrap() = Some(stats.clone()); @@ -578,7 +669,9 @@ impl EpochTrieStore { pins: &[B256], root_block: u64, current_block: u64, + floor: u64, ) -> Result { + debug_assert!(floor <= root_block, "the floor is a minimum, so it never exceeds the root"); let mut stats = CollectStats::default(); // Refuse to collect against a root the store cannot resolve. @@ -615,7 +708,8 @@ impl EpochTrieStore { } // The epoch about to be swept must not hold writes for any block above - // the collection root. + // the collection floor -- the collection root, or lower if a consumer + // registered a bound (see `collect_bounded`). // // Invariant I4 keeps later state alive by writing it unconditionally to // the *newest* epoch -- which only helps if the epoch being swept is a @@ -636,7 +730,25 @@ impl EpochTrieStore { let epochs = self.epochs.read().unwrap(); let oldest = epochs.first().context("no epochs")?; match oldest.last_block { - Some(b) if b <= root_block => {} + Some(b) if b <= floor => {} + // A bound holds the floor. This is not a failure and must not + // be reported as one: a consumer is reading history the + // collector wanted to reclaim, the disk will be reclaimed when + // it moves on, and a cycle that errored once a minute would + // bury the failures that do matter. §7.1's "report it" is this + // log, and its safeguard is `max_bound_lag`. + Some(b) if floor < root_block => { + info!( + target: "rustock::gc", + "Not collecting: the oldest epoch holds writes up to block {b}, above \ + the floor at block {floor} that a registered bound is holding ({} \ + blocks below the collection root at {root_block}). The store will \ + grow until that consumer catches up.", + root_block.saturating_sub(floor) + ); + stats.held_by_bound = Some(floor); + return Ok(stats); + } Some(b) => bail!( "refusing to sweep: the oldest epoch received writes up to block {b}, \ above the collection root at block {root_block}. Sweeping it would \ @@ -1333,7 +1445,7 @@ mod tests { use rustock_trie::TrieKeySlice; fn cfg(epochs: usize) -> EpochConfig { - EpochConfig { epochs, burial_depth: 0, rotate_bytes: 1 } + EpochConfig { epochs, burial_depth: 0, rotate_bytes: 1, ..Default::default() } } fn key(n: u64) -> Vec { @@ -1346,7 +1458,7 @@ mod tests { fn flat_store(dir: &std::path::Path, epochs: usize) -> EpochTrieStore { EpochTrieStore::open_with( dir, - EpochConfig { epochs, burial_depth: 0, rotate_bytes: 1 << 30 }, + EpochConfig { epochs, burial_depth: 0, rotate_bytes: 1 << 30, ..Default::default() }, None, Arc::new(crate::epoch_backend::FlatFactory { expected_keys: 4096, @@ -1831,6 +1943,132 @@ mod tests { walk(&s, old_root).expect("earlier state survives too"); } + /// A bound is what protects a *pending segment* -- a range of blocks the + /// deferred segbuild builder has not re-executed yet. It is not a pin: the + /// builder needs every node the range read, including nodes created and + /// destroyed inside it, which no end state reaches. + #[test] + fn a_bound_below_the_collection_root_refuses_the_sweep() { + let d = tempfile::tempdir().unwrap(); + let s = EpochTrieStore::open(d.path(), cfg(4), None).unwrap(); + + let root = build(&s, 120, 0); + // Grow to full width, closing each epoch at block 5,000. + for _ in 0..3 { + s.collect(root, 5_000, 5_000).unwrap(); + } + assert_eq!(s.epoch_count(), 4, "grown, nothing swept yet"); + + // Unbounded, the next cycle sweeps: the oldest epoch's writes are at + // or below the collection root. + // + // Bounded at block 1,000 -- a segment whose range the builder has not + // reached -- it must not, because the oldest epoch holds writes up to + // 5,000 and those are what the builder will read. + let stats = s + .collect_bounded(root, &[], &[1_000], 5_000, 5_000) + .expect("a held floor is not a failure: the node must not see an error here"); + assert_eq!( + stats.held_by_bound, + Some(1_000), + "the cycle must say which floor held it" + ); + assert_eq!(stats.reclaimed_bytes, 0, "and must have reclaimed nothing"); + assert!(s.sweep_log().is_empty(), "nothing was swept"); + + // Nothing was swept, so the cycle is repeatable once the bound moves. + walk(&s, root).expect("state survives a held collection"); + s.collect_bounded(root, &[], &[5_000], 5_000, 5_000) + .expect("the same cycle proceeds once the bound has caught up"); + } + + #[test] + fn a_bound_at_or_above_the_root_changes_nothing() { + let d = tempfile::tempdir().unwrap(); + let bounded = tempfile::tempdir().unwrap(); + + // Two identical stores driven through identical cycles, one with the + // bound held above the collection root throughout. + let plain = EpochTrieStore::open(d.path(), cfg(3), None).unwrap(); + let with_bound = EpochTrieStore::open(bounded.path(), cfg(3), None).unwrap(); + for i in 0..5u64 { + let r1 = build(&plain, 64, i * 10_000); + let r2 = build(&with_bound, 64, i * 10_000); + assert_eq!(r1, r2, "the two stores hold the same state"); + let at = (i + 1) * 1_000; + plain.collect(r1, at, at).unwrap(); + // The bound sits above the root, so the minimum is still the root. + with_bound.collect_bounded(r2, &[], &[at + 500], at, at).unwrap(); + } + + assert_eq!( + plain.sweep_log().len(), + with_bound.sweep_log().len(), + "a bound above the collection root must not change what is swept" + ); + assert_eq!(plain.collected_below(), with_bound.collected_below()); + } + + /// §7.1: a builder that dies with a bound registered must not be able to + /// stop collection for ever. The store overrides a bound that has stopped + /// advancing rather than filling the disk. + #[test] + fn a_stale_bound_is_overridden() { + let d = tempfile::tempdir().unwrap(); + let s = EpochTrieStore::open( + d.path(), + EpochConfig { + epochs: 4, + burial_depth: 0, + rotate_bytes: 1, + max_bound_lag: 2_000, + }, + None, + ) + .unwrap(); + + let root = build(&s, 120, 0); + for _ in 0..3 { + s.collect(root, 5_000, 5_000).unwrap(); + } + + // 1,000 is 4,000 blocks below the head, past the 2,000 limit, so it is + // ignored and the floor falls back to the collection root. + s.collect_bounded(root, &[], &[1_000], 5_000, 5_000) + .expect("a bound lagging past max_bound_lag must not block collection"); + + // The same bound within the limit still holds. + let root = build(&s, 120, 1); + let stats = s.collect_bounded(root, &[], &[4_000], 5_000, 5_000).unwrap(); + assert_eq!( + stats.held_by_bound, + Some(4_000), + "a bound inside the lag limit is honoured" + ); + } + + #[test] + fn the_floor_is_the_minimum_of_every_bound() { + let d = tempfile::tempdir().unwrap(); + let s = EpochTrieStore::open(d.path(), cfg(4), None).unwrap(); + // Several consumers, several bounds: the lowest decides, so one slow + // consumer protects what a fast one has already finished with. + assert_eq!(s.effective_floor(&[9_000, 3_000, 7_000], 10_000, 10_000), 3_000); + assert_eq!(s.effective_floor(&[], 10_000, 10_000), 10_000); + assert_eq!( + s.effective_floor(&[20_000], 10_000, 10_000), + 10_000, + "a bound above the root cannot raise the floor" + ); + // 1,000 is 99,000 blocks below the head, past the default 12,000 + // limit, so it is dropped and the next-lowest bound decides. + assert_eq!( + s.effective_floor(&[1_000, 95_000], 100_000, 100_000), + 95_000, + "the stale bound at 1,000 is ignored, so 95,000 decides" + ); + } + #[test] fn a_seeded_epoch_is_rotated_before_it_can_be_written_to() { // The structural half of the same fix: a store opened with one diff --git a/crates/storage/src/flat_migrate.rs b/crates/storage/src/flat_migrate.rs index 0714b5f9..40f6e942 100644 --- a/crates/storage/src/flat_migrate.rs +++ b/crates/storage/src/flat_migrate.rs @@ -295,7 +295,7 @@ mod tests { } fn config() -> EpochConfig { - EpochConfig { epochs: 3, burial_depth: 10, rotate_bytes: 32 * 1024 } + EpochConfig { epochs: 3, burial_depth: 10, rotate_bytes: 32 * 1024, ..Default::default() } } fn trie_key(i: u16) -> Vec { diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index 487e4fd9..7ca386e7 100644 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -13,7 +13,7 @@ pub mod trie_tool; pub mod trie_snapshot; pub mod trie_inspect; pub mod epoch_store; -pub mod segbuild_capture; +pub mod segbuild_boundaries; pub mod window_store; pub mod position; pub mod pruner; diff --git a/crates/storage/src/segbuild_boundaries.rs b/crates/storage/src/segbuild_boundaries.rs new file mode 100644 index 00000000..e0664f4b --- /dev/null +++ b/crates/storage/src/segbuild_boundaries.rs @@ -0,0 +1,909 @@ +//! Where segments should be cut, decided while syncing and built later. +//! +//! The hot path does not build segments. It counts bytes and, when enough have +//! been written, records that a segment ends at this block. A background task +//! builds the range afterwards by re-executing it +//! (`docs/segbuild-continuous-design.md`). +//! +//! That split is the whole point. Building by interception made a segment a +//! side effect of whatever the node happened to do -- including executing +//! blocks beside the chain that never became canonical -- so the segment stopped +//! being *the read set of its range*, which is the only property that makes it +//! verifiable. Re-executing a settled canonical range in isolation has one +//! unambiguous read set. +//! +//! # What has to be durable, and what does not +//! +//! **A boundary must survive a crash.** Losing one merges two segments into an +//! oversized one that may not fit a consumer's memory, which is the property +//! the sizing exists to protect. So boundaries are appended and fsynced -- cheap, +//! at one line per gigabyte of state written. +//! +//! **The counter need not.** It resets on restart, so the segment in progress +//! is cut late. Sizes are advisory: they decide where to cut, and roughly the +//! right place is all that is required. +//! +//! # Append-only, two logs +//! +//! `BOUNDARIES` records decisions, `BUILT` records what has been built, and +//! `UNCOVERED` records a range that has been given up on. None is ever +//! rewritten, so a crash cannot corrupt one into something that parses as a +//! different fact. What remains to build is what is in the first and in neither +//! of the others. +//! +//! `UNCOVERED` is what keeps a hole in the set an explicit fact on disk rather +//! than a gap someone notices later by comparing segment names (§3.1). A range +//! that cannot be built -- its state collected, its disk full -- is retried a +//! few times and then written off, which is also what lets the builder carry on +//! with later ranges instead of looping on the one it cannot do. + +use anyhow::{Context, Result}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +/// A decision that a segment ends at a block. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Boundary { + /// Last block of the segment. + pub block: u64, + /// Bytes written while it accumulated. Advisory; recorded so a surprising + /// segment size can be traced to the decision that produced it. + pub approx_bytes: u64, +} + +/// A range waiting to be built. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PendingRange { + pub start: u64, + pub end: u64, + pub approx_bytes: u64, +} + +/// A range that has been built, and the block hash it was built against. +/// +/// The hash is what makes a deep reorg detectable: if the canonical hash at +/// `end` is no longer this one, the segment describes blocks the chain has +/// abandoned. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BuiltRange { + pub start: u64, + pub end: u64, + /// Canonical hash at `end` when the range was built. `None` for a record + /// written before hashes were logged. + pub end_hash: Option<[u8; 32]>, +} + +/// A range the builder has given up on, and why. +/// +/// The set then has a known hole, which can be filled from an archive. The +/// alternative -- retrying for ever -- would stop every later range from being +/// built and would log the same failure once a tick. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UncoveredRange { + pub start: u64, + pub end: u64, + /// What the last attempt failed with. Free text, for a human. + pub reason: String, +} + +/// # This must never be able to stop the node +/// +/// Extending the segment set is a by-product of syncing. Every lock here is +/// taken with `unwrap_or_else(|e| e.into_inner())` rather than `unwrap()`, so a +/// panic in a builder thread cannot poison a lock and then panic the node's +/// execution path on the next block. For the same reason nothing here panics, +/// exits, or returns an error that a caller is expected to treat as fatal: +/// errors describe a failure to extend the set, which is not a reason to stop +/// following the chain. +pub struct SegmentBoundaries { + dir: PathBuf, + target_bytes: u64, + /// Bytes written since the last boundary. Deliberately not durable. + counter: AtomicU64, + /// Boundaries in the order recorded, lowest block first. + boundaries: std::sync::RwLock>, + /// Every range already built, with the hash it was built against. + built: std::sync::RwLock>, + /// Ranges written off as unbuildable, newest last. + uncovered: std::sync::RwLock>, + /// Failed attempts per range, in this process only. Not durable: a + /// restart is itself a reason to try again, since the commonest causes + /// (full disk, a store that was mid-collection) are the kind that a + /// restart may have cleared. + attempts: std::sync::Mutex>, +} + +const BOUNDARIES: &str = "BOUNDARIES"; +const BUILT: &str = "BUILT"; +const UNCOVERED: &str = "UNCOVERED"; +const HALTED: &str = "HALTED"; + +fn hex32(b: &[u8; 32]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +fn unhex32(s: &str) -> Option<[u8; 32]> { + if s.len() != 64 { + return None; + } + let mut out = [0u8; 32]; + for (i, byte) in out.iter_mut().enumerate() { + *byte = u8::from_str_radix(s.get(i * 2..i * 2 + 2)?, 16).ok()?; + } + Some(out) +} + +impl SegmentBoundaries { + /// Opens the logs in `dir`, creating it if needed. + /// + /// `target_bytes` is how much written state a segment should accumulate + /// before being cut. Bytes, not blocks: cost per block varies tenfold + /// across eras, so equal block counts produce segments from 0.2 GB to over + /// 2 GB, while equal bytes produce the ~1 GB segments a consumer can hold + /// in memory. + pub fn open(dir: impl Into, target_bytes: u64) -> Result { + let dir = dir.into(); + std::fs::create_dir_all(&dir) + .with_context(|| format!("creating {}", dir.display()))?; + let boundaries = read_boundaries(&dir.join(BOUNDARIES))?; + let built = read_built(&dir.join(BUILT))?; + let uncovered = read_uncovered(&dir.join(UNCOVERED))?; + Ok(Self { + dir, + target_bytes, + counter: AtomicU64::new(0), + boundaries: std::sync::RwLock::new(boundaries), + built: std::sync::RwLock::new(built), + uncovered: std::sync::RwLock::new(uncovered), + attempts: std::sync::Mutex::new(Vec::new()), + }) + } + + /// Account for bytes written by the block being executed. + /// + /// The entire hot-path cost of this design: one relaxed atomic add. + pub fn add_bytes(&self, bytes: u64) { + self.counter.fetch_add(bytes, Ordering::Relaxed); + } + + /// Call when a block finishes. Records a boundary if enough has been + /// written, and returns it. + /// + /// 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 { + return Ok(None); + } + // Reset first: if appending fails, the next block tries again rather + // than this one cutting repeatedly. + self.counter.store(0, Ordering::Relaxed); + + let b = Boundary { block, approx_bytes: acc }; + { + let mut guard = self.boundaries.write().unwrap_or_else(|e| e.into_inner()); + if guard.last().is_some_and(|l| l.block >= block) { + // Already recorded, or the chain moved backwards. Either way + // do not append a boundary that is not above the last. + return Ok(None); + } + append_line( + &self.dir.join(BOUNDARIES), + &format!("{}\t{}\t{}", b.block, b.approx_bytes, unix_now()), + )?; + guard.push(b); + } + Ok(Some(b)) + } + + /// Ranges whose end is at least `lag` blocks below `head` and which have + /// not been built. + /// + /// A range starts after the previous boundary, or at `first_block` for the + /// first one. Returned lowest first, so a builder works forwards and a + /// later range is never built before an earlier one. + pub fn ready(&self, head: u64, lag: u64, first_block: u64) -> Vec { + let boundaries = self.boundaries.read().unwrap_or_else(|e| e.into_inner()); + let built = self.built.read().unwrap_or_else(|e| e.into_inner()); + let uncovered = self.uncovered.read().unwrap_or_else(|e| e.into_inner()); + let mut out = Vec::new(); + let mut start = first_block; + for b in boundaries.iter() { + // A boundary at or below where this builder starts. It can only + // happen if the set was extended underneath an existing log -- an + // operator filling a gap offline, say. Such a "range" runs + // backwards, so skip it, and do not let it drag `start` back below + // where this builder begins. + if b.block < start { + continue; + } + let range = PendingRange { start, end: b.block, approx_bytes: b.approx_bytes }; + start = b.block + 1; + if built.iter().any(|b| b.start == range.start && b.end == range.end) { + continue; + } + // Written off. Offering it again would loop on the range the + // builder has already failed at, and starve every later one. + if uncovered.iter().any(|u| u.start == range.start && u.end == range.end) { + continue; + } + if b.block + lag > head { + // Not settled yet. Everything after this is higher still. + break; + } + out.push(range); + } + out + } + + /// The lowest block whose state a build still needs: one below the start + /// of the lowest range that has not been built. + /// + /// This is half of what protects a pending range from the collector. It is + /// passed to `EpochTrieStore::collect_bounded` as a **bound**, which keeps + /// every node written *above* it -- including nodes created and destroyed + /// inside the range, which no state at either end reaches. The other half + /// is a **pin** on the state root at this same block, which keeps the seed + /// trie the build starts from. Neither alone is sufficient: + /// + /// - the bound misses the seed, because the seed's nodes were written + /// below it and may already be dead at the collection root; + /// - the pin misses the intra-range nodes, because they are in no state. + /// + /// Together they are exhaustive: a node read while re-executing + /// `[start, end]` was either already in the trie at `start - 1` (pinned) + /// or written by a block at or after `start` (bounded). + /// + /// Includes the range still accumulating, which has no boundary yet: its + /// state has to be kept for the same reason, and its seed is the last + /// boundary. + /// + /// `None` when there is nothing to protect, and -- deliberately -- when + /// building is halted. A halted builder is waiting for a human, and a bound + /// that waits for a human is a bound that fills the disk (§7.1). The + /// pending state is then collected and those ranges have to be rebuilt from + /// an archive, which is the lesser failure. + pub fn collection_bound(&self, first_block: u64) -> Option { + if self.halted().is_some() { + return None; + } + let boundaries = self.boundaries.read().unwrap_or_else(|e| e.into_inner()); + let built = self.built.read().unwrap_or_else(|e| e.into_inner()); + let uncovered = self.uncovered.read().unwrap_or_else(|e| e.into_inner()); + let mut start = first_block; + for b in boundaries.iter() { + // Behind this builder's start; see `ready`. + if b.block < start { + continue; + } + let settled = built.iter().any(|x| x.start == start && x.end == b.block) + // A range that has been written off is not going to be built, + // so holding the floor for it only costs disk. + || uncovered.iter().any(|u| u.start == start && u.end == b.block); + if !settled { + // Ranges are settled in order, so the first gap is the lowest. + return Some(start.saturating_sub(1)); + } + start = b.block + 1; + } + // Every closed range is built; the open one still needs its seed. + Some(start.saturating_sub(1)) + } + + /// Record that `[start, end]` has been built, against the canonical hash + /// at `end`. + /// + /// The hash is not decoration. It is the only way to notice later that the + /// chain reorganised below a segment that already exists. + pub fn mark_built(&self, start: u64, end: u64, end_hash: [u8; 32]) -> Result<()> { + append_line( + &self.dir.join(BUILT), + &format!("{start}\t{end}\t{}\t{}", hex32(&end_hash), unix_now()), + )?; + self.built.write().unwrap_or_else(|e| e.into_inner()).push(BuiltRange { + start, + end, + end_hash: Some(end_hash), + }); + Ok(()) + } + + /// Count a failed attempt at `[start, end]` and report how many there have + /// now been, this process. + /// + /// Not durable, deliberately: a restart is itself a reason to try again, + /// because the usual causes -- a full disk, a store that was mid-collection + /// -- are the kind a restart may have cleared. What *is* durable is giving + /// up, which is [`Self::mark_uncovered`]. + pub fn record_failure(&self, start: u64, end: u64) -> u32 { + let mut guard = self.attempts.lock().unwrap_or_else(|e| e.into_inner()); + match guard.iter_mut().find(|(s, e, _)| *s == start && *e == end) { + Some((_, _, n)) => { + *n += 1; + *n + } + None => { + guard.push((start, end, 1)); + 1 + } + } + } + + /// Write off `[start, end]`: it will not be offered again, and it stops + /// holding the collector's floor. + /// + /// This is §3.1's requirement that a hole be a fact on disk. The segment + /// set then has a gap that can be filled from an archive, which is strictly + /// better than a segment that claims the range and under-covers it. + pub fn mark_uncovered(&self, start: u64, end: u64, reason: &str) -> Result<()> { + // One line, no tabs or newlines inside the reason, or the record would + // parse as a different one. + let flat: String = reason.chars().map(|c| if c.is_control() || c == '\t' { ' ' } else { c }).collect(); + append_line( + &self.dir.join(UNCOVERED), + &format!("{start}\t{end}\t{}\t{flat}", unix_now()), + )?; + self.uncovered + .write() + .unwrap_or_else(|e| e.into_inner()) + .push(UncoveredRange { start, end, reason: flat }); + Ok(()) + } + + /// Every range written off so far. + pub fn uncovered(&self) -> Vec { + self.uncovered.read().unwrap_or_else(|e| e.into_inner()).clone() + } + + /// Whether building is halted, and why. + /// + /// Halting is durable and deliberately not self-clearing: the conditions + /// that cause it mean something has gone wrong with the chain, not with + /// this process, and a builder that resumed on its own would quietly + /// produce segments across a discontinuity. + pub fn halted(&self) -> Option { + std::fs::read_to_string(self.dir.join(HALTED)).ok() + } + + /// Stop building, durably, with a reason an operator will read. + pub fn halt(&self, reason: &str) -> Result<()> { + let path = self.dir.join(HALTED); + std::fs::write( + &path, + format!( + "{reason}\n\nBuilding is stopped. Nothing will be built while this file \ + exists.\nInvestigate, repair the set if needed, then remove this file to \ + resume.\nrecorded {}\n", + unix_now() + ), + ) + .with_context(|| format!("writing {}", path.display()))?; + Ok(()) + } + + /// Check that every built range still sits on the canonical chain. + /// + /// `canonical_hash_at` returns the canonical hash at a height, or `None` if + /// the height is unknown. + /// + /// A reorg shallower than the lag cannot reach a built range, because + /// nothing is built until it is `lag` blocks settled. So a mismatch here + /// means the chain reorganised by more than the lag -- on mainnet, more + /// than a thousand blocks. That is not an operational event to recover + /// from; it is evidence that the chain's assumptions have failed, and the + /// honest response is to stop and require a human. + pub fn verify_built_still_canonical( + &self, + mut canonical_hash_at: impl FnMut(u64) -> Option<[u8; 32]>, + ) -> Result> { + let built = self.built.read().unwrap_or_else(|e| e.into_inner()).clone(); + for b in built { + let Some(was) = b.end_hash else { continue }; + let Some(now) = canonical_hash_at(b.end) else { + // The height is no longer known at all, which is itself a + // reorg past it. + let reason = format!( + "segbuild: block {} is no longer on the canonical chain. Segment \ + {}..{} was built against {} and that height now has no canonical \ + block. A reorg deeper than the build lag has happened.", + b.end, b.start, b.end, hex32(&was) + ); + self.halt(&reason)?; + return Ok(Some(reason)); + }; + if now != was { + let reason = format!( + "segbuild: a reorg deeper than the build lag has happened. Segment \ + {}..{} was built against block {} = {}, but that height is now {}. \ + The segment describes blocks the chain has abandoned.", + b.start, b.end, b.end, hex32(&was), hex32(&now) + ); + self.halt(&reason)?; + return Ok(Some(reason)); + } + } + Ok(None) + } + + /// Bytes accumulated since the last boundary. + pub fn accumulated(&self) -> u64 { + self.counter.load(Ordering::Relaxed) + } + + /// Every boundary recorded so far. + pub fn boundaries(&self) -> Vec { + self.boundaries.read().unwrap_or_else(|e| e.into_inner()).clone() + } + + /// How many ranges have been built. + pub fn built_count(&self) -> usize { + self.built.read().unwrap_or_else(|e| e.into_inner()).len() + } + + /// Every range built so far. + pub fn built(&self) -> Vec { + self.built.read().unwrap_or_else(|e| e.into_inner()).clone() + } +} + +fn unix_now() -> u64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +/// Append one line and fsync it. +/// +/// `sync_all` rather than a buffered write: a boundary that is in the page +/// cache when the machine loses power is a boundary that did not happen, and +/// the cost is one fsync per gigabyte of state written. +fn append_line(path: &Path, line: &str) -> Result<()> { + use std::io::Write as _; + let mut f = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(path) + .with_context(|| format!("opening {}", path.display()))?; + writeln!(f, "{line}").with_context(|| format!("writing {}", path.display()))?; + f.sync_all().with_context(|| format!("syncing {}", path.display()))?; + Ok(()) +} + +/// Reads `BOUNDARIES`, ignoring a trailing partial line. +/// +/// A crash during the append can leave a line without its newline. Such a line +/// records a boundary that may not have been acted on, and dropping it costs +/// one late cut -- whereas parsing half a number would invent a boundary +/// somewhere else entirely. +fn read_boundaries(path: &Path) -> Result> { + let Ok(text) = std::fs::read_to_string(path) else { return Ok(Vec::new()) }; + let mut out = Vec::new(); + for line in complete_lines(&text) { + let mut f = line.split('\t'); + let (Some(block), Some(bytes)) = (f.next(), f.next()) else { continue }; + let (Ok(block), Ok(approx_bytes)) = (block.parse(), bytes.parse()) else { continue }; + out.push(Boundary { block, approx_bytes }); + } + out.sort_by_key(|b| b.block); + Ok(out) +} + +fn read_built(path: &Path) -> Result> { + let Ok(text) = std::fs::read_to_string(path) else { return Ok(Vec::new()) }; + let mut out = Vec::new(); + for line in complete_lines(&text) { + let mut f = line.split('\t'); + let (Some(s), Some(e)) = (f.next(), f.next()) else { continue }; + let (Ok(start), Ok(end)) = (s.parse(), e.parse()) else { continue }; + // A record written before hashes were logged has a timestamp here + // instead; it parses as no hash, and such a range is simply not + // checked rather than treated as reorganised. + let end_hash = f.next().and_then(unhex32); + out.push(BuiltRange { start, end, end_hash }); + } + Ok(out) +} + +fn read_uncovered(path: &Path) -> Result> { + let Ok(text) = std::fs::read_to_string(path) else { return Ok(Vec::new()) }; + let mut out = Vec::new(); + for line in complete_lines(&text) { + let mut f = line.split('\t'); + let (Some(s), Some(e)) = (f.next(), f.next()) else { continue }; + let (Ok(start), Ok(end)) = (s.parse(), e.parse()) else { continue }; + let _when = f.next(); + let reason = f.next().unwrap_or("(no reason recorded)").to_string(); + out.push(UncoveredRange { start, end, reason }); + } + Ok(out) +} + +/// Lines that were fully written, i.e. everything before the last newline. +fn complete_lines(text: &str) -> impl Iterator { + let end = text.rfind('\n').map_or(0, |i| i + 1); + text[..end].lines().filter(|l| !l.trim().is_empty()) +} + +/// Counts bytes written through it, and changes nothing else. +/// +/// This is interception, but only of a number. The capture design that was +/// abandoned had to copy every node, which made a segment depend on what the +/// node happened to execute; counting an uncle's writes merely cuts a segment +/// slightly early, and sizes are advisory. +pub struct CountingWrites { + inner: std::sync::Arc, + boundaries: std::sync::Arc, +} + +impl CountingWrites { + pub fn new( + inner: std::sync::Arc, + boundaries: std::sync::Arc, + ) -> Self { + Self { inner, boundaries } + } +} + +impl rustock_trie::TrieStore for CountingWrites { + fn get(&self, key: &[u8]) -> Option> { + self.inner.get(key) + } + + fn put(&self, key: &[u8], value: &[u8]) { + self.boundaries.add_bytes((key.len() + value.len()) as u64); + self.inner.put(key, value); + } + + fn put_many(&self, items: &[(Vec, Vec)]) { + let bytes: usize = items.iter().map(|(k, v)| k.len() + v.len()).sum(); + self.boundaries.add_bytes(bytes as u64); + self.inner.put_many(items); + } + + fn flush(&self) { + self.inner.flush(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_boundary_is_cut_only_once_the_target_is_reached() { + let dir = tempfile::tempdir().unwrap(); + let b = SegmentBoundaries::open(dir.path(), 1000).unwrap(); + + b.add_bytes(400); + assert_eq!(b.end_block(10).unwrap(), None, "under target"); + b.add_bytes(700); + assert_eq!( + b.end_block(11).unwrap(), + Some(Boundary { block: 11, approx_bytes: 1100 }), + "over target, cut at the block that crossed it" + ); + assert_eq!(b.accumulated(), 0, "counter resets after a cut"); + assert_eq!(b.end_block(12).unwrap(), None, "does not cut again immediately"); + } + + #[test] + fn boundaries_survive_a_restart_and_the_counter_does_not() { + let dir = tempfile::tempdir().unwrap(); + { + let b = SegmentBoundaries::open(dir.path(), 100).unwrap(); + b.add_bytes(150); + b.end_block(5).unwrap(); + b.add_bytes(60); // in progress, deliberately not durable + } + let b = SegmentBoundaries::open(dir.path(), 100).unwrap(); + assert_eq!(b.boundaries(), vec![Boundary { block: 5, approx_bytes: 150 }]); + assert_eq!(b.accumulated(), 0, "the counter is not durable by design"); + } + + /// A crash during the append can leave a line with no newline. Dropping it + /// costs one late cut; parsing it could invent a boundary elsewhere. + #[test] + fn a_torn_trailing_line_is_ignored() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join(BOUNDARIES), "5\t150\t1700000000\n9\t20").unwrap(); + let b = SegmentBoundaries::open(dir.path(), 100).unwrap(); + assert_eq!( + b.boundaries(), + vec![Boundary { block: 5, approx_bytes: 150 }], + "the complete line survives, the torn one does not" + ); + } + + #[test] + fn ready_waits_for_the_lag_and_skips_what_is_built() { + let dir = tempfile::tempdir().unwrap(); + let b = SegmentBoundaries::open(dir.path(), 10).unwrap(); + for block in [100u64, 200, 300] { + b.add_bytes(10); + b.end_block(block).unwrap(); + } + + // head only 500: the 300 boundary is not yet 1000 blocks settled. + assert_eq!( + b.ready(500, 1000, 1), + Vec::new(), + "nothing is settled enough to build" + ); + + let ready = b.ready(1200, 1000, 1); + assert_eq!( + ready, + vec![ + PendingRange { start: 1, end: 100, approx_bytes: 10 }, + PendingRange { start: 101, end: 200, approx_bytes: 10 }, + ], + "100 and 200 are settled; 300 needs head >= 1300" + ); + + b.mark_built(1, 100, [7u8; 32]).unwrap(); + assert_eq!( + b.ready(1200, 1000, 1), + vec![PendingRange { start: 101, end: 200, approx_bytes: 10 }], + "a built range is not offered again" + ); + } + + #[test] + fn built_ranges_survive_a_restart() { + let dir = tempfile::tempdir().unwrap(); + { + let b = SegmentBoundaries::open(dir.path(), 10).unwrap(); + b.add_bytes(10); + b.end_block(50).unwrap(); + b.mark_built(1, 50, [7u8; 32]).unwrap(); + } + let b = SegmentBoundaries::open(dir.path(), 10).unwrap(); + assert_eq!(b.built_count(), 1); + assert!(b.ready(10_000, 1000, 1).is_empty(), "already built"); + } + + /// A boundary must never be recorded at or below the last one: the ranges + /// are derived by walking boundaries in order, so a backwards one would + /// produce a range with `start > end`. + #[test] + fn a_boundary_at_or_below_the_last_is_refused() { + let dir = tempfile::tempdir().unwrap(); + let b = SegmentBoundaries::open(dir.path(), 10).unwrap(); + b.add_bytes(10); + assert!(b.end_block(100).unwrap().is_some()); + b.add_bytes(10); + assert_eq!(b.end_block(100).unwrap(), None, "same block"); + b.add_bytes(10); + assert_eq!(b.end_block(99).unwrap(), None, "below the last"); + assert_eq!(b.boundaries().len(), 1); + } + + /// A reorg deeper than the lag reaches a range already built. That is not + /// an operational event -- on mainnet it means more than a thousand blocks + /// were abandoned, which implies the chain itself is under attack -- so the + /// builder stops and stays stopped until a human clears it. + #[test] + fn a_reorg_below_a_built_segment_halts_building() { + let dir = tempfile::tempdir().unwrap(); + let b = SegmentBoundaries::open(dir.path(), 10).unwrap(); + b.add_bytes(10); + b.end_block(5_000).unwrap(); + b.mark_built(1, 5_000, [0xAA; 32]).unwrap(); + + assert!(b.halted().is_none(), "nothing wrong yet"); + assert_eq!( + b.verify_built_still_canonical(|_| Some([0xAA; 32])).unwrap(), + None, + "same hash: the segment still describes the chain" + ); + assert!(b.halted().is_none()); + + // The chain now has a different block at that height. + let reason = b + .verify_built_still_canonical(|_| Some([0xBB; 32])) + .unwrap() + .expect("a changed hash must be reported"); + assert!(reason.contains("reorg deeper than the build lag"), "{reason}"); + + let halted = b.halted().expect("halt must be durable"); + assert!(halted.contains("Nothing will be built while this file exists")); + + // And it survives a restart: halting is not self-clearing. + let b2 = SegmentBoundaries::open(dir.path(), 10).unwrap(); + assert!(b2.halted().is_some(), "a halt must outlive the process"); + } + + /// A height that has vanished entirely is also a reorg past it. + #[test] + fn a_built_segment_whose_height_is_gone_halts_building() { + let dir = tempfile::tempdir().unwrap(); + let b = SegmentBoundaries::open(dir.path(), 10).unwrap(); + b.add_bytes(10); + b.end_block(42).unwrap(); + b.mark_built(1, 42, [0xCC; 32]).unwrap(); + + let reason = b + .verify_built_still_canonical(|_| None) + .unwrap() + .expect("an unknown height must be reported"); + assert!(reason.contains("no longer on the canonical chain"), "{reason}"); + assert!(b.halted().is_some()); + } + + /// The hash survives a restart, or the check could not run after one. + #[test] + fn the_hash_a_range_was_built_against_survives_a_restart() { + let dir = tempfile::tempdir().unwrap(); + { + let b = SegmentBoundaries::open(dir.path(), 10).unwrap(); + b.add_bytes(10); + b.end_block(77).unwrap(); + b.mark_built(1, 77, [0xDE; 32]).unwrap(); + } + let b = SegmentBoundaries::open(dir.path(), 10).unwrap(); + assert_eq!( + b.built(), + vec![BuiltRange { start: 1, end: 77, end_hash: Some([0xDE; 32]) }] + ); + } + + #[test] + fn the_collection_bound_tracks_the_lowest_unbuilt_range() { + let dir = tempfile::tempdir().unwrap(); + let b = SegmentBoundaries::open(dir.path(), 10).unwrap(); + + // Nothing closed yet: the open range starts at the first block, so its + // seed is the block before it. + assert_eq!(b.collection_bound(1), Some(0)); + + b.add_bytes(10); + b.end_block(1_000).unwrap(); + b.add_bytes(10); + b.end_block(2_000).unwrap(); + + // Two closed ranges pending, lowest first. + assert_eq!(b.collection_bound(1), Some(0), "1..1000 is unbuilt"); + + b.mark_built(1, 1_000, [1; 32]).unwrap(); + assert_eq!( + b.collection_bound(1), + Some(1_000), + "the floor follows the builder: 1001..2000 seeds from #1000" + ); + + b.mark_built(1_001, 2_000, [2; 32]).unwrap(); + assert_eq!( + b.collection_bound(1), + Some(2_000), + "all closed ranges built; the open range still seeds from #2000" + ); + } + + /// §7.1: a bound that waits for a human is a bound that fills the disk. + #[test] + fn a_halted_builder_holds_no_bound() { + let dir = tempfile::tempdir().unwrap(); + let b = SegmentBoundaries::open(dir.path(), 10).unwrap(); + b.add_bytes(10); + b.end_block(1_000).unwrap(); + assert_eq!(b.collection_bound(1), Some(0)); + + b.halt("deliberate, for the test").unwrap(); + assert_eq!( + b.collection_bound(1), + None, + "a halted builder must not hold the collector's floor down for ever" + ); + } + + /// §3.1: a range that cannot be built becomes a recorded hole, not an + /// infinite retry and not a segment that under-covers. + #[test] + fn a_written_off_range_stops_being_offered_and_stops_holding_the_floor() { + let dir = tempfile::tempdir().unwrap(); + let b = SegmentBoundaries::open(dir.path(), 10).unwrap(); + b.add_bytes(10); + b.end_block(1_000).unwrap(); + b.add_bytes(10); + b.end_block(2_000).unwrap(); + + assert_eq!(b.ready(10_000, 100, 1).len(), 2); + assert_eq!(b.collection_bound(1), Some(0)); + + assert_eq!(b.record_failure(1, 1_000), 1, "attempts are counted per range"); + assert_eq!(b.record_failure(1, 1_000), 2); + assert_eq!(b.record_failure(1_001, 2_000), 1, "and separately per range"); + + b.mark_uncovered(1, 1_000, "the seed state was collected").unwrap(); + + let ready = b.ready(10_000, 100, 1); + assert_eq!(ready.len(), 1, "the written-off range is not offered again"); + assert_eq!(ready[0].start, 1_001, "the builder moves on to the next one"); + assert_eq!( + b.collection_bound(1), + Some(1_000), + "and it stops holding the collector's floor at its own start" + ); + + // The hole is on disk, with a reason, and survives a restart. + let b2 = SegmentBoundaries::open(dir.path(), 10).unwrap(); + assert_eq!( + b2.uncovered(), + vec![UncoveredRange { + start: 1, + end: 1_000, + reason: "the seed state was collected".into() + }] + ); + assert_eq!(b2.ready(10_000, 100, 1).len(), 1); + assert_eq!( + b2.record_failure(1_001, 2_000), + 1, + "attempt counts are per process: a restart is a reason to try again" + ); + } + + /// A reason is free text from an error chain, which can contain anything. + /// A tab or a newline in it would make the record parse as a different one. + #[test] + fn a_reason_cannot_break_its_own_record() { + let dir = tempfile::tempdir().unwrap(); + let b = SegmentBoundaries::open(dir.path(), 10).unwrap(); + b.mark_uncovered(5, 9, "line one\nline\ttwo\t42\t99").unwrap(); + + let b2 = SegmentBoundaries::open(dir.path(), 10).unwrap(); + assert_eq!( + b2.uncovered(), + vec![UncoveredRange { start: 5, end: 9, reason: "line one line two 42 99".into() }], + "one record, with the separators flattened out of the reason" + ); + } + + /// The set can be extended underneath an existing log -- an operator + /// filling a hole offline moves where this builder starts. The boundaries + /// below that point then describe ranges that run backwards, and a builder + /// must never be handed one. + #[test] + fn a_boundary_below_the_builders_start_is_skipped() { + let dir = tempfile::tempdir().unwrap(); + let b = SegmentBoundaries::open(dir.path(), 10).unwrap(); + b.add_bytes(10); + b.end_block(1_000).unwrap(); + b.add_bytes(10); + b.end_block(5_000).unwrap(); + + // The set now covers up to #2,000, so this builder starts at #2,001 + // and the #1,000 boundary is behind it. + let ready = b.ready(10_000, 100, 2_001); + assert_eq!(ready.len(), 1, "only the range that runs forwards: {ready:?}"); + assert_eq!( + (ready[0].start, ready[0].end), + (2_001, 5_000), + "and the skipped boundary must not drag the next range's start back with it" + ); + assert_eq!(b.collection_bound(2_001), Some(2_000), "the floor follows the same rule"); + } + + #[test] + fn counting_writes_counts_and_delegates() { + use rustock_trie::TrieStore as _; + let dir = tempfile::tempdir().unwrap(); + let boundaries = std::sync::Arc::new(SegmentBoundaries::open(dir.path(), 1 << 40).unwrap()); + let inner = std::sync::Arc::new(rustock_trie::MemoryTrieStore::new()); + let counting = CountingWrites::new(inner.clone(), boundaries.clone()); + + counting.put(&[1u8; 32], b"hello"); + assert_eq!(boundaries.accumulated(), 32 + 5); + assert_eq!( + counting.get(&[1u8; 32]).as_deref(), + Some(&b"hello"[..]), + "reads pass through untouched" + ); + + counting.put_many(&[(vec![2u8; 32], vec![0u8; 10]), (vec![3u8; 32], vec![0u8; 20])]); + assert_eq!(boundaries.accumulated(), 37 + (32 + 10) + (32 + 20)); + assert!(inner.get(&[3u8; 32]).is_some(), "the batch reached the inner store"); + } +} diff --git a/crates/storage/src/segbuild_capture.rs b/crates/storage/src/segbuild_capture.rs deleted file mode 100644 index 7420527d..00000000 --- a/crates/storage/src/segbuild_capture.rs +++ /dev/null @@ -1,471 +0,0 @@ -//! Capture segbuild segments while the node syncs, durably. -//! -//! The node writes every trie node to its own store *and* to the open segment, -//! and copies into the segment every node it reads. Segbuild stops being a -//! separate replay job: the frontier never falls behind the head, and nothing -//! races the pruner. -//! -//! # Never half-done -//! -//! The first sketch of this buffered captured nodes in an in-memory window and -//! sealed by size. That loses up to a whole window on any restart, which is -//! the most ordinary operational event there is -- it would manufacture holes -//! routinely, and silently. -//! -//! So nothing is buffered. Captured nodes go straight into the open segment's -//! RocksDB, which has its own WAL, and the segment carries a **high-water -//! mark**: the highest block number whose capture is complete. The mark is -//! written at block boundaries, after that block's nodes. -//! -//! That makes the mark conservative by construction. A crash can only leave it -//! *behind* reality, never ahead -- the nodes are already durable when it -//! advances. On restart the node compares it against its execution head: -//! -//! * equal -- carry on; -//! * mark behind head -- the blocks between are uncaptured. Re-execute them, -//! or record the gap for the validation pass. Either is safe, because -//! **capture is idempotent**: nodes are content-addressed, so writing one -//! twice is a no-op and re-executing a block cannot corrupt a segment. -//! -//! A segment therefore always describes exactly what it holds, and the honest -//! answer to "is this segment complete" is a number on disk rather than an -//! inference. -//! -//! # The primary store stays authoritative -//! -//! Reads are answered by the node's own trie and copied into the segment; -//! writes reach the primary first. Capture is strictly additive, so a defect -//! in it can make a segment less complete but cannot change what the node -//! computes or persists. That is what makes this safe in a live node's path. -//! -//! # What a segment is sound for -//! -//! What its range *touched*, not the state that range can *reach* -- so, the -//! code that sealed it (`docs/trie-segments-design.md` §6.9d, #397/#398). -//! Live-built segments are a strong regression instrument and not an -//! independent check: a consensus bug in the node is captured into the segment -//! and later replays agree with it, as §8 warns of recorded roots. -use crate::RocksDbTrieStore; -use anyhow::{Context, Result}; -use rustock_trie::TrieStore; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, RwLock}; - -/// Reserved metadata key. Trie keys are 32-byte node hashes, so a key of any -/// other length cannot collide with one. -const HWM_KEY: &[u8] = b"segbuild:high-water-mark"; - -pub struct CaptureConfig { - /// Where segments are written. - pub dir: PathBuf, - /// Seal the open segment once it exceeds this. Checked at block - /// boundaries only, so a segment never stops mid-block. - pub seal_bytes: u64, -} - -struct Open { - store: RocksDbTrieStore, - path: PathBuf, - start_block: u64, - /// Highest block whose capture is complete and durable. - hwm: u64, -} - -pub struct SegbuildCapture { - primary: Arc, - cfg: CaptureConfig, - open: RwLock>, - /// Block currently executing. Capture belongs to it; the mark only - /// advances once it finishes. - current: AtomicU64, - sealed: AtomicU64, - captured: AtomicU64, - /// Serialises sealing against block-boundary bookkeeping. - seal_lock: Mutex<()>, - /// This block's captured nodes, written as one batch at `end_block`. - /// - /// Writing each node as it is touched cost 3.1 us -- measured at 7.6x the - /// bare store, which is 6--18 ms a block and would have halved the node's - /// sync rate. The high-water mark only needs durability at a block - /// boundary, so one batch per block gives the same guarantee: a crash - /// loses the block in flight either way, and the mark stays conservative - /// because it is written in the same batch as the nodes it covers. - pending: Mutex, Vec)>>, -} - -impl SegbuildCapture { - /// Open or resume capture. Returns the high-water mark found on disk, so - /// the caller can compare it with its execution head and decide whether - /// blocks need re-executing. - pub fn open(primary: Arc, cfg: CaptureConfig) -> Result<(Self, u64)> { - std::fs::create_dir_all(&cfg.dir) - .with_context(|| format!("creating {}", cfg.dir.display()))?; - let resumed = Self::find_open_segment(&cfg.dir)?; - let (open, hwm) = match resumed { - Some((path, start)) => { - let store = RocksDbTrieStore::open(&path) - .with_context(|| format!("reopening {}", path.display()))?; - let hwm = store - .get(HWM_KEY) - .and_then(|v| v.try_into().ok()) - .map(u64::from_be_bytes) - .unwrap_or(start); - (Some(Open { store, path, start_block: start, hwm }), hwm) - } - None => (None, 0), - }; - Ok(( - Self { - primary, - cfg, - open: RwLock::new(open), - current: AtomicU64::new(hwm), - sealed: AtomicU64::new(0), - captured: AtomicU64::new(0), - seal_lock: Mutex::new(()), - pending: Mutex::new(Vec::new()), - }, - hwm, - )) - } - - /// An unsealed segment is named `open-`; a sealed one follows the - /// existing `NNN-start-end/sealed` convention, so a half-written segment - /// can never be mistaken for a complete one by name. - fn find_open_segment(dir: &Path) -> Result> { - for e in std::fs::read_dir(dir)?.flatten() { - let name = e.file_name().to_string_lossy().to_string(); - if let Some(rest) = name.strip_prefix("open-") { - if let Ok(start) = rest.parse::() { - return Ok(Some((e.path(), start))); - } - } - } - Ok(None) - } - - fn ensure_open(&self, block: u64) -> Result<()> { - if self.open.read().unwrap().is_some() { - return Ok(()); - } - let path = self.cfg.dir.join(format!("open-{block}")); - let store = RocksDbTrieStore::open(&path) - .with_context(|| format!("creating {}", path.display()))?; - *self.open.write().unwrap() = - Some(Open { store, path, start_block: block, hwm: block.saturating_sub(1) }); - Ok(()) - } - - /// Call before executing `block`. Opens a segment if none is open. - pub fn begin_block(&self, block: u64) -> Result<()> { - self.ensure_open(block)?; - self.current.store(block, Ordering::SeqCst); - Ok(()) - } - - /// Call after `block` is fully executed and its state persisted. Advances - /// the durable mark, then seals if the segment is big enough. Advancing - /// after the fact is what keeps the mark conservative. - pub fn end_block(&self, block: u64) -> Result<()> { - let _g = self.seal_lock.lock().unwrap(); - let (size, should_seal) = { - let mut guard = self.open.write().unwrap(); - let Some(open) = guard.as_mut() else { return Ok(()) }; - // The mark rides in the same batch as the nodes it covers, so the - // two can never disagree after a crash. - let mut items = std::mem::take(&mut *self.pending.lock().unwrap()); - items.push((HWM_KEY.to_vec(), block.to_be_bytes().to_vec())); - open.store.put_many(&items); - open.store.flush(); - open.hwm = block; - let size = dir_size(&open.path); - (size, size >= self.cfg.seal_bytes) - }; - let _ = size; - if should_seal { - self.seal_locked(block)?; - } - Ok(()) - } - - /// Seal the open segment at `end`, renaming it to the sealed convention. - /// Called at a block boundary, so the recorded range is exactly what the - /// segment holds. - fn seal_locked(&self, end: u64) -> Result<()> { - let mut guard = self.open.write().unwrap(); - let Some(open) = guard.take() else { return Ok(()) }; - let start = open.start_block; - drop(open.store); // close RocksDB before renaming - let n = self.sealed.fetch_add(1, Ordering::Relaxed); - let final_dir = self.cfg.dir.join(format!("{n:03}-{start}-{end}")); - std::fs::create_dir_all(&final_dir)?; - std::fs::rename(&open.path, final_dir.join("sealed")) - .with_context(|| format!("sealing {} -> {}", open.path.display(), final_dir.display()))?; - Ok(()) - } - - /// Seal on a clean shutdown, so a graceful restart leaves no gap at all. - pub fn seal_for_shutdown(&self) -> Result<()> { - let _g = self.seal_lock.lock().unwrap(); - let end = { - let guard = self.open.read().unwrap(); - match guard.as_ref() { - Some(o) => o.hwm, - None => return Ok(()), - } - }; - self.seal_locked(end) - } - - pub fn high_water_mark(&self) -> u64 { - self.open.read().unwrap().as_ref().map(|o| o.hwm).unwrap_or(0) - } - - pub fn stats(&self) -> (u64, u64, u64) { - ( - self.captured.load(Ordering::Relaxed), - self.sealed.load(Ordering::Relaxed), - self.high_water_mark(), - ) - } -} - -fn dir_size(p: &Path) -> u64 { - let mut t = 0; - if let Ok(rd) = std::fs::read_dir(p) { - for e in rd.flatten() { - if let Ok(m) = e.metadata() { - t += m.len(); - } - } - } - t -} - -impl TrieStore for SegbuildCapture { - fn get(&self, key: &[u8]) -> Option> { - let v = self.primary.get(key)?; - if self.open.read().unwrap().is_some() { - self.pending.lock().unwrap().push((key.to_vec(), v.clone())); - self.captured.fetch_add(1, Ordering::Relaxed); - } - Some(v) - } - - fn put(&self, key: &[u8], value: &[u8]) { - // Primary first: the capture must never be ahead of what the node - // actually persisted. - self.primary.put(key, value); - if self.open.read().unwrap().is_some() { - self.pending.lock().unwrap().push((key.to_vec(), value.to_vec())); - self.captured.fetch_add(1, Ordering::Relaxed); - } - } - - fn flush(&self) { - self.primary.flush(); - if let Some(open) = self.open.read().unwrap().as_ref() { - open.store.flush(); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use rustock_trie::MemoryTrieStore; - - fn primary_with(pairs: &[(&[u8], &[u8])]) -> Arc { - let p = Arc::new(MemoryTrieStore::new()); - for (k, v) in pairs { - p.put(k, v); - } - p - } - - fn open_at(dir: &Path, primary: Arc) -> (SegbuildCapture, u64) { - SegbuildCapture::open( - primary, - CaptureConfig { dir: dir.to_path_buf(), seal_bytes: 1 << 40 }, - ) - .unwrap() - } - - /// The property this design exists for: a crash cannot leave the mark - /// ahead of what is durable. The mark advances only after a block's nodes - /// are written, so dropping mid-block loses the block, never the record. - #[test] - fn a_crash_mid_block_leaves_the_mark_behind_not_ahead() { - let dir = tempfile::tempdir().unwrap(); - let key = [7u8; 32]; - let primary = primary_with(&[(&key, b"v")]); - - { - let (cap, hwm) = open_at(dir.path(), primary.clone()); - assert_eq!(hwm, 0, "nothing captured yet"); - cap.begin_block(100).unwrap(); - let _ = cap.get(&key); - cap.end_block(100).unwrap(); - - // Block 101 starts, captures, and the process dies before - // end_block -- the `cap` is dropped with no seal and no mark. - cap.begin_block(101).unwrap(); - let _ = cap.get(&key); - } - - let (_cap, hwm) = open_at(dir.path(), primary); - assert_eq!(hwm, 100, "resumes at the last COMPLETED block, not the one in flight"); - } - - /// Re-executing a block after a crash must be safe. Nodes are - /// content-addressed, so capture is idempotent -- this is what makes - /// "backtrack to the mark and re-execute" a sound recovery. - #[test] - fn re_executing_a_block_is_idempotent() { - let dir = tempfile::tempdir().unwrap(); - let key = [9u8; 32]; - let primary = primary_with(&[(&key, b"val")]); - let (cap, _) = open_at(dir.path(), primary); - - for _ in 0..3 { - cap.begin_block(500).unwrap(); - let _ = cap.get(&key); - cap.end_block(500).unwrap(); - } - assert_eq!(cap.high_water_mark(), 500); - let open = cap.open.read().unwrap(); - assert_eq!( - open.as_ref().unwrap().store.get(&key).as_deref(), - Some(&b"val"[..]), - "value unchanged by repeated capture" - ); - } - - /// An unsealed segment is named `open-` and a sealed one - /// `NNN-start-end/sealed`, so a half-written segment cannot be mistaken - /// for a complete one by a reader that only looks at names. - #[test] - fn an_unsealed_segment_is_not_named_like_a_sealed_one() { - let dir = tempfile::tempdir().unwrap(); - let key = [1u8; 32]; - let primary = primary_with(&[(&key, b"x")]); - let (cap, _) = open_at(dir.path(), primary); - cap.begin_block(10).unwrap(); - let _ = cap.get(&key); - cap.end_block(10).unwrap(); - - let names: Vec = std::fs::read_dir(dir.path()) - .unwrap() - .flatten() - .map(|e| e.file_name().to_string_lossy().to_string()) - .collect(); - assert!(names.iter().any(|n| n == "open-10"), "got {names:?}"); - assert!(!names.iter().any(|n| n.contains("sealed")), "nothing sealed yet: {names:?}"); - - cap.seal_for_shutdown().unwrap(); - let after: Vec = std::fs::read_dir(dir.path()) - .unwrap() - .flatten() - .map(|e| e.file_name().to_string_lossy().to_string()) - .collect(); - assert!(after.iter().any(|n| n == "000-10-10"), "sealed with its range: {after:?}"); - assert!(!after.iter().any(|n| n.starts_with("open-")), "no open segment left"); - assert!(dir.path().join("000-10-10/sealed/CURRENT").exists(), "sealed layout"); - } - - /// Capture is additive: the primary decides every answer, including - /// absence, so a defect in capture cannot change what the node sees. - #[test] - fn the_primary_answers_every_read() { - let dir = tempfile::tempdir().unwrap(); - let key = [3u8; 32]; - let primary = primary_with(&[(&key, b"authoritative")]); - let (cap, _) = open_at(dir.path(), primary); - cap.begin_block(1).unwrap(); - assert_eq!(cap.get(&key).as_deref(), Some(&b"authoritative"[..])); - assert_eq!(cap.get(&[4u8; 32]), None, "absence comes from the primary"); - } - - /// Sealing by size happens at a block boundary, never mid-block. - #[test] - fn sealing_lands_on_a_block_boundary() { - let dir = tempfile::tempdir().unwrap(); - let key = [5u8; 32]; - let primary = primary_with(&[(&key, &[0u8; 4096])]); - let (cap, _) = SegbuildCapture::open( - primary, - CaptureConfig { dir: dir.path().to_path_buf(), seal_bytes: 1 }, - ) - .unwrap(); - cap.begin_block(42).unwrap(); - let _ = cap.get(&key); - cap.end_block(42).unwrap(); // size exceeded -> seals here - assert!(dir.path().join("000-42-42/sealed").exists(), "sealed at the boundary"); - // A new block opens a fresh segment rather than reopening the sealed one. - cap.begin_block(43).unwrap(); - assert!(dir.path().join("open-43").exists()); - } -} - -/// What capture costs, measured rather than assumed -- step 2 of enabling this -/// on a live node. Run with: -/// cargo test -p rustock-storage --release capture_overhead -- --ignored --nocapture -#[cfg(test)] -mod overhead { - use super::*; - use rustock_trie::MemoryTrieStore; - use std::time::Instant; - - #[test] - #[ignore = "timing; run explicitly"] - fn capture_overhead() { - const N: usize = 200_000; - let keys: Vec<[u8; 32]> = (0..N) - .map(|i| { - let mut k = [0u8; 32]; - k[..8].copy_from_slice(&(i as u64).to_be_bytes()); - k - }) - .collect(); - let val = vec![0u8; 70]; // mean trie node, per 6.9b - - // Baseline: the node's store alone. - let plain = Arc::new(MemoryTrieStore::new()); - let t = Instant::now(); - for k in &keys { - plain.put(k, &val); - } - for k in &keys { - let _ = plain.get(k); - } - let base = t.elapsed().as_secs_f64(); - - // With capture. - let dir = tempfile::tempdir().unwrap(); - let primary = Arc::new(MemoryTrieStore::new()); - let (cap, _) = SegbuildCapture::open( - primary, - CaptureConfig { dir: dir.path().to_path_buf(), seal_bytes: 1 << 40 }, - ) - .unwrap(); - cap.begin_block(1).unwrap(); - let t = Instant::now(); - for k in &keys { - cap.put(k, &val); - } - for k in &keys { - let _ = cap.get(k); - } - let with = t.elapsed().as_secs_f64(); - cap.end_block(1).unwrap(); - - let (captured, _, hwm) = cap.stats(); - eprintln!(" {N} puts + {N} gets"); - eprintln!(" primary only : {base:.3}s"); - eprintln!(" with capture : {with:.3}s ({:.2}x)", with / base); - eprintln!(" captured {captured} nodes, hwm {hwm}, segment {} MB", - dir_size(&dir.path().join("open-1")) / 1_048_576); - eprintln!(" per-node capture cost: {:.1} us", (with - base) / (2.0 * N as f64) * 1e6); - } -} diff --git a/docs/generating-segbuild.md b/docs/generating-segbuild.md index e3eae57a..098ad6c9 100644 --- a/docs/generating-segbuild.md +++ b/docs/generating-segbuild.md @@ -189,12 +189,67 @@ tail arrives at the anchor. ## 3. Keeping the set current -Rebuilding from an archive every time the chain advances does not scale. -`crates/storage/src/segbuild_capture.rs` captures segments as a by-product of -normal syncing: writes go to both stores, reads come from the primary and are -written to the capture, and a sealed segment is closed when it fills. It is -crash-safe — the high-water mark is written in the same atomic batch as the -nodes it describes — and costs about 1.24x per-block execution. - -**It is not wired into the node yet.** See -[`trie-capture-design.md`](trie-capture-design.md) for what remains. +Rebuilding from an archive every time the chain advances does not scale, so the +node extends the set itself — **not** by capturing as it syncs, but by deciding +where segments should be cut and re-executing each range afterwards. + +The node syncs normally into its own store and adds each block's written bytes +to a counter. When enough has accumulated, the block number is recorded as a +boundary. Once the head is `--segbuild-lag` blocks past a boundary, a background +task builds that range by re-executing it from the node's own store. + +```sh +rustock-cli --segbuild-out /path/to/segbuild \ + --segbuild-target-mb 1024 \ + --segbuild-lag 1000 +``` + +Blocks are executed twice. At the tip that is close to free — a 1,000-block +range is about ten seconds of work per eight hours of chain — and it buys two +properties interception could not give: + +- **The segment is exactly its range's read set.** A settled range of canonical + blocks, re-executed in isolation, touches exactly the nodes it needs. Capture + by interception also collected state from blocks executed beside the chain + that never became canonical, so the segment stopped being the read set of its + range. +- **It cannot produce a wrong segment.** The build verifies every state root and + aborts on a missing node, so a failure leaves no segment rather than one that + silently under-covers. + +### 3.1 What the node checks before it starts extending + +`--segbuild-out` must point at a set that is **current**, and the node says so +at startup rather than discovering it later: + +- the directory must already hold at least one `NNN-start-end` segment — a + continuous builder extends a set, it cannot bootstrap one, because the + pre-fork era needs the baseline of §2; and +- the executed head must not be more than `--segbuild-lag` blocks past the set's + end. A gap cannot be built from the node's store: that state has been + collected. Fill it with §1 against an archive first. + +### 3.2 How a pending range is kept alive + +The node's trie store is garbage-collected, so a range waiting to be built has +to be protected, and it takes two things that each cover what the other cannot: + +- a **collection bound** at the block the range seeds from, which keeps + everything blocks after it wrote — including nodes created and destroyed + inside the range, which no state reaches; and +- a **pin** on that same block's state root, which keeps the seed trie, whose + nodes were written below the bound. + +Both are derived from one number and registered automatically. A builder that +falls more than `--gc-max-bound-lag` blocks behind loses the protection — a node +out of disk is worse than an incomplete set. Once the collector has actually +swept beneath a pending range, that range is written off into `UNCOVERED` +*without being attempted*: the store's own watermark says its nodes are not +recoverable, so replaying it would only read into the hole. A build that fails +for any other reason — a full disk, a damaged store — is retried twice more and +then written off the same way. `UNCOVERED` is the set's list of known holes, +which §1 can fill from an archive. + +See [`segbuild-continuous-design.md`](segbuild-continuous-design.md) for the +argument in full, and [`trie-capture-design.md`](trie-capture-design.md) for why +interception was abandoned. diff --git a/docs/segbuild-continuous-design.md b/docs/segbuild-continuous-design.md new file mode 100644 index 00000000..2c81f93e --- /dev/null +++ b/docs/segbuild-continuous-design.md @@ -0,0 +1,525 @@ +# Keeping the segment set current: deferred re-execution + +**Status:** implemented. `rustock_storage::segbuild_boundaries` is the counter +and the logs, `rustock_execution::segment_build` is the builder, and +`--segbuild-out` turns it on. The retention mechanism is +`EpochTrieStore::collect_bounded`. What is not settled is §7.3. + +The segment set covers `#1..#9,420,000` and the chain keeps moving. Rebuilding +from a 131 GB archive every time is not a plan, so the set has to extend itself +as the node syncs. This is how, and why it is not the obvious way. + +Read [`trie-capture-design.md`](trie-capture-design.md) first if you want the +history: it is the retrospective on the previous attempt and the source of the +rules this design is trying to satisfy. + +--- + +## 1. The obvious design, and why it was abandoned + +Intercept the execution trie store, write every node to both the node's own +store and an open segment, copy every read into the segment, seal by size. +`crates/storage/src/segbuild_capture.rs` implemented exactly this, with a +high-water mark written in the same atomic batch as the nodes so a crash could +never leave the mark ahead of the data. Measured cost: **1.24x** per-block +execution, after batching per block brought it down from 7.6x. + +It works, and it was merged. It is still the wrong design, and wiring it into +the node is what made that clear. Three problems, none of which is a bug in the +module: + +**It captures uncles.** The node executes blocks beside the chain before +adopting them. Those executions read and write state through the same store, so +an intercepting segment accumulates nodes from branches that never became +canonical. The segment's range then claims to describe the canonical chain while +holding state from blocks that are not on it. Harmless for reads — nodes are +content-addressed — but the segment is no longer *the read set of its range*, +which is the only property that makes it verifiable. + +**Fast-forwarded blocks break the mark.** `fast_forward_state` adopts a block +without re-running the EVM when it was already executed beside the chain. Its +nodes were written earlier, possibly in a previous process, possibly before +capture was enabled. Advancing the mark over such a block asserts coverage the +segment may not have. Three mitigations were considered and all of them push +complexity into the hot path. This is not rare: a single branch switch on +mainnet logged *"4 taken up without executing any again"*. + +**Every operational event becomes a reconciliation case.** Restart, crash +mid-block, reorg past the mark, enabling the feature on a node with history — +each needs a rule, and each rule can only be tested by contriving the event. +A first implementation grew four reconciliation outcomes and a `GAPS` file +before the fast-forward question even surfaced. + +The common thread: **interception makes the segment a side effect of whatever +the node happened to do**, including things that have nothing to do with the +canonical chain. + +--- + +## 2. The design + +Stop intercepting. Let the node sync normally into its own store, and build +each segment afterwards by **re-executing the range it covers**. + +``` + node syncs normally, one store, no interception + │ + per block: add bytes-written to a counter + │ + counter >= target ──► record a boundary: "segment ends at block B" + │ + B + lag blocks later ──► background build of [A..B] from the + node's own store, via build_segments + │ + verified segment, sealed +``` + +Three moving parts: + +**A byte counter.** Each executed block adds the bytes it wrote to the node's +trie store. Nothing is copied; the counter is the whole of the hot-path cost. + +**A boundary log.** When the counter reaches the target the current block number +is appended to a boundary log and the counter resets. A boundary is a *decision* +about where a segment ends, recorded durably and cheaply, long before the +segment exists. Appending a number and fsyncing is the only durability the hot +path needs. + +**A deferred builder.** Once the head is `lag` blocks past a recorded boundary, +a background task runs `build_segments` over that range, reading state from the +node's own store. Same tool that built the existing 161 GB set, which verifies +every block's state root as it goes. + +### 2.1 What this buys + +**The segment is exactly its range's read set.** A settled range of canonical +blocks, re-executed in isolation, touches exactly the nodes that range needs. +No uncles, no beside-the-chain execution, no dependence on what the node did +while it was syncing. + +**It cannot produce a wrong segment.** `build_segments` verifies every state +root and aborts on a missing node. A failed build leaves no segment; it does not +leave a segment that silently under-covers. Compare the intercepting design, +whose failure mode was the hot path carrying on while the segment quietly lost +nodes — the §6.9d hazard, where a missing node is indistinguishable at the API +from a genuine absence. + +**It is retryable and interruptible.** A build that fails or is killed can be +re-run from its boundary. Nothing is half-done, because the segment only becomes +real at the end. + +**The hot path keeps one invariant instead of five.** No mark, no pending +buffer, no seal-at-boundary, no reconciliation, no fast-forward question. A +counter and an append. + +### 2.2 What it costs + +**Every block executes twice.** Once by the node, once by the builder. + +At the tip this is close to free, and it is worth being precise about why: a +block arrives roughly every 30 seconds, and the builder re-executes recent +blocks at about 100 blocks/s with the segment resident. A 1,000-block range is +~10 seconds of work per ~8 hours of chain. The node is idle almost all of that +time; the second execution fits in the gaps. + +During catch-up sync it is a real cost: the node is CPU-bound and the builder +competes with it. The builder may therefore fall behind and catch up later — but +not arbitrarily far. A pending range holds the collector's floor (§7), and past +`max_bound_lag` the floor is released and the state the range needs is +collected. The *decision* survives either way, because the boundary log is +durable; the state does not, and such a range has to be filled from an archive. + +--- + +## 3. Is the state still there? The retention argument + +The builder reads historical state from a **garbage-collected** store, `lag` +blocks after the fact. Whether that works is the question the whole design rests +on, and the answer is in `EpochConfig`: + +```rust +Self { epochs: 4, burial_depth: 4_000, rotate_bytes: 1 << 30 } +``` + +A node survives until the epoch holding it is swept, and the collection root +sits `burial_depth` below the head. Consider the three kinds of node a +re-execution of `[A..B]`, `B = head - lag`, can need: + +| node | still there? | +|---|---| +| written during `[A..B]` | only if its epoch has not been swept | +| written earlier, still in the state at some block of `[A..B]` | only if it is also in the state at the collection root | +| written earlier, already dead before `A` | not needed: it is in no state the range reads | + +**The first two are not free, and `lag < burial_depth` does not give them.** An +earlier draft of this document claimed it did, by arguing that the collection +root sits below `B` and therefore below everything the range writes. The +collection root sits below `B`, but it sits *inside* `[A..B]`, because a segment +is far longer than the lag: with the defaults the root is at `head - 4,000` +while `A` is around `head - 90,000`. So + +- a node written at `A + 5` and dead by `A + 9` is reachable from no state at + all, including the collection root's, and +- a node present in the state at `A - 1` but superseded at `A + 100` is not in + the state at the collection root either. + +Both are read by the re-execution. Nothing in the collector keeps them unless +it is told to. + +So retention is **arranged, not argued**: the builder registers a bound and a +pin, and §7 gives the mechanism and why one without the other is not enough. +The short version is that the two halves are exhaustive — a node read while +re-executing `[A..B]` was either already in the trie at `A - 1`, which the pin +keeps, or written by a block at or after `A`, which the bound keeps — and that +`SegmentBoundaries::collection_bound` is the single place that computes both. + +Granularity is epoch-level, which is coarser than necessary and therefore +conservative: it keeps more than asked, never less. + +The sweep gate this builds on is not a soft guarantee. It is enforced in +`collect_inner`, with a recorded incident behind it: seeding a store with one +epoch, executing 3,800 blocks into it and collecting against a root below those +blocks destroyed exactly that state, and execution went on to read zeros and +compute 176,127 gas for a block whose header said 328,664. + +### 3.1 What still has to be handled + +The guarantee is about the *collector*, not about everything that can go wrong. +A build can still fail to read a node — a corrupted store, a manual collection +forced against a bad root, a `lag` configured above `burial_depth`. The builder +must therefore treat a missing node as what it is: + +- **abort the build for that range** (it already does), and +- **record the range as uncovered**, so the hole is a fact on disk rather than a + gap someone notices later by comparing segment names. + +The set then has a known hole that can be filled from an archive, rather than a +segment that lies. + +--- + +## 4. Components and contracts + +### 4.1 The counter + +Signal: **bytes written to the trie store per executed block**, not a block +count. Equal block counts produce segments from 0.2 GB to over 2 GB because cost +per block varies tenfold across eras; equal bytes produce the ~1 GB segments +that fit in a consumer's memory, which is the property that makes replaying one +fast. + +The counter is approximate by design. It drives *where to cut*, and a cut in +roughly the right place is all that is needed. + +### 4.2 The boundary log + +Append-only, one line per boundary, fsynced: + +``` +\t\t +``` + +Durability requirement: a boundary must survive a crash, because losing one +means two segments merge into an oversized one. Durability is cheap here — +one line per gigabyte of state written. + +A boundary is **advisory until a build succeeds**. If a build fails, the +boundary stays in the log and the range stays unbuilt. After three failures it +is written off into a third log, `UNCOVERED` — §3.1's requirement that a hole be +a fact on disk, and what lets the builder carry on with later ranges instead of +looping on the one it cannot do. + +**Where the cut decision is made: by the background task, at the executed +head.** The counter is incremented by the store wrapper, per write. The decision +to *cut* is taken by the same task that builds, which reads the node's executed +head and calls `end_block` on it. + +This needs no hook in the execution loop, and it cannot name a block that has +not been executed — which matters, because a segment can only be built from +state that exists. The cost is that a cut lands on the first poll after the +target is crossed rather than exactly on it, which is acceptable for the same +reason the counter is approximate: sizes are advisory. + +Only the handle the block processor writes through is wrapped. The readers' +handle is not: an `eth_call` writes speculative state through the same store, +and counting it would cut segments early for no reason. + +### 4.3 The deferred builder + +`rustock_execution::segment_build`, which is the library form of the +`build_segments` example that built the existing 161 GB set, reduced to the one +case a running node needs: one range, no chunk claiming, no worker pool, no +baseline. It runs when `exec_head >= boundary + lag`. For range `[A..B]`: + +1. seed from the state root at `A - 1`, read from the node's store **and put + into the window as it is read** — this read is the one in the whole build + that bypasses copy-on-read, and leaving it out is why 96 of the original 97 + chunks could not replay their own first block; +2. replay `A..B`, verifying every state root against its header; +3. seal the window; +4. rename `.building-A-B` to `NNN-A-B`; +5. record the range built, with the canonical hash at `B`. + +Constraints: + +- **One build at a time.** Two concurrent builds double the memory and compete + with the node for the same store. +- **Read-only on the node's store.** Everything read is copied into the window, + and the window is what is written. +- **Bounded memory.** Two in-memory tables of `--segbuild-seal-mb`, which is the + builder's budget and not the segment size: a segment is the whole range, and + sealing a table merely flushes it into the segment's store. Three workers at + 700 MB x 2 tables was the measured ceiling on a 7.7 GB box, and a fourth was + *worse* than three. +- **Killable.** A killed build leaves `.building-A-B`, which no reader parses as + a segment, and resumes from its last checkpoint. + +**Step 4 is the commit.** Nothing that reads the set can see a half-built +segment, because until the rename there is no name that parses as one. This is +what makes "either a correct segment or no segment" structural rather than a +property of the error handling: the mismatch path, the missing-node path, the +cancel path and a SIGKILL all leave the same thing behind. + +### 4.4 Numbering, and not colliding with the existing set + +The existing set uses `000`–`097` and `900`–`908`. A continuous builder must +take indices that cannot collide, and must continue across restarts rather than +restarting at `000` — an index that repeats stops indicating order, which is +what made two abandoned directories sharing an index hard to diagnose (§11 of +`trie-segments-design.md`). + +Take the highest existing index and continue. Only a name that is exactly +`NNN-start-end` counts; a suffixed name is retired and must not influence +numbering. + +--- + +## 5. Failure modes + +| event | what happens | +|---|---| +| node restarts | counter resets, so one segment is cut late. Harmless: sizes are advisory | +| crash mid-build | `.building-A-B` stays behind, which no reader parses as a segment; the build resumes from its last checkpoint | +| reorg below a boundary | the boundary is above `head - lag` and so not yet built; re-record it | +| reorg below an already-built segment | only possible for a reorg deeper than the lag. A `HALTED` file is written and building stops until a human clears it (§7) | +| missing node during a build | abort; after three attempts the range is written off into `UNCOVERED` and stops holding the floor | +| builder falls behind | ranges queue up and hold the collector's floor. Past `max_bound_lag` the floor is released and those ranges fail on missing state, each written off after three attempts | +| disk fills | build fails, boundary stays unbuilt, node unaffected | + +The shape worth noticing: every failure leaves either a correct segment or no +segment. None leaves a segment that claims more than it holds. + +--- + +## 6. What this replaces + +`crates/storage/src/segbuild_capture.rs` is deleted. Its crash-safety +machinery — the high-water mark in the same batch as the nodes, the per-block +pending buffer, seal-at-a-block-boundary — solves problems this design does not +have. + +**Deleted rather than left in place.** 471 lines of unused dual-write code +implies it is the supported path. Its measurement is worth keeping, and is +recorded here: interception costs 1.24x per-block execution after per-block +batching, and 7.6x without. + +--- + +## 7. Decisions and open questions + +**A reorg below a built segment: decided — halt and require a human.** + +Nothing is built until it is `lag` blocks settled, so a reorg can only reach a +built range by being deeper than the lag. On mainnet that is more than a +thousand blocks abandoned, which is not an operational event: it means a +majority of miners rewrote settled history, and the social contract has failed +before the segment set has. Recovering gracefully from it would be designing +for a world in which the chain's assumptions do not hold. + +**The builder stops. The node does not.** This is the whole meaning of +fail-stop here, and it is worth stating because the phrase invites the opposite +reading: the node must keep following the chain, keep serving RPC and keep +answering queries, because that is exactly how an operator finds out what +happened. A node that stopped would remove the instrument needed to diagnose +the event. + +That has a hard consequence for the implementation. **Nothing in the segbuild +path may be fatal to the node.** Not a halt, not a failed build, not a full +disk, not a panic in a builder thread. Concretely: every lock in +`segbuild_boundaries` is taken poison-tolerantly, so a panic in a builder +thread cannot poison a lock and then panic the node's execution path on the +next block; and the builder's errors must be logged and dropped by the caller +rather than propagated into sync. Extending the segment set is a by-product. +Failing to extend it is not a reason to stop following the chain. + +`BUILT` records the canonical hash at each range's end +block, every tick compares it against the chain's current hash at that height, +and a mismatch — or a height that no longer has a canonical block at all — +writes a `HALTED` file with the reason and stops building. Nothing is built +while that file exists, it is not self-clearing, and it survives a restart: the +fault is in the chain rather than in this process, so a builder that resumed on +its own would quietly produce segments across a discontinuity. + +Clearing it is deliberate and manual. Investigate, repair the set if needed, +remove the file. + +The check is cheap — one canonical-hash lookup per built range — and is only +meaningful because of the lag. Without it, ordinary shallow reorgs would trip +the alarm constantly. + +**Protecting a pending range: decided — a bound *and* a pin.** + +An earlier draft of §3 argued the state is retained anyway. It is not, so this +is not a nicety: without it the builder reads a hole. + +**A pin alone is the wrong shape.** `collect_pinned` keeps everything +*reachable from a state*, which is what the snapshot checkpoint needs. A segment +needs every node its *block range touched*, including nodes created and +destroyed inside the range, which no state at either end reaches. Pinning the +seed root at `A - 1` protects the seed and misses those. + +**A bound alone is also not enough**, and this is the part that is easy to get +backwards. A bound keeps what blocks *after* it wrote. The seed trie at `A - 1` +was written *before* it, and a node of that trie that is superseded at `A + 100` +is in no state the collector marks — not the collection root's, since the root +sits at `head - 4,000`, well above `A`. The bound does not keep it. + +**So both, and they are exhaustive.** A node read while re-executing `[A..B]` +was written either before `A` or at/after `A`. If before, and it is still needed, +it is in the trie at `A - 1` — that is what "still needed" means — and the pin +keeps it. If at or after, the bound keeps it. One block number, +`A - 1`, produces both: the bound is that number, the pin is the state root the +header at that number declares. `SegmentBoundaries::collection_bound` returns +it, and the GC cycle turns it into one bound and one pin. + +**Why a bound is the right shape for its half**: "the nodes a block range +touched" is a statement about blocks, and the epoch store already tags writes by +block. Each epoch records `last_block`, and the sweep gate is already a block +comparison: + +```rust +match oldest.last_block { + Some(b) if b <= root_block => {} // safe to sweep + Some(b) => bail!("refusing to sweep: ... writes up to block {b} ...") +``` + +So the mechanism is to generalise that single threshold into a minimum: + +``` +threshold = min(root_block, every registered bound) +sweep the oldest epoch only if epoch.last_block <= threshold +``` + +The collector's own `root_block` is simply the bound it imposes on itself. + +Bounds are supplied the way pins are, by a callback evaluated per cycle +(`gc_bounds` alongside `gc_pins`), so nothing is stored and nothing has to be +revoked: a range stops holding the floor the moment it is built and drops out +of the pending set. Persistence across restarts is free, because the pending +ranges are the difference between `BOUNDARIES` and `BUILT`. + +In steady state the bound costs nothing. The builder is `lag` blocks behind, so +the lowest unbuilt range starts about one segment back, while the oldest of four +one-gigabyte epochs holds writes from about three segments back — comfortably +below the floor, so the sweep proceeds as it always did. The bound bites only +when the builder falls behind by epochs rather than blocks, which is exactly +when it should. + +### 7.1 A bound that stops advancing must not fill the disk + +A bound blocks collection. A builder that is stuck, crashed, or simply far +behind therefore holds the floor down, and the store grows without limit. By +the rule in §7 that is not allowed to harm the node, so a bound has to be +accountable: + +- **Report it.** Every cycle, log which bound holds the floor and how far below + the head it sits. A floor drifting away from the head is the symptom. A held + floor is reported as an *outcome*, not an error: `CollectStats::held_by_bound` + names it and the cycle returns `Ok`, because a cycle that failed once a minute + would bury the failures that matter. +- **Override a stale one.** Past a configured distance the bound is ignored, + loudly. The reasoning is `CollectStats::unservable`'s: an incomplete segment + set is a thing to repair later, a node out of disk is not. + +The override must be loud enough to be acted on, because the consequence is a +gap in the set. It is the same trade as refusing to abort a cycle for an +unservable pin: do not turn one broken thing into two. + +**Interaction with the snapshot checkpoint pin.** Both want state kept alive, +and they compose by construction: the live set is a union, bounds are a minimum, +and the segment's own seed root joins the snapshot roots in the same pin list. +It has not been *measured* with both active, which is the part still open — the +cost of a pin is the delta between it and the collection root, and a seed root +one segment back is a larger delta than a snapshot checkpoint 10,000 blocks +back. + +### 7.2 Enabling it needs a current set, and that is checked at startup + +A gap between where the set ends and where the node has executed cannot be +built from the node's store: the state those ranges read is long collected. So +`--segbuild-out` refuses at startup if + +- the directory holds no `NNN-start-end` segment at all — a continuous builder + extends a set, it cannot bootstrap one, because the pre-fork era needs a + baseline the node does not have; or +- the executed head is more than `lag` blocks past the set's end — the operator + fills the gap with the offline tool against an archive first. + +Refusing at startup rather than at runtime is the one place where segbuild may +stop the node, and it is not really an exception: nothing is serving yet, the +flag was explicitly asked for, and the alternative is a node that looks +configured while recording ranges that must fail. + +### 7.3 Still open: the builder during a long catch-up + +The startup check in §7.2 keeps a *gap* out of the picture, but it cannot stop a +node that starts current from falling behind afterwards — a week of downtime, a +partition, a stall. Then the node executes forward while the builder re-executes +the same blocks a second time on the same box, so the builder loses ground at +roughly one block for every block gained. + +The arithmetic says how much that costs, and it is less than it first looks: + +| quantity | default | as chain time | +|---|---|---| +| `--gc-max-bound-lag` | 12,000 blocks | ~4 days | +| one segment | ~90,000 blocks | ~31 days | + +A pending range keeps its protection until the builder is `max_bound_lag` behind +the executed head. Past that the floor is released, the range's seed is +collected, and the build fails — on its *first* lookup, before any replay, so +three attempts cost three lookups rather than minutes. The range is then written +off into `UNCOVERED` and the builder moves on. + +So the consequence of leaving this alone: a node resuming from more than roughly +a week of downtime records a hole for each segment it passed, cheaply and +loudly, and the holes are filled from an archive with §1. Not a cascade, not +expensive, but not free either. + +**Decided — skip, don't attempt.** The builder asks the store what it has +already collected, and a range the collector has swept beneath is written off +without being replayed. + +The predicate is the store's own **collection watermark** +(`EpochTrieStore::collected_below`), not the builder's distance from the head. +That distinction is the whole point: distance says a range *lost its +protection*, which is not the same as having been collected — nothing is gone +until a sweep actually reaches it, and a range that still has its nodes should +still be built. The watermark is a recorded fact with exactly the meaning +needed: a node missing beneath it was taken by the collector and is not +recoverable from this store, while a node missing above it is damage. So the +test is `collected_below >= range.start`, and a range that passes it is +recorded in `UNCOVERED` with that reason, releases the floor, and is never +offered again. + +This costs nothing in the normal case — the watermark trails the collection +root, which trails the head — and in the bad case it turns minutes of replay +into a lookup, three times over into once, and a confusing mid-build failure +into a sentence an operator can act on. + +**Still open — idle-only.** Should the builder stop building entirely while the +node is more than `lag` blocks behind the best header? It would free CPU for +catch-up exactly when the node needs it, at the cost of guaranteeing the holes +that the rule above merely records sooner. That is a policy decision about a +production node rather than a code question: it trades segment coverage for +sync speed, and which an operator wants depends on why their node is behind. diff --git a/docs/tools.md b/docs/tools.md index 6c593aa6..ca2e9bd0 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -78,9 +78,16 @@ usage. ## Snapshot sync and segments +Building the initial set is +[`generating-segbuild.md`](generating-segbuild.md); a running node extends it +itself, which is +[`segbuild-continuous-design.md`](segbuild-continuous-design.md). The tools +below are for building a set from an archive, and for asking what a segment +does and does not hold. + | tool | what it answers | |---|---| -| [`build_segments`](../crates/cli/examples/build_segments.rs) **(writes)** | Replay a block range, verifying every state root, and build the range's trie segments as a by-product. | +| [`build_segments`](../crates/cli/examples/build_segments.rs) **(writes)** | Replay a block range, verifying every state root, and build the range's trie segments as a by-product. The library form a node uses is `rustock_execution::segment_build`. | | [`audit_chunk`](../crates/cli/examples/audit_chunk.rs) | What does a segment chunk NOT contain that a consumer needs? | | [`patch_size`](../crates/cli/examples/patch_size.rs) | How many nodes would it take to make a chunk answer the lookups it cannot? | | [`repair_chunk`](../crates/cli/examples/repair_chunk.rs) **(writes)** | Make a segment chunk answer the lookups a foreign client issues. | diff --git a/node-light.example.toml b/node-light.example.toml index f2945769..499f1a1a 100644 --- a/node-light.example.toml +++ b/node-light.example.toml @@ -190,6 +190,36 @@ backend = "epoch" # light: bounds state size. This setting ALO # rotate_mb = 1024 # default # burial = 4000 # default # check_secs = 60 # default +# A bound is a consumer saying "do not discard what blocks after this wrote" -- +# a segment build that has not run yet. It blocks collection while it is held, +# so a consumer that is stuck or far behind would hold the floor down until the +# disk filled. Past this distance from the head the bound is ignored, loudly: +# an incomplete segment set is a thing to repair later, a node out of disk is +# not. +# max_bound_lag = 12000 # default + +# Extending the segbuild segment set while syncing. The node counts the bytes +# each block writes, records where segments should end, and re-executes each +# range once it is `lag` blocks settled -- so blocks are executed twice, which +# at the tip is about ten seconds of work per eight hours of chain. See +# docs/segbuild-continuous-design.md. +# +# `out` must already hold a `NNN-start-end` segment and be current with this +# node's executed head, or the node refuses to start: the blocks in a gap +# cannot be rebuilt from a garbage-collected store, so recording them would +# only record ranges that must fail. Unset leaves the feature off. +# +# `target_mb` is the segment size, in written state rather than blocks: cost +# per block varies tenfold across eras, so equal block counts give segments +# from 0.2 GB to over 2 GB while equal bytes give ones a consumer can hold in +# memory. `seal_mb` is something else -- the builder's own memory budget, two +# tables of it, flushed into the segment as they fill. +[segbuild] +# out = "/var/lib/rustock/segbuild" # default: unset +# target_mb = 1024 # default +# lag = 1000 # default +# seal_mb = 256 # default + # Block-history pruning: bodies, receipts, the transaction index, headers and # the canonical mapping, for blocks far enough behind. diff --git a/node.example.toml b/node.example.toml index 26db8123..53d96d0b 100644 --- a/node.example.toml +++ b/node.example.toml @@ -182,6 +182,36 @@ # rotate_mb = 1024 # default # burial = 4000 # default # check_secs = 60 # default +# A bound is a consumer saying "do not discard what blocks after this wrote" -- +# a segment build that has not run yet. It blocks collection while it is held, +# so a consumer that is stuck or far behind would hold the floor down until the +# disk filled. Past this distance from the head the bound is ignored, loudly: +# an incomplete segment set is a thing to repair later, a node out of disk is +# not. +# max_bound_lag = 12000 # default + +# Extending the segbuild segment set while syncing. The node counts the bytes +# each block writes, records where segments should end, and re-executes each +# range once it is `lag` blocks settled -- so blocks are executed twice, which +# at the tip is about ten seconds of work per eight hours of chain. See +# docs/segbuild-continuous-design.md. +# +# `out` must already hold a `NNN-start-end` segment and be current with this +# node's executed head, or the node refuses to start: the blocks in a gap +# cannot be rebuilt from a garbage-collected store, so recording them would +# only record ranges that must fail. Unset leaves the feature off. +# +# `target_mb` is the segment size, in written state rather than blocks: cost +# per block varies tenfold across eras, so equal block counts give segments +# from 0.2 GB to over 2 GB while equal bytes give ones a consumer can hold in +# memory. `seal_mb` is something else -- the builder's own memory budget, two +# tables of it, flushed into the segment as they fill. +[segbuild] +# out = "/var/lib/rustock/segbuild" # default: unset +# target_mb = 1024 # default +# lag = 1000 # default +# seal_mb = 256 # default + # --------------------------------------------------------------------------- # Peg events the Bridge does not emit # ---------------------------------------------------------------------------