diff --git a/.sqlx/query-594f0b138422b4f15986e92d07deadaac1dce80502a2f8b3e35d490e8ff148d5.json b/.sqlx/query-594f0b138422b4f15986e92d07deadaac1dce80502a2f8b3e35d490e8ff148d5.json new file mode 100644 index 0000000..3c73c17 --- /dev/null +++ b/.sqlx/query-594f0b138422b4f15986e92d07deadaac1dce80502a2f8b3e35d490e8ff148d5.json @@ -0,0 +1,41 @@ +{ + "db_name": "PostgreSQL", + "query": "\n select height, miner, observed_at, at_tip\n from block\n where chain = $1\n order by height desc\n limit $2\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "height", + "type_info": "Int8" + }, + { + "ordinal": 1, + "name": "miner", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "observed_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 3, + "name": "at_tip", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + false + ] + }, + "hash": "594f0b138422b4f15986e92d07deadaac1dce80502a2f8b3e35d490e8ff148d5" +} diff --git a/CLAUDE.md b/CLAUDE.md index 0a7dc72..965efd0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -149,6 +149,32 @@ the build if the committed output is stale. the wire as a JSON *number*, so the type and the runtime value disagree. Every u64 DTO field carries `#[ts(type = "number")]`. Add it to any new one. +## A restart is visible, so warm start has to put everything back + +`blackbeard-api-cert.path` watches the host certificate and issues a full +`systemctl restart` when it rotates — several times a day, on top of every +deploy. Two pieces of state live only in memory and used to come back empty: + +- The **block ticker**, which is built from live blocks and has no other source. + It returned holding one row and refilled over the following minute. +- The **tip samples** behind the measured interval, because the window replay + pushed everything with `at_tip: false`. Right for blocks a previous process + caught up on; wrong for the ones it genuinely watched arrive, which `0002` + has recorded ever since. Without them the headline hashrate falls back to the + *target* — at mainnet's interval that is an eight-fold drop, correctly + labelled nominal and reported as a bug every time. + +`restore_ticker_and_timing` puts both back, so a restart is no longer +user-visible. It runs *after* the attributions and carried names, because the +ticker rows need their display names. Restored tip samples are capped at ten +minutes old: the interval stays arithmetically valid across a gap, but it stops +being *current*, and a sample from an hour ago averaged with one from now +describes the hour rather than the tip. + +Worth knowing: the store already recycles pooled connections hourly precisely +so a rotated certificate is a routine reconnect. The path unit's restart is +therefore belt-and-braces over a case the pool already handles. + ## Separation of concerns is load-bearing here - `blackbeard-core` has **no I/O, no clock, no sockets**. That is what lets the diff --git a/crates/blackbeard-api/src/ingest.rs b/crates/blackbeard-api/src/ingest.rs index 7769b89..ec3f76c 100644 --- a/crates/blackbeard-api/src/ingest.rs +++ b/crates/blackbeard-api/src/ingest.rs @@ -84,7 +84,7 @@ pub fn spawn(chain: Arc, store: Store, config: &crate::config::Con /// Load what the database already knows, so a restart does not serve an empty /// site while it re-watches a week of blocks. -pub async fn warm_start(chain: &Arc, store: &Store) { +pub async fn warm_start(chain: &Arc, store: &Store, ticker_blocks: usize) { let id = chain.id(); match store @@ -142,6 +142,95 @@ pub async fn warm_start(chain: &Arc, store: &Store) { } Err(e) => tracing::warn!(chain = %id, error = %e, "warm start: no names carried"), } + + restore_ticker_and_timing(chain, store, ticker_blocks).await; +} + +/// How stale a tip observation may be and still seed the measured interval. +/// +/// The interval is `span / height difference`, which stays arithmetically valid +/// across a gap — blocks kept being produced while the observer was away, and +/// both terms grow together. What it stops being is *current*: a sample from an +/// hour ago averaged with one from now describes the hour, not the tip. Ten +/// minutes is comfortably inside the two hundred samples the window keeps, so a +/// routine restart restores a real figure and a long outage measures afresh. +const MAX_RESTORED_TIP_AGE: chrono::TimeDelta = chrono::TimeDelta::minutes(10); + +/// Put back the two things a restart otherwise loses. +/// +/// The block ticker is built from live blocks and has no other source, so it +/// came back holding one row and refilled over the following minute. The tip +/// samples behind the measured block interval were dropped outright, because +/// the window replay pushes everything with `at_tip: false` — correct for +/// blocks the previous process caught up on, wrong for the ones it genuinely +/// watched arrive, which `0002` has recorded ever since. +/// +/// Between them that is the whole of "the hashrate fell to a fraction and the +/// block list emptied": nominal instead of measured is an eight-fold drop at +/// mainnet's current interval, and it happened on every deploy and every +/// certificate rotation. +async fn restore_ticker_and_timing(chain: &Arc, store: &Store, ticker_blocks: usize) { + let id = chain.id(); + let want = ticker_blocks.max(blackbeard_core::window::MAX_TIP_SAMPLES); + let Ok(recent) = store.recent_tip_blocks(&id, want as i64).await else { + tracing::warn!(chain = %id, "warm start: ticker and timing not restored"); + return; + }; + if recent.is_empty() { + return; + } + + // Newest first from the query; the window and the ticker both want oldest + // first, and the interval is only meaningful over samples in order. + let mut oldest_first = recent; + oldest_first.reverse(); + + let cutoff = Utc::now() - MAX_RESTORED_TIP_AGE; + let mut restored_samples = 0usize; + let restored_ticker; + let mut ticker = Vec::new(); + let mut previous: Option> = None; + + { + let mut inner = chain.write(); + for (observed, at_tip) in &oldest_first { + if *at_tip && observed.observed_at >= cutoff { + inner.window.push(observed.clone(), true); + restored_samples += 1; + } + } + + // The ticker is the tail, and it needs names — which is why this runs + // after the attributions and carried names are already in place. + let tail = oldest_first + .len() + .saturating_sub(ticker_blocks.min(oldest_first.len())); + for (observed, _) in &oldest_first[tail..] { + let attributed = inner + .attributor + .attribute(&observed.miner, |key| chain.telemetry.name_of(key)); + ticker.push(RecentBlock { + height: observed.height, + miner: observed.miner.clone(), + display: attributed.display, + attribution: attributed.source, + observed_at: observed.observed_at, + // Between two rows we recorded, so this is a real gap. `None` + // for the first, which has no predecessor in this batch. + gap_seconds: previous.map(|p| (observed.observed_at - p).as_seconds_f64()), + }); + previous = Some(observed.observed_at); + } + inner.ticker = ticker.into(); + restored_ticker = inner.ticker.len(); + } + + tracing::info!( + chain = %id, + tip_samples = restored_samples, + ticker = restored_ticker, + "warm start: ticker and timing restored" + ); } /// Consume the head stream. diff --git a/crates/blackbeard-api/src/registry.rs b/crates/blackbeard-api/src/registry.rs index 4380190..ec1814b 100644 --- a/crates/blackbeard-api/src/registry.rs +++ b/crates/blackbeard-api/src/registry.rs @@ -134,7 +134,7 @@ impl Registry { } }; let runtime = Arc::new(ChainRuntime::new(spec, rpc)); - crate::ingest::warm_start(&runtime, &store).await; + crate::ingest::warm_start(&runtime, &store, config.server.ticker_blocks).await; crate::ingest::spawn(Arc::clone(&runtime), store.clone(), &config); by_slug.insert(runtime.spec.slug.clone(), Arc::clone(&runtime)); tracked.push(runtime); diff --git a/crates/blackbeard-core/src/window.rs b/crates/blackbeard-core/src/window.rs index 5d3232a..a512dab 100644 --- a/crates/blackbeard-core/src/window.rs +++ b/crates/blackbeard-core/src/window.rs @@ -56,7 +56,7 @@ pub struct RollingWindow { const MIN_TIP_SAMPLES: usize = 20; /// Tip samples retained. At a 6 s target this is roughly the last 20 minutes — /// long enough to smooth Poisson noise, short enough to follow a real change. -const MAX_TIP_SAMPLES: usize = 200; +pub const MAX_TIP_SAMPLES: usize = 200; impl RollingWindow { /// A window holding at most `capacity` blocks. diff --git a/crates/blackbeard-data/src/store.rs b/crates/blackbeard-data/src/store.rs index fa20961..39c39c5 100644 --- a/crates/blackbeard-data/src/store.rs +++ b/crates/blackbeard-data/src/store.rs @@ -370,6 +370,47 @@ impl Store { .collect()) } + /// The last `limit` blocks with their tip flag, newest **first**. + /// + /// Feeds the two things a restart otherwise loses: the block ticker, which + /// is built from live blocks and has no other source, and the timing + /// samples behind the measured block interval. Both live only in memory, so + /// without this every restart truncates the ticker to one row and drops the + /// headline hashrate to its nominal figure until twenty fresh tip + /// observations accumulate. + pub async fn recent_tip_blocks( + &self, + chain: &ChainId, + limit: i64, + ) -> Result, DataError> { + let rows = sqlx::query!( + r#" + select height, miner, observed_at, at_tip + from block + where chain = $1 + order by height desc + limit $2 + "#, + chain.as_str(), + limit, + ) + .fetch_all(&self.pool) + .await?; + Ok(rows + .into_iter() + .map(|r| { + ( + Observed { + height: r.height as u64, + miner: MinerId(r.miner), + observed_at: r.observed_at, + }, + r.at_tip, + ) + }) + .collect()) + } + /// Totals for one miner across everything the observer has recorded. /// /// `cumulative_work` is the sum of the difficulty of every block the miner