From f98571916c6081719ddc55d4e0e9cfa3717fb790 Mon Sep 17 00:00:00 2001 From: Sergio Demian Lerner Date: Sat, 21 Nov 2026 11:27:49 +0000 Subject: [PATCH 1/3] Decide a gap by the collection watermark, and make the builder audible MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three things, all found by asking whether this node could actually turn the feature on. The startup gate asked the wrong question. It refused when the executed head was more than `--segbuild-lag` past the end of the set -- distance from the head, which is the mistake §7.3 corrects inside the builder. Distance says a range lost its protection; it does not say anything was taken. A node stopped for a week has a gap of thousands of blocks whose nodes are all present, because nothing swept while it was down. This node is exactly that case: the set ends at #9,420,000, it has executed to #9,430,703, and the collection watermark is #9,342,320 -- 77,681 blocks below the gap, so every node those blocks wrote is still in an unswept epoch. The gate now asks the store what it collected instead of inferring it from distance, and refuses only when the watermark is above the gap's first block. A buildable gap still needs closing promptly, so `cut_at` records a boundary at the executed head during startup and the catch-up becomes a range of its own. Left to the size-driven cut it would have waited a gigabyte of writes -- about a month of chain -- while its collection bound went stale after four days, and the state would have been collected out from under it. `segbuild_status` answers the question in one command. It took eight to answer by hand, because nothing printed the executed head's *number*: `height_peek` prints its hash, so it had to be bisected out of `block_info`. The question is two comparisons against values already on disk, and the tool prints all three numbers, what is pending, and whether a gap is buildable. A halt was silent, and a long build was too. `segbuild_boundaries` had no logging at all: `halt()` wrote the HALTED file and `tick()` returned `Tick::Halted(reason)`, which the caller discarded. So a reorg deeper than the lag -- the most serious event this design has a rule for -- produced no log line, at the time or ever after. It now logs at `error` the moment it happens, reminds at `warn` once an hour for as long as it lasts, naming the file to remove, and says nothing on the other ticks. A build also had nothing between "Building" and "Built", a quarter of an hour of silence for a full segment, so there is now a progress line every 10,000 blocks carrying the rate and the sealed bytes; and the seed a range starts from is `info` rather than `debug`, because that is the decision that matters for a range built after a catch-up. Co-Authored-By: Claude Opus 5 --- crates/cli/examples/segbuild_status.rs | 167 ++++++++++++++++++++++ crates/cli/src/main.rs | 99 +++++++++++-- crates/execution/src/segment_build.rs | 38 ++++- crates/storage/src/segbuild_boundaries.rs | 20 ++- 4 files changed, 306 insertions(+), 18 deletions(-) create mode 100644 crates/cli/examples/segbuild_status.rs diff --git a/crates/cli/examples/segbuild_status.rs b/crates/cli/examples/segbuild_status.rs new file mode 100644 index 00000000..5b0b386f --- /dev/null +++ b/crates/cli/examples/segbuild_status.rs @@ -0,0 +1,167 @@ +//! Can this node extend the segbuild set, or is there a gap? +//! +//! Three numbers answer it, and all three are already on disk: +//! +//! - where the **set** ends, from the `NNN-start-end` directory names; +//! - where the node has **executed** to, from the block store's `exec_head`; +//! - the collection **watermark**, from the epoch store's `collected-below`. +//! +//! This exists because answering that took eight commands otherwise: no tool +//! printed the executed head's *number* (`height_peek` prints its hash), so it +//! had to be bisected out of `block_info`. The question is two comparisons, and +//! it should cost one command. +//! +//! The distinction the output insists on: a gap between the set and the +//! executed head is a gap in **coverage**, which says nothing about whether the +//! blocks can still be built. Whether they can is what the watermark answers -- +//! beneath it a missing node was taken by the collector and is not recoverable +//! here; at or above it, the nodes are still in an unswept epoch. A node that +//! was stopped for a week has a gap of thousands of blocks whose nodes are all +//! present, because nothing swept while it was down. +//! +//! Read-only, and safe to run against a live node. +//! +//! ```text +//! segbuild_status [--trie-dir DIR] [--engine flatdb|rocksdb] +//! ``` +//! +//! `--trie-dir` defaults to `/trie-epochs-flat` and `--engine` to +//! `flatdb`, which is what the mainnet node runs. The trie store is opened only +//! to read the watermark; pass an engine that does not match the store and it +//! says so rather than guessing. + +use anyhow::{Context, Result}; +use rustock_storage::epoch_store::{EpochConfig, EpochTrieStore}; +use rustock_storage::segbuild_boundaries::SegmentBoundaries; +use rustock_storage::BlockStore; + +fn flag(name: &str, default: &str) -> String { + let args: Vec = std::env::args().collect(); + args.windows(2) + .find(|w| w[0] == format!("--{name}")) + .map(|w| w[1].clone()) + .unwrap_or_else(|| default.to_string()) +} + +fn main() -> Result<()> { + let positional: Vec = std::env::args() + .skip(1) + .take_while(|a| !a.starts_with("--")) + .collect(); + if positional.len() != 2 { + eprintln!( + "usage: segbuild_status \ + [--trie-dir DIR] [--engine flatdb|rocksdb]" + ); + std::process::exit(64); + } + let data_dir = positional[0].clone(); + let segbuild_dir = positional[1].clone(); + let trie_dir = flag("trie-dir", &format!("{data_dir}/trie-epochs-flat")); + let engine = flag("engine", "flatdb"); + + let store = BlockStore::open_read_only(&data_dir) + .with_context(|| format!("opening {data_dir} read-only"))?; + + let exec_head = match store.exec_head()? { + Some((hash, _)) => store.header(hash)?.map(|h| h.number), + None => None, + }; + let canonical_tip = store.head()?.and_then(|h| store.header(h).ok().flatten()).map(|h| h.number); + let set_end = rustock_execution::segment_build::set_end(std::path::Path::new(&segbuild_dir))?; + + // The watermark. Opened read-only and only for this one value, so a store + // that cannot be opened is reported rather than fatal: the two block + // numbers above are still worth printing. + let engine_parsed = rustock_storage::TrieEngine::parse(&engine)?; + let config = EpochConfig::default(); + let expected = rustock_storage::epoch_backend::keys_for_rotation(config.rotate_bytes); + let watermark = match EpochTrieStore::open_read_only_with( + std::path::Path::new(&trie_dir), + config, + engine_parsed.factory(expected), + ) { + Ok(es) => Ok(es.collected_below()), + Err(e) => Err(e), + }; + + println!("block store {data_dir}"); + println!("segment set {segbuild_dir}"); + println!("trie store {trie_dir} ({engine})"); + println!(); + match set_end { + Some(n) => println!(" set ends at #{n}"), + None => println!(" set ends at (no NNN-start-end segment: nothing to extend)"), + } + match exec_head { + Some(n) => println!(" executed head #{n}"), + None => println!(" executed head (none: this node has executed nothing)"), + } + if let Some(n) = canonical_tip { + println!(" canonical tip #{n}"); + } + match &watermark { + Ok(Some(n)) => println!(" collected below #{n}"), + Ok(None) => println!(" collected below (no sweep has completed)"), + Err(e) => println!(" collected below unreadable: {e:#}"), + } + + // What is pending, if the logs exist yet. + let logs = SegmentBoundaries::open(&segbuild_dir, u64::MAX); + if let Ok(logs) = &logs { + let boundaries = logs.boundaries(); + println!(); + println!(" boundaries recorded {}", boundaries.len()); + println!(" ranges built {}", logs.built_count()); + if let Some(reason) = logs.halted() { + println!(" HALTED {reason}"); + } + for u in logs.uncovered() { + println!(" uncovered #{}..#{} {}", u.start, u.end, u.reason); + } + if let Some(first) = set_end { + if let Some(bound) = logs.collection_bound(first + 1) { + println!(" collection bound #{bound}"); + } + } + } + + println!(); + let (Some(set_end), Some(exec_head)) = (set_end, exec_head) else { + println!("Cannot extend: the set or the executed head is missing (see above)."); + std::process::exit(1); + }; + + let gap = exec_head.saturating_sub(set_end); + if gap == 0 { + println!("No gap: the set is current with the executed head. --segbuild-out will start."); + return Ok(()); + } + + println!("Coverage gap: #{}..#{exec_head} is {gap} blocks.", set_end + 1); + // The gap's blocks wrote at or after set_end + 1, so those writes are + // intact unless the collector has been at or above there. + match watermark { + Ok(Some(w)) if w > set_end + 1 => { + println!( + "NOT buildable from this store: the collector swept beneath #{w}, which is \ + above the gap's first block. Those nodes are gone. Fill the gap with the \ + offline tool against an archive trie." + ); + std::process::exit(2); + } + Ok(Some(w)) => println!( + "Buildable: the watermark (#{w}) is {} blocks below the gap, so every node the \ + gap's blocks wrote is still in an unswept epoch. The seed state at #{set_end} \ + is the one part nothing can promise -- it was written below the watermark and \ + was not pinned -- so a build may still fail on a missing node, loudly.", + (set_end + 1).saturating_sub(w) + ), + Ok(None) => println!("Buildable: no sweep has completed, so nothing has been collected."), + Err(_) => println!( + "Buildability unknown: the watermark could not be read (see above). Check \ + --trie-dir and --engine against what the node runs." + ), + } + Ok(()) +} diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 402531c5..224bcdfb 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -3121,19 +3121,47 @@ async fn run(local_offset: Option) -> Result<()> { rustock_execution::segment_build::UNITRIE_FROM ) })?; - // A gap between the set and the node is unbuildable from here: the - // node's store is garbage-collected, so the state those ranges read - // is gone. Saying so now beats recording ranges that must fail. - if exec_head > set_end + args.segbuild_lag { - anyhow::bail!( - "--segbuild-out {} ends at #{set_end}, but this node has executed to \ - #{exec_head}. The {} blocks in between cannot be built from a \ - garbage-collected store. Fill #{}..#{exec_head} with the offline tool \ - against an archive trie first, or point --segbuild-out at a set that \ - is current.", - dir.display(), - exec_head - set_end, - set_end + 1 + // A gap between where the set ends and where the node has executed + // is a gap in *coverage*. Whether it can still be built is a + // different question, and the store answers it: the collection + // watermark is the height beneath which a missing node was taken by + // the collector and is not recoverable here. + // + // Distance from the head does not answer it, and an earlier version + // of this check used distance -- the same mistake §7.3 corrects + // inside the builder. A node stopped for a week has a gap of + // thousands of blocks whose nodes are all still present, because + // nothing swept while it was down. + let watermark = epoch_store.as_ref().and_then(|es| es.collected_below()); + let gap = exec_head.saturating_sub(set_end); + if gap > 0 { + // The gap's blocks wrote at or after set_end + 1. Those writes + // are intact unless the collector has been at or above there. + if watermark.is_some_and(|w| w > set_end + 1) { + anyhow::bail!( + "--segbuild-out {} ends at #{set_end}, this node has executed to \ + #{exec_head}, and the collector has already swept beneath \ + #{}. The {gap} blocks in between wrote nodes this store can no \ + longer return, so they cannot be rebuilt from here. Fill \ + #{}..#{exec_head} with the offline tool against an archive trie \ + first, or point --segbuild-out at a set that is current.", + dir.display(), + watermark.unwrap_or(0), + set_end + 1 + ); + } + warn!( + "segbuild: the set ends at #{set_end} and this node has executed to \ + #{exec_head}, a gap of {gap} blocks. The collector has not been \ + beneath it ({}), so it is still buildable, and it will be cut as a \ + range of its own at startup. Its seed state at #{set_end} is the one \ + part nothing can promise -- it was written below the watermark and \ + was not pinned while the node ran -- so the build may fail on a \ + missing node, loudly, leaving no segment.", + match watermark { + Some(w) => format!("watermark #{w}"), + None => "no sweep has completed".into(), + } ); } if exec_head < set_end { @@ -3150,6 +3178,28 @@ async fn run(local_offset: Option) -> Result<()> { if let Some(reason) = boundaries.halted() { warn!("segbuild is halted and will build nothing: {reason}"); } + // Close the catch-up as its own range. Left to the size-driven cut + // it would wait a gigabyte of writes -- about a month of chain -- + // before anything tried to build it, and its collection bound would + // go stale long before that. + if gap > 0 { + match boundaries.cut_at(exec_head) { + Ok(Some(b)) => info!( + "segbuild: recorded a boundary at #{} so #{}..#{} is built as a \ + range of its own", + b.block, + set_end + 1, + b.block + ), + Ok(None) => debug!( + "segbuild: a boundary at or above #{exec_head} is already recorded" + ), + Err(e) => warn!( + "segbuild: could not record the catch-up boundary at \ + #{exec_head}: {e:#}" + ), + } + } info!( "segbuild: extending {} from #{}, cutting every ~{} MB, building {} blocks \ behind the executed head", @@ -3530,10 +3580,14 @@ async fn run(local_offset: Option) -> Result<()> { first_block, )); let store_for_segbuild = store.clone(); + let segbuild_dir_for_log = args.segbuild_out.clone().expect("checked above"); tokio::spawn(async move { // Deliberately slow. A boundary is one decision per gigabyte of // written state, and a build is minutes of work; polling faster // would only read `exec_head` more often. + // One reminder an hour while halted, at a 30-second tick. + const HALT_REMINDER_TICKS: u64 = 120; + let mut halted_ticks: u64 = 0; let mut tick = tokio::time::interval(std::time::Duration::from_secs(30)); // A build runs for minutes, so ticks are missed while it does. // Delay rather than burst through the backlog afterwards: the @@ -3584,7 +3638,24 @@ async fn run(local_offset: Option) -> Result<()> { // which is the whole point of keeping this out of the node's // path. match tokio::task::spawn_blocking(move || b.tick(head, &|| false)).await { - Ok(_) => {} + // Each outcome has already said what it did, at the level + // it deserved, except being halted: that persists, so it is + // the one state worth repeating. A node halted for a week + // should say so in a log an operator reads today, without + // writing the same line every 30 seconds. + Ok(rustock_execution::segment_build::Tick::Halted(reason)) => { + if halted_ticks.is_multiple_of(HALT_REMINDER_TICKS) { + warn!( + target: "rustock::segbuild", + "Segment building is halted and is extending nothing: \ + {reason} Remove the HALTED file under {} once the set has \ + been checked.", + segbuild_dir_for_log.display() + ); + } + halted_ticks += 1; + } + Ok(_) => halted_ticks = 0, Err(e) => warn!( target: "rustock::segbuild", "The segment builder stopped with {e}; it will be tried again" diff --git a/crates/execution/src/segment_build.rs b/crates/execution/src/segment_build.rs index 2bfd8b48..2db3bb50 100644 --- a/crates/execution/src/segment_build.rs +++ b/crates/execution/src/segment_build.rs @@ -72,6 +72,14 @@ const REROOT_EVERY: u64 = 500; /// costs minutes rather than hours. const CHECKPOINT_EVERY: u64 = 20_000; +/// Blocks between progress lines. +/// +/// A segment is ~90,000 blocks and runs at order 100 blk/s, so without this a +/// build is a quarter of an hour of silence between "Building" and "Built" -- +/// and an operator cannot tell a slow build from a stuck one. Nine lines per +/// segment is enough to see the rate and cheap enough to ignore. +const PROGRESS_EVERY: u64 = 10_000; + #[derive(Clone, Debug)] pub struct BuildConfig { /// Directory holding the segment set. The segment is created inside it. @@ -292,7 +300,7 @@ pub fn build_range( // replay their own first block (§11.3a) and why segment 097 needed // repairing after the fact. win.put(seed.as_slice(), &data); - debug!( + info!( target: "rustock::segbuild", "Seeded #{start}..#{end} from #{} root {seed:?}", parent.number ); @@ -357,6 +365,16 @@ pub fn build_range( if done.is_multiple_of(CHECKPOINT_EVERY) { window.checkpoint(n, root_hash.as_slice())?; } + if done.is_multiple_of(PROGRESS_EVERY) { + let secs = t0.elapsed().as_secs_f64(); + info!( + target: "rustock::segbuild", + "Building #{start}..#{end}: at #{n}, {done} of {} blocks, {:.0} blk/s, {} MB sealed", + end - first + 1, + done as f64 / secs.max(0.001), + window.sealed_bytes.load(std::sync::atomic::Ordering::Relaxed) / (1 << 20) + ); + } } window.finish()?; @@ -487,6 +505,11 @@ impl SegmentBuilder { /// following the chain. pub fn tick(&self, head: u64, cancel: &(dyn Fn() -> bool + Sync)) -> Tick { if let Some(reason) = self.boundaries.halted() { + // Already halted. Said at `debug` because the caller is expected to + // report the state at its own rate -- every 30 seconds for as long + // as a human takes to respond would be thousands of identical + // lines. + debug!(target: "rustock::segbuild", "Still halted, building nothing: {reason}"); return Tick::Halted(reason); } @@ -498,7 +521,18 @@ impl SegmentBuilder { match self.boundaries.verify_built_still_canonical(|h| { blocks.canonical_hash(h).ok().flatten().map(|hash| hash.into()) }) { - Ok(Some(reason)) => return Tick::Halted(reason), + Ok(Some(reason)) => { + // The moment it happens, and the loudest line this module has. + // A reorg deeper than the lag means settled history was + // rewritten; the builder stops and stays stopped, and an + // operator who never sees this has no way to know why the set + // stopped growing. + error!( + target: "rustock::segbuild", + "HALTING segment building: {reason} Nothing will be built until a human investigates and removes the HALTED file. The node is unaffected and keeps following the chain." + ); + return Tick::Halted(reason); + } Ok(None) => {} Err(e) => { warn!( diff --git a/crates/storage/src/segbuild_boundaries.rs b/crates/storage/src/segbuild_boundaries.rs index e0664f4b..c181799f 100644 --- a/crates/storage/src/segbuild_boundaries.rs +++ b/crates/storage/src/segbuild_boundaries.rs @@ -172,10 +172,26 @@ impl SegmentBoundaries { /// Only ever cuts at a block boundary, because a segment that ended /// mid-block would cover part of a block's writes and claim the block. pub fn end_block(&self, block: u64) -> Result> { - let acc = self.counter.load(Ordering::Relaxed); - if acc < self.target_bytes { + if self.counter.load(Ordering::Relaxed) < self.target_bytes { return Ok(None); } + self.cut_at(block) + } + + /// Record a boundary at `block` whatever the counter says. + /// + /// For a cut that is not about size: a node starting with the set behind + /// its executed head closes that catch-up as a range of its own, rather + /// than leaving it to be merged into the next size-driven segment. Merging + /// it would mean the gap waited a gigabyte of writes -- about a month of + /// chain -- before anything tried to build it, by which time its + /// collection bound would have gone stale and the state would be gone. + /// + /// Still refuses a boundary at or below the last one, for the same reason + /// `end_block` does: ranges are derived by walking boundaries in order, so + /// one that goes backwards produces a range with `start > end`. + pub fn cut_at(&self, block: u64) -> Result> { + let acc = self.counter.load(Ordering::Relaxed); // Reset first: if appending fails, the next block tries again rather // than this one cutting repeatedly. self.counter.store(0, Ordering::Relaxed); From e679d24fa69e6dd452286b78e27c39732bc38370 Mon Sep 17 00:00:00 2001 From: Sergio Demian Lerner Date: Sat, 21 Nov 2026 11:32:21 +0000 Subject: [PATCH 2/3] segbuild_status: check the seed root, not just the watermark The watermark settles whether a gap's own writes survived, but not whether the build has anywhere to start. The seed is the state root the set's last block declares, and it was written below the watermark, so whether it survived depends on it having been live when the sweep drained. One read answers it, and that read is the whole difference between deciding from an argument and deciding from a fact -- here it is present at #9,420,000, so the 10,740-block gap can be built. A present root is the top node and not proof of the trie beneath it, which the output says. If it is ever absent the message names the recourse: that segment's own sealed store holds the verified state at its end block. Co-Authored-By: Claude Opus 5 --- crates/cli/examples/segbuild_status.rs | 45 ++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 3 deletions(-) diff --git a/crates/cli/examples/segbuild_status.rs b/crates/cli/examples/segbuild_status.rs index 5b0b386f..e0e92f8f 100644 --- a/crates/cli/examples/segbuild_status.rs +++ b/crates/cli/examples/segbuild_status.rs @@ -76,13 +76,34 @@ fn main() -> Result<()> { let engine_parsed = rustock_storage::TrieEngine::parse(&engine)?; let config = EpochConfig::default(); let expected = rustock_storage::epoch_backend::keys_for_rotation(config.rotate_bytes); - let watermark = match EpochTrieStore::open_read_only_with( + let opened = EpochTrieStore::open_read_only_with( std::path::Path::new(&trie_dir), config, engine_parsed.factory(expected), - ) { + ); + let watermark = match &opened { Ok(es) => Ok(es.collected_below()), - Err(e) => Err(e), + Err(e) => Err(anyhow::anyhow!("{e:#}")), + }; + + // The seed a gap's build would start from: the state root the set's last + // block declares. One lookup, and it is the only part of a gap that the + // watermark cannot settle -- those nodes were written below it, so whether + // they survived depends on whether they were still live when the sweep + // drained. Checking it costs a single read and replaces the one unknown in + // deciding whether to build a gap. + // + // A present root proves the top node is there, not the whole trie beneath + // it, so this is a necessary condition and not a sufficient one. + let seed = match (&opened, set_end) { + (Ok(es), Some(end)) => { + let root = store + .canonical_hash(end)? + .and_then(|h| store.header(h).ok().flatten()) + .map(|h| h.state_root); + root.map(|r| (end, r, rustock_trie::TrieStore::get(es, r.as_slice()).is_some())) + } + _ => None, }; println!("block store {data_dir}"); @@ -105,6 +126,12 @@ fn main() -> Result<()> { Ok(None) => println!(" collected below (no sweep has completed)"), Err(e) => println!(" collected below unreadable: {e:#}"), } + if let Some((end, root, present)) = &seed { + println!( + " seed root at #{end} {} ({root:?})", + if *present { "PRESENT" } else { "ABSENT" } + ); + } // What is pending, if the logs exist yet. let logs = SegmentBoundaries::open(&segbuild_dir, u64::MAX); @@ -163,5 +190,17 @@ fn main() -> Result<()> { --trie-dir and --engine against what the node runs." ), } + match seed { + Some((end, _, true)) => println!( + "The seed state root at #{end} is present, so a build has somewhere to \ + start. That is the top node, not proof of the whole trie beneath it." + ), + Some((end, _, false)) => println!( + "The seed state root at #{end} is ABSENT. A build would fail on its first \ + read. Seed it from that segment's own sealed store instead -- it holds \ + the verified state at its end block." + ), + None => {} + } Ok(()) } From 9bd059fb9136746c3e1f7f1514fede42a58f96b8 Mon Sep 17 00:00:00 2001 From: Sergio Demian Lerner Date: Sat, 21 Nov 2026 11:54:40 +0000 Subject: [PATCH 3/3] Cut the catch-up boundary below the head, not at it The startup boundary was recorded at the executed head, which is zero blocks settled, so `ready` held the range for another `--segbuild-lag` blocks before offering it -- eight hours at mainnet block time, spent waiting for state the node already has on disk. Cut `lag` blocks lower and the range is settled the moment it is recorded, so the catch-up builds on the first tick. The `lag` blocks left over stay in the open range and are absorbed by the next size-driven cut, which is where all of them would have gone anyway. For the mainnet node that is the difference between closing a 10,745-block gap in about two minutes and closing it tomorrow. Co-Authored-By: Claude Opus 5 --- crates/cli/src/main.rs | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 224bcdfb..3bd9c778 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -3153,15 +3153,17 @@ async fn run(local_offset: Option) -> Result<()> { warn!( "segbuild: the set ends at #{set_end} and this node has executed to \ #{exec_head}, a gap of {gap} blocks. The collector has not been \ - beneath it ({}), so it is still buildable, and it will be cut as a \ - range of its own at startup. Its seed state at #{set_end} is the one \ + beneath it ({}), so it is still buildable, and all but the last {} \ + blocks of it are cut as a range of their own now. Its seed state at \ + #{set_end} is the one \ part nothing can promise -- it was written below the watermark and \ was not pinned while the node ran -- so the build may fail on a \ missing node, loudly, leaving no segment.", match watermark { Some(w) => format!("watermark #{w}"), None => "no sweep has completed".into(), - } + }, + args.segbuild_lag ); } if exec_head < set_end { @@ -3182,21 +3184,33 @@ async fn run(local_offset: Option) -> Result<()> { // it would wait a gigabyte of writes -- about a month of chain -- // before anything tried to build it, and its collection bound would // go stale long before that. - if gap > 0 { - match boundaries.cut_at(exec_head) { + // + // Cut `lag` blocks *below* the executed head, not at it. A boundary + // at the head is zero blocks settled, so `ready` would hold the + // range for another `lag` blocks -- eight hours at mainnet's block + // time -- before building state the node already has. One block + // lower than that and it is ready on the first tick. The `lag` + // blocks left over stay in the open range and are absorbed by the + // next size-driven cut, which is what would have happened to all of + // them anyway. + let catch_up_end = exec_head.saturating_sub(args.segbuild_lag); + if gap > 0 && catch_up_end > set_end { + match boundaries.cut_at(catch_up_end) { Ok(Some(b)) => info!( "segbuild: recorded a boundary at #{} so #{}..#{} is built as a \ - range of its own", + range of its own, starting on the next tick -- it is already \ + {} blocks settled", b.block, set_end + 1, - b.block + b.block, + args.segbuild_lag ), Ok(None) => debug!( - "segbuild: a boundary at or above #{exec_head} is already recorded" + "segbuild: a boundary at or above #{catch_up_end} is already recorded" ), Err(e) => warn!( "segbuild: could not record the catch-up boundary at \ - #{exec_head}: {e:#}" + #{catch_up_end}: {e:#}" ), } }