diff --git a/CLAUDE.md b/CLAUDE.md index d658c778a..b18d9ae19 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -959,11 +959,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 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 + 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 cde197219..2b162b471 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 aa644f422..ff85d0a96 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, }; @@ -24,13 +25,24 @@ 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` (also accepted for Lighthouse + /// compatibility, changing nothing). 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 @@ -348,6 +360,7 @@ async fn run_client(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(), event_stream: !options.disable_event_stream, }; ethlambda_validator::run(config, || stop.start()) @@ -477,6 +490,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"), @@ -607,6 +621,37 @@ 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()); + let options = parse(&["--broadcast", "none"]).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/dto.rs b/crates/validator/src/beacon_node/dto.rs index 1041cd97e..70add53a6 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 495347b7c..0c4d519d4 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 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 +//! 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. //! //! # Only nodes on this client's chain //! @@ -41,7 +65,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, @@ -57,6 +81,42 @@ 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. 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 { @@ -67,6 +127,85 @@ 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. +#[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, + /// `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); 5] = [ + ("attestations", Self::Attestations), + ("blocks", Self::Blocks), + ("sync-committee", Self::SyncCommittee), + ("subscriptions", Self::Subscriptions), + ("none", Self::Nothing), + ]; +} + +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 | BroadcastTopic::Nothing => {} + } + } + broadcast + } } /// What an error says when every node was skipped for being on another chain @@ -181,15 +320,19 @@ impl NodeState { } } -/// A `BeaconNodeApi` backed by an ordered list of others, answering from the -/// first one that succeeds. +/// 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, /// The chain check's state of each node, by position in `nodes`. Built /// with it and never resized, so the two always line up. states: Vec, @@ -209,11 +352,19 @@ impl FallbackBeaconNode { Self { nodes, health, + broadcast: Broadcast::default(), states, readmissions: AtomicU64::new(0), } } + /// 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 /// reads the records the walk is ordered by. pub fn health(&self) -> &Arc { @@ -536,9 +687,10 @@ impl FallbackBeaconNode { /// whose usable flag is down (on another chain, or not checked yet) is /// skipped without a request. /// - /// 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 @@ -625,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() { @@ -639,8 +791,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); } } @@ -761,6 +915,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); } } @@ -786,6 +941,205 @@ 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. The call + /// waits for them until one accepts, and then at most [`BROADCAST_GRACE`] + /// 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. + /// + /// "Every node" is every node on this client's chain: a node whose usable + /// flag is down is never sent a signed message. + async fn broadcast_to_all<'p, T, F>( + &'p self, + what: &'static str, + sent: Sent<'p, T>, + call: F, + ) -> Vec<(usize, Result)> + where + F: Fn(&'p B) -> BoxFuture<'p, Result>, + { + 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 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()) { + let sends = self.sends_to(failing, &call).collect(); + answers.extend(self.send_to(what, sends, false).await); + } + answers + } + + /// `call` started on each node at `positions`, by position. + fn sends_to<'p, T, F>( + &'p self, + positions: Vec<(usize, Tier)>, + call: &F, + ) -> 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 = sends.iter().map(|(position, _)| *position).collect(); + let mut sends: futures_util::stream::FuturesUnordered<_> = sends + .into_iter() + .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); + 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)); + } + // 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"); + } + 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); + } + // No answer at all: every node was skipped for not being on this + // client's chain. + let detail = refusals + .pop() + .map(|(_, err)| err.to_string()) + .unwrap_or_else(|| NO_USABLE_NODE.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, Sent::Nothing, 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, Sent::Nothing, 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] @@ -903,25 +1257,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, Sent::Nothing, |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 @@ -963,6 +1346,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 @@ -1016,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); @@ -1109,7 +1501,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], @@ -1121,6 +1515,113 @@ impl BeaconNodeApi for FallbackBeaconNode { .await } + /// Without `--broadcast blocks`, [`Self::publish_execution_payload_envelope`]: + /// 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 + /// 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, 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 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 + /// 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 && blob_data_included { + 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() + )) + })?; + // A producer that left this client's chain is not sent it, as no call + // 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 { + 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 = Sent::Nothing; + if !producer_failing { + 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| { + node.publish_execution_payload_envelope(body, true) + }) + .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 @@ -1143,22 +1644,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 @@ -1179,12 +1684,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 @@ -1251,13 +1757,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 } @@ -1275,13 +1784,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 } @@ -2472,6 +2984,612 @@ 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 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. 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; + 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 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!(!fallback.health().tiers().contains(&(1, Tier::Failing))); + 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"), 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 + /// 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 (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. + #[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()); + + 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" + ); + + // 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)] + ); + } + + // 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 + /// 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 b0e589bb4..625c55a7b 100644 --- a/crates/validator/src/beacon_node/health.rs +++ b/crates/validator/src/beacon_node/health.rs @@ -24,10 +24,19 @@ //! 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. 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 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 //! fallback does not ask a node whose last probe reported syncing or @@ -36,16 +45,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 +64,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 +99,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 +110,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 +184,77 @@ 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. 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, + /// 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 sent 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 +292,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 +317,103 @@ 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 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) { + self.mark_failing(position, what, err); + } } - /// Stop reading a probe for routing once it is older than `age`. + 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 { + 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, 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) + // 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; + } + (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 +424,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 +434,113 @@ 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, 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 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() + } + + /// 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 ranked_at(&self, now: SystemTime) -> Vec<(usize, Standing)> { + 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, (bool, bool))> = 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, 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, 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 /// 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 +548,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 +561,25 @@ 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()) +} + +/// 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. 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) } /// The duty loop's gate for `slot`, read at its boundary: whether the slot's @@ -372,7 +605,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 } @@ -555,8 +787,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 +826,180 @@ 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]); + } + + /// 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] + 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 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 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 +1033,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 be98dd118..ff8a567c8 100644 --- a/crates/validator/src/beacon_node/mock.rs +++ b/crates/validator/src/beacon_node/mock.rs @@ -82,6 +82,17 @@ 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>, + /// 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>, @@ -648,6 +659,57 @@ 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; + } + + /// 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 + .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`, 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(()); + }; + 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) { @@ -1076,6 +1138,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()) } @@ -1127,6 +1190,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.delay_first_call("attestation_data").await; @@ -1224,6 +1288,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() @@ -1356,6 +1421,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 { @@ -1423,6 +1489,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 09ee15eee..59389cbe9 100644 --- a/crates/validator/src/beacon_node/mod.rs +++ b/crates/validator/src/beacon_node/mod.rs @@ -694,6 +694,27 @@ 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, and for a body without its + /// blobs, with or without the flag, to send it to the producing node + /// 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, + 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/client_health.rs b/crates/validator/src/client_health.rs new file mode 100644 index 000000000..f8042e719 --- /dev/null +++ b/crates/validator/src/client_health.rs @@ -0,0 +1,754 @@ +//! 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. +//! - **`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. A +//! refresh that resolved no validator holds no schedule to run out, and +//! counts through the next epoch. +//! +//! # Status +//! +//! - `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 +//! 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 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"; + +/// 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; + +/// [`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. +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, + /// 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, +} + +struct Attached { + nodes: Arc, + /// How old a probe may be and still be read. + read_for: Duration, + /// What says which epoch it is, for the schedule check. + clock: SlotClock, + 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), + covered_through: AtomicU64::new(NOT_REFRESHED), + attached: OnceLock::new(), + } + } + + /// Read the beacon nodes' probes from `nodes`, judging a probe stale past + /// 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: clock.slot_duration() * PROBE_READ_SLOTS, + clock, + protection, + }); + } + + /// 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.covered_through + .store(covered_through, Ordering::Relaxed); + self.started.store(true, Ordering::Relaxed); + } + + /// 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 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. + 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 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 && schedule_current { + 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, + schedule_current, + }, + } + } + + /// 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, + pub schedule_current: 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)) + } + + /// 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(), clock(), SlashingProtection::in_memory()); + (health, probes) + } + + /// The body is the issue's: `status`, `service` and the four checks, each + /// with exactly the fields it names, plus `schedule_current`. + #[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, 0); + + 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, + "schedule_current": true, + } + }) + ); + } + + /// 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_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 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 = 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 + /// 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(), + clock(), + 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: 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); + 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, 0); + 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, 0); + 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, 0); + 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, 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(), clock(), protection.clone()); + probes.record(0, synced()); + health.epoch_refreshed(1, 0); + 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, 0); + + 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/duties.rs b/crates/validator/src/duties.rs index 4eba16dcc..4550f8bda 100644 --- a/crates/validator/src/duties.rs +++ b/crates/validator/src/duties.rs @@ -503,18 +503,18 @@ 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 { self.ptc.contains_key(&epoch) } - /// Whether an attester schedule is held for `epoch`, an empty one - /// included. - pub fn holds_attesters(&self, epoch: Epoch) -> bool { - self.by_epoch.contains_key(&epoch) - } - /// Whether a proposer schedule is held for `epoch`, an empty one /// included: "none of ours" is an answer too. pub fn holds_proposers(&self, epoch: Epoch) -> bool { diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index 7500ebba0..805c92c87 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -29,6 +29,7 @@ pub mod aggregation_selection; pub mod attestation; pub mod beacon_node; pub mod chain_check; +pub mod client_health; pub mod doppelganger; pub mod duties; pub mod error; @@ -174,6 +175,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, /// Read the beacon nodes' event streams, so attestations and sync /// committee messages go out when the slot's block arrives and payload /// votes when its payload does, rather than only at their deadlines. See @@ -287,6 +291,12 @@ where // 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 waits for one at startup, for as long @@ -301,8 +311,9 @@ where 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"); } }); @@ -312,7 +323,7 @@ where .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)); // The chain the client runs on is the first node's that answers, waiting // for one while none does; every other node is checked against it, and a @@ -366,6 +377,11 @@ where "Slashing protection loaded" ); let protection = slashing_protection::SharedProtection::new(protection); + health.attach( + beacon_node.health().clone(), + clock.clone(), + 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 @@ -687,6 +703,9 @@ where Ok(settled) => owed = settled, Err(err) => return Err(err), } + if owed.is_some() { + report_refreshed(&health, &duties, epoch, resolved.len()); + } } // A node the chain check let back in since the last slot was @@ -878,6 +897,7 @@ where ); match settled { Ok(Some(owed)) => { + report_refreshed(&health, &duties, epoch, resolved.len()); send_owed( owed, epoch, @@ -1260,7 +1280,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(_) => { @@ -1370,13 +1389,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); } } } @@ -1414,7 +1426,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!( @@ -1612,7 +1623,6 @@ async fn ahead_of_block( Ok(Ok(())) => {} Ok(Err(err)) => { warn!(%slot, %err, "Proposer duties fetch failed; asking again next slot"); - metrics::set_beacon_node_available(false); } Err(_) => { warn!( @@ -1690,7 +1700,6 @@ fn settle_refresh( "Failed to refresh duties: the beacon node is syncing or optimistic; keeping the \ previous schedule and proposing no block until a refresh gets through" ); - metrics::set_beacon_node_available(false); *node_syncing = true; Ok(None) } @@ -1700,7 +1709,6 @@ fn settle_refresh( // 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); Ok(None) } // Unreachable today: every error `refresh_epoch` can produce comes @@ -1717,6 +1725,26 @@ fn settle_refresh( } } +/// Tell `/health` that `epoch`'s refresh got through, resolving `resolved` +/// validators, and how far the schedule it left reaches: through the +/// lookahead epoch only when its fetch went through, since `refresh_around` +/// shrugs a failed one off and the schedule then ends with this 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. +fn report_refreshed( + health: &client_health::ClientHealth, + duties: &DutiesService, + epoch: u64, + resolved: usize, +) { + let covered_through = if resolved == 0 || duties.holds_attesters(epoch + 1) { + epoch + 1 + } else { + epoch + }; + health.epoch_refreshed(resolved, covered_through); +} + /// Send what a refresh left owing, from tasks of their own, once the slot's /// block is out: the subnet subscriptions when it moved the attester /// schedule, and the builder registrations of the validators it resolved. @@ -1769,7 +1797,6 @@ fn spawn_subscriptions( let subscribed = subscriptions::subscribe(&beacon_node, &schedule, &store, &context); let _ = subscribed.await.inspect_err(|err| { warn!(%epoch, %err, "Failed to subscribe to attestation subnets"); - metrics::set_beacon_node_available(false); }); }); } @@ -1908,7 +1935,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 { // Taken here, after the last await, rather than from diff --git a/crates/validator/src/metrics.rs b/crates/validator/src/metrics.rs index b5d04360a..5667fb29c 100644 --- a/crates/validator/src/metrics.rs +++ b/crates/validator/src/metrics.rs @@ -319,10 +319,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() }); @@ -532,6 +547,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); @@ -687,6 +703,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); } @@ -750,16 +770,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) => ( [( @@ -776,14 +805,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/proposal.rs b/crates/validator/src/proposal.rs index e08bccfc9..6f12f7040 100644 --- a/crates/validator/src/proposal.rs +++ b/crates/validator/src/proposal.rs @@ -627,6 +627,7 @@ impl ProposalService { pubkey, fork, block_root, + producer, payload, builder_index, body, @@ -644,8 +645,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()) @@ -677,12 +679,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<()> { @@ -718,8 +725,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/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 9bb6e8425..1dd2acdd6 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -443,7 +443,8 @@ slot's end, so a node serving a wrong one cannot park a duty past its slot. | Flag | Default | Meaning | |---|---|---| -| `--beacon-nodes` | required | Base URLs of the beacon nodes to use, comma-separated or repeated. Every node on this client's chain 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. A node on another chain, or not checked yet, is skipped: see [the chain check](#several-beacon-nodes-the-chain-check) and [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 on this client's chain 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. A node on another chain, or not checked yet, is skipped: see [the chain check](#several-beacon-nodes-the-chain-check), [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 on this client's chain 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 | @@ -651,9 +652,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` @@ -662,16 +663,95 @@ 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. + +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 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 +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. + +Every node here means every node on this client's chain: a node the +[chain check](#several-beacon-nodes-the-chain-check) found on another chain, +or has not checked yet, is never probed, asked or sent a broadcast, whatever +its rank, and an envelope whose producer left the chain goes to the others. + +`--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` 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. +- **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, 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, 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. ### Doppelganger protection @@ -1068,6 +1148,69 @@ 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, + "schedule_current": 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. +- **`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. 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: + +- `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 + 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 f5eedc930..9a0be5afa 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 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 |