From e717b9fa60c2d9e429aba0bf2b6aa6a578f027ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Wed, 25 Nov 2026 18:57:15 -0300 Subject: [PATCH 1/3] fix(p2p): park votes for a block still importing, and check them again once it lands A subnet attestation or aggregate whose vote block is not stored yet, or has no cached post-state yet, was reported Ignore(UnknownBlock/StateUnavailable) at once. Validators vote as soon as the block reaches them, so the first votes for every block arrive while this node is still waiting for its columns or running its state transition, and all of them were dropped: not relayed, not pooled for an aggregator here, and never received again, since every peer sends the same message id. Such a vote is now parked under the voted block's root with its verdict withheld, so gossipsub keeps holding the message. The chain actor's import sends BlockChainToP2P::block_state_ready once the post-state is cached, and p2p runs the parked votes' stateful checks again, in blocking batches of 64 on one permit each, reporting whatever they answer. This is lighthouse's reprocess queue; the specification allows it. Bounds: one retry per vote; 16,384 parked at most (lighthouse's cap); a vote still parked 2.5 s after arriving gets its first verdict, inside gossipsub's 3.5 to 4.2 s window. A root announced just before its vote's verdict reaches the actor is remembered (last 64 roots), so that vote is checked again at once rather than waiting out its deadline. New metrics: lean_beacon_gossip_parked_votes_total{kind,result} and lean_beacon_gossip_parked_votes. --- CLAUDE.md | 1 + crates/blockchain/src/beacon_envelope.rs | 19 ++ crates/blockchain/src/lib.rs | 53 ++- crates/net/api/src/lib.rs | 5 + crates/net/p2p/src/beacon/mod.rs | 1 + crates/net/p2p/src/beacon/parked_votes.rs | 335 ++++++++++++++++++ crates/net/p2p/src/beacon/verdict.rs | 395 +++++++++++++++++++++- crates/net/p2p/src/lib.rs | 31 +- crates/net/p2p/src/metrics.rs | 31 ++ crates/net/p2p/src/req_resp/handlers.rs | 1 + docs/beacon_wire.md | 24 ++ docs/metrics.md | 16 +- 12 files changed, 892 insertions(+), 20 deletions(-) create mode 100644 crates/net/p2p/src/beacon/parked_votes.rs diff --git a/CLAUDE.md b/CLAUDE.md index f621ef5f4..c4cc0f13f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -357,6 +357,7 @@ actual_slot = finalized_slot + 1 + relative_index - `fork_digest` is a 4-byte hex string (no `0x` prefix); currently the dummy `12345678` agreed across clients - Mesh size: 8 (6-12 bounds), heartbeat: 700ms - Beacon wire: `validate_messages()` is on, so every beacon message waits for a verdict (~4.2s before gossipsub's cache evicts it). Rules in `state_transition::beacon::gossip` (cheap half inline, stateful half on a bounded `spawn_blocking` task); plumbing in `p2p/src/beacon/verdict.rs`. Lean gossip still auto-forwards + - A subnet attestation or aggregate whose vote block is not imported yet (`UnknownBlock`/`StateUnavailable`) is parked with its verdict withheld (`p2p/src/beacon/parked_votes.rs`, lighthouse's reprocess queue) and checked once more when the chain actor's import sends `block_state_ready`; past 2.5 s, or with 16,384 parked, it gets its first verdict instead - Beacon peer scoring: lighthouse's parameters ported in `p2p/src/beacon/scoring.rs` (block, aggregate, 64 attestation subnets, exits, slashings; columns and sync contributions unscored), refreshed every slot from the head's active validator count. Mesh-delivery scoring (P3) is gated off while the head lags more than 4 slots and for an epoch after, because a catching-up node `Ignore`s every aggregate and would otherwise graylist its own mesh. Every held fork digest is parametrized before `transition::apply` joins it (gossipsub never scores a mesh grafted before its topic had parameters); the previous digest's weights are zeroed at the switch, and the switch restarts the P3 warmup. The swarm disconnects peers below the graylist (-16000) every 10 s, and peers gossipsub reported as `SlowPeer` in every check for a minute (a disabled gossipsub handler never drains its send queue, so the queue's message copies stay in memory until the connection closes). Gossipsub reports an expired forward like a full queue, so our own saturated uplink makes every peer look slow: a report counts only above `SLOW_PEER_REPORT_THRESHOLD` failures (Lighthouse's cut), and one check disconnects at most `MAX_SLOW_PEER_DISCONNECTS_PER_CHECK` peers. Lean runs unscored. See [`docs/beacon_wire.md`](docs/beacon_wire.md#peer-scoring) - Data columns: every check runs in p2p. A column gossip did not accept (`Queue`/`Overloaded`), every fetched column, and parked columns replayed after their parent imports go through the chain checks in `p2p/src/beacon/column_checks.rs`, grouped by block with each `(block, index)` kept once. A group's rules before the KZG proofs run through one `column::ChainPrechecks`, which judges what the block's sidecars share (the fulu signed header's rules, the gloas block lookup) once; the proofs then go through `column::kzg_verdicts` in sub-batches of at most 16 columns, each on its own `column_check_permits` permit, a failed batch re-verified column by column. Each sidecar gets the verdict `column::chain_checks_for` gives it alone. The chain actor stores what it gets unchecked; only debug builds re-run `chain_checks_for` there. A held fulu block's custody columns can also come from the execution client (`engine_getBlobsV2`, `crates/blockchain/src/beacon_blobs.rs`; asked only for a block at most `MAX_ASK_AGE_SLOTS` behind the clock, so not during range sync), put through the same `ChainPrechecks` and `kzg_verdicts` in the chain actor's blocking task (the spec lets a node skip that, this one does not: a stored column keeps every other copy out, and import trusts it), and handed to p2p as `SidecarOrigin::ExecutionLayer` through `check_data_column_sidecars`, which records them seen, publishes them on their subnets and forwards them; see `docs/beacon_engine.md` - Beacon subscribes seven global topics plus two node-id-derived subnet families: custody diff --git a/crates/blockchain/src/beacon_envelope.rs b/crates/blockchain/src/beacon_envelope.rs index 2eb77ccd4..b5c481b57 100644 --- a/crates/blockchain/src/beacon_envelope.rs +++ b/crates/blockchain/src/beacon_envelope.rs @@ -1310,6 +1310,25 @@ pub(crate) mod tests { assert!(server.envelopes.blocks_awaiting_parent_payload.is_empty()); } + #[tokio::test] + #[cfg_attr( + not(feature = "beacon-spec-tests"), + ignore = "needs the fork choice fixtures; run `make consensus-spec-tests`" + )] + async fn an_imported_block_tells_the_p2p_layer_its_state_is_ready() { + let case = Case::new("get_head", TIEBREAK); + let mut server = case.server(12); + let p2p = Arc::new(crate::tests::RecordingP2P::default()); + server.p2p = Some(p2p.clone()); + + server + .on_block(case.block(PARENT), ImportTimings::default()) + .await; + + assert!(server.store.has_state(&root(PARENT)).unwrap()); + assert_eq!(*p2p.states_ready.lock().unwrap(), vec![root(PARENT)]); + } + #[tokio::test] #[cfg_attr( not(feature = "beacon-spec-tests"), diff --git a/crates/blockchain/src/lib.rs b/crates/blockchain/src/lib.rs index fb62201fc..9c93f0ff4 100644 --- a/crates/blockchain/src/lib.rs +++ b/crates/blockchain/src/lib.rs @@ -3421,6 +3421,8 @@ impl BlockChainServer { // This root now has a post-state, which is the one thing every // sidecar parked under it was waiting for. self.drain_sidecars_awaiting_parent(block_root); + // And every vote for it the p2p layer is holding. + self.announce_block_state_ready(block_root); // An envelope that arrived ahead of this block can be judged now. self.note_block_imported_for_envelope(block_root); @@ -3539,6 +3541,21 @@ impl BlockChainServer { } } + /// Tell the p2p layer `block_root` has a post-state now, so the votes for + /// it that arrived while it was still importing can be checked. + /// + /// Beacon only: lean gossip has no verdicts to hold. + pub(crate) fn announce_block_state_ready(&self, block_root: H256) { + if self.store.chain() != Chain::Beacon { + return; + } + if let Some(ref p2p) = self.p2p { + let _ = p2p.block_state_ready(block_root).inspect_err( + |err| error!(%block_root, %err, "Failed to tell the p2p layer a block's state is ready"), + ); + } + } + /// Move pending children of `parent_root` into the work queue for iterative /// processing. This replaces the old recursive `process_pending_children`. fn collect_pending_children( @@ -5235,14 +5252,17 @@ mod tests { } /// Every `BlockChainToP2P` message the chain actor sends, kept for a test - /// to read back. Only `check_data_column_sidecars` and `fetch_block` are - /// recorded: nothing under test here sends the others. + /// to read back. Only `check_data_column_sidecars`, `fetch_block` and + /// `block_state_ready` are recorded: nothing under test here sends the + /// others. #[derive(Default)] pub(crate) struct RecordingP2P { pub(crate) checks: std::sync::Mutex>>, /// The origin each entry of `checks` was handed over with, in order. pub(crate) check_origins: std::sync::Mutex>, pub(crate) fetches: std::sync::Mutex>, + /// Every root announced through `block_state_ready`, in order. + pub(crate) states_ready: std::sync::Mutex>, } impl ethlambda_network_api::BlockChainToP2P for RecordingP2P { @@ -5281,6 +5301,13 @@ mod tests { self.checks.lock().unwrap().push(sidecars); Ok(()) } + fn block_state_ready( + &self, + block_root: H256, + ) -> Result<(), spawned_concurrency::error::ActorError> { + self.states_ready.lock().unwrap().push(block_root); + Ok(()) + } } /// `beacon_server(store)` with a [`RecordingP2P`] wired in as its p2p ref. @@ -5291,6 +5318,28 @@ mod tests { (server, p2p) } + #[test] + fn a_ready_beacon_state_is_announced_and_a_lean_one_is_not() { + let (server, p2p) = beacon_server_recording(beacon_store(GENESIS_TIME, 0)); + server.announce_block_state_ready(H256::repeat_byte(7)); + assert_eq!( + *p2p.states_ready.lock().unwrap(), + vec![H256::repeat_byte(7)] + ); + + // Lean gossip has no verdicts held, so there is nothing to release. + let store = Store::from_anchor_state( + Arc::new(InMemoryBackend::default()), + State::from_genesis(0, Vec::new()), + DEFAULT_MILLISECONDS_PER_SLOT, + ); + let mut server = lean_server(store); + let p2p = Arc::new(RecordingP2P::default()); + server.p2p = Some(p2p.clone()); + server.announce_block_state_ready(H256::repeat_byte(7)); + assert!(p2p.states_ready.lock().unwrap().is_empty()); + } + /// A beacon store whose clock reads slot 10, so a sidecar at slot 10 is /// neither future nor finalized. Fulu is active from genesis, since a /// stored sidecar is decoded as the fork its slot names. diff --git a/crates/net/api/src/lib.rs b/crates/net/api/src/lib.rs index 2d8100c84..5c018a629 100644 --- a/crates/net/api/src/lib.rs +++ b/crates/net/api/src/lib.rs @@ -52,6 +52,11 @@ pub trait BlockChainToP2P: Send + Sync { sidecars: Vec, origin: SidecarOrigin, ) -> Result<(), ActorError>; + /// A beacon block's post-state is now cached under `block_root`. The p2p + /// layer holds the subnet attestations and aggregates that voted for it + /// before it got there, since their checks read that state, and checks + /// them again now. + fn block_state_ready(&self, block_root: H256) -> Result<(), ActorError>; } /// Where the sidecars handed to [`BlockChainToP2P::check_data_column_sidecars`] diff --git a/crates/net/p2p/src/beacon/mod.rs b/crates/net/p2p/src/beacon/mod.rs index a81b7d86c..6342a614c 100644 --- a/crates/net/p2p/src/beacon/mod.rs +++ b/crates/net/p2p/src/beacon/mod.rs @@ -22,6 +22,7 @@ pub mod envelope_checks; pub mod fork_schedule; pub mod handler; pub mod messages; +pub mod parked_votes; pub mod protocols; pub mod scoring; pub mod subnets; diff --git a/crates/net/p2p/src/beacon/parked_votes.rs b/crates/net/p2p/src/beacon/parked_votes.rs new file mode 100644 index 000000000..72e3772fd --- /dev/null +++ b/crates/net/p2p/src/beacon/parked_votes.rs @@ -0,0 +1,335 @@ +//! Subnet attestations and aggregates whose verdict waits for the block they +//! vote for. +//! +//! Validators vote as soon as the slot's block reaches them, so the first +//! votes for a block arrive while this node is still importing it: waiting +//! for its custody columns, or running its state transition. Their stateful +//! checks read the voted block's own post-state, so until the import finishes +//! they answer `Ignore(StateUnavailable)`, or `Ignore(UnknownBlock)` for a +//! block not stored at all. Reported at once, that verdict drops the vote: +//! gossipsub does not relay it, it never reaches the attestation pool an +//! aggregator here reads, and no other copy follows, since every peer sends +//! the same message id. On a devnet with ~130 ms imports this cost each node +//! 5 to 8% of the subnet votes it received. +//! +//! The specification lets a client hold these ("a client MAY queue +//! attestations for processing once block is retrieved"), and lighthouse +//! does: its reprocess queue withholds the verdict, and checks the message +//! again on the block's `BlockImported`. This is the same, keyed by the voted +//! block's root: the verdict channel parks the vote instead of reporting +//! it, gossipsub keeps holding the message meanwhile, and +//! [`BlockChainToP2P::block_state_ready`] releases every vote parked under +//! the root to its stateful checks again. Whatever they answer then is +//! reported and acted on exactly as a first answer would be, so an accepted +//! vote propagates as the original message. +//! +//! What bounds it: +//! +//! - **One retry.** A vote checked again is never parked a second time. +//! - **A deadline inside gossipsub's.** Gossipsub drops a message still +//! waiting for its verdict after `history_length` (6) heartbeats of 700 ms, +//! which is 3.5 to 4.2 s after it arrived, depending on where in a +//! heartbeat it did. [`PARKED_VOTE_DEADLINE`] plus one +//! [`PARKED_VOTE_SWEEP_INTERVAL`] stays under that, so a vote whose block +//! never comes still gets its first verdict, as it would have before. +//! - **A cap.** Votes are parked before their signature is checked, so at +//! [`MAX_PARKED_VOTES`] the next one is reported as it would have been +//! before this queue existed. +//! +//! The import signal can win the race against the verdict it releases: the +//! check reads the store on a blocking thread, the import caches the state +//! and sends its signal, and only then does the verdict reach the actor. A +//! vote whose root was announced among the last [`RECENTLY_READY_ROOTS`] is +//! therefore checked again at once instead of being parked. +//! +//! [`BlockChainToP2P::block_state_ready`]: ethlambda_network_api::BlockChainToP2P::block_state_ready + +use std::collections::{HashMap, VecDeque}; +use std::time::{Duration, Instant}; + +use ethlambda_state_transition::beacon::gossip::Outcome; +use ethlambda_types::beacon::primitives::Root; + +use crate::beacon::verdict::{GossipId, Validated}; + +/// How many votes may be parked at once. Lighthouse's +/// `MAXIMUM_QUEUED_ATTESTATIONS`. +pub(crate) const MAX_PARKED_VOTES: usize = 16_384; + +/// How long after its arrival a parked vote may still wait for its block. +/// See the module documentation for why it must stay under 3.5 s with +/// [`PARKED_VOTE_SWEEP_INTERVAL`] added. +pub(crate) const PARKED_VOTE_DEADLINE: Duration = Duration::from_millis(2_500); + +/// How often parked votes past [`PARKED_VOTE_DEADLINE`] are swept while any +/// are parked. +pub(crate) const PARKED_VOTE_SWEEP_INTERVAL: Duration = Duration::from_millis(250); + +/// How many recently announced roots are remembered, for the race the module +/// documentation describes. About one block a slot is announced, so this +/// covers the last few minutes, far longer than any check takes. +const RECENTLY_READY_ROOTS: usize = 64; + +/// A vote whose verdict is withheld until its block's post-state is ready. +pub(crate) struct ParkedVote { + pub(crate) id: GossipId, + pub(crate) object: Validated, + /// What its first check answered: the verdict it gets if it is never + /// checked again. + pub(crate) outcome: Outcome, +} + +impl ParkedVote { + /// Whether it is too late to check this vote again: gossipsub would drop + /// it before a second verdict could reach it. + pub(crate) fn expired(&self, now: Instant) -> bool { + now.saturating_duration_since(self.id.received_at) >= PARKED_VOTE_DEADLINE + } +} + +/// What [`ParkedVotes::park`] did with a vote. +pub(crate) enum Parking { + /// Parked until its root is announced or its deadline passes. + Parked, + /// Its root was already announced: check it again now. + Ready(ParkedVote), + /// The queue is full: report its first verdict now. + Full(ParkedVote), +} + +/// The parked votes, by the root of the block they vote for. +#[derive(Default)] +pub(crate) struct ParkedVotes { + by_root: HashMap>, + len: usize, + recently_ready: VecDeque, + /// Whether an expiry sweep is already scheduled, so parking a vote never + /// starts a second timer. + sweep_scheduled: bool, +} + +impl ParkedVotes { + /// Park `vote` under `root`, the block it votes for. + pub(crate) fn park(&mut self, root: Root, vote: ParkedVote) -> Parking { + if self.recently_ready.contains(&root) { + return Parking::Ready(vote); + } + if self.len >= MAX_PARKED_VOTES { + return Parking::Full(vote); + } + self.by_root.entry(root).or_default().push(vote); + self.len += 1; + Parking::Parked + } + + /// `root` has a post-state now: take every vote parked under it, and + /// remember the root for a verdict still on its way (see the module + /// documentation). + pub(crate) fn take_ready(&mut self, root: Root) -> Vec { + if !self.recently_ready.contains(&root) { + if self.recently_ready.len() == RECENTLY_READY_ROOTS { + self.recently_ready.pop_front(); + } + self.recently_ready.push_back(root); + } + let votes = self.by_root.remove(&root).unwrap_or_default(); + self.len -= votes.len(); + votes + } + + /// Take every vote past its deadline at `now`. + pub(crate) fn take_expired(&mut self, now: Instant) -> Vec { + let mut expired = Vec::new(); + self.by_root.retain(|_, votes| { + let (late, waiting): (Vec<_>, Vec<_>) = std::mem::take(votes) + .into_iter() + .partition(|vote| vote.expired(now)); + expired.extend(late); + *votes = waiting; + !votes.is_empty() + }); + self.len -= expired.len(); + expired + } + + pub(crate) fn len(&self) -> usize { + self.len + } + + pub(crate) fn is_empty(&self) -> bool { + self.len == 0 + } + + /// Mark a sweep as scheduled. `true` when none was, meaning the caller + /// must schedule it. + pub(crate) fn claim_sweep(&mut self) -> bool { + !std::mem::replace(&mut self.sweep_scheduled, true) + } + + /// The scheduled sweep is running: the next park schedules another. + pub(crate) fn sweep_started(&mut self) { + self.sweep_scheduled = false; + } +} + +#[cfg(test)] +mod tests { + use ethlambda_state_transition::beacon::gossip::IgnoreReason; + use ethlambda_types::beacon::containers::electra::SingleAttestation; + use ethlambda_types::beacon::containers::{AttestationData, Checkpoint}; + use libp2p::PeerId; + use libp2p::gossipsub::MessageId; + + use super::*; + + fn vote(attester: u64, received_at: Instant) -> ParkedVote { + ParkedVote { + id: GossipId { + message_id: MessageId::new(&attester.to_le_bytes()), + propagation_source: PeerId::random(), + received_at, + kind: "beacon_attestation", + }, + object: Validated::Attestation { + attestation: Box::new(SingleAttestation { + committee_index: 0, + attester_index: attester, + data: AttestationData { + slot: 1, + index: 0, + beacon_block_root: Root::repeat_byte(1), + source: Checkpoint::default(), + target: Checkpoint::default(), + }, + signature: Default::default(), + }), + subnet_id: 0, + }, + outcome: Outcome::Ignore(IgnoreReason::StateUnavailable), + } + } + + fn attesters(votes: &[ParkedVote]) -> Vec { + let mut attesters: Vec = votes + .iter() + .map(|vote| match &vote.object { + Validated::Attestation { attestation, .. } => attestation.attester_index, + _ => unreachable!("only attestations are parked here"), + }) + .collect(); + attesters.sort_unstable(); + attesters + } + + #[test] + fn an_announced_root_releases_only_its_own_votes() { + let now = Instant::now(); + let mut parked = ParkedVotes::default(); + let (a, b) = (Root::repeat_byte(1), Root::repeat_byte(2)); + assert!(matches!(parked.park(a, vote(1, now)), Parking::Parked)); + assert!(matches!(parked.park(a, vote(2, now)), Parking::Parked)); + assert!(matches!(parked.park(b, vote(3, now)), Parking::Parked)); + assert_eq!(parked.len(), 3); + + assert_eq!(attesters(&parked.take_ready(a)), vec![1, 2]); + assert_eq!(parked.len(), 1); + assert!(parked.take_ready(a).is_empty()); + assert_eq!(attesters(&parked.take_ready(b)), vec![3]); + assert!(parked.is_empty()); + } + + #[test] + fn a_vote_for_a_root_already_announced_is_checked_again_at_once() { + let now = Instant::now(); + let mut parked = ParkedVotes::default(); + let root = Root::repeat_byte(1); + assert!(parked.take_ready(root).is_empty()); + + assert!(matches!(parked.park(root, vote(1, now)), Parking::Ready(_))); + assert!(parked.is_empty()); + } + + #[test] + fn only_the_latest_announced_roots_are_remembered() { + let now = Instant::now(); + let mut parked = ParkedVotes::default(); + for byte in 0..=RECENTLY_READY_ROOTS as u8 { + parked.take_ready(Root::repeat_byte(byte)); + } + + // The first one has been pushed out; the latest is still known. + assert!(matches!( + parked.park(Root::repeat_byte(0), vote(1, now)), + Parking::Parked + )); + assert!(matches!( + parked.park(Root::repeat_byte(RECENTLY_READY_ROOTS as u8), vote(2, now)), + Parking::Ready(_) + )); + } + + #[test] + fn a_full_queue_hands_the_vote_back() { + let now = Instant::now(); + let mut parked = ParkedVotes::default(); + for attester in 0..MAX_PARKED_VOTES as u64 { + let root = Root::repeat_byte((attester % 4) as u8); + assert!(matches!( + parked.park(root, vote(attester, now)), + Parking::Parked + )); + } + + assert!(matches!( + parked.park(Root::repeat_byte(9), vote(u64::MAX, now)), + Parking::Full(_) + )); + assert_eq!(parked.len(), MAX_PARKED_VOTES); + + // Releasing a root makes room again. + let released = parked.take_ready(Root::repeat_byte(0)).len(); + assert_eq!(parked.len(), MAX_PARKED_VOTES - released); + assert!(matches!( + parked.park(Root::repeat_byte(9), vote(u64::MAX, now)), + Parking::Parked + )); + } + + #[test] + fn only_votes_past_the_deadline_expire() { + let early = Instant::now(); + let late = early + Duration::from_secs(1); + let mut parked = ParkedVotes::default(); + let root = Root::repeat_byte(1); + parked.park(root, vote(1, early)); + parked.park(root, vote(2, late)); + parked.park(Root::repeat_byte(2), vote(3, early)); + + let sweep = early + PARKED_VOTE_DEADLINE; + assert!( + parked + .take_expired(sweep - Duration::from_millis(1)) + .is_empty() + ); + assert_eq!(attesters(&parked.take_expired(sweep)), vec![1, 3]); + assert_eq!(parked.len(), 1); + assert_eq!(attesters(&parked.take_ready(root)), vec![2]); + } + + #[test] + fn one_sweep_is_scheduled_at_a_time() { + let mut parked = ParkedVotes::default(); + assert!(parked.claim_sweep()); + assert!(!parked.claim_sweep()); + parked.sweep_started(); + assert!(parked.claim_sweep()); + } + + #[test] + fn the_deadline_leaves_room_for_a_sweep_inside_gossipsubs_window() { + // Gossipsub drops a message awaiting its verdict as early as five + // heartbeats of 700 ms after it arrived. + let earliest_eviction = Duration::from_millis(5 * 700); + assert!(PARKED_VOTE_DEADLINE + PARKED_VOTE_SWEEP_INTERVAL < earliest_eviction); + } +} diff --git a/crates/net/p2p/src/beacon/verdict.rs b/crates/net/p2p/src/beacon/verdict.rs index d8d1870e6..40e60514a 100644 --- a/crates/net/p2p/src/beacon/verdict.rs +++ b/crates/net/p2p/src/beacon/verdict.rs @@ -13,6 +13,7 @@ //! gossip message ends in exactly one [`report`]: gossipsub holds each one //! until then. +use std::collections::HashMap; use std::panic::{AssertUnwindSafe, catch_unwind}; use std::time::Instant; @@ -39,12 +40,13 @@ use ethlambda_types::beacon::primitives::{Root, ValidatorIndex}; use libp2p::PeerId; use libp2p::gossipsub::{MessageAcceptance, MessageId}; use spawned_concurrency::message::Message; -use spawned_concurrency::tasks::{Context, Handler}; +use spawned_concurrency::tasks::{Context, Handler, send_after}; use tracing::{debug, error, warn}; use crate::beacon::column_checks; +use crate::beacon::parked_votes::{PARKED_VOTE_SWEEP_INTERVAL, ParkedVote, Parking}; use crate::gossipsub::operation_kind; -use crate::{P2PServer, metrics}; +use crate::{P2PServer, metrics, p2p_protocol}; /// Which gossip message a verdict is for. pub(crate) struct GossipId { @@ -597,6 +599,10 @@ pub(crate) struct GossipVerdict { id: GossipId, outcome: Outcome, object: Validated, + /// Whether this is the first check, which may park a vote for a block + /// that is not ready yet (see [`parked_votes`](crate::beacon::parked_votes)). A check run again after + /// parking may not park again. + parkable: bool, } impl Message for GossipVerdict { @@ -638,20 +644,209 @@ pub(crate) fn settle_message( } impl Handler for P2PServer { - async fn handle(&mut self, msg: GossipVerdict, _ctx: &Context) { - let GossipVerdict { - id, - outcome, - object, - } = msg; - let outcome = settle_message(self, &id.message_id, outcome, &object); - let received_at = id.received_at; - if report(self, id, outcome) { - object.forward(self, received_at, outcome); + async fn handle(&mut self, msg: GossipVerdict, ctx: &Context) { + match receive_verdict(self, msg) { + AfterVerdict::Done => {} + AfterVerdict::ScheduleSweep => schedule_parked_vote_sweep(ctx), + AfterVerdict::Recheck(vote) => spawn_rechecks(self, ctx, vec![*vote]), + } + } +} + +/// What is left to do for a verdict once [`receive_verdict`] has done +/// everything that needs no [`Context`]. +pub(crate) enum AfterVerdict { + Done, + /// A vote was parked into a queue with no expiry sweep scheduled yet. + ScheduleSweep, + /// A vote for a block whose state is already ready: check it again. + Recheck(Box), +} + +/// Take a stateful check's verdict: park the vote it is for when its block is +/// not ready yet (see [`parked_votes`](crate::beacon::parked_votes)), and settle, report and forward it +/// otherwise. +pub(crate) fn receive_verdict(server: &mut P2PServer, verdict: GossipVerdict) -> AfterVerdict { + let GossipVerdict { + id, + outcome, + object, + parkable, + } = verdict; + let Some(root) = parkable.then(|| parkable_root(&object, outcome)).flatten() else { + conclude(server, id, outcome, object); + return AfterVerdict::Done; + }; + let kind = id.kind; + let vote = ParkedVote { + id, + object, + outcome, + }; + match server.parked_votes.park(root, vote) { + Parking::Parked => { + metrics::inc_parked_votes(kind, "parked"); + metrics::set_parked_votes(server.parked_votes.len()); + if server.parked_votes.claim_sweep() { + AfterVerdict::ScheduleSweep + } else { + AfterVerdict::Done + } + } + Parking::Ready(vote) => AfterVerdict::Recheck(Box::new(vote)), + Parking::Full(vote) => { + metrics::inc_parked_votes(kind, "full"); + conclude(server, vote.id, vote.outcome, vote.object); + AfterVerdict::Done + } + } +} + +/// The root of the block `object` votes for, when `outcome` says only that +/// block's post-state was missing: a subnet attestation or an aggregate +/// answered `Ignore(UnknownBlock)` or `Ignore(StateUnavailable)`. Nothing +/// else is ever parked. +fn parkable_root(object: &Validated, outcome: Outcome) -> Option { + if !matches!( + outcome, + Outcome::Ignore(IgnoreReason::UnknownBlock | IgnoreReason::StateUnavailable) + ) { + return None; + } + match object { + Validated::Attestation { attestation, .. } => Some(attestation.data.beacon_block_root), + Validated::Aggregate { aggregate, .. } => Some(aggregate.data().beacon_block_root), + _ => None, + } +} + +/// Settle `outcome` for `object`, report it to gossipsub, and hand the object +/// on when the outcome lets it go on: everything a verdict does once it is +/// final. +fn conclude(server: &mut P2PServer, id: GossipId, outcome: Outcome, object: Validated) { + let outcome = settle_message(server, &id.message_id, outcome, &object); + let received_at = id.received_at; + if report(server, id, outcome) { + object.forward(server, received_at, outcome); + } +} + +/// Check the votes parked under `block_root` again, now that its post-state +/// is ready. +pub(crate) fn release_parked_votes( + server: &mut P2PServer, + ctx: &Context, + block_root: Root, +) { + let votes = server.parked_votes.take_ready(block_root); + if votes.is_empty() { + return; + } + metrics::set_parked_votes(server.parked_votes.len()); + spawn_rechecks(server, ctx, votes); +} + +/// Report the first verdict of every parked vote past its deadline. Returns +/// whether votes are still parked, so another sweep is due. +pub(crate) fn sweep_parked_votes(server: &mut P2PServer) -> bool { + server.parked_votes.sweep_started(); + let expired = server.parked_votes.take_expired(Instant::now()); + if !expired.is_empty() { + metrics::set_parked_votes(server.parked_votes.len()); + } + for vote in expired { + metrics::inc_parked_votes(vote.id.kind, "expired"); + conclude(server, vote.id, vote.outcome, vote.object); + } + !server.parked_votes.is_empty() && server.parked_votes.claim_sweep() +} + +/// Schedule the next expiry sweep of the parked votes. +pub(crate) fn schedule_parked_vote_sweep(ctx: &Context) { + send_after( + PARKED_VOTE_SWEEP_INTERVAL, + ctx.clone(), + p2p_protocol::SweepParkedVotes, + ); +} + +/// Run the stateful checks of released votes again, a verdict each, in +/// blocking batches of up to [`RECHECK_BATCH`] votes of one kind, a permit a +/// batch. +/// +/// Batched because a root's votes are released together: one task, and one +/// permit, per vote would put the whole burst on the attestation pool at +/// once, and every vote past its last permit would be reported +/// `Ignore(Overloaded)`. A vote already past its deadline gets its first +/// verdict instead, since a second one could not reach gossipsub in time. +fn spawn_rechecks(server: &mut P2PServer, ctx: &Context, votes: Vec) { + let now = Instant::now(); + let mut by_kind: HashMap<&'static str, Vec> = HashMap::new(); + for vote in votes { + if vote.expired(now) { + metrics::inc_parked_votes(vote.id.kind, "expired"); + conclude(server, vote.id, vote.outcome, vote.object); + } else { + metrics::inc_parked_votes(vote.id.kind, "rechecked"); + by_kind.entry(vote.id.kind).or_default().push(vote); + } + } + for (kind, mut votes) in by_kind { + while !votes.is_empty() { + let rest = votes.split_off(votes.len().min(RECHECK_BATCH)); + spawn_recheck_batch(server, ctx, kind, votes); + votes = rest; } } } +/// One blocking batch of [`spawn_rechecks`]. +fn spawn_recheck_batch( + server: &mut P2PServer, + ctx: &Context, + kind: &'static str, + votes: Vec, +) { + const POOL: &str = "attestation"; + let Ok(permit) = server + .attestation_validation_permits + .clone() + .try_acquire_owned() + else { + for vote in votes { + metrics::inc_validation_permit_exhausted(POOL); + let outcome = Outcome::Ignore(IgnoreReason::Overloaded); + conclude(server, vote.id, outcome, vote.object); + } + return; + }; + let store = server.store.clone(); + let actor = ctx.actor_ref(); + let in_use = metrics::PoolInUse::new(POOL); + let task = metrics::BlockingTask::new(kind); + tokio::task::spawn_blocking(move || { + let _permit = permit; + let _in_use = in_use; + let _run = task.start(); + for ParkedVote { id, mut object, .. } in votes { + let outcome = guarded(|| object.stateful_checks(&store)); + let verdict = GossipVerdict { + id, + outcome, + object, + parkable: false, + }; + if actor.send(verdict).is_err() { + warn!("P2P actor stopped before a rechecked vote's verdict arrived"); + return; + } + } + }); +} + +/// How many released votes one blocking task checks again. +const RECHECK_BATCH: usize = 64; + /// How an outcome maps onto gossipsub, and whether the object still goes on /// towards the chain actor (see [`Validated::forward`] for the route). pub(crate) fn disposition(outcome: Outcome) -> (MessageAcceptance, bool) { @@ -764,6 +959,7 @@ pub(crate) fn spawn_stateful_checks( id, outcome, object, + parkable: true, }) .inspect_err(|_| warn!("P2P actor stopped before a gossip verdict arrived")); }); @@ -1748,6 +1944,181 @@ mod tests { assert_eq!(guarded(|| Outcome::Accept), Outcome::Accept); } + // ----------------------------------------------------------------- + // Parked votes: a verdict withheld until the voted block is ready + // ----------------------------------------------------------------- + + fn gossip_id(byte: u8, kind: &'static str, received_at: Instant) -> GossipId { + GossipId { + message_id: MessageId::new(&[byte]), + propagation_source: PeerId::random(), + received_at, + kind, + } + } + + fn attestation_verdict(attester: u64, outcome: Outcome, parkable: bool) -> GossipVerdict { + GossipVerdict { + id: gossip_id(attester as u8, "beacon_attestation", Instant::now()), + outcome, + object: Validated::Attestation { + attestation: Box::new(electra_attestation(1, attester)), + subnet_id: 0, + }, + parkable, + } + } + + /// The verdicts reported to gossipsub so far, in order, by name: + /// `MessageAcceptance` has no `PartialEq`. + fn reported( + commands: &mut tokio::sync::mpsc::UnboundedReceiver, + ) -> Vec<&'static str> { + let mut reported = Vec::new(); + while let Ok(command) = commands.try_recv() { + if let crate::swarm_adapter::SwarmCommand::ReportValidation { acceptance, .. } = command + { + reported.push(match acceptance { + MessageAcceptance::Accept => "accept", + MessageAcceptance::Ignore => "ignore", + MessageAcceptance::Reject => "reject", + }); + } + } + reported + } + + async fn capturing_server() -> ( + P2PServer, + tokio::sync::mpsc::UnboundedReceiver, + ) { + let mut server = unconnected_beacon_server(Config::mainnet(), 0).await; + let (swarm_handle, commands) = crate::swarm_adapter::SwarmHandle::capturing(); + server.swarm_handle = swarm_handle; + (server, commands) + } + + #[tokio::test] + async fn a_vote_for_a_block_not_ready_yet_is_parked_without_a_verdict() { + let (mut server, mut commands) = capturing_server().await; + + for (attester, reason) in [ + (1, IgnoreReason::StateUnavailable), + (2, IgnoreReason::UnknownBlock), + ] { + let verdict = attestation_verdict(attester, Outcome::Ignore(reason), true); + receive_verdict(&mut server, verdict); + } + let aggregate = GossipVerdict { + id: gossip_id(9, "beacon_aggregate_and_proof", Instant::now()), + outcome: Outcome::Ignore(IgnoreReason::StateUnavailable), + object: Validated::Aggregate { + aggregate: Box::new(electra_aggregate(1, 9)), + attesting_indices: Vec::new(), + }, + parkable: true, + }; + receive_verdict(&mut server, aggregate); + + assert_eq!(server.parked_votes.len(), 3); + assert!( + reported(&mut commands).is_empty(), + "gossipsub still holds all three" + ); + } + + #[tokio::test] + async fn only_the_first_parked_vote_schedules_a_sweep() { + let (mut server, _commands) = capturing_server().await; + let outcome = Outcome::Ignore(IgnoreReason::StateUnavailable); + + let first = receive_verdict(&mut server, attestation_verdict(1, outcome, true)); + let second = receive_verdict(&mut server, attestation_verdict(2, outcome, true)); + + assert!(matches!(first, AfterVerdict::ScheduleSweep)); + assert!(matches!(second, AfterVerdict::Done)); + } + + #[tokio::test] + async fn a_vote_checked_again_or_refused_otherwise_is_reported_at_once() { + let (mut server, mut commands) = capturing_server().await; + let unavailable = Outcome::Ignore(IgnoreReason::StateUnavailable); + + // A second check may not park again. + receive_verdict(&mut server, attestation_verdict(1, unavailable, false)); + // Only a missing block or state parks. + let reject = Outcome::Reject(RejectReason::BadSignature); + receive_verdict(&mut server, attestation_verdict(2, reject, true)); + let seen = Outcome::Ignore(IgnoreReason::AlreadySeen); + receive_verdict(&mut server, attestation_verdict(3, seen, true)); + // And only a vote: a block waits in the chain actor instead. + let block = GossipVerdict { + id: gossip_id(4, "beacon_block", Instant::now()), + outcome: Outcome::Ignore(IgnoreReason::UnknownBlock), + object: Validated::Block { + block: Box::new(fulu_block(5, 1)), + block_root: Root::repeat_byte(1), + }, + parkable: true, + }; + receive_verdict(&mut server, block); + + assert!(server.parked_votes.is_empty()); + assert_eq!( + reported(&mut commands), + vec!["ignore", "reject", "ignore", "ignore"] + ); + } + + #[tokio::test] + async fn a_vote_whose_block_was_announced_first_is_checked_again_at_once() { + let (mut server, mut commands) = capturing_server().await; + // `electra_attestation` votes for the zero root. + server.parked_votes.take_ready(Root::ZERO); + + let unavailable = Outcome::Ignore(IgnoreReason::StateUnavailable); + let after = receive_verdict(&mut server, attestation_verdict(1, unavailable, true)); + + assert!(matches!(after, AfterVerdict::Recheck(_))); + assert!(server.parked_votes.is_empty()); + assert!(reported(&mut commands).is_empty()); + } + + #[tokio::test] + async fn a_parked_vote_past_its_deadline_gets_its_first_verdict() { + let (mut server, mut commands) = capturing_server().await; + let unavailable = Outcome::Ignore(IgnoreReason::StateUnavailable); + let mut verdict = attestation_verdict(1, unavailable, true); + verdict.id.received_at = Instant::now() + .checked_sub(crate::beacon::parked_votes::PARKED_VOTE_DEADLINE) + .expect("the clock is past the deadline"); + receive_verdict(&mut server, verdict); + receive_verdict(&mut server, attestation_verdict(2, unavailable, true)); + + let more_due = sweep_parked_votes(&mut server); + + assert!(more_due, "the vote within its deadline is still parked"); + assert_eq!(server.parked_votes.len(), 1); + assert_eq!(reported(&mut commands), vec!["ignore"]); + } + + #[tokio::test] + async fn a_sweep_that_empties_the_queue_schedules_no_other() { + let (mut server, _commands) = capturing_server().await; + let unavailable = Outcome::Ignore(IgnoreReason::StateUnavailable); + let mut verdict = attestation_verdict(1, unavailable, true); + verdict.id.received_at = Instant::now() + .checked_sub(crate::beacon::parked_votes::PARKED_VOTE_DEADLINE) + .expect("the clock is past the deadline"); + receive_verdict(&mut server, verdict); + + assert!(!sweep_parked_votes(&mut server)); + assert!(server.parked_votes.is_empty()); + // The next park schedules a sweep of its own. + let after = receive_verdict(&mut server, attestation_verdict(2, unavailable, true)); + assert!(matches!(after, AfterVerdict::ScheduleSweep)); + } + /// The compressed BLS12-381 G2 generator: a signature that decodes and /// combines, standing in for a verified one where the test is about /// pooling and not about verification. diff --git a/crates/net/p2p/src/lib.rs b/crates/net/p2p/src/lib.rs index 0e53c025c..089b05010 100644 --- a/crates/net/p2p/src/lib.rs +++ b/crates/net/p2p/src/lib.rs @@ -44,8 +44,8 @@ use ethlambda_network_api::{ ConnectedPeer, FetchRequest, GossipEventSink, InitBlockChain, MetaDataController, P2PToBlockChainRef, PeerDirection, PeerTableController, SidecarOrigin, block_chain_to_p2p::{ - CheckDataColumnSidecars, FetchBlock, PublishAggregatedAttestation, PublishAttestation, - PublishBlock, + BlockStateReady, CheckDataColumnSidecars, FetchBlock, PublishAggregatedAttestation, + PublishAttestation, PublishBlock, }, rpc_to_p2p::{ PublishBeaconAggregate, PublishBeaconAttestation, PublishBeaconBlock, @@ -1650,6 +1650,7 @@ impl P2P { sync_committee_pool, gossip_events, aggregator_subnets: HashMap::new(), + parked_votes: Default::default(), peer_scoring, }; let scores_peers = server.peer_scoring.is_some(); @@ -1887,6 +1888,10 @@ pub struct P2PServer { /// backbone subnets are separate and never left. pub(crate) aggregator_subnets: HashMap, + /// Subnet attestations and aggregates whose verdict waits for the block + /// they vote for to have a post-state. See [`beacon::parked_votes`]. + pub(crate) parked_votes: beacon::parked_votes::ParkedVotes, + /// Gossipsub scoring's inputs and gate. `None` on lean, which runs /// without peer scoring. See [`beacon::scoring`]. pub(crate) peer_scoring: Option, @@ -2019,6 +2024,10 @@ pub(crate) trait P2PProtocol: Send + Sync { fn discover_peers(&self) -> Result<(), ActorError>; #[allow(dead_code)] // invoked via send_after, not called directly fn leave_expired_aggregator_subnets(&self) -> Result<(), ActorError>; + /// Report the first verdict of the parked votes past their deadline; see + /// [`beacon::parked_votes`]. Scheduled only while votes are parked. + #[allow(dead_code)] // invoked via send_after, not called directly + fn sweep_parked_votes(&self) -> Result<(), ActorError>; #[allow(dead_code)] // invoked via send_after, not called directly fn retry_beacon_range_batch(&self) -> Result<(), ActorError>; /// Apply the fork schedule at the wall-clock epoch. Sent once at startup and @@ -2146,6 +2155,17 @@ impl P2PServer { beacon::sync_committee::prune_sync_committee_pool(self); } + #[send_handler] + async fn handle_sweep_parked_votes( + &mut self, + _msg: p2p_protocol::SweepParkedVotes, + ctx: &Context, + ) { + if beacon::verdict::sweep_parked_votes(self) { + beacon::verdict::schedule_parked_vote_sweep(ctx); + } + } + #[send_handler] async fn handle_advance_fork_schedule( &mut self, @@ -2359,6 +2379,12 @@ impl Handler for P2PServer { } } +impl Handler for P2PServer { + async fn handle(&mut self, msg: BlockStateReady, ctx: &Context) { + beacon::verdict::release_parked_votes(self, ctx, msg.block_root); + } +} + /// Ask for whatever a [`FetchRequest`] says is missing. /// /// Both halves are by-root lookups with their own dedup and retry ladder, and @@ -4143,6 +4169,7 @@ pub(crate) mod test_support { sync_committee_pool: Default::default(), gossip_events: None, aggregator_subnets: HashMap::new(), + parked_votes: Default::default(), peer_scoring: None, } } diff --git a/crates/net/p2p/src/metrics.rs b/crates/net/p2p/src/metrics.rs index ae675755a..e7835cf43 100644 --- a/crates/net/p2p/src/metrics.rs +++ b/crates/net/p2p/src/metrics.rs @@ -566,6 +566,37 @@ pub(crate) fn inc_validation_permit_exhausted(pool: &str) { .inc(); } +static LEAN_BEACON_GOSSIP_PARKED_VOTES_TOTAL: LazyLock = LazyLock::new(|| { + register_int_counter_vec!( + "lean_beacon_gossip_parked_votes_total", + "Subnet attestations and aggregates whose verdict waited for their block's post-state, by what happened to them", + &["kind", "result"] + ) + .unwrap() +}); + +/// Count one vote of topic `kind` through the parked-vote queue (see +/// `beacon::parked_votes`): `parked`, `full` (refused by the cap, so it got +/// its verdict at once), `rechecked` (checked again once its block's state was +/// ready) or `expired` (never ready in time, so it got its first verdict). +pub(crate) fn inc_parked_votes(kind: &str, result: &str) { + LEAN_BEACON_GOSSIP_PARKED_VOTES_TOTAL + .with_label_values(&[kind, result]) + .inc(); +} + +/// Set how many votes are parked right now. +pub(crate) fn set_parked_votes(count: usize) { + static LEAN_BEACON_GOSSIP_PARKED_VOTES: LazyLock = LazyLock::new(|| { + register_int_gauge!( + "lean_beacon_gossip_parked_votes", + "Subnet attestations and aggregates waiting for their block's post-state before their verdict" + ) + .unwrap() + }); + LEAN_BEACON_GOSSIP_PARKED_VOTES.set(count.try_into().unwrap_or(i64::MAX)); +} + /// Record how long a column check (`kind` `column_check`: one block's /// prechecks, or one further KZG sub-batch of its columns) or an envelope /// check (`envelope_check`) awaited a `column_check` permit. diff --git a/crates/net/p2p/src/req_resp/handlers.rs b/crates/net/p2p/src/req_resp/handlers.rs index 107f13492..354aec116 100644 --- a/crates/net/p2p/src/req_resp/handlers.rs +++ b/crates/net/p2p/src/req_resp/handlers.rs @@ -3751,6 +3751,7 @@ pub(crate) mod tests { sync_committee_pool: Default::default(), gossip_events: None, aggregator_subnets: HashMap::new(), + parked_votes: Default::default(), peer_scoring: None, } } diff --git a/docs/beacon_wire.md b/docs/beacon_wire.md index e0da290ab..935d6c810 100644 --- a/docs/beacon_wire.md +++ b/docs/beacon_wire.md @@ -434,6 +434,28 @@ thread, in this order: block's ancestor at the target epoch (REJECT), and the finalized checkpoint is an ancestor of the vote block (IGNORE). +Steps 1 and 2 fail for a while on every block this node imports: validators +vote as soon as the block reaches them, so the first votes for it arrive +while this node is still waiting for its columns or running its state +transition. Those IGNOREs are not reported straight away. The vote is parked +under the block's root with its verdict withheld, so gossipsub keeps holding +the message, and when the chain actor's import caches the post-state it tells +p2p (`BlockChainToP2P::block_state_ready`), which runs the stateful checks +again, in blocking batches, and reports what they answer then. An accepted +vote propagates as the original message. This is lighthouse's reprocess +queue, which the specification allows ("a client MAY queue attestations for +processing once block is retrieved"). Without it, a devnet with ~130 ms +imports lost 5 to 8% of each node's subnet votes, all of them the earliest. + +A vote is parked once: its second check reports whatever it answers. One +still parked 2.5 s after it arrived gets its first verdict, since gossipsub +drops a message awaiting a verdict as early as 3.5 s in (6 heartbeats of +700 ms of history). The queue holds at most 16,384 votes, lighthouse's own +cap, since nothing about a parked vote has been verified; past it, a vote +gets its first verdict at once. Unlike lighthouse, a vote for a block this +node has never seen does not start a lookup for that block: it waits for +gossip or sync to bring it. See `crates/net/p2p/src/beacon/parked_votes.rs`. + The seen caches (`SeenAggregates`, keyed both by `(target_epoch, aggregator_index)` and by `(hash_tree_root(data), committee_index)`; `SeenAttestations`, by `(target_epoch, attester_index)`) live in p2p now, @@ -950,6 +972,8 @@ as a query filter, so a `quic`-only record is invisible to it. | `lean_beacon_gossip_messages_total{topic,result}` | Gossip received, by topic and by `decoded` / `decode_failed` / `decompress_failed` / `unsupported_fork` | | `lean_beacon_gossip_validation_total{kind,outcome,reason}` | Gossip verdicts, now including `beacon_aggregate_and_proof` and `beacon_attestation`; see [metrics.md](./metrics.md#beacon-gossip-validation) | | `lean_beacon_gossip_verdict_expired_total{kind}` | Verdicts that came too late to propagate anything; should stay at zero | +| `lean_beacon_gossip_parked_votes_total{kind,result}` | Votes whose verdict waited for their block's post-state: `parked`, `full`, `rechecked`, `expired` | +| `lean_beacon_gossip_parked_votes` | Votes parked right now | | `lean_beacon_status_digest_mismatch_total` | Peers whose `Status` moved onto another fork digest, once per move (not per refresh) | | `lean_beacon_fork_digest{digest}` | The digest computed at startup, as a label | | `lean_beacon_aggregate_decode_seconds` | Time spent decoding one aggregate off the wire | diff --git a/docs/metrics.md b/docs/metrics.md index 99fc8f157..c38529c20 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -417,6 +417,8 @@ own section. These are ethlambda-specific, not part of the leanMetrics spec. | `lean_beacon_gossip_validation_total` | Counter | Verdicts, by topic kind, outcome and reason | On every verdict reported to gossipsub | kind, outcome=accept,queue,ignore,reject, reason | | | `lean_beacon_gossip_validation_seconds` | Histogram | Time from a message's arrival to its verdict | On every verdict reported to gossipsub | kind | 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 4, 8 | | `lean_beacon_gossip_verdict_expired_total` | Counter | Verdicts that arrived after gossipsub evicted the message, so an Accept propagated nothing | When `report_message_validation_result` returns `false` | kind | | +| `lean_beacon_gossip_parked_votes_total` | Counter | Subnet attestations and aggregates whose verdict waited for their block's post-state, by what happened to them | When a vote is parked, refused by the full queue, checked again, or past its deadline | kind, result=parked,full,rechecked,expired | | +| `lean_beacon_gossip_parked_votes` | Gauge | Votes parked right now | On every park, release and sweep | | | `kind` is the topic kind, with every `data_column_sidecar_{subnet}` sharing the label `data_column_sidecar`, every `beacon_attestation_{subnet_id}` sharing @@ -439,10 +441,16 @@ envelope verifies. When the execution client has found that parent's payload invalid, nothing will verify it, and the block is ignored instead (`parent_payload_invalid`). The aggregate, attestation, `payload_attestation_message`, `execution_payload_bid` and `proposer_preferences` -topics never answer `queue`, since the vote -block's post-state is either cached or it is not -(`IgnoreReason::UnknownBlock`/`StateUnavailable`), with nothing to hold the -message for. **`verdict_expired_total` should stay at +topics never answer `queue`. An aggregate or a subnet attestation whose vote +block is not stored yet, or has no cached post-state yet +(`IgnoreReason::UnknownBlock`/`StateUnavailable`), is held anyway, though not +as `queue`: its verdict is withheld while it waits for the block's import, then +its checks run again (`lean_beacon_gossip_parked_votes_total`, and +`crates/net/p2p/src/beacon/parked_votes.rs`). Only a vote still waiting at its +deadline, 2.5 s after it arrived, or one the full queue refused, is counted +under those two reasons. Its time to verdict includes the wait, so +`lean_beacon_gossip_validation_seconds` for these two kinds reads up to that +deadline. **`verdict_expired_total` should stay at zero**: a rising count means validation is too slow for gossipsub's message cache. From 9dcef96e7201cadcadcc5459cc202701228eb653 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:33:48 -0300 Subject: [PATCH 2/3] fix(p2p): check parked votes again on a pool of their own, and cap parked aggregates Review round 1 on #899: - A released root started every batch at once, each taking a permit from the attestation pool with try_acquire. At the cap that is 256 batches against 128 permits: the batches past the last permit were ignored as overloaded, and the votes arriving meanwhile found no permit either, the loss parking is there to prevent. Rechecks now run on a pool of their own (RECHECK_PERMITS, 32, pool="recheck"), and a batch waits for a permit rather than failing without one. - A vote's deadline was checked once, when its batch was spawned. It is now checked again right before each vote's turn, so one reached too late (after a long wait for a permit, or a slow batch) gets its first verdict, which can still reach gossipsub, instead of a second that cannot. "rechecked" now counts only votes whose checks ran again. - The cap counted votes alone, and an electra aggregate parked before its signature check can carry 16 KiB of bits, so junk aggregates naming roots that never import could keep about 256 MiB resident. Aggregates now have a cap of their own, MAX_PARKED_AGGREGATES (2,048, two slots of an honest network's), about 32 MiB at most. - A missing post-state was read as "still importing", but it also means a block imported earlier whose state has left the cache, for which no release ever comes. When the block has a stored state, the first check runs once more at once and the vote is not parked. That also covers a state that landed while the check ran. - Tests: the aggregate cap, and a recheck that never parks again and keeps its first outcome once past its deadline. --- crates/net/p2p/src/beacon/parked_votes.rs | 107 +++++++++++++++- crates/net/p2p/src/beacon/verdict.rs | 145 +++++++++++++++------- crates/net/p2p/src/lib.rs | 17 +++ crates/net/p2p/src/metrics.rs | 15 ++- crates/net/p2p/src/req_resp/handlers.rs | 3 + docs/metrics.md | 8 +- 6 files changed, 243 insertions(+), 52 deletions(-) diff --git a/crates/net/p2p/src/beacon/parked_votes.rs b/crates/net/p2p/src/beacon/parked_votes.rs index 72e3772fd..5b2eb1c26 100644 --- a/crates/net/p2p/src/beacon/parked_votes.rs +++ b/crates/net/p2p/src/beacon/parked_votes.rs @@ -34,7 +34,9 @@ //! never comes still gets its first verdict, as it would have before. //! - **A cap.** Votes are parked before their signature is checked, so at //! [`MAX_PARKED_VOTES`] the next one is reported as it would have been -//! before this queue existed. +//! before this queue existed. Aggregates have a smaller cap of their own, +//! [`MAX_PARKED_AGGREGATES`], since one can be far larger than a subnet +//! attestation. //! //! The import signal can win the race against the verdict it releases: the //! check reads the store on a blocking thread, the import caches the state @@ -56,6 +58,17 @@ use crate::beacon::verdict::{GossipId, Validated}; /// `MAXIMUM_QUEUED_ATTESTATIONS`. pub(crate) const MAX_PARKED_VOTES: usize = 16_384; +/// How many of the parked votes may be aggregates. +/// +/// An electra aggregate's bits run to `MAX_VALIDATORS_PER_COMMITTEE * +/// MAX_COMMITTEES_PER_SLOT`, 16 KiB decoded and a few hundred bytes on the +/// wire, and it is parked before its signature is checked. Under +/// [`MAX_PARKED_VOTES`] alone a peer naming roots that never import could +/// keep about 256 MiB of them resident; this keeps it near 32 MiB. An honest +/// network sends about a thousand aggregates a slot, so this holds two slots' +/// worth. +pub(crate) const MAX_PARKED_AGGREGATES: usize = 2_048; + /// How long after its arrival a parked vote may still wait for its block. /// See the module documentation for why it must stay under 3.5 s with /// [`PARKED_VOTE_SWEEP_INTERVAL`] added. @@ -85,6 +98,16 @@ impl ParkedVote { pub(crate) fn expired(&self, now: Instant) -> bool { now.saturating_duration_since(self.id.received_at) >= PARKED_VOTE_DEADLINE } + + /// Whether this is an aggregate, which [`MAX_PARKED_AGGREGATES`] caps. + fn is_aggregate(&self) -> bool { + matches!(self.object, Validated::Aggregate { .. }) + } +} + +/// How many of `votes` are aggregates. +fn aggregates_in(votes: &[ParkedVote]) -> usize { + votes.iter().filter(|vote| vote.is_aggregate()).count() } /// What [`ParkedVotes::park`] did with a vote. @@ -102,6 +125,8 @@ pub(crate) enum Parking { pub(crate) struct ParkedVotes { by_root: HashMap>, len: usize, + /// How many of the `len` are aggregates. + aggregates: usize, recently_ready: VecDeque, /// Whether an expiry sweep is already scheduled, so parking a vote never /// starts a second timer. @@ -114,11 +139,13 @@ impl ParkedVotes { if self.recently_ready.contains(&root) { return Parking::Ready(vote); } - if self.len >= MAX_PARKED_VOTES { + let aggregate = vote.is_aggregate(); + if self.len >= MAX_PARKED_VOTES || (aggregate && self.aggregates >= MAX_PARKED_AGGREGATES) { return Parking::Full(vote); } self.by_root.entry(root).or_default().push(vote); self.len += 1; + self.aggregates += usize::from(aggregate); Parking::Parked } @@ -134,6 +161,7 @@ impl ParkedVotes { } let votes = self.by_root.remove(&root).unwrap_or_default(); self.len -= votes.len(); + self.aggregates -= aggregates_in(&votes); votes } @@ -149,6 +177,7 @@ impl ParkedVotes { !votes.is_empty() }); self.len -= expired.len(); + self.aggregates -= aggregates_in(&expired); expired } @@ -209,6 +238,42 @@ mod tests { } } + fn aggregate(aggregator: u64, received_at: Instant) -> ParkedVote { + use ethlambda_types::beacon::containers::{SignedAggregateAndProof, phase0}; + + let aggregate = SignedAggregateAndProof::Phase0(phase0::SignedAggregateAndProof { + message: phase0::AggregateAndProof { + aggregator_index: aggregator, + aggregate: phase0::Attestation { + aggregation_bits: phase0::AggregationBits::with_length(1).unwrap(), + data: AttestationData { + slot: 1, + index: 0, + beacon_block_root: Root::repeat_byte(1), + source: Checkpoint::default(), + target: Checkpoint::default(), + }, + signature: Default::default(), + }, + selection_proof: Default::default(), + }, + signature: Default::default(), + }); + ParkedVote { + id: GossipId { + message_id: MessageId::new(&aggregator.to_be_bytes()), + propagation_source: PeerId::random(), + received_at, + kind: "beacon_aggregate_and_proof", + }, + object: Validated::Aggregate { + aggregate: Box::new(aggregate), + attesting_indices: Vec::new(), + }, + outcome: Outcome::Ignore(IgnoreReason::UnknownBlock), + } + } + fn attesters(votes: &[ParkedVote]) -> Vec { let mut attesters: Vec = votes .iter() @@ -295,6 +360,44 @@ mod tests { )); } + /// Aggregates fill a cap of their own, well below the queue's: past it + /// the next aggregate is handed back, while a subnet attestation still + /// parks, and releasing or expiring aggregates makes room for more. + #[test] + fn aggregates_have_a_smaller_cap_of_their_own() { + let now = Instant::now(); + let mut parked = ParkedVotes::default(); + let (a, b) = (Root::repeat_byte(1), Root::repeat_byte(2)); + for aggregator in 0..MAX_PARKED_AGGREGATES as u64 { + let root = if aggregator % 2 == 0 { a } else { b }; + assert!(matches!( + parked.park(root, aggregate(aggregator, now)), + Parking::Parked + )); + } + + assert!(matches!( + parked.park(a, aggregate(u64::MAX, now)), + Parking::Full(_) + )); + assert!(matches!(parked.park(a, vote(1, now)), Parking::Parked)); + + assert_eq!(parked.take_ready(a).len(), MAX_PARKED_AGGREGATES / 2 + 1); + assert!(matches!( + parked.park(Root::repeat_byte(3), aggregate(u64::MAX, now)), + Parking::Parked + )); + let expired = parked.take_expired(now + PARKED_VOTE_DEADLINE).len(); + assert_eq!(expired, MAX_PARKED_AGGREGATES / 2 + 1); + assert!(parked.is_empty()); + for aggregator in 0..MAX_PARKED_AGGREGATES as u64 { + assert!(matches!( + parked.park(b, aggregate(aggregator, now)), + Parking::Parked + )); + } + } + #[test] fn only_votes_past_the_deadline_expire() { let early = Instant::now(); diff --git a/crates/net/p2p/src/beacon/verdict.rs b/crates/net/p2p/src/beacon/verdict.rs index 40e60514a..f42c105db 100644 --- a/crates/net/p2p/src/beacon/verdict.rs +++ b/crates/net/p2p/src/beacon/verdict.rs @@ -771,14 +771,15 @@ pub(crate) fn schedule_parked_vote_sweep(ctx: &Context) { } /// Run the stateful checks of released votes again, a verdict each, in -/// blocking batches of up to [`RECHECK_BATCH`] votes of one kind, a permit a -/// batch. +/// blocking batches of up to [`RECHECK_BATCH`] votes of one kind. /// -/// Batched because a root's votes are released together: one task, and one -/// permit, per vote would put the whole burst on the attestation pool at -/// once, and every vote past its last permit would be reported -/// `Ignore(Overloaded)`. A vote already past its deadline gets its first -/// verdict instead, since a second one could not reach gossipsub in time. +/// Batched because a root's votes are released together, and run on a pool +/// of their own ([`P2PServer::recheck_permits`]): on the attestation pool, a +/// big release would take the permits of the votes arriving meanwhile, which +/// would then be ignored as overloaded, the very loss parking is there to +/// prevent. A batch waits for a permit rather than failing without one, and +/// each vote's deadline is checked again right before its turn (see +/// [`recheck`]), so a vote reached too late still gets its first verdict. fn spawn_rechecks(server: &mut P2PServer, ctx: &Context, votes: Vec) { let now = Instant::now(); let mut by_kind: HashMap<&'static str, Vec> = HashMap::new(); @@ -787,7 +788,6 @@ fn spawn_rechecks(server: &mut P2PServer, ctx: &Context, votes: Vec

, votes: Vec

, kind: &'static str, votes: Vec, ) { - const POOL: &str = "attestation"; - let Ok(permit) = server - .attestation_validation_permits - .clone() - .try_acquire_owned() - else { - for vote in votes { - metrics::inc_validation_permit_exhausted(POOL); - let outcome = Outcome::Ignore(IgnoreReason::Overloaded); - conclude(server, vote.id, outcome, vote.object); - } - return; - }; + let permits = server.recheck_permits.clone(); let store = server.store.clone(); let actor = ctx.actor_ref(); - let in_use = metrics::PoolInUse::new(POOL); - let task = metrics::BlockingTask::new(kind); - tokio::task::spawn_blocking(move || { - let _permit = permit; - let _in_use = in_use; - let _run = task.start(); - for ParkedVote { id, mut object, .. } in votes { - let outcome = guarded(|| object.stateful_checks(&store)); - let verdict = GossipVerdict { - id, - outcome, - object, - parkable: false, - }; - if actor.send(verdict).is_err() { - warn!("P2P actor stopped before a rechecked vote's verdict arrived"); - return; + tokio::spawn(async move { + let Ok(permit) = permits.acquire_owned().await else { + warn!("The recheck permit pool closed before a batch of parked votes ran"); + return; + }; + let in_use = metrics::PoolInUse::new(RECHECK_POOL); + let task = metrics::BlockingTask::new(kind); + tokio::task::spawn_blocking(move || { + let _permit = permit; + let _in_use = in_use; + let _run = task.start(); + for vote in votes { + let verdict = recheck(&store, vote, Instant::now()); + if actor.send(verdict).is_err() { + warn!("P2P actor stopped before a rechecked vote's verdict arrived"); + return; + } } - } + }); }); } +/// Check a released vote again at `now`, or, past its deadline by then, give +/// it the outcome of its first check, since a second one could not reach +/// gossipsub in time. Either way the verdict may not park it again. +fn recheck(store: &Store, vote: ParkedVote, now: Instant) -> GossipVerdict { + let late = vote.expired(now); + let ParkedVote { + id, + mut object, + outcome, + } = vote; + let outcome = if late { + metrics::inc_parked_votes(id.kind, "expired"); + outcome + } else { + metrics::inc_parked_votes(id.kind, "rechecked"); + guarded(|| object.stateful_checks(store)) + }; + GossipVerdict { + id, + outcome, + object, + parkable: false, + } +} + +/// The label of [`P2PServer::recheck_permits`] (see +/// [`metrics::VALIDATION_POOLS`]). +const RECHECK_POOL: &str = "recheck"; + /// How many released votes one blocking task checks again. const RECHECK_BATCH: usize = 64; @@ -953,13 +971,26 @@ pub(crate) fn spawn_stateful_checks( let _in_use = in_use; let _run = task.start(); let mut object = object; - let outcome = guarded(|| object.stateful_checks(&store)); + let mut outcome = guarded(|| object.stateful_checks(&store)); + let mut parkable = true; + // A missing post-state means the block is still importing only when + // it has no stored state either. With one, it was imported: its state + // left the cache since, and no release will come for it, or it landed + // while this check ran, and its release may already be gone. Either + // way the vote is checked once more now and not parked. + if outcome == Outcome::Ignore(IgnoreReason::StateUnavailable) + && parkable_root(&object, outcome) + .is_some_and(|root| store.has_state(&root).unwrap_or(false)) + { + outcome = guarded(|| object.stateful_checks(&store)); + parkable = false; + } let _ = actor .send(GossipVerdict { id, outcome, object, - parkable: true, + parkable, }) .inspect_err(|_| warn!("P2P actor stopped before a gossip verdict arrived")); }); @@ -1969,6 +2000,34 @@ mod tests { } } + /// A released vote still in time has its checks run again; one past its + /// deadline by its turn keeps the outcome of its first check. Neither + /// verdict may park the vote a second time. The first outcome here is one + /// the stateful checks never give, so a fresh check is told apart from it. + #[tokio::test] + async fn a_recheck_never_parks_again_and_keeps_the_first_outcome_past_the_deadline() { + let server = unconnected_beacon_server(Config::mainnet(), 0).await; + let first = Outcome::Ignore(IgnoreReason::Overloaded); + let parked = |received_at| ParkedVote { + id: gossip_id(1, "beacon_attestation", received_at), + object: Validated::Attestation { + attestation: Box::new(electra_attestation(1, 1)), + subnet_id: 0, + }, + outcome: first, + }; + let arrived = Instant::now(); + + let deadline = arrived + crate::beacon::parked_votes::PARKED_VOTE_DEADLINE; + let late = recheck(&server.store, parked(arrived), deadline); + assert_eq!(late.outcome, first); + assert!(!late.parkable); + + let in_time = recheck(&server.store, parked(arrived), arrived); + assert_ne!(in_time.outcome, first, "the checks ran again"); + assert!(!in_time.parkable); + } + /// The verdicts reported to gossipsub so far, in order, by name: /// `MessageAcceptance` has no `PartialEq`. fn reported( diff --git a/crates/net/p2p/src/lib.rs b/crates/net/p2p/src/lib.rs index 089b05010..322d2bc28 100644 --- a/crates/net/p2p/src/lib.rs +++ b/crates/net/p2p/src/lib.rs @@ -285,6 +285,16 @@ const COLUMN_CHECK_PERMITS: usize = 16; /// has data from a follower. const ATTESTATION_VALIDATION_PERMITS: usize = 128; +/// How many batches of parked votes may be checked again at once (see +/// `beacon::parked_votes`). +/// +/// A pool of its own, a quarter of [`ATTESTATION_VALIDATION_PERMITS`]: a +/// block's votes are released together, and on the attestation pool a big +/// release would take the permits of the votes arriving meanwhile, which +/// would be ignored as overloaded. A batch waits for a permit here rather +/// than failing without one. +const RECHECK_PERMITS: usize = 32; + /// How many `execution_payload_bid` and `proposer_preferences` stateful checks /// may run at once. A pool of its own, so a burst of bids (each costs a BLS /// verification) cannot starve blocks, columns or attestations of permits. @@ -1642,6 +1652,7 @@ impl P2P { attestation_validation_permits: Arc::new(tokio::sync::Semaphore::new( ATTESTATION_VALIDATION_PERMITS, )), + recheck_permits: Arc::new(tokio::sync::Semaphore::new(RECHECK_PERMITS)), payload_attestation_pool, builder_market, builder_validation_permits: Arc::new(tokio::sync::Semaphore::new( @@ -1854,6 +1865,9 @@ pub struct P2PServer { /// [`Self::gossip_validation_permits`]; see /// [`ATTESTATION_VALIDATION_PERMITS`]. pub(crate) attestation_validation_permits: Arc, + /// Permits for batches of parked votes checked again once their block's + /// post-state is ready. See [`RECHECK_PERMITS`]. + pub(crate) recheck_permits: Arc, /// Permits for sync committee message and contribution stateful gossip /// checks in flight on blocking threads. Separate from the other two /// pools; see [`SYNC_VALIDATION_PERMITS`]. @@ -4149,6 +4163,9 @@ pub(crate) mod test_support { attestation_validation_permits: std::sync::Arc::new(tokio::sync::Semaphore::new( crate::ATTESTATION_VALIDATION_PERMITS, )), + recheck_permits: std::sync::Arc::new(tokio::sync::Semaphore::new( + crate::RECHECK_PERMITS, + )), seen_sync_messages: ethlambda_state_transition::beacon::gossip::sync_committee::SeenSyncCommitteeMessages::new( crate::SEEN_SYNC_MESSAGES_CAPACITY, diff --git a/crates/net/p2p/src/metrics.rs b/crates/net/p2p/src/metrics.rs index e7835cf43..0f7d8f7c8 100644 --- a/crates/net/p2p/src/metrics.rs +++ b/crates/net/p2p/src/metrics.rs @@ -475,10 +475,17 @@ pub fn observe_beacon_gossip_verdict( /// Labels of the permit pools that bound blocking-thread validation work. /// `column_check` is [`P2PServer::column_check_permits`](crate::P2PServer), -/// shared by the fetched-column and fetched-envelope checks; the rest are the -/// four gossip pools. -pub(crate) const VALIDATION_POOLS: &[&str] = - &["gossip", "attestation", "builder", "sync", "column_check"]; +/// shared by the fetched-column and fetched-envelope checks; `recheck` is +/// [`P2PServer::recheck_permits`](crate::P2PServer), for parked votes checked +/// again; the rest are the four gossip pools. +pub(crate) const VALIDATION_POOLS: &[&str] = &[ + "gossip", + "attestation", + "builder", + "sync", + "column_check", + "recheck", +]; static LEAN_BEACON_VALIDATION_PERMITS_IN_USE: LazyLock = LazyLock::new(|| { register_int_gauge_vec!( diff --git a/crates/net/p2p/src/req_resp/handlers.rs b/crates/net/p2p/src/req_resp/handlers.rs index 354aec116..77ed3b14a 100644 --- a/crates/net/p2p/src/req_resp/handlers.rs +++ b/crates/net/p2p/src/req_resp/handlers.rs @@ -3731,6 +3731,9 @@ pub(crate) mod tests { attestation_validation_permits: std::sync::Arc::new(tokio::sync::Semaphore::new( crate::ATTESTATION_VALIDATION_PERMITS, )), + recheck_permits: std::sync::Arc::new(tokio::sync::Semaphore::new( + crate::RECHECK_PERMITS, + )), seen_sync_messages: ethlambda_state_transition::beacon::gossip::sync_committee::SeenSyncCommitteeMessages::new( crate::SEEN_SYNC_MESSAGES_CAPACITY, diff --git a/docs/metrics.md b/docs/metrics.md index e6bd875d4..e03569e02 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -445,8 +445,10 @@ topics never answer `queue`. An aggregate or a subnet attestation whose vote block is not stored yet, or has no cached post-state yet (`IgnoreReason::UnknownBlock`/`StateUnavailable`), is held anyway, though not as `queue`: its verdict is withheld while it waits for the block's import, then -its checks run again (`lean_beacon_gossip_parked_votes_total`, and -`crates/net/p2p/src/beacon/parked_votes.rs`). Only a vote still waiting at its +its checks run again, on a permit pool of their own (`pool="recheck"`) +(`lean_beacon_gossip_parked_votes_total`, and +`crates/net/p2p/src/beacon/parked_votes.rs`). A vote whose block was imported +but whose state has left the cache is checked once more at once and not held. Only a vote still waiting at its deadline, 2.5 s after it arrived, or one the full queue refused, is counted under those two reasons. Its time to verdict includes the wait, so `lean_beacon_gossip_validation_seconds` for these two kinds reads up to that @@ -509,7 +511,7 @@ ethlambda-specific, not part of the leanMetrics spec. | Name | Type | Usage | Sample collection event | Labels | Buckets | |------|------|-------|-------------------------|--------|---------| -| `lean_beacon_validation_permits_in_use` | Gauge | Permits held per pool: blocking tasks queued or running | A permit is acquired / released | pool=gossip,attestation,builder,sync,column_check | | +| `lean_beacon_validation_permits_in_use` | Gauge | Permits held per pool: blocking tasks queued or running | A permit is acquired / released | pool=gossip,attestation,builder,sync,column_check,recheck | | | `lean_beacon_validation_permit_exhausted_total` | Counter | Objects reported `Ignore(Overloaded)` because their pool had no free permit | On each failed `try_acquire` | pool=gossip,attestation,builder,sync | | | `lean_beacon_validation_queue_seconds` | Histogram | Time from `spawn_blocking` being called to the closure starting (tokio blocking-pool queueing) | When the closure starts | kind | 0.0001, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 4 | | `lean_beacon_validation_run_seconds` | Histogram | Run time of the closure itself | When the closure ends (panic included) | kind | same as above | From 53bbf25d2d8cbdfc5348fb13b78a7e3a3ec618d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:01:11 -0300 Subject: [PATCH 3/3] fix(p2p): keep the parked-vote state probe inside the panic guard Review round 2 on #899: - Round 1's has_state probe ran outside guarded. has_state panics on a storage error (its reads expect rather than return one), so a failing read would have unwound the blocking task with no verdict sent, and gossipsub would have held the message until its cache evicted it. The probe and the second check now run inside the same guarded closure as the first, so a panic there is Ignore(Internal) like any other. - A batch of rechecked votes was timed under its votes' own kind, mixing 64-check batches with single first checks in the blocking-task histograms. Batches are timed under beacon_attestation_recheck and beacon_aggregate_and_proof_recheck. - The deadline test compared against a literal 5 * 700 ms. Gossipsub's heartbeat and history length are now named constants (GOSSIPSUB_HEARTBEAT, GOSSIPSUB_HISTORY_LENGTH) that build_swarm and the test both read. - Docs: docs/metrics.md says which votes the two ignore reasons count, that rechecked/expired include votes checked again at once, and the recheck timing labels; docs/beacon_wire.md and CLAUDE.md give the aggregate cap, the recheck pool and the evicted-state rule. Not changed: a smaller cap for UnknownBlock votes. Those include votes for a block held in memory while its columns arrive, the case this PR is for, and the shared cap matches lighthouse's with no regression against main. --- CLAUDE.md | 2 +- crates/net/p2p/src/beacon/parked_votes.rs | 7 ++-- crates/net/p2p/src/beacon/verdict.rs | 43 ++++++++++++++++------- crates/net/p2p/src/lib.rs | 12 +++++-- docs/beacon_wire.md | 9 +++-- docs/metrics.md | 11 +++--- 6 files changed, 58 insertions(+), 26 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 967c29d25..becc05b0c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -357,7 +357,7 @@ actual_slot = finalized_slot + 1 + relative_index - `fork_digest` is a 4-byte hex string (no `0x` prefix); currently the dummy `12345678` agreed across clients - Mesh size: 8 (6-12 bounds), heartbeat: 700ms - Beacon wire: `validate_messages()` is on, so every beacon message waits for a verdict (~4.2s before gossipsub's cache evicts it). Rules in `state_transition::beacon::gossip` (cheap half inline, stateful half on a bounded `spawn_blocking` task); plumbing in `p2p/src/beacon/verdict.rs`. Lean gossip still auto-forwards - - A subnet attestation or aggregate whose vote block is not imported yet (`UnknownBlock`/`StateUnavailable`) is parked with its verdict withheld (`p2p/src/beacon/parked_votes.rs`, lighthouse's reprocess queue) and checked once more when the chain actor's import sends `block_state_ready`; past 2.5 s, or with 16,384 parked, it gets its first verdict instead + - A subnet attestation or aggregate whose vote block is not imported yet (`UnknownBlock`/`StateUnavailable`) is parked with its verdict withheld (`p2p/src/beacon/parked_votes.rs`, lighthouse's reprocess queue) and checked once more when the chain actor's import sends `block_state_ready`; past 2.5 s, or with 16,384 parked (2,048 of them aggregates), it gets its first verdict instead. Rechecks run on their own permit pool (`recheck_permits`), not the attestation pool - Beacon peer scoring: lighthouse's parameters ported in `p2p/src/beacon/scoring.rs` (block, aggregate, 64 attestation subnets, exits, slashings; columns and sync contributions unscored), refreshed every slot from the head's active validator count. Mesh-delivery scoring (P3) is gated off while the head lags more than 4 slots and for an epoch after, because a catching-up node `Ignore`s every aggregate and would otherwise graylist its own mesh. Every held fork digest is parametrized before `transition::apply` joins it (gossipsub never scores a mesh grafted before its topic had parameters); the previous digest's weights are zeroed at the switch, and the switch restarts the P3 warmup. The swarm disconnects peers below the graylist (-16000) every 10 s, and peers gossipsub reported as `SlowPeer` in every check for a minute (a disabled gossipsub handler never drains its send queue, so the queue's message copies stay in memory until the connection closes). Gossipsub reports an expired forward like a full queue, so our own saturated uplink makes every peer look slow: a report counts only above `SLOW_PEER_REPORT_THRESHOLD` failures (Lighthouse's cut), and one check disconnects at most `MAX_SLOW_PEER_DISCONNECTS_PER_CHECK` peers. Lean runs unscored. See [`docs/beacon_wire.md`](docs/beacon_wire.md#peer-scoring) - Data columns: every check runs in p2p. A column gossip did not accept (`Queue`/`Overloaded`), every fetched column, and parked columns replayed after their parent imports go through the chain checks in `p2p/src/beacon/column_checks.rs`, grouped by block with each `(block, index)` kept once. A group's rules before the KZG proofs run through one `column::ChainPrechecks`, which judges what the block's sidecars share (the fulu signed header's rules, the gloas block lookup) once; the proofs then go through `column::kzg_verdicts` in sub-batches of at most 16 columns, each on its own `column_check_permits` permit, a failed batch re-verified column by column. Each sidecar gets the verdict `column::chain_checks_for` gives it alone. The chain actor stores what it gets unchecked; only debug builds re-run `chain_checks_for` there. A held fulu block's custody columns can also come from the execution client (`engine_getBlobsV2`, `crates/blockchain/src/beacon_blobs.rs`; asked only for a block at most `MAX_ASK_AGE_SLOTS` behind the clock, so not during range sync), put through the same `ChainPrechecks` and `kzg_verdicts` in the chain actor's blocking task (the spec lets a node skip that, this one does not: a stored column keeps every other copy out, and import trusts it), and handed to p2p as `SidecarOrigin::ExecutionLayer` through `check_data_column_sidecars`, which records them seen, publishes them on their subnets and forwards them; see `docs/beacon_engine.md` - Beacon subscribes seven global topics plus two node-id-derived subnet families: custody diff --git a/crates/net/p2p/src/beacon/parked_votes.rs b/crates/net/p2p/src/beacon/parked_votes.rs index 5b2eb1c26..6c04cf0bc 100644 --- a/crates/net/p2p/src/beacon/parked_votes.rs +++ b/crates/net/p2p/src/beacon/parked_votes.rs @@ -430,9 +430,10 @@ mod tests { #[test] fn the_deadline_leaves_room_for_a_sweep_inside_gossipsubs_window() { - // Gossipsub drops a message awaiting its verdict as early as five - // heartbeats of 700 ms after it arrived. - let earliest_eviction = Duration::from_millis(5 * 700); + // Gossipsub drops a message awaiting its verdict as early as one + // heartbeat short of its history after it arrived: five of 700 ms. + let heartbeats = u32::try_from(crate::GOSSIPSUB_HISTORY_LENGTH - 1).expect("small"); + let earliest_eviction = crate::GOSSIPSUB_HEARTBEAT * heartbeats; assert!(PARKED_VOTE_DEADLINE + PARKED_VOTE_SWEEP_INTERVAL < earliest_eviction); } } diff --git a/crates/net/p2p/src/beacon/verdict.rs b/crates/net/p2p/src/beacon/verdict.rs index f42c105db..c21a2afe1 100644 --- a/crates/net/p2p/src/beacon/verdict.rs +++ b/crates/net/p2p/src/beacon/verdict.rs @@ -817,7 +817,7 @@ fn spawn_recheck_batch( return; }; let in_use = metrics::PoolInUse::new(RECHECK_POOL); - let task = metrics::BlockingTask::new(kind); + let task = metrics::BlockingTask::new(recheck_task_kind(kind)); tokio::task::spawn_blocking(move || { let _permit = permit; let _in_use = in_use; @@ -862,6 +862,17 @@ fn recheck(store: &Store, vote: ParkedVote, now: Instant) -> GossipVerdict { /// [`metrics::VALIDATION_POOLS`]). const RECHECK_POOL: &str = "recheck"; +/// The `kind` a batch of rechecked votes is timed under: its own, so the +/// blocking-task histograms keep a batch of up to [`RECHECK_BATCH`] checks +/// apart from the single checks of first arrivals. +fn recheck_task_kind(kind: &'static str) -> &'static str { + match kind { + "beacon_attestation" => "beacon_attestation_recheck", + "beacon_aggregate_and_proof" => "beacon_aggregate_and_proof_recheck", + other => other, + } +} + /// How many released votes one blocking task checks again. const RECHECK_BATCH: usize = 64; @@ -971,20 +982,26 @@ pub(crate) fn spawn_stateful_checks( let _in_use = in_use; let _run = task.start(); let mut object = object; - let mut outcome = guarded(|| object.stateful_checks(&store)); let mut parkable = true; - // A missing post-state means the block is still importing only when - // it has no stored state either. With one, it was imported: its state - // left the cache since, and no release will come for it, or it landed - // while this check ran, and its release may already be gone. Either - // way the vote is checked once more now and not parked. - if outcome == Outcome::Ignore(IgnoreReason::StateUnavailable) - && parkable_root(&object, outcome) - .is_some_and(|root| store.has_state(&root).unwrap_or(false)) - { - outcome = guarded(|| object.stateful_checks(&store)); + // One `guarded` around the probe too: `has_state` panics, rather + // than returning an error, on a storage failure. + let outcome = guarded(|| { + let outcome = object.stateful_checks(&store); + // A missing post-state means the block is still importing only + // when it has no stored state either. With one, it was imported: + // its state left the cache since, and no release will come for + // it, or it landed while this check ran, and its release may + // already be gone. Either way the vote is checked once more now + // and not parked. + let imported = outcome == Outcome::Ignore(IgnoreReason::StateUnavailable) + && parkable_root(&object, outcome) + .is_some_and(|root| store.has_state(&root).is_ok_and(|stored| stored)); + if !imported { + return outcome; + } parkable = false; - } + object.stateful_checks(&store) + }); let _ = actor .send(GossipVerdict { id, diff --git a/crates/net/p2p/src/lib.rs b/crates/net/p2p/src/lib.rs index 322d2bc28..1135f6e5b 100644 --- a/crates/net/p2p/src/lib.rs +++ b/crates/net/p2p/src/lib.rs @@ -295,6 +295,14 @@ const ATTESTATION_VALIDATION_PERMITS: usize = 128; /// than failing without one. const RECHECK_PERMITS: usize = 32; +/// Gossipsub's heartbeat. With [`GOSSIPSUB_HISTORY_LENGTH`] it bounds how long +/// gossipsub holds a message awaiting its verdict, which parked votes must +/// stay inside (see `beacon::parked_votes`). +pub(crate) const GOSSIPSUB_HEARTBEAT: Duration = Duration::from_millis(700); + +/// How many heartbeats of message history gossipsub keeps. +pub(crate) const GOSSIPSUB_HISTORY_LENGTH: usize = 6; + /// How many `execution_payload_bid` and `proposer_preferences` stateful checks /// may run at once. A pool of its own, so a burst of bids (each costs a BLS /// verification) cannot starve blocks, columns or attestations of permits. @@ -1237,9 +1245,9 @@ pub(crate) fn gossipsub_config( .mesh_n_high(12) // d_lazy .gossip_lazy(6) - .heartbeat_interval(Duration::from_millis(700)) + .heartbeat_interval(GOSSIPSUB_HEARTBEAT) .fanout_ttl(Duration::from_secs(60)) - .history_length(6) + .history_length(GOSSIPSUB_HISTORY_LENGTH) .history_gossip(3) .prune_backoff(PRUNE_BACKOFF) .unsubscribe_backoff(PRUNE_BACKOFF) diff --git a/docs/beacon_wire.md b/docs/beacon_wire.md index 935d6c810..c74f269b0 100644 --- a/docs/beacon_wire.md +++ b/docs/beacon_wire.md @@ -451,8 +451,13 @@ A vote is parked once: its second check reports whatever it answers. One still parked 2.5 s after it arrived gets its first verdict, since gossipsub drops a message awaiting a verdict as early as 3.5 s in (6 heartbeats of 700 ms of history). The queue holds at most 16,384 votes, lighthouse's own -cap, since nothing about a parked vote has been verified; past it, a vote -gets its first verdict at once. Unlike lighthouse, a vote for a block this +cap, since nothing about a parked vote has been verified, and at most 2,048 +aggregates among them, since an aggregate's bits can reach 16 KiB before its +signature is checked; past either, a vote gets its first verdict at once. +Released votes are checked again on a permit pool of their own, so a big +release takes no permit from the votes arriving meanwhile. A vote whose block +was imported but whose state has left the cache is checked once more at once +and not parked, since no release would come for it. Unlike lighthouse, a vote for a block this node has never seen does not start a lookup for that block: it waits for gossip or sync to bring it. See `crates/net/p2p/src/beacon/parked_votes.rs`. diff --git a/docs/metrics.md b/docs/metrics.md index e03569e02..c29c52926 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -417,7 +417,7 @@ own section. These are ethlambda-specific, not part of the leanMetrics spec. | `lean_beacon_gossip_validation_total` | Counter | Verdicts, by topic kind, outcome and reason | On every verdict reported to gossipsub | kind, outcome=accept,queue,ignore,reject, reason | | | `lean_beacon_gossip_validation_seconds` | Histogram | Time from a message's arrival to its verdict | On every verdict reported to gossipsub | kind | 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 4, 8 | | `lean_beacon_gossip_verdict_expired_total` | Counter | Verdicts that arrived after gossipsub evicted the message, so an Accept propagated nothing | When `report_message_validation_result` returns `false` | kind | | -| `lean_beacon_gossip_parked_votes_total` | Counter | Subnet attestations and aggregates whose verdict waited for their block's post-state, by what happened to them | When a vote is parked, refused by the full queue, checked again, or past its deadline | kind, result=parked,full,rechecked,expired | | +| `lean_beacon_gossip_parked_votes_total` | Counter | Subnet attestations and aggregates whose verdict waited for their block's post-state, by what happened to them | When a vote is parked, refused by the full queue, checked again, or past its deadline. `rechecked` and `expired` also count a vote checked again at once because its block was announced before its first verdict arrived, which is never `parked` | kind, result=parked,full,rechecked,expired | | | `lean_beacon_gossip_parked_votes` | Gauge | Votes parked right now | On every park, release and sweep | | | `kind` is the topic kind, with every `data_column_sidecar_{subnet}` sharing the @@ -448,9 +448,10 @@ as `queue`: its verdict is withheld while it waits for the block's import, then its checks run again, on a permit pool of their own (`pool="recheck"`) (`lean_beacon_gossip_parked_votes_total`, and `crates/net/p2p/src/beacon/parked_votes.rs`). A vote whose block was imported -but whose state has left the cache is checked once more at once and not held. Only a vote still waiting at its -deadline, 2.5 s after it arrived, or one the full queue refused, is counted -under those two reasons. Its time to verdict includes the wait, so +but whose state has left the cache is checked once more at once and not held. A vote counted under those two +reasons is one still waiting at its deadline, 2.5 s after it arrived, one the +full queue refused, or one whose second check still found its block or state +missing. Its time to verdict includes the wait, so `lean_beacon_gossip_validation_seconds` for these two kinds reads up to that deadline. **`verdict_expired_total` should stay at zero**: a rising count means validation is too slow for gossipsub's message @@ -514,7 +515,7 @@ ethlambda-specific, not part of the leanMetrics spec. | `lean_beacon_validation_permits_in_use` | Gauge | Permits held per pool: blocking tasks queued or running | A permit is acquired / released | pool=gossip,attestation,builder,sync,column_check,recheck | | | `lean_beacon_validation_permit_exhausted_total` | Counter | Objects reported `Ignore(Overloaded)` because their pool had no free permit | On each failed `try_acquire` | pool=gossip,attestation,builder,sync | | | `lean_beacon_validation_queue_seconds` | Histogram | Time from `spawn_blocking` being called to the closure starting (tokio blocking-pool queueing) | When the closure starts | kind | 0.0001, 0.0005, 0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2, 4 | -| `lean_beacon_validation_run_seconds` | Histogram | Run time of the closure itself | When the closure ends (panic included) | kind | same as above | +| `lean_beacon_validation_run_seconds` | Histogram | Run time of the closure itself. A batch of up to 64 parked votes checked again is one closure, timed under `beacon_attestation_recheck` or `beacon_aggregate_and_proof_recheck` | When the closure ends (panic included) | kind | same as above | | `lean_beacon_column_check_permit_wait_seconds` | Histogram | Time a block's fetched or replayed columns (their prechecks, or a further KZG sub-batch) or a fetched envelope waited for a `column_check` permit | When the permit is granted | kind=column_check,envelope_check | same as above | | `lean_beacon_epoch_precompute_running` | Gauge | 1 while an epoch precompute worker runs its advance | Worker start / end | | |