diff --git a/crates/blockchain/src/metrics.rs b/crates/blockchain/src/metrics.rs index d694c9453..51ca0f581 100644 --- a/crates/blockchain/src/metrics.rs +++ b/crates/blockchain/src/metrics.rs @@ -1770,6 +1770,82 @@ pub fn observe_beacon_aggregate_end_to_end(duration: Duration) { LEAN_BEACON_AGGREGATE_END_TO_END_SECONDS.observe(duration.as_secs_f64()); } +/// Record one merge of a PQ block's attestation proofs, when it ends: how +/// long leanVM took, how many child proofs it folded, and the merged proof's +/// size when there is one. +/// +/// `phase` is `ahead` for a packing started ahead of the slot and +/// `production` for one block production ran itself. A merge that failed or +/// outlived its budget is observed like any other: its cost is still cost, +/// and [`inc_pq_merges`] says what became of it. +pub fn observe_pq_merge( + phase: &str, + elapsed: Duration, + children: usize, + proof_bytes: Option, +) { + static LEAN_BEACON_PQ_MERGE_SECONDS: std::sync::LazyLock = + std::sync::LazyLock::new(|| { + register_histogram_vec!( + "lean_beacon_pq_merge_seconds", + "Time leanVM took to merge a PQ block's attestation proofs into one, by phase", + &["phase"], + vec![ + 0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0 + ] + ) + .unwrap() + }); + static LEAN_BEACON_PQ_MERGE_CHILDREN: std::sync::LazyLock = + std::sync::LazyLock::new(|| { + register_histogram!( + "lean_beacon_pq_merge_children", + "Child proofs one merge of a PQ block's attestation proofs folded", + vec![2.0, 3.0, 4.0, 6.0, 8.0, 12.0, 16.0, 24.0, 32.0, 48.0, 64.0] + ) + .unwrap() + }); + static LEAN_BEACON_PQ_MERGED_PROOF_SIZE_BYTES: std::sync::LazyLock = + std::sync::LazyLock::new(|| { + register_histogram!( + "lean_beacon_pq_merged_proof_size_bytes", + "Bytes size of a PQ block's merged attestation proof", + vec![ + 131072.0, 163840.0, 196608.0, 229376.0, 262144.0, 327680.0, 393216.0, 524288.0, + 786432.0, 1048576.0 + ] + ) + .unwrap() + }); + LEAN_BEACON_PQ_MERGE_SECONDS + .with_label_values(&[phase]) + .observe(elapsed.as_secs_f64()); + LEAN_BEACON_PQ_MERGE_CHILDREN.observe(children as f64); + if let Some(bytes) = proof_bytes { + LEAN_BEACON_PQ_MERGED_PROOF_SIZE_BYTES.observe(bytes as f64); + } +} + +/// Count one packing that had several proofs to merge, by phase (see +/// [`observe_pq_merge`]) and by what became of the merge: `merged`, `failed`, +/// `late` (it outlived its budget) or `skipped` (no time left for it, or +/// another merge held leanVM). All but `merged` pack one committee's +/// attestation in place of everything selected. +pub fn inc_pq_merges(phase: &str, outcome: &str) { + static LEAN_BEACON_PQ_MERGES_TOTAL: std::sync::LazyLock = + std::sync::LazyLock::new(|| { + register_int_counter_vec!( + "lean_beacon_pq_merges_total", + "Packings of a PQ block's attestations with several proofs to merge, by phase and outcome", + &["phase", "outcome"] + ) + .unwrap() + }); + LEAN_BEACON_PQ_MERGES_TOTAL + .with_label_values(&[phase, outcome]) + .inc(); +} + /// Count one `engine_getBlobsV2` attempt for a held fulu block, by what came /// back: `hit` (every blob), `miss` (the execution client answered `null`, so /// at least one blob is not in its pool) or `error` (transport, timeout or a diff --git a/crates/blockchain/src/pq_attestation_packing.rs b/crates/blockchain/src/pq_attestation_packing.rs index b182c870d..86f41977f 100644 --- a/crates/blockchain/src/pq_attestation_packing.rs +++ b/crates/blockchain/src/pq_attestation_packing.rs @@ -64,6 +64,7 @@ use ethlambda_types::primitives::H256; use tokio::sync::{Semaphore, SemaphorePermit, watch}; use tracing::{debug, info, warn}; +use crate::metrics; use crate::payload_attributes::advance_for_proposal; /// What a PQ block packs: its attestations and the proof of all of them. @@ -137,6 +138,16 @@ pub enum PermitWait<'a> { Wait { abandoned: &'a AtomicBool }, } +impl PermitWait<'_> { + /// The `phase` label the merge metrics record this packing under. + fn phase(self) -> &'static str { + match self { + Self::TryOnce => "production", + Self::Wait { .. } => "ahead", + } + } +} + /// The pool's candidates for a block at `slot`: aggregates from /// `slot - MIN_ATTESTATION_INCLUSION_DELAY_PQ` and earlier. fn candidates_for(store: &Store, slot: Slot) -> Vec> { @@ -186,7 +197,10 @@ pub async fn pack_attestations( return unmerged(slot, packed, true, candidates); } let children = packed.children.len(); - let fall_back = |reason: &str| { + let phase = permit_wait.phase(); + // `outcome` is the merge's, as `metrics::inc_pq_merges` counts it. + let fall_back = |outcome: &str, reason: &str| { + metrics::inc_pq_merges(phase, outcome); warn!(%slot, children, reason, "Packing one PQ attestation instead of merging every proof"); match fallback.clone() { Some(single) => unmerged(slot, single, false, candidates.clone()), @@ -194,7 +208,7 @@ pub async fn pack_attestations( } }; let Some(remaining) = merge_budget(config, slot) else { - return fall_back("no time left to merge"); + return fall_back("skipped", "no time left to merge"); }; let permit = match merge_permit(permit_wait, remaining).await { Ok(permit) => permit, @@ -203,11 +217,11 @@ pub async fn pack_attestations( debug!(%slot, "A PQ attestation packing was abandoned before its merge"); return PackedAttestations::new(Vec::new(), Vec::new(), false, candidates); } - Err(NoPermit::Refused(reason)) => return fall_back(reason), + Err(NoPermit::Refused(reason)) => return fall_back("skipped", reason), }; // The wait for the permit came out of the budget. let Some(remaining) = merge_budget(config, slot) else { - return fall_back("no time left to merge"); + return fall_back("skipped", "no time left to merge"); }; let budget_ms = remaining.as_millis() as u64; let state_for_plan = state.clone(); @@ -268,8 +282,10 @@ pub async fn pack_attestations( }; let started = Instant::now(); let proof = packed.merge().map_err(|err| err.to_string()); - // Logged when it ends, deadline or not: what a merge costs here, how - // big it was and how much of the budget it used. + let took = started.elapsed(); + // Recorded and logged when it ends, deadline or not: what a merge + // costs here, how big it was and how much of the budget it used. + metrics::observe_pq_merge(phase, took, children, proof.as_ref().ok().map(Vec::len)); let signatures: usize = packed .children .iter() @@ -303,7 +319,7 @@ pub async fn pack_attestations( children, signatures, proof_bytes = proof.as_ref().map_or(0, Vec::len), - took_ms = started.elapsed().as_millis() as u64, + took_ms = took.as_millis() as u64, budget_ms, ok = proof.is_ok(), "Merged PQ attestation proofs" @@ -312,6 +328,7 @@ pub async fn pack_attestations( }); match tokio::time::timeout(remaining, job).await { Ok(Ok(Ok((packed, proof, completion, has_duty)))) => { + metrics::inc_pq_merges(phase, "merged"); if let Some(completion) = completion && let Some(op) = completion.ready(if has_duty { "proposal" } else { "reusable" }) { @@ -326,12 +343,12 @@ pub async fn pack_attestations( ); PackedAttestations::new(packed.attestations, proof, true, candidates) } - Ok(Ok(Err(err))) => fall_back(&format!("the merge failed: {err}")), - Ok(Err(err)) => fall_back(&format!("the merge task failed: {err}")), - Err(_) => fall_back(&format!( - "the merge missed its {} ms budget", - remaining.as_millis() - )), + Ok(Ok(Err(err))) => fall_back("failed", &format!("the merge failed: {err}")), + Ok(Err(err)) => fall_back("failed", &format!("the merge task failed: {err}")), + Err(_) => fall_back( + "late", + &format!("the merge missed its {} ms budget", remaining.as_millis()), + ), } } @@ -795,6 +812,103 @@ mod tests { } /// An abandoned packing gives the merge permit up without taking it. + /// A network aggregate of every member of `committee` at `data`'s slot. + fn full_aggregate( + state: &BeaconState, + store: &Store, + data: AttestationData, + committee: u64, + ) -> PooledPqAggregate { + use ethlambda_state_transition::beacon::helpers::accessors::CommitteeCacheExt as _; + let members = store + .committee_cache() + .committees(state, data.target.epoch) + .committee(data.slot, committee) + .unwrap() + .to_vec(); + let mut aggregation_bits = AggregationBits::with_length(members.len()); + for position in 0..members.len() { + aggregation_bits.set(position, true).unwrap(); + } + let mut committee_bits = pq::CommitteeBits::new(); + committee_bits.set(committee as usize, true).unwrap(); + let mut attesting_indices = members; + attesting_indices.sort_unstable(); + PooledPqAggregate { + attestation: Attestation { + aggregation_bits, + data, + committee_bits, + }, + committee_index: committee, + attesting_indices, + proof: vec![committee as u8; 4].try_into().unwrap(), + } + } + + /// A packing with two proofs to merge and no time left for it packs + /// without them, and `/metrics` counts the merge as skipped under the + /// packing's phase: ahead of the slot, or at production. + #[tokio::test] + async fn a_merge_with_no_time_left_is_counted_as_skipped_by_phase() { + use ethlambda_metrics::series_value; + use ethlambda_state_transition::beacon::helpers::accessors::{ + get_block_root, get_block_root_at_slot, + }; + use ethlambda_state_transition::beacon::helpers::test_state::with_validators_at; + use ethlambda_types::beacon::containers::shared::Checkpoint; + use ethlambda_types::beacon::fork::ForkName; + use ethlambda_types::beacon::preset; + + // Two committees per slot under either preset. + let validators = 2 * preset::slots_per_epoch() * preset::target_committee_size(); + let state = with_validators_at(ForkName::Pq, validators as usize); + let store = empty_pool_store(); + let data_slot = state.slot() - MIN_ATTESTATION_INCLUSION_DELAY_PQ; + let epoch = compute_epoch_at_slot(data_slot); + let data = AttestationData { + slot: data_slot, + index: 0, + beacon_block_root: get_block_root_at_slot(&state, data_slot).unwrap(), + source: state.current_justified_checkpoint(), + target: Checkpoint { + epoch, + root: get_block_root(&state, epoch).unwrap(), + }, + }; + for committee in 0..2 { + let aggregate = full_aggregate(&state, &store, data, committee); + store.pq_aggregate_pool().insert(aggregate); + } + // Genesis at the UNIX epoch: the state's slot ended long ago. + let mut config = Config::mainnet(); + config.genesis_time = 0; + assert!(merge_budget(&config, state.slot()).is_none()); + + let skipped = |phase: &str| { + let series = + format!(r#"lean_beacon_pq_merges_total{{outcome="skipped",phase="{phase}"}}"#); + series_value(&series).unwrap_or(0.0) + }; + let abandoned = AtomicBool::new(false); + let waits = [ + ("production", PermitWait::TryOnce), + ( + "ahead", + PermitWait::Wait { + abandoned: &abandoned, + }, + ), + ]; + for (phase, wait) in waits { + let before = skipped(phase); + let packed = pack_attestations(&store, &state, &config, wait).await; + assert!(!packed.complete, "{phase}"); + assert!(packed.proof.is_empty(), "{phase}"); + assert_eq!(skipped(phase) - before, 1.0, "{phase}"); + } + } + #[tokio::test] async fn an_abandoned_packing_does_not_take_the_merge_permit() { let abandoned = AtomicBool::new(true); diff --git a/crates/blockchain/state_transition/src/beacon/gossip/pq.rs b/crates/blockchain/state_transition/src/beacon/gossip/pq.rs index fd5b71bd0..30883f705 100644 --- a/crates/blockchain/state_transition/src/beacon/gossip/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/gossip/pq.rs @@ -335,14 +335,16 @@ pub fn aggregate_stateful_checks( // [Modified in PQ] [REJECT] The aggregate stark is valid. let statements = get_attestation_statements(&state, aggregate, &committees) .map_err(|_| Outcome::Reject(RejectReason::AggregateProof))?; - let verify_started = ethlambda_telemetry::pq_events::is_enabled().then(std::time::Instant::now); - let verified = verify_aggregates(&statements, &aggregate_and_proof.proof); - if let Some(started) = verify_started { + let verifying = std::time::Instant::now(); + let proven = verify_aggregates(&statements, &aggregate_and_proof.proof); + let elapsed = verifying.elapsed(); + crate::metrics::observe_pq_proof_verification("aggregate", elapsed); + if ethlambda_telemetry::pq_events::is_enabled() { ethlambda_telemetry::pq_events::gossip::record_current_proof_verify_ns( - u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX), + u64::try_from(elapsed.as_nanos()).unwrap_or(u64::MAX), ); } - if !verified { + if !proven { return Err(Outcome::Reject(RejectReason::AggregateProof)); } let attesting_indices = get_attesting_indices(&state, aggregate, &committees) @@ -1135,6 +1137,14 @@ mod tests { message: vote_root.0, }; let proof = stark::prove_aggregates(&[statement], &[vec![vote.0.to_vec()]]).unwrap(); + // An aggregate that reaches the proof check has its verification + // timed: the valid one and the unproven one below, not the two + // refused before it. + let verifications = || { + let series = r#"lean_beacon_pq_proof_verification_seconds_count{kind="aggregate"}"#; + ethlambda_metrics::series_value(series).unwrap_or(0.0) + }; + let verified_before = verifications(); let valid = aggregate( &state, @@ -1183,6 +1193,7 @@ mod tests { aggregate_stateful_checks(&store, &unproven), Err(Outcome::Reject(RejectReason::AggregateProof)) ); + assert_eq!(verifications() - verified_before, 2.0); } #[test] diff --git a/crates/blockchain/state_transition/src/beacon/stf/pq.rs b/crates/blockchain/state_transition/src/beacon/stf/pq.rs index 6172b444f..a07ab1907 100644 --- a/crates/blockchain/state_transition/src/beacon/stf/pq.rs +++ b/crates/blockchain/state_transition/src/beacon/stf/pq.rs @@ -328,8 +328,14 @@ pub fn process_stark( for attestation in body.attestations.iter() { statements.extend(get_attestation_statements(state, attestation, committees)?); } + let verifying = std::time::Instant::now(); + let proven = verify_aggregates(&statements, &body.proof); + // A block without attestations has nothing to verify: not a sample. + if !statements.is_empty() { + crate::metrics::observe_pq_proof_verification("block", verifying.elapsed()); + } verify( - verify_aggregates(&statements, &body.proof), + proven, "process_stark: stark.VerifyAggregates(statements, body.proof)", ) } @@ -1203,6 +1209,12 @@ mod tests { proof: proof.try_into().expect("far below MAX_STARK_PROOF_SIZE"), ..pq::BeaconBlockBody::empty() }; + // Each verification is timed as a block's, a refused proof's too. + let timed = || { + let series = r#"lean_beacon_pq_proof_verification_seconds_count{kind="block"}"#; + ethlambda_metrics::series_value(series).unwrap_or(0.0) + }; + let before = timed(); // The reference encoding: the signatures, in statement order. let proof = signatures.concat(); assert!(process_stark(&state, &body_with(proof.clone()), &committees).is_ok()); @@ -1213,6 +1225,7 @@ mod tests { reversed.reverse(); let reversed = reversed.concat(); assert!(process_stark(&state, &body_with(reversed), &committees).is_err()); + assert!(timed() - before >= 3.0); } /// A full-committee attestation to `data_slot` voting for the head and diff --git a/crates/blockchain/state_transition/src/metrics.rs b/crates/blockchain/state_transition/src/metrics.rs index 4fc73ec52..60ca4fe5d 100644 --- a/crates/blockchain/state_transition/src/metrics.rs +++ b/crates/blockchain/state_transition/src/metrics.rs @@ -536,6 +536,35 @@ pub fn time_data_column_kzg_verify() -> TimingGuard { TimingGuard::new(&LEAN_DATA_COLUMN_KZG_VERIFY_SECONDS) } +/// Record one verification of a PQ attestation proof (`stark.VerifyAggregates`, +/// leanVM's on a node that follows PQ), by what was verified: `aggregate` for +/// an aggregate's proof of one committee, `block` for a block's merged proof. +/// A proof that does not verify is observed too. +/// +/// Here because both run inside this crate's rules: the aggregate's in +/// `beacon::gossip::pq`, which the p2p layer calls for gossip and the Beacon +/// API for a validator client's own aggregates, and the block's in +/// `process_stark`. +pub fn observe_pq_proof_verification(kind: &str, elapsed: std::time::Duration) { + static LEAN_BEACON_PQ_PROOF_VERIFICATION_SECONDS: LazyLock = LazyLock::new( + || { + register_histogram_vec!( + "lean_beacon_pq_proof_verification_seconds", + "Time to verify one PQ attestation proof, by what it proves (one aggregate, a block's attestations)", + &["kind"], + vec![ + 0.001, 0.0025, 0.005, 0.0075, 0.01, 0.015, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, + 2.0 + ] + ) + .unwrap() + }, + ); + LEAN_BEACON_PQ_PROOF_VERIFICATION_SECONDS + .with_label_values(&[kind]) + .observe(elapsed.as_secs_f64()); +} + /// Register the metrics above that should be visible before their first /// observation. pub fn init() { diff --git a/crates/common/metrics/src/gather.rs b/crates/common/metrics/src/gather.rs index 8912d18e6..9b6adfdec 100644 --- a/crates/common/metrics/src/gather.rs +++ b/crates/common/metrics/src/gather.rs @@ -28,6 +28,63 @@ pub fn gather_default_metrics() -> Result { Ok(res) } +/// The value of one series in the default registry, named as the text +/// exposition spells it: the metric's name, then its labels in alphabetical +/// order, as in `requests_total{method="get",outcome="ok"}`. A histogram's +/// are its `_count`, `_sum` and `_bucket` series. `None` for a series nothing +/// has recorded yet. +/// +/// For tests that check a code path left its metrics behind: the registry is +/// the process's, so a test reads what it recorded under labels of its own, +/// or compares a reading before with one after. +pub fn series_value(series: &str) -> Option { + let metrics = gather_default_metrics().ok()?; + metrics.lines().find_map(|line| { + line.strip_prefix(series)? + .strip_prefix(' ')? + .trim() + .parse() + .ok() + }) +} + +#[cfg(test)] +mod series_tests { + use super::*; + use crate::{register_histogram_vec, register_int_counter_vec}; + + #[test] + fn a_series_is_read_by_its_exposition_name() { + let counter = register_int_counter_vec!( + "series_value_test_total", + "A counter for series_value's test", + &["outcome", "kind"] + ) + .unwrap(); + counter.with_label_values(&["ok", "a"]).inc_by(3); + let read = series_value(r#"series_value_test_total{kind="a",outcome="ok"}"#); + assert_eq!(read, Some(3.0)); + // Another label set, and a name this one is only a prefix of. + assert_eq!( + series_value(r#"series_value_test_total{kind="b",outcome="ok"}"#), + None + ); + assert_eq!(series_value("series_value_test"), None); + + let histogram = register_histogram_vec!( + "series_value_test_seconds", + "A histogram for series_value's test", + &["kind"], + vec![1.0, 2.0] + ) + .unwrap(); + histogram.with_label_values(&["a"]).observe(1.5); + let count = series_value(r#"series_value_test_seconds_count{kind="a"}"#); + let sum = series_value(r#"series_value_test_seconds_sum{kind="a"}"#); + assert_eq!((count, sum), (Some(1.0), Some(1.5))); + } +} + /// The process collector comes from the `prometheus` crate's `process` /// feature, which registers it with the default registry on Linux only. /// Dashboards read the node's memory from it, so dropping the feature would diff --git a/crates/common/metrics/src/lib.rs b/crates/common/metrics/src/lib.rs index a1a19e370..ad341b81a 100644 --- a/crates/common/metrics/src/lib.rs +++ b/crates/common/metrics/src/lib.rs @@ -12,5 +12,5 @@ pub use prometheus::{ }; // Re-export commonly used items -pub use gather::{GatherError, gather_default_metrics}; +pub use gather::{GatherError, gather_default_metrics, series_value}; pub use timing::TimingGuard; diff --git a/crates/net/p2p/src/beacon/pq.rs b/crates/net/p2p/src/beacon/pq.rs index 582f4ee49..5e6a8ad2d 100644 --- a/crates/net/p2p/src/beacon/pq.rs +++ b/crates/net/p2p/src/beacon/pq.rs @@ -11,7 +11,7 @@ //! (queued ones too, as for gloas). Blocks and data column sidecars take the //! shared path. -use std::time::Instant; +use std::time::{Duration, Instant}; use std::time::Instant as StdInstant; @@ -21,7 +21,8 @@ use ethlambda_state_transition::beacon::gossip::{self, IgnoreReason, Outcome}; use ethlambda_state_transition::beacon::helpers::pq::get_committee_indices; use ethlambda_storage::{Store, pools::PooledPqAggregate}; use ethlambda_types::beacon::containers::{SignedExecutionPayloadEnvelope, pq}; -use ethlambda_types::beacon::primitives::ValidatorIndex; +use ethlambda_types::beacon::primitives::{Slot, ValidatorIndex}; +use ethlambda_types::chain_config::ChainConfig; use ethlambda_types::time::unix_now_ms; use tracing::{debug, trace, warn}; @@ -176,12 +177,43 @@ impl PqValidated { } } + /// Record when in its slot an accepted attestation or aggregate reached + /// this node, `received_at` being when it came off the wire. + /// + /// Only an accepted one is a sample. The offset is measured from the slot + /// the message itself names, so observing a message that merely decodes + /// would let any peer write the samples it likes: a slot long past reads + /// as the time since genesis, and such a message is ignored, which costs + /// its sender no score. An accepted vote is in the current or the + /// previous epoch, signed by its validator, and the first one for its + /// key, so a sample is a real vote's real arrival. + fn observe_vote_arrival(&self, store: &Store, received_at: StdInstant) { + let (kind, slot) = match self { + Self::Aggregate { signed, .. } => ( + beacon_topics::BEACON_AGGREGATE_AND_PROOF, + signed.message.aggregate.data.slot, + ), + Self::Attestation { attestation, .. } => ( + beacon_topics::BEACON_ATTESTATION_KIND, + attestation.data.slot, + ), + _ => return, + }; + let since_arrival_ms = received_at.elapsed().as_millis() as u64; + let arrived_ms = unix_now_ms().saturating_sub(since_arrival_ms); + let offset = arrival_offset(&store.config().time_grid(), slot, arrived_ms); + metrics::observe_pq_gossip_arrival_offset(kind, offset); + } + /// Hand the parts fork choice reads to the chain actor, given the gossip /// `outcome`: an aggregate's vote and a payload attestation only when /// accepted, an envelope also when queued (the actor holds one whose block /// it has not imported). Subnet attestations, slashings, bids and /// preferences stop at relay, as gloas's do. pub(crate) fn forward(self, server: &P2PServer, received_at: StdInstant, outcome: Outcome) { + if outcome == Outcome::Accept { + self.observe_vote_arrival(&server.store, received_at); + } if let Self::Aggregate { signed, attesting_indices, @@ -495,6 +527,15 @@ pub(crate) fn triage( Some(Dispatch::Validate(Validated::Pq(Box::new(object)))) } +/// How far into `slot` the wall clock read `arrived_ms`. Zero for a message +/// that arrived ahead of its slot, which gossip allows by the clock disparity. +fn arrival_offset(grid: &ChainConfig, slot: Slot, arrived_ms: u64) -> Duration { + let slot_start_ms = grid + .genesis_time_ms() + .saturating_add(slot.saturating_mul(grid.milliseconds_per_slot)); + Duration::from_millis(arrived_ms.saturating_sub(slot_start_ms)) +} + /// Gossip one of a validator client's PQ messages, which the Beacon API /// validated with PQ's gossip rules, on its topic under the digest of its /// slot, record it in the seen caches gossip validation reads, and hand the @@ -657,6 +698,19 @@ mod tests { ) } + /// A vote's arrival is measured from the start of its own slot, not the + /// wall clock's: an aggregate of slot 2 that arrives in slot 3 is 13 s in. + #[test] + fn a_votes_arrival_is_measured_from_its_own_slot() { + let grid = ChainConfig::new(100, 12_000); + let slot_2_ms = 100_000 + 2 * 12_000; + let offset = |arrived_ms| arrival_offset(&grid, 2, arrived_ms); + assert_eq!(offset(slot_2_ms + 7_300), Duration::from_millis(7_300)); + assert_eq!(offset(slot_2_ms + 13_000), Duration::from_secs(13)); + // Ahead of its slot, within the clock disparity gossip allows. + assert_eq!(offset(slot_2_ms - 200), Duration::ZERO); + } + /// A message this build cannot decode under a PQ digest is this build's /// gap, as on every topic of a fork the node does not follow: ignored, /// so no peer is scored down for it. @@ -676,6 +730,83 @@ mod tests { )); } + /// A vote's arrival is a sample only once gossip validation accepted it, + /// under its topic kind. One that merely decodes names whatever slot its + /// sender chose, so neither decoding it nor any other verdict records + /// anything; nor does an accepted message that is not a vote. + #[tokio::test] + async fn only_an_accepted_votes_arrival_is_recorded() { + let server = unconnected_beacon_server(config(), 0).await; + let arrivals = || { + [ + beacon_topics::BEACON_ATTESTATION_KIND, + beacon_topics::BEACON_AGGREGATE_AND_PROOF, + ] + .map(|kind| { + let series = format!( + r#"lean_beacon_pq_gossip_arrival_offset_seconds_count{{kind="{kind}"}}"# + ); + ethlambda_metrics::series_value(&series).unwrap_or(0.0) + }) + }; + let before = arrivals(); + + let attestation = pq::SingleAttestation { + committee_index: 0, + attester_index: 0, + data: Default::default(), + signature: Default::default(), + }; + let aggregate = pq::SignedAggregateAndProof { + message: pq::AggregateAndProof { + aggregator_index: 0, + aggregate: pq::Attestation { + aggregation_bits: Default::default(), + data: Default::default(), + committee_bits: Default::default(), + }, + proof: Default::default(), + }, + signature: Default::default(), + }; + let attestation_object = || PqValidated::Attestation { + attestation: Box::new(attestation.clone()), + subnet_id: 3, + }; + let aggregate_object = || PqValidated::Aggregate { + signed: Box::new(aggregate.clone()), + attesting_indices: Vec::new(), + topic: String::new(), + pq_aggregate_id: None, + }; + + // Decoded off the wire, with the slot and signature a peer chose. + let subnet_topic = format!("{}3", beacon_topics::BEACON_ATTESTATION_PREFIX); + assert!(triage_now(&server, &subnet_topic, &attestation.to_ssz()).is_some()); + let aggregate_topic = beacon_topics::BEACON_AGGREGATE_AND_PROOF; + assert!(triage_now(&server, aggregate_topic, &aggregate.to_ssz()).is_some()); + // Every verdict but `Accept` that reaches `forward`. + for outcome in [ + Outcome::Ignore(IgnoreReason::Overloaded), + Outcome::Queue(gossip::QueueReason::BlockUnknown), + ] { + attestation_object().forward(&server, Instant::now(), outcome); + aggregate_object().forward(&server, Instant::now(), outcome); + } + // Accepted, and not a vote. + PqValidated::ProposerSlashing(Box::default()).forward( + &server, + Instant::now(), + Outcome::Accept, + ); + assert_eq!(arrivals(), before); + + attestation_object().forward(&server, Instant::now(), Outcome::Accept); + assert_eq!(arrivals(), [before[0] + 1.0, before[1]]); + aggregate_object().forward(&server, Instant::now(), Outcome::Accept); + assert_eq!(arrivals(), [before[0] + 1.0, before[1] + 1.0]); + } + /// A block or a column takes the shared path under a PQ digest too. #[tokio::test] async fn a_pq_digests_block_topic_is_not_triaged_here() { diff --git a/crates/net/p2p/src/metrics.rs b/crates/net/p2p/src/metrics.rs index 0f7d8f7c8..9d865867f 100644 --- a/crates/net/p2p/src/metrics.rs +++ b/crates/net/p2p/src/metrics.rs @@ -397,6 +397,33 @@ static LEAN_BEACON_GOSSIP_VALIDATION_SECONDS: LazyLock = LazyLock: .unwrap() }); +/// Record how far into its vote's slot a PQ attestation or aggregate that +/// gossip validation accepted reached this node, by topic kind +/// (`beacon_attestation`, `beacon_aggregate_and_proof`: the `kind` values of +/// `lean_beacon_gossip_validation_seconds`). +/// +/// The bounds follow a 12-second slot: attestations are due by 4.8 s, and the +/// four aggregator seats broadcast at 7.2, 7.8, 8.4 and 9.0 s. +pub fn observe_pq_gossip_arrival_offset(kind: &str, offset: std::time::Duration) { + static LEAN_BEACON_PQ_GOSSIP_ARRIVAL_OFFSET_SECONDS: LazyLock = LazyLock::new( + || { + register_histogram_vec!( + "lean_beacon_pq_gossip_arrival_offset_seconds", + "How far into its vote's slot an accepted PQ attestation or aggregate arrived on gossip, by topic kind", + &["kind"], + vec![ + 0.25, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 4.0, 4.8, 6.0, 7.2, 7.5, 7.8, 8.1, 8.4, + 8.7, 9.0, 9.5, 10.0, 12.0, 24.0 + ] + ) + .unwrap() + }, + ); + LEAN_BEACON_PQ_GOSSIP_ARRIVAL_OFFSET_SECONDS + .with_label_values(&[kind]) + .observe(offset.as_secs_f64()); +} + static LEAN_BEACON_GOSSIP_VERDICT_EXPIRED_TOTAL: LazyLock = LazyLock::new(|| { register_int_counter_vec!( "lean_beacon_gossip_verdict_expired_total", diff --git a/crates/net/rpc/src/beacon/pq_aggregation.rs b/crates/net/rpc/src/beacon/pq_aggregation.rs index 20fe89283..465ef7d0a 100644 --- a/crates/net/rpc/src/beacon/pq_aggregation.rs +++ b/crates/net/rpc/src/beacon/pq_aggregation.rs @@ -46,6 +46,7 @@ use tokio_util::sync::CancellationToken; use tracing::{debug, info, warn}; use crate::beacon::validator::head; +use crate::metrics::{self, PqCommitteeProof}; /// Start proving PQ aggregates at every aggregator's cutoff, if the network /// schedules PQ. Stops with `shutdown`. @@ -147,23 +148,9 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { let deadline_ms = slot_start_ms(config, slot) + get_pq_aggregate_due_ms(position, config); // The same cutoff for telemetry: a duty abandoned below was abandoned at it. let deadline_ns = deadline_ms.saturating_mul(1_000_000); - let Some(budget) = deadline_ms.checked_sub(now_ms()).filter(|&left| left > 0) else { - warn!(%slot, position, "No time left to prove this seat's PQ aggregates"); - if ethlambda_telemetry::pq_events::is_enabled() - && let Ok((_, state)) = head(store) - { - for (committee, validator) in committees_at_seat(store, &state, slot, position) { - let _ = schedule_committee_duty( - config, &state, store, slot, committee, position, validator, - ); - let key = - ethlambda_telemetry::pq_events::duty::committee_key(slot, committee, position); - ethlambda_telemetry::pq_events::duty::missed_deadline(&key, deadline_ns); - } - } - return; - }; + let budget = deadline_ms.saturating_sub(now_ms()); let deadline = Instant::now() + Duration::from_millis(budget); + let slot_start = slot_start_ms(config, slot); let store = store.clone(); let cfg = config.clone(); let spawned = Instant::now(); @@ -208,23 +195,32 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { let all_groups = store .pq_signature_pool() .collected(slot, &committee_indices); + // A committee seated here that collected no vote has no group, and + // so nothing to prove: it is counted on its own below, or a quiet + // committee would leave no trace of the duty at all. + let seen_committees: std::collections::HashSet = + all_groups.iter().map(|g| g.committee_index).collect(); + let quiet: Vec = committee_indices + .iter() + .copied() + .filter(|committee| !seen_committees.contains(committee)) + .collect(); if ethlambda_telemetry::pq_events::is_enabled() { - let seen_committees: std::collections::HashSet = - all_groups.iter().map(|g| g.committee_index).collect(); - for &(committee, _) in &seated { - if !seen_committees.contains(&committee) { - let key = ethlambda_telemetry::pq_events::duty::committee_key( - slot, committee, position, - ); - ethlambda_telemetry::pq_events::duty::details( - &key, - serde_json::json!({ "available_signers": 0, "selected_signers": 0 }), - ); - ethlambda_telemetry::pq_events::duty::complete(&key, "no_inputs", "no_inputs"); - } + for &committee in &quiet { + let key = + ethlambda_telemetry::pq_events::duty::committee_key(slot, committee, position); + ethlambda_telemetry::pq_events::duty::details( + &key, + serde_json::json!({ "available_signers": 0, "selected_signers": 0 }), + ); + ethlambda_telemetry::pq_events::duty::complete(&key, "no_inputs", "no_inputs"); } } - let committees = all_groups.len(); + let no_inputs = quiet.len(); + // One aggregate is due per vote a committee collected signatures + // for: its attesters can disagree within a slot, and each vote is + // proved on its own. + let aggregates = all_groups.len(); let mut groups = Vec::with_capacity(all_groups.len()); // What an earlier seat of this node already proved in full is not // proved again: see `PqSignaturePool::is_proven`. @@ -250,7 +246,7 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { groups.push(group); } } - let already_proven = committees - groups.len(); + let already_proven = aggregates - groups.len(); let signatures: usize = groups.iter().map(|group| group.signatures.len()).sum(); // The larger groups first, in case not every one fits before the // deadline. @@ -268,7 +264,11 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { serde_json::json!({ "available_signers": collected }), ); if Instant::now() >= deadline { - warn!(%slot, position, "The PQ aggregate deadline passed with committees left to prove"); + if budget == 0 { + warn!(%slot, position, "No time left to prove this seat's PQ aggregates"); + } else { + warn!(%slot, position, "The PQ aggregate deadline passed with committees left to prove"); + } ethlambda_telemetry::pq_events::duty::missed_deadline(&duty_key, deadline_ns); for rem in group_iter { let rem_key = ethlambda_telemetry::pq_events::duty::committee_key( @@ -276,6 +276,10 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { rem.committee_index, position, ); + ethlambda_telemetry::pq_events::duty::details( + &rem_key, + serde_json::json!({ "available_signers": rem.signatures.len() }), + ); ethlambda_telemetry::pq_events::duty::missed_deadline(&rem_key, deadline_ns); } break; @@ -284,8 +288,21 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { let committee_started = Instant::now(); let result = prove_committee(&store, &state, group, duty_ref); let took_ms = committee_started.elapsed().as_millis() as u64; + let on_time = Instant::now() < deadline; + // Every proof made, late ones too: a late one is what the seat's + // window could not hold. + if let Ok((aggregate, proving, _)) = &result { + let proof = PqCommitteeProof { + proving: *proving, + ready_offset: Duration::from_millis(now_ms().saturating_sub(slot_start)), + signatures: aggregate.attesting_indices.len(), + proof_bytes: aggregate.proof.len(), + }; + metrics::observe_pq_committee_proof(position, &proof); + } match result { - Ok((aggregate, prove_ms, plan)) if Instant::now() < deadline => { + Ok((aggregate, proving, plan)) if on_time => { + let prove_ms = proving.as_millis() as u64; proved += 1; prove_ms_total += prove_ms; info!( @@ -312,7 +329,8 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { ethlambda_telemetry::pq_events::duty::remember_result(&aggregate.proof, op); } } - Ok((aggregate, prove_ms, plan)) => { + Ok((aggregate, proving, plan)) => { + let prove_ms = proving.as_millis() as u64; late += 1; prove_ms_total += prove_ms; if let Some(plan) = plan { @@ -334,6 +352,10 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { rem.committee_index, position, ); + ethlambda_telemetry::pq_events::duty::details( + &rem_key, + serde_json::json!({ "available_signers": rem.signatures.len() }), + ); ethlambda_telemetry::pq_events::duty::missed_deadline( &rem_key, deadline_ns, @@ -360,18 +382,32 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { } } } + let unproved = aggregates - already_proven - proved - failed - late; + let outcomes = [ + ("proved", proved), + ("late", late), + ("failed", failed), + ("already_proven", already_proven), + ("unproved", unproved), + ("no_inputs", no_inputs), + ]; + for (outcome, count) in outcomes { + metrics::inc_pq_committee_proofs(position, outcome, count as u64); + } // One line for the seat's whole proving pass: what leanVM was asked // for, what it cost, and what the budget left undone. info!( %slot, position, - committees, + committees = seated.len(), + aggregates, signatures, proved, already_proven, failed, late, - unproved = committees - already_proven - proved - failed - late, + unproved, + no_inputs, queued_ms, state_ms, prove_ms = prove_ms_total, @@ -388,8 +424,8 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { /// positions, signatures in committee order, which is the order /// `get_attestation_statements` lists their keys in. /// -/// Also returns how long the proof itself took, in milliseconds: the rest -/// of the call is reading the committee and assembling the statements. +/// Also returns how long the proof itself took: the rest of the call is +/// reading the committee and assembling the statements. fn prove_committee( store: &Store, state: &BeaconState, @@ -398,7 +434,7 @@ fn prove_committee( ) -> Result< ( Arc, - u64, + Duration, Option, ), String, @@ -461,7 +497,7 @@ fn prove_committee( &[signatures], ) .map_err(|err| err.to_string())?; - let prove_ms = proving.elapsed().as_millis() as u64; + let proving = proving.elapsed(); if let Some(ref p) = plan { p.set_claims(serde_json::json!({ "output_unique": sig_count })); } @@ -474,7 +510,7 @@ fn prove_committee( .try_into() .map_err(|_| "the proof exceeds MAX_STARK_PROOF_SIZE".to_string())?, }); - Ok((aggregate, prove_ms, plan)) + Ok((aggregate, proving, plan)) } fn now_ms() -> u64 { @@ -508,7 +544,307 @@ fn next_slot_to_seal(config: &Config, now_ms: u64) -> Slot { #[cfg(test)] mod tests { + use ethlambda_metrics::series_value; + use ethlambda_state_transition::beacon::helpers::pq::initialize_aggregation_committee_window; + use ethlambda_state_transition::beacon::helpers::test_state::with_validators_at; + use ethlambda_types::beacon::containers::shared::{AttestationData, Checkpoint}; + use ethlambda_types::beacon::primitives::Root; + use super::*; + use crate::test_utils::beacon_store_at; + + /// Held by every test that drives [`prove_seat`], so one proving pass + /// runs at a time. The metrics are the process's, and the proof size and + /// signature histograms carry no `position` label to tell two passes + /// apart: a test reading them while another's pass ran would count that + /// one's proofs as its own. + static PROVING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + + /// A seat's proving pass leaves its work on `/metrics`: the proof's + /// proving time, readiness, signatures and size under the seat's + /// position, and each committee it was due to prove under its outcome. + /// The next seat, with nothing new to prove, counts the committee as + /// already proven and times nothing. + #[tokio::test] + async fn a_seats_proving_pass_is_timed_and_counted() { + let _proving = PROVING.lock().await; + let mut state = with_validators_at(ForkName::Pq, 256); + // The builder leaves the aggregation committees empty; the fork + // upgrade fills them like this. + let window = initialize_aggregation_committee_window(&state).unwrap(); + let BeaconState::Pq(inner) = &mut state else { + unreachable!("built at PQ") + }; + inner.aggregation_committee_window = window; + let slot = state.slot(); + let epoch = compute_epoch_at_slot(slot); + let (store, _root) = beacon_store_at(state.clone()); + // A wall clock between 5 and 6 s into `slot`: before seat 0's + // broadcast at 7.2 s and seat 1's at 7.8 s, so both have time left. + let mut config = Config::mainnet(); + config.genesis_time = (now_ms() - 5_000 - slot * config.slot_duration_ms) / 1000; + + let committee = 0; + let aggregators = get_aggregation_committee(&state, slot, committee).unwrap(); + let members = store + .committee_cache() + .committees(&state, epoch) + .committee(slot, committee) + .unwrap() + .to_vec(); + let data = AttestationData { + slot, + index: 0, + beacon_block_root: Root::repeat_byte(1), + source: state.current_justified_checkpoint(), + target: Checkpoint { + epoch, + root: Root::repeat_byte(2), + }, + }; + { + let mut pool = store.pq_signature_pool(); + for &aggregator in aggregators.iter().take(2) { + assert!(pool.subscribe(slot, slot, committee, aggregator)); + } + for &attester_index in &members { + let attestation = pq::SingleAttestation { + committee_index: committee, + attester_index, + data, + signature: Default::default(), + }; + assert!(pool.insert(slot, &attestation)); + } + } + + let count = |outcome: &str, position: u64| { + let series = format!( + r#"lean_beacon_pq_committee_proofs_total{{outcome="{outcome}",position="{position}"}}"# + ); + series_value(&series).unwrap_or(0.0) + }; + let timed = |position: u64| { + let series = + format!(r#"lean_beacon_pq_committee_proof_seconds_count{{position="{position}"}}"#); + series_value(&series).unwrap_or(0.0) + }; + // Not labelled by position: read as what this pass adds. + let unlabelled = || { + [ + "lean_beacon_pq_committee_proof_signatures_sum", + "lean_beacon_pq_committee_proof_size_bytes_count", + ] + .map(|series| series_value(series).unwrap_or(0.0)) + }; + let [signatures_before, sized_before] = unlabelled(); + + prove_seat(&store, &config, slot, 0).await; + assert_eq!(store.pq_aggregate_pool().candidates(slot).len(), 1); + assert_eq!(count("proved", 0), 1.0); + for outcome in ["late", "failed", "already_proven", "unproved", "no_inputs"] { + assert_eq!(count(outcome, 0), 0.0, "{outcome}"); + } + assert_eq!(timed(0), 1.0); + let ready = series_value( + r#"lean_beacon_pq_committee_proof_ready_offset_seconds_sum{position="0"}"#, + ) + .unwrap(); + assert!((5.0..7.2).contains(&ready), "ready {ready} s into the slot"); + let [signatures, sized] = unlabelled(); + assert_eq!(signatures - signatures_before, members.len() as f64); + assert_eq!(sized - sized_before, 1.0); + + prove_seat(&store, &config, slot, 1).await; + assert_eq!(count("already_proven", 1), 1.0); + assert_eq!(count("proved", 1), 0.0); + assert_eq!(timed(1), 0.0); + assert_eq!(unlabelled(), [signatures, sized]); + } + + /// A seat reached after its broadcast deadline (for example after an + /// earlier seat's blocking proof overran) still accounts for every + /// committee it was due to prove on `/metrics`, separating committees an + /// earlier seat already proved from committees left `unproved`, without + /// starting leanVM. + #[tokio::test] + async fn a_seat_reached_after_its_deadline_counts_its_unproved_committees() { + use ethlambda_types::beacon::preset; + + let _proving = PROVING.lock().await; + let validators = 2 * preset::slots_per_epoch() * preset::target_committee_size(); + let mut state = with_validators_at(ForkName::Pq, validators as usize); + let window = initialize_aggregation_committee_window(&state).unwrap(); + let BeaconState::Pq(inner) = &mut state else { + unreachable!("built at PQ") + }; + inner.aggregation_committee_window = window; + let slot = state.slot(); + let epoch = compute_epoch_at_slot(slot); + let (store, _root) = beacon_store_at(state.clone()); + + // 10 s into a 12 s slot: past seat 2's broadcast deadline (8.4 s). + let position = 2; + let mut config = Config::mainnet(); + config.genesis_time = (now_ms() - 10_000 - slot * config.slot_duration_ms) / 1000; + + let data = AttestationData { + slot, + index: 0, + beacon_block_root: Root::repeat_byte(3), + source: state.current_justified_checkpoint(), + target: Checkpoint { + epoch, + root: Root::repeat_byte(4), + }, + }; + for committee in [0, 1] { + let aggregators = get_aggregation_committee(&state, slot, committee).unwrap(); + let seat_aggregator = aggregators[position as usize]; + let members = store + .committee_cache() + .committees(&state, epoch) + .committee(slot, committee) + .unwrap() + .to_vec(); + let mut pool = store.pq_signature_pool(); + assert!(pool.subscribe(slot, slot, committee, seat_aggregator)); + for &attester_index in members.iter().take(4) { + let attestation = pq::SingleAttestation { + committee_index: committee, + attester_index, + data, + signature: Default::default(), + }; + assert!(pool.insert(slot, &attestation)); + } + } + // Mark committee 0 as already proven by an earlier seat, leaving + // committee 1 unproved. + let group_0 = store + .pq_signature_pool() + .collected(slot, &[0]) + .into_iter() + .next() + .unwrap(); + let (proved_0, _, _) = prove_committee(&store, &state, group_0, None).unwrap(); + store.pq_signature_pool().insert_proven(proved_0); + + let count = |outcome: &str| { + let series = format!( + r#"lean_beacon_pq_committee_proofs_total{{outcome="{outcome}",position="{position}"}}"# + ); + series_value(&series).unwrap_or(0.0) + }; + let timed = || { + let series = + format!(r#"lean_beacon_pq_committee_proof_seconds_count{{position="{position}"}}"#); + series_value(&series).unwrap_or(0.0) + }; + let unproved_before = count("unproved"); + let already_proven_before = count("already_proven"); + let timed_before = timed(); + + prove_seat(&store, &config, slot, position).await; + + assert_eq!(count("unproved") - unproved_before, 1.0); + assert_eq!(count("already_proven") - already_proven_before, 1.0); + for outcome in ["proved", "late", "failed", "no_inputs"] { + assert_eq!(count(outcome), 0.0, "{outcome}"); + } + assert_eq!(timed() - timed_before, 0.0); + assert!(store.pq_aggregate_pool().candidates(slot).is_empty()); + } + + /// The counter's unit is the aggregate, one committee's signatures on + /// one vote: a committee whose attesters disagree is due one per vote, + /// and a committee that collected no signature, which has none to prove, + /// is still counted, once, as `no_inputs`. + #[tokio::test] + async fn a_split_committee_counts_per_vote_and_a_quiet_one_as_no_inputs() { + use ethlambda_types::beacon::preset; + + let _proving = PROVING.lock().await; + let validators = 2 * preset::slots_per_epoch() * preset::target_committee_size(); + let mut state = with_validators_at(ForkName::Pq, validators as usize); + let window = initialize_aggregation_committee_window(&state).unwrap(); + let BeaconState::Pq(inner) = &mut state else { + unreachable!("built at PQ") + }; + inner.aggregation_committee_window = window; + let slot = state.slot(); + let epoch = compute_epoch_at_slot(slot); + let (store, _root) = beacon_store_at(state.clone()); + + // 5 s into a 12 s slot: seat 3 broadcasts at 9.0 s, so it has time. + let position = 3; + let mut config = Config::mainnet(); + config.genesis_time = (now_ms() - 5_000 - slot * config.slot_duration_ms) / 1000; + + // Both committees are this seat's. Committee 0's attesters split + // over two heads; committee 1's are not heard from. + let (split, quiet) = (0, 1); + for committee in [split, quiet] { + let aggregators = get_aggregation_committee(&state, slot, committee).unwrap(); + let seat_aggregator = aggregators[position as usize]; + let mut pool = store.pq_signature_pool(); + assert!(pool.subscribe(slot, slot, committee, seat_aggregator)); + } + let members = store + .committee_cache() + .committees(&state, epoch) + .committee(slot, split) + .unwrap() + .to_vec(); + let (seeing, missing) = members.split_at(members.len() / 2); + for (head, attesters) in [(5, seeing), (6, missing)] { + let data = AttestationData { + slot, + index: 0, + beacon_block_root: Root::repeat_byte(head), + source: state.current_justified_checkpoint(), + target: Checkpoint { + epoch, + root: Root::repeat_byte(4), + }, + }; + for &attester_index in attesters { + let attestation = pq::SingleAttestation { + committee_index: split, + attester_index, + data, + signature: Default::default(), + }; + assert!(store.pq_signature_pool().insert(slot, &attestation)); + } + } + + let outcomes = [ + "proved", + "late", + "failed", + "already_proven", + "unproved", + "no_inputs", + ]; + let counts = || { + outcomes.map(|outcome| { + let series = format!( + r#"lean_beacon_pq_committee_proofs_total{{outcome="{outcome}",position="{position}"}}"# + ); + series_value(&series).unwrap_or(0.0) + }) + }; + let before = counts(); + + prove_seat(&store, &config, slot, position).await; + + let after = counts(); + let added: Vec = after.iter().zip(before).map(|(a, b)| a - b).collect(); + // Two aggregates proved for the split committee, one quiet committee. + assert_eq!(added, [2.0, 0.0, 0.0, 0.0, 0.0, 1.0], "{outcomes:?}"); + assert_eq!(store.pq_aggregate_pool().candidates(slot).len(), 2); + } #[test] fn each_seat_proves_between_its_cutoff_and_its_broadcast() { diff --git a/crates/net/rpc/src/metrics.rs b/crates/net/rpc/src/metrics.rs index 567ea19df..571065c3f 100644 --- a/crates/net/rpc/src/metrics.rs +++ b/crates/net/rpc/src/metrics.rs @@ -39,6 +39,110 @@ pub(crate) fn observe_builder_request(call: &str, outcome: &str, elapsed: Durati .observe(elapsed.as_secs_f64()); } +/// One PQ committee proof this node made for an aggregator seat. +pub(crate) struct PqCommitteeProof { + /// How long leanVM took, which includes any wait for a proof it was + /// already making: it makes one at a time. + pub proving: Duration, + /// How far into the proof's slot it was ready. + pub ready_offset: Duration, + pub signatures: usize, + pub proof_bytes: usize, +} + +/// Record a PQ committee proof made for the aggregator seat at `position`, +/// whether it was ready before that seat's broadcast time or not. +/// +/// The ready-offset bounds are a 12-second slot's seat cutoffs (4.8, 5.4, 6.0 +/// and 6.6 s) and broadcast times (7.2, 7.8, 8.4 and 9.0 s), with some +/// between and below for a shorter slot. +pub(crate) fn observe_pq_committee_proof(position: u64, proof: &PqCommitteeProof) { + static LEAN_BEACON_PQ_COMMITTEE_PROOF_SECONDS: LazyLock = LazyLock::new(|| { + register_histogram_vec!( + "lean_beacon_pq_committee_proof_seconds", + "Time leanVM took to prove one committee's PQ aggregate, by aggregator seat", + &["position"], + vec![ + 0.05, 0.1, 0.2, 0.3, 0.4, 0.6, 0.8, 1.0, 1.2, 1.6, 2.0, 2.4, 3.2, 4.8, 8.0 + ] + ) + .unwrap() + }); + static LEAN_BEACON_PQ_COMMITTEE_PROOF_READY_OFFSET_SECONDS: LazyLock = + LazyLock::new(|| { + register_histogram_vec!( + "lean_beacon_pq_committee_proof_ready_offset_seconds", + "How far into its slot a committee's PQ aggregate proof was ready, by aggregator seat", + &["position"], + vec![ + 1.0, 2.0, 2.4, 3.0, 3.6, 4.2, 4.8, 5.1, 5.4, 5.7, 6.0, 6.3, 6.6, 6.9, 7.2, 7.8, + 8.4, 9.0, 10.0, 12.0 + ] + ) + .unwrap() + }); + static LEAN_BEACON_PQ_COMMITTEE_PROOF_SIGNATURES: LazyLock = LazyLock::new(|| { + register_histogram!( + "lean_beacon_pq_committee_proof_signatures", + "Signatures one committee's PQ aggregate proof proves", + vec![ + 1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0, 128.0, 256.0, 512.0, 1024.0, 2048.0, 4096.0 + ] + ) + .unwrap() + }); + static LEAN_BEACON_PQ_COMMITTEE_PROOF_SIZE_BYTES: LazyLock = LazyLock::new(|| { + register_histogram!( + "lean_beacon_pq_committee_proof_size_bytes", + "Bytes size of one committee's PQ aggregate proof", + pq_proof_size_buckets() + ) + .unwrap() + }); + let position = position.to_string(); + LEAN_BEACON_PQ_COMMITTEE_PROOF_SECONDS + .with_label_values(&[&position]) + .observe(proof.proving.as_secs_f64()); + LEAN_BEACON_PQ_COMMITTEE_PROOF_READY_OFFSET_SECONDS + .with_label_values(&[&position]) + .observe(proof.ready_offset.as_secs_f64()); + LEAN_BEACON_PQ_COMMITTEE_PROOF_SIGNATURES.observe(proof.signatures as f64); + LEAN_BEACON_PQ_COMMITTEE_PROOF_SIZE_BYTES.observe(proof.proof_bytes as f64); +} + +/// Bounds for a committee proof's size, up to `MAX_STARK_PROOF_SIZE` (1 MiB): +/// 32 KiB apart where committee proofs fall, 160 to 200 KB. +fn pq_proof_size_buckets() -> Vec { + vec![ + 131072.0, 163840.0, 196608.0, 229376.0, 262144.0, 327680.0, 393216.0, 524288.0, 786432.0, + 1048576.0, + ] +} + +/// Count `count` committee aggregates the aggregator seat at `position` was +/// due to prove, by what became of them: `proved` before the seat's broadcast +/// time, `late` (proved after it, and not used), `failed`, `already_proven` +/// (an earlier seat of this node proved every signature collected) or +/// `unproved` (the seat's time ran out first). +/// +/// An aggregate is one committee's signatures on one vote, which is what a +/// proof covers: a committee whose attesters disagree within the slot is due +/// one per vote. A committee that collected no signature has none, and is +/// counted once as `no_inputs`, so every committee of the seat leaves a trace. +pub(crate) fn inc_pq_committee_proofs(position: u64, outcome: &str, count: u64) { + static LEAN_BEACON_PQ_COMMITTEE_PROOFS_TOTAL: LazyLock = LazyLock::new(|| { + register_int_counter_vec!( + "lean_beacon_pq_committee_proofs_total", + "Committee aggregates an aggregator seat of this node was due to prove (one per vote a committee collected signatures for, and one for a committee that collected none), by seat and outcome", + &["position", "outcome"] + ) + .unwrap() + }); + LEAN_BEACON_PQ_COMMITTEE_PROOFS_TOTAL + .with_label_values(&[&position.to_string(), outcome]) + .inc_by(count); +} + pub fn start_prometheus_metrics_api() -> Router { Router::new() .route("/metrics", get(get_metrics)) diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index 0536e9424..e0ad1d29f 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -189,6 +189,10 @@ proofs through one of two backends, chosen once per process: 12-second slot. On 14 cores of an Apple M4 Max, a `release-fast` build proves 128 signatures in about 0.28 s and 512 in about 0.86 s; verifying takes about 6 ms either way, and the proofs are 160 to 200 KB. +- **What it costs on a running node.** The node's `/metrics` times every + committee proof, block-proof merge and proof verification, and when in the + slot attestations and aggregates arrive: see + [metrics.md](./metrics.md#pq-aggregation-timing). pq-devnet-0 ran the prover as a separate `leanvm-sidecar` (bindings v0.15.0), which the image built and its `ethlambda-pq` supervisor started and diff --git a/docs/metrics.md b/docs/metrics.md index 3eeb71579..e8b06c9c8 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -913,6 +913,88 @@ When `ethlambda beacon` or `ethlambda validator` is started with `--telemetry-ev | `pq_measurement_export_rejected_total` | Counter | Record submissions rejected in valid OTLP `partial_success` responses | `event` | | `pq_measurement_export_warnings_total` | Counter | OTLP export requests acknowledged with a `partial_success` warning message and zero rejected records | | +### PQ Aggregation Timing + +On a network that schedules the PQ fork, `ethlambda beacon` proves its +aggregators' committees with leanVM, merges the proofs a block packs into one, +and verifies the proofs other nodes made (see +[beacon_pq.md](./beacon_pq.md#validator-duties)). These time each of those, and +when in the slot votes reach the node. They are ethlambda-specific, appear only +once the node has done the work they measure, and lean nodes never emit them. + +| Name | Type | Usage | Sample collection event | Labels | Buckets | +|------|------|-------|-------------------------|--------|---------| +| `lean_beacon_pq_committee_proof_seconds` | Histogram | Time leanVM took to prove one committee's aggregate | On each committee proof an aggregator seat of this node made, late ones included | position=0..3 | 0.05, 0.1, 0.2, 0.3, 0.4, 0.6, 0.8, 1, 1.2, 1.6, 2, 2.4, 3.2, 4.8, 8 | +| `lean_beacon_pq_committee_proof_ready_offset_seconds` | Histogram | How far into its slot the proof was ready | Same | position=0..3 | 1, 2, 2.4, 3, 3.6, 4.2, 4.8, 5.1, 5.4, 5.7, 6, 6.3, 6.6, 6.9, 7.2, 7.8, 8.4, 9, 10, 12 | +| `lean_beacon_pq_committee_proof_signatures` | Histogram | Signatures the proof proves | Same | | 1, 2, 4, … 4096 (powers of two) | +| `lean_beacon_pq_committee_proof_size_bytes` | Histogram | Bytes size of the proof | Same | | 131072, 163840, 196608, 229376, 262144, 327680, 393216, 524288, 786432, 1048576 | +| `lean_beacon_pq_committee_proofs_total` | Counter | Committee aggregates an aggregator seat of this node was due to prove, by what became of them | Once per seat, when its proving pass ends | position=0..3, outcome=proved,late,failed,already_proven,unproved,no_inputs | | +| `lean_beacon_pq_merge_seconds` | Histogram | Time leanVM took to merge a block's attestation proofs into one | When a merge ends, in time or not | phase=ahead,production | 0.1, 0.2, 0.4, 0.6, 0.8, 1, 1.5, 2, 3, 4, 6, 8, 12 | +| `lean_beacon_pq_merge_children` | Histogram | Child proofs the merge folded | Same | | 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64 | +| `lean_beacon_pq_merged_proof_size_bytes` | Histogram | Bytes size of the merged proof | When a merge ends with a proof | | 131072, 163840, 196608, 229376, 262144, 327680, 393216, 524288, 786432, 1048576 | +| `lean_beacon_pq_merges_total` | Counter | Packings with several proofs to merge, by what became of the merge | Once per such packing | phase=ahead,production, outcome=merged,failed,late,skipped | | +| `lean_beacon_pq_proof_verification_seconds` | Histogram | Time to verify one attestation proof | On each aggregate that reached the proof check, and each block with attestations whose transition ran | kind=aggregate,block | 0.001, 0.0025, 0.005, 0.0075, 0.01, 0.015, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2 | +| `lean_beacon_pq_gossip_arrival_offset_seconds` | Histogram | How far into its vote's slot an attestation or aggregate arrived on gossip | On each one gossip validation accepted | kind=beacon_attestation,beacon_aggregate_and_proof | 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 4.8, 6, 7.2, 7.5, 7.8, 8.1, 8.4, 8.7, 9, 9.5, 10, 12, 24 | + +**Committee proofs.** `position` is the aggregator's seat in its committee's +aggregation committee. Seat `p` stops collecting at 40% + `p` × 5% of the slot +and broadcasts at 60% + `p` × 5%, so each has a fifth of a slot to prove in: +2.4 s of a 12-second slot, which is where the bucket bounds of the two offset +histograms come from (cutoffs at 4.8, 5.4, 6.0 and 6.6 s, broadcasts at 7.2, +7.8, 8.4 and 9.0 s). Read `committee_proof_seconds` against that window and +`ready_offset` against the seat's broadcast time. The proving time includes +any wait for a proof leanVM was already making, since it makes one at a time: +a block-proof merge running at a seat's cutoff shows up here. + +`committee_proofs_total` is the ledger. Its unit is the aggregate: one +committee's signatures on one vote, which is what one proof covers. A +committee whose attesters all vote alike is due one; one whose attesters +disagree within the slot (some saw the block, some did not) is due one per +vote, each proved on its own, so the outcomes of a seat can add up to more than +its committees. `proved` plus `late` is the sample count of +`committee_proof_seconds`. `late` is a proof finished after its seat's +broadcast time, which is discarded; `unproved` is an aggregate the seat ran out +of time before starting; `already_proven` is one an earlier seat of this node +proved in full, which is the staggered design working and not a miss; +`no_inputs` is a committee that had collected no signature at the seat's +cutoff, counted once, so there was nothing to prove. `late` or `unproved` +climbing means the host's prover does not keep up with its committees: +`ethlambda pq-prover-check` measures the same proof offline. `no_inputs` +climbing means the committee's attestations are not reaching this node by the +cutoff (the attestation subnet, or the attesters themselves), which no prover +speed fixes. + +**Merges.** `phase` is `ahead` for the packing the chain actor starts a third +of a slot before this node's proposal, and `production` for one block +production runs itself when that result cannot be used. A packing with one +proof has nothing to merge and counts nowhere here. Every outcome but `merged` +means the block packed one committee's attestation in place of everything +selected: `skipped` is no time left or another merge holding leanVM, `late` a +merge that outlived its budget (its duration is still observed when it ends), +`failed` a leanVM error. + +**Verification.** `aggregate` is one committee's proof, from gossip or from +this node's validator client through the Beacon API, which runs the same +rules; a proof that does not verify is observed too, and a gossip one is +counted by `lean_beacon_gossip_validation_total{reason="aggregate_proof"}`. +`block` is a block's merged proof in `process_stark`: at import, and when the +node computes the state root of a block it produces. A block without +attestations is not a sample. + +**Arrival.** Measured from the start of the vote's own slot, at the instant +gossipsub delivered the message (not the later one of its verdict), so an +aggregate that arrives a slot late reads over 12 s. It covers the attestations +and aggregates gossip validation accepted, and only those: the slot is the one +the message names, so a message that was merely decoded could claim any slot +and write any sample, at no cost to the peer sending it. An accepted vote is +in the current or the previous epoch, signed by its validator and the first for +its key. What is left out is therefore every vote ignored or rejected: a +duplicate, an aggregate whose attesters an earlier one already covered, a vote +whose block never imported, and all of them while the node is syncing. None of +this node's own are samples either: gossip never hands a node its messages +back. The time from arrival to verdict is +`lean_beacon_gossip_validation_seconds`, under the same `kind` values. + --- ✅(*) **Partial support**: These metrics are implemented but not collected "on scrape" as the spec requires. They are updated on specific events (e.g., on tick, on block processing) rather than being computed fresh on each Prometheus scrape.