From 02c139b06823115f87e8f7953cb9b7bacb4b3ae3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Tue, 24 Nov 2026 18:09:31 -0300 Subject: [PATCH 01/12] feat(validator): check each beacon node's sync status before every slot's duties The client asked whether its beacon node was syncing or optimistic once an epoch, at the top of refresh_epoch, and between refreshes left every duty to the node's 503. The Beacon API has none for a syncing node's head root or an optimistic node's payload attestation data, and with several nodes every request still started at the first one listed. beacon_node::health probes every node's /eth/v1/node/syncing once a slot, all at once, a sixth of a slot before the boundary (2 s on 12 s slots), on its own task. NodeHealth keeps each node's last probe (the full SyncStatus, head_slot and sync_distance included, or the error), shared through FallbackBeaconNode::health() with a cheap snapshot(). - The duty loop reads the probe at the boundary: a slot signs nothing when some node answered and every node that answered is syncing or optimistic. A node that did not answer does not count, so the 503 stays the backstop. Logged, and counted on ethlambda_validator_slots_skipped_syncing_total. Only the fee recipient re-send, which signs nothing, still runs in such a slot. - refresh_epoch drops its own check and runs only in a slot that passed, so the epoch refresh and the duties read one probe. - The fallback tries the nodes that passed first, then the rest, each in command-line order; Producer positions are unchanged. - The head root and the PTC data are never asked of a node whose last probe said syncing or optimistic, so no sync committee message is signed over a syncing node's head and no PTC vote over an optimistic one. - el_offline and each node's change of state are logged on change. --- CLAUDE.md | 10 + README.md | 2 +- bin/ethlambda/src/validator.rs | 8 +- crates/validator/src/beacon_node/dto.rs | 77 +- crates/validator/src/beacon_node/fallback.rs | 401 +++++++-- crates/validator/src/beacon_node/health.rs | 846 +++++++++++++++++++ crates/validator/src/beacon_node/http.rs | 49 +- crates/validator/src/beacon_node/mock.rs | 48 +- crates/validator/src/beacon_node/mod.rs | 31 + crates/validator/src/lib.rs | 35 +- crates/validator/src/metrics.rs | 17 + crates/validator/src/payload_attestation.rs | 28 +- crates/validator/src/sync_committee.rs | 6 + docs/cli.md | 57 +- docs/metrics.md | 7 +- docs/spec_deviations.md | 21 + 16 files changed, 1555 insertions(+), 88 deletions(-) create mode 100644 crates/validator/src/beacon_node/health.rs diff --git a/CLAUDE.md b/CLAUDE.md index 4774cf07a..25c893a9a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -940,6 +940,16 @@ transitions are in `ethlambda-types`, per the section above. Nothing above holds them in memory only), and `produceBlockV4` carries the boost factor and `--builder-min-bid`. `--gas-limit` sets the target gas limit the preferences carry, which the node's own gloas payload is built toward. + Every slot it probes each beacon node's `/eth/v1/node/syncing` a sixth of a + slot before the boundary, on its own task (`beacon_node::health`, records + in `NodeHealth`, shared by the fallback): a slot in which every node that + answered is syncing or optimistic signs nothing and skips the epoch refresh, + only the fee recipient re-send going on (a node that did not answer does not + count, so the duty endpoints' 503 stays the backstop); requests try the + nodes that passed first, then the rest, each + in `--beacon-nodes` order; and the head root and PTC data are never asked of + a node whose last probe said syncing or optimistic. No rule reads the head's + age off the client's clock. It keeps EIP-3076 minimal-watermark slashing protection in `--validators-dir/slashing_protection.json` (`crate::slashing_protection`), durable before every block (blinded ones included) and attestation signature; diff --git a/README.md b/README.md index 6a4364f34..c57b41e14 100644 --- a/README.md +++ b/README.md @@ -358,7 +358,7 @@ beacon node. | Flag | Meaning | |---|---| -| `--beacon-nodes` | Base URLs of the beacon nodes to use, comma-separated or repeated. Tried in order, so the order is a preference | +| `--beacon-nodes` | Base URLs of the beacon nodes to use, comma-separated or repeated. Each is asked whether it is syncing once a slot; the ones that said synced are tried first, then the rest, each in the order given, so the order is a preference. A slot in which every node that answered is syncing or on an optimistic head signs nothing | | `--validators-dir` | Directory of EIP-2335 keystores and `validator_definitions.yml`. Without that file, keystores in the Lighthouse layout (`<0xpubkey>/voting-keystore.json`) are discovered and the file is written | | `--secrets-dir` | One password file per keystore, named after the validator's public key | | `--suggested-fee-recipient` | Execution address for block rewards, `0x`-prefixed. Optional, but without it the beacon node picks an address that is not yours | diff --git a/bin/ethlambda/src/validator.rs b/bin/ethlambda/src/validator.rs index 01774a1b4..5fadee669 100644 --- a/bin/ethlambda/src/validator.rs +++ b/bin/ethlambda/src/validator.rs @@ -19,9 +19,11 @@ const ADDRESS_BYTES: usize = 20; pub(crate) struct ValidatorOptions { /// Base URL(s) of the beacon node's HTTP API (e.g. http://localhost:5052). /// - /// Several may be supplied, comma-separated or by repeating the flag. They - /// are tried in order and the first that answers is used, so the order is - /// a preference, not a load-balancing policy. + /// Several may be supplied, comma-separated or by repeating the flag. Each + /// is asked whether it is syncing once a slot; the ones that are not are + /// tried first, then the rest, each in the order given, and the first that + /// answers is used, so the order is a preference, not a load-balancing + /// policy. #[arg(long, value_delimiter = ',', required = true)] pub(crate) beacon_nodes: Vec, diff --git a/crates/validator/src/beacon_node/dto.rs b/crates/validator/src/beacon_node/dto.rs index 817443696..2e506f567 100644 --- a/crates/validator/src/beacon_node/dto.rs +++ b/crates/validator/src/beacon_node/dto.rs @@ -19,7 +19,7 @@ //! |---|---|---| //! | `AttesterDuty` | pubkey, validator_index, committee_index, committee_length, committees_at_slot, validator_committee_index, slot | all seven, all used | //! | Genesis | genesis_time, genesis_validators_root, genesis_fork_version | the first two; the fork version comes from `/config/spec` | -//! | Syncing | head_slot, sync_distance, is_syncing, is_optimistic, el_offline | is_syncing and is_optimistic gate signing; el_offline is logged | +//! | Syncing | head_slot, sync_distance, is_syncing, is_optimistic, el_offline | all five: is_syncing and is_optimistic gate signing; el_offline is logged; head_slot and sync_distance are recorded, and read leniently | //! | `ValidatorResponse` | index, balance, status, validator | index, status, validator.pubkey; the single-validator form also reads the activation, exit and withdrawable epochs | //! | `ProposerDuty` | pubkey, validator_index, slot | all three, all used | //! | `ProposerPreparation` | validator_index, fee_recipient | both, sent not read | @@ -154,6 +154,48 @@ pub struct SyncingDto { /// to; what it cannot do is validate new payloads, and it reports that /// through `is_optimistic` when it starts to matter. pub el_offline: Option, + /// The node's head slot. Kept in the per-slot probe's record (see + /// [`crate::beacon_node::health`]), never read to decide anything. + /// + /// `None` when absent or not an integer, rather than a failed decode. A + /// failed decode reads as a node that did not answer, which does not count + /// as syncing, so a node answering `is_syncing: true` beside a malformed + /// `head_slot` would open the gate it should hold shut. + #[serde(default, deserialize_with = "lenient_u64")] + pub head_slot: Option, + /// How many slots the node's head is behind its own wall clock. Kept and + /// read leniently, as `head_slot` is. + #[serde(default, deserialize_with = "lenient_u64")] + pub sync_distance: Option, +} + +impl From for crate::beacon_node::health::SyncStatus { + /// An absent `is_optimistic` or `el_offline` reads as `false`, for the + /// reasons given on the two fields. + fn from(dto: SyncingDto) -> Self { + Self { + head_slot: dto.head_slot, + sync_distance: dto.sync_distance, + is_syncing: dto.is_syncing, + is_optimistic: dto.is_optimistic.unwrap_or(false), + el_offline: dto.el_offline.unwrap_or(false), + } + } +} + +/// A 64-bit integer, quoted as the Beacon API sends it or bare, and `None` for +/// anything else: null, a negative or fractional number, text that is not an +/// integer. For fields kept for the record, where a malformed value must not +/// fail the answer around it. +fn lenient_u64<'de, D: serde::Deserializer<'de>>( + deserializer: D, +) -> std::result::Result, D::Error> { + let value = Option::::deserialize(deserializer)?; + Ok(match value { + Some(serde_json::Value::String(text)) => text.parse().ok(), + Some(serde_json::Value::Number(number)) => number.as_u64(), + _ => None, + }) } #[derive(Debug, Clone, Deserialize)] @@ -940,12 +982,11 @@ mod tests { ); } - /// A real `GET /eth/v1/node/syncing` body, carrying all five spec fields; - /// only two are declared here. + /// A real `GET /eth/v1/node/syncing` body, carrying all five spec fields. const SYNCING: &str = r#"{ "data": { "head_slot": "12345678", - "sync_distance": "0", + "sync_distance": "3", "is_syncing": false, "is_optimistic": true, "el_offline": false @@ -953,10 +994,36 @@ mod tests { }"#; #[test] - fn parses_syncing_ignoring_the_fields_it_does_not_declare() { + fn parses_every_syncing_field() { let response: DataResponse = serde_json::from_str(SYNCING).expect("parses"); assert!(!response.data.is_syncing); assert_eq!(response.data.is_optimistic, Some(true)); + assert_eq!(response.data.el_offline, Some(false)); + assert_eq!(response.data.head_slot, Some(12_345_678)); + assert_eq!(response.data.sync_distance, Some(3)); + } + + /// The head slot and sync distance are kept for the record only, so one + /// that is missing or malformed is `None` rather than a failed answer: + /// the flags beside it still count. + #[test] + fn a_missing_or_malformed_head_slot_does_not_fail_the_answer() { + for data in [ + r#"{ "is_syncing": true }"#, + r#"{ "is_syncing": true, "head_slot": null, "sync_distance": "-1" }"#, + r#"{ "is_syncing": true, "head_slot": "soon", "sync_distance": 1.5 }"#, + ] { + let body = format!(r#"{{ "data": {data} }}"#); + let response: DataResponse = serde_json::from_str(&body).expect(data); + assert!(response.data.is_syncing, "{data}"); + assert_eq!(response.data.head_slot, None, "{data}"); + assert_eq!(response.data.sync_distance, None, "{data}"); + } + + let bare = r#"{ "data": { "is_syncing": false, "head_slot": 7, "sync_distance": 0 } }"#; + let response: DataResponse = serde_json::from_str(bare).expect("parses"); + assert_eq!(response.data.head_slot, Some(7)); + assert_eq!(response.data.sync_distance, Some(0)); } /// A real `POST /eth/v1/beacon/states/head/validators` body, including diff --git a/crates/validator/src/beacon_node/fallback.rs b/crates/validator/src/beacon_node/fallback.rs index 6209f7db9..0c68b28c7 100644 --- a/crates/validator/src/beacon_node/fallback.rs +++ b/crates/validator/src/beacon_node/fallback.rs @@ -1,11 +1,16 @@ //! Ordered failover across several beacon nodes. //! -//! First healthy wins, in the order given on the command line. Deliberately not -//! health-scored: Lighthouse ranks its nodes by sync distance and tie-breaks on -//! list order, which is better, and is a refinement this does not need yet. +//! First healthy wins. The nodes whose last sync probe passed (neither syncing +//! nor optimistic, see [`super::health`]) are tried first, in the order given on +//! the command line, then the rest in the same order. Deliberately no finer +//! than passed or not: Lighthouse ranks its nodes by sync distance, optimistic +//! status and `el_offline`, and tie-breaks on list order, which is better, and +//! is a refinement this does not need yet. use std::future::Future; use std::pin::Pin; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; use async_trait::async_trait; use ethlambda_types::beacon::builder::SignedValidatorRegistrationV1; @@ -22,6 +27,7 @@ use crate::beacon_node::dto::{ CommitteeSubscriptionDto, ProposerPreparationDto, SingleAttestationDto, SyncCommitteeSubscriptionDto, SyncDutyDto, }; +use crate::beacon_node::health::{NodeHealth, Probe, Standing, SyncStatus, SyncVerdict}; use crate::beacon_node::{ AggregateAttestation, AttesterDuties, BeaconNodeApi, BlockRequest, Delivery, Genesis, Liveness, ProposerDuties, PtcDuties, Published, SignedAggregates, ValidatorDetails, ValidatorEntry, @@ -36,18 +42,60 @@ use crate::error::{Error, Result}; /// to `Self`. type BoxFuture<'a, T> = Pin + Send + 'a>>; +/// Which nodes a request may be sent to. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Reach { + /// Every node. + Every, + /// Every node but those whose last sync probe reported syncing or + /// optimistic, for the calls the Beacon API gives no 503 for in that state. + /// A node that did not answer its probe is still asked. + SkipUnsynced, +} + /// A `BeaconNodeApi` backed by an ordered list of others, answering from the /// first one that succeeds. pub struct FallbackBeaconNode { /// In the order given, which never changes: a [`Producer`] is a position /// in it, so a blinded block goes back to the node that produced it. nodes: Vec, + /// Each node's last sync probe, by the same positions. What orders the + /// walk, and what the duty loop gates each slot on. + health: Arc, } impl FallbackBeaconNode { pub fn new(nodes: Vec) -> Self { assert!(!nodes.is_empty(), "at least one beacon node is required"); - Self { nodes } + let health = Arc::new(NodeHealth::new(nodes.len())); + Self { nodes, health } + } + + /// Each node's last sync probe. Shared, so whatever reports on the nodes + /// reads the records the walk is ordered by. + pub fn health(&self) -> &Arc { + &self.health + } + + /// Ask every node for its sync status at once, each within `budget`, and + /// record each answer, or the error in its place, as it arrives: a node + /// that hangs holds back only its own record. `slot` is the slot the probe + /// is taken ahead of. See [`super::health`]. + pub async fn probe(&self, slot: Slot, budget: Duration) { + let health = &self.health; + let asks = self + .nodes + .iter() + .enumerate() + .map(|(position, node)| async move { + let at = SystemTime::now(); + let outcome = match tokio::time::timeout(budget, node.sync_status()).await { + Ok(answer) => answer.map_err(|err| err.to_string()), + Err(_) => Err(format!("no answer within {} ms", budget.as_millis())), + }; + health.record(position, Probe { slot, at, outcome }); + }); + futures_util::future::join_all(asks).await; } /// The nodes, in order, for a test outside this module that drives a @@ -59,16 +107,22 @@ impl FallbackBeaconNode { /// Try each node in order, returning the first success. /// + /// The order is [`NodeHealth::ranked`]'s: the nodes whose last sync probe + /// passed first, then the rest, each in command-line order. With no probe + /// held it is the command-line order. + /// /// "Success" means the node returned `Ok`, nothing more. That is the right /// rule only where an `Ok` is an answer this client can act on, which is - /// why [`BeaconNodeApi::is_syncing`] does not use this helper: there, - /// `Ok(true)` is a node reporting itself unusable, and returning it from - /// the first node would mask every healthy node behind it. + /// why [`BeaconNodeApi::is_optimistic_or_syncing`] does not use this + /// helper: there, `Ok(true)` is a node reporting itself unusable, and + /// returning it from the first node would mask every healthy node behind + /// it. /// - /// A node that is syncing is skipped here in practice, because the calls - /// routed through this helper answer 503 while syncing and 503 is mapped to - /// an error. That is a property of those endpoints, not something this - /// function arranges. + /// A node that is syncing and still listed is skipped here in practice, + /// because the calls routed through this helper answer 503 while syncing + /// and 503 is mapped to an error. That is a property of those endpoints, + /// not something this function arranges; [`Self::try_each_synced`] is for + /// the calls where it is not. /// /// `'p` is a single, caller-inferred lifetime rather than a higher-ranked /// `for<'b>` one: a higher-ranked bound would force the closure's future to @@ -91,7 +145,22 @@ impl FallbackBeaconNode { where F: Fn(&'p B) -> BoxFuture<'p, Result>, { - self.try_each_at_inner(what, true, call).await + self.try_each_at_inner(what, true, Reach::Every, call).await + } + + /// [`Self::try_each`] without the nodes whose last sync probe reported + /// syncing or optimistic, for a call whose endpoint answers such a node + /// with no 503 and data this client must not sign. A node that did not + /// answer its probe is still asked. When no node is left to ask, this is + /// `Err(BeaconNodeSyncing)`, which the callers read as "do not sign" rather + /// than as a failure. + async fn try_each_synced<'p, T, F>(&'p self, what: &'static str, call: F) -> Result + where + F: Fn(&'p B) -> BoxFuture<'p, Result>, + { + self.try_each_at_inner(what, true, Reach::SkipUnsynced, call) + .await + .map(|(_, value)| value) } /// [`Self::try_each`] without the final `warn!`, for a caller whose own @@ -103,22 +172,34 @@ impl FallbackBeaconNode { where F: Fn(&'p B) -> BoxFuture<'p, Result>, { - self.try_each_at_inner(what, false, call) + self.try_each_at_inner(what, false, Reach::Every, call) .await .map(|(_, value)| value) } + /// The walk behind every `try_each`. The position returned is the node's + /// command-line position, whatever order it was asked in. async fn try_each_at_inner<'p, T, F>( &'p self, what: &'static str, warn_when_all_fail: bool, + reach: Reach, call: F, ) -> Result<(usize, T)> where F: Fn(&'p B) -> BoxFuture<'p, Result>, { let mut last = None; - for (position, node) in self.nodes.iter().enumerate() { + let mut asked = false; + for (position, standing) in self.health.ranked() { + let Some(node) = self.nodes.get(position) else { + continue; + }; + if reach == Reach::SkipUnsynced && standing.is_unsynced() { + debug!(%what, position, ?standing, "Not asking a beacon node whose last sync probe said it is unsynced"); + continue; + } + asked = true; match call(node).await { Ok(value) => return Ok((position, value)), Err(err) => { @@ -131,6 +212,11 @@ impl FallbackBeaconNode { } } } + // Every node said, at its last probe, that it is one this client must + // not sign against: an answer, not a failure. + if reach == Reach::SkipUnsynced && !asked { + return Err(Error::BeaconNodeSyncing); + } let detail = last .map(|err| err.to_string()) .unwrap_or_else(|| "no nodes configured".to_string()); @@ -271,45 +357,39 @@ impl BeaconNodeApi for FallbackBeaconNode { /// /// Deliberately not a plain `try_each`. A node answering `true` is /// answering successfully, so `try_each` would return that `Ok(true)` from - /// the first node and never consult the rest, and the caller - /// (`refresh_epoch`) turns `true` into "do not refresh duties". A syncing - /// node at the head of the list would therefore stop duties from being - /// refreshed for as long as it was syncing, with a perfectly healthy node - /// sitting behind it unused, which is the opposite of what configuring a - /// second node is for. + /// the first node and never consult the rest, and a caller that turns + /// `true` into "hold off" would hold off with a perfectly healthy node + /// sitting behind a syncing one, which is the opposite of what configuring + /// a second node is for. /// - /// So: look for a node that is usable, and report `false` the moment one is - /// found. `true` means every reachable node said it was syncing or - /// optimistic, which is the only situation where the caller's decision to - /// hold off is right. - /// - /// A node that fails outright is skipped like any other failure, and only - /// if none answers at all does this surface an error. + /// So every node is asked at once, and the answers are read by the rule + /// the duty loop's per-slot gate reads its probe by + /// ([`SyncVerdict::signs`]): `false` when some node is usable, `true` when + /// every node that answered said it was syncing or optimistic. A node that + /// fails outright is left out of the count, and only if none answers at + /// all does this surface an error. async fn is_optimistic_or_syncing(&self) -> Result { + let answers = + futures_util::future::join_all(self.nodes.iter().map(|node| node.sync_status())).await; let mut last = None; - let mut any_answered = false; - for (position, node) in self.nodes.iter().enumerate() { - match node.is_optimistic_or_syncing().await { - Ok(false) => return Ok(false), - Ok(true) => { - any_answered = true; - debug!( - position, - "Beacon node is syncing or optimistic; trying the next" - ); - } + let mut standings = Vec::with_capacity(answers.len()); + for (position, answer) in answers.into_iter().enumerate() { + match answer { + Ok(status) => standings.push(Standing::of(&status)), Err(err) => { - debug!(what = "syncing", position, %err, "Beacon node request failed; trying the next"); + debug!(what = "syncing", position, %err, "Beacon node request failed"); last = Some(err); } } } - if any_answered { - // Every node that answered said it was unusable. That is a real - // answer, not a failure: the caller should hold off, and saying so - // is more useful than an error claiming nothing could be reached. - return Ok(true); + let verdict = SyncVerdict::tally(standings); + if verdict.answered > 0 { + // Every node that answered said it was unusable, when none is + // synced. That is a real answer, not a failure: the caller should + // hold off, and saying so is more useful than an error claiming + // nothing could be reached. + return Ok(!verdict.signs()); } let detail = last @@ -322,6 +402,13 @@ impl BeaconNodeApi for FallbackBeaconNode { Err(Error::AllBeaconNodesFailed(detail)) } + /// The first node in the walk's order to answer, as for any query. The + /// per-slot probe asks each node itself (see [`Self::probe`]), and nothing + /// else calls this through the fallback. + async fn sync_status(&self) -> Result { + self.try_each("syncing", |node| node.sync_status()).await + } + async fn validator_indices(&self, pubkeys: &[BlsPubkey]) -> Result> { self.try_each("validator_indices", |node| node.validator_indices(pubkeys)) .await @@ -577,11 +664,14 @@ impl BeaconNodeApi for FallbackBeaconNode { /// walk, even though another might have one. That is the right trade: PTC /// votes are due at three quarters of the slot, and a node that has seen /// nothing by then is one this client should not be voting through. + /// + /// Never from a node whose last sync probe reported syncing or optimistic: + /// see the trait's contract. async fn payload_attestation_data( &self, slot: Slot, ) -> Result> { - self.try_each("payload_attestation_data", |node| { + self.try_each_synced("payload_attestation_data", |node| { node.payload_attestation_data(slot) }) .await @@ -687,9 +777,11 @@ impl BeaconNodeApi for FallbackBeaconNode { } /// An optimistic head is an error from each implementation, so a node - /// tracking an unvalidated head is walked past rather than signed over. + /// tracking an unvalidated head is walked past rather than signed over. A + /// node whose last sync probe reported syncing or optimistic is not asked + /// at all: see the trait's contract. async fn head_block_root(&self) -> Result { - self.try_each("head_block_root", |node| node.head_block_root()) + self.try_each_synced("head_block_root", |node| node.head_block_root()) .await } @@ -924,13 +1016,13 @@ mod tests { ); } - /// A syncing node at the head of the list must not stop duties being - /// refreshed when a healthy node sits behind it. + /// A syncing node at the head of the list must not make the fallback + /// report itself unusable when a healthy node sits behind it. /// - /// `is_syncing` returning `Ok(true)` is a *successful* call, so a plain - /// `try_each` would return the first node's answer and never look further. - /// `refresh_epoch` turns `true` into "do not refresh", so the second node - /// would go unused for as long as the first was syncing. + /// `is_optimistic_or_syncing` returning `Ok(true)` is a *successful* call, + /// so a plain `try_each` would return the first node's answer and never + /// look further, and a caller holding off on `true` would leave the second + /// node unused for as long as the first was syncing. #[tokio::test] async fn a_syncing_first_node_does_not_mask_a_healthy_second() { let syncing = MockBeaconNode { @@ -1470,6 +1562,209 @@ mod tests { ); } + /// A node that answers every duty endpoint for slot 96, its head root + /// marked with `mark` so the answer names the node that gave it. + fn answering(mark: u8) -> MockBeaconNode { + use ethlambda_types::beacon::primitives::BlsSignature; + let root = Root::repeat_byte(mark); + let mut node = MockBeaconNode::new().with_attestation_data(96); + node.aggregate = node.attestation_data; + node.with_block(96, 7) + .with_head_root(root) + .with_contribution(altair::SyncCommitteeContribution { + slot: 96, + beacon_block_root: root, + subcommittee_index: 0, + aggregation_bits: Default::default(), + signature: BlsSignature([1; 96]), + }) + .with_payload_attestation_data(gloas::PayloadAttestationData { + beacon_block_root: root, + slot: 96, + payload_present: true, + blob_data_available: true, + }) + } + + /// The issue's second case: the first node is syncing but answers every + /// endpoint, as a node that does not refuse with 503 would; the second is + /// synced. Once a probe has said so, every duty is served by the second, + /// and the first is asked nothing. + #[tokio::test] + async fn every_duty_is_served_by_the_synced_node_listed_second() { + let syncing = MockBeaconNode { + syncing: true, + ..answering(1) + }; + let fallback = FallbackBeaconNode::new(vec![syncing, answering(2)]); + fallback.probe(96, std::time::Duration::from_secs(1)).await; + + fallback + .attestation_data(96, fork_of(96)) + .await + .expect("attestation data"); + let block = fallback + .produce_block(&request(96, 7)) + .await + .expect("a block"); + assert_eq!(block.producer, Producer::at(1)); + fallback + .publish_block(ForkName::Electra, b"body") + .await + .expect("published"); + fallback + .aggregate_attestation(96, Root::ZERO, 0) + .await + .expect("an aggregate"); + let head = fallback.head_block_root().await.expect("a head"); + assert_eq!(head, Root::repeat_byte(2)); + fallback + .sync_committee_contribution(96, 0, head) + .await + .expect("a contribution"); + fallback + .payload_attestation_data(96) + .await + .expect("payload data") + .expect("a block"); + + let first = &fallback.nodes[0]; + assert_eq!(first.attestation_data_call_count(), 0); + assert!(first.block_requests().is_empty()); + assert!(first.published_blocks().is_empty()); + assert!(first.aggregate_requests().is_empty()); + assert!(first.contribution_requests().is_empty()); + assert_eq!(first.payload_attestation_data_call_count(), 0); + + let second = &fallback.nodes[1]; + assert_eq!(second.attestation_data_call_count(), 1); + assert_eq!(second.block_requests().len(), 1); + assert_eq!(second.published_blocks().len(), 1); + assert_eq!(second.aggregate_requests().len(), 1); + assert_eq!(second.contribution_requests().len(), 1); + assert_eq!(second.payload_attestation_data_call_count(), 1); + } + + /// The order is a preference, not a filter: a call the synced node fails + /// still falls through to the rest, where the 503 the Beacon API requires + /// of a syncing node is the backstop. + #[tokio::test] + async fn a_node_that_did_not_pass_is_still_asked_after_the_ones_that_did() { + let syncing = MockBeaconNode { + syncing: true, + ..answering(1) + }; + let failing = answering(2).failing_call("attestation_data", "timed out"); + let fallback = FallbackBeaconNode::new(vec![syncing, failing]); + fallback.probe(96, std::time::Duration::from_secs(1)).await; + + fallback + .attestation_data(96, fork_of(96)) + .await + .expect("the first node answers once the second has failed"); + assert_eq!(fallback.nodes[0].attestation_data_call_count(), 1); + } + + /// The walk's order is not the list's, but a blinded block still names the + /// node that produced it by its command-line position, and goes back there. + #[tokio::test] + async fn a_blinded_block_goes_back_to_its_producer_whatever_the_walk_order() { + let syncing = MockBeaconNode { + syncing: true, + ..blinded_node() + }; + let fallback = FallbackBeaconNode::new(vec![syncing, blinded_node()]); + fallback.probe(5, std::time::Duration::from_secs(1)).await; + + let produced = fallback + .produce_block(&blinded_request(5, 7)) + .await + .expect("node 1 produces"); + assert_eq!(produced.producer, Producer::at(1)); + fallback + .publish_blinded_block(produced.producer, ForkName::Electra, &[4]) + .await + .expect("published"); + assert!( + fallback.nodes[0] + .published_blinded + .lock() + .expect("lock") + .is_empty() + ); + assert_eq!( + *fallback.nodes[1].published_blinded.lock().expect("lock"), + vec![(ForkName::Electra, vec![4])] + ); + } + + /// A head root and payload attestation data are never taken from a node + /// whose probe said syncing or optimistic, even when the synced node ahead + /// of it in the walk fails the call: no 503 would stop the answer. + #[tokio::test] + async fn an_unsynced_node_is_not_asked_for_a_head_root_or_payload_data() { + for unsynced in [ + MockBeaconNode { + syncing: true, + ..answering(1) + }, + MockBeaconNode { + optimistic: true, + ..answering(1) + }, + ] { + let failing = answering(2) + .failing_call("head_block_root", "timed out") + .failing_call("payload_attestation_data", "timed out"); + let fallback = FallbackBeaconNode::new(vec![unsynced, failing]); + fallback.probe(96, std::time::Duration::from_secs(1)).await; + + let err = fallback.head_block_root().await.expect_err("no root"); + assert!(matches!(err, Error::AllBeaconNodesFailed(_)), "got {err:?}"); + let err = fallback + .payload_attestation_data(96) + .await + .expect_err("no data"); + assert!(matches!(err, Error::AllBeaconNodesFailed(_)), "got {err:?}"); + assert_eq!(fallback.nodes[0].payload_attestation_data_call_count(), 0); + } + } + + /// With every node unsynced at its last probe, nobody is asked, and the + /// answer is the one a caller reads as "do not sign" rather than a failed + /// node. + #[tokio::test] + async fn every_node_unsynced_is_a_syncing_answer_without_asking() { + let optimistic = MockBeaconNode { + optimistic: true, + ..answering(1) + }; + let fallback = FallbackBeaconNode::new(vec![optimistic]); + fallback.probe(96, std::time::Duration::from_secs(1)).await; + + let err = fallback.head_block_root().await.expect_err("no root"); + assert!(matches!(err, Error::BeaconNodeSyncing), "got {err:?}"); + let err = fallback + .payload_attestation_data(96) + .await + .expect_err("no data"); + assert!(matches!(err, Error::BeaconNodeSyncing), "got {err:?}"); + assert_eq!(fallback.nodes[0].payload_attestation_data_call_count(), 0); + } + + /// A node whose probe failed is not known to be unsynced, and is asked. + #[tokio::test] + async fn a_node_that_did_not_answer_its_probe_is_still_asked_for_a_head_root() { + let unprobed = answering(3).failing_call("is_syncing", "down"); + let fallback = FallbackBeaconNode::new(vec![unprobed]); + fallback.probe(96, std::time::Duration::from_secs(1)).await; + + assert_eq!( + fallback.head_block_root().await.expect("a root"), + Root::repeat_byte(3) + ); + } + fn blinded_request(slot: Slot, proposer_index: ValidatorIndex) -> BlockRequest { BlockRequest { builder_boost_factor: Some(100), diff --git a/crates/validator/src/beacon_node/health.rs b/crates/validator/src/beacon_node/health.rs new file mode 100644 index 000000000..509d6cf9c --- /dev/null +++ b/crates/validator/src/beacon_node/health.rs @@ -0,0 +1,846 @@ +//! What each configured beacon node last said about its own sync status. +//! +//! # One probe a slot, ahead of the boundary +//! +//! [`run`] asks every node for `GET /eth/v1/node/syncing` once a slot, all at +//! once, a sixth of a slot before the slot's boundary: 2 s on mainnet's 12 s +//! slots, Lighthouse's lookahead. That is after the previous slot's last duty +//! offset (the payload timeliness committee vote, three quarters in) and early +//! enough that a healthy node has answered by the boundary. The duty loop reads +//! the answers there and never waits for one. The probe runs on its own task and +//! clock, as the doppelganger check does, so a slow node never delays a duty +//! and an overrunning duty never delays a probe. +//! +//! # What the answers are read for +//! +//! - **The slot's gate** ([`slot_signs`]). A slot signs nothing (no block, +//! attestation, aggregate, sync committee message, contribution or payload +//! timeliness vote) when at least one node answered the probe taken for it +//! and every node that answered reported syncing or optimistic. A node that +//! did not answer does not count as syncing: the 503 a duty endpoint answers +//! while its node syncs still covers it, so nodes that cannot be reached +//! never stop duties on their own. Only the probe taken for the slot counts, +//! so a late answer, or a probe task that stopped, opens the gate rather than +//! holding it shut. +//! - **Routing** ([`NodeHealth::ranked`]). The fallback asks the nodes whose +//! last probe passed (neither syncing nor optimistic) first, in command-line +//! order, then the rest, in the same order. Positions stay command-line +//! positions, so a blinded block still goes back to the node that produced it. +//! - **Two calls the Beacon API leaves ungated.** No 503 covers a syncing +//! node's head root, or an optimistic node's payload attestation data, so the +//! fallback does not ask a node whose last probe reported syncing or +//! optimistic for either. Without that, a passed node failing either call +//! would hand it to the next node in the walk, which may be that one. +//! +//! # No clock-based rule +//! +//! Nothing here judges a node by how old its head looks against this client's +//! clock. During a network-wide stall every head is old, and clients that stop +//! signing then keep the chain stalled. The signal is the node's own +//! `is_syncing` and `is_optimistic`. `head_slot` and `sync_distance` are kept in +//! the record, not acted on. A record older than two slots is no longer read for +//! routing, which only ever moves a node back to plain command-line order. + +use std::sync::{Arc, OnceLock, PoisonError, RwLock}; +use std::time::{Duration, SystemTime}; + +use ethlambda_types::beacon::primitives::Slot; +use tracing::{info, warn}; + +use crate::beacon_node::BeaconNodeApi; +use crate::beacon_node::fallback::FallbackBeaconNode; +use crate::slot_clock::SlotClock; + +/// How far ahead of a slot's boundary its probe is taken, as a fraction of the +/// slot: a sixth, which is Lighthouse's 2 s on mainnet's 12 s slots. Past the +/// payload timeliness committee vote, the latest duty offset of the slot +/// before, at three quarters. +const PROBE_LEAD_DIVISOR: u32 = 6; + +/// How many slots a node's last probe is read for routing. Each probe replaces +/// the last one a slot later, so only a probe task that stopped leaves one this +/// old. +const ROUTING_SLOTS: u32 = 2; + +/// One node's `GET /eth/v1/node/syncing` answer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SyncStatus { + /// The node's head slot. `None` when the node sent none, or one that is not + /// a quoted integer: see `SyncingDto::head_slot`. + pub head_slot: Option, + /// How many slots the node's head is behind its own wall clock. `None` as + /// for `head_slot`. + pub sync_distance: Option, + /// The node's consensus head is behind the network's. + pub is_syncing: bool, + /// The node's head has an execution payload its execution client has not + /// validated. `false` when the node left the field out. + pub is_optimistic: bool, + /// The node cannot reach its execution client. Logged, never acted on: the + /// node reports `is_optimistic` once that starts to matter. `false` when + /// the node left the field out. + pub el_offline: bool, +} + +impl SyncStatus { + /// Neither syncing nor optimistic: a node a validator may sign against. + pub fn is_synced(&self) -> bool { + !self.is_syncing && !self.is_optimistic + } +} + +/// One probe of one node. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Probe { + /// The slot the probe was taken ahead of. The slot's gate reads this probe + /// and no other. + pub slot: Slot, + /// When the request was sent. + pub at: SystemTime, + /// The node's answer, or why there is none: an error, or no answer within + /// the probe's budget. + pub outcome: Result, +} + +impl Probe { + pub fn standing(&self) -> Standing { + match &self.outcome { + Ok(status) => Standing::of(status), + Err(_) => Standing::NoAnswer, + } + } +} + +/// What a node's probe says about it, in the terms the gate and the routing +/// read. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Standing { + /// Answered, neither syncing nor optimistic. + Synced, + /// Answered `is_syncing: true`, optimistic or not. + Syncing, + /// Answered `is_optimistic: true` and not syncing. + Optimistic, + /// The probe failed: an error, or no answer in time. + NoAnswer, + /// Not probed yet, or the last probe is too old to read. + Unknown, +} + +impl Standing { + pub fn of(status: &SyncStatus) -> Self { + if status.is_syncing { + Self::Syncing + } else if status.is_optimistic { + Self::Optimistic + } else { + Self::Synced + } + } + + /// The node said it is one a validator must not sign against. + pub fn is_unsynced(self) -> bool { + matches!(self, Self::Syncing | Self::Optimistic) + } +} + +/// How the nodes that answered one round of probes split. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct SyncVerdict { + /// Nodes that answered at all. + pub answered: usize, + /// Of those, the ones neither syncing nor optimistic. + pub synced: usize, + pub syncing: usize, + pub optimistic: usize, +} + +impl SyncVerdict { + pub fn tally(standings: impl IntoIterator) -> Self { + let mut verdict = Self::default(); + for standing in standings { + match standing { + Standing::Synced => verdict.synced += 1, + Standing::Syncing => verdict.syncing += 1, + Standing::Optimistic => verdict.optimistic += 1, + Standing::NoAnswer | Standing::Unknown => continue, + } + verdict.answered += 1; + } + verdict + } + + /// Whether duties may be signed: some node answered synced, or no node + /// answered at all, which leaves each duty to its endpoint's 503. + pub fn signs(&self) -> bool { + self.answered == 0 || self.synced > 0 + } +} + +/// The last probe of each configured beacon node, in command-line order. +/// +/// Shared, so the fallback that routes requests by it and anything that reports +/// on the nodes read the same records. [`Self::snapshot`] is the cheap read for +/// the latter. +pub struct NodeHealth { + probes: RwLock>>, + /// How long a probe is read for routing. Unset until [`run`] starts, so a + /// fallback that is never probed on a schedule (a test, the voluntary-exit + /// command) reads whatever it holds. + read_for: OnceLock, +} + +impl NodeHealth { + pub fn new(nodes: usize) -> Self { + Self { + probes: RwLock::new(vec![None; nodes]), + read_for: OnceLock::new(), + } + } + + /// Every node's last probe, in command-line order: `None` for a node not + /// probed yet. A copy, so a caller holds no lock. + pub fn snapshot(&self) -> Vec> { + self.read().clone() + } + + /// Stop reading a probe for routing once it is older than `age`. + pub fn expire_after(&self, age: Duration) { + let _ = self.read_for.set(age); + } + + /// Keep `probe` as the node at `position`'s last, and log what changed: a + /// node that stopped or started answering synced, and `el_offline` going on + /// or off. Only changes, since a probe runs every slot. + pub fn record(&self, position: usize, probe: Probe) { + let standing = probe.standing(); + let el_offline = is_el_offline(&probe); + let (head_slot, sync_distance) = match &probe.outcome { + Ok(status) => (status.head_slot, status.sync_distance), + Err(_) => (None, None), + }; + let error = probe.outcome.as_ref().err().cloned(); + let previous = { + let mut probes = self.probes.write().unwrap_or_else(PoisonError::into_inner); + let Some(held) = probes.get_mut(position) else { + return; + }; + held.replace(probe) + }; + + let was = previous.as_ref().map(Probe::standing); + if was != Some(standing) { + match standing { + Standing::Synced if was.is_some() => info!( + position, + ?head_slot, + "Beacon node reports it is synced; duties go to it first again" + ), + Standing::Syncing => warn!( + position, + ?head_slot, + ?sync_distance, + "Beacon node reports it is syncing; duties go to the other nodes first" + ), + Standing::Optimistic => warn!( + position, + ?head_slot, + "Beacon node reports an optimistic head; duties go to the other nodes first" + ), + Standing::NoAnswer => warn!( + position, + error = error.as_deref().unwrap_or_default(), + "Beacon node did not answer its sync probe" + ), + Standing::Synced | Standing::Unknown => {} + } + } + let was_el_offline = previous.as_ref().is_some_and(is_el_offline); + if el_offline && !was_el_offline { + warn!( + position, + "Beacon node reports its execution client is offline; it will go optimistic if it \ + has not already" + ); + } else if was_el_offline && !el_offline && standing != Standing::NoAnswer { + info!(position, "Beacon node reports its execution client is back"); + } + } + + /// Every position, the nodes whose last probe passed first, then the rest, + /// each group in command-line order, with each node's standing. + /// + /// The order requests walk the nodes in. Nothing more than passed or not: + /// with no probe held, it is plain command-line order. + pub fn ranked(&self) -> Vec<(usize, Standing)> { + self.ranked_at(SystemTime::now()) + } + + fn ranked_at(&self, now: SystemTime) -> Vec<(usize, Standing)> { + let read_for = self.read_for.get().copied(); + let probes = self.read(); + let standings = probes.iter().enumerate().map(|(position, probe)| { + let standing = match probe { + Some(probe) if !is_stale(probe, read_for, now) => probe.standing(), + _ => Standing::Unknown, + }; + (position, standing) + }); + let (mut ranked, rest): (Vec<_>, Vec<_>) = + standings.partition(|(_, standing)| *standing == Standing::Synced); + ranked.extend(rest); + ranked + } + + /// How the probes taken for `slot` split. A node whose last probe was taken + /// for another slot did not answer this one. + pub fn verdict(&self, slot: Slot) -> SyncVerdict { + let probes = self.read(); + let for_slot = probes.iter().flatten().filter(|probe| probe.slot == slot); + SyncVerdict::tally(for_slot.map(Probe::standing)) + } + + /// The records are plain values with no invariant between them, so one a + /// panicking writer left behind is still a record worth reading. + fn read(&self) -> std::sync::RwLockReadGuard<'_, Vec>> { + self.probes.read().unwrap_or_else(PoisonError::into_inner) + } +} + +fn is_el_offline(probe: &Probe) -> bool { + matches!(&probe.outcome, Ok(status) if status.el_offline) +} + +fn is_stale(probe: &Probe, read_for: Option, now: SystemTime) -> bool { + read_for.is_some_and(|limit| now.duration_since(probe.at).unwrap_or_default() > limit) +} + +/// The duty loop's gate for `slot`, read at its boundary: whether the slot's +/// duties may be signed, by the probe taken ahead of it. A slot it withholds is +/// logged and counted here. +pub fn slot_signs(health: &NodeHealth, slot: Slot) -> bool { + let verdict = health.verdict(slot); + if verdict.signs() { + return true; + } + let SyncVerdict { + answered, + syncing, + optimistic, + .. + } = verdict; + warn!( + %slot, + answered, + syncing, + optimistic, + "Every beacon node that answered this slot's sync probe is syncing or optimistic; \ + signing nothing in this slot" + ); + crate::metrics::inc_slots_skipped_syncing(); + crate::metrics::set_beacon_node_available(false); + false +} + +/// Probe every node in `beacon_node` once a slot, ahead of each boundary, for +/// the life of the client. See the module doc. +pub async fn run(beacon_node: Arc>, clock: SlotClock) { + beacon_node + .health() + .expire_after(clock.slot_duration() * ROUTING_SLOTS); + let mut last = None; + loop { + let (slot, wait) = next_probe(&clock, last, SystemTime::now()); + tokio::time::sleep(wait).await; + // Until the next probe is due, so rounds never overlap and a node that + // hangs is recorded as not answering by then. + let budget = probe_time(&clock, slot + 1) + .duration_since(SystemTime::now()) + .unwrap_or_default(); + beacon_node.probe(slot, budget).await; + last = Some(slot); + } +} + +/// When the probe for `slot` is taken: [`PROBE_LEAD_DIVISOR`]'s fraction of a +/// slot before its boundary. +fn probe_time(clock: &SlotClock, slot: Slot) -> SystemTime { + let start = clock.start_of(slot); + let lead = clock.slot_duration() / PROBE_LEAD_DIVISOR; + start.checked_sub(lead).unwrap_or(start) +} + +/// The slot to probe for next, given the last one probed, and how long until +/// its probe is due. +/// +/// The slot is the first whose boundary is still ahead, and never one already +/// probed. Inside its lead already (a client just started, or a probe that +/// overran), the wait is zero, so the slot the duty loop serves next has a +/// probe whenever one can answer before its boundary. +fn next_probe(clock: &SlotClock, last: Option, now: SystemTime) -> (Slot, Duration) { + let ahead = clock.slot_at(now).map_or(0, |slot| slot + 1); + let slot = last.map_or(ahead, |last| ahead.max(last + 1)); + let wait = probe_time(clock, slot) + .duration_since(now) + .unwrap_or_default(); + (slot, wait) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::UNIX_EPOCH; + + use crate::beacon_node::mock::MockBeaconNode; + + const GENESIS: u64 = 1_000_000; + + fn status(is_syncing: bool, is_optimistic: bool) -> SyncStatus { + SyncStatus { + head_slot: Some(100), + sync_distance: Some(0), + is_syncing, + is_optimistic, + el_offline: false, + } + } + + fn probe(slot: Slot, outcome: Result) -> Probe { + Probe { + slot, + at: SystemTime::now(), + outcome, + } + } + + fn synced(slot: Slot) -> Probe { + probe(slot, Ok(status(false, false))) + } + + fn syncing(slot: Slot) -> Probe { + probe(slot, Ok(status(true, false))) + } + + fn optimistic(slot: Slot) -> Probe { + probe(slot, Ok(status(false, true))) + } + + fn down(slot: Slot) -> Probe { + probe(slot, Err("connection refused".to_string())) + } + + fn health(probes: Vec) -> NodeHealth { + let health = NodeHealth::new(probes.len()); + for (position, probe) in probes.into_iter().enumerate() { + health.record(position, probe); + } + health + } + + /// A slot is withheld only when some node answered and none of those that + /// did is synced. Nodes that did not answer change nothing either way. + #[test] + fn a_slot_is_withheld_only_when_every_node_that_answered_is_unsynced() { + let slot = 10; + let cases = [ + (vec![synced(slot)], true), + (vec![down(slot)], true), + (vec![down(slot), down(slot)], true), + (vec![syncing(slot)], false), + (vec![optimistic(slot)], false), + (vec![syncing(slot), optimistic(slot)], false), + (vec![syncing(slot), down(slot)], false), + (vec![syncing(slot), synced(slot)], true), + (vec![optimistic(slot), down(slot), synced(slot)], true), + ]; + for (probes, signs) in cases { + let standings: Vec = probes.iter().map(Probe::standing).collect(); + assert_eq!(health(probes).verdict(slot).signs(), signs, "{standings:?}"); + } + } + + /// Only the probe taken for the slot counts: a node still on the last + /// slot's answer has not answered this one, so an old "syncing" cannot hold + /// a slot shut. + #[test] + fn only_the_probe_taken_for_the_slot_counts() { + let health = health(vec![syncing(9), syncing(9)]); + assert!(health.verdict(10).signs()); + assert_eq!(health.verdict(10).answered, 0); + + let health_now = NodeHealth::new(2); + health_now.record(0, syncing(9)); + health_now.record(1, syncing(10)); + let verdict = health_now.verdict(10); + assert_eq!((verdict.answered, verdict.syncing), (1, 1)); + assert!(!verdict.signs()); + } + + #[test] + fn the_gate_counts_each_kind_of_answer() { + let slot = 4; + let health = health(vec![syncing(slot), optimistic(slot), down(slot)]); + assert_eq!( + health.verdict(slot), + SyncVerdict { + answered: 2, + synced: 0, + syncing: 1, + optimistic: 1, + } + ); + assert!(!slot_signs(&health, slot)); + } + + /// Syncing and optimistic together is syncing: the node is behind, which + /// says more than that its head is unvalidated. + #[test] + fn a_syncing_and_optimistic_node_stands_as_syncing() { + assert_eq!(Standing::of(&status(true, true)), Standing::Syncing); + assert_eq!(Standing::of(&status(false, true)), Standing::Optimistic); + assert_eq!(Standing::of(&status(false, false)), Standing::Synced); + } + + #[test] + fn nodes_that_passed_come_first_in_command_line_order() { + let health = health(vec![ + syncing(3), + synced(3), + down(3), + synced(3), + optimistic(3), + ]); + let order: Vec = health + .ranked() + .into_iter() + .map(|(position, _)| position) + .collect(); + assert_eq!(order, vec![1, 3, 0, 2, 4]); + } + + /// Before any probe the walk is the command-line order, unchanged, which + /// is what every fallback that is never probed relies on. + #[test] + fn an_unprobed_health_keeps_command_line_order() { + let health = NodeHealth::new(3); + assert_eq!( + health.ranked(), + vec![ + (0, Standing::Unknown), + (1, Standing::Unknown), + (2, Standing::Unknown) + ] + ); + } + + /// A probe older than the bound is not read for routing: the node goes + /// back to command-line order, as if never probed. + #[test] + fn a_stale_probe_is_not_read_for_routing() { + let health = NodeHealth::new(2); + health.expire_after(Duration::from_secs(24)); + let taken = SystemTime::now(); + health.record(0, syncing(3)); + health.record( + 1, + Probe { + at: taken, + ..synced(3) + }, + ); + + let fresh = health.ranked_at(taken + Duration::from_secs(1)); + assert_eq!(fresh[0], (1, Standing::Synced)); + + let later = health.ranked_at(taken + Duration::from_secs(60)); + assert_eq!(later, vec![(0, Standing::Unknown), (1, Standing::Unknown)]); + } + + /// The snapshot is every node's last probe, in command-line order, with + /// what the node said about its head. + #[test] + fn the_snapshot_holds_each_nodes_last_probe() { + let health = NodeHealth::new(3); + health.record(2, syncing(7)); + health.record(0, synced(6)); + health.record(0, synced(7)); + + let snapshot = health.snapshot(); + assert_eq!(snapshot.len(), 3); + assert_eq!(snapshot[0].as_ref().map(|probe| probe.slot), Some(7)); + assert!(snapshot[1].is_none()); + let syncing = snapshot[2].as_ref().expect("probed"); + assert_eq!( + syncing.outcome.as_ref().expect("answered").head_slot, + Some(100) + ); + } + + fn clock() -> SlotClock { + SlotClock::new(GENESIS, 12_000, 3_333, 6_667) + } + + fn at_ms(since_genesis_ms: u64) -> SystemTime { + UNIX_EPOCH + Duration::from_secs(GENESIS) + Duration::from_millis(since_genesis_ms) + } + + /// On mainnet's 12 s slots the probe is taken 2 s before each boundary. + #[test] + fn the_probe_is_taken_a_sixth_of_a_slot_before_the_boundary() { + let clock = clock(); + assert_eq!(probe_time(&clock, 5), at_ms(5 * 12_000 - 2_000)); + } + + /// The first probe is for the next boundary, the one the duty loop serves + /// first, and waits for that boundary's lead. + #[test] + fn the_first_probe_is_for_the_next_boundary() { + let clock = clock(); + let (slot, wait) = next_probe(&clock, None, at_ms(3 * 12_000 + 500)); + assert_eq!(slot, 4); + assert_eq!(wait, Duration::from_millis(12_000 - 2_000 - 500)); + } + + /// A client started inside the lead probes at once, for the boundary + /// ahead of it. + #[test] + fn a_client_started_inside_the_lead_probes_at_once() { + let clock = clock(); + let (slot, wait) = next_probe(&clock, None, at_ms(3 * 12_000 + 11_000)); + assert_eq!((slot, wait), (4, Duration::ZERO)); + } + + #[test] + fn later_probes_wait_for_the_lead_before_their_boundary() { + let clock = clock(); + // Slot 4 was just probed, in slot 3; slot 5's is due 2 s before it. + let now = at_ms(3 * 12_000 + 10_100); + let (slot, wait) = next_probe(&clock, Some(4), now); + assert_eq!(slot, 5); + assert_eq!(wait, Duration::from_millis(12_000 - 100)); + } + + /// A probe that ran past the boundary it was for does not hold the next + /// one back: the next is for the next boundary still ahead. + #[test] + fn an_overrun_probe_moves_on_to_the_next_boundary() { + let clock = clock(); + let now = at_ms(5 * 12_000 + 11_000); + let (slot, wait) = next_probe(&clock, Some(4), now); + assert_eq!(slot, 6); + assert_eq!(wait, Duration::ZERO, "inside slot 6's lead already"); + } + + /// Before genesis the first probe waits for slot 0's lead. + #[test] + fn before_genesis_the_first_probe_is_slot_zeros() { + let clock = clock(); + let now = UNIX_EPOCH + Duration::from_secs(GENESIS - 60); + let (slot, wait) = next_probe(&clock, None, now); + assert_eq!(slot, 0); + assert_eq!(wait, Duration::from_secs(58)); + } + + fn fallback(nodes: Vec) -> FallbackBeaconNode { + FallbackBeaconNode::new(nodes) + } + + /// A probe asks every node and records each in its own position, an + /// error in place of an answer for a node that is down. + #[tokio::test] + async fn a_probe_records_every_node_in_command_line_order() { + let syncing = MockBeaconNode { + syncing: true, + ..MockBeaconNode::new() + }; + let fallback = fallback(vec![ + MockBeaconNode::new(), + syncing, + MockBeaconNode::failing("down"), + ]); + fallback.probe(8, Duration::from_secs(1)).await; + + let snapshot = fallback.health().snapshot(); + let standings: Vec = snapshot + .iter() + .map(|probe| probe.as_ref().expect("probed").standing()) + .collect(); + assert_eq!( + standings, + vec![Standing::Synced, Standing::Syncing, Standing::NoAnswer] + ); + assert!(snapshot.iter().flatten().all(|probe| probe.slot == 8)); + } + + /// A node that does not answer within the budget is recorded as not + /// answering, and does not hold back the others' records. + #[tokio::test(start_paused = true)] + async fn a_hung_node_is_recorded_as_not_answering_within_the_budget() { + let hung = MockBeaconNode::new().with_sync_status_delay(Duration::from_secs(60)); + let fallback = fallback(vec![hung, MockBeaconNode::new()]); + + let started = tokio::time::Instant::now(); + fallback.probe(8, Duration::from_secs(2)).await; + assert!(started.elapsed() < Duration::from_secs(3)); + + let snapshot = fallback.health().snapshot(); + let hung = snapshot[0].as_ref().expect("recorded"); + assert_eq!(hung.standing(), Standing::NoAnswer); + assert!( + hung.outcome + .as_ref() + .expect_err("no answer") + .contains("no answer") + ); + assert_eq!( + snapshot[1].as_ref().expect("recorded").standing(), + Standing::Synced + ); + } + + /// The issue's first case: a node that passes the epoch's refresh and then + /// goes optimistic withholds the next slot, whose probe says so. The duty + /// loop then runs no proposal and no slot duties for it. Of those duties, + /// the sync committee message and the payload vote are also refused at the + /// fallback, which does not ask an optimistic node for either. + #[tokio::test] + async fn a_node_gone_optimistic_after_the_refresh_withholds_the_next_slot() { + use ethlambda_types::beacon::primitives::{BlsPubkey, Bytes32, Root}; + use tokio::sync::RwLock; + + use crate::beacon_node::ValidatorEntry; + use crate::beacon_node::dto::{PtcDutyDto, SyncDutyDto, encode_hex}; + use crate::duties::DutiesService; + use crate::keys::ValidatorStore; + use crate::payload_attestation::PayloadAttestationService; + use crate::proposer_settings::ProposerSettings; + use crate::signing::SigningContext; + use crate::sync_committee::SyncCommitteeService; + + let mut node = MockBeaconNode::new() + .with_duties(3, Root::repeat_byte(1), Vec::new()) + .with_duties(4, Root::repeat_byte(2), Vec::new()) + .with_proposers(3, Root::repeat_byte(1), Vec::new()) + .with_head_root(Root::repeat_byte(5)); + node.validators = vec![ValidatorEntry { + index: 11, + pubkey: BlsPubkey([1; 48]), + status: "active_ongoing".to_string(), + }]; + let beacon_node = Arc::new(fallback(vec![node])); + let context = Arc::new(SigningContext::new( + ethlambda_types::beacon::config::Config::mainnet(), + Root::ZERO, + )); + let settings = ProposerSettings::new(Bytes32::ZERO, None); + let mut duties = DutiesService::new(beacon_node.clone(), Vec::new()); + + let slot = 3 * ethlambda_types::beacon::preset::slots_per_epoch(); + beacon_node.probe(slot, Duration::from_secs(1)).await; + assert!(slot_signs(beacon_node.health(), slot)); + crate::refresh_epoch( + &beacon_node, + &mut duties, + &[BlsPubkey([1; 48])], + 3, + &settings, + &context, + ) + .await + .expect("the refresh passes on a synced node"); + + beacon_node.nodes()[0].set_sync_status(SyncStatus { + is_optimistic: true, + ..beacon_node.nodes()[0].current_status() + }); + beacon_node.probe(slot + 1, Duration::from_secs(1)).await; + assert!( + !slot_signs(beacon_node.health(), slot + 1), + "the next slot signs nothing" + ); + + let store = RwLock::new(ValidatorStore::new()); + let sync_duty = SyncDutyDto { + pubkey: encode_hex(&[1u8; 48]), + validator_index: 11, + validator_sync_committee_indices: vec![0], + }; + let sync = SyncCommitteeService::new(beacon_node.clone(), context.clone()); + let root = sync + .publish_messages(slot + 1, &[sync_duty], &store) + .await + .expect("not a failure"); + assert!(root.is_none(), "no head root to sign"); + + let ptc_duty = PtcDutyDto { + pubkey: encode_hex(&[1u8; 48]), + validator_index: 11, + slot: slot + 1, + }; + let ptc = PayloadAttestationService::new(beacon_node.clone(), context); + let voted = ptc + .attest(slot + 1, &[ptc_duty], &store) + .await + .expect("not a failure"); + assert_eq!(voted, 0); + + let node = &beacon_node.nodes()[0]; + assert!(node.submitted_sync_messages().is_empty()); + assert_eq!(node.payload_attestation_data_call_count(), 0); + assert!(node.submitted_payload_attestations().is_empty()); + } + + /// The issue's third case: a node that is syncing but not optimistic + /// answers its stale head with `execution_optimistic: false`, which the + /// head root fetch alone cannot tell apart. Its probe can, so no message is + /// signed over that root, even when a synced node listed ahead of it fails + /// the fetch. + #[tokio::test] + async fn no_sync_committee_message_is_signed_over_a_syncing_nodes_head() { + use ethlambda_types::beacon::primitives::Root; + use tokio::sync::RwLock; + + use crate::beacon_node::dto::{SyncDutyDto, encode_hex}; + use crate::keys::ValidatorStore; + use crate::signing::SigningContext; + use crate::sync_committee::SyncCommitteeService; + + let stale = || MockBeaconNode { + syncing: true, + ..MockBeaconNode::new().with_head_root(Root::repeat_byte(9)) + }; + let failing_synced = MockBeaconNode::new().failing_call("head_block_root", "timed out"); + let context = Arc::new(SigningContext::new( + ethlambda_types::beacon::config::Config::mainnet(), + Root::ZERO, + )); + let duty = SyncDutyDto { + pubkey: encode_hex(&[1u8; 48]), + validator_index: 11, + validator_sync_committee_indices: vec![0], + }; + let store = RwLock::new(ValidatorStore::new()); + + for nodes in [vec![stale()], vec![failing_synced, stale()]] { + let beacon_node = Arc::new(fallback(nodes)); + beacon_node.probe(20, Duration::from_secs(1)).await; + let service = SyncCommitteeService::new(beacon_node.clone(), context.clone()); + let signed = service + .publish_messages(20, std::slice::from_ref(&duty), &store) + .await; + assert!( + matches!( + signed, + Ok(None) | Err(crate::error::Error::AllBeaconNodesFailed(_)) + ), + "got {signed:?}" + ); + assert!( + beacon_node + .nodes() + .iter() + .all(|node| node.submitted_sync_messages().is_empty()) + ); + } + } +} diff --git a/crates/validator/src/beacon_node/http.rs b/crates/validator/src/beacon_node/http.rs index ab30118a6..942d1e61d 100644 --- a/crates/validator/src/beacon_node/http.rs +++ b/crates/validator/src/beacon_node/http.rs @@ -46,6 +46,7 @@ use crate::beacon_node::dto::{ SyncingDto, ValidatorDetailsDto, ValidatorEntryDto, VersionedResponse, config_from_spec_response, encode_hex, parse_pubkey, parse_root, }; +use crate::beacon_node::health::SyncStatus; use crate::beacon_node::{ AggregateAttestation, AggregateKind, AttesterDuties, BeaconNodeApi, BlockRequest, Delivery, Genesis, Liveness, ProposerDuties, PtcDuties, Published, SignedAggregates, ValidatorDetails, @@ -644,29 +645,34 @@ impl BeaconNodeApi for HttpBeaconNode { } async fn is_optimistic_or_syncing(&self) -> Result { - let response: DataResponse = self.get("/eth/v1/node/syncing").await?; - let syncing = response.data.is_syncing; - let optimistic = response.data.is_optimistic.unwrap_or(false); + let status = self.sync_status().await?; // Reported rather than acted on. An execution client that has just gone // offline leaves the node with the head it validated before that, which // is still a head worth attesting to; the moment that stops being true // the node reports it as optimistic instead. - if response.data.el_offline.unwrap_or(false) { + if status.el_offline { warn!( url = %self.base_url, "Beacon node reports its execution client is offline; it will go optimistic if it \ has not already" ); } - if optimistic && !syncing { + if status.is_optimistic && !status.is_syncing { warn!( url = %self.base_url, "Beacon node has finished syncing but is tracking an unvalidated head; refusing \ to sign against it" ); } - Ok(syncing || optimistic) + Ok(!status.is_synced()) + } + + /// Logs nothing: the per-slot probe asks this every slot, and its record + /// logs a node's status only when it changes. + async fn sync_status(&self) -> Result { + let response: DataResponse = self.get("/eth/v1/node/syncing").await?; + Ok(response.data.into()) } /// Resolves each pubkey to its validator index and current status. @@ -1806,6 +1812,37 @@ mod tests { assert!(served.seen.lock().expect("lock").is_empty()); } + /// The probe's request: every field of the answer reaches the record, and + /// an absent `is_optimistic` or `el_offline` reads as `false`. + #[tokio::test] + async fn the_sync_status_carries_every_field_of_the_answer() { + let reply = br#"{"data":{"head_slot":"640","sync_distance":"12","is_syncing":true,"is_optimistic":true,"el_offline":true}}"#.to_vec(); + let served = serve(200, vec![("content-type", "application/json")], reply).await; + let status = served.node.sync_status().await.expect("decodes"); + assert_eq!( + status, + SyncStatus { + head_slot: Some(640), + sync_distance: Some(12), + is_syncing: true, + is_optimistic: true, + el_offline: true, + } + ); + assert!( + served.seen.lock().expect("lock")[0] + .0 + .ends_with("/eth/v1/node/syncing") + ); + + let reply = + br#"{"data":{"head_slot":"640","sync_distance":"0","is_syncing":false}}"#.to_vec(); + let served = serve(200, vec![("content-type", "application/json")], reply).await; + let status = served.node.sync_status().await.expect("decodes"); + assert!(status.is_synced()); + assert!(!status.el_offline); + } + #[tokio::test] async fn v2_proposer_duties_use_the_v2_path() { let reply = br#"{"dependent_root":"0x0909090909090909090909090909090909090909090909090909090909090909","execution_optimistic":false,"data":[]}"#.to_vec(); diff --git a/crates/validator/src/beacon_node/mock.rs b/crates/validator/src/beacon_node/mock.rs index 64176513c..9e46b4d0a 100644 --- a/crates/validator/src/beacon_node/mock.rs +++ b/crates/validator/src/beacon_node/mock.rs @@ -25,6 +25,7 @@ use crate::beacon_node::dto::{ AttesterDutyDto, CommitteeSubscriptionDto, ProposerDutyDto, ProposerPreparationDto, PtcDutyDto, SingleAttestationDto, SyncCommitteeSubscriptionDto, SyncDutyDto, }; +use crate::beacon_node::health::SyncStatus; use crate::beacon_node::{ AggregateAttestation, AggregateKind, AttesterDuties, BeaconNodeApi, BlockRequest, Delivery, Genesis, Liveness, ProposerDuties, PtcDuties, Published, SignedAggregates, ValidatorDetails, @@ -63,6 +64,12 @@ pub struct MockBeaconNode { /// `syncing`, because the pair a real node can report and this client must /// still refuse is exactly "synced, but optimistic". pub optimistic: bool, + /// What the node reports about its sync status once set, in place of + /// `syncing` and `optimistic`: a node whose status changes while a test + /// runs. See [`MockBeaconNode::set_sync_status`]. + pub sync_status_override: Mutex>, + /// How long `sync_status` takes before it answers, as a hung node would. + pub sync_status_delay: Option, pub validators: Vec, pub duties: Mutex>, pub proposers: Mutex>, @@ -463,6 +470,33 @@ impl MockBeaconNode { self } + /// Make `sync_status` take `delay` before it answers. + pub fn with_sync_status_delay(mut self, delay: std::time::Duration) -> Self { + self.sync_status_delay = Some(delay); + self + } + + /// Report `status` from now on, whatever `syncing` and `optimistic` say: + /// the node went optimistic, say, after a test's first probe. + pub fn set_sync_status(&self, status: SyncStatus) { + *self.sync_status_override.lock().expect("lock") = Some(status); + } + + /// What the node reports about its sync status now: the override when one + /// is set, else `syncing` and `optimistic`, with no head slot. + pub fn current_status(&self) -> SyncStatus { + self.sync_status_override + .lock() + .expect("lock") + .unwrap_or(SyncStatus { + head_slot: None, + sync_distance: None, + is_syncing: self.syncing, + is_optimistic: self.optimistic, + el_offline: false, + }) + } + /// Make `submit_proposer_preferences` take `delay` before it answers. pub fn with_preference_delay(mut self, delay: std::time::Duration) -> Self { self.preference_delay = Some(delay); @@ -830,7 +864,17 @@ impl BeaconNodeApi for MockBeaconNode { async fn is_optimistic_or_syncing(&self) -> Result { self.guard("is_syncing")?; - Ok(self.syncing || self.optimistic) + Ok(!self.current_status().is_synced()) + } + + /// Fails with `is_optimistic_or_syncing`, under the same key: both are the + /// one `/eth/v1/node/syncing` request on a real node. + async fn sync_status(&self) -> Result { + if let Some(delay) = self.sync_status_delay { + tokio::time::sleep(delay).await; + } + self.guard("is_syncing")?; + Ok(self.current_status()) } async fn validator_indices(&self, pubkeys: &[BlsPubkey]) -> Result> { @@ -1412,7 +1456,7 @@ impl BeaconNodeApi for MockBeaconNode { tokio::time::sleep(delay).await; } self.guard("liveness")?; - if self.syncing || self.optimistic { + if !self.current_status().is_synced() { return Err(Error::BeaconNodeSyncing); } let live = self.live.lock().expect("lock"); diff --git a/crates/validator/src/beacon_node/mod.rs b/crates/validator/src/beacon_node/mod.rs index 4bb58a9f5..5e05e6cb6 100644 --- a/crates/validator/src/beacon_node/mod.rs +++ b/crates/validator/src/beacon_node/mod.rs @@ -20,6 +20,7 @@ use crate::beacon_node::dto::{ AttesterDutyDto, CommitteeSubscriptionDto, ProposerDutyDto, ProposerPreparationDto, PtcDutyDto, SingleAttestationDto, SyncCommitteeSubscriptionDto, SyncDutyDto, }; +use crate::beacon_node::health::SyncStatus; use crate::error::{BeaconNodeFailure, Error, Result}; use ethlambda_types::beacon::containers::altair; use ethlambda_types::beacon::containers::electra; @@ -28,6 +29,7 @@ use ethlambda_types::beacon::containers::gloas; pub mod block_contents; pub mod dto; pub mod fallback; +pub mod health; pub mod http; #[cfg(test)] @@ -403,8 +405,20 @@ pub trait BeaconNodeApi: Send + Sync { /// [`crate::error::Error::BeaconNodeSyncing`]. That is a backstop, not the /// check: it puts correctness entirely in the node's hands for a rule the /// client is the one bound by. + /// + /// The duty loop does not call this. It reads the same two flags from the + /// probe [`health`] takes ahead of every slot, through + /// [`Self::sync_status`]. This answers the callers outside the loop: the + /// voluntary-exit command, and a node's own check before + /// [`Self::liveness`]. async fn is_optimistic_or_syncing(&self) -> Result; + /// The node's `GET /eth/v1/node/syncing` answer in full: the two flags + /// [`Self::is_optimistic_or_syncing`] reads, `el_offline`, and the head slot + /// and sync distance it reports. What [`health`]'s per-slot probe asks each + /// node. + async fn sync_status(&self) -> Result; + /// Resolves each pubkey to its current validator index and status, so the /// rest of the client can address validators by index, as the Beacon API /// does everywhere except this one lookup. @@ -668,6 +682,15 @@ pub trait BeaconNodeApi: Send + Sync { /// # Contract: the answer is for `slot`, or this is an `Err` /// /// For the reason [`Self::attestation_data`] states. + /// + /// # Not from a node whose last probe said syncing or optimistic + /// + /// The Beacon API asks for a 503 here only while a node syncs, and the + /// answer carries no `execution_optimistic`, so an optimistic node may hand + /// out data for a block its execution client has not validated. The + /// fallback therefore does not ask a node whose last [`health`] probe + /// reported syncing or optimistic, and answers `Err(BeaconNodeSyncing)` + /// when that leaves no node to ask. async fn payload_attestation_data( &self, slot: Slot, @@ -782,6 +805,14 @@ pub trait BeaconNodeApi: Send + Sync { /// execution client has not validated. Mapping it to the same error a 503 /// gets makes failover try the next node rather than hand this one's root /// to the signer. + /// + /// # Not from a node whose last probe said syncing + /// + /// A syncing node that is not optimistic answers its stale head with + /// `execution_optimistic: false`, and the Beacon API defines no 503 for this + /// endpoint. The fallback therefore does not ask a node whose last + /// [`health`] probe reported syncing or optimistic, and answers + /// `Err(BeaconNodeSyncing)` when that leaves no node to ask. async fn head_block_root(&self) -> Result; /// Submit signed sync committee messages to the node's pool. Returns how diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index 37cb83f78..e4fa2b107 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -431,6 +431,15 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { })); } + // Every beacon node's sync status, probed a sixth of a slot ahead of each + // boundary on its own clock: the duty loop reads it at the boundary and + // never waits for it. Aborted once the client stops. See + // `beacon_node::health`. + let probes = tokio::spawn(crate::beacon_node::health::run( + beacon_node.clone(), + clock.clone(), + )); + // The check runs on its own clock, three quarters into each slot, so a // slow duty never delays it and a slow liveness query never delays a // duty. Its handle is kept: the duties race it below, and it is aborted @@ -476,6 +485,16 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { let epoch = clock.epoch_of(slot); + // The slot's sync check, from the probe taken ahead of this + // boundary. A slot it withholds signs nothing and skips the epoch + // refresh, which the next slot that passes tries again. Only the + // fee recipient re-send goes on, since it signs nothing and a node + // restarted mid-sync must be prepared before its first proposal. + if !crate::beacon_node::health::slot_signs(beacon_node.health(), slot) { + preparations.after_slot(slot, &resolved, &store); + continue; + } + // What the refresh below leaves owing once the slot's block is // out: the subnet subscriptions when it moved the attester // schedule, and the builder registrations of the validators it @@ -484,8 +503,8 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { let mut to_register = None; if last_epoch != Some(epoch) { // Snapshot the pubkeys and let the guard drop right here, before - // `refresh_epoch`'s awaits (a sync check, two duties fetches, a - // validator lookup). Passing the guard itself in used to extend + // `refresh_epoch`'s awaits (two duties fetches, a validator + // lookup). Passing the guard itself in used to extend // it across that whole call, because `&*store.read().await` as a // match scrutinee has its temporary lifetime extended to the // entire match. Holding a read lock that long lets the @@ -704,11 +723,12 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { }; let stopped = run_until_stopped(duties, &protection, shutdown, keymanager).await; - // Whatever stopped the client, the check stops with it rather than - // polling the beacon node for a runtime that outlives `run`. + // Whatever stopped the client, the check and the probe stop with it rather + // than polling the beacon node for a runtime that outlives `run`. if let Some(check) = check { check.abort(); } + probes.abort(); Err(stopped) } @@ -1176,6 +1196,9 @@ struct Refreshed { /// Sends no subnet subscription and no builder registration itself: both /// need signatures, so the duty loop sends them from tasks of their own, off /// the path to the slot's block. See [`Refreshed`]. +/// +/// Asks no node whether it is syncing: the duty loop runs this only in a slot +/// its per-slot sync check passed (see [`beacon_node::health`]). async fn refresh_epoch( beacon_node: &Arc, duties: &mut DutiesService, @@ -1191,10 +1214,6 @@ async fn refresh_epoch( return Ok(Refreshed::default()); } - if beacon_node.is_optimistic_or_syncing().await? { - return Err(Error::BeaconNodeSyncing); - } - // Re-resolved every epoch, not once at startup: a validator can be // deposited but not yet activated, in which case it has no index to ask // duties for until it is. diff --git a/crates/validator/src/metrics.rs b/crates/validator/src/metrics.rs index 2b9860043..9bafa6b74 100644 --- a/crates/validator/src/metrics.rs +++ b/crates/validator/src/metrics.rs @@ -305,6 +305,18 @@ static AGGREGATION_FAILURES_TOTAL: LazyLock = LazyLock::new(|| { .unwrap() }); +/// Slots the duty loop signed nothing in, because every beacon node that +/// answered the slot's sync probe reported syncing or optimistic. See +/// `beacon_node::health`. +static SLOTS_SKIPPED_SYNCING_TOTAL: LazyLock = LazyLock::new(|| { + register_int_counter!( + "ethlambda_validator_slots_skipped_syncing_total", + "Slots with no duty signed because every beacon node that answered the slot's sync probe \ + was syncing or optimistic" + ) + .unwrap() +}); + static BEACON_NODE_AVAILABLE: LazyLock = LazyLock::new(|| { register_int_gauge!( "ethlambda_validator_beacon_node_available", @@ -485,6 +497,7 @@ pub fn init() { LazyLock::force(&AGGREGATES_PUBLISHED_TOTAL); LazyLock::force(&AGGREGATION_FAILURES_TOTAL); LazyLock::force(&FEE_RECIPIENT_MISMATCHES_TOTAL); + LazyLock::force(&SLOTS_SKIPPED_SYNCING_TOTAL); LazyLock::force(&BEACON_NODE_AVAILABLE); LazyLock::force(&SIGNING_DURATION_SECONDS); LazyLock::force(&REMOTE_SIGNER_REQUEST_DURATION_SECONDS); @@ -626,6 +639,10 @@ pub fn inc_fee_recipient_mismatches() { FEE_RECIPIENT_MISMATCHES_TOTAL.inc(); } +pub fn inc_slots_skipped_syncing() { + SLOTS_SKIPPED_SYNCING_TOTAL.inc(); +} + pub fn set_beacon_node_available(available: bool) { BEACON_NODE_AVAILABLE.set(i64::from(available)); } diff --git a/crates/validator/src/payload_attestation.rs b/crates/validator/src/payload_attestation.rs index 788422e63..dc8b0722f 100644 --- a/crates/validator/src/payload_attestation.rs +++ b/crates/validator/src/payload_attestation.rs @@ -22,6 +22,16 @@ //! nothing is signed. Voting `payload_present = false` for a block this client //! never saw would be a claim about a block it cannot name. //! +//! # Optimistic heads +//! +//! The optimistic-sync specification does not name `DOMAIN_PTC_ATTESTER`, and +//! the Beacon API asks for a 503 on the data only while a node syncs. This +//! client withholds the vote over an optimistic head anyway. The fallback does +//! not ask a node whose last sync probe reported syncing or optimistic for the +//! data (see [`crate::beacon_node::health`]), and with no node left to ask, +//! nothing is signed. A node that goes optimistic between its probe and the +//! vote is not caught here; ethlambda's own node refuses the data then. +//! //! # Duplicates //! //! The specification attaches no slashing condition to a PTC vote, but a second, @@ -41,7 +51,7 @@ use tracing::{error, info, warn}; use crate::beacon_node::BeaconNodeApi; use crate::beacon_node::dto::{PtcDutyDto, parse_pubkey}; -use crate::error::Result; +use crate::error::{Error, Result}; use crate::keys::ValidatorStore; use crate::signing::{SigningContext, sign_all}; @@ -101,9 +111,19 @@ impl PayloadAttestationService { return Ok(0); } - let Some(data) = self.beacon_node.payload_attestation_data(slot).await? else { - info!(%slot, "No block known for this slot; not voting on its payload"); - return Ok(0); + let data = match self.beacon_node.payload_attestation_data(slot).await { + Ok(Some(data)) => data, + Ok(None) => { + info!(%slot, "No block known for this slot; not voting on its payload"); + return Ok(0); + } + // Every node's last sync probe said syncing or optimistic, so none + // was asked: see "Optimistic heads" above. + Err(Error::BeaconNodeSyncing) => { + warn!(%slot, "Every beacon node is syncing or on an optimistic head; not voting on this slot's payload"); + return Ok(0); + } + Err(err) => return Err(err), }; // Checked again here, having already been checked by the diff --git a/crates/validator/src/sync_committee.rs b/crates/validator/src/sync_committee.rs index 767536b7a..f140a9f4d 100644 --- a/crates/validator/src/sync_committee.rs +++ b/crates/validator/src/sync_committee.rs @@ -22,6 +22,12 @@ //! over an optimistic head, so [`BeaconNodeApi::head_block_root`] fails with //! `BeaconNodeSyncing` for one, and nothing is signed. //! +//! A node that is syncing but not optimistic answers its stale head with +//! `execution_optimistic: false`, and the Beacon API has no 503 for it. The +//! fallback therefore does not ask a node whose last sync probe reported +//! syncing or optimistic for the head (see [`crate::beacon_node::health`]): +//! with every node in that state, the fetch answers `BeaconNodeSyncing` too. +//! //! # Duplicates //! //! Not slashable. The slot is recorded per validator at signing time only so a diff --git a/docs/cli.md b/docs/cli.md index 89a0219ac..8c78a4bcb 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -371,7 +371,7 @@ implementation's, so none of the [common flags](#common-flags) apply to it. | Flag | Default | Meaning | |---|---|---| -| `--beacon-nodes` | required | Base URLs of the beacon nodes to use, comma-separated or repeated. Tried in list order; the first that answers serves the request, so the order is a preference, not load balancing | +| `--beacon-nodes` | required | Base URLs of the beacon nodes to use, comma-separated or repeated. Every node is asked `/eth/v1/node/syncing` once a slot; the ones that answered synced and not optimistic are tried first, in list order, then the rest in list order. The first that answers serves the request, so the order is a preference, not load balancing. See [The per-slot sync check](#the-per-slot-sync-check) | | `--validators-dir` | required | Directory holding the EIP-2335 keystores and `validator_definitions.yml`, which also lists the keys a remote signer holds (see [Remote signing](#remote-signing-web3signer)). Without that file, keystores in the Lighthouse layout (`<0xpubkey>/voting-keystore.json`, password in `--secrets-dir/<0xpubkey>`) are discovered and the file is written | | `--secrets-dir` | required | Directory holding one password file per keystore, named after the validator's public key | | `--http-address` | `127.0.0.1` | Bind address for the metrics and keymanager servers | @@ -501,7 +501,9 @@ epoch's lookahead. When an epoch's schedule could not be fetched, the client asks again after each slot's duties until it has one. A member sleeps until `PAYLOAD_ATTESTATION_DUE_BPS` of the slot, asks the node for the payload attestation data, signs it under the PTC domain and submits it. A `204` -(the node knows no block for the slot) means no vote. So a gloas slot runs in +(the node knows no block for the slot) means no vote, and so does a node whose +last sync probe said syncing or optimistic: the data is not asked of it, so +no vote is cast over an optimistic head. So a gloas slot runs in this order: propose at the boundary, attest at `ATTESTATION_DUE_BPS_GLOAS`, aggregate at `AGGREGATE_DUE_BPS_GLOAS`, then the committee vote. The attestation and the committee vote are each bounded by the end of the slot. @@ -514,7 +516,9 @@ until the period's end, so the node joins the subnets. The next period's are added once its boundary is within four epochs. A member sleeps until `SYNC_MESSAGE_DUE_BPS` (`SYNC_MESSAGE_DUE_BPS_GLOAS` from gloas), reads `/eth/v1/beacon/blocks/head/root`, signs it and submits one message per -validator. It refuses to sign when the node reports the head optimistic. A +validator. It refuses to sign when the node reports the head optimistic, and +never reads the head from a node whose last sync probe said syncing or +optimistic, since a syncing node answers its stale head with no flag set. A member selected by the selection-proof hash for a subnet then waits for `CONTRIBUTION_DUE_BPS` (`CONTRIBUTION_DUE_BPS_GLOAS`), fetches the node's contribution for that subnet and publishes it wrapped and signed. A subnet whose @@ -526,6 +530,53 @@ slot. Voluntary exits are signed by the keymanager API's `voluntary_exit` route and by [`ethlambda voluntary-exit`](#voluntary-exit). +### The per-slot sync check + +A validator must not sign against a beacon node that is syncing, whose head is +not the network's, or one whose head is optimistic (its execution client has +not validated the payload): the optimistic-sync specification says an +optimistic validator must not propose, attest or take part in sync +committees. So every slot the client asks every configured node +`GET /eth/v1/node/syncing`, all at once, a sixth of a slot before the slot's +boundary: 2 s on 12 s slots, as Lighthouse does. That is after the previous +slot's last duty and leaves a healthy node time to answer, so the duty loop +reads the answers at the boundary and never waits for one. A node gets until +the next slot's probe to answer. + +- **A slot signs nothing when every node that answered is syncing or + optimistic**, and at least one answered: no block, attestation, aggregate, + sync committee message, contribution or payload timeliness vote. The epoch's + duty refresh, the proposer preferences poll and the builder registration + re-sends are skipped with the slot, and a refresh that was due runs at the + next slot that passes. The fee recipient re-send still goes out, since it + signs nothing and a node restarted while syncing must be prepared before its + first proposal. Each skipped slot is logged at warn and counted on + `ethlambda_validator_slots_skipped_syncing_total`, also by a client with no + keys loaded. +- **A node that did not answer does not count as syncing.** Its duty endpoints + still answer `503` while it syncs, which the client reads as a node to fail + over from. So nodes that cannot be reached never stop the duties by + themselves, and only the probe taken for the slot counts: a late answer, or + one from an earlier slot, opens the check rather than holding it shut. +- **Requests go to the nodes that passed first**, then the rest, each group + in `--beacon-nodes` order. A blinded block still goes back to the node that + produced it. +- **The head root and the payload attestation data are never asked of a node + whose last probe said syncing or optimistic**, even after the nodes that + passed have failed the request. Neither endpoint has a `503` for that state: + a syncing node answers its stale head, and an optimistic one hands out + payload data for a block its execution client has not validated. +- **`el_offline` is logged, not acted on**: a node whose execution client has + just gone offline still has the head it validated before, and reports itself + optimistic once that stops being true. A node's change of state (synced, + syncing, optimistic, no answer, `el_offline`) is logged once, when it + changes. +- **There is no clock-based rule.** The client never skips duties because the + head looks old by its own clock: during a network-wide stall every head is + old, and clients that stop signing then keep the chain stalled. Only the + node's own `is_syncing` and `is_optimistic` count. `head_slot` and + `sync_distance` are recorded, not acted on. + ### Doppelganger protection Off unless `--enable-doppelganger-protection` is passed. A doppelganger is a diff --git a/docs/metrics.md b/docs/metrics.md index 481c3bcb7..99fc8f157 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -922,9 +922,9 @@ and absent is not the same as zero. | `ethlambda_validator_envelopes_published_total` | Counter | Execution payload envelopes a beacon node accepted for blocks this client proposed (gloas) | | `ethlambda_validator_envelope_failures_total` | Counter | Proposed gloas blocks whose self-built envelope was not published. The block is out and the proposal counts as made, but the slot's payload is withheld, so this is the failure that costs the payload. Should read zero | | `ethlambda_validator_payload_attestations_published_total` | Counter | Payload timeliness committee votes a beacon node accepted (gloas) | -| `ethlambda_validator_payload_attestation_failures_total` | Counter | Slots whose payload timeliness committee duty did not result in published votes | +| `ethlambda_validator_payload_attestation_failures_total` | Counter | Slots whose payload timeliness committee duty did not result in published votes. A vote withheld because every node's last sync probe said syncing or optimistic is not counted | | `ethlambda_validator_sync_committee_messages_published_total` | Counter | Sync committee messages a beacon node accepted | -| `ethlambda_validator_sync_committee_failures_total` | Counter | Slots whose sync committee message duty ended in an error or ran past its slot. A head the node reports optimistic is not a failure: nothing is signed | +| `ethlambda_validator_sync_committee_failures_total` | Counter | Slots whose sync committee message duty ended in an error or ran past its slot. A head the node reports optimistic, or every node's last sync probe saying syncing or optimistic, is not a failure: nothing is signed | | `ethlambda_validator_sync_contributions_published_total` | Counter | Sync committee contributions this client published as an aggregator. Bursty, like `aggregates_published_total` | | `ethlambda_validator_sync_contribution_failures_total` | Counter | Sync aggregation duties that ended in an error or ran past their slot. A subnet with no contribution to fetch is skipped and not counted | | `ethlambda_validator_sync_duties_held` | Gauge | Sync committee duties held for the current period | @@ -941,7 +941,8 @@ and absent is not the same as zero. | `ethlambda_validator_blinded_blocks_proposed_total` | Counter | Blinded blocks a beacon node handed to its builder. A subset of `blocks_proposed_total` | | `ethlambda_validator_blinded_blocks_unconfirmed_total` | Counter | Blinded blocks the beacon node did not confirm (a 5xx other than 503, or no answer once connected), which the relay may still have published. Not retried, since a second block for the slot would be an equivocation | | `ethlambda_validator_block_publication_delay_seconds` | Histogram | Slot start to block accepted. Its buckets are tighter than the attestation histogram's, because a block is due at the slot boundary rather than a third of the way in | -| `ethlambda_validator_beacon_node_available` | Gauge | 1 when a beacon node answered the last duty refresh or attestation | +| `ethlambda_validator_slots_skipped_syncing_total` | Counter | Slots in which nothing was signed because every beacon node that answered the slot's sync probe (`/eth/v1/node/syncing`, a sixth of a slot before the boundary) reported syncing or optimistic. Should read zero once the nodes are synced; a steady climb is a node that stays syncing or on an optimistic head, usually because its execution client is behind. Nodes that did not answer are not counted against the slot, so this stays flat while every node is down. See [The per-slot sync check](./cli.md#the-per-slot-sync-check) | +| `ethlambda_validator_beacon_node_available` | Gauge | 1 when a beacon node answered the last duty refresh or attestation. 0 after a slot the sync check withheld, until the next refresh succeeds | | `ethlambda_validator_signing_duration_seconds` | Histogram | Time a duty waited for its batch of signatures. With local keys that is the signing itself. With keys in a remote signer it is the batch's slowest answer, round trip and verification included, and at most the 2 s signing budget, so a sample in the top bucket means a signer that did not answer in time | | `ethlambda_validator_remote_signer_request_duration_seconds` | Histogram | Time one signing request to a remote signer took, from sending it to its answer or failure, not counting the wait for one of the signer's 64 request slots. The number to watch for a slow signer; empty when every key is local | | `ethlambda_validator_slashing_protection_write_seconds` | Histogram | Time to durably write the slashing-protection record, once per slot's attestation batch and once per block, before signing. Milliseconds on a local disk; worth an alert above about a second, since the duty waits for it and a write held past 3 s is refused | diff --git a/docs/spec_deviations.md b/docs/spec_deviations.md index 3d40775c8..2ce8553a3 100644 --- a/docs/spec_deviations.md +++ b/docs/spec_deviations.md @@ -919,6 +919,27 @@ comes first. The validator client signs once, at the deadline reads, and refuses to when that root is optimistic (`specs/bellatrix/optimistic-sync.md`). +## The validator client withholds payload timeliness votes over an optimistic head + +- **Specification:** `specs/bellatrix/optimistic-sync.md` says an optimistic + validator must not produce a block, attest, or take part in sync + committees. It does not name `DOMAIN_PTC_ATTESTER`, and the Beacon API asks + for a `503` on `GET /eth/v1/validator/payload_attestation_data` only while a + node is syncing. Its answer carries no `execution_optimistic`. +- **ethlambda:** the validator client asks every configured beacon node + `/eth/v1/node/syncing` once a slot, a sixth of a slot before the boundary + (`crates/validator/src/beacon_node/health.rs`). It does not ask a node whose + last probe reported syncing or optimistic for payload attestation data, and + casts no vote when no node is left to ask. A slot in which every node that + answered reported syncing or optimistic signs nothing at all, this vote + included. +- **Why:** the vote is signed over the block's root and says whether its + payload arrived, which a node tracking an unvalidated payload is in no + position to say. ethlambda's own beacon node already refuses the data for an + optimistic block (`require_validated` in `crates/net/rpc/src/beacon/ptc.rs`), + so this matters against other implementations. A node that turns optimistic + between its probe and the vote is not caught by the client. + ## The validator client's builder proposals With `--builder-proposals` the validator client registers its validators with From a65fcaf09516b3d41e6ab3665f57bdeecf978a59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:02:21 -0300 Subject: [PATCH 02/12] fix(validator): keep a slot open for a synced node still answering its probe A synced node whose sync probe had not come back by the boundary counted as not answering, so one fast syncing answer withheld the slot while routing still ranked that node synced. A node still on the slot before's synced answer now holds the gate open. The probe task's end is logged: it loops for the client's life, so it ends only by panicking, and the duties then go on unchecked. The el_offline change logs compare against the last probe that answered, so a failed probe in between neither hides the execution client coming back nor reports it going offline twice. --- crates/validator/src/beacon_node/health.rs | 80 ++++++++++++++++++++-- crates/validator/src/lib.rs | 25 ++++++- docs/cli.md | 5 +- 3 files changed, 101 insertions(+), 9 deletions(-) diff --git a/crates/validator/src/beacon_node/health.rs b/crates/validator/src/beacon_node/health.rs index 509d6cf9c..90576428d 100644 --- a/crates/validator/src/beacon_node/health.rs +++ b/crates/validator/src/beacon_node/health.rs @@ -21,7 +21,9 @@ //! while its node syncs still covers it, so nodes that cannot be reached //! never stop duties on their own. Only the probe taken for the slot counts, //! so a late answer, or a probe task that stopped, opens the gate rather than -//! holding it shut. +//! holding it shut. A node whose answer is still on its way at the boundary, +//! and that answered synced the slot before, holds the gate open too, so a +//! slow synced node does not lose the slot to a fast syncing one. //! - **Routing** ([`NodeHealth::ranked`]). The fallback asks the nodes whose //! last probe passed (neither syncing nor optimistic) first, in command-line //! order, then the rest, in the same order. Positions stay command-line @@ -41,6 +43,7 @@ //! the record, not acted on. A record older than two slots is no longer read for //! routing, which only ever moves a node back to plain command-line order. +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, OnceLock, PoisonError, RwLock}; use std::time::{Duration, SystemTime}; @@ -153,6 +156,9 @@ pub struct SyncVerdict { pub synced: usize, pub syncing: usize, pub optimistic: usize, + /// Nodes whose probe for the slot had not come back when it was read, and + /// that answered synced for the slot before. Not counted as answering. + pub awaited_synced: usize, } impl SyncVerdict { @@ -171,9 +177,10 @@ impl SyncVerdict { } /// Whether duties may be signed: some node answered synced, or no node - /// answered at all, which leaves each duty to its endpoint's 503. + /// answered at all, which leaves each duty to its endpoint's 503, or a + /// node that was synced a slot ago has not answered yet. pub fn signs(&self) -> bool { - self.answered == 0 || self.synced > 0 + self.answered == 0 || self.synced > 0 || self.awaited_synced > 0 } } @@ -184,6 +191,10 @@ impl SyncVerdict { /// the latter. pub struct NodeHealth { probes: RwLock>>, + /// Whether each node's last probe that answered reported its execution + /// client offline. A probe with no answer leaves it as it was, so the + /// change logs compare one answer with the last. + el_offline: Vec, /// How long a probe is read for routing. Unset until [`run`] starts, so a /// fallback that is never probed on a schedule (a test, the voluntary-exit /// command) reads whatever it holds. @@ -194,6 +205,7 @@ impl NodeHealth { pub fn new(nodes: usize) -> Self { Self { probes: RwLock::new(vec![None; nodes]), + el_offline: (0..nodes).map(|_| AtomicBool::new(false)).collect(), read_for: OnceLock::new(), } } @@ -255,14 +267,19 @@ impl NodeHealth { Standing::Synced | Standing::Unknown => {} } } - let was_el_offline = previous.as_ref().is_some_and(is_el_offline); + // Against the last probe that answered, so a failed probe in between + // neither hides the execution client coming back nor repeats it going. + if standing == Standing::NoAnswer { + return; + } + let was_el_offline = self.el_offline[position].swap(el_offline, Ordering::Relaxed); if el_offline && !was_el_offline { warn!( position, "Beacon node reports its execution client is offline; it will go optimistic if it \ has not already" ); - } else if was_el_offline && !el_offline && standing != Standing::NoAnswer { + } else if was_el_offline && !el_offline { info!(position, "Beacon node reports its execution client is back"); } } @@ -293,11 +310,18 @@ impl NodeHealth { } /// How the probes taken for `slot` split. A node whose last probe was taken - /// for another slot did not answer this one. + /// for another slot did not answer this one; one still on the slot before's + /// synced answer is counted apart, as awaited. pub fn verdict(&self, slot: Slot) -> SyncVerdict { let probes = self.read(); let for_slot = probes.iter().flatten().filter(|probe| probe.slot == slot); - SyncVerdict::tally(for_slot.map(Probe::standing)) + let mut verdict = SyncVerdict::tally(for_slot.map(Probe::standing)); + verdict.awaited_synced = probes + .iter() + .flatten() + .filter(|probe| probe.slot + 1 == slot && probe.standing() == Standing::Synced) + .count(); + verdict } /// The records are plain values with no invariant between them, so one a @@ -476,6 +500,25 @@ mod tests { assert!(!verdict.signs()); } + /// A synced node whose answer for the slot is still on its way holds the + /// slot open against a fast syncing one. Once its answer is in, or its + /// probe failed, the slot's own answers decide. + #[test] + fn a_synced_node_still_answering_holds_the_slot_open() { + let nodes = NodeHealth::new(2); + nodes.record(0, synced(9)); + nodes.record(1, syncing(10)); + let verdict = nodes.verdict(10); + assert_eq!((verdict.answered, verdict.awaited_synced), (1, 1)); + assert!(verdict.signs()); + + nodes.record(0, down(10)); + assert!(!nodes.verdict(10).signs(), "its probe failed"); + + let older = health(vec![synced(8), syncing(10)]); + assert!(!older.verdict(10).signs(), "synced two slots ago only"); + } + #[test] fn the_gate_counts_each_kind_of_answer() { let slot = 4; @@ -487,6 +530,7 @@ mod tests { synced: 0, syncing: 1, optimistic: 1, + awaited_synced: 0, } ); assert!(!slot_signs(&health, slot)); @@ -556,6 +600,28 @@ mod tests { assert_eq!(later, vec![(0, Standing::Unknown), (1, Standing::Unknown)]); } + /// A probe with no answer leaves the execution client's last reported + /// state as it was, so the next answer is compared with the one before it. + #[test] + fn a_failed_probe_leaves_the_execution_clients_state() { + let el_offline = |slot| { + probe( + slot, + Ok(SyncStatus { + el_offline: true, + ..status(false, false) + }), + ) + }; + let nodes = NodeHealth::new(1); + let held = |nodes: &NodeHealth| nodes.el_offline[0].load(Ordering::Relaxed); + nodes.record(0, el_offline(3)); + nodes.record(0, down(4)); + assert!(held(&nodes), "no answer, nothing changed"); + nodes.record(0, synced(5)); + assert!(!held(&nodes)); + } + /// The snapshot is every node's last probe, in command-line order, with /// what the node said about its head. #[test] diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index e4fa2b107..82446527d 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -435,10 +435,33 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { // boundary on its own clock: the duty loop reads it at the boundary and // never waits for it. Aborted once the client stops. See // `beacon_node::health`. + // + // It loops for the life of the client, so it ends only by panicking. The + // duties then go on as before the check existed (every slot signs, and + // requests walk the nodes in command-line order), which is logged here + // rather than left to pass unnoticed. let probes = tokio::spawn(crate::beacon_node::health::run( beacon_node.clone(), clock.clone(), )); + let stop_probes = probes.abort_handle(); + tokio::spawn(async move { + let ended = probes.await; + if !ended + .as_ref() + .is_err_and(tokio::task::JoinError::is_cancelled) + { + let reason = match ended { + Err(err) => err.to_string(), + Ok(()) => "its task returned".to_string(), + }; + error!( + %reason, + "The beacon node sync probe stopped; no slot is withheld for a syncing node from \ + now on, until the validator client is restarted" + ); + } + }); // The check runs on its own clock, three quarters into each slot, so a // slow duty never delays it and a slow liveness query never delays a @@ -728,7 +751,7 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { if let Some(check) = check { check.abort(); } - probes.abort(); + stop_probes.abort(); Err(stopped) } diff --git a/docs/cli.md b/docs/cli.md index 8c78a4bcb..5ccde17f0 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -557,7 +557,10 @@ the next slot's probe to answer. still answer `503` while it syncs, which the client reads as a node to fail over from. So nodes that cannot be reached never stop the duties by themselves, and only the probe taken for the slot counts: a late answer, or - one from an earlier slot, opens the check rather than holding it shut. + one from an earlier slot, opens the check rather than holding it shut. A + node whose answer is still on its way at the boundary, and that answered + synced the slot before, holds the check open too, so a slow synced node does + not lose the slot to a fast syncing one. - **Requests go to the nodes that passed first**, then the rest, each group in `--beacon-nodes` order. A blinded block still goes back to the node that produced it. From 3c95556c50c502a4fcaa4d0ab29ef90cdb4d8ac6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:43:26 -0300 Subject: [PATCH 03/12] fix(validator): ask the ungated calls only of a node whose probe answered synced The head root and the payload attestation data have no 503 behind them, yet a node whose sync probe failed was still asked for them: a syncing node with a slow or broken /node/syncing could hand out its stale head, or an optimistic one its unvalidated payload data, for this client to sign. For those two calls a node must have answered its last probe synced, or have no probe to read (a fallback no probe task runs for). With no node left to ask the answer stays BeaconNodeSyncing, which the sync committee and PTC services read as "do not sign". --- CLAUDE.md | 2 +- crates/validator/src/beacon_node/fallback.rs | 45 +++++++++++++------- crates/validator/src/beacon_node/health.rs | 14 +++++- docs/cli.md | 11 +++-- 4 files changed, 49 insertions(+), 23 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 25c893a9a..5142e0250 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -948,7 +948,7 @@ transitions are in `ethlambda-types`, per the section above. Nothing above count, so the duty endpoints' 503 stays the backstop); requests try the nodes that passed first, then the rest, each in `--beacon-nodes` order; and the head root and PTC data are never asked of - a node whose last probe said syncing or optimistic. No rule reads the head's + a node whose last probe said syncing or optimistic, or got no answer. No rule reads the head's age off the client's clock. It keeps EIP-3076 minimal-watermark slashing protection in `--validators-dir/slashing_protection.json` (`crate::slashing_protection`), diff --git a/crates/validator/src/beacon_node/fallback.rs b/crates/validator/src/beacon_node/fallback.rs index 0c68b28c7..414dc3999 100644 --- a/crates/validator/src/beacon_node/fallback.rs +++ b/crates/validator/src/beacon_node/fallback.rs @@ -48,8 +48,9 @@ enum Reach { /// Every node. Every, /// Every node but those whose last sync probe reported syncing or - /// optimistic, for the calls the Beacon API gives no 503 for in that state. - /// A node that did not answer its probe is still asked. + /// optimistic, or got no answer, for the calls the Beacon API gives no 503 + /// for in that state. A node with no probe to read is still asked (see + /// [`Standing::may_serve_ungated`]). SkipUnsynced, } @@ -149,11 +150,11 @@ impl FallbackBeaconNode { } /// [`Self::try_each`] without the nodes whose last sync probe reported - /// syncing or optimistic, for a call whose endpoint answers such a node - /// with no 503 and data this client must not sign. A node that did not - /// answer its probe is still asked. When no node is left to ask, this is - /// `Err(BeaconNodeSyncing)`, which the callers read as "do not sign" rather - /// than as a failure. + /// syncing or optimistic, or got no answer, for a call whose endpoint + /// answers such a node with no 503 and data this client must not sign. A + /// node with no probe to read is still asked. When no node is left to ask, + /// this is `Err(BeaconNodeSyncing)`, which the callers read as "do not + /// sign" rather than as a failure. async fn try_each_synced<'p, T, F>(&'p self, what: &'static str, call: F) -> Result where F: Fn(&'p B) -> BoxFuture<'p, Result>, @@ -195,8 +196,8 @@ impl FallbackBeaconNode { let Some(node) = self.nodes.get(position) else { continue; }; - if reach == Reach::SkipUnsynced && standing.is_unsynced() { - debug!(%what, position, ?standing, "Not asking a beacon node whose last sync probe said it is unsynced"); + if reach == Reach::SkipUnsynced && !standing.may_serve_ungated() { + debug!(%what, position, ?standing, "Not asking a beacon node whose last sync probe did not answer synced"); continue; } asked = true; @@ -212,8 +213,8 @@ impl FallbackBeaconNode { } } } - // Every node said, at its last probe, that it is one this client must - // not sign against: an answer, not a failure. + // No node vouched, at its last probe, for being one this client may + // sign against: an answer, not a failure. if reach == Reach::SkipUnsynced && !asked { return Err(Error::BeaconNodeSyncing); } @@ -1752,15 +1753,27 @@ mod tests { assert_eq!(fallback.nodes[0].payload_attestation_data_call_count(), 0); } - /// A node whose probe failed is not known to be unsynced, and is asked. + /// A node whose probe failed vouches for nothing, and nothing stops a + /// syncing node's stale head root, so it is not asked either. A node with + /// no probe at all, in a fallback no probe task runs for, still is. #[tokio::test] - async fn a_node_that_did_not_answer_its_probe_is_still_asked_for_a_head_root() { - let unprobed = answering(3).failing_call("is_syncing", "down"); - let fallback = FallbackBeaconNode::new(vec![unprobed]); + async fn a_node_that_did_not_answer_its_probe_is_not_asked_for_a_head_root() { + let unanswered = answering(3).failing_call("is_syncing", "down"); + let fallback = FallbackBeaconNode::new(vec![unanswered]); fallback.probe(96, std::time::Duration::from_secs(1)).await; + let err = fallback.head_block_root().await.expect_err("no root"); + assert!(matches!(err, Error::BeaconNodeSyncing), "got {err:?}"); + let err = fallback + .payload_attestation_data(96) + .await + .expect_err("no data"); + assert!(matches!(err, Error::BeaconNodeSyncing), "got {err:?}"); + assert_eq!(fallback.nodes[0].payload_attestation_data_call_count(), 0); + + let never_probed = FallbackBeaconNode::new(vec![answering(3)]); assert_eq!( - fallback.head_block_root().await.expect("a root"), + never_probed.head_block_root().await.expect("a root"), Root::repeat_byte(3) ); } diff --git a/crates/validator/src/beacon_node/health.rs b/crates/validator/src/beacon_node/health.rs index 90576428d..70037de6c 100644 --- a/crates/validator/src/beacon_node/health.rs +++ b/crates/validator/src/beacon_node/health.rs @@ -31,8 +31,10 @@ //! - **Two calls the Beacon API leaves ungated.** No 503 covers a syncing //! node's head root, or an optimistic node's payload attestation data, so the //! fallback does not ask a node whose last probe reported syncing or -//! optimistic for either. Without that, a passed node failing either call -//! would hand it to the next node in the walk, which may be that one. +//! optimistic, or got no answer, for either. Without that, a passed node +//! failing either call would hand it to the next node in the walk, which may +//! be that one. Unlike the gate, a node that did not answer is not given the +//! benefit of the doubt here: no 503 stands behind it. //! //! # No clock-based rule //! @@ -145,6 +147,14 @@ impl Standing { pub fn is_unsynced(self) -> bool { matches!(self, Self::Syncing | Self::Optimistic) } + + /// Whether a call the Beacon API gives no 503 for in an unsynced state may + /// go to the node: its probe answered synced, or there is no probe to + /// read, as in a fallback no probe task runs for. A probe that failed + /// vouches for nothing, and nothing else would stop the answer. + pub fn may_serve_ungated(self) -> bool { + matches!(self, Self::Synced | Self::Unknown) + } } /// How the nodes that answered one round of probes split. diff --git a/docs/cli.md b/docs/cli.md index 5ccde17f0..db05eaf13 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -565,10 +565,13 @@ the next slot's probe to answer. in `--beacon-nodes` order. A blinded block still goes back to the node that produced it. - **The head root and the payload attestation data are never asked of a node - whose last probe said syncing or optimistic**, even after the nodes that - passed have failed the request. Neither endpoint has a `503` for that state: - a syncing node answers its stale head, and an optimistic one hands out - payload data for a block its execution client has not validated. + whose last probe said syncing or optimistic, or got no answer**, even after + the nodes that passed have failed the request. Neither endpoint has a `503` + for that state: a syncing node answers its stale head, and an optimistic one + hands out payload data for a block its execution client has not validated. + So here, unlike for the slot's check, a node that did not answer is not + given the benefit of the doubt. With no node left to ask, the sync committee + message and the payload vote are not signed. - **`el_offline` is logged, not acted on**: a node whose execution client has just gone offline still has the head it validated before, and reports itself optimistic once that stops being true. A node's change of state (synced, From cded59039944f69f2dc71f7153895947445bf388 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:15:22 -0300 Subject: [PATCH 04/12] feat(validator): rank beacon nodes by health and broadcast signed messages Requests walk the beacon nodes by tier, best first: synced and validated; optimistic or with the execution client offline; syncing or more than 8 slots behind by sync_distance; not probed yet; failing. Command-line order breaks ties, so one healthy node, or several, are asked as listed. A request that times out or cannot connect ranks its node failing until a later probe answers, so a hung node costs one request timeout per probe rather than one per request. `nodes` stays in command-line order, so a Producer still names the node that built a blinded block. `--broadcast attestations,blocks,sync-committee` sends those signed messages to every node at once, succeeding when any accepts. Nodes ranked failing are sent a broadcast only when no other node took it. A block reports the best answer (200 over 202 over refused). An envelope goes to its block's producer first, then the rest, or to the producer alone when sent without its blobs. A blinded block stays on its producer. None is broadcast by default. --- CLAUDE.md | 15 +- README.md | 2 +- bin/ethlambda/src/validator.rs | 50 +- crates/validator/src/beacon_node/fallback.rs | 936 ++++++++++++++++++- crates/validator/src/beacon_node/health.rs | 537 +++++++++-- crates/validator/src/beacon_node/mock.rs | 53 ++ crates/validator/src/beacon_node/mod.rs | 18 + crates/validator/src/lib.rs | 5 +- crates/validator/src/proposal.rs | 15 +- docs/cli.md | 87 +- 10 files changed, 1560 insertions(+), 158 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 5142e0250..fb7808e30 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -945,11 +945,16 @@ transitions are in `ethlambda-types`, per the section above. Nothing above in `NodeHealth`, shared by the fallback): a slot in which every node that answered is syncing or optimistic signs nothing and skips the epoch refresh, only the fee recipient re-send going on (a node that did not answer does not - count, so the duty endpoints' 503 stays the backstop); requests try the - nodes that passed first, then the rest, each - in `--beacon-nodes` order; and the head root and PTC data are never asked of - a node whose last probe said syncing or optimistic, or got no answer. No rule reads the head's - age off the client's clock. + count, so the duty endpoints' 503 stays the backstop); requests walk the + nodes by `health::Tier` (synced; optimistic or `el_offline`; syncing or + `sync_distance` > 8; unprobed; failing), `--beacon-nodes` order breaking + ties, and a request that timed out or could not connect ranks its node + failing until a later probe answers; and the head root and PTC data are + never asked of a node whose last probe said syncing or optimistic, or got + no answer. No rule that stops a duty reads the head's age. `--broadcast` + (`fallback::Broadcast`) sends attestations, blocks (envelopes producer + first) or sync committee messages to every node, failing-ranked nodes only + if none accepted. It keeps EIP-3076 minimal-watermark slashing protection in `--validators-dir/slashing_protection.json` (`crate::slashing_protection`), durable before every block (blinded ones included) and attestation signature; diff --git a/README.md b/README.md index c57b41e14..ffefa9de4 100644 --- a/README.md +++ b/README.md @@ -358,7 +358,7 @@ beacon node. | Flag | Meaning | |---|---| -| `--beacon-nodes` | Base URLs of the beacon nodes to use, comma-separated or repeated. Each is asked whether it is syncing once a slot; the ones that said synced are tried first, then the rest, each in the order given, so the order is a preference. A slot in which every node that answered is syncing or on an optimistic head signs nothing | +| `--beacon-nodes` | Base URLs of the beacon nodes to use, comma-separated or repeated. Each is asked whether it is syncing once a slot and ranked by the answer (synced, then optimistic or with its execution client offline, then syncing or more than 8 slots behind, then failing), the order given breaking ties, so the order is a preference. A slot in which every node that answered is syncing or on an optimistic head signs nothing. `--broadcast` sends chosen signed messages to every node | | `--validators-dir` | Directory of EIP-2335 keystores and `validator_definitions.yml`. Without that file, keystores in the Lighthouse layout (`<0xpubkey>/voting-keystore.json`) are discovered and the file is written | | `--secrets-dir` | One password file per keystore, named after the validator's public key | | `--suggested-fee-recipient` | Execution address for block rewards, `0x`-prefixed. Optional, but without it the beacon node picks an address that is not yours | diff --git a/bin/ethlambda/src/validator.rs b/bin/ethlambda/src/validator.rs index 5fadee669..3da046958 100644 --- a/bin/ethlambda/src/validator.rs +++ b/bin/ethlambda/src/validator.rs @@ -6,6 +6,7 @@ use std::path::PathBuf; use ethlambda_types::beacon::primitives::{Bytes32, ExecutionAddress, H160}; +use ethlambda_validator::beacon_node::fallback::BroadcastTopic; use ethlambda_validator::proposer_settings::{ DEFAULT_GAS_LIMIT, GRAFFITI_BYTES, graffiti_from_text, }; @@ -20,13 +21,23 @@ pub(crate) struct ValidatorOptions { /// Base URL(s) of the beacon node's HTTP API (e.g. http://localhost:5052). /// /// Several may be supplied, comma-separated or by repeating the flag. Each - /// is asked whether it is syncing once a slot; the ones that are not are - /// tried first, then the rest, each in the order given, and the first that - /// answers is used, so the order is a preference, not a load-balancing - /// policy. + /// is asked whether it is syncing once a slot and ranked by the answer + /// (synced, then optimistic or with its execution client offline, then + /// syncing or more than 8 slots behind, then failing), the order given + /// breaking ties, and the first that answers is used, so the order is a + /// preference, not a load-balancing policy. #[arg(long, value_delimiter = ',', required = true)] pub(crate) beacon_nodes: Vec, + /// Signed messages to send to every beacon node at once rather than to + /// the first that accepts them, comma-separated: `attestations` + /// (attestations, aggregates, payload attestations), `blocks` (blocks + /// and envelopes; never a blinded block), `sync-committee` (messages and + /// contributions), `subscriptions` (always sent to every node, accepted + /// for Lighthouse compatibility). None by default. + #[arg(long, value_delimiter = ',')] + pub(crate) broadcast: Vec, + /// Directory holding the EIP-2335 keystores and `validator_definitions.yml`. /// Without that file, keystores in the Lighthouse layout /// (`<0xpubkey>/voting-keystore.json`, password in @@ -285,6 +296,7 @@ pub(crate) async fn run(options: ValidatorOptions) -> eyre::Result<()> { builder_min_bid: options.builder_min_bid, init_slashing_protection: options.init_slashing_protection, doppelganger_protection: options.enable_doppelganger_protection, + broadcast: options.broadcast.into_iter().collect(), }) .await .map_err(Into::into) @@ -297,6 +309,7 @@ mod tests { fn options(graffiti: &str) -> ValidatorOptions { ValidatorOptions { beacon_nodes: vec!["http://localhost:5052".to_string()], + broadcast: Vec::new(), validators_dir: PathBuf::from("/tmp/validators"), secrets_dir: PathBuf::from("/tmp/secrets"), http_address: "127.0.0.1".parse().expect("valid address"), @@ -367,6 +380,35 @@ mod tests { assert!(options.enable_doppelganger_protection); } + /// Nothing is broadcast unless asked for, as in Lighthouse; topics are + /// comma-separated or repeated, and an unknown one is refused at startup. + #[test] + fn broadcast_topics_are_off_unless_named() { + use ethlambda_validator::beacon_node::fallback::Broadcast; + + let topics = + |options: ValidatorOptions| -> Broadcast { options.broadcast.into_iter().collect() }; + assert_eq!(topics(parse(&[]).expect("parses")), Broadcast::default()); + let options = parse(&[ + "--broadcast", + "attestations,blocks", + "--broadcast", + "sync-committee", + ]) + .expect("parses"); + assert_eq!( + topics(options), + Broadcast { + attestations: true, + blocks: true, + sync_committee: true, + } + ); + let options = parse(&["--broadcast", "subscriptions"]).expect("parses"); + assert_eq!(topics(options), Broadcast::default()); + parse(&["--broadcast", "everything"]).expect_err("not a topic"); + } + #[test] fn builder_proposals_default_to_a_factor_of_100() { let options = parse(&["--builder-proposals"]).expect("parses"); diff --git a/crates/validator/src/beacon_node/fallback.rs b/crates/validator/src/beacon_node/fallback.rs index 414dc3999..f65a68098 100644 --- a/crates/validator/src/beacon_node/fallback.rs +++ b/crates/validator/src/beacon_node/fallback.rs @@ -1,11 +1,35 @@ -//! Ordered failover across several beacon nodes. +//! Ranked failover across several beacon nodes. //! -//! First healthy wins. The nodes whose last sync probe passed (neither syncing -//! nor optimistic, see [`super::health`]) are tried first, in the order given on -//! the command line, then the rest in the same order. Deliberately no finer -//! than passed or not: Lighthouse ranks its nodes by sync distance, optimistic -//! status and `el_offline`, and tie-breaks on list order, which is better, and -//! is a refinement this does not need yet. +//! # Queries: the best-ranked node that answers +//! +//! A request walks the nodes in [`NodeHealth::ranked`]'s order and returns the +//! first answer. The order is [`Tier`]'s, as Lighthouse ranks its nodes: synced +//! and validated first; then synced but optimistic, or with the execution +//! client offline; then syncing, or more than [`super::health::SYNC_TOLERANCE`] +//! slots behind by the node's own `sync_distance`; then nodes not probed yet; +//! then failing ones. Command-line order breaks ties, so a single healthy node, +//! or several equally healthy ones, are asked exactly as listed. The probe that +//! feeds it runs once a slot ([`super::health::run`]), and a request that times +//! out or cannot connect ranks its node failing at once, until a later probe +//! answers ([`NodeHealth::record_request_failure`]): a hung node costs one +//! request timeout per probe, not one per request. +//! +//! The nodes themselves stay in command-line order, and only a list of +//! positions is ranked, so a [`Producer`] still names the node that produced a +//! blinded block. +//! +//! # Signed messages: one node, or every node with `--broadcast` +//! +//! By default a signed message goes to the first node in the walk that accepts +//! it, as a query does. [`Broadcast`] sends a chosen kind to every node at +//! once instead, succeeding when any accepts, so it reaches the network through +//! every node's gossip mesh rather than one. A node ranked failing is sent it +//! only when none of the others accepted, so a hung node does not hold back +//! the answer. Subscriptions and the other state installed on a node +//! ([`FallbackBeaconNode::try_all`]) go to every node whatever the flag says, +//! and a blinded block only ever goes back to its producer. Every message is +//! signed once, before it reaches this module, so slashing protection records +//! it once however many nodes are sent it. use std::future::Future; use std::pin::Pin; @@ -27,7 +51,7 @@ use crate::beacon_node::dto::{ CommitteeSubscriptionDto, ProposerPreparationDto, SingleAttestationDto, SyncCommitteeSubscriptionDto, SyncDutyDto, }; -use crate::beacon_node::health::{NodeHealth, Probe, Standing, SyncStatus, SyncVerdict}; +use crate::beacon_node::health::{NodeHealth, Probe, Standing, SyncStatus, SyncVerdict, Tier}; use crate::beacon_node::{ AggregateAttestation, AttesterDuties, BeaconNodeApi, BlockRequest, Delivery, Genesis, Liveness, ProposerDuties, PtcDuties, Published, SignedAggregates, ValidatorDetails, ValidatorEntry, @@ -54,22 +78,108 @@ enum Reach { SkipUnsynced, } -/// A `BeaconNodeApi` backed by an ordered list of others, answering from the -/// first one that succeeds. +/// One kind of signed message `--broadcast` can send to every node. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum BroadcastTopic { + /// Attestations, aggregates and payload attestations. + Attestations, + /// Blocks and execution payload envelopes. Never a blinded block, which + /// goes back to its producer alone. + Blocks, + /// Sync committee messages and contributions. + SyncCommittee, + /// Committee and sync committee subscriptions, fee recipient preparations, + /// builder registrations and proposer preferences. Always sent to every + /// node, so naming it changes nothing; accepted as Lighthouse's flag + /// accepts it. + Subscriptions, +} + +impl BroadcastTopic { + /// Every topic, by the name the command line takes. + pub const NAMES: [(&'static str, Self); 4] = [ + ("attestations", Self::Attestations), + ("blocks", Self::Blocks), + ("sync-committee", Self::SyncCommittee), + ("subscriptions", Self::Subscriptions), + ]; +} + +impl std::str::FromStr for BroadcastTopic { + type Err = String; + + fn from_str(name: &str) -> std::result::Result { + Self::NAMES + .iter() + .find(|(known, _)| *known == name) + .map(|(_, topic)| *topic) + .ok_or_else(|| { + let known: Vec<&str> = Self::NAMES.iter().map(|(known, _)| *known).collect(); + format!( + "unknown broadcast topic {name:?}; expected one of {}", + known.join(", ") + ) + }) + } +} + +/// Which signed messages go to every node at once, rather than to the first +/// node in the walk that accepts them. All off by default, as Lighthouse's +/// `--broadcast` defaults to subscriptions alone, which always go to every +/// node here. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Broadcast { + pub attestations: bool, + pub blocks: bool, + pub sync_committee: bool, +} + +impl FromIterator for Broadcast { + fn from_iter>(topics: I) -> Self { + let mut broadcast = Self::default(); + for topic in topics { + match topic { + BroadcastTopic::Attestations => broadcast.attestations = true, + BroadcastTopic::Blocks => broadcast.blocks = true, + BroadcastTopic::SyncCommittee => broadcast.sync_committee = true, + BroadcastTopic::Subscriptions => {} + } + } + broadcast + } +} + +/// A `BeaconNodeApi` backed by a list of others, answering from the +/// best-ranked one that succeeds. pub struct FallbackBeaconNode { /// In the order given, which never changes: a [`Producer`] is a position - /// in it, so a blinded block goes back to the node that produced it. + /// in it, so a blinded block goes back to the node that produced it. Only + /// the walk's list of positions is ranked. nodes: Vec, - /// Each node's last sync probe, by the same positions. What orders the - /// walk, and what the duty loop gates each slot on. + /// Each node's last sync probe and unanswered request, by the same + /// positions. What orders the walk, and what the duty loop gates each slot + /// on. health: Arc, + /// The signed messages sent to every node rather than to one. + broadcast: Broadcast, } impl FallbackBeaconNode { pub fn new(nodes: Vec) -> Self { assert!(!nodes.is_empty(), "at least one beacon node is required"); let health = Arc::new(NodeHealth::new(nodes.len())); - Self { nodes, health } + Self { + nodes, + health, + broadcast: Broadcast::default(), + } + } + + /// Send the signed messages `broadcast` names to every node. See the + /// module doc. + pub fn with_broadcast(mut self, broadcast: Broadcast) -> Self { + self.broadcast = broadcast; + self } /// Each node's last sync probe. Shared, so whatever reports on the nodes @@ -108,9 +218,10 @@ impl FallbackBeaconNode { /// Try each node in order, returning the first success. /// - /// The order is [`NodeHealth::ranked`]'s: the nodes whose last sync probe - /// passed first, then the rest, each in command-line order. With no probe - /// held it is the command-line order. + /// The order is [`NodeHealth::ranked`]'s: by [`Tier`], command-line order + /// breaking ties. With no probe held and no request failed it is the + /// command-line order. A node that times out or cannot be connected to is + /// recorded as such, which ranks it last until its next probe answers. /// /// "Success" means the node returned `Ok`, nothing more. That is the right /// rule only where an `Ok` is an answer this client can act on, which is @@ -207,8 +318,10 @@ impl FallbackBeaconNode { // Debug, not warn: with more than one node configured, an // outage on one of them fires this every slot for as long // as it lasts. The event that actually means the client - // missed a duty is every node failing, below. + // missed a duty is every node failing, below. A node that + // stopped answering is warned about once, by the record. debug!(%what, position, %err, "Beacon node request failed; trying the next"); + self.health.record_request_failure(position, what, &err); last = Some(err); } } @@ -320,6 +433,7 @@ impl FallbackBeaconNode { } else { debug!(%what, position, %err, node_effect, "Beacon node did not accept"); } + self.health.record_request_failure(position, what, &err); last = Some(err); } } @@ -341,6 +455,151 @@ impl FallbackBeaconNode { } Err(Error::AllBeaconNodesFailed(detail)) } + + /// Send a signed message to every node at once, for `--broadcast`, and + /// hand back each node's answer by its command-line position. + /// + /// Every node not ranked [`Tier::Failing`] is sent it together, and the + /// call waits for all of them. The failing ones are sent it only when none + /// of the others accepted: a node that timed out on the last request or + /// probe would otherwise hold every broadcast back by a request timeout, + /// past a proposal's deadline, while a node that accepted has already put + /// the message on the network. `sent` is a position the caller has + /// already sent to itself, left out here, and whether it accepted, which + /// counts as an acceptance for that rule. + /// + /// Each answer that says the node stopped answering is recorded, as the + /// walk records it. What each answer means is the caller's to read. + async fn broadcast_to_all<'p, T, F>( + &'p self, + what: &'static str, + sent: Option<(usize, bool)>, + call: F, + ) -> Vec<(usize, Result)> + where + F: Fn(&'p B) -> BoxFuture<'p, Result>, + { + let skip = sent.map(|(position, _)| position); + let accepted_already = sent.is_some_and(|(_, accepted)| accepted); + let (failing, first): (Vec<_>, Vec<_>) = self + .health + .tiers() + .into_iter() + .filter(|(position, _)| Some(*position) != skip) + .partition(|(_, tier)| *tier == Tier::Failing); + let mut answers = self.send_to(what, first, &call).await; + if !accepted_already && !answers.iter().any(|(_, answer)| answer.is_ok()) { + answers.extend(self.send_to(what, failing, &call).await); + } + answers + } + + /// Send to the nodes at `positions` at once and record each node that did + /// not answer. + async fn send_to<'p, T, F>( + &'p self, + what: &'static str, + positions: Vec<(usize, Tier)>, + call: &F, + ) -> Vec<(usize, Result)> + where + F: Fn(&'p B) -> BoxFuture<'p, Result>, + { + let sends = positions.into_iter().filter_map(|(position, _)| { + let send = call(self.nodes.get(position)?); + Some(async move { (position, send.await) }) + }); + let answers = futures_util::future::join_all(sends).await; + for (position, answer) in &answers { + if let Err(err) = answer { + self.health.record_request_failure(*position, what, err); + } + } + answers + } + + /// A broadcast's answers read as one: the best accepted answer by + /// `better`, or every node failing. A node that refused while another + /// accepted is logged at `debug!`, since a node down for a while would + /// otherwise warn on every message; none accepting is warned about as + /// [`Self::try_each`] warns about it. + fn best_answer( + what: &'static str, + answers: Vec<(usize, Result)>, + better: impl Fn(&T, &T) -> bool, + ) -> Result { + let mut best: Option = None; + let mut refusals = Vec::new(); + for (position, answer) in answers { + match answer { + Ok(value) => { + if best.as_ref().is_none_or(|held| better(&value, held)) { + best = Some(value); + } + } + Err(err) => refusals.push((position, err)), + } + } + if let Some(best) = best { + for (position, err) in refusals { + debug!(%what, position, %err, "Beacon node did not accept a broadcast another node accepted"); + } + return Ok(best); + } + let detail = refusals + .pop() + .map(|(_, err)| err.to_string()) + .unwrap_or_else(|| "no nodes configured".to_string()); + warn!(%what, %detail, "All configured beacon nodes failed; duty likely missed"); + Err(Error::AllBeaconNodesFailed(detail)) + } + + /// A count of accepted entries, sent to every node under `--broadcast` and + /// to the first that accepts otherwise. Under broadcast the answer is the + /// most any node accepted: each of those reached the network through that + /// node at least. + async fn send_counted<'p, F>( + &'p self, + what: &'static str, + broadcast: bool, + call: F, + ) -> Result + where + F: Fn(&'p B) -> BoxFuture<'p, Result>, + { + if !broadcast { + return self.try_each(what, call).await; + } + let answers = self.broadcast_to_all(what, None, call).await; + Self::best_answer(what, answers, |count, held| count > held) + } + + /// [`Self::send_counted`] for a message whose acceptance is all a node + /// says about it. + async fn send_signed<'p, F>( + &'p self, + what: &'static str, + broadcast: bool, + call: F, + ) -> Result<()> + where + F: Fn(&'p B) -> BoxFuture<'p, Result<()>>, + { + if !broadcast { + return self.try_each(what, call).await; + } + let answers = self.broadcast_to_all(what, None, call).await; + Self::best_answer(what, answers, |_, _| false) + } +} + +/// How good a block publish's answer is, for picking a broadcast's best: a node +/// that imported the block over one that only broadcast it. +fn publish_rank(published: Published) -> u8 { + match published { + Published::Imported | Published::HandedToBuilder => 2, + Published::BroadcastNotImported => 1, + } } #[async_trait] @@ -453,25 +712,54 @@ impl BeaconNodeApi for FallbackBeaconNode { Ok(block) } - /// First node that accepts it wins, rather than a broadcast to every node. + /// First node in the walk that accepts it wins, unless `--broadcast blocks` + /// sends it to every node. /// - /// Publishing is the one call where that choice is not obvious, because - /// sending to every node would reach more of the network's gossip mesh at - /// once. It stays first-wins for now because a node that accepts a block - /// gossips it, so the second node would receive it over the network in any - /// case, and because a broadcast makes the outcome ambiguous: with three - /// nodes answering 200, 202 and a timeout, there is no single answer to - /// report. + /// First-wins by default because a node that accepts a block gossips it, + /// so the other nodes receive it over the network in any case. A broadcast + /// reaches more of the network's gossip mesh at once, which is what gets a + /// block from a node with few peers out in time. /// /// A 202 counts as success and stops the walk. The node could not import /// the block, but it did broadcast it, so the network has it and offering /// it to another node would not change that. + /// + /// Under broadcast the answer is the best any node gave: imported (200) + /// over broadcast but not imported (202), either over a refusal, so a + /// proposal is reported clean when some node imported it. Each node's + /// answer is logged, a refusal at `warn!`, since a proposal is rare and a + /// node refusing one is worth seeing. Only when no node accepted is this + /// an error. async fn publish_block(&self, fork: ForkName, body: &[u8]) -> Result { - self.try_each("publish_block", |node| node.publish_block(fork, body)) - .await + let what = "publish_block"; + if !self.broadcast.blocks { + return self + .try_each(what, |node| node.publish_block(fork, body)) + .await; + } + let answers = self + .broadcast_to_all(what, None, |node| node.publish_block(fork, body)) + .await; + let accepted = answers.iter().any(|(_, answer)| answer.is_ok()); + for (position, answer) in &answers { + match answer { + Ok(published) => debug!(%what, position, ?published, "Beacon node took the block"), + Err(err) if accepted => warn!( + %what, + position, + %err, + "Beacon node did not take the block; another node did" + ), + Err(_) => {} + } + } + Self::best_answer(what, answers, |published, held| { + publish_rank(*published) > publish_rank(*held) + }) } - /// Only on the node that produced the block, with no failover. + /// Only on the node that produced the block, with no failover, whatever + /// `--broadcast` says. /// /// Unlike [`Self::publish_block`], offering the block to another node /// would not reach the network: only the producing node's builder holds @@ -504,6 +792,13 @@ impl BeaconNodeApi for FallbackBeaconNode { // The node behind this one is a single node, with nothing to choose. node.publish_blinded_block(Producer::default(), fork, body) .await + .inspect_err(|err| { + self.health.record_request_failure( + producer.position(), + "publish_blinded_block", + err, + ); + }) } /// To every node, like the other calls that install state on a node: a @@ -644,7 +939,9 @@ impl BeaconNodeApi for FallbackBeaconNode { } /// First node that accepts it wins, for the reason [`Self::publish_block`] - /// is: the accepting node gossips it. + /// is: the accepting node gossips it. Never broadcast: with no producer + /// named there is no node to send it to first (see + /// [`Self::publish_execution_payload_envelope_produced_by`]). async fn publish_execution_payload_envelope( &self, body: &[u8], @@ -656,6 +953,67 @@ impl BeaconNodeApi for FallbackBeaconNode { .await } + /// Without `--broadcast blocks`, [`Self::publish_execution_payload_envelope`]: + /// the first node in the walk that accepts it. + /// + /// With it, the producer first, then every other node. The producer is + /// the one node certain to hold the block the envelope reveals (it built + /// it, and imported it on publish), so its answer comes first and puts + /// the envelope on the network. The others are sent it once the producer + /// has answered: a node that has not imported the block yet queues or + /// drops its envelope, and each has had the block a round trip longer by + /// then. It succeeds when any node accepted. + /// + /// Two exceptions. A body without its blobs (`blob_data_included: false`) + /// goes to the producer alone, whatever its rank, since only it cached + /// them at production time. And for a body with them, a producer ranked + /// failing (it did not answer a request since its last probe, the block's + /// own publish perhaps) is not waited on first: it is one of the failing + /// nodes the broadcast reaches only if no other node accepts. + async fn publish_execution_payload_envelope_produced_by( + &self, + producer: Producer, + body: &[u8], + blob_data_included: bool, + ) -> Result<()> { + let what = "publish_execution_payload_envelope"; + if !self.broadcast.blocks { + return self + .publish_execution_payload_envelope(body, blob_data_included) + .await; + } + let position = producer.position(); + let node = self.nodes.get(position).ok_or_else(|| { + Error::InconsistentResponse(format!( + "an envelope names beacon node {position} as its producer, but {} are configured", + self.nodes.len() + )) + })?; + let producer_failing = self.health.tiers().contains(&(position, Tier::Failing)); + + let mut answers = Vec::new(); + let mut sent = None; + if !producer_failing || !blob_data_included { + let answer = node + .publish_execution_payload_envelope(body, blob_data_included) + .await; + if let Err(err) = &answer { + self.health.record_request_failure(position, what, err); + } + sent = Some((position, answer.is_ok())); + answers.push((position, answer)); + } + if blob_data_included { + let rest = self + .broadcast_to_all(what, sent, |node| { + node.publish_execution_payload_envelope(body, blob_data_included) + }) + .await; + answers.extend(rest); + } + Self::best_answer(what, answers, |_, _| false) + } + async fn ptc_duties(&self, epoch: Epoch, indices: &[ValidatorIndex]) -> Result { self.try_each("ptc_duties", |node| node.ptc_duties(epoch, indices)) .await @@ -678,22 +1036,26 @@ impl BeaconNodeApi for FallbackBeaconNode { .await } + /// To every node with `--broadcast attestations`, the most any accepted. async fn submit_payload_attestations( &self, messages: &[gloas::PayloadAttestationMessage], ) -> Result { - self.try_each("submit_payload_attestations", |node| { - node.submit_payload_attestations(messages) - }) + self.send_counted( + "submit_payload_attestations", + self.broadcast.attestations, + |node| node.submit_payload_attestations(messages), + ) .await } + /// To every node with `--broadcast attestations`, the most any accepted. async fn submit_attestations( &self, attestations: &[SingleAttestationDto], fork_name: &str, ) -> Result { - self.try_each("submit_attestations", |node| { + self.send_counted("submit_attestations", self.broadcast.attestations, |node| { node.submit_attestations(attestations, fork_name) }) .await @@ -714,12 +1076,13 @@ impl BeaconNodeApi for FallbackBeaconNode { .await } + /// To every node with `--broadcast attestations`. async fn publish_aggregates( &self, fork: ForkName, aggregates: &SignedAggregates, ) -> Result<()> { - self.try_each("publish_aggregates", |node| { + self.send_signed("publish_aggregates", self.broadcast.attestations, |node| { node.publish_aggregates(fork, aggregates) }) .await @@ -786,13 +1149,16 @@ impl BeaconNodeApi for FallbackBeaconNode { .await } + /// To every node with `--broadcast sync-committee`, the most any accepted. async fn submit_sync_committee_messages( &self, messages: &[altair::SyncCommitteeMessage], ) -> Result { - self.try_each("submit_sync_committee_messages", |node| { - node.submit_sync_committee_messages(messages) - }) + self.send_counted( + "submit_sync_committee_messages", + self.broadcast.sync_committee, + |node| node.submit_sync_committee_messages(messages), + ) .await } @@ -810,13 +1176,16 @@ impl BeaconNodeApi for FallbackBeaconNode { .await } + /// To every node with `--broadcast sync-committee`. async fn publish_contribution_and_proofs( &self, contributions: &[altair::SignedContributionAndProof], ) -> Result<()> { - self.try_each("publish_contribution_and_proofs", |node| { - node.publish_contribution_and_proofs(contributions) - }) + self.send_signed( + "publish_contribution_and_proofs", + self.broadcast.sync_committee, + |node| node.publish_contribution_and_proofs(contributions), + ) .await } @@ -2003,6 +2372,491 @@ mod tests { } } + /// Every `--broadcast` topic on. + fn every_topic() -> Broadcast { + Broadcast { + attestations: true, + blocks: true, + sync_committee: true, + } + } + + /// The request timeout an HTTP node fails a hung request after. + const TIMEOUT: std::time::Duration = std::time::Duration::from_secs(8); + + /// The issue's first test: a node that takes every request and never + /// answers, listed first, with a healthy node second. Once the first probe + /// has found it silent, attestation data comes from the second at once, + /// slot after slot, and the hung node is not asked again until it answers + /// a probe. + #[tokio::test(start_paused = true)] + async fn a_hung_first_node_is_not_asked_once_a_probe_finds_it_silent() { + use std::time::Duration; + let hung = MockBeaconNode::new() + .with_attestation_data(96) + .with_hang(TIMEOUT); + let fallback = + FallbackBeaconNode::new(vec![hung, MockBeaconNode::new().with_attestation_data(96)]); + fallback.probe(96, Duration::from_secs(2)).await; + + for _ in 0..3 { + let started = tokio::time::Instant::now(); + fallback + .attestation_data(96, fork_of(96)) + .await + .expect("the second node answers"); + assert!( + started.elapsed() < Duration::from_secs(1), + "within the slot" + ); + } + assert_eq!(fallback.nodes[0].hung_calls_to("attestation_data"), 0); + assert_eq!(fallback.nodes[1].attestation_data_call_count(), 3); + + // It answers its next probe, and is first again. + fallback.nodes[0].set_hang(None); + fallback.probe(97, Duration::from_secs(2)).await; + fallback + .attestation_data(96, fork_of(96)) + .await + .expect("the first node answers"); + assert_eq!(fallback.nodes[0].attestation_data_call_count(), 1); + assert_eq!(fallback.nodes[1].attestation_data_call_count(), 3); + } + + /// Before any probe has found it, a hung node costs one request timeout: + /// the request that timed out ranks it last at once, so the next request + /// goes straight to the healthy node, and so does every one after it until + /// the hung node answers a probe. A probe it does not answer keeps it last. + #[tokio::test(start_paused = true)] + async fn a_request_that_timed_out_ranks_its_node_last_until_a_probe_answers() { + use std::time::Duration; + let hung = MockBeaconNode::new() + .with_attestation_data(96) + .with_hang(TIMEOUT); + let fallback = + FallbackBeaconNode::new(vec![hung, MockBeaconNode::new().with_attestation_data(96)]); + + let started = tokio::time::Instant::now(); + fallback + .attestation_data(96, fork_of(96)) + .await + .expect("the second node answers after the first timed out"); + assert!(started.elapsed() >= TIMEOUT); + assert_eq!(fallback.nodes[0].hung_calls_to("attestation_data"), 1); + + let started = tokio::time::Instant::now(); + fallback + .attestation_data(96, fork_of(96)) + .await + .expect("the second node answers"); + assert!(started.elapsed() < Duration::from_secs(1)); + assert_eq!(fallback.nodes[0].hung_calls_to("attestation_data"), 1); + + fallback.probe(97, Duration::from_secs(2)).await; + fallback + .attestation_data(96, fork_of(96)) + .await + .expect("the second node answers"); + assert_eq!(fallback.nodes[0].hung_calls_to("attestation_data"), 1); + + fallback.nodes[0].set_hang(None); + fallback.probe(98, Duration::from_secs(2)).await; + fallback + .attestation_data(96, fork_of(96)) + .await + .expect("the first node answers"); + assert_eq!(fallback.nodes[0].attestation_data_call_count(), 1); + assert_eq!(fallback.nodes[1].attestation_data_call_count(), 3); + } + + /// A node that reports itself not syncing but further behind its clock + /// than the tolerance is asked after a synced node listed behind it; one + /// within the tolerance keeps its place. + #[tokio::test] + async fn a_node_behind_by_its_sync_distance_is_asked_after_a_synced_one() { + for (sync_distance, first_asked) in + [(crate::beacon_node::health::SYNC_TOLERANCE + 1, 1), (5, 0)] + { + let lagging = MockBeaconNode::new().with_attestation_data(96); + lagging.set_sync_status(SyncStatus { + head_slot: Some(96 - sync_distance), + sync_distance: Some(sync_distance), + is_syncing: false, + is_optimistic: false, + el_offline: false, + }); + let fallback = FallbackBeaconNode::new(vec![ + lagging, + MockBeaconNode::new().with_attestation_data(96), + ]); + fallback.probe(96, std::time::Duration::from_secs(1)).await; + + fallback + .attestation_data(96, fork_of(96)) + .await + .expect("attestation data"); + assert_eq!( + fallback.nodes[first_asked].attestation_data_call_count(), + 1, + "sync distance {sync_distance}" + ); + assert_eq!( + fallback.nodes[1 - first_asked].attestation_data_call_count(), + 0, + "sync distance {sync_distance}" + ); + } + } + + /// Two nodes that both answered synced are asked in the order listed. + #[tokio::test] + async fn two_healthy_nodes_are_asked_in_command_line_order() { + let fallback = FallbackBeaconNode::new(vec![answering(1), answering(2)]); + fallback.probe(96, std::time::Duration::from_secs(1)).await; + + fallback + .attestation_data(96, fork_of(96)) + .await + .expect("attestation data"); + assert_eq!( + fallback.head_block_root().await.expect("a head"), + Root::repeat_byte(1) + ); + assert_eq!(fallback.nodes[0].attestation_data_call_count(), 1); + assert_eq!(fallback.nodes[1].attestation_data_call_count(), 0); + } + + /// The issue's blinded-block test: a node ranked first but listed second + /// produces the block, which goes back to position 1, under `--broadcast + /// blocks` too. + #[tokio::test] + async fn a_blinded_block_ranked_first_but_listed_second_goes_back_to_position_one() { + let lagging = blinded_node(); + lagging.set_sync_status(SyncStatus { + head_slot: Some(1), + sync_distance: Some(40), + is_syncing: false, + is_optimistic: false, + el_offline: false, + }); + let fallback = + FallbackBeaconNode::new(vec![lagging, blinded_node()]).with_broadcast(every_topic()); + fallback.probe(5, std::time::Duration::from_secs(1)).await; + assert_eq!(fallback.health().tiers()[0], (1, Tier::Synced)); + + let produced = fallback + .produce_block(&blinded_request(5, 7)) + .await + .expect("node 1 produces"); + assert_eq!(produced.producer, Producer::at(1)); + fallback + .publish_blinded_block(produced.producer, ForkName::Electra, &[4]) + .await + .expect("published"); + assert!( + fallback.nodes[0] + .published_blinded + .lock() + .expect("lock") + .is_empty() + ); + assert_eq!( + *fallback.nodes[1].published_blinded.lock().expect("lock"), + vec![(ForkName::Electra, vec![4])] + ); + } + + /// The issue's broadcast test: answers of 202, a timeout and 200 report + /// the 200, wherever it is in the list, and every node that answered got + /// the same body. The node that timed out is ranked failing from then on, + /// so the next broadcast does not wait for it. + #[tokio::test(start_paused = true)] + async fn a_broadcast_block_answered_202_a_timeout_and_200_reports_the_200() { + use std::time::Duration; + let fallback = FallbackBeaconNode::new(vec![ + MockBeaconNode::new().with_publish_outcome(Published::BroadcastNotImported), + MockBeaconNode::new().with_hang(TIMEOUT), + MockBeaconNode::new(), + ]) + .with_broadcast(Broadcast { + blocks: true, + ..Broadcast::default() + }); + + let outcome = fallback + .publish_block(ForkName::Electra, b"body") + .await + .expect("two nodes took it"); + assert_eq!(outcome, Published::Imported); + for position in [0, 2] { + assert_eq!( + fallback.nodes[position].published_blocks(), + vec![(ForkName::Electra, b"body".to_vec())], + "node {position}" + ); + } + assert_eq!(fallback.nodes[1].hung_calls_to("publish_block"), 1); + + let started = tokio::time::Instant::now(); + fallback + .publish_block(ForkName::Electra, b"next") + .await + .expect("two nodes took it"); + assert!(started.elapsed() < Duration::from_secs(1)); + assert_eq!(fallback.nodes[1].hung_calls_to("publish_block"), 1); + } + + /// A 202 is still a block on the network, so it is the answer when no node + /// imported; no node taking it at all is every node failing. + #[tokio::test] + async fn a_broadcast_block_no_node_imported_is_a_202_and_none_taking_it_an_error() { + let blocks = Broadcast { + blocks: true, + ..Broadcast::default() + }; + let fallback = FallbackBeaconNode::new(vec![ + MockBeaconNode::failing("down"), + MockBeaconNode::new().with_publish_outcome(Published::BroadcastNotImported), + ]) + .with_broadcast(blocks); + let outcome = fallback + .publish_block(ForkName::Electra, b"body") + .await + .expect("one node took it"); + assert_eq!(outcome, Published::BroadcastNotImported); + + let down = FallbackBeaconNode::new(vec![ + MockBeaconNode::failing("down"), + MockBeaconNode::failing("also down"), + ]) + .with_broadcast(blocks); + let err = down + .publish_block(ForkName::Electra, b"body") + .await + .expect_err("no node took it"); + assert!(matches!(err, Error::AllBeaconNodesFailed(_)), "got {err:?}"); + } + + fn single_attestation(attester_index: ValidatorIndex) -> SingleAttestationDto { + let data = MockBeaconNode::new() + .with_attestation_data(96) + .attestation_data + .expect("set"); + SingleAttestationDto { + committee_index: 0, + attester_index, + data: crate::beacon_node::dto::AttestationDataOutDto::from(&data), + signature: crate::beacon_node::dto::encode_hex(&[7u8; 96]), + } + } + + fn payload_vote() -> gloas::PayloadAttestationMessage { + gloas::PayloadAttestationMessage { + validator_index: 3, + data: gloas::PayloadAttestationData { + beacon_block_root: Root::repeat_byte(1), + slot: 96, + payload_present: true, + blob_data_available: true, + }, + signature: Default::default(), + } + } + + /// `--broadcast attestations` sends attestations, aggregates and payload + /// votes to every node, the same signed message to each, and succeeds + /// past a node that refused. Without it the first node takes them alone. + #[tokio::test] + async fn broadcast_attestations_reach_every_node() { + let nodes = || { + vec![ + MockBeaconNode::new(), + MockBeaconNode::failing("down"), + MockBeaconNode::new(), + ] + }; + let fallback = FallbackBeaconNode::new(nodes()).with_broadcast(Broadcast { + attestations: true, + ..Broadcast::default() + }); + let accepted = fallback + .submit_attestations(&[single_attestation(11)], "electra") + .await + .expect("two nodes took it"); + assert_eq!(accepted, 1); + fallback + .publish_aggregates(ForkName::Electra, &SignedAggregates::Electra(Vec::new())) + .await + .expect("two nodes took it"); + fallback + .submit_payload_attestations(&[payload_vote()]) + .await + .expect("two nodes took it"); + for position in [0, 2] { + let node = &fallback.nodes[position]; + let submitted = node.submitted(); + assert_eq!(submitted.len(), 1, "node {position}"); + assert_eq!(submitted[0].attester_index, 11); + assert_eq!(submitted[0].signature, single_attestation(11).signature); + assert_eq!(node.published_aggregates().len(), 1, "node {position}"); + assert_eq!(node.submitted_payload_attestations(), vec![payload_vote()]); + } + + let one_node = FallbackBeaconNode::new(nodes()); + one_node + .submit_attestations(&[single_attestation(11)], "electra") + .await + .expect("the first node takes it"); + assert_eq!(one_node.nodes[0].submitted().len(), 1); + assert!(one_node.nodes[2].submitted().is_empty()); + } + + /// `--broadcast sync-committee` sends messages and contributions to every + /// node. + #[tokio::test] + async fn broadcast_sync_committee_messages_reach_every_node() { + let fallback = FallbackBeaconNode::new(vec![MockBeaconNode::new(), MockBeaconNode::new()]) + .with_broadcast(Broadcast { + sync_committee: true, + ..Broadcast::default() + }); + let message = altair::SyncCommitteeMessage { + slot: 96, + beacon_block_root: Root::repeat_byte(2), + validator_index: 5, + signature: Default::default(), + }; + let accepted = fallback + .submit_sync_committee_messages(std::slice::from_ref(&message)) + .await + .expect("both took it"); + assert_eq!(accepted, 1); + fallback + .publish_contribution_and_proofs(&[]) + .await + .expect("both took it"); + for node in &fallback.nodes { + assert_eq!(node.submitted_sync_messages(), vec![message.clone()]); + } + } + + /// A node ranked failing is sent a broadcast only when no other node + /// took it: here the only other node is down, so the one that timed out + /// last time, and answers now, is asked after it. + #[tokio::test(start_paused = true)] + async fn a_failing_node_is_sent_a_broadcast_when_no_other_node_takes_it() { + let fallback = FallbackBeaconNode::new(vec![ + MockBeaconNode::new().with_hang(TIMEOUT), + MockBeaconNode::failing("down"), + ]) + .with_broadcast(every_topic()); + + let err = fallback + .submit_attestations(&[single_attestation(11)], "electra") + .await + .expect_err("neither took it"); + assert!(matches!(err, Error::AllBeaconNodesFailed(_)), "got {err:?}"); + assert_eq!(fallback.health().tiers()[1], (0, Tier::Failing)); + + fallback.nodes[0].set_hang(None); + let accepted = fallback + .submit_attestations(&[single_attestation(11)], "electra") + .await + .expect("the failing node takes it once the other refused"); + assert_eq!(accepted, 1); + assert_eq!(fallback.nodes[0].submitted().len(), 1); + } + + /// Under `--broadcast blocks` an envelope goes to the node that produced + /// its block first, and to the rest only once that node has answered. One + /// without its blobs goes to the producer alone, since only it cached + /// them. Without the flag, it is the first node in the walk that takes it, + /// as before. + #[tokio::test] + async fn a_broadcast_envelope_goes_to_its_producer_first_then_to_the_rest() { + let gate = Arc::new(tokio::sync::Semaphore::new(0)); + let producer = MockBeaconNode::new().with_envelope_publish_gate(gate.clone()); + let blocks = Broadcast { + blocks: true, + ..Broadcast::default() + }; + let fallback = Arc::new( + FallbackBeaconNode::new(vec![MockBeaconNode::new(), producer, MockBeaconNode::new()]) + .with_broadcast(blocks), + ); + + let publish = tokio::spawn({ + let fallback = fallback.clone(); + async move { + fallback + .publish_execution_payload_envelope_produced_by( + Producer::at(1), + b"envelope", + true, + ) + .await + } + }); + fallback.nodes[1].envelope_publish_entered.notified().await; + assert!(fallback.nodes[0].published_envelopes().is_empty()); + assert!(fallback.nodes[2].published_envelopes().is_empty()); + gate.add_permits(1); + publish.await.expect("the publish ends").expect("published"); + for node in fallback.nodes.iter() { + assert_eq!( + node.published_envelopes(), + vec![(b"envelope".to_vec(), true)] + ); + } + + let bare = FallbackBeaconNode::new(vec![MockBeaconNode::new(), MockBeaconNode::new()]) + .with_broadcast(blocks); + bare.publish_execution_payload_envelope_produced_by(Producer::at(1), b"bare", false) + .await + .expect("published"); + assert!(bare.nodes[0].published_envelopes().is_empty()); + assert_eq!( + bare.nodes[1].published_envelopes(), + vec![(b"bare".to_vec(), false)] + ); + + let one_node = FallbackBeaconNode::new(vec![MockBeaconNode::new(), MockBeaconNode::new()]); + one_node + .publish_execution_payload_envelope_produced_by(Producer::at(1), b"walked", true) + .await + .expect("published"); + assert_eq!(one_node.nodes[0].published_envelopes().len(), 1); + assert!(one_node.nodes[1].published_envelopes().is_empty()); + } + + /// Doppelganger protection's liveness query asks every node at once and + /// takes the first answer, so the ranking does not decide who answers: a + /// node ranked failing for a timed-out request still answers it. + #[tokio::test(start_paused = true)] + async fn liveness_is_answered_whatever_the_ranking() { + let seeing = MockBeaconNode::new() + .with_attestation_data(96) + .with_hang(TIMEOUT); + seeing.live.lock().expect("lock").push((12, 7)); + let fallback = FallbackBeaconNode::new(vec![seeing, MockBeaconNode::failing("down")]); + fallback + .attestation_data(96, fork_of(96)) + .await + .expect_err("neither answers"); + assert_eq!(fallback.health().tiers()[1], (0, Tier::Failing)); + + fallback.nodes[0].set_hang(None); + let answers = fallback.liveness(&[12], &[7]).await.expect("answers"); + assert_eq!( + answers, + vec![vec![Liveness { + index: 7, + is_live: true + }]] + ); + } + /// `count` registrations with distinct keys. Unsigned: no mock checks. fn registrations( count: usize, diff --git a/crates/validator/src/beacon_node/health.rs b/crates/validator/src/beacon_node/health.rs index 70037de6c..69e0bfbff 100644 --- a/crates/validator/src/beacon_node/health.rs +++ b/crates/validator/src/beacon_node/health.rs @@ -24,10 +24,18 @@ //! holding it shut. A node whose answer is still on its way at the boundary, //! and that answered synced the slot before, holds the gate open too, so a //! slow synced node does not lose the slot to a fast syncing one. -//! - **Routing** ([`NodeHealth::ranked`]). The fallback asks the nodes whose -//! last probe passed (neither syncing nor optimistic) first, in command-line -//! order, then the rest, in the same order. Positions stay command-line -//! positions, so a blinded block still goes back to the node that produced it. +//! - **Routing** ([`NodeHealth::ranked`]). The fallback asks the nodes in +//! [`Tier`] order, best first: synced and validated; synced but optimistic +//! or with its execution client offline; syncing, or more than +//! [`SYNC_TOLERANCE`] slots behind by its own `sync_distance`; not probed +//! yet; failing. Command-line order breaks ties, so a single healthy node, +//! or several equally healthy ones, are asked exactly as listed. Positions +//! stay command-line positions, so a blinded block still goes back to the +//! node that produced it. +//! - **The last real request** ([`NodeHealth::record_request_failure`]). A +//! request to a node that timed out or could not connect ranks it failing +//! until a probe recorded after it answers, so a node that hangs costs at +//! most one request timeout per probe, not one per request. //! - **Two calls the Beacon API leaves ungated.** No 503 covers a syncing //! node's head root, or an optimistic node's payload attestation data, so the //! fallback does not ask a node whose last probe reported syncing or @@ -36,16 +44,17 @@ //! be that one. Unlike the gate, a node that did not answer is not given the //! benefit of the doubt here: no 503 stands behind it. //! -//! # No clock-based rule +//! # No clock-based rule for signing //! -//! Nothing here judges a node by how old its head looks against this client's +//! Nothing here stops a duty because a head looks old against this client's //! clock. During a network-wide stall every head is old, and clients that stop -//! signing then keep the chain stalled. The signal is the node's own -//! `is_syncing` and `is_optimistic`. `head_slot` and `sync_distance` are kept in -//! the record, not acted on. A record older than two slots is no longer read for -//! routing, which only ever moves a node back to plain command-line order. +//! signing then keep the chain stalled. The gate reads the node's own +//! `is_syncing` and `is_optimistic`, nothing else. `sync_distance`, which is the +//! node's own clock against its head, only orders the walk: in a stall every +//! node is behind by about as much, so they share a tier and keep command-line +//! order. A record older than two slots is no longer read for routing, which +//! only ever moves a node back to plain command-line order. -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, OnceLock, PoisonError, RwLock}; use std::time::{Duration, SystemTime}; @@ -54,8 +63,16 @@ use tracing::{info, warn}; use crate::beacon_node::BeaconNodeApi; use crate::beacon_node::fallback::FallbackBeaconNode; +use crate::error::{BeaconNodeFailure, Error}; use crate::slot_clock::SlotClock; +/// How many slots behind its own clock a node may report (`sync_distance`) and +/// still rank as synced: Lighthouse's tolerance. A node answers `is_syncing: +/// false` by its own threshold, which the Beacon API leaves to each client, so +/// one a few slots behind can still say it is synced while it hands out an old +/// head. Past this it ranks with the syncing nodes. +pub const SYNC_TOLERANCE: u64 = 8; + /// How far ahead of a slot's boundary its probe is taken, as a fraction of the /// slot: a sixth, which is Lighthouse's 2 s on mainnet's 12 s slots. Past the /// payload timeliness committee vote, the latest duty offset of the slot @@ -81,9 +98,9 @@ pub struct SyncStatus { /// The node's head has an execution payload its execution client has not /// validated. `false` when the node left the field out. pub is_optimistic: bool, - /// The node cannot reach its execution client. Logged, never acted on: the - /// node reports `is_optimistic` once that starts to matter. `false` when - /// the node left the field out. + /// The node cannot reach its execution client. Ranks the node below the + /// fully synced ones, never stops a duty: the node reports `is_optimistic` + /// once that starts to matter. `false` when the node left the field out. pub el_offline: bool, } @@ -92,6 +109,15 @@ impl SyncStatus { pub fn is_synced(&self) -> bool { !self.is_syncing && !self.is_optimistic } + + /// Syncing, or further behind its own clock than [`SYNC_TOLERANCE`]. A + /// node that sent no `sync_distance` is judged by `is_syncing` alone. + pub fn is_behind(&self) -> bool { + self.is_syncing + || self + .sync_distance + .is_some_and(|distance| distance > SYNC_TOLERANCE) + } } /// One probe of one node. @@ -157,6 +183,75 @@ impl Standing { } } +/// Where a node ranks in the order requests walk the nodes in, best first. +/// +/// For ordering only. Whether a slot signs, and which nodes the head root and +/// the payload attestation data may come from, is [`Standing`]'s, so a node +/// that is merely behind or has lost its execution client ranks lower without +/// being refused anything. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Tier { + /// Answered neither syncing nor optimistic, within [`SYNC_TOLERANCE`] of + /// its clock, with its execution client online. + Synced, + /// Answered within the tolerance and not syncing, but optimistic or with + /// its execution client offline. + Degraded, + /// Answered syncing, or more than [`SYNC_TOLERANCE`] slots behind. + Behind, + /// Not probed yet, or its last probe is too old to read. + Unknown, + /// Did not answer its last probe, or since then did not answer a request + /// (it timed out or could not connect). + Failing, +} + +impl Tier { + /// The tier a probe puts a node in, before any request since. + pub fn of(probe: &Probe) -> Self { + match &probe.outcome { + Err(_) => Self::Failing, + Ok(status) if status.is_behind() => Self::Behind, + Ok(status) if status.is_optimistic || status.el_offline => Self::Degraded, + Ok(_) => Self::Synced, + } + } +} + +/// A request to a node that got no answer, which ranks the node +/// [`Tier::Failing`] until a probe recorded after it answers. +#[derive(Debug, Clone, PartialEq, Eq)] +struct RequestFailure { + at: SystemTime, +} + +/// Whether a request failing with `err` says the node is not answering, and so +/// ranks it [`Tier::Failing`]: it timed out, or the connection could not be +/// made. Both cost a duty seconds (the request timeout, the connect timeout) +/// each time the node is asked first. A status, even a 5xx, is an answer, and a +/// 404 from a node with nothing to aggregate is routine. +pub fn ranks_failing(err: &Error) -> bool { + matches!( + err, + Error::BeaconNode { + failure: BeaconNodeFailure::Timeout | BeaconNodeFailure::Connect, + .. + } + ) +} + +/// One node's record: its last probe, and the last request it did not answer +/// since that probe, if any. +#[derive(Debug, Clone, Default)] +struct Record { + probe: Option, + failure: Option, + /// Whether the last probe that answered reported the execution client + /// offline. A probe with no answer leaves it as it was, so the change logs + /// compare one answer with the last. + el_offline: bool, +} + /// How the nodes that answered one round of probes split. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct SyncVerdict { @@ -194,28 +289,24 @@ impl SyncVerdict { } } -/// The last probe of each configured beacon node, in command-line order. +/// The last probe of each configured beacon node, in command-line order, and +/// the last request each did not answer since. /// /// Shared, so the fallback that routes requests by it and anything that reports -/// on the nodes read the same records. [`Self::snapshot`] is the cheap read for -/// the latter. +/// on the nodes read the same records. [`Self::snapshot`] and [`Self::tiers`] +/// are the cheap reads for the latter. pub struct NodeHealth { - probes: RwLock>>, - /// Whether each node's last probe that answered reported its execution - /// client offline. A probe with no answer leaves it as it was, so the - /// change logs compare one answer with the last. - el_offline: Vec, - /// How long a probe is read for routing. Unset until [`run`] starts, so a - /// fallback that is never probed on a schedule (a test, the voluntary-exit - /// command) reads whatever it holds. + records: RwLock>, + /// How long a probe, or a request failure, is read for routing. Unset + /// until [`run`] starts, so a fallback that is never probed on a schedule + /// (a test, the voluntary-exit command) reads whatever it holds. read_for: OnceLock, } impl NodeHealth { pub fn new(nodes: usize) -> Self { Self { - probes: RwLock::new(vec![None; nodes]), - el_offline: (0..nodes).map(|_| AtomicBool::new(false)).collect(), + records: RwLock::new(vec![Record::default(); nodes]), read_for: OnceLock::new(), } } @@ -223,40 +314,98 @@ impl NodeHealth { /// Every node's last probe, in command-line order: `None` for a node not /// probed yet. A copy, so a caller holds no lock. pub fn snapshot(&self) -> Vec> { - self.read().clone() + self.read() + .iter() + .map(|record| record.probe.clone()) + .collect() + } + + /// Keep that a request to the node at `position` failed with `err`, when + /// that failure says the node is not answering ([`ranks_failing`]): the + /// node then ranks [`Tier::Failing`] until a probe recorded after this + /// answers. Logged once, when the node starts being passed over. + pub fn record_request_failure(&self, position: usize, what: &'static str, err: &Error) { + if !ranks_failing(err) { + return; + } + let already = { + let mut records = self.write(); + let Some(record) = records.get_mut(position) else { + return; + }; + record + .failure + .replace(RequestFailure { + at: SystemTime::now(), + }) + .is_some() + }; + if !already { + warn!( + %what, + position, + %err, + "Beacon node did not answer a request; it is asked last until it answers a sync \ + probe" + ); + } } - /// Stop reading a probe for routing once it is older than `age`. + /// Stop reading a probe, or a request failure, for routing once it is older + /// than `age`. pub fn expire_after(&self, age: Duration) { let _ = self.read_for.set(age); } /// Keep `probe` as the node at `position`'s last, and log what changed: a - /// node that stopped or started answering synced, and `el_offline` going on - /// or off. Only changes, since a probe runs every slot. + /// node that stopped or started answering synced, falling behind or + /// catching up by [`SYNC_TOLERANCE`], and `el_offline` going on or off. + /// Only changes, since a probe runs every slot. + /// + /// A probe that answered also ends a request failure recorded before it + /// ([`Self::record_request_failure`]): the node answers again, so it is + /// ranked by what it said. pub fn record(&self, position: usize, probe: Probe) { let standing = probe.standing(); let el_offline = is_el_offline(&probe); + let lagging = is_lagging(&probe); let (head_slot, sync_distance) = match &probe.outcome { Ok(status) => (status.head_slot, status.sync_distance), Err(_) => (None, None), }; let error = probe.outcome.as_ref().err().cloned(); - let previous = { - let mut probes = self.probes.write().unwrap_or_else(PoisonError::into_inner); - let Some(held) = probes.get_mut(position) else { + let answered = probe.outcome.is_ok(); + let (previous, cleared, was_el_offline) = { + let mut records = self.write(); + let Some(record) = records.get_mut(position) else { return; }; - held.replace(probe) + let cleared = if answered { + record.failure.take().is_some() + } else { + false + }; + let was_el_offline = record.el_offline; + if answered { + record.el_offline = el_offline; + } + (record.probe.replace(probe), cleared, was_el_offline) }; + if cleared { + info!( + position, + "Beacon node answered its sync probe after a request it did not answer; it is \ + ranked by its probe again" + ); + } let was = previous.as_ref().map(Probe::standing); if was != Some(standing) { match standing { Standing::Synced if was.is_some() => info!( position, ?head_slot, - "Beacon node reports it is synced; duties go to it first again" + "Beacon node reports it is synced again" ), Standing::Syncing => warn!( position, @@ -267,7 +416,7 @@ impl NodeHealth { Standing::Optimistic => warn!( position, ?head_slot, - "Beacon node reports an optimistic head; duties go to the other nodes first" + "Beacon node reports an optimistic head; duties go to the synced nodes first" ), Standing::NoAnswer => warn!( position, @@ -277,58 +426,108 @@ impl NodeHealth { Standing::Synced | Standing::Unknown => {} } } + // A node that says it is syncing is reported as such above; this is + // the one that does not, and lags anyway. + let was_lagging = previous.as_ref().is_some_and(is_lagging); + if lagging && !was_lagging { + warn!( + position, + ?head_slot, + ?sync_distance, + tolerance = SYNC_TOLERANCE, + "Beacon node's head is further behind its clock than the tolerance, though it \ + does not report syncing; duties go to the nodes closer to the head first" + ); + } else if was_lagging + && !lagging + && matches!(standing, Standing::Synced | Standing::Optimistic) + { + info!( + position, + ?head_slot, + ?sync_distance, + "Beacon node is within the sync tolerance again" + ); + } // Against the last probe that answered, so a failed probe in between // neither hides the execution client coming back nor repeats it going. - if standing == Standing::NoAnswer { + if !answered { return; } - let was_el_offline = self.el_offline[position].swap(el_offline, Ordering::Relaxed); if el_offline && !was_el_offline { warn!( position, - "Beacon node reports its execution client is offline; it will go optimistic if it \ - has not already" + "Beacon node reports its execution client is offline; duties go to the nodes with \ + one first, and it will go optimistic if it has not already" ); } else if was_el_offline && !el_offline { info!(position, "Beacon node reports its execution client is back"); } } - /// Every position, the nodes whose last probe passed first, then the rest, - /// each group in command-line order, with each node's standing. + /// Every position in the order requests walk the nodes in, with each + /// node's standing: by [`Tier`], best first, command-line order breaking + /// ties. With no probe held and no request failed, every node is + /// [`Tier::Unknown`], so it is plain command-line order. /// - /// The order requests walk the nodes in. Nothing more than passed or not: - /// with no probe held, it is plain command-line order. + /// The standing is the probe's alone, whatever the tier: a node ranked + /// failing for a request it did not answer still reads as synced to the + /// calls that refuse unsynced nodes. pub fn ranked(&self) -> Vec<(usize, Standing)> { - self.ranked_at(SystemTime::now()) + self.ranking_at(SystemTime::now()) + .into_iter() + .map(|(position, standing, _)| (position, standing)) + .collect() } - fn ranked_at(&self, now: SystemTime) -> Vec<(usize, Standing)> { + /// Every position in the walk's order, as [`Self::ranked`], with each + /// node's [`Tier`]: what a report on the nodes shows. + pub fn tiers(&self) -> Vec<(usize, Tier)> { + self.ranking_at(SystemTime::now()) + .into_iter() + .map(|(position, _, tier)| (position, tier)) + .collect() + } + + fn ranking_at(&self, now: SystemTime) -> Vec<(usize, Standing, Tier)> { let read_for = self.read_for.get().copied(); - let probes = self.read(); - let standings = probes.iter().enumerate().map(|(position, probe)| { - let standing = match probe { - Some(probe) if !is_stale(probe, read_for, now) => probe.standing(), - _ => Standing::Unknown, - }; - (position, standing) - }); - let (mut ranked, rest): (Vec<_>, Vec<_>) = - standings.partition(|(_, standing)| *standing == Standing::Synced); - ranked.extend(rest); - ranked + let records = self.read(); + let mut ranking: Vec<(usize, Standing, Tier)> = records + .iter() + .enumerate() + .map(|(position, record)| { + let probe = record + .probe + .as_ref() + .filter(|probe| !is_stale(probe.at, read_for, now)); + let standing = probe.map_or(Standing::Unknown, Probe::standing); + let failed = record + .failure + .as_ref() + .is_some_and(|failure| !is_stale(failure.at, read_for, now)); + let tier = if failed { + Tier::Failing + } else { + probe.map_or(Tier::Unknown, Tier::of) + }; + (position, standing, tier) + }) + .collect(); + // Stable, and keyed on the position too, so ties keep command-line + // order whatever order the records were written in. + ranking.sort_by_key(|&(position, _, tier)| (tier, position)); + ranking } /// How the probes taken for `slot` split. A node whose last probe was taken /// for another slot did not answer this one; one still on the slot before's /// synced answer is counted apart, as awaited. pub fn verdict(&self, slot: Slot) -> SyncVerdict { - let probes = self.read(); - let for_slot = probes.iter().flatten().filter(|probe| probe.slot == slot); + let records = self.read(); + let probes = || records.iter().filter_map(|record| record.probe.as_ref()); + let for_slot = probes().filter(|probe| probe.slot == slot); let mut verdict = SyncVerdict::tally(for_slot.map(Probe::standing)); - verdict.awaited_synced = probes - .iter() - .flatten() + verdict.awaited_synced = probes() .filter(|probe| probe.slot + 1 == slot && probe.standing() == Standing::Synced) .count(); verdict @@ -336,8 +535,12 @@ impl NodeHealth { /// The records are plain values with no invariant between them, so one a /// panicking writer left behind is still a record worth reading. - fn read(&self) -> std::sync::RwLockReadGuard<'_, Vec>> { - self.probes.read().unwrap_or_else(PoisonError::into_inner) + fn read(&self) -> std::sync::RwLockReadGuard<'_, Vec> { + self.records.read().unwrap_or_else(PoisonError::into_inner) + } + + fn write(&self) -> std::sync::RwLockWriteGuard<'_, Vec> { + self.records.write().unwrap_or_else(PoisonError::into_inner) } } @@ -345,8 +548,13 @@ fn is_el_offline(probe: &Probe) -> bool { matches!(&probe.outcome, Ok(status) if status.el_offline) } -fn is_stale(probe: &Probe, read_for: Option, now: SystemTime) -> bool { - read_for.is_some_and(|limit| now.duration_since(probe.at).unwrap_or_default() > limit) +/// Behind by more than [`SYNC_TOLERANCE`] without saying it is syncing. +fn is_lagging(probe: &Probe) -> bool { + matches!(&probe.outcome, Ok(status) if !status.is_syncing && status.is_behind()) +} + +fn is_stale(at: SystemTime, read_for: Option, now: SystemTime) -> bool { + read_for.is_some_and(|limit| now.duration_since(at).unwrap_or_default() > limit) } /// The duty loop's gate for `slot`, read at its boundary: whether the slot's @@ -555,8 +763,38 @@ mod tests { assert_eq!(Standing::of(&status(false, false)), Standing::Synced); } + fn order(health: &NodeHealth) -> Vec { + health + .ranked() + .into_iter() + .map(|(position, _)| position) + .collect() + } + + fn at_distance(slot: Slot, sync_distance: u64) -> Probe { + probe( + slot, + Ok(SyncStatus { + sync_distance: Some(sync_distance), + ..status(false, false) + }), + ) + } + + fn el_offline(slot: Slot) -> Probe { + probe( + slot, + Ok(SyncStatus { + el_offline: true, + ..status(false, false) + }), + ) + } + + /// The tiers, best first: synced; optimistic; syncing; failing. Nodes in + /// one tier keep command-line order. #[test] - fn nodes_that_passed_come_first_in_command_line_order() { + fn nodes_are_ranked_by_tier_and_then_by_command_line_order() { let health = health(vec![ syncing(3), synced(3), @@ -564,12 +802,136 @@ mod tests { synced(3), optimistic(3), ]); - let order: Vec = health - .ranked() - .into_iter() - .map(|(position, _)| position) - .collect(); - assert_eq!(order, vec![1, 3, 0, 2, 4]); + assert_eq!(order(&health), vec![1, 3, 4, 0, 2]); + assert_eq!( + health.tiers(), + vec![ + (1, Tier::Synced), + (3, Tier::Synced), + (4, Tier::Degraded), + (0, Tier::Behind), + (2, Tier::Failing) + ] + ); + } + + /// Two nodes equally healthy keep the order they were listed in, so a + /// client with one healthy node, or several, behaves as it always did. + /// Distances inside the tolerance do not reorder them either. + #[test] + fn two_healthy_nodes_keep_command_line_order() { + assert_eq!(order(&health(vec![synced(3), synced(3)])), vec![0, 1]); + let within = health(vec![at_distance(3, 2), at_distance(3, 0)]); + assert_eq!(order(&within), vec![0, 1]); + } + + /// A node that says it is not syncing but whose head is more than the + /// tolerance behind its own clock ranks with the syncing nodes, after a + /// synced node listed behind it. Within the tolerance it is synced: the + /// issue's example of 5 slots is inside Lighthouse's 8, so 9 is the case + /// that moves. + #[test] + fn a_node_beyond_the_sync_tolerance_ranks_after_a_synced_one() { + let behind = health(vec![at_distance(3, SYNC_TOLERANCE + 1), synced(3)]); + assert_eq!(order(&behind), vec![1, 0]); + assert_eq!(behind.tiers()[1], (0, Tier::Behind)); + assert_eq!( + behind.ranked()[1], + (0, Standing::Synced), + "ranked lower, still synced to the gate" + ); + + let within = health(vec![at_distance(3, 5), synced(3)]); + assert_eq!(order(&within), vec![0, 1]); + let at_the_edge = health(vec![at_distance(3, SYNC_TOLERANCE), synced(3)]); + assert_eq!(order(&at_the_edge), vec![0, 1]); + + // Behind, it still ranks above a node that did not answer at all. + let both = health(vec![down(3), at_distance(3, 40)]); + assert_eq!(order(&both), vec![1, 0]); + } + + /// An optimistic node, or one whose execution client is offline, ranks + /// below a synced one and above a syncing one. + #[test] + fn optimistic_and_el_offline_nodes_rank_between_synced_and_syncing() { + let health = health(vec![syncing(3), el_offline(3), optimistic(3), synced(3)]); + assert_eq!(order(&health), vec![3, 1, 2, 0]); + assert_eq!(health.tiers()[1], (1, Tier::Degraded)); + } + + /// A node never probed, or one whose probe has not come back yet, ranks + /// below every node that answered and above one that failed. + #[test] + fn a_node_not_probed_yet_ranks_below_those_that_answered() { + let health = NodeHealth::new(3); + health.record(1, syncing(3)); + health.record(2, down(3)); + assert_eq!( + health.tiers(), + vec![(1, Tier::Behind), (0, Tier::Unknown), (2, Tier::Failing)] + ); + } + + fn failed(failure: BeaconNodeFailure) -> Error { + Error::BeaconNode { + url: "mock".to_string(), + failure, + detail: "no answer".to_string(), + } + } + + /// A request that timed out ranks its node failing at once, and a probe + /// recorded after it that answers ranks it by its probe again. A probe + /// that fails changes nothing. An answer with an error status is an + /// answer, and a request that broke once sent fails fast, so neither + /// ranks a node failing; a refused connection does. + #[test] + fn a_request_with_no_answer_ranks_the_node_failing_until_a_probe_answers() { + let health = health(vec![synced(3), synced(3)]); + health.record_request_failure(0, "attestation_data", &failed(BeaconNodeFailure::Timeout)); + assert_eq!(order(&health), vec![1, 0]); + assert_eq!(health.tiers()[1], (0, Tier::Failing)); + assert_eq!( + health.ranked()[1], + (0, Standing::Synced), + "the gate still reads the probe" + ); + + health.record(0, down(4)); + assert_eq!(order(&health), vec![1, 0]); + health.record(0, synced(5)); + assert_eq!(order(&health), vec![0, 1]); + + let refused = Error::BeaconNodeStatus { + status: 404, + body: "no aggregate".to_string(), + }; + health.record_request_failure(0, "aggregate_attestation", &refused); + health.record_request_failure(0, "attestation_data", &failed(BeaconNodeFailure::Request)); + assert_eq!(order(&health), vec![0, 1], "neither ranks it failing"); + + health.record_request_failure(0, "attestation_data", &failed(BeaconNodeFailure::Connect)); + assert_eq!(order(&health), vec![1, 0]); + } + + /// A request failure is read for as long as a probe is: a probe task that + /// stopped leaves every node back in command-line order. + #[test] + fn a_stale_request_failure_is_not_read_for_routing() { + let health = NodeHealth::new(2); + health.expire_after(Duration::from_secs(24)); + let failed_at = SystemTime::now(); + health.record_request_failure(0, "attestation_data", &failed(BeaconNodeFailure::Timeout)); + assert_eq!(health.ranking_at(failed_at)[1].2, Tier::Failing); + let later = health.ranking_at(failed_at + Duration::from_secs(60)); + assert_eq!( + later, + vec![ + (0, Standing::Unknown, Tier::Unknown), + (1, Standing::Unknown, Tier::Unknown) + ] + ); } /// Before any probe the walk is the command-line order, unchanged, which @@ -603,28 +965,25 @@ mod tests { }, ); - let fresh = health.ranked_at(taken + Duration::from_secs(1)); - assert_eq!(fresh[0], (1, Standing::Synced)); + let fresh = health.ranking_at(taken + Duration::from_secs(1)); + assert_eq!(fresh[0], (1, Standing::Synced, Tier::Synced)); - let later = health.ranked_at(taken + Duration::from_secs(60)); - assert_eq!(later, vec![(0, Standing::Unknown), (1, Standing::Unknown)]); + let later = health.ranking_at(taken + Duration::from_secs(60)); + assert_eq!( + later, + vec![ + (0, Standing::Unknown, Tier::Unknown), + (1, Standing::Unknown, Tier::Unknown) + ] + ); } /// A probe with no answer leaves the execution client's last reported /// state as it was, so the next answer is compared with the one before it. #[test] fn a_failed_probe_leaves_the_execution_clients_state() { - let el_offline = |slot| { - probe( - slot, - Ok(SyncStatus { - el_offline: true, - ..status(false, false) - }), - ) - }; let nodes = NodeHealth::new(1); - let held = |nodes: &NodeHealth| nodes.el_offline[0].load(Ordering::Relaxed); + let held = |nodes: &NodeHealth| nodes.read()[0].el_offline; nodes.record(0, el_offline(3)); nodes.record(0, down(4)); assert!(held(&nodes), "no answer, nothing changed"); diff --git a/crates/validator/src/beacon_node/mock.rs b/crates/validator/src/beacon_node/mock.rs index 9e46b4d0a..98b236e86 100644 --- a/crates/validator/src/beacon_node/mock.rs +++ b/crates/validator/src/beacon_node/mock.rs @@ -70,6 +70,14 @@ pub struct MockBeaconNode { pub sync_status_override: Mutex>, /// How long `sync_status` takes before it answers, as a hung node would. pub sync_status_delay: Option, + /// When set, a node that takes the request and never answers, as the HTTP + /// client sees one: each call that checks it ([`Self::stall`]) waits this + /// long, the request timeout, and then fails as a timeout. Settable while + /// a test runs, so a hung node can come back. See [`Self::set_hang`]. + pub hang: Mutex>, + /// The method of every call made while [`Self::hang`] was set, recorded + /// on entry. + pub hung_calls: Mutex>, pub validators: Vec, pub duties: Mutex>, pub proposers: Mutex>, @@ -476,6 +484,46 @@ impl MockBeaconNode { self } + /// Hang every call that checks [`Self::hang`] for `timeout`, then fail it + /// as a timeout, as a node that accepts the request and never answers. + pub fn with_hang(self, timeout: std::time::Duration) -> Self { + self.set_hang(Some(timeout)); + self + } + + /// Start or stop hanging: `None` is a node that answers again. + pub fn set_hang(&self, timeout: Option) { + *self.hang.lock().expect("lock") = timeout; + } + + /// How many calls to `what` were made while the node hung. + pub fn hung_calls_to(&self, what: &str) -> usize { + self.hung_calls + .lock() + .expect("lock") + .iter() + .filter(|called| **called == what) + .count() + } + + /// For a call that checks it: when the node hangs, wait out the timeout + /// and fail as the HTTP client fails a request that got no answer. Checked + /// by `sync_status`, `attestation_data`, `publish_block`, + /// `submit_attestations` and `publish_execution_payload_envelope`. + async fn stall(&self, what: &'static str) -> Result<()> { + let hang = *self.hang.lock().expect("lock"); + let Some(timeout) = hang else { + return Ok(()); + }; + self.hung_calls.lock().expect("lock").push(what); + tokio::time::sleep(timeout).await; + Err(Error::BeaconNode { + url: "mock".to_string(), + failure: BeaconNodeFailure::Timeout, + detail: format!("{what}: no answer within {} ms", timeout.as_millis()), + }) + } + /// Report `status` from now on, whatever `syncing` and `optimistic` say: /// the node went optimistic, say, after a test's first probe. pub fn set_sync_status(&self, status: SyncStatus) { @@ -873,6 +921,7 @@ impl BeaconNodeApi for MockBeaconNode { if let Some(delay) = self.sync_status_delay { tokio::time::sleep(delay).await; } + self.stall("sync_status").await?; self.guard("is_syncing")?; Ok(self.current_status()) } @@ -924,6 +973,7 @@ impl BeaconNodeApi for MockBeaconNode { } async fn attestation_data(&self, slot: Slot, fork: ForkName) -> Result { + self.stall("attestation_data").await?; self.guard("attestation_data")?; *self.attestation_data_calls.lock().expect("lock") += 1; self.attestation_data_forks.lock().expect("lock").push(fork); @@ -1020,6 +1070,7 @@ impl BeaconNodeApi for MockBeaconNode { } async fn publish_block(&self, fork: ForkName, body: &[u8]) -> Result { + self.stall("publish_block").await?; self.guard("publish_block")?; self.published_blocks .lock() @@ -1152,6 +1203,7 @@ impl BeaconNodeApi for MockBeaconNode { body: &[u8], blob_data_included: bool, ) -> Result<()> { + self.stall("publish_execution_payload_envelope").await?; self.guard("publish_execution_payload_envelope")?; self.envelope_publish_entered.notify_one(); if let Some(gate) = &self.envelope_publish_gate { @@ -1218,6 +1270,7 @@ impl BeaconNodeApi for MockBeaconNode { attestations: &[SingleAttestationDto], fork_name: &str, ) -> Result { + self.stall("submit_attestations").await?; self.guard("submit_attestations")?; self.submitted .lock() diff --git a/crates/validator/src/beacon_node/mod.rs b/crates/validator/src/beacon_node/mod.rs index 5e05e6cb6..89a50440b 100644 --- a/crates/validator/src/beacon_node/mod.rs +++ b/crates/validator/src/beacon_node/mod.rs @@ -670,6 +670,24 @@ pub trait BeaconNodeApi: Send + Sync { blob_data_included: bool, ) -> Result<()>; + /// [`Self::publish_execution_payload_envelope`] for the envelope of a block + /// `producer` produced (the [`ProducedBlock::producer`] of the block it + /// reveals the payload of). + /// + /// A single node has no one to choose and ignores `producer`, which is + /// the default. The fallback reads it under `--broadcast blocks`, to send + /// the envelope to the producing node first. + async fn publish_execution_payload_envelope_produced_by( + &self, + producer: Producer, + body: &[u8], + blob_data_included: bool, + ) -> Result<()> { + let _ = producer; + self.publish_execution_payload_envelope(body, blob_data_included) + .await + } + /// The payload timeliness committee duties for `indices` in `epoch`. /// /// An epoch before gloas answers with no duties rather than an error. diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index 82446527d..f819f21bd 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -161,6 +161,9 @@ pub struct ValidatorConfig { /// has seen it stay silent for a full epoch, and stop if it does not. See /// [`doppelganger`]. pub doppelganger_protection: bool, + /// `--broadcast`: the signed messages sent to every beacon node rather + /// than the first that accepts them. See [`beacon_node::fallback`]. + pub broadcast: beacon_node::fallback::Broadcast, } /// Builder proposals: register each validator with the beacon node's builder @@ -276,7 +279,7 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { .iter() .map(HttpBeaconNode::new) .collect::>>()?; - let beacon_node = Arc::new(FallbackBeaconNode::new(nodes)); + let beacon_node = Arc::new(FallbackBeaconNode::new(nodes).with_broadcast(config.broadcast)); let genesis = beacon_node.genesis().await?; let spec = beacon_node.spec().await?; diff --git a/crates/validator/src/proposal.rs b/crates/validator/src/proposal.rs index ccf6b8205..05800d875 100644 --- a/crates/validator/src/proposal.rs +++ b/crates/validator/src/proposal.rs @@ -612,6 +612,7 @@ impl ProposalService { pubkey, fork, block_root, + producer, payload, builder_index, body, @@ -629,8 +630,9 @@ impl ProposalService { // Logged and counted rather than propagated. The block is out and // the proposal did happen; what failed is the reveal, which has its // own series because it is the failure that costs the payload. - let reveal = - self.publish_envelope(slot, validator, &pubkey, block_root, payload, store); + let reveal = self.publish_envelope( + slot, validator, &pubkey, block_root, producer, payload, store, + ); let _ = before(deadline, slot, reveal) .await .inspect(|()| crate::metrics::inc_envelopes_published()) @@ -662,12 +664,17 @@ impl ProposalService { /// be for this block and this self-build before it is signed: the signature /// covers the envelope as it stands, so one for another block would be a /// valid signature on the wrong payload. + /// + /// `producer` is the node that built the block, which the fallback sends + /// the envelope to first under `--broadcast blocks`. + #[allow(clippy::too_many_arguments)] async fn publish_envelope( &self, slot: Slot, validator: u64, pubkey: &BlsPubkey, block_root: Root, + producer: Producer, payload: Option, store: &RwLock, ) -> Result<()> { @@ -703,8 +710,10 @@ impl ProposalService { Some(payload) => payload.into_signed_contents_ssz(signature), None => signed_envelope_ssz(envelope, signature), }; + // Signed once, above; under `--broadcast blocks` the same body goes to + // every node, the block's producer first. self.beacon_node - .publish_execution_payload_envelope(&body, included) + .publish_execution_payload_envelope_produced_by(producer, &body, included) .await?; info!(%slot, validator, bytes = body.len(), blob_data_included = included, "Envelope published"); Ok(()) diff --git a/docs/cli.md b/docs/cli.md index db05eaf13..279447553 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -371,7 +371,8 @@ implementation's, so none of the [common flags](#common-flags) apply to it. | Flag | Default | Meaning | |---|---|---| -| `--beacon-nodes` | required | Base URLs of the beacon nodes to use, comma-separated or repeated. Every node is asked `/eth/v1/node/syncing` once a slot; the ones that answered synced and not optimistic are tried first, in list order, then the rest in list order. The first that answers serves the request, so the order is a preference, not load balancing. See [The per-slot sync check](#the-per-slot-sync-check) | +| `--beacon-nodes` | required | Base URLs of the beacon nodes to use, comma-separated or repeated. Every node is asked `/eth/v1/node/syncing` once a slot and ranked by the answer, list order breaking ties. The first that answers serves the request, so the order is a preference, not load balancing. See [The per-slot sync check](#the-per-slot-sync-check) and [Ranking and broadcast](#ranking-and-broadcast) | +| `--broadcast` | none | Signed messages to send to every beacon node at once instead of the first that accepts them, comma-separated: `attestations` (attestations, aggregates, payload attestations), `blocks` (blocks and envelopes, never a blinded block), `sync-committee` (messages and contributions). `subscriptions` is accepted and changes nothing, since subscriptions, fee recipients, builder registrations and proposer preferences always go to every node. See [Ranking and broadcast](#ranking-and-broadcast) | | `--validators-dir` | required | Directory holding the EIP-2335 keystores and `validator_definitions.yml`, which also lists the keys a remote signer holds (see [Remote signing](#remote-signing-web3signer)). Without that file, keystores in the Lighthouse layout (`<0xpubkey>/voting-keystore.json`, password in `--secrets-dir/<0xpubkey>`) are discovered and the file is written | | `--secrets-dir` | required | Directory holding one password file per keystore, named after the validator's public key | | `--http-address` | `127.0.0.1` | Bind address for the metrics and keymanager servers | @@ -561,9 +562,9 @@ the next slot's probe to answer. node whose answer is still on its way at the boundary, and that answered synced the slot before, holds the check open too, so a slow synced node does not lose the slot to a fast syncing one. -- **Requests go to the nodes that passed first**, then the rest, each group - in `--beacon-nodes` order. A blinded block still goes back to the node that - produced it. +- **Requests go to the best-ranked node first**: see + [Ranking and broadcast](#ranking-and-broadcast). A blinded block still goes + back to the node that produced it. - **The head root and the payload attestation data are never asked of a node whose last probe said syncing or optimistic, or got no answer**, even after the nodes that passed have failed the request. Neither endpoint has a `503` @@ -572,16 +573,74 @@ the next slot's probe to answer. So here, unlike for the slot's check, a node that did not answer is not given the benefit of the doubt. With no node left to ask, the sync committee message and the payload vote are not signed. -- **`el_offline` is logged, not acted on**: a node whose execution client has - just gone offline still has the head it validated before, and reports itself - optimistic once that stops being true. A node's change of state (synced, - syncing, optimistic, no answer, `el_offline`) is logged once, when it - changes. -- **There is no clock-based rule.** The client never skips duties because the - head looks old by its own clock: during a network-wide stall every head is - old, and clients that stop signing then keep the chain stalled. Only the - node's own `is_syncing` and `is_optimistic` count. `head_slot` and - `sync_distance` are recorded, not acted on. +- **`el_offline` ranks a node lower and stops nothing**: a node whose + execution client has just gone offline still has the head it validated + before, and reports itself optimistic once that stops being true. A node's + change of state (synced, syncing, optimistic, no answer, `el_offline`, + behind by its sync distance) is logged once, when it changes. +- **There is no clock-based rule for signing.** The client never skips duties + because the head looks old: during a network-wide stall every head is old, + and clients that stop signing then keep the chain stalled. Only the node's + own `is_syncing` and `is_optimistic` count. `sync_distance` only ranks the + nodes, and in a stall every node is about as far behind. + +### Ranking and broadcast + +With several `--beacon-nodes`, every request walks the nodes in rank order +and takes the first answer. The rank comes from each node's last sync probe, +best first, as Lighthouse ranks its nodes: + +1. synced and validated: not syncing, not optimistic, execution client + online, and at most 8 slots behind by its own `sync_distance` + (Lighthouse's tolerance); +2. synced but optimistic, or with its execution client offline; +3. syncing, or more than 8 slots behind; +4. not probed yet; +5. failing: it did not answer its last probe, or since then did not answer a + request. + +`--beacon-nodes` order breaks ties, so a single healthy node, or several +equally healthy ones, are asked exactly as listed. Lighthouse's finer tiers +(16 and 64 slots behind) are not kept: they only reorder nodes that are all +behind, which in practice means a stalled network, where every node is behind +by about as much. + +A request that times out, or whose connection cannot be made, ranks its node +failing at once, until a later probe answers. So a node that takes requests +and never answers costs one request timeout (8 s) and then nothing until it +answers again, rather than a timeout on every request: an attestation duty +used to wait out the whole timeout on a hung first node every slot, which +left the second node no time. An answer with an error status (a `404` from a +node with nothing to aggregate, a `503` from a syncing one) is an answer and +changes no rank. A probe more than two slots old is not read, which only +matters if the probe task stops, and puts every node back in list order. + +`--broadcast` sends signed messages to every node at once rather than to the +first that accepts them, so they reach the network through every node's gossip +mesh: `attestations` (attestations, aggregates, payload attestations), +`blocks` (blocks and envelopes) and `sync-committee` (messages and +contributions), comma-separated. None by default, as in Lighthouse, so the +client behaves as before unless asked. Subscriptions, fee recipient +preparations, builder registrations and proposer preferences always go to +every node; `subscriptions` is accepted for compatibility and changes +nothing. + +- **One accepting node is success.** A message one node took is on the + network. A node that refused is logged. +- **Failing nodes are sent it last.** A node ranked failing is sent a + broadcast only when no other node took it, so a hung node does not hold + every broadcast back by a request timeout. +- **A block reports the best answer**: imported (`200`) over broadcast but + not imported (`202`) over refused, each node's answer logged. A blinded + block still goes only to the node that produced it. +- **An envelope goes to its block's producer first**, then to the other + nodes once the producer has answered. The producer certainly holds the + block the envelope reveals; a node that has not imported it yet queues or + drops the envelope, and waiting for the producer's answer gives each a + round trip longer to import it. An envelope sent without its blobs goes to + the producer alone, since only it cached them. +- **Signed once.** Every message is signed, and recorded by slashing + protection, before it is sent, however many nodes it is sent to. ### Doppelganger protection From c41881115e08c77e77d81b341ab6aa20980a618d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:11:57 -0300 Subject: [PATCH 05/12] fix(validator): rank a syncing node last inside its tier, send a blobless envelope to its producer In a stall every node is past the sync tolerance and ranks Behind, so a syncing node listed first was asked ahead of a synced one. Inside a tier, a node reporting syncing now goes last, and an optimistic or el_offline one after the rest. An envelope without its blobs goes to its producer alone with or without --broadcast blocks: only the producer cached them, and a producer ranked failing for a timed-out block publish was otherwise asked last. Also: --broadcast accepts Lighthouse's `none` as a no-op, the request failures are recorded with inspect_err, and the dto.rs table says el_offline and sync_distance rank a node. --- bin/ethlambda/src/validator.rs | 5 +- crates/validator/src/beacon_node/dto.rs | 2 +- crates/validator/src/beacon_node/fallback.rs | 50 +++++++++------ crates/validator/src/beacon_node/health.rs | 66 ++++++++++++++++---- crates/validator/src/beacon_node/mod.rs | 4 +- docs/cli.md | 21 ++++--- 6 files changed, 107 insertions(+), 41 deletions(-) diff --git a/bin/ethlambda/src/validator.rs b/bin/ethlambda/src/validator.rs index 3da046958..c5769aed9 100644 --- a/bin/ethlambda/src/validator.rs +++ b/bin/ethlambda/src/validator.rs @@ -34,7 +34,8 @@ pub(crate) struct ValidatorOptions { /// (attestations, aggregates, payload attestations), `blocks` (blocks /// and envelopes; never a blinded block), `sync-committee` (messages and /// contributions), `subscriptions` (always sent to every node, accepted - /// for Lighthouse compatibility). None by default. + /// for Lighthouse compatibility), `none` (also accepted for Lighthouse + /// compatibility, changing nothing). None by default. #[arg(long, value_delimiter = ',')] pub(crate) broadcast: Vec, @@ -406,6 +407,8 @@ mod tests { ); let options = parse(&["--broadcast", "subscriptions"]).expect("parses"); assert_eq!(topics(options), Broadcast::default()); + let options = parse(&["--broadcast", "none"]).expect("parses"); + assert_eq!(topics(options), Broadcast::default()); parse(&["--broadcast", "everything"]).expect_err("not a topic"); } diff --git a/crates/validator/src/beacon_node/dto.rs b/crates/validator/src/beacon_node/dto.rs index 2e506f567..5a7f2c555 100644 --- a/crates/validator/src/beacon_node/dto.rs +++ b/crates/validator/src/beacon_node/dto.rs @@ -19,7 +19,7 @@ //! |---|---|---| //! | `AttesterDuty` | pubkey, validator_index, committee_index, committee_length, committees_at_slot, validator_committee_index, slot | all seven, all used | //! | Genesis | genesis_time, genesis_validators_root, genesis_fork_version | the first two; the fork version comes from `/config/spec` | -//! | Syncing | head_slot, sync_distance, is_syncing, is_optimistic, el_offline | all five: is_syncing and is_optimistic gate signing; el_offline is logged; head_slot and sync_distance are recorded, and read leniently | +//! | Syncing | head_slot, sync_distance, is_syncing, is_optimistic, el_offline | all five: is_syncing and is_optimistic gate signing; el_offline and sync_distance rank the node, stopping nothing; head_slot is recorded; head_slot and sync_distance are read leniently | //! | `ValidatorResponse` | index, balance, status, validator | index, status, validator.pubkey; the single-validator form also reads the activation, exit and withdrawable epochs | //! | `ProposerDuty` | pubkey, validator_index, slot | all three, all used | //! | `ProposerPreparation` | validator_index, fee_recipient | both, sent not read | diff --git a/crates/validator/src/beacon_node/fallback.rs b/crates/validator/src/beacon_node/fallback.rs index f65a68098..b16e67b2d 100644 --- a/crates/validator/src/beacon_node/fallback.rs +++ b/crates/validator/src/beacon_node/fallback.rs @@ -93,15 +93,20 @@ pub enum BroadcastTopic { /// node, so naming it changes nothing; accepted as Lighthouse's flag /// accepts it. Subscriptions, + /// `none`, which turns Lighthouse's default subscriptions broadcast off. + /// Subscriptions always go to every node here, so it changes nothing; + /// accepted so a Lighthouse command line carries over. + Nothing, } impl BroadcastTopic { /// Every topic, by the name the command line takes. - pub const NAMES: [(&'static str, Self); 4] = [ + pub const NAMES: [(&'static str, Self); 5] = [ ("attestations", Self::Attestations), ("blocks", Self::Blocks), ("sync-committee", Self::SyncCommittee), ("subscriptions", Self::Subscriptions), + ("none", Self::Nothing), ]; } @@ -142,7 +147,7 @@ impl FromIterator for Broadcast { BroadcastTopic::Attestations => broadcast.attestations = true, BroadcastTopic::Blocks => broadcast.blocks = true, BroadcastTopic::SyncCommittee => broadcast.sync_committee = true, - BroadcastTopic::Subscriptions => {} + BroadcastTopic::Subscriptions | BroadcastTopic::Nothing => {} } } broadcast @@ -507,15 +512,14 @@ impl FallbackBeaconNode { { let sends = positions.into_iter().filter_map(|(position, _)| { let send = call(self.nodes.get(position)?); - Some(async move { (position, send.await) }) + Some(async move { + let answer = send + .await + .inspect_err(|err| self.health.record_request_failure(position, what, err)); + (position, answer) + }) }); - let answers = futures_util::future::join_all(sends).await; - for (position, answer) in &answers { - if let Err(err) = answer { - self.health.record_request_failure(*position, what, err); - } - } - answers + futures_util::future::join_all(sends).await } /// A broadcast's answers read as one: the best accepted answer by @@ -954,7 +958,8 @@ impl BeaconNodeApi for FallbackBeaconNode { } /// Without `--broadcast blocks`, [`Self::publish_execution_payload_envelope`]: - /// the first node in the walk that accepts it. + /// the first node in the walk that accepts it. A body without its blobs is + /// the exception, below, with or without the flag. /// /// With it, the producer first, then every other node. The producer is /// the one node certain to hold the block the envelope reveals (it built @@ -977,7 +982,7 @@ impl BeaconNodeApi for FallbackBeaconNode { blob_data_included: bool, ) -> Result<()> { let what = "publish_execution_payload_envelope"; - if !self.broadcast.blocks { + if !self.broadcast.blocks && blob_data_included { return self .publish_execution_payload_envelope(body, blob_data_included) .await; @@ -996,10 +1001,8 @@ impl BeaconNodeApi for FallbackBeaconNode { if !producer_failing || !blob_data_included { let answer = node .publish_execution_payload_envelope(body, blob_data_included) - .await; - if let Err(err) = &answer { - self.health.record_request_failure(position, what, err); - } + .await + .inspect_err(|err| self.health.record_request_failure(position, what, err)); sent = Some((position, answer.is_ok())); answers.push((position, answer)); } @@ -2771,8 +2774,8 @@ mod tests { /// Under `--broadcast blocks` an envelope goes to the node that produced /// its block first, and to the rest only once that node has answered. One /// without its blobs goes to the producer alone, since only it cached - /// them. Without the flag, it is the first node in the walk that takes it, - /// as before. + /// them, with or without the flag. Without the flag, one with its blobs is + /// the first node in the walk that takes it, as before. #[tokio::test] async fn a_broadcast_envelope_goes_to_its_producer_first_then_to_the_rest() { let gate = Arc::new(tokio::sync::Semaphore::new(0)); @@ -2828,6 +2831,17 @@ mod tests { .expect("published"); assert_eq!(one_node.nodes[0].published_envelopes().len(), 1); assert!(one_node.nodes[1].published_envelopes().is_empty()); + + one_node + .publish_execution_payload_envelope_produced_by(Producer::at(1), b"bare", false) + .await + .expect("published"); + assert_eq!(one_node.nodes[0].published_envelopes().len(), 1); + assert_eq!( + one_node.nodes[1].published_envelopes(), + vec![(b"bare".to_vec(), false)], + "a body without its blobs goes to its producer without the flag too" + ); } /// Doppelganger protection's liveness query asks every node at once and diff --git a/crates/validator/src/beacon_node/health.rs b/crates/validator/src/beacon_node/health.rs index 69e0bfbff..15230e5f3 100644 --- a/crates/validator/src/beacon_node/health.rs +++ b/crates/validator/src/beacon_node/health.rs @@ -28,10 +28,11 @@ //! [`Tier`] order, best first: synced and validated; synced but optimistic //! or with its execution client offline; syncing, or more than //! [`SYNC_TOLERANCE`] slots behind by its own `sync_distance`; not probed -//! yet; failing. Command-line order breaks ties, so a single healthy node, -//! or several equally healthy ones, are asked exactly as listed. Positions -//! stay command-line positions, so a blinded block still goes back to the -//! node that produced it. +//! yet; failing. Inside the behind tier, which a stall fills with every +//! node, a node that does not report syncing goes first. Command-line order +//! breaks ties, so a single healthy node, or several equally healthy ones, +//! are asked exactly as listed. Positions stay command-line positions, so a +//! blinded block still goes back to the node that produced it. //! - **The last real request** ([`NodeHealth::record_request_failure`]). A //! request to a node that timed out or could not connect ranks it failing //! until a probe recorded after it answers, so a node that hangs costs at @@ -197,7 +198,9 @@ pub enum Tier { /// Answered within the tolerance and not syncing, but optimistic or with /// its execution client offline. Degraded, - /// Answered syncing, or more than [`SYNC_TOLERANCE`] slots behind. + /// Answered syncing, or more than [`SYNC_TOLERANCE`] slots behind. Inside + /// it, a node that does not report syncing goes first (see + /// [`NodeHealth::ranked`]). Behind, /// Not probed yet, or its last probe is too old to read. Unknown, @@ -466,9 +469,11 @@ impl NodeHealth { } /// Every position in the order requests walk the nodes in, with each - /// node's standing: by [`Tier`], best first, command-line order breaking - /// ties. With no probe held and no request failed, every node is - /// [`Tier::Unknown`], so it is plain command-line order. + /// node's standing: by [`Tier`], best first, then inside a tier syncing + /// last and optimistic or `el_offline` after the rest (which only reorders + /// [`Tier::Behind`]), command-line order breaking ties. With no probe held + /// and no request failed, every node is [`Tier::Unknown`], so it is plain + /// command-line order. /// /// The standing is the probe's alone, whatever the tier: a node ranked /// failing for a request it did not answer still reads as synced to the @@ -492,7 +497,7 @@ impl NodeHealth { fn ranking_at(&self, now: SystemTime) -> Vec<(usize, Standing, Tier)> { let read_for = self.read_for.get().copied(); let records = self.read(); - let mut ranking: Vec<(usize, Standing, Tier)> = records + let mut ranking: Vec<(usize, Standing, Tier, (bool, bool))> = records .iter() .enumerate() .map(|(position, record)| { @@ -510,13 +515,16 @@ impl NodeHealth { } else { probe.map_or(Tier::Unknown, Tier::of) }; - (position, standing, tier) + (position, standing, tier, within_tier(probe)) }) .collect(); // Stable, and keyed on the position too, so ties keep command-line // order whatever order the records were written in. - ranking.sort_by_key(|&(position, _, tier)| (tier, position)); + ranking.sort_by_key(|&(position, _, tier, within)| (tier, within, position)); ranking + .into_iter() + .map(|(position, standing, tier, _)| (position, standing, tier)) + .collect() } /// How the probes taken for `slot` split. A node whose last probe was taken @@ -553,6 +561,18 @@ fn is_lagging(probe: &Probe) -> bool { matches!(&probe.outcome, Ok(status) if !status.is_syncing && status.is_behind()) } +/// What orders the nodes of one [`Tier`], before command-line order: one that +/// reports syncing last, and one optimistic or with its execution client +/// offline after the rest, as Lighthouse orders them inside each distance +/// tier. Only [`Tier::Behind`] mixes them: once a stall puts every node past +/// the tolerance, a synced node still goes ahead of a syncing one. +fn within_tier(probe: Option<&Probe>) -> (bool, bool) { + match probe.map(|probe| &probe.outcome) { + Some(Ok(status)) => (status.is_syncing, status.is_optimistic || status.el_offline), + _ => (false, false), + } +} + fn is_stale(at: SystemTime, read_for: Option, now: SystemTime) -> bool { read_for.is_some_and(|limit| now.duration_since(at).unwrap_or_default() > limit) } @@ -851,6 +871,30 @@ mod tests { assert_eq!(order(&both), vec![1, 0]); } + /// In a stall every node is past the tolerance and shares the behind tier. + /// Inside it, a node that reports syncing still goes after one that does + /// not, and an optimistic one after a validated one, whatever the list + /// order. + #[test] + fn inside_the_behind_tier_a_syncing_node_goes_last() { + let stalled = |is_syncing, is_optimistic| { + probe( + 3, + Ok(SyncStatus { + sync_distance: Some(SYNC_TOLERANCE + 2), + ..status(is_syncing, is_optimistic) + }), + ) + }; + let health = health(vec![ + stalled(true, false), + stalled(false, true), + stalled(false, false), + ]); + assert_eq!(order(&health), vec![2, 1, 0]); + assert!(health.tiers().iter().all(|&(_, tier)| tier == Tier::Behind)); + } + /// An optimistic node, or one whose execution client is offline, ranks /// below a synced one and above a syncing one. #[test] diff --git a/crates/validator/src/beacon_node/mod.rs b/crates/validator/src/beacon_node/mod.rs index 89a50440b..3ed2f62e5 100644 --- a/crates/validator/src/beacon_node/mod.rs +++ b/crates/validator/src/beacon_node/mod.rs @@ -676,7 +676,9 @@ pub trait BeaconNodeApi: Send + Sync { /// /// A single node has no one to choose and ignores `producer`, which is /// the default. The fallback reads it under `--broadcast blocks`, to send - /// the envelope to the producing node first. + /// the envelope to the producing node first, and for a body without its + /// blobs, with or without the flag, to send it to the producing node + /// alone, the one that cached them. async fn publish_execution_payload_envelope_produced_by( &self, producer: Producer, diff --git a/docs/cli.md b/docs/cli.md index 279447553..dcdff2e60 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -372,7 +372,7 @@ implementation's, so none of the [common flags](#common-flags) apply to it. | Flag | Default | Meaning | |---|---|---| | `--beacon-nodes` | required | Base URLs of the beacon nodes to use, comma-separated or repeated. Every node is asked `/eth/v1/node/syncing` once a slot and ranked by the answer, list order breaking ties. The first that answers serves the request, so the order is a preference, not load balancing. See [The per-slot sync check](#the-per-slot-sync-check) and [Ranking and broadcast](#ranking-and-broadcast) | -| `--broadcast` | none | Signed messages to send to every beacon node at once instead of the first that accepts them, comma-separated: `attestations` (attestations, aggregates, payload attestations), `blocks` (blocks and envelopes, never a blinded block), `sync-committee` (messages and contributions). `subscriptions` is accepted and changes nothing, since subscriptions, fee recipients, builder registrations and proposer preferences always go to every node. See [Ranking and broadcast](#ranking-and-broadcast) | +| `--broadcast` | none | Signed messages to send to every beacon node at once instead of the first that accepts them, comma-separated: `attestations` (attestations, aggregates, payload attestations), `blocks` (blocks and envelopes, never a blinded block), `sync-committee` (messages and contributions). `subscriptions` and `none` are accepted, as Lighthouse takes them, and change nothing, since subscriptions, fee recipients, builder registrations and proposer preferences always go to every node. See [Ranking and broadcast](#ranking-and-broadcast) | | `--validators-dir` | required | Directory holding the EIP-2335 keystores and `validator_definitions.yml`, which also lists the keys a remote signer holds (see [Remote signing](#remote-signing-web3signer)). Without that file, keystores in the Lighthouse layout (`<0xpubkey>/voting-keystore.json`, password in `--secrets-dir/<0xpubkey>`) are discovered and the file is written | | `--secrets-dir` | required | Directory holding one password file per keystore, named after the validator's public key | | `--http-address` | `127.0.0.1` | Bind address for the metrics and keymanager servers | @@ -599,11 +599,14 @@ best first, as Lighthouse ranks its nodes: 5. failing: it did not answer its last probe, or since then did not answer a request. -`--beacon-nodes` order breaks ties, so a single healthy node, or several -equally healthy ones, are asked exactly as listed. Lighthouse's finer tiers -(16 and 64 slots behind) are not kept: they only reorder nodes that are all -behind, which in practice means a stalled network, where every node is behind -by about as much. +Inside a tier, a node that reports syncing goes last, and an optimistic one +or one with its execution client offline after the rest. That only reorders +tier 3, which a stalled network fills with every node, so a synced node is +still asked ahead of a syncing one there. `--beacon-nodes` order breaks ties, +so a single healthy node, or several equally healthy ones, are asked exactly +as listed. Lighthouse's finer tiers (16 and 64 slots behind) are not kept: +they only reorder nodes that are all behind, which in practice means a stalled +network, where every node is behind by about as much. A request that times out, or whose connection cannot be made, ranks its node failing at once, until a later probe answers. So a node that takes requests @@ -622,8 +625,8 @@ mesh: `attestations` (attestations, aggregates, payload attestations), contributions), comma-separated. None by default, as in Lighthouse, so the client behaves as before unless asked. Subscriptions, fee recipient preparations, builder registrations and proposer preferences always go to -every node; `subscriptions` is accepted for compatibility and changes -nothing. +every node; `subscriptions` and `none` are accepted for compatibility and +change nothing. - **One accepting node is success.** A message one node took is on the network. A node that refused is logged. @@ -638,7 +641,7 @@ nothing. block the envelope reveals; a node that has not imported it yet queues or drops the envelope, and waiting for the producer's answer gives each a round trip longer to import it. An envelope sent without its blobs goes to - the producer alone, since only it cached them. + the producer alone, since only it cached them, with or without the flag. - **Signed once.** Every message is signed, and recorded by slashing protection, before it is sent, however many nodes it is sent to. From f92a870f58dd9b9bcf8d5ffeaba393137f4447fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:59:32 -0300 Subject: [PATCH 06/12] fix(validator): stop a broadcast waiting on a hung node, keep the bare envelope's failover A broadcast waited for every node not ranked failing. A node hanging on publish_block for the first time held it past the proposal's deadline, which cut the whole publish: the proposal read as failed, the self-built envelope was skipped, and the hung node's timeout was never recorded, so the next proposal waited on it again. Once a node accepts, a broadcast now waits at most half a second more; a node still sending is cut off and ranked failing. An envelope without its blobs went to its producer alone. A block with no blobs can be revealed through any node, so a producer that does not take it is now followed by the walk, with or without --broadcast. A request failure is cleared only by a probe sent after it, not by one already on its way when the request failed. --- CLAUDE.md | 2 +- crates/validator/src/beacon_node/fallback.rs | 173 ++++++++++++++----- crates/validator/src/beacon_node/health.rs | 67 +++++-- crates/validator/src/beacon_node/mod.rs | 3 +- docs/cli.md | 10 +- 5 files changed, 191 insertions(+), 64 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index fb7808e30..a6de6afcb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -949,7 +949,7 @@ transitions are in `ethlambda-types`, per the section above. Nothing above nodes by `health::Tier` (synced; optimistic or `el_offline`; syncing or `sync_distance` > 8; unprobed; failing), `--beacon-nodes` order breaking ties, and a request that timed out or could not connect ranks its node - failing until a later probe answers; and the head root and PTC data are + failing until a probe sent after it answers; and the head root and PTC data are never asked of a node whose last probe said syncing or optimistic, or got no answer. No rule that stops a duty reads the head's age. `--broadcast` (`fallback::Broadcast`) sends attestations, blocks (envelopes producer diff --git a/crates/validator/src/beacon_node/fallback.rs b/crates/validator/src/beacon_node/fallback.rs index b16e67b2d..51823bbc9 100644 --- a/crates/validator/src/beacon_node/fallback.rs +++ b/crates/validator/src/beacon_node/fallback.rs @@ -10,8 +10,8 @@ //! then failing ones. Command-line order breaks ties, so a single healthy node, //! or several equally healthy ones, are asked exactly as listed. The probe that //! feeds it runs once a slot ([`super::health::run`]), and a request that times -//! out or cannot connect ranks its node failing at once, until a later probe -//! answers ([`NodeHealth::record_request_failure`]): a hung node costs one +//! out or cannot connect ranks its node failing at once, until a probe sent +//! after it answers ([`NodeHealth::record_request_failure`]): a hung node costs one //! request timeout per probe, not one per request. //! //! The nodes themselves stay in command-line order, and only a list of @@ -66,6 +66,14 @@ use crate::error::{Error, Result}; /// to `Self`. type BoxFuture<'a, T> = Pin + Send + 'a>>; +/// How long a broadcast waits for the nodes still sending once one node has +/// accepted. The message is on the network by then, and a caller with a +/// deadline (a proposal's is the attestation offset, 3 s into a 12 s gloas +/// slot) would otherwise wait out a hung node's whole request timeout, be cut +/// at its deadline, and never learn that node did not answer. A node still +/// sending when this runs out is cut off and ranked failing. +const BROADCAST_GRACE: Duration = Duration::from_millis(500); + /// Which nodes a request may be sent to. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Reach { @@ -464,14 +472,15 @@ impl FallbackBeaconNode { /// Send a signed message to every node at once, for `--broadcast`, and /// hand back each node's answer by its command-line position. /// - /// Every node not ranked [`Tier::Failing`] is sent it together, and the - /// call waits for all of them. The failing ones are sent it only when none - /// of the others accepted: a node that timed out on the last request or - /// probe would otherwise hold every broadcast back by a request timeout, - /// past a proposal's deadline, while a node that accepted has already put - /// the message on the network. `sent` is a position the caller has - /// already sent to itself, left out here, and whether it accepted, which - /// counts as an acceptance for that rule. + /// Every node not ranked [`Tier::Failing`] is sent it together. The call + /// waits for them until one accepts, and then at most [`BROADCAST_GRACE`] + /// longer: a node still sending by then is cut off and ranked failing. The + /// failing ones are sent it only when none of the others accepted: a node + /// that timed out on the last request or probe would otherwise hold every + /// broadcast back, while a node that accepted has already put the message + /// on the network. `sent` is a position the caller has already sent to + /// itself, left out here, and whether it accepted, which counts as an + /// acceptance for both rules. /// /// Each answer that says the node stopped answering is recorded, as the /// walk records it. What each answer means is the caller's to read. @@ -492,34 +501,68 @@ impl FallbackBeaconNode { .into_iter() .filter(|(position, _)| Some(*position) != skip) .partition(|(_, tier)| *tier == Tier::Failing); - let mut answers = self.send_to(what, first, &call).await; + let mut answers = self.send_to(what, first, accepted_already, &call).await; if !accepted_already && !answers.iter().any(|(_, answer)| answer.is_ok()) { - answers.extend(self.send_to(what, failing, &call).await); + answers.extend(self.send_to(what, failing, false, &call).await); } answers } - /// Send to the nodes at `positions` at once and record each node that did - /// not answer. + /// Send to the nodes at `positions` at once, and record each node that did + /// not answer. Waits for every send until one accepts (or from the start, + /// when `accepted` says one already has), then at most + /// [`BROADCAST_GRACE`] for the rest, which are then dropped and recorded + /// as not answering. async fn send_to<'p, T, F>( &'p self, what: &'static str, positions: Vec<(usize, Tier)>, + accepted: bool, call: &F, ) -> Vec<(usize, Result)> where F: Fn(&'p B) -> BoxFuture<'p, Result>, { - let sends = positions.into_iter().filter_map(|(position, _)| { - let send = call(self.nodes.get(position)?); - Some(async move { - let answer = send - .await - .inspect_err(|err| self.health.record_request_failure(position, what, err)); - (position, answer) + use futures_util::StreamExt as _; + + let mut outstanding: Vec = Vec::new(); + let mut sends: futures_util::stream::FuturesUnordered<_> = positions + .into_iter() + .filter_map(|(position, _)| { + let send = call(self.nodes.get(position)?); + outstanding.push(position); + Some(async move { + let answer = send + .await + .inspect_err(|err| self.health.record_request_failure(position, what, err)); + (position, answer) + }) }) - }); - futures_util::future::join_all(sends).await + .collect(); + let mut grace_ends = accepted.then(|| tokio::time::Instant::now() + BROADCAST_GRACE); + let mut answers = Vec::new(); + loop { + let next = match grace_ends { + None => sends.next().await, + Some(ends) => match tokio::time::timeout_at(ends, sends.next()).await { + Ok(next) => next, + Err(_) => break, + }, + }; + let Some((position, answer)) = next else { + break; + }; + outstanding.retain(|&waiting| waiting != position); + if answer.is_ok() && grace_ends.is_none() { + grace_ends = Some(tokio::time::Instant::now() + BROADCAST_GRACE); + } + answers.push((position, answer)); + } + for position in outstanding { + debug!(%what, position, "Beacon node had not answered a broadcast another node accepted; not waiting for it"); + self.health.record_no_answer(position, what); + } + answers } /// A broadcast's answers read as one: the best accepted answer by @@ -970,11 +1013,14 @@ impl BeaconNodeApi for FallbackBeaconNode { /// then. It succeeds when any node accepted. /// /// Two exceptions. A body without its blobs (`blob_data_included: false`) - /// goes to the producer alone, whatever its rank, since only it cached - /// them at production time. And for a body with them, a producer ranked - /// failing (it did not answer a request since its last probe, the block's - /// own publish perhaps) is not waited on first: it is one of the failing - /// nodes the broadcast reaches only if no other node accepts. + /// goes to the producer first, whatever its rank and with or without the + /// flag, since only it cached the blobs at production time; if it does + /// not take it, the walk follows, as without the flag, since a block with + /// no blobs can be revealed through any node. And for a body with them, a + /// producer ranked failing (it did not answer a request since its last + /// probe, the block's own publish perhaps) is not waited on first: it is + /// one of the failing nodes the broadcast reaches only if no other node + /// accepts. async fn publish_execution_payload_envelope_produced_by( &self, producer: Producer, @@ -994,26 +1040,35 @@ impl BeaconNodeApi for FallbackBeaconNode { self.nodes.len() )) })?; + if !blob_data_included { + let answer = node + .publish_execution_payload_envelope(body, false) + .await + .inspect_err(|err| self.health.record_request_failure(position, what, err)); + let Err(err) = answer else { + return Ok(()); + }; + debug!(%what, position, %err, "The producer did not take its envelope; trying the walk"); + return self.publish_execution_payload_envelope(body, false).await; + } let producer_failing = self.health.tiers().contains(&(position, Tier::Failing)); let mut answers = Vec::new(); let mut sent = None; - if !producer_failing || !blob_data_included { + if !producer_failing { let answer = node - .publish_execution_payload_envelope(body, blob_data_included) + .publish_execution_payload_envelope(body, true) .await .inspect_err(|err| self.health.record_request_failure(position, what, err)); sent = Some((position, answer.is_ok())); answers.push((position, answer)); } - if blob_data_included { - let rest = self - .broadcast_to_all(what, sent, |node| { - node.publish_execution_payload_envelope(body, blob_data_included) - }) - .await; - answers.extend(rest); - } + let rest = self + .broadcast_to_all(what, sent, |node| { + node.publish_execution_payload_envelope(body, true) + }) + .await; + answers.extend(rest); Self::best_answer(what, answers, |_, _| false) } @@ -2570,12 +2625,14 @@ mod tests { ); } - /// The issue's broadcast test: answers of 202, a timeout and 200 report - /// the 200, wherever it is in the list, and every node that answered got - /// the same body. The node that timed out is ranked failing from then on, - /// so the next broadcast does not wait for it. + /// The issue's broadcast test: answers of 202, a hang and 200 report the + /// 200, wherever it is in the list, and every node that answered got the + /// same body. The hung node is not waited for past the grace, so a caller + /// with a deadline shorter than the request timeout, as a proposal has, + /// still gets the answer; it is ranked failing from then on, so the next + /// broadcast does not wait for it at all. #[tokio::test(start_paused = true)] - async fn a_broadcast_block_answered_202_a_timeout_and_200_reports_the_200() { + async fn a_broadcast_block_answered_202_a_hang_and_200_reports_the_200() { use std::time::Duration; let fallback = FallbackBeaconNode::new(vec![ MockBeaconNode::new().with_publish_outcome(Published::BroadcastNotImported), @@ -2587,11 +2644,14 @@ mod tests { ..Broadcast::default() }); - let outcome = fallback - .publish_block(ForkName::Electra, b"body") - .await - .expect("two nodes took it"); + let deadline = TIMEOUT / 4; + let outcome = + tokio::time::timeout(deadline, fallback.publish_block(ForkName::Electra, b"body")) + .await + .expect("answered before a deadline shorter than the hang") + .expect("two nodes took it"); assert_eq!(outcome, Published::Imported); + assert_eq!(fallback.health().tiers()[2], (1, Tier::Failing)); for position in [0, 2] { assert_eq!( fallback.nodes[position].published_blocks(), @@ -2842,6 +2902,25 @@ mod tests { vec![(b"bare".to_vec(), false)], "a body without its blobs goes to its producer without the flag too" ); + + // A producer that does not take it is followed by the walk: a block + // with no blobs can be revealed through any node. + let refusing = || { + MockBeaconNode::new() + .failing_call("publish_execution_payload_envelope", "no cached blobs") + }; + for broadcast in [Broadcast::default(), blocks] { + let fallback = FallbackBeaconNode::new(vec![MockBeaconNode::new(), refusing()]) + .with_broadcast(broadcast); + fallback + .publish_execution_payload_envelope_produced_by(Producer::at(1), b"bare", false) + .await + .expect("the other node takes it"); + assert_eq!( + fallback.nodes[0].published_envelopes(), + vec![(b"bare".to_vec(), false)] + ); + } } /// Doppelganger protection's liveness query asks every node at once and diff --git a/crates/validator/src/beacon_node/health.rs b/crates/validator/src/beacon_node/health.rs index 15230e5f3..6da4ca5b4 100644 --- a/crates/validator/src/beacon_node/health.rs +++ b/crates/validator/src/beacon_node/health.rs @@ -35,7 +35,7 @@ //! blinded block still goes back to the node that produced it. //! - **The last real request** ([`NodeHealth::record_request_failure`]). A //! request to a node that timed out or could not connect ranks it failing -//! until a probe recorded after it answers, so a node that hangs costs at +//! until a probe sent after it answers, so a node that hangs costs at //! most one request timeout per probe, not one per request. //! - **Two calls the Beacon API leaves ungated.** No 503 covers a syncing //! node's head root, or an optimistic node's payload attestation data, so the @@ -222,7 +222,7 @@ impl Tier { } /// A request to a node that got no answer, which ranks the node -/// [`Tier::Failing`] until a probe recorded after it answers. +/// [`Tier::Failing`] until a probe sent after it answers. #[derive(Debug, Clone, PartialEq, Eq)] struct RequestFailure { at: SystemTime, @@ -325,12 +325,22 @@ impl NodeHealth { /// Keep that a request to the node at `position` failed with `err`, when /// that failure says the node is not answering ([`ranks_failing`]): the - /// node then ranks [`Tier::Failing`] until a probe recorded after this + /// node then ranks [`Tier::Failing`] until a probe sent after this /// answers. Logged once, when the node starts being passed over. pub fn record_request_failure(&self, position: usize, what: &'static str, err: &Error) { - if !ranks_failing(err) { - return; + if ranks_failing(err) { + self.mark_failing(position, what, err); } + } + + /// Keep that the node at `position` had not answered a broadcast by the + /// time the broadcast stopped waiting for it, a moment after another node + /// accepted: it ranks [`Tier::Failing`] as for a request that timed out. + pub fn record_no_answer(&self, position: usize, what: &'static str) { + self.mark_failing(position, what, &"no answer while another node accepted"); + } + + fn mark_failing(&self, position: usize, what: &'static str, err: &dyn std::fmt::Display) { let already = { let mut records = self.write(); let Some(record) = records.get_mut(position) else { @@ -383,11 +393,13 @@ impl NodeHealth { let Some(record) = records.get_mut(position) else { return; }; - let cleared = if answered { - record.failure.take().is_some() - } else { - false - }; + // Only by a probe sent after the failure: one already on its way + // when the request failed says nothing about the node since. + let cleared = answered + && record + .failure + .take_if(|failure| probe.at >= failure.at) + .is_some(); let was_el_offline = record.el_offline; if answered { record.el_offline = el_offline; @@ -563,9 +575,9 @@ fn is_lagging(probe: &Probe) -> bool { /// What orders the nodes of one [`Tier`], before command-line order: one that /// reports syncing last, and one optimistic or with its execution client -/// offline after the rest, as Lighthouse orders them inside each distance -/// tier. Only [`Tier::Behind`] mixes them: once a stall puts every node past -/// the tolerance, a synced node still goes ahead of a syncing one. +/// offline after the rest. Only [`Tier::Behind`] mixes them: once a stall +/// puts every node past the tolerance, a synced node still goes ahead of a +/// syncing one. fn within_tier(probe: Option<&Probe>) -> (bool, bool) { match probe.map(|probe| &probe.outcome) { Some(Ok(status)) => (status.is_syncing, status.is_optimistic || status.el_offline), @@ -959,6 +971,35 @@ mod tests { assert_eq!(order(&health), vec![1, 0]); } + /// A probe already on its way when the request failed, answered after it, + /// says nothing about the node since, and leaves it failing; one sent + /// after the failure clears it. + #[test] + fn only_a_probe_sent_after_a_request_failure_clears_it() { + let health = health(vec![synced(3), synced(3)]); + let sent_before = SystemTime::now() - Duration::from_secs(1); + health.record_request_failure(0, "attestation_data", &failed(BeaconNodeFailure::Timeout)); + health.record( + 0, + Probe { + at: sent_before, + ..synced(4) + }, + ); + assert_eq!(order(&health), vec![1, 0], "still failing"); + health.record(0, synced(5)); + assert_eq!(order(&health), vec![0, 1]); + } + + /// A broadcast that stopped waiting for a node ranks it failing, as a + /// timed-out request does. + #[test] + fn a_node_cut_off_by_a_broadcast_ranks_failing() { + let health = health(vec![synced(3), synced(3)]); + health.record_no_answer(0, "publish_block"); + assert_eq!(health.tiers()[1], (0, Tier::Failing)); + } + /// A request failure is read for as long as a probe is: a probe task that /// stopped leaves every node back in command-line order. #[test] diff --git a/crates/validator/src/beacon_node/mod.rs b/crates/validator/src/beacon_node/mod.rs index 3ed2f62e5..d04b25d02 100644 --- a/crates/validator/src/beacon_node/mod.rs +++ b/crates/validator/src/beacon_node/mod.rs @@ -678,7 +678,8 @@ pub trait BeaconNodeApi: Send + Sync { /// the default. The fallback reads it under `--broadcast blocks`, to send /// the envelope to the producing node first, and for a body without its /// blobs, with or without the flag, to send it to the producing node - /// alone, the one that cached them. + /// first, the one that cached them, and to the others only if it does not + /// take it. async fn publish_execution_payload_envelope_produced_by( &self, producer: Producer, diff --git a/docs/cli.md b/docs/cli.md index dcdff2e60..841632c48 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -609,7 +609,7 @@ they only reorder nodes that are all behind, which in practice means a stalled network, where every node is behind by about as much. A request that times out, or whose connection cannot be made, ranks its node -failing at once, until a later probe answers. So a node that takes requests +failing at once, until a probe sent after it answers. So a node that takes requests and never answers costs one request timeout (8 s) and then nothing until it answers again, rather than a timeout on every request: an attestation duty used to wait out the whole timeout on a hung first node every slot, which @@ -633,6 +633,10 @@ change nothing. - **Failing nodes are sent it last.** A node ranked failing is sent a broadcast only when no other node took it, so a hung node does not hold every broadcast back by a request timeout. +- **Half a second after the first acceptance, the rest are cut off.** A node + still sending by then is not waited for and is ranked failing, so a node + that hangs for the first time costs a broadcast half a second, not a + request timeout a proposal's deadline would cut short. - **A block reports the best answer**: imported (`200`) over broadcast but not imported (`202`) over refused, each node's answer logged. A blinded block still goes only to the node that produced it. @@ -641,7 +645,9 @@ change nothing. block the envelope reveals; a node that has not imported it yet queues or drops the envelope, and waiting for the producer's answer gives each a round trip longer to import it. An envelope sent without its blobs goes to - the producer alone, since only it cached them, with or without the flag. + the producer first, with or without the flag, since only it cached them; + if it does not take it, the other nodes are tried in rank order, since a + block with no blobs can be revealed through any of them. - **Signed once.** Every message is signed, and recorded by slashing protection, before it is sent, however many nodes it is sent to. From dd613c209300d2100169c25307f71205dfc59d0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:11:00 -0300 Subject: [PATCH 07/12] feat(validator): make /health report whether the client can do its duties The validator client's /health always answered 200 with a constant body, so a client whose beacon nodes were all down or syncing, or whose slashing-protection writes kept failing, looked healthy to every probe. client_health::ClientHealth holds what the endpoint reads, all of it state the client already keeps, and makes no beacon node request of its own. /health now answers 200 when the client can do its duties and 503 when it cannot, with status, service and four checks: - beacon_nodes {usable, configured}: usable counts the nodes whose latest sync probe (beacon_node::health) answered neither syncing nor optimistic and is at most two slots old. One is enough. - validators {loaded, resolved}: reported, never failing. loaded is read from the key store with try_read, falling back to the last count. - slashing_protection {last_write_ok}: SharedProtection::last_write_ok, two atomics beside the record's mutex. commit() sets the write flag from file::write's outcome; blocking() sets the wait flag on a RECORD_WAIT timeout and clears it when it reaches the record. A failed write fails the check until a later write succeeds. - started: the duty loop marks the first successful refresh_epoch. status is healthy (200), starting (503: not started, nothing else failed; a node not probed yet does not count against a client that has not started) or unhealthy (503). beacon_node_available is now set on every /metrics scrape from the same report, as is the new ethlambda_validator_healthy gauge and validators_loaded, so a gauge and the endpoint read one answer. Its old writers in the duty loop and the sync gate are gone. docs/cli.md documents the endpoint and docs/metrics.md the metric changes. --- crates/validator/src/beacon_node/health.rs | 1 - crates/validator/src/client_health.rs | 669 ++++++++++++++++++ crates/validator/src/lib.rs | 28 +- crates/validator/src/metrics.rs | 51 +- .../validator/src/slashing_protection/mod.rs | 132 +++- docs/cli.md | 54 ++ docs/metrics.md | 5 +- 7 files changed, 912 insertions(+), 28 deletions(-) create mode 100644 crates/validator/src/client_health.rs diff --git a/crates/validator/src/beacon_node/health.rs b/crates/validator/src/beacon_node/health.rs index 6da4ca5b4..bb3217f19 100644 --- a/crates/validator/src/beacon_node/health.rs +++ b/crates/validator/src/beacon_node/health.rs @@ -612,7 +612,6 @@ pub fn slot_signs(health: &NodeHealth, slot: Slot) -> bool { signing nothing in this slot" ); crate::metrics::inc_slots_skipped_syncing(); - crate::metrics::set_beacon_node_available(false); false } diff --git a/crates/validator/src/client_health.rs b/crates/validator/src/client_health.rs new file mode 100644 index 000000000..5b1f4e2b8 --- /dev/null +++ b/crates/validator/src/client_health.rs @@ -0,0 +1,669 @@ +//! What `/health` answers: whether this client can do its duties now. +//! +//! # Cheap and local +//! +//! [`ClientHealth::report`] reads state the client already keeps and asks no +//! beacon node anything: each node's latest sync probe +//! ([`crate::beacon_node::health`]), the key store, the last duty refresh and +//! the slashing-protection record's last write. Nothing in it waits on a lock. +//! The key store is read with `try_read`, falling back to the last count read, +//! since a keymanager import holds it while it decrypts a batch. The record's +//! outcome is read from two atomics beside its mutex, which the stuck write +//! being reported would be holding. +//! +//! # The checks +//! +//! - **`beacon_nodes`**: `usable` counts the nodes whose latest probe was +//! answered, neither syncing nor optimistic, and is at most two slots old, +//! out of the `configured` ones. One usable node passes. A probe older than +//! that means the probe task stopped, which leaves nothing to vouch for the +//! node. +//! - **`validators`**: `loaded` and `resolved`, reported and never failing. A +//! key waiting for activation has no index, and a client started with no +//! keys to wait for a keymanager import is idle on purpose; neither is +//! fixed by restarting it or taking it out of rotation. A key doppelganger +//! protection still withholds counts as loaded. +//! - **`slashing_protection.last_write_ok`**: the record's last write +//! succeeded and the last access did not give up waiting for it (see +//! [`SharedProtection::last_write_ok`]). A failed write fails the check +//! until a later write succeeds. +//! - **`started`**: a duty refresh has succeeded since the process started. +//! +//! # Status +//! +//! - `healthy`, `200`: started, at least one usable node, and the record's +//! last write went through. +//! - `starting`, `503`: not started yet, and nothing else has failed. A node +//! not probed yet does not count against the client before it starts, so a +//! normal startup reads `starting` throughout rather than `unhealthy`. Once +//! started, a node with no probe counts as unusable: the first refresh runs +//! at the boundary the first probe was taken ahead of, so a node with no +//! record by then has not answered it, or the probe task is not running. +//! Without that, a probe task that never ran would leave the client +//! `healthy` with nothing to vouch for a node. +//! - `unhealthy`, `503`: anything else. +//! +//! A client with some nodes unusable and at least one usable is `healthy`, +//! with the counts in the body. +//! +//! The same report sets `ethlambda_validator_healthy`, +//! `ethlambda_validator_beacon_node_available` and +//! `ethlambda_validator_validators_loaded` on every scrape of `/metrics` (see +//! [`publish`]), so an alert on a gauge and a probe of the endpoint read one +//! answer. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock}; +use std::time::{Duration, SystemTime}; + +use axum::http::StatusCode; +use serde::Serialize; +use tokio::sync::RwLock; + +use crate::beacon_node::health::{NodeHealth, Probe, Standing}; +use crate::keys::ValidatorStore; +use crate::slashing_protection::SharedProtection; + +/// What every report names as its `service`. +pub const SERVICE: &str = "ethlambda-validator"; + +/// How many slots a node's latest probe is read for. Probes are a slot +/// apart, so only a probe task that stopped leaves one this old; the same +/// bound the fallback reads probes for when it routes. +const PROBE_READ_SLOTS: u32 = 2; + +/// The state `/health` reads, shared by the metrics server, which reports it, +/// and the duty loop, which keeps it. +pub struct ClientHealth { + /// How many beacon nodes were configured, known before any is reached. + configured: usize, + store: Arc>, + /// The last count read from `store`, answered while a writer holds it. + loaded: AtomicU64, + /// Validators the last successful refresh resolved to an index. + resolved: AtomicU64, + /// A duty refresh has succeeded. + started: AtomicBool, + /// Set once the beacon nodes and the record exist, which is after the + /// metrics server is already answering. + attached: OnceLock, +} + +struct Attached { + nodes: Arc, + /// How old a probe may be and still be read. + read_for: Duration, + protection: SharedProtection, +} + +impl ClientHealth { + /// The state of a client that has done nothing yet: `starting`, with + /// `configured` beacon nodes none of which is probed, and `store`'s keys. + pub fn new(configured: usize, store: Arc>) -> Self { + let loaded = store.try_read().map_or(0, |store| store.len() as u64); + Self { + configured, + store, + loaded: AtomicU64::new(loaded), + resolved: AtomicU64::new(0), + started: AtomicBool::new(false), + attached: OnceLock::new(), + } + } + + /// Read the beacon nodes' probes from `nodes`, judging a probe stale past + /// two of `slot_duration`, and the record's last write from `protection`. + /// Called once; a second call changes nothing. + pub fn attach( + &self, + nodes: Arc, + slot_duration: Duration, + protection: SharedProtection, + ) { + let _ = self.attached.set(Attached { + nodes, + read_for: slot_duration * PROBE_READ_SLOTS, + protection, + }); + } + + /// A duty refresh succeeded, resolving `resolved` validators to an index. + /// The first one is what moves the client from `starting`. + pub fn epoch_refreshed(&self, resolved: usize) { + self.resolved.store(resolved as u64, Ordering::Relaxed); + self.started.store(true, Ordering::Relaxed); + } + + /// What `/health` answers now. + pub fn report(&self) -> Report { + self.report_at(SystemTime::now()) + } + + fn report_at(&self, now: SystemTime) -> Report { + let attached = self.attached.get(); + let nodes = match attached { + Some(attached) => tally(&attached.nodes.snapshot(), attached.read_for, now), + None => NodeTally { + usable: 0, + unprobed: self.configured, + }, + }; + let last_write_ok = attached.is_none_or(|attached| attached.protection.last_write_ok()); + let started = self.started.load(Ordering::Relaxed); + + let nodes_ok = nodes.usable > 0; + let status = if started && nodes_ok && last_write_ok { + Status::Healthy + } else if !started && last_write_ok && (nodes_ok || nodes.unprobed > 0) { + Status::Starting + } else { + Status::Unhealthy + }; + + Report { + status, + service: SERVICE, + checks: Checks { + beacon_nodes: BeaconNodes { + usable: nodes.usable, + configured: self.configured, + }, + validators: Validators { + loaded: self.loaded(), + resolved: self.resolved.load(Ordering::Relaxed), + }, + slashing_protection: SlashingProtectionCheck { last_write_ok }, + started, + }, + } + } + + /// How many keys the store holds, or the last count read while a writer + /// holds it. + fn loaded(&self) -> u64 { + match self.store.try_read() { + Ok(store) => { + let loaded = store.len() as u64; + self.loaded.store(loaded, Ordering::Relaxed); + loaded + } + Err(_) => self.loaded.load(Ordering::Relaxed), + } + } +} + +/// How the configured nodes split, as the report reads them. +#[derive(Debug, Default, PartialEq, Eq)] +struct NodeTally { + /// Latest probe answered, neither syncing nor optimistic, and readable. + usable: usize, + /// No probe recorded yet. + unprobed: usize, +} + +fn tally(probes: &[Option], read_for: Duration, now: SystemTime) -> NodeTally { + let mut tally = NodeTally::default(); + for probe in probes { + match probe { + None => tally.unprobed += 1, + Some(probe) if is_usable(probe, read_for, now) => tally.usable += 1, + Some(_) => {} + } + } + tally +} + +fn is_usable(probe: &Probe, read_for: Duration, now: SystemTime) -> bool { + let age = now.duration_since(probe.at).unwrap_or_default(); + age <= read_for && probe.standing() == Standing::Synced +} + +/// Set the gauges that mirror `report`: `ethlambda_validator_healthy`, +/// `ethlambda_validator_beacon_node_available` and +/// `ethlambda_validator_validators_loaded`. The metrics server calls this on +/// every scrape, before it gathers, so the series read what `/health` would +/// have answered at that moment. +pub fn publish(report: &Report) { + crate::metrics::set_healthy(report.is_healthy()); + crate::metrics::set_beacon_node_available(report.beacon_node_available()); + crate::metrics::set_validators_loaded(report.checks.validators.loaded); +} + +/// `/health`'s body. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Report { + pub status: Status, + pub service: &'static str, + pub checks: Checks, +} + +impl Report { + /// The client can do its duties. + pub fn is_healthy(&self) -> bool { + self.status == Status::Healthy + } + + /// `200` when healthy, `503` otherwise, starting included. + pub fn status_code(&self) -> StatusCode { + if self.is_healthy() { + StatusCode::OK + } else { + StatusCode::SERVICE_UNAVAILABLE + } + } + + /// At least one configured beacon node is usable: what + /// `ethlambda_validator_beacon_node_available` reports. + pub fn beacon_node_available(&self) -> bool { + self.checks.beacon_nodes.usable > 0 + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Status { + Healthy, + Starting, + Unhealthy, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Checks { + pub beacon_nodes: BeaconNodes, + pub validators: Validators, + pub slashing_protection: SlashingProtectionCheck, + pub started: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct BeaconNodes { + pub usable: usize, + pub configured: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Validators { + pub loaded: u64, + pub resolved: u64, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct SlashingProtectionCheck { + pub last_write_ok: bool, +} + +#[cfg(test)] +mod tests { + use super::*; + + use crate::beacon_node::health::SyncStatus; + use crate::slashing_protection::SlashingProtection; + + const SLOT: Duration = Duration::from_secs(12); + + fn status(is_syncing: bool, is_optimistic: bool) -> SyncStatus { + SyncStatus { + head_slot: Some(100), + sync_distance: Some(0), + is_syncing, + is_optimistic, + el_offline: false, + } + } + + fn probe(outcome: Result) -> Probe { + Probe { + slot: 10, + at: SystemTime::now(), + outcome, + } + } + + fn synced() -> Probe { + probe(Ok(status(false, false))) + } + + fn syncing() -> Probe { + probe(Ok(status(true, false))) + } + + fn optimistic() -> Probe { + probe(Ok(status(false, true))) + } + + fn down() -> Probe { + probe(Err("connection refused".to_string())) + } + + fn store_of(keys: u8) -> Arc> { + let mut store = ValidatorStore::new(); + for key in 1..=keys { + store + .insert_secret("test", &[key; 32]) + .expect("a valid secret"); + } + Arc::new(RwLock::new(store)) + } + + /// A client with `nodes` beacon nodes and `keys` keys, attached to an + /// in-memory record, before any probe or refresh. + fn client(nodes: usize, keys: u8) -> (ClientHealth, Arc) { + let health = ClientHealth::new(nodes, store_of(keys)); + let probes = Arc::new(NodeHealth::new(nodes)); + health.attach(probes.clone(), SLOT, SlashingProtection::in_memory()); + (health, probes) + } + + /// The body is the issue's: `status`, `service` and the four checks, each + /// with exactly the fields it names. + #[test] + fn the_body_has_the_issues_shape() { + let (health, probes) = client(2, 3); + probes.record(0, synced()); + probes.record(1, down()); + health.epoch_refreshed(2); + + let body = serde_json::to_value(health.report()).expect("serializes"); + assert_eq!( + body, + serde_json::json!({ + "status": "healthy", + "service": "ethlambda-validator", + "checks": { + "beacon_nodes": { "usable": 1, "configured": 2 }, + "validators": { "loaded": 3, "resolved": 2 }, + "slashing_protection": { "last_write_ok": true }, + "started": true, + } + }) + ); + } + + /// Until the first refresh the client is `starting`, a `503`, and the + /// refresh that moves it is a real one, driven through the mock. + #[tokio::test] + async fn a_client_is_starting_until_its_first_refresh() { + use ethlambda_types::beacon::primitives::{BlsPubkey, Bytes32, Root}; + + use crate::beacon_node::ValidatorEntry; + use crate::beacon_node::fallback::FallbackBeaconNode; + use crate::beacon_node::mock::MockBeaconNode; + use crate::duties::DutiesService; + use crate::proposer_settings::ProposerSettings; + use crate::signing::SigningContext; + + let mut node = MockBeaconNode::new() + .with_duties(3, Root::repeat_byte(1), Vec::new()) + .with_duties(4, Root::repeat_byte(2), Vec::new()) + .with_proposers(3, Root::repeat_byte(1), Vec::new()); + node.validators = vec![ValidatorEntry { + index: 11, + pubkey: BlsPubkey([1; 48]), + status: "active_ongoing".to_string(), + }]; + let beacon_node = Arc::new(FallbackBeaconNode::new(vec![node])); + let health = ClientHealth::new(1, store_of(1)); + health.attach( + beacon_node.health().clone(), + SLOT, + SlashingProtection::in_memory(), + ); + + let report = health.report(); + assert_eq!(report.status, Status::Starting, "before the first probe"); + assert_eq!(report.status_code(), StatusCode::SERVICE_UNAVAILABLE); + + let slot = 3 * ethlambda_types::beacon::preset::slots_per_epoch(); + beacon_node.probe(slot, Duration::from_secs(1)).await; + let report = health.report(); + assert_eq!(report.status, Status::Starting, "probed, not refreshed"); + assert_eq!(report.checks.beacon_nodes.usable, 1); + assert!(!report.checks.started); + + let context = SigningContext::new( + ethlambda_types::beacon::config::Config::mainnet(), + Root::ZERO, + ); + let settings = ProposerSettings::new(Bytes32::ZERO, None); + let mut duties = DutiesService::new(beacon_node.clone(), Vec::new()); + let refreshed = crate::refresh_epoch( + &beacon_node, + &mut duties, + &[BlsPubkey([1; 48])], + 3, + &settings, + &context, + ) + .await + .expect("the refresh passes on a synced node"); + // What the duty loop does with a refresh that succeeded. + health.epoch_refreshed(refreshed.resolved.len()); + + let report = health.report(); + assert_eq!(report.status, Status::Healthy); + assert_eq!(report.status_code(), StatusCode::OK); + assert!(report.checks.started); + assert_eq!(report.checks.validators.resolved, 1); + } + + /// Nothing probed yet reads `starting`, not `unhealthy`, until the client + /// has started; and before the nodes are even attached, the same. + #[test] + fn startup_before_the_first_probe_is_starting_not_unhealthy() { + let unattached = ClientHealth::new(2, store_of(1)); + let report = unattached.report(); + assert_eq!(report.status, Status::Starting); + assert_eq!(report.checks.beacon_nodes.usable, 0); + assert_eq!(report.checks.beacon_nodes.configured, 2); + + let (health, probes) = client(2, 1); + assert_eq!(health.report().status, Status::Starting); + // One node answered unusable, the other has not answered yet. + probes.record(0, down()); + assert_eq!(health.report().status, Status::Starting); + // Every node answered, none usable: the nodes are why it has not + // started. + probes.record(1, syncing()); + assert_eq!(health.report().status, Status::Unhealthy); + } + + /// Once started, a node with no probe counts as unusable: the probe task + /// should have recorded it by then. + #[test] + fn a_started_client_with_no_probe_is_unhealthy() { + let (health, _probes) = client(1, 1); + health.epoch_refreshed(1); + let report = health.report(); + assert_eq!(report.status, Status::Unhealthy); + assert_eq!(report.status_code(), StatusCode::SERVICE_UNAVAILABLE); + } + + /// Every node unusable (down, syncing or optimistic) turns the client + /// unhealthy; one coming back turns it healthy again. + #[test] + fn no_usable_node_is_unhealthy_until_one_recovers() { + let (health, probes) = client(3, 1); + health.epoch_refreshed(1); + probes.record(0, down()); + probes.record(1, syncing()); + probes.record(2, optimistic()); + let report = health.report(); + assert_eq!(report.status, Status::Unhealthy); + assert_eq!(report.checks.beacon_nodes.usable, 0); + assert!(!report.beacon_node_available()); + + probes.record(1, synced()); + let report = health.report(); + assert_eq!(report.status, Status::Healthy); + assert_eq!(report.checks.beacon_nodes.usable, 1); + assert!(report.beacon_node_available()); + } + + /// A probe past two slots old is not read: the probe task that took it + /// has stopped. + #[test] + fn a_stale_probe_does_not_count_as_usable() { + let (health, probes) = client(1, 1); + health.epoch_refreshed(1); + let taken = SystemTime::now(); + probes.record( + 0, + Probe { + at: taken, + ..synced() + }, + ); + + let fresh = health.report_at(taken + SLOT); + assert_eq!(fresh.status, Status::Healthy); + let stale = health.report_at(taken + SLOT * 3); + assert_eq!(stale.status, Status::Unhealthy); + assert_eq!(stale.checks.beacon_nodes.usable, 0); + } + + /// No keys loaded and none resolved are reported, and fail nothing: a + /// client started empty waits for a keymanager import on purpose. + #[test] + fn an_empty_store_reports_zero_loaded_and_stays_healthy() { + let (health, probes) = client(1, 0); + probes.record(0, synced()); + health.epoch_refreshed(0); + let report = health.report(); + assert_eq!(report.status, Status::Healthy); + assert_eq!( + report.checks.validators, + Validators { + loaded: 0, + resolved: 0 + } + ); + } + + /// While a writer holds the store, `loaded` is the last count read + /// rather than a wait. + #[tokio::test] + async fn a_held_store_answers_the_last_count_read() { + let store = store_of(2); + let health = ClientHealth::new(1, store.clone()); + assert_eq!(health.report().checks.validators.loaded, 2); + + let mut writer = store.write().await; + writer + .insert_secret("test", &[9; 32]) + .expect("a valid secret"); + assert_eq!(health.report().checks.validators.loaded, 2); + drop(writer); + assert_eq!(health.report().checks.validators.loaded, 3); + } + + /// A failed slashing-protection write turns the client unhealthy, and a + /// later write that succeeds turns it back. + #[cfg(unix)] + #[tokio::test] + async fn a_failed_record_write_is_unhealthy_until_a_write_succeeds() { + use std::os::unix::fs::PermissionsExt as _; + + use ethlambda_types::beacon::primitives::{BlsPubkey, Root}; + + use crate::slashing_protection::blocking; + + // SAFETY: `geteuid` reads a process attribute and cannot fail. + if unsafe { libc::geteuid() } == 0 { + eprintln!("skipped: root bypasses directory permissions"); + return; + } + let dir = tempfile::tempdir().expect("temp dir"); + let key = BlsPubkey([1; 48]); + let record = SlashingProtection::open(dir.path(), Root::ZERO, &[key], true).expect("init"); + let protection = crate::slashing_protection::SharedProtection::new(record); + let health = ClientHealth::new(1, store_of(1)); + let probes = Arc::new(NodeHealth::new(1)); + health.attach(probes.clone(), SLOT, protection.clone()); + probes.record(0, synced()); + health.epoch_refreshed(1); + assert_eq!(health.report().status, Status::Healthy); + + let read_only = std::fs::Permissions::from_mode(0o500); + std::fs::set_permissions(dir.path(), read_only).expect("chmod"); + let failed = blocking(&protection, move |record| { + record.check_and_record_block(&key, 10) + }) + .await; + let writable = std::fs::Permissions::from_mode(0o700); + std::fs::set_permissions(dir.path(), writable).expect("chmod back"); + assert!( + failed.is_err(), + "the write must fail in a read-only directory" + ); + + let report = health.report(); + assert_eq!(report.status, Status::Unhealthy); + assert!(!report.checks.slashing_protection.last_write_ok); + + blocking(&protection, move |record| { + record.check_and_record_block(&key, 10) + }) + .await + .expect("written") + .expect("slot 10 is still signable"); + let report = health.report(); + assert_eq!(report.status, Status::Healthy); + assert!(report.checks.slashing_protection.last_write_ok); + } + + /// `/health` and the two gauges a scrape of `/metrics` sets read one + /// answer, going down and coming back. The only test that touches those + /// process-wide gauges, so tests running beside it cannot move them. + #[tokio::test] + async fn the_gauges_match_the_endpoint() { + use http_body_util::BodyExt as _; + use tower::ServiceExt as _; + + async fn get(router: &axum::Router, path: &str) -> (StatusCode, String) { + let request = axum::http::Request::get(path) + .body(axum::body::Body::empty()) + .expect("a request"); + let response = router.clone().oneshot(request).await.expect("answered"); + let status = response.status(); + let body = response.into_body().collect().await.expect("a body"); + let body = String::from_utf8(body.to_bytes().to_vec()).expect("utf-8"); + (status, body) + } + + fn gauge(metrics: &str, name: &str) -> i64 { + metrics + .lines() + .find_map(|line| line.strip_prefix(name)?.strip_prefix(' ')) + .unwrap_or_else(|| panic!("{name} is exposed")) + .trim() + .parse() + .expect("an integer") + } + + crate::metrics::init(); + let (health, probes) = client(1, 1); + let health = Arc::new(health); + let router = crate::metrics::router(health.clone()); + health.epoch_refreshed(1); + + for (probe, code) in [ + (down(), StatusCode::SERVICE_UNAVAILABLE), + (synced(), StatusCode::OK), + ] { + probes.record(0, probe); + let (status, body) = get(&router, "/health").await; + assert_eq!(status, code); + let report: serde_json::Value = serde_json::from_str(&body).expect("json"); + let healthy = i64::from(code == StatusCode::OK); + assert_eq!(report["status"] == "healthy", healthy == 1); + + let (_, metrics) = get(&router, "/metrics").await; + assert_eq!(gauge(&metrics, "ethlambda_validator_healthy"), healthy); + assert_eq!( + gauge(&metrics, "ethlambda_validator_beacon_node_available"), + healthy, + "the one node is the only check that moved" + ); + } + } +} diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index f819f21bd..25f815180 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -28,6 +28,7 @@ pub mod aggregation; pub mod aggregation_selection; pub mod attestation; pub mod beacon_node; +pub mod client_health; pub mod doppelganger; pub mod duties; pub mod error; @@ -255,6 +256,12 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { // The keymanager mutates this at runtime while the duty loop reads it, so // it is shared rather than owned outright from here on. let store = Arc::new(RwLock::new(store)); + // What `/health` reports. The nodes and the record are attached once + // they exist; until the first refresh it answers `starting`. + let health = Arc::new(client_health::ClientHealth::new( + config.beacon_nodes.len(), + store.clone(), + )); // Bound before any beacon-node network call, deliberately: a validator // that cannot reach its beacon node still exits (via the `?`s below) if @@ -268,8 +275,9 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { source, })?; info!(address = %config.metrics, "Metrics listening"); + let router = metrics::router(health.clone()); tokio::spawn(async move { - if let Err(err) = axum::serve(listener, metrics::router()).await { + if let Err(err) = axum::serve(listener, router).await { error!(%err, "Metrics server stopped"); } }); @@ -317,6 +325,11 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { "Slashing protection loaded" ); let protection = slashing_protection::SharedProtection::new(protection); + health.attach( + beacon_node.health().clone(), + clock.slot_duration(), + protection.clone(), + ); // Every key loaded is registered before anything that signs exists, in // the epoch the clock is in now, so this process's own activity before a @@ -557,6 +570,7 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { last_epoch = Some(epoch); resubscribe = moved; to_register = Some(registrable); + health.epoch_refreshed(refreshed_entries.len()); resolved = Arc::new(refreshed_entries); } // A beacon node that is down, syncing or answering badly will @@ -565,7 +579,6 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { // on it would hide the cause behind a warning every slot. Err(err) if err.is_retryable() => { warn!(%epoch, %err, "Failed to refresh duties; keeping the previous schedule"); - metrics::set_beacon_node_available(false); } // Unreachable today: every error `refresh_epoch` can produce // comes from a `BeaconNodeApi` call, and every variant those @@ -632,7 +645,6 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { subscriptions::subscribe(&beacon_node, &owed, &store, &context); let _ = subscribed.await.inspect_err(|err| { warn!(%epoch, %err, "Failed to subscribe to attestation subnets"); - metrics::set_beacon_node_available(false); }); }); } @@ -930,7 +942,6 @@ async fn sync_committee_duty( Ok(Err(err)) => { error!(%slot, %err, "Failed to publish sync committee messages for this slot"); metrics::inc_sync_committee_failures(); - metrics::set_beacon_node_available(false); return; } Err(_) => { @@ -1033,13 +1044,6 @@ async fn attest_and_aggregate( Err(err) => { error!(%slot, %err, "Failed to publish attestations for this slot"); metrics::inc_attestation_failures(); - // Every error `attest` can return originates from the beacon - // node (a failed fetch, a bad or mismatched response, a - // failed submission), so a failure here is exactly the signal - // this gauge exists for: `refresh_epoch` only runs once an - // epoch and would otherwise leave it reporting stale - // availability for up to that long. - metrics::set_beacon_node_available(false); } } } @@ -1070,7 +1074,6 @@ async fn payload_attest( Ok(Err(err)) => { error!(%slot, %err, "Failed to publish payload attestations for this slot"); metrics::inc_payload_attestation_failures(); - metrics::set_beacon_node_available(false); } Err(_) => { warn!( @@ -1282,7 +1285,6 @@ async fn refresh_epoch( refresh_ptc(duties, epoch, context).await; refresh_sync(beacon_node, duties, epoch, context).await; metrics::set_duties_held(duties.all().len() as u64); - metrics::set_beacon_node_available(true); let registrable = entries.iter().filter(|entry| is_registrable(&entry.status)); Ok(Refreshed { moved: changed, diff --git a/crates/validator/src/metrics.rs b/crates/validator/src/metrics.rs index 9bafa6b74..e25c8ed4a 100644 --- a/crates/validator/src/metrics.rs +++ b/crates/validator/src/metrics.rs @@ -317,10 +317,25 @@ static SLOTS_SKIPPED_SYNCING_TOTAL: LazyLock = LazyLock::new(|| { .unwrap() }); +/// Set on every scrape from the same report `/health` answers with. See +/// `crate::client_health`. static BEACON_NODE_AVAILABLE: LazyLock = LazyLock::new(|| { register_int_gauge!( "ethlambda_validator_beacon_node_available", - "1 when a beacon node answered the last duty refresh or attestation" + "1 when at least one beacon node answered its latest sync probe neither syncing nor \ + optimistic" + ) + .unwrap() +}); + +/// What `/health` answers, as a series: 1 for its `200`, 0 for its `503`. +/// Set on every scrape from the same report, so an alert on it and a probe of +/// the endpoint cannot disagree. See `crate::client_health`. +static HEALTHY: LazyLock = LazyLock::new(|| { + register_int_gauge!( + "ethlambda_validator_healthy", + "1 when /health answers 200: the client has started, a beacon node is usable and the \ + last slashing-protection write went through" ) .unwrap() }); @@ -499,6 +514,7 @@ pub fn init() { LazyLock::force(&FEE_RECIPIENT_MISMATCHES_TOTAL); LazyLock::force(&SLOTS_SKIPPED_SYNCING_TOTAL); LazyLock::force(&BEACON_NODE_AVAILABLE); + LazyLock::force(&HEALTHY); LazyLock::force(&SIGNING_DURATION_SECONDS); LazyLock::force(&REMOTE_SIGNER_REQUEST_DURATION_SECONDS); LazyLock::force(&PUBLICATION_DELAY_SECONDS); @@ -647,6 +663,10 @@ pub fn set_beacon_node_available(available: bool) { BEACON_NODE_AVAILABLE.set(i64::from(available)); } +pub fn set_healthy(healthy: bool) { + HEALTHY.set(i64::from(healthy)); +} + pub fn set_doppelganger_detecting(count: u64) { DOPPELGANGER_DETECTING.set(count as i64); } @@ -683,16 +703,25 @@ pub fn observe_publication_delay(seconds: f64) { PUBLICATION_DELAY_SECONDS.observe(seconds); } -/// A Prometheus endpoint for this process. +/// A Prometheus endpoint for this process, and `/health`, both answered from +/// `health`. /// /// Deliberately not `ethlambda-rpc`'s router: reaching that would put the /// blockchain and storage crates, and RocksDB with them, on a process that /// only signs attestations. -pub fn router() -> axum::Router { +pub fn router(health: std::sync::Arc) -> axum::Router { + use std::sync::Arc; + + use axum::extract::State; use axum::response::IntoResponse; use axum::routing::get; - async fn serve() -> impl IntoResponse { + use crate::client_health::ClientHealth; + + async fn serve(State(health): State>) -> impl IntoResponse { + // The gauges that mirror `/health`, from the report it would answer + // now, before the series are read. + crate::client_health::publish(&health.report()); match ethlambda_metrics::gather_default_metrics() { Ok(body) => ( [( @@ -709,14 +738,16 @@ pub fn router() -> axum::Router { } } - async fn health() -> impl IntoResponse { - ( - [(axum::http::header::CONTENT_TYPE, "application/json")], - r#"{"status":"healthy","service":"ethlambda-validator"}"#, - ) + /// `200` when the client can do its duties, `503` when it cannot or has + /// not started yet, with the checks behind the answer. See + /// `crate::client_health`. + async fn report(State(health): State>) -> impl IntoResponse { + let report = health.report(); + (report.status_code(), axum::Json(report)) } axum::Router::new() .route("/metrics", get(serve)) - .route("/health", get(health)) + .route("/health", get(report)) + .with_state(health) } diff --git a/crates/validator/src/slashing_protection/mod.rs b/crates/validator/src/slashing_protection/mod.rs index a76f7ea0e..1c447d038 100644 --- a/crates/validator/src/slashing_protection/mod.rs +++ b/crates/validator/src/slashing_protection/mod.rs @@ -61,6 +61,7 @@ pub mod file; use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use ethlambda_types::beacon::containers::shared::AttestationData; @@ -90,16 +91,29 @@ use crate::error::{Error, Result}; pub struct SharedProtection { record: Arc>, unusable: CancellationToken, + /// The record's own, shared so it is read without the mutex. + outcomes: Arc, } impl SharedProtection { pub fn new(protection: SlashingProtection) -> Self { Self { + outcomes: protection.outcomes.clone(), record: Arc::new(Mutex::new(protection)), unusable: CancellationToken::new(), } } + /// Whether the record's last write succeeded and the last access through + /// [`blocking`] reached it within [`RECORD_WAIT`]: what `/health` reports + /// as `slashing_protection.last_write_ok`. A failed write keeps it false + /// until a later write succeeds, whatever is read in between. + /// + /// Never waits on the record's lock, which a stuck write may be holding. + pub fn last_write_ok(&self) -> bool { + self.outcomes.last_write_ok() + } + /// Lock the record on the calling thread, waiting out any other holder. /// For synchronous callers; an async one goes through [`blocking`]. pub fn lock(&self) -> std::sync::LockResult> { @@ -118,6 +132,24 @@ impl SharedProtection { const RECORD_WAIT: std::time::Duration = std::time::Duration::from_secs(3); const RECORD_POLL: std::time::Duration = std::time::Duration::from_millis(5); +/// How the record's last write and last wait for it went, for +/// [`SharedProtection::last_write_ok`]. Two flags, not one: an access that +/// reaches the record clears the wait's, and only a write that succeeds +/// clears the write's, so a read in between never hides a failed write. +#[derive(Debug, Default)] +struct Outcomes { + /// The last write of the file failed, [`Error::Unflushed`] included. + write_failed: AtomicBool, + /// The last access through [`blocking`] gave up after [`RECORD_WAIT`]. + wait_timed_out: AtomicBool, +} + +impl Outcomes { + fn last_write_ok(&self) -> bool { + !self.write_failed.load(Ordering::Relaxed) && !self.wait_timed_out.load(Ordering::Relaxed) + } +} + /// Run `operation` on the record on tokio's blocking pool, and wait for it. /// /// Every async caller goes through here, including ones that only read: the @@ -148,7 +180,11 @@ pub async fn blocking( protection: &SharedProtection, operation: impl FnOnce(&mut SlashingProtection) -> Result + Send + 'static, ) -> Result { - let SharedProtection { record, unusable } = protection.clone(); + let SharedProtection { + record, + unusable, + outcomes, + } = protection.clone(); tokio::task::spawn_blocking(move || { // Declared before the guard, so on a panic in `operation` it drops // after the guard has poisoned the lock: nobody is told the record is @@ -169,6 +205,7 @@ pub async fn blocking( } Err(std::sync::TryLockError::WouldBlock) => { if std::time::Instant::now() >= deadline { + outcomes.wait_timed_out.store(true, Ordering::Relaxed); return Err(Error::SlashingProtectionUnusable { reason: format!( "the record has been held by other accesses for {} s: a write \ @@ -181,6 +218,7 @@ pub async fn blocking( } } }; + outcomes.wait_timed_out.store(false, Ordering::Relaxed); operation(&mut protection) }) .await @@ -441,6 +479,8 @@ pub struct SlashingProtection { records: HashMap, /// `None` only for [`Self::in_memory`]. storage: Option, + /// Written by [`Self::commit`], read through [`SharedProtection`]. + outcomes: Arc, } impl SlashingProtection { @@ -549,6 +589,7 @@ impl SlashingProtection { genesis_validators_root, records, storage: Some(Storage { path, _lock: lock }), + outcomes: Arc::default(), }) } @@ -580,6 +621,7 @@ impl SlashingProtection { genesis_validators_root, records, storage: Some(Storage { path, _lock: lock }), + outcomes: Arc::default(), }) } @@ -597,6 +639,7 @@ impl SlashingProtection { genesis_validators_root: Root::ZERO, records: HashMap::new(), storage: None, + outcomes: Arc::default(), }) } @@ -867,7 +910,10 @@ impl SlashingProtection { .filter(|(pubkey, _)| !changes.contains_key(*pubkey)) .chain(changes.iter()); let _timing = crate::metrics::time_slashing_protection_write(); - if let Err(err) = file::write(&storage.path, self.genesis_validators_root, next) { + let written = file::write(&storage.path, self.genesis_validators_root, next); + let failed = &self.outcomes.write_failed; + failed.store(written.is_err(), Ordering::Relaxed); + if let Err(err) = written { crate::metrics::inc_slashing_protection_write_failures(); if matches!(err, Error::Unflushed { .. }) { self.records.extend(changes); @@ -944,6 +990,7 @@ mod tests { genesis_validators_root: Root::ZERO, records: HashMap::new(), storage: None, + outcomes: Arc::default(), } } @@ -1708,4 +1755,85 @@ mod tests { .await .expect("the task itself raises the signal"); } + + /// A failed write turns `last_write_ok` off, an access that writes + /// nothing leaves it off, and the next write that succeeds turns it back + /// on. + #[cfg(unix)] + #[tokio::test] + async fn a_failed_write_is_reported_until_a_later_write_succeeds() { + use std::os::unix::fs::PermissionsExt as _; + + if running_as_root() { + eprintln!("skipped: root bypasses directory permissions"); + return; + } + let dir = tempfile::tempdir().expect("temp dir"); + let protection = SharedProtection::new(open(dir.path(), &[1], true).expect("init")); + assert!(protection.last_write_ok(), "nothing has failed yet"); + + let read_only = std::fs::Permissions::from_mode(0o500); + std::fs::set_permissions(dir.path(), read_only).expect("chmod"); + let failed = blocking(&protection, |record| { + record.check_and_record_block(&pubkey(1), 10) + }) + .await; + let writable = std::fs::Permissions::from_mode(0o700); + std::fs::set_permissions(dir.path(), writable).expect("chmod back"); + assert!( + failed.is_err(), + "the write must fail in a read-only directory" + ); + assert!(!protection.last_write_ok()); + + let read = blocking(&protection, |record| Ok(record.check_block(&pubkey(1), 10))); + assert!(read.await.expect("reached").is_ok(), "nothing was recorded"); + assert!( + !protection.last_write_ok(), + "an access that writes nothing does not clear a failed write" + ); + + blocking(&protection, |record| { + record.check_and_record_block(&pubkey(1), 10) + }) + .await + .expect("written") + .expect("slot 10 is still signable"); + assert!(protection.last_write_ok()); + } + + /// An access that gives up on a record held past [`RECORD_WAIT`] turns + /// `last_write_ok` off, and the next access that reaches it turns it back + /// on. Waits out the real `RECORD_WAIT`, since the wait is on a blocking + /// thread's clock. The record is held until the refused access returns, + /// however late its task starts. + #[tokio::test] + async fn a_record_held_past_the_wait_is_reported_until_an_access_reaches_it() { + let protection = SlashingProtection::in_memory(); + let (locked, held) = std::sync::mpsc::channel::<()>(); + let (release, released) = std::sync::mpsc::channel::<()>(); + let holder = { + let protection = protection.clone(); + std::thread::spawn(move || { + let _guard = protection.lock().expect("not poisoned"); + locked.send(()).expect("the test is waiting"); + released.recv().expect("released"); + }) + }; + held.recv().expect("the holder took the record"); + + let refused = blocking(&protection, |_| Ok(())).await; + assert!( + matches!(refused, Err(Error::SlashingProtectionUnusable { .. })), + "got {refused:?}" + ); + assert!(!protection.last_write_ok()); + + release.send(()).expect("the holder is waiting"); + holder.join().expect("the holder ends"); + blocking(&protection, |_| Ok(())) + .await + .expect("the record is free again"); + assert!(protection.last_write_ok()); + } } diff --git a/docs/cli.md b/docs/cli.md index 841632c48..7ca869602 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -956,6 +956,60 @@ beacon chain. Every series is registered at startup so it reads zero rather than being absent before its first event, which is what lets an alert fire on "attestations stopped". See [Metrics](./metrics.md#validator-client). +`GET /health` on the same port answers whether the client can do its duties: +`200` when it can, `503` when it cannot or has not started yet, with the checks +behind the answer. + +```json +{ + "status": "unhealthy", + "service": "ethlambda-validator", + "checks": { + "beacon_nodes": { "usable": 0, "configured": 2 }, + "validators": { "loaded": 64, "resolved": 64 }, + "slashing_protection": { "last_write_ok": true }, + "started": true + } +} +``` + +It reads state the client already keeps and sends no request of its own, so it +is cheap to poll. + +- **`beacon_nodes`**: `usable` counts the nodes whose latest + [sync probe](#the-per-slot-sync-check) was answered, neither syncing nor + optimistic, and is at most two slots old. One usable node is enough: a client + with some nodes down and one usable is `healthy`, with the counts in the + body. +- **`validators`**: the keys loaded, and those the last duty refresh resolved to + an index. Reported, never failing: a key waiting for activation has no index + yet, and a client started with no keys, to wait for a keymanager import, is + idle on purpose. A key doppelganger protection still withholds counts as + loaded. +- **`slashing_protection.last_write_ok`**: the record's last write succeeded, + and the last access to it did not give up after waiting 3 s for another one + to finish. A failed write keeps it `false` until a later write succeeds. A + full disk or a read-only remount under `--validators-dir` shows up here. +- **`started`**: a duty refresh has succeeded since the process started. + +`status` is one of three: + +- `healthy` (`200`): started, at least one usable node, and the last write went + through. +- `starting` (`503`): no refresh has succeeded yet and nothing else has failed. + A node not probed yet does not count against a client that has not started, + so a normal startup reads `starting` throughout. Once started, a node with no + probe counts as unusable. +- `unhealthy` (`503`): anything else. + +Remote signers are not checked, since that would take a request to each. +`ethlambda_validator_healthy` carries the same answer as a series, set from the +same report on every scrape. + +Point readiness checks, load balancers and uptime monitors at it, not a +Kubernetes liveness probe: it answers `503` while every beacon node is down or +syncing, which restarting the validator client does not fix. + ## `voluntary-exit` `ethlambda voluntary-exit` signs a voluntary exit for one validator and hands diff --git a/docs/metrics.md b/docs/metrics.md index 99fc8f157..26bbcc67a 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -907,7 +907,7 @@ and absent is not the same as zero. | Metric | Type | Description | |---|---|---| -| `ethlambda_validator_validators_loaded` | Gauge | Validator keys loaded from the keystores | +| `ethlambda_validator_validators_loaded` | Gauge | Validator keys this client holds, local and remote, the count `/health` reports as `validators.loaded`. Set at startup and again on every scrape, so keys imported or deleted through the keymanager API show up | | `ethlambda_validator_validators_resolved` | Gauge | Loaded keys that have an index on chain, out of `validators_loaded`. A persistent gap means validators are deposited but not yet activated | | `ethlambda_validator_duties_held` | Gauge | Attester duties currently scheduled | | `ethlambda_validator_attestations_published_total` | Counter | Attestations a beacon node accepted | @@ -942,7 +942,8 @@ and absent is not the same as zero. | `ethlambda_validator_blinded_blocks_unconfirmed_total` | Counter | Blinded blocks the beacon node did not confirm (a 5xx other than 503, or no answer once connected), which the relay may still have published. Not retried, since a second block for the slot would be an equivocation | | `ethlambda_validator_block_publication_delay_seconds` | Histogram | Slot start to block accepted. Its buckets are tighter than the attestation histogram's, because a block is due at the slot boundary rather than a third of the way in | | `ethlambda_validator_slots_skipped_syncing_total` | Counter | Slots in which nothing was signed because every beacon node that answered the slot's sync probe (`/eth/v1/node/syncing`, a sixth of a slot before the boundary) reported syncing or optimistic. Should read zero once the nodes are synced; a steady climb is a node that stays syncing or on an optimistic head, usually because its execution client is behind. Nodes that did not answer are not counted against the slot, so this stays flat while every node is down. See [The per-slot sync check](./cli.md#the-per-slot-sync-check) | -| `ethlambda_validator_beacon_node_available` | Gauge | 1 when a beacon node answered the last duty refresh or attestation. 0 after a slot the sync check withheld, until the next refresh succeeds | +| `ethlambda_validator_beacon_node_available` | Gauge | 1 when at least one configured beacon node answered its latest sync probe neither syncing nor optimistic, and that probe is at most two slots old. 0 before the first probe answers, and while every node is down, syncing or optimistic, which includes every slot the sync check withholds. Set on every scrape from the per-node probe records `/health` reads, so it follows the nodes rather than the last duty: a failed attestation no longer sets it to 0, and a node that comes back sets it to 1 within a slot, without waiting for the next epoch's refresh | +| `ethlambda_validator_healthy` | Gauge | 1 when `/health` answers `200`, 0 when it answers `503`: the client has run a duty refresh, at least one beacon node is usable, and the last slashing-protection write went through. Set on every scrape from the same report `/health` answers with, so an alert on it and a probe of the endpoint cannot disagree. 0 while the client is starting. See [Metrics](./cli.md#metrics) for the checks | | `ethlambda_validator_signing_duration_seconds` | Histogram | Time a duty waited for its batch of signatures. With local keys that is the signing itself. With keys in a remote signer it is the batch's slowest answer, round trip and verification included, and at most the 2 s signing budget, so a sample in the top bucket means a signer that did not answer in time | | `ethlambda_validator_remote_signer_request_duration_seconds` | Histogram | Time one signing request to a remote signer took, from sending it to its answer or failure, not counting the wait for one of the signer's 64 request slots. The number to watch for a slow signer; empty when every key is local | | `ethlambda_validator_slashing_protection_write_seconds` | Histogram | Time to durably write the slashing-protection record, once per slot's attestation batch and once per block, before signing. Milliseconds on a local disk; worth an alert above about a second, since the duty waits for it and a write held past 3 s is refused | From 8d4e5bfea7eb1773a0f47bf0b6ef0c551c01e6ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:22:09 -0300 Subject: [PATCH 08/12] fix(validator): report unhealthy once the last duty schedule has run out A node can answer its sync probe synced and still fail every duty refresh. /health then stayed 200 for good after the first refresh, with no duties left to do once the held schedule ran out, and the failure paths that used to drop beacon_node_available are gone. /health gains a schedule_current check: the last successful refresh is at most two epochs old, so the schedule it fetched (its own epoch and the next) still covers now. healthy now also requires it. --- crates/validator/src/client_health.rs | 82 +++++++++++++++++++++++++-- docs/cli.md | 12 +++- docs/metrics.md | 2 +- 3 files changed, 86 insertions(+), 10 deletions(-) diff --git a/crates/validator/src/client_health.rs b/crates/validator/src/client_health.rs index 5b1f4e2b8..962da1b74 100644 --- a/crates/validator/src/client_health.rs +++ b/crates/validator/src/client_health.rs @@ -28,11 +28,16 @@ //! [`SharedProtection::last_write_ok`]). A failed write fails the check //! until a later write succeeds. //! - **`started`**: a duty refresh has succeeded since the process started. +//! - **`schedule_current`**: the last successful duty refresh is at most two +//! epochs old, so the schedule it fetched (its own epoch and the next) still +//! covers now. A node can answer its probe synced and still fail every +//! refresh; once the schedule runs out the client has no duties to do. +//! `true` before the first refresh, which `started` reports. //! //! # Status //! -//! - `healthy`, `200`: started, at least one usable node, and the record's -//! last write went through. +//! - `healthy`, `200`: started, at least one usable node, the record's last +//! write went through, and the schedule is current. //! - `starting`, `503`: not started yet, and nothing else has failed. A node //! not probed yet does not count against the client before it starts, so a //! normal startup reads `starting` throughout rather than `unhealthy`. Once @@ -54,7 +59,7 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, OnceLock}; -use std::time::{Duration, SystemTime}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; use axum::http::StatusCode; use serde::Serialize; @@ -72,6 +77,10 @@ pub const SERVICE: &str = "ethlambda-validator"; /// bound the fallback reads probes for when it routes. const PROBE_READ_SLOTS: u32 = 2; +/// How many epochs a successful duty refresh's schedule covers: its own and +/// the next. +const SCHEDULE_EPOCHS: u64 = 2; + /// The state `/health` reads, shared by the metrics server, which reports it, /// and the duty loop, which keeps it. pub struct ClientHealth { @@ -84,6 +93,9 @@ pub struct ClientHealth { resolved: AtomicU64, /// A duty refresh has succeeded. started: AtomicBool, + /// When the last duty refresh succeeded, in milliseconds since the Unix + /// epoch: `0` before the first. + refreshed_at: AtomicU64, /// Set once the beacon nodes and the record exist, which is after the /// metrics server is already answering. attached: OnceLock, @@ -93,6 +105,8 @@ struct Attached { nodes: Arc, /// How old a probe may be and still be read. read_for: Duration, + /// How long a successful refresh's schedule lasts. + schedule_lasts: Duration, protection: SharedProtection, } @@ -107,22 +121,26 @@ impl ClientHealth { loaded: AtomicU64::new(loaded), resolved: AtomicU64::new(0), started: AtomicBool::new(false), + refreshed_at: AtomicU64::new(0), attached: OnceLock::new(), } } /// Read the beacon nodes' probes from `nodes`, judging a probe stale past /// two of `slot_duration`, and the record's last write from `protection`. - /// Called once; a second call changes nothing. + /// Called once, after the preset is adopted, since an epoch's length is + /// read from it; a second call changes nothing. pub fn attach( &self, nodes: Arc, slot_duration: Duration, protection: SharedProtection, ) { + let schedule_slots = SCHEDULE_EPOCHS * ethlambda_types::beacon::preset::slots_per_epoch(); let _ = self.attached.set(Attached { nodes, read_for: slot_duration * PROBE_READ_SLOTS, + schedule_lasts: slot_duration * u32::try_from(schedule_slots).unwrap_or(u32::MAX), protection, }); } @@ -130,10 +148,29 @@ impl ClientHealth { /// A duty refresh succeeded, resolving `resolved` validators to an index. /// The first one is what moves the client from `starting`. pub fn epoch_refreshed(&self, resolved: usize) { + self.epoch_refreshed_at(resolved, SystemTime::now()); + } + + fn epoch_refreshed_at(&self, resolved: usize, at: SystemTime) { + let millis = at + .duration_since(UNIX_EPOCH) + .map_or(0, |since| since.as_millis() as u64); self.resolved.store(resolved as u64, Ordering::Relaxed); + self.refreshed_at.store(millis.max(1), Ordering::Relaxed); self.started.store(true, Ordering::Relaxed); } + /// The last successful refresh's schedule still covers `now`, or no + /// refresh has succeeded yet. + fn schedule_current(&self, attached: &Attached, now: SystemTime) -> bool { + let refreshed = self.refreshed_at.load(Ordering::Relaxed); + if refreshed == 0 { + return true; + } + let at = UNIX_EPOCH + Duration::from_millis(refreshed); + now.duration_since(at).unwrap_or_default() <= attached.schedule_lasts + } + /// What `/health` answers now. pub fn report(&self) -> Report { self.report_at(SystemTime::now()) @@ -150,9 +187,10 @@ impl ClientHealth { }; let last_write_ok = attached.is_none_or(|attached| attached.protection.last_write_ok()); let started = self.started.load(Ordering::Relaxed); + let schedule_current = attached.is_none_or(|attached| self.schedule_current(attached, now)); let nodes_ok = nodes.usable > 0; - let status = if started && nodes_ok && last_write_ok { + let status = if started && nodes_ok && last_write_ok && schedule_current { Status::Healthy } else if !started && last_write_ok && (nodes_ok || nodes.unprobed > 0) { Status::Starting @@ -174,6 +212,7 @@ impl ClientHealth { }, slashing_protection: SlashingProtectionCheck { last_write_ok }, started, + schedule_current, }, } } @@ -273,6 +312,7 @@ pub struct Checks { pub validators: Validators, pub slashing_protection: SlashingProtectionCheck, pub started: bool, + pub schedule_current: bool, } #[derive(Debug, Clone, PartialEq, Eq, Serialize)] @@ -355,7 +395,7 @@ mod tests { } /// The body is the issue's: `status`, `service` and the four checks, each - /// with exactly the fields it names. + /// with exactly the fields it names, plus `schedule_current`. #[test] fn the_body_has_the_issues_shape() { let (health, probes) = client(2, 3); @@ -374,11 +414,41 @@ mod tests { "validators": { "loaded": 3, "resolved": 2 }, "slashing_protection": { "last_write_ok": true }, "started": true, + "schedule_current": true, } }) ); } + /// A refresh's schedule covers its own epoch and the next. Once the last + /// successful refresh is older than that, the client has no duties left + /// to do, whatever its nodes' probes say. + #[test] + fn a_schedule_past_two_epochs_is_unhealthy() { + let (health, probes) = client(1, 1); + let refreshed = SystemTime::now(); + health.epoch_refreshed_at(1, refreshed); + let two_epochs = SLOT * (2 * ethlambda_types::beacon::preset::slots_per_epoch()) as u32; + // The last slot the schedule covers, with a fresh probe. + let last = refreshed + two_epochs - SLOT; + probes.record( + 0, + Probe { + at: last, + ..synced() + }, + ); + + let covered = health.report_at(last); + assert_eq!(covered.status, Status::Healthy); + assert!(covered.checks.schedule_current); + + let past = health.report_at(last + SLOT * 2); + assert_eq!(past.status, Status::Unhealthy); + assert!(!past.checks.schedule_current); + assert!(past.beacon_node_available(), "the node still probes usable"); + } + /// Until the first refresh the client is `starting`, a `503`, and the /// refresh that moves it is a real one, driven through the mock. #[tokio::test] diff --git a/docs/cli.md b/docs/cli.md index 7ca869602..daff09163 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -968,7 +968,8 @@ behind the answer. "beacon_nodes": { "usable": 0, "configured": 2 }, "validators": { "loaded": 64, "resolved": 64 }, "slashing_protection": { "last_write_ok": true }, - "started": true + "started": true, + "schedule_current": true } } ``` @@ -991,11 +992,16 @@ is cheap to poll. to finish. A failed write keeps it `false` until a later write succeeds. A full disk or a read-only remount under `--validators-dir` shows up here. - **`started`**: a duty refresh has succeeded since the process started. +- **`schedule_current`**: the last successful duty refresh is at most two + epochs old, so the schedule it fetched (its own epoch and the next) still + covers now. A node can answer its probe synced and still fail every refresh; + once the schedule runs out the client has nothing to sign. `true` before the + first refresh. `status` is one of three: -- `healthy` (`200`): started, at least one usable node, and the last write went - through. +- `healthy` (`200`): started, at least one usable node, the last write went + through, and the schedule is current. - `starting` (`503`): no refresh has succeeded yet and nothing else has failed. A node not probed yet does not count against a client that has not started, so a normal startup reads `starting` throughout. Once started, a node with no diff --git a/docs/metrics.md b/docs/metrics.md index 26bbcc67a..03b5ff33f 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -943,7 +943,7 @@ and absent is not the same as zero. | `ethlambda_validator_block_publication_delay_seconds` | Histogram | Slot start to block accepted. Its buckets are tighter than the attestation histogram's, because a block is due at the slot boundary rather than a third of the way in | | `ethlambda_validator_slots_skipped_syncing_total` | Counter | Slots in which nothing was signed because every beacon node that answered the slot's sync probe (`/eth/v1/node/syncing`, a sixth of a slot before the boundary) reported syncing or optimistic. Should read zero once the nodes are synced; a steady climb is a node that stays syncing or on an optimistic head, usually because its execution client is behind. Nodes that did not answer are not counted against the slot, so this stays flat while every node is down. See [The per-slot sync check](./cli.md#the-per-slot-sync-check) | | `ethlambda_validator_beacon_node_available` | Gauge | 1 when at least one configured beacon node answered its latest sync probe neither syncing nor optimistic, and that probe is at most two slots old. 0 before the first probe answers, and while every node is down, syncing or optimistic, which includes every slot the sync check withholds. Set on every scrape from the per-node probe records `/health` reads, so it follows the nodes rather than the last duty: a failed attestation no longer sets it to 0, and a node that comes back sets it to 1 within a slot, without waiting for the next epoch's refresh | -| `ethlambda_validator_healthy` | Gauge | 1 when `/health` answers `200`, 0 when it answers `503`: the client has run a duty refresh, at least one beacon node is usable, and the last slashing-protection write went through. Set on every scrape from the same report `/health` answers with, so an alert on it and a probe of the endpoint cannot disagree. 0 while the client is starting. See [Metrics](./cli.md#metrics) for the checks | +| `ethlambda_validator_healthy` | Gauge | 1 when `/health` answers `200`, 0 when it answers `503`: the client has run a duty refresh within the last two epochs, at least one beacon node is usable, and the last slashing-protection write went through. Set on every scrape from the same report `/health` answers with, so an alert on it and a probe of the endpoint cannot disagree. 0 while the client is starting. See [Metrics](./cli.md#metrics) for the checks | | `ethlambda_validator_signing_duration_seconds` | Histogram | Time a duty waited for its batch of signatures. With local keys that is the signing itself. With keys in a remote signer it is the batch's slowest answer, round trip and verification included, and at most the 2 s signing budget, so a sample in the top bucket means a signer that did not answer in time | | `ethlambda_validator_remote_signer_request_duration_seconds` | Histogram | Time one signing request to a remote signer took, from sending it to its answer or failure, not counting the wait for one of the signer's 64 request slots. The number to watch for a slow signer; empty when every key is local | | `ethlambda_validator_slashing_protection_write_seconds` | Histogram | Time to durably write the slashing-protection record, once per slot's attestation batch and once per block, before signing. Milliseconds on a local disk; worth an alert above about a second, since the duty waits for it and a write held past 3 s is refused | From 0256e843ae0e41c698e86d34c1a60cb35ed85273 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:40:42 -0300 Subject: [PATCH 09/12] fix(validator): judge the health schedule check by the epochs actually held schedule_current allowed two epochs from the refresh's completion. A refresh late in its epoch then read current for most of an epoch past the schedule's end, and one whose lookahead fetch failed (which refresh_around shrugs off) read current through an epoch it held no attester duties for. The duty loop now passes the last epoch the attester schedule holds after a successful refresh: the lookahead epoch when its fetch went through, else the refresh's own (DutiesService::holds_attesters). ClientHealth compares it with the clock's epoch, so attach takes the SlotClock. --- crates/validator/src/client_health.rs | 165 ++++++++++++++------------ crates/validator/src/duties.rs | 6 + crates/validator/src/lib.rs | 12 +- docs/cli.md | 11 +- docs/metrics.md | 2 +- 5 files changed, 112 insertions(+), 84 deletions(-) diff --git a/crates/validator/src/client_health.rs b/crates/validator/src/client_health.rs index 962da1b74..28ce3341d 100644 --- a/crates/validator/src/client_health.rs +++ b/crates/validator/src/client_health.rs @@ -28,11 +28,12 @@ //! [`SharedProtection::last_write_ok`]). A failed write fails the check //! until a later write succeeds. //! - **`started`**: a duty refresh has succeeded since the process started. -//! - **`schedule_current`**: the last successful duty refresh is at most two -//! epochs old, so the schedule it fetched (its own epoch and the next) still -//! covers now. A node can answer its probe synced and still fail every -//! refresh; once the schedule runs out the client has no duties to do. -//! `true` before the first refresh, which `started` reports. +//! - **`schedule_current`**: the attester schedule the last successful duty +//! refresh left held reaches the clock's epoch: its own epoch, and the next +//! when the lookahead fetch went through too. A node can answer its probe +//! synced and still fail every refresh, or every lookahead; once the +//! schedule runs out the client has no attestations to make. `true` before +//! the first refresh, which `started` reports, and before genesis. //! //! # Status //! @@ -59,15 +60,17 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, OnceLock}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use std::time::{Duration, SystemTime}; use axum::http::StatusCode; +use ethlambda_types::beacon::primitives::Epoch; use serde::Serialize; use tokio::sync::RwLock; use crate::beacon_node::health::{NodeHealth, Probe, Standing}; use crate::keys::ValidatorStore; use crate::slashing_protection::SharedProtection; +use crate::slot_clock::SlotClock; /// What every report names as its `service`. pub const SERVICE: &str = "ethlambda-validator"; @@ -77,9 +80,8 @@ pub const SERVICE: &str = "ethlambda-validator"; /// bound the fallback reads probes for when it routes. const PROBE_READ_SLOTS: u32 = 2; -/// How many epochs a successful duty refresh's schedule covers: its own and -/// the next. -const SCHEDULE_EPOCHS: u64 = 2; +/// [`ClientHealth::covered_through`] before any refresh has succeeded. +const NOT_REFRESHED: u64 = u64::MAX; /// The state `/health` reads, shared by the metrics server, which reports it, /// and the duty loop, which keeps it. @@ -93,9 +95,9 @@ pub struct ClientHealth { resolved: AtomicU64, /// A duty refresh has succeeded. started: AtomicBool, - /// When the last duty refresh succeeded, in milliseconds since the Unix - /// epoch: `0` before the first. - refreshed_at: AtomicU64, + /// The last epoch the attester schedule held after the last successful + /// refresh: [`NOT_REFRESHED`] before the first. + covered_through: AtomicU64, /// Set once the beacon nodes and the record exist, which is after the /// metrics server is already answering. attached: OnceLock, @@ -105,8 +107,8 @@ struct Attached { nodes: Arc, /// How old a probe may be and still be read. read_for: Duration, - /// How long a successful refresh's schedule lasts. - schedule_lasts: Duration, + /// What says which epoch it is, for the schedule check. + clock: SlotClock, protection: SharedProtection, } @@ -121,54 +123,43 @@ impl ClientHealth { loaded: AtomicU64::new(loaded), resolved: AtomicU64::new(0), started: AtomicBool::new(false), - refreshed_at: AtomicU64::new(0), + covered_through: AtomicU64::new(NOT_REFRESHED), attached: OnceLock::new(), } } /// Read the beacon nodes' probes from `nodes`, judging a probe stale past - /// two of `slot_duration`, and the record's last write from `protection`. - /// Called once, after the preset is adopted, since an epoch's length is - /// read from it; a second call changes nothing. - pub fn attach( - &self, - nodes: Arc, - slot_duration: Duration, - protection: SharedProtection, - ) { - let schedule_slots = SCHEDULE_EPOCHS * ethlambda_types::beacon::preset::slots_per_epoch(); + /// two of `clock`'s slots, the epoch from `clock`, and the record's last + /// write from `protection`. Called once, after the preset is adopted, + /// since an epoch's length is read from it; a second call changes nothing. + pub fn attach(&self, nodes: Arc, clock: SlotClock, protection: SharedProtection) { let _ = self.attached.set(Attached { nodes, - read_for: slot_duration * PROBE_READ_SLOTS, - schedule_lasts: slot_duration * u32::try_from(schedule_slots).unwrap_or(u32::MAX), + read_for: clock.slot_duration() * PROBE_READ_SLOTS, + clock, protection, }); } - /// A duty refresh succeeded, resolving `resolved` validators to an index. - /// The first one is what moves the client from `starting`. - pub fn epoch_refreshed(&self, resolved: usize) { - self.epoch_refreshed_at(resolved, SystemTime::now()); - } - - fn epoch_refreshed_at(&self, resolved: usize, at: SystemTime) { - let millis = at - .duration_since(UNIX_EPOCH) - .map_or(0, |since| since.as_millis() as u64); + /// A duty refresh succeeded, resolving `resolved` validators to an index + /// and leaving the attester schedule held through `covered_through`. The + /// first one is what moves the client from `starting`. + pub fn epoch_refreshed(&self, resolved: usize, covered_through: Epoch) { self.resolved.store(resolved as u64, Ordering::Relaxed); - self.refreshed_at.store(millis.max(1), Ordering::Relaxed); + self.covered_through + .store(covered_through, Ordering::Relaxed); self.started.store(true, Ordering::Relaxed); } - /// The last successful refresh's schedule still covers `now`, or no - /// refresh has succeeded yet. + /// The attester schedule held reaches the epoch `now` is in, or no + /// refresh has succeeded yet, or it is before genesis. fn schedule_current(&self, attached: &Attached, now: SystemTime) -> bool { - let refreshed = self.refreshed_at.load(Ordering::Relaxed); - if refreshed == 0 { - return true; - } - let at = UNIX_EPOCH + Duration::from_millis(refreshed); - now.duration_since(at).unwrap_or_default() <= attached.schedule_lasts + let covered = self.covered_through.load(Ordering::Relaxed); + covered == NOT_REFRESHED + || attached + .clock + .slot_at(now) + .is_none_or(|slot| attached.clock.epoch_of(slot) <= covered) } /// What `/health` answers now. @@ -385,12 +376,23 @@ mod tests { Arc::new(RwLock::new(store)) } + /// Slots of [`SLOT`], with genesis a day from now. Before genesis every + /// schedule is current, so only the test that sets a clock past genesis + /// reads the schedule check. + fn clock() -> SlotClock { + let now = SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .expect("after 1970") + .as_secs(); + SlotClock::new(now + 86_400, SLOT.as_millis() as u64, 3_333, 6_667) + } + /// A client with `nodes` beacon nodes and `keys` keys, attached to an /// in-memory record, before any probe or refresh. fn client(nodes: usize, keys: u8) -> (ClientHealth, Arc) { let health = ClientHealth::new(nodes, store_of(keys)); let probes = Arc::new(NodeHealth::new(nodes)); - health.attach(probes.clone(), SLOT, SlashingProtection::in_memory()); + health.attach(probes.clone(), clock(), SlashingProtection::in_memory()); (health, probes) } @@ -401,7 +403,7 @@ mod tests { let (health, probes) = client(2, 3); probes.record(0, synced()); probes.record(1, down()); - health.epoch_refreshed(2); + health.epoch_refreshed(2, 0); let body = serde_json::to_value(health.report()).expect("serializes"); assert_eq!( @@ -420,33 +422,42 @@ mod tests { ); } - /// A refresh's schedule covers its own epoch and the next. Once the last - /// successful refresh is older than that, the client has no duties left - /// to do, whatever its nodes' probes say. + /// The schedule reaches the last epoch the refresh left held, whenever in + /// its epoch the refresh ran. From the epoch after, the client has no + /// attestations left to make, whatever its nodes' probes say; and a + /// refresh whose lookahead failed covers its own epoch alone. #[test] - fn a_schedule_past_two_epochs_is_unhealthy() { - let (health, probes) = client(1, 1); - let refreshed = SystemTime::now(); - health.epoch_refreshed_at(1, refreshed); - let two_epochs = SLOT * (2 * ethlambda_types::beacon::preset::slots_per_epoch()) as u32; - // The last slot the schedule covers, with a fresh probe. - let last = refreshed + two_epochs - SLOT; - probes.record( - 0, - Probe { - at: last, - ..synced() - }, + fn a_schedule_that_ends_before_the_clocks_epoch_is_unhealthy() { + let clock = SlotClock::new(1_000_000, SLOT.as_millis() as u64, 3_333, 6_667); + let health = ClientHealth::new(1, store_of(1)); + let probes = Arc::new(NodeHealth::new(1)); + health.attach( + probes.clone(), + clock.clone(), + SlashingProtection::in_memory(), ); + let first_slot = |epoch: Epoch| epoch * ethlambda_types::beacon::preset::slots_per_epoch(); + // The report at `slot`'s start, with a fresh synced probe. + let report_at_slot = |slot| { + let at = clock.start_of(slot); + probes.record(0, Probe { at, ..synced() }); + health.report_at(at) + }; - let covered = health.report_at(last); + let epoch = 10; + health.epoch_refreshed(1, epoch + 1); + let covered = report_at_slot(first_slot(epoch + 2) - 1); assert_eq!(covered.status, Status::Healthy); assert!(covered.checks.schedule_current); - let past = health.report_at(last + SLOT * 2); + let past = report_at_slot(first_slot(epoch + 2)); assert_eq!(past.status, Status::Unhealthy); assert!(!past.checks.schedule_current); assert!(past.beacon_node_available(), "the node still probes usable"); + + health.epoch_refreshed(1, epoch); + let without_lookahead = report_at_slot(first_slot(epoch + 1)); + assert_eq!(without_lookahead.status, Status::Unhealthy); } /// Until the first refresh the client is `starting`, a `503`, and the @@ -475,7 +486,7 @@ mod tests { let health = ClientHealth::new(1, store_of(1)); health.attach( beacon_node.health().clone(), - SLOT, + clock(), SlashingProtection::in_memory(), ); @@ -506,8 +517,10 @@ mod tests { ) .await .expect("the refresh passes on a synced node"); - // What the duty loop does with a refresh that succeeded. - health.epoch_refreshed(refreshed.resolved.len()); + // What the duty loop does with a refresh that succeeded: the mock + // answers the lookahead too, so the schedule runs through epoch 4. + assert!(duties.holds_attesters(4)); + health.epoch_refreshed(refreshed.resolved.len(), 4); let report = health.report(); assert_eq!(report.status, Status::Healthy); @@ -542,7 +555,7 @@ mod tests { #[test] fn a_started_client_with_no_probe_is_unhealthy() { let (health, _probes) = client(1, 1); - health.epoch_refreshed(1); + health.epoch_refreshed(1, 0); let report = health.report(); assert_eq!(report.status, Status::Unhealthy); assert_eq!(report.status_code(), StatusCode::SERVICE_UNAVAILABLE); @@ -553,7 +566,7 @@ mod tests { #[test] fn no_usable_node_is_unhealthy_until_one_recovers() { let (health, probes) = client(3, 1); - health.epoch_refreshed(1); + health.epoch_refreshed(1, 0); probes.record(0, down()); probes.record(1, syncing()); probes.record(2, optimistic()); @@ -574,7 +587,7 @@ mod tests { #[test] fn a_stale_probe_does_not_count_as_usable() { let (health, probes) = client(1, 1); - health.epoch_refreshed(1); + health.epoch_refreshed(1, 0); let taken = SystemTime::now(); probes.record( 0, @@ -597,7 +610,7 @@ mod tests { fn an_empty_store_reports_zero_loaded_and_stays_healthy() { let (health, probes) = client(1, 0); probes.record(0, synced()); - health.epoch_refreshed(0); + health.epoch_refreshed(0, 0); let report = health.report(); assert_eq!(report.status, Status::Healthy); assert_eq!( @@ -648,9 +661,9 @@ mod tests { let protection = crate::slashing_protection::SharedProtection::new(record); let health = ClientHealth::new(1, store_of(1)); let probes = Arc::new(NodeHealth::new(1)); - health.attach(probes.clone(), SLOT, protection.clone()); + health.attach(probes.clone(), clock(), protection.clone()); probes.record(0, synced()); - health.epoch_refreshed(1); + health.epoch_refreshed(1, 0); assert_eq!(health.report().status, Status::Healthy); let read_only = std::fs::Permissions::from_mode(0o500); @@ -714,7 +727,7 @@ mod tests { let (health, probes) = client(1, 1); let health = Arc::new(health); let router = crate::metrics::router(health.clone()); - health.epoch_refreshed(1); + health.epoch_refreshed(1, 0); for (probe, code) in [ (down(), StatusCode::SERVICE_UNAVAILABLE), diff --git a/crates/validator/src/duties.rs b/crates/validator/src/duties.rs index a32af3965..bf9c39da2 100644 --- a/crates/validator/src/duties.rs +++ b/crates/validator/src/duties.rs @@ -314,6 +314,12 @@ impl DutiesService { self.sync.retain(|held, _| *held >= period); } + /// Whether an attester schedule is held for `epoch`, an empty one + /// included: a fetch that found no duties still answered. + pub fn holds_attesters(&self, epoch: Epoch) -> bool { + self.by_epoch.contains_key(&epoch) + } + /// Whether a payload timeliness committee schedule is held for `epoch`, /// an empty one included: a fetch that found no duties still answered. pub fn holds_ptc(&self, epoch: Epoch) -> bool { diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index 25f815180..7da1115ea 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -327,7 +327,7 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { let protection = slashing_protection::SharedProtection::new(protection); health.attach( beacon_node.health().clone(), - clock.slot_duration(), + clock.clone(), protection.clone(), ); @@ -570,7 +570,15 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { last_epoch = Some(epoch); resubscribe = moved; to_register = Some(registrable); - health.epoch_refreshed(refreshed_entries.len()); + // Through the lookahead epoch only when its fetch + // went through: `refresh_around` shrugs a failed one + // off, and the schedule then ends with this epoch. + let covered_through = if duties.holds_attesters(epoch + 1) { + epoch + 1 + } else { + epoch + }; + health.epoch_refreshed(refreshed_entries.len(), covered_through); resolved = Arc::new(refreshed_entries); } // A beacon node that is down, syncing or answering badly will diff --git a/docs/cli.md b/docs/cli.md index daff09163..6695f73d9 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -992,11 +992,12 @@ is cheap to poll. to finish. A failed write keeps it `false` until a later write succeeds. A full disk or a read-only remount under `--validators-dir` shows up here. - **`started`**: a duty refresh has succeeded since the process started. -- **`schedule_current`**: the last successful duty refresh is at most two - epochs old, so the schedule it fetched (its own epoch and the next) still - covers now. A node can answer its probe synced and still fail every refresh; - once the schedule runs out the client has nothing to sign. `true` before the - first refresh. +- **`schedule_current`**: the attester schedule the last successful duty + refresh left held reaches the current epoch: the refresh's own epoch, and + the next when its lookahead fetch went through too. A node can answer its + probe synced and still fail every refresh, or every lookahead; once the + schedule runs out the client has no attestations to make. `true` before the + first refresh and before genesis. `status` is one of three: diff --git a/docs/metrics.md b/docs/metrics.md index 03b5ff33f..b3e97dd15 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -943,7 +943,7 @@ and absent is not the same as zero. | `ethlambda_validator_block_publication_delay_seconds` | Histogram | Slot start to block accepted. Its buckets are tighter than the attestation histogram's, because a block is due at the slot boundary rather than a third of the way in | | `ethlambda_validator_slots_skipped_syncing_total` | Counter | Slots in which nothing was signed because every beacon node that answered the slot's sync probe (`/eth/v1/node/syncing`, a sixth of a slot before the boundary) reported syncing or optimistic. Should read zero once the nodes are synced; a steady climb is a node that stays syncing or on an optimistic head, usually because its execution client is behind. Nodes that did not answer are not counted against the slot, so this stays flat while every node is down. See [The per-slot sync check](./cli.md#the-per-slot-sync-check) | | `ethlambda_validator_beacon_node_available` | Gauge | 1 when at least one configured beacon node answered its latest sync probe neither syncing nor optimistic, and that probe is at most two slots old. 0 before the first probe answers, and while every node is down, syncing or optimistic, which includes every slot the sync check withholds. Set on every scrape from the per-node probe records `/health` reads, so it follows the nodes rather than the last duty: a failed attestation no longer sets it to 0, and a node that comes back sets it to 1 within a slot, without waiting for the next epoch's refresh | -| `ethlambda_validator_healthy` | Gauge | 1 when `/health` answers `200`, 0 when it answers `503`: the client has run a duty refresh within the last two epochs, at least one beacon node is usable, and the last slashing-protection write went through. Set on every scrape from the same report `/health` answers with, so an alert on it and a probe of the endpoint cannot disagree. 0 while the client is starting. See [Metrics](./cli.md#metrics) for the checks | +| `ethlambda_validator_healthy` | Gauge | 1 when `/health` answers `200`, 0 when it answers `503`: the client has run a duty refresh whose attester schedule reaches the current epoch, at least one beacon node is usable, and the last slashing-protection write went through. Set on every scrape from the same report `/health` answers with, so an alert on it and a probe of the endpoint cannot disagree. 0 while the client is starting. See [Metrics](./cli.md#metrics) for the checks | | `ethlambda_validator_signing_duration_seconds` | Histogram | Time a duty waited for its batch of signatures. With local keys that is the signing itself. With keys in a remote signer it is the batch's slowest answer, round trip and verification included, and at most the 2 s signing budget, so a sample in the top bucket means a signer that did not answer in time | | `ethlambda_validator_remote_signer_request_duration_seconds` | Histogram | Time one signing request to a remote signer took, from sending it to its answer or failure, not counting the wait for one of the signer's 64 request slots. The number to watch for a slow signer; empty when every key is local | | `ethlambda_validator_slashing_protection_write_seconds` | Histogram | Time to durably write the slashing-protection record, once per slot's attestation batch and once per block, before signing. Milliseconds on a local disk; worth an alert above about a second, since the duty waits for it and a write held past 3 s is refused | From 0e4626ef81e69b115ba1063766b8b1d097b2f452 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:30:48 -0300 Subject: [PATCH 10/12] fix(validator): keep a client with no resolved validator schedule-current across boundaries A refresh that resolved no validator (no keys, or keys waiting for activation) fetches no attester schedule, so the schedule check counted it through its own epoch only, and /health read unhealthy at every epoch boundary until that slot's refresh returned. Such a refresh now counts through the next epoch: there is no schedule to run out. --- crates/validator/src/client_health.rs | 4 +++- crates/validator/src/lib.rs | 14 +++++++++----- docs/cli.md | 4 +++- 3 files changed, 15 insertions(+), 7 deletions(-) diff --git a/crates/validator/src/client_health.rs b/crates/validator/src/client_health.rs index 28ce3341d..f8042e719 100644 --- a/crates/validator/src/client_health.rs +++ b/crates/validator/src/client_health.rs @@ -33,7 +33,9 @@ //! when the lookahead fetch went through too. A node can answer its probe //! synced and still fail every refresh, or every lookahead; once the //! schedule runs out the client has no attestations to make. `true` before -//! the first refresh, which `started` reports, and before genesis. +//! the first refresh, which `started` reports, and before genesis. A +//! refresh that resolved no validator holds no schedule to run out, and +//! counts through the next epoch. //! //! # Status //! diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index 7da1115ea..aff0e1f0d 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -573,11 +573,15 @@ pub async fn run(config: ValidatorConfig) -> Result<()> { // Through the lookahead epoch only when its fetch // went through: `refresh_around` shrugs a failed one // off, and the schedule then ends with this epoch. - let covered_through = if duties.holds_attesters(epoch + 1) { - epoch + 1 - } else { - epoch - }; + // With no validator resolved there is no schedule + // to run out, and nothing to fetch for the next + // epoch either, so it stands until the next refresh. + let covered_through = + if refreshed_entries.is_empty() || duties.holds_attesters(epoch + 1) { + epoch + 1 + } else { + epoch + }; health.epoch_refreshed(refreshed_entries.len(), covered_through); resolved = Arc::new(refreshed_entries); } diff --git a/docs/cli.md b/docs/cli.md index 6695f73d9..002d49ac3 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -997,7 +997,9 @@ is cheap to poll. the next when its lookahead fetch went through too. A node can answer its probe synced and still fail every refresh, or every lookahead; once the schedule runs out the client has no attestations to make. `true` before the - first refresh and before genesis. + first refresh and before genesis. A client with no validator resolved (no + keys, or keys waiting for activation) holds no schedule, and a refresh + counts through the next epoch, so it is not caught out at each boundary. `status` is one of three: From 7dd74306539c1b37d644a0419bb6027058cdfaab Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Wed, 25 Nov 2026 17:14:10 -0300 Subject: [PATCH 11/12] test(validator): load a key in the sync-gate issue-case tests With an empty ValidatorStore the sync committee and PTC services sign nothing whichever node answers, so both tests still passed with head_block_root routed back through the plain try_each walk. Loading one key makes a stale or optimistic node's root produce a submitted message, which the existing asserts catch. --- crates/validator/src/beacon_node/health.rs | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/crates/validator/src/beacon_node/health.rs b/crates/validator/src/beacon_node/health.rs index 70037de6c..b0e589bb4 100644 --- a/crates/validator/src/beacon_node/health.rs +++ b/crates/validator/src/beacon_node/health.rs @@ -787,7 +787,6 @@ mod tests { use crate::beacon_node::ValidatorEntry; use crate::beacon_node::dto::{PtcDutyDto, SyncDutyDto, encode_hex}; use crate::duties::DutiesService; - use crate::keys::ValidatorStore; use crate::payload_attestation::PayloadAttestationService; use crate::proposer_settings::ProposerSettings; use crate::signing::SigningContext; @@ -835,9 +834,13 @@ mod tests { "the next slot signs nothing" ); - let store = RwLock::new(ValidatorStore::new()); + // A real key, so a node that did serve the head root or the payload + // data would get a signed message submitted, which the asserts below + // catch. With no key the services sign nothing either way. + let (store, pubkeys) = crate::test_support::store_with_keys(1); + let store = RwLock::new(store); let sync_duty = SyncDutyDto { - pubkey: encode_hex(&[1u8; 48]), + pubkey: encode_hex(&pubkeys[0].0), validator_index: 11, validator_sync_committee_indices: vec![0], }; @@ -849,7 +852,7 @@ mod tests { assert!(root.is_none(), "no head root to sign"); let ptc_duty = PtcDutyDto { - pubkey: encode_hex(&[1u8; 48]), + pubkey: encode_hex(&pubkeys[0].0), validator_index: 11, slot: slot + 1, }; @@ -877,7 +880,6 @@ mod tests { use tokio::sync::RwLock; use crate::beacon_node::dto::{SyncDutyDto, encode_hex}; - use crate::keys::ValidatorStore; use crate::signing::SigningContext; use crate::sync_committee::SyncCommitteeService; @@ -890,12 +892,15 @@ mod tests { ethlambda_types::beacon::config::Config::mainnet(), Root::ZERO, )); + // A real key, so a stale root that reached the service would be signed + // and submitted, which the assert below catches. + let (store, pubkeys) = crate::test_support::store_with_keys(1); + let store = RwLock::new(store); let duty = SyncDutyDto { - pubkey: encode_hex(&[1u8; 48]), + pubkey: encode_hex(&pubkeys[0].0), validator_index: 11, validator_sync_committee_indices: vec![0], }; - let store = RwLock::new(ValidatorStore::new()); for nodes in [vec![stale()], vec![failing_synced, stale()]] { let beacon_node = Arc::new(fallback(nodes)); From fd499a02b935d54198b58251cefca138acea838b Mon Sep 17 00:00:00 2001 From: Pablo Deymonnaz Date: Thu, 26 Nov 2026 18:33:15 -0300 Subject: [PATCH 12/12] fix(validator): don't rank a slow node failing after a broadcast cuts it off, and give the envelope's producer a head start - A node a broadcast stops waiting for 500 ms after the first acceptance is no longer ranked Failing. One that is only slower (to import a block, or to take a large envelope) was cut out of every broadcast until its next probe, slot after slot. A hung node still costs a broadcast at most the grace, and its probe ranks it failing. `NodeHealth::record_no_answer` is removed. - Under `--broadcast blocks` the envelope's producer gets a 500 ms head start (`PRODUCER_HEAD_START`) rather than an unbounded wait. A producer that holds the request open (one that answered the block 202 waits for a block it never imported) no longer keeps the envelope from every node until the proposal's deadline cuts the reveal; past the head start its answer is awaited with the others' (`Sent::Pending`). - An envelope without its blobs that the producer refused is not sent to it a second time by the walk (`Reach::EveryBut`). - `register_validators_in_batches` records failed batches against node health. --- crates/validator/src/beacon_node/fallback.rs | 295 ++++++++++++++----- crates/validator/src/beacon_node/health.rs | 16 - crates/validator/src/beacon_node/mock.rs | 16 +- docs/cli.md | 27 +- 4 files changed, 261 insertions(+), 93 deletions(-) diff --git a/crates/validator/src/beacon_node/fallback.rs b/crates/validator/src/beacon_node/fallback.rs index cadc92624..0c4d519d4 100644 --- a/crates/validator/src/beacon_node/fallback.rs +++ b/crates/validator/src/beacon_node/fallback.rs @@ -85,10 +85,38 @@ type BoxFuture<'a, T> = Pin + Send + 'a>>; /// accepted. The message is on the network by then, and a caller with a /// deadline (a proposal's is the attestation offset, 3 s into a 12 s gloas /// slot) would otherwise wait out a hung node's whole request timeout, be cut -/// at its deadline, and never learn that node did not answer. A node still -/// sending when this runs out is cut off and ranked failing. +/// at its deadline. A node still sending when this runs out is cut off, but +/// not ranked failing for it: a node that imports a block more slowly than the +/// fastest one, or uploads a large envelope over a slower link, answers late +/// every time, and ranking it failing would cut it out of every broadcast +/// until the next probe, slot after slot. A node that really hung is ranked +/// failing by its probe, and until then costs each broadcast this much. const BROADCAST_GRACE: Duration = Duration::from_millis(500); +/// How long an envelope's producer is waited on alone before the other nodes +/// are sent the envelope too, under `--broadcast blocks`. Long enough for a +/// producer holding the block to answer, so the others get the envelope a +/// round trip after it; short enough that a producer that holds the request +/// open (one that answered 202 and never imported the block waits for it) does +/// not keep the envelope from every node until the proposal's deadline. +const PRODUCER_HEAD_START: Duration = BROADCAST_GRACE; + +/// What a caller of [`FallbackBeaconNode::broadcast_to_all`] has already done +/// with one node, which the broadcast then leaves out of its own sends. +enum Sent<'p, T> { + /// Nothing: every node is the broadcast's. + Nothing, + /// Sent and answered; `accepted` counts as an acceptance for the + /// broadcast's rules. + Answered { position: usize, accepted: bool }, + /// Sent and not answered yet: the broadcast waits on it as on its own + /// sends. + Pending { + position: usize, + send: BoxFuture<'p, Result>, + }, +} + /// Which nodes a request may be sent to. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Reach { @@ -99,6 +127,9 @@ enum Reach { /// for in that state. A node with no probe to read is still asked (see /// [`Standing::may_serve_ungated`]). SkipUnsynced, + /// Every node but the one at this position, which the caller has already + /// asked. + EveryBut(usize), } /// One kind of signed message `--broadcast` can send to every node. @@ -746,7 +777,7 @@ impl FallbackBeaconNode { let Some(node) = self.nodes.get(position) else { continue; }; - if !self.is_usable(position) { + if !self.is_usable(position) || reach == Reach::EveryBut(position) { continue; } if reach == Reach::SkipUnsynced && !standing.may_serve_ungated() { @@ -916,13 +947,14 @@ impl FallbackBeaconNode { /// /// Every node not ranked [`Tier::Failing`] is sent it together. The call /// waits for them until one accepts, and then at most [`BROADCAST_GRACE`] - /// longer: a node still sending by then is cut off and ranked failing. The - /// failing ones are sent it only when none of the others accepted: a node - /// that timed out on the last request or probe would otherwise hold every - /// broadcast back, while a node that accepted has already put the message - /// on the network. `sent` is a position the caller has already sent to - /// itself, left out here, and whether it accepted, which counts as an - /// acceptance for both rules. + /// longer: a node still sending by then is cut off, though not ranked + /// failing for it (see [`BROADCAST_GRACE`]). The failing ones are sent it + /// only when none of the others accepted: a node that timed out on the + /// last request or probe would otherwise hold every broadcast back, while + /// a node that accepted has already put the message on the network. + /// `sent` is a node the caller has already sent to itself, left out here: + /// its acceptance counts for both rules, and a send still waiting for its + /// answer is waited on with the broadcast's own. /// /// Each answer that says the node stopped answering is recorded, as the /// walk records it. What each answer means is the caller's to read. @@ -932,56 +964,69 @@ impl FallbackBeaconNode { async fn broadcast_to_all<'p, T, F>( &'p self, what: &'static str, - sent: Option<(usize, bool)>, + sent: Sent<'p, T>, call: F, ) -> Vec<(usize, Result)> where F: Fn(&'p B) -> BoxFuture<'p, Result>, { - let skip = sent.map(|(position, _)| position); - let accepted_already = sent.is_some_and(|(_, accepted)| accepted); + let (skip, accepted_already, pending) = match sent { + Sent::Nothing => (None, false, None), + Sent::Answered { position, accepted } => (Some(position), accepted, None), + Sent::Pending { position, send } => (Some(position), false, Some((position, send))), + }; let (failing, first): (Vec<_>, Vec<_>) = self .health .tiers() .into_iter() .filter(|(position, _)| Some(*position) != skip && self.is_usable(*position)) .partition(|(_, tier)| *tier == Tier::Failing); - let mut answers = self.send_to(what, first, accepted_already, &call).await; + let sends = pending + .into_iter() + .chain(self.sends_to(first, &call)) + .collect(); + let mut answers = self.send_to(what, sends, accepted_already).await; if !accepted_already && !answers.iter().any(|(_, answer)| answer.is_ok()) { - answers.extend(self.send_to(what, failing, false, &call).await); + let sends = self.sends_to(failing, &call).collect(); + answers.extend(self.send_to(what, sends, false).await); } answers } - /// Send to the nodes at `positions` at once, and record each node that did - /// not answer. Waits for every send until one accepts (or from the start, - /// when `accepted` says one already has), then at most - /// [`BROADCAST_GRACE`] for the rest, which are then dropped and recorded - /// as not answering. - async fn send_to<'p, T, F>( + /// `call` started on each node at `positions`, by position. + fn sends_to<'p, T, F>( &'p self, - what: &'static str, positions: Vec<(usize, Tier)>, - accepted: bool, call: &F, - ) -> Vec<(usize, Result)> + ) -> impl Iterator>)> where F: Fn(&'p B) -> BoxFuture<'p, Result>, { + positions + .into_iter() + .filter_map(|(position, _)| Some((position, call(self.nodes.get(position)?)))) + } + + /// Await `sends` at once, and record each node that said it is not + /// answering. Waits for every send until one accepts (or from the start, + /// when `accepted` says one already has), then at most + /// [`BROADCAST_GRACE`] for the rest, which are then dropped. + async fn send_to<'p, T>( + &'p self, + what: &'static str, + sends: Vec<(usize, BoxFuture<'p, Result>)>, + accepted: bool, + ) -> Vec<(usize, Result)> { use futures_util::StreamExt as _; - let mut outstanding: Vec = Vec::new(); - let mut sends: futures_util::stream::FuturesUnordered<_> = positions + let mut outstanding: Vec = sends.iter().map(|(position, _)| *position).collect(); + let mut sends: futures_util::stream::FuturesUnordered<_> = sends .into_iter() - .filter_map(|(position, _)| { - let send = call(self.nodes.get(position)?); - outstanding.push(position); - Some(async move { - let answer = send - .await - .inspect_err(|err| self.health.record_request_failure(position, what, err)); - (position, answer) - }) + .map(|(position, send)| async move { + let answer = send + .await + .inspect_err(|err| self.health.record_request_failure(position, what, err)); + (position, answer) }) .collect(); let mut grace_ends = accepted.then(|| tokio::time::Instant::now() + BROADCAST_GRACE); @@ -1003,9 +1048,10 @@ impl FallbackBeaconNode { } answers.push((position, answer)); } + // Not ranked failing: a node that answers late is not a hung one, and + // its probe says which (see `BROADCAST_GRACE`). for position in outstanding { debug!(%what, position, "Beacon node had not answered a broadcast another node accepted; not waiting for it"); - self.health.record_no_answer(position, what); } answers } @@ -1064,7 +1110,7 @@ impl FallbackBeaconNode { if !broadcast { return self.try_each(what, call).await; } - let answers = self.broadcast_to_all(what, None, call).await; + let answers = self.broadcast_to_all(what, Sent::Nothing, call).await; Self::best_answer(what, answers, |count, held| count > held) } @@ -1082,7 +1128,7 @@ impl FallbackBeaconNode { if !broadcast { return self.try_each(what, call).await; } - let answers = self.broadcast_to_all(what, None, call).await; + let answers = self.broadcast_to_all(what, Sent::Nothing, call).await; Self::best_answer(what, answers, |_, _| false) } } @@ -1237,7 +1283,7 @@ impl BeaconNodeApi for FallbackBeaconNode { .await; } let answers = self - .broadcast_to_all(what, None, |node| node.publish_block(fork, body)) + .broadcast_to_all(what, Sent::Nothing, |node| node.publish_block(fork, body)) .await; let accepted = answers.iter().any(|(_, answer)| answer.is_ok()); for (position, answer) in &answers { @@ -1360,6 +1406,8 @@ impl BeaconNodeApi for FallbackBeaconNode { Ok(()) => accepted[batch] = true, Err(err) => { refused += 1; + self.health + .record_request_failure(position, "register_validators", &err); let detail = err.to_string(); first_refusal.get_or_insert_with(|| detail.clone()); last[batch] = Some(detail); @@ -1475,15 +1523,21 @@ impl BeaconNodeApi for FallbackBeaconNode { /// the one node certain to hold the block the envelope reveals (it built /// it, and imported it on publish), so its answer comes first and puts /// the envelope on the network. The others are sent it once the producer - /// has answered: a node that has not imported the block yet queues or - /// drops its envelope, and each has had the block a round trip longer by - /// then. It succeeds when any node accepted. + /// has answered, or once [`PRODUCER_HEAD_START`] has passed without an + /// answer: a node that has not imported the block yet queues or drops + /// its envelope, and each has had the block a round trip longer by then, + /// but a producer that holds the request open (one that answered the + /// block 202 and never imported it waits for it) must not keep the + /// envelope from every node until the proposal's deadline cuts the reveal. + /// Past the head start the producer's answer is awaited with the others'. + /// It succeeds when any node accepted. /// /// Two exceptions. A body without its blobs (`blob_data_included: false`) /// goes to the producer first, whatever its rank and with or without the /// flag, since only it cached the blobs at production time; if it does - /// not take it, the walk follows, as without the flag, since a block with - /// no blobs can be revealed through any node. And for a body with them, a + /// not take it, the walk follows among the other nodes, as without the + /// flag, since a block with no blobs can be revealed through any node. + /// And for a body with them, a /// producer ranked failing (it did not answer a request since its last /// probe, the block's own publish perhaps) is not waited on first: it is /// one of the failing nodes the broadcast reaches only if no other node @@ -1511,30 +1565,53 @@ impl BeaconNodeApi for FallbackBeaconNode { // goes to such a node: the walk, or the broadcast, takes it instead. let producer_usable = self.is_usable(position); if !blob_data_included { - if producer_usable { - let answer = node - .publish_execution_payload_envelope(body, false) - .await - .inspect_err(|err| self.health.record_request_failure(position, what, err)); - let Err(err) = answer else { - return Ok(()); - }; - debug!(%what, position, %err, "The producer did not take its envelope; trying the walk"); + if !producer_usable { + return self.publish_execution_payload_envelope(body, false).await; } - return self.publish_execution_payload_envelope(body, false).await; + let answer = node + .publish_execution_payload_envelope(body, false) + .await + .inspect_err(|err| self.health.record_request_failure(position, what, err)); + let Err(err) = answer else { + return Ok(()); + }; + // The walk leaves the producer out: it just answered this very + // body. With no other node to walk, its answer is the outcome. + if self.usable_nodes().all(|(usable, _)| usable == position) { + let detail = self.failure_detail(Some(err)); + warn!(%what, %detail, "All configured beacon nodes failed; duty likely missed"); + return Err(Error::AllBeaconNodesFailed(detail)); + } + debug!(%what, position, %err, "The producer did not take its envelope; trying the walk"); + return self + .try_each_at_inner(what, true, Reach::EveryBut(position), |node| { + node.publish_execution_payload_envelope(body, false) + }) + .await + .map(|(_, ())| ()); } let producer_failing = !producer_usable || self.health.tiers().contains(&(position, Tier::Failing)); + // The producer alone first, for at most `PRODUCER_HEAD_START`; past + // that, the rest are sent it while its answer is still awaited. let mut answers = Vec::new(); - let mut sent = None; + let mut sent = Sent::Nothing; if !producer_failing { - let answer = node - .publish_execution_payload_envelope(body, true) - .await - .inspect_err(|err| self.health.record_request_failure(position, what, err)); - sent = Some((position, answer.is_ok())); - answers.push((position, answer)); + let mut send = node.publish_execution_payload_envelope(body, true); + sent = match tokio::time::timeout(PRODUCER_HEAD_START, &mut send).await { + Ok(answer) => { + let answer = answer + .inspect_err(|err| self.health.record_request_failure(position, what, err)); + let accepted = answer.is_ok(); + answers.push((position, answer)); + Sent::Answered { position, accepted } + } + Err(_) => { + debug!(%what, position, "The producer has not answered its envelope yet; sending it to the other nodes too"); + Sent::Pending { position, send } + } + }; } let rest = self .broadcast_to_all(what, sent, |node| { @@ -3106,8 +3183,9 @@ mod tests { /// 200, wherever it is in the list, and every node that answered got the /// same body. The hung node is not waited for past the grace, so a caller /// with a deadline shorter than the request timeout, as a proposal has, - /// still gets the answer; it is ranked failing from then on, so the next - /// broadcast does not wait for it at all. + /// still gets the answer. Being cut off does not rank it failing (its + /// probe does that), so the next broadcast is sent to it again, and again + /// waits for it no longer than the grace. #[tokio::test(start_paused = true)] async fn a_broadcast_block_answered_202_a_hang_and_200_reports_the_200() { use std::time::Duration; @@ -3128,7 +3206,7 @@ mod tests { .expect("answered before a deadline shorter than the hang") .expect("two nodes took it"); assert_eq!(outcome, Published::Imported); - assert_eq!(fallback.health().tiers()[2], (1, Tier::Failing)); + assert!(!fallback.health().tiers().contains(&(1, Tier::Failing))); for position in [0, 2] { assert_eq!( fallback.nodes[position].published_blocks(), @@ -3144,7 +3222,34 @@ mod tests { .await .expect("two nodes took it"); assert!(started.elapsed() < Duration::from_secs(1)); - assert_eq!(fallback.nodes[1].hung_calls_to("publish_block"), 1); + assert_eq!(fallback.nodes[1].hung_calls_to("publish_block"), 2); + } + + /// A node that answers every broadcast a little later than the grace, as + /// one slower to import a block does, is cut off each time but never + /// ranked failing for it: it is sent every broadcast, rather than being + /// cut out of the rest of each slot's broadcasts until its next probe. + #[tokio::test(start_paused = true)] + async fn a_slow_node_cut_off_by_a_broadcast_is_not_ranked_failing() { + use std::time::Duration; + let slower = BROADCAST_GRACE + Duration::from_millis(100); + let fallback = FallbackBeaconNode::new(vec![ + MockBeaconNode::new(), + MockBeaconNode::new().with_slow_answers(slower), + ]) + .with_broadcast(every_topic()); + + for _ in 0..2 { + let started = tokio::time::Instant::now(); + fallback + .submit_attestations(&[single_attestation(11)], "electra") + .await + .expect("the first node took it"); + // Waited out the grace: the slow node was sent it, every time. + assert!(started.elapsed() >= BROADCAST_GRACE); + assert!(started.elapsed() < slower); + assert!(!fallback.health().tiers().contains(&(1, Tier::Failing))); + } } /// A 202 is still a block on the network, so it is the answer when no node @@ -3309,7 +3414,8 @@ mod tests { } /// Under `--broadcast blocks` an envelope goes to the node that produced - /// its block first, and to the rest only once that node has answered. One + /// its block first, and to the rest only once that node has answered (or + /// its head start ran out; see the next test). One /// without its blobs goes to the producer alone, since only it cached /// them, with or without the flag. Without the flag, one with its blobs is /// the first node in the walk that takes it, as before. @@ -3398,6 +3504,63 @@ mod tests { vec![(b"bare".to_vec(), false)] ); } + + // The walk leaves out the producer that just refused it: with no + // other node, its refusal is the outcome. + let alone = FallbackBeaconNode::new(vec![refusing()]).with_broadcast(blocks); + let err = alone + .publish_execution_payload_envelope_produced_by(Producer::at(0), b"bare", false) + .await + .expect_err("the only node refused it"); + assert!( + matches!(&err, Error::AllBeaconNodesFailed(detail) if detail.contains("no cached blobs")), + "got {err:?}" + ); + } + + /// A producer that holds its envelope's request open, as one that + /// answered the block 202 and waits for a block it never imported does, + /// keeps the envelope from the other nodes for its head start only. They + /// are sent it then, so the reveal lands well inside a proposal's + /// deadline, which would otherwise cut it before any other node had it. + #[tokio::test(start_paused = true)] + async fn a_producer_that_holds_its_envelope_open_does_not_keep_it_from_the_rest() { + let fallback = FallbackBeaconNode::new(vec![ + MockBeaconNode::new(), + MockBeaconNode::new().with_hang(TIMEOUT), + MockBeaconNode::new(), + ]) + .with_broadcast(Broadcast { + blocks: true, + ..Broadcast::default() + }); + + let deadline = TIMEOUT / 4; + let started = tokio::time::Instant::now(); + tokio::time::timeout( + deadline, + fallback.publish_execution_payload_envelope_produced_by( + Producer::at(1), + b"envelope", + true, + ), + ) + .await + .expect("answered before the deadline") + .expect("the other nodes took it"); + assert!(started.elapsed() <= PRODUCER_HEAD_START + BROADCAST_GRACE); + assert_eq!( + fallback.nodes[1].hung_calls_to("publish_execution_payload_envelope"), + 1, + "the producer was sent it first, and once" + ); + for position in [0, 2] { + assert_eq!( + fallback.nodes[position].published_envelopes(), + vec![(b"envelope".to_vec(), true)], + "node {position}" + ); + } } /// Doppelganger protection's liveness query asks every node at once and diff --git a/crates/validator/src/beacon_node/health.rs b/crates/validator/src/beacon_node/health.rs index 0c13e0ef4..5c7fb9938 100644 --- a/crates/validator/src/beacon_node/health.rs +++ b/crates/validator/src/beacon_node/health.rs @@ -333,13 +333,6 @@ impl NodeHealth { } } - /// Keep that the node at `position` had not answered a broadcast by the - /// time the broadcast stopped waiting for it, a moment after another node - /// accepted: it ranks [`Tier::Failing`] as for a request that timed out. - pub fn record_no_answer(&self, position: usize, what: &'static str) { - self.mark_failing(position, what, &"no answer while another node accepted"); - } - fn mark_failing(&self, position: usize, what: &'static str, err: &dyn std::fmt::Display) { let already = { let mut records = self.write(); @@ -991,15 +984,6 @@ mod tests { assert_eq!(order(&health), vec![0, 1]); } - /// A broadcast that stopped waiting for a node ranks it failing, as a - /// timed-out request does. - #[test] - fn a_node_cut_off_by_a_broadcast_ranks_failing() { - let health = health(vec![synced(3), synced(3)]); - health.record_no_answer(0, "publish_block"); - assert_eq!(health.tiers()[1], (0, Tier::Failing)); - } - /// A request failure is read for as long as a probe is: a probe task that /// stopped leaves every node back in command-line order. #[test] diff --git a/crates/validator/src/beacon_node/mock.rs b/crates/validator/src/beacon_node/mock.rs index b2562f5b3..d45f8032d 100644 --- a/crates/validator/src/beacon_node/mock.rs +++ b/crates/validator/src/beacon_node/mock.rs @@ -89,6 +89,9 @@ pub struct MockBeaconNode { /// The method of every call made while [`Self::hang`] was set, recorded /// on entry. pub hung_calls: Mutex>, + /// When set, a node that answers every call that checks [`Self::hang`], + /// but this much later: slower than its peers, not hung. + pub slow: Option, pub validators: Vec, pub duties: Mutex>, pub proposers: Mutex>, @@ -531,6 +534,13 @@ impl MockBeaconNode { *self.hang.lock().expect("lock") = timeout; } + /// Answer every call that checks [`Self::hang`] `delay` late, as a node + /// that is slower than its peers but answers. + pub fn with_slow_answers(mut self, delay: std::time::Duration) -> Self { + self.slow = Some(delay); + self + } + /// How many calls to `what` were made while the node hung. pub fn hung_calls_to(&self, what: &str) -> usize { self.hung_calls @@ -544,8 +554,12 @@ impl MockBeaconNode { /// For a call that checks it: when the node hangs, wait out the timeout /// and fail as the HTTP client fails a request that got no answer. Checked /// by `sync_status`, `attestation_data`, `publish_block`, - /// `submit_attestations` and `publish_execution_payload_envelope`. + /// `submit_attestations` and `publish_execution_payload_envelope`, which + /// all also wait out [`Self::slow`] first. async fn stall(&self, what: &'static str) -> Result<()> { + if let Some(delay) = self.slow { + tokio::time::sleep(delay).await; + } let hang = *self.hang.lock().expect("lock"); let Some(timeout) = hang else { return Ok(()); diff --git a/docs/cli.md b/docs/cli.md index e05147ea8..f19790eaa 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -721,20 +721,27 @@ change nothing. broadcast only when no other node took it, so a hung node does not hold every broadcast back by a request timeout. - **Half a second after the first acceptance, the rest are cut off.** A node - still sending by then is not waited for and is ranked failing, so a node - that hangs for the first time costs a broadcast half a second, not a - request timeout a proposal's deadline would cut short. + still sending by then is not waited for, so a node that hangs costs a + broadcast half a second, not a request timeout a proposal's deadline would + cut short. It is not ranked failing for it: a node that is only slower (to + import a block, or to take a large envelope) would otherwise be dropped + from every broadcast until its next probe, slot after slot. A node that + really hung is ranked failing once its probe gets no answer. - **A block reports the best answer**: imported (`200`) over broadcast but not imported (`202`) over refused, each node's answer logged. A blinded block still goes only to the node that produced it. - **An envelope goes to its block's producer first**, then to the other - nodes once the producer has answered. The producer certainly holds the - block the envelope reveals; a node that has not imported it yet queues or - drops the envelope, and waiting for the producer's answer gives each a - round trip longer to import it. An envelope sent without its blobs goes to - the producer first, with or without the flag, since only it cached them; - if it does not take it, the other nodes are tried in rank order, since a - block with no blobs can be revealed through any of them. + nodes once the producer has answered, or after half a second without an + answer. The producer certainly holds the block the envelope reveals; a + node that has not imported it yet queues or drops the envelope, and + waiting for the producer's answer gives each a round trip longer to import + it. The half-second bound is for a producer that holds the request open + (one that answered the block `202` and never imported it waits for it), + which would otherwise keep the envelope from every node until the + proposal's deadline. An envelope sent without its blobs goes to the + producer first, with or without the flag, since only it cached them; if it + does not take it, the other nodes are tried in rank order, since a block + with no blobs can be revealed through any of them. - **Signed once.** Every message is signed, and recorded by slashing protection, before it is sent, however many nodes it is sent to.