diff --git a/crates/validator/src/attestation.rs b/crates/validator/src/attestation.rs index 9a8c58b23..39f59b89f 100644 --- a/crates/validator/src/attestation.rs +++ b/crates/validator/src/attestation.rs @@ -17,6 +17,7 @@ use crate::error::Result; use crate::keys::ValidatorStore; use crate::signing::{SigningContext, sign_all}; use crate::slashing_protection::SharedProtection; +use crate::slot_clock::SlotClock; /// What one slot's attestation duty produced. /// @@ -55,6 +56,9 @@ pub struct AttestationService { /// What every validator has signed, shared with the proposal service and /// the keymanager. See [`crate::slashing_protection`]. protection: SharedProtection, + /// The slot clock each accepted vote's delay is measured from, when the + /// client gave one (see [`Self::with_clock`]). + clock: Option, } impl AttestationService { @@ -67,15 +71,25 @@ impl AttestationService { beacon_node, context, protection, + clock: None, } } + /// Measure each accepted vote's delay from the start of its slot + /// (`ethlambda_validator_attestation_vote_delay_seconds`). + pub fn with_clock(mut self, clock: SlotClock) -> Self { + self.clock = Some(clock); + self + } + /// Sign and publish every duty held for `slot`. /// /// One `attestation_data` fetch is shared by every validator attesting at /// this slot, and every signature goes out in one submission: the data does /// not depend on the validator, and the beacon node's pool endpoint takes a - /// list. + /// list. From PQ the votes go out in several submissions instead, each as + /// soon as it is signed, since a leanXMSS signature is far too slow to hold + /// the batch for (see `publish_pq_as_signed`). /// /// Returns how many attestations were published, and the data they were /// signed over, which this slot's aggregation duty needs. @@ -269,6 +283,23 @@ impl AttestationService { to_sign.push((duty, pubkey)); } + // From PQ a leanXMSS signature at the target epoch's leaf, over the + // same signing root: the slashing protection record above already + // guards that leaf (one per target epoch). Those keys are derived from + // local keystores at startup and sign here, with no round trip, in + // parallel off this task, and each vote goes out as soon as it is + // signed rather than with the batch (see `publish_pq_as_signed`). + if is_pq { + let published = self + .publish_pq_as_signed(slot, &to_sign, &data, &data_dto, fork_name) + .await?; + return Ok(Attested { + published, + refused, + data: Some(data), + }); + } + // Signed concurrently rather than one after another. A local key // signs in microseconds either way; a remote signer costs a round // trip per signature, and a hundred validators behind one signer @@ -287,35 +318,9 @@ impl AttestationService { // a signer hangs every vote in it, a local key's too, is published // the full budget after the attestation offset (see // `SIGNING_BUDGET` for what that leaves before aggregation). - // - // From PQ a leanXMSS signature at the target epoch's leaf, over the - // same signing root: the slashing protection record above already - // guards that leaf (one per target epoch). Those keys are derived from - // local keystores at startup, so they sign here, with no round trip, - // in parallel off this task (`pq::sign_all`). - let signatures: Vec> = { - let _timing = crate::metrics::time_signing(); - if is_pq { - let root = self.context.attestation_signing_root(&data); - let leaf = crate::pq::attestation_leaf(data.target.epoch); - let requests = to_sign - .iter() - .map(|(_, pubkey)| crate::pq::SignRequest { - pubkey: *pubkey, - leaf, - root, - }) - .collect(); - crate::pq::sign_all(requests) - .await - .into_iter() - .map(|signature| { - signature - .map(|signature| encode_hex(&signature.0)) - .map_err(|err| err.to_string()) - }) - .collect() - } else { + let signatures: Vec> = + { + let _timing = crate::metrics::time_signing(); sign_all(to_sign.iter().map(|(_, pubkey)| { (*pubkey, self.context.sign_attestation(store, pubkey, &data)) })) @@ -327,8 +332,7 @@ impl AttestationService { .map_err(|err| err.to_string()) }) .collect() - } - }; + }; let mut attestations = Vec::with_capacity(to_sign.len()); for ((duty, _), signature) in to_sign.iter().zip(signatures) { @@ -372,12 +376,135 @@ impl AttestationService { } info!(%slot, count = published, "Published attestations"); crate::metrics::inc_attestations_published(published as u64); + self.observe_vote_delays(slot, published); Ok(Attested { published, refused, data: Some(data), }) } + + /// Signs `to_sign`'s PQ votes over `data` and submits each as soon as it + /// is signed, rather than the batch once its slowest signature is done. + /// Returns how many the beacon node accepted. + /// + /// A leanXMSS signature costs about 0.3 s of a core and varies several + /// fold from one to the next (see `pq::sign_batch`), so twenty of them + /// keep a host's cores busy for a second or more. Published whole, every + /// vote waited for the slowest; published as signed, the median vote goes + /// out about halfway through, as other clients' do. + /// + /// A submission carries whatever was signed by the time the previous one + /// answered: the first vote alone, then the ones that came in meanwhile, + /// so a slow node costs fewer, larger requests rather than a queue of + /// small ones. A failed submission costs its own votes only; the slot's + /// error is returned only when none was accepted at all. + async fn publish_pq_as_signed( + &self, + slot: Slot, + to_sign: &[(&AttesterDutyDto, BlsPubkey)], + data: &AttestationData, + data_dto: &AttestationDataOutDto, + fork_name: &str, + ) -> Result { + let root = self.context.attestation_signing_root(data); + let leaf = crate::pq::attestation_leaf(data.target.epoch); + let requests = to_sign + .iter() + .map(|(_, pubkey)| crate::pq::SignRequest { + pubkey: *pubkey, + leaf, + root, + }) + .collect(); + // Until the last signature exists, not the last submission, so the + // histogram still reads as the time the duty's signing took. + let mut timing = Some(crate::metrics::time_signing()); + let mut signed = crate::pq::sign_streamed(requests); + + let mut ready = Vec::with_capacity(to_sign.len()); + let mut answered = 0; + let mut published = 0; + let mut failure = None; + while signed.recv_many(&mut ready, to_sign.len()).await > 0 { + answered += ready.len(); + if answered >= to_sign.len() { + timing.take(); + } + let mut attestations = Vec::with_capacity(ready.len()); + for (position, signature) in ready.drain(..) { + let (duty, _) = &to_sign[position]; + match signature { + Ok(signature) => attestations.push(SingleAttestationDto { + committee_index: duty.committee_index, + attester_index: duty.validator_index, + data: data_dto.clone(), + signature: encode_hex(&signature.0), + }), + // One validator failing must not cost the others their + // attestation. + Err(err) => { + error!(%slot, validator = duty.validator_index, %err, "Failed to sign attestation"); + crate::metrics::inc_signing_failures(); + } + } + } + if attestations.is_empty() { + continue; + } + + let submitted = attestations.len(); + let pending = to_sign.len() - answered; + match self + .beacon_node + .submit_attestations(&attestations, fork_name) + .await + { + Ok(accepted) => { + if accepted < submitted { + warn!( + %slot, + published = accepted, + submitted, + "Some attestations in this slot's batch were rejected by the beacon node" + ); + } + info!(%slot, count = accepted, pending, "Published attestations"); + crate::metrics::inc_attestations_published(accepted as u64); + self.observe_vote_delays(slot, accepted); + published += accepted; + } + Err(err) => { + warn!(%slot, count = submitted, pending, %err, "Failed to submit some of this slot's attestations"); + failure = Some(err); + } + } + } + + if answered < to_sign.len() { + let missing = to_sign.len() - answered; + error!(%slot, missing, "The PQ signing task stopped before every attestation was signed"); + for _ in 0..missing { + crate::metrics::inc_signing_failures(); + } + } + match failure { + Some(err) if published == 0 => Err(err), + _ => Ok(published), + } + } + + /// One delay observation per vote the node accepted just now, from the + /// start of `slot`, when the service has a clock. + fn observe_vote_delays(&self, slot: Slot, votes: usize) { + let Some(clock) = &self.clock else { + return; + }; + let elapsed = std::time::SystemTime::now() + .duration_since(clock.start_of(slot)) + .unwrap_or_default(); + crate::metrics::observe_vote_publication_delay(elapsed.as_secs_f64(), votes); + } } #[cfg(test)] @@ -617,6 +744,7 @@ mod tests { beacon_node: node_again.clone(), context: context(), protection: service.protection, + clock: None, }; let second = service .attest(101, &[duty(&pubkey_hex, 1337, 101, 3)], &store) diff --git a/crates/validator/src/lib.rs b/crates/validator/src/lib.rs index b520727a1..fd893d88e 100644 --- a/crates/validator/src/lib.rs +++ b/crates/validator/src/lib.rs @@ -507,7 +507,8 @@ pub async fn run(config: ValidatorConfig, stop: impl Future = LazyLock static PUBLICATION_DELAY_SECONDS: LazyLock = LazyLock::new(|| { register_histogram!( "ethlambda_validator_publication_delay_seconds", - "Time from slot start to this slot's attestations being accepted by a beacon node", + "Time from slot start to this slot's attestations being accepted by a beacon node (the last of them, from PQ on)", + vec![0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 6.0, 8.0, 12.0] + ) + .unwrap() +}); + +/// One observation per vote, where [`PUBLICATION_DELAY_SECONDS`] has one per +/// slot. The two differ from PQ on, where a slot's votes go out over a second +/// or more as each is signed: this one's median is the slot's median vote, +/// the number block explorers compare clients by. +static VOTE_PUBLICATION_DELAY_SECONDS: LazyLock = LazyLock::new(|| { + register_histogram!( + "ethlambda_validator_attestation_vote_delay_seconds", + "Time from slot start to each attestation being accepted by a beacon node, one observation per vote", vec![0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 6.0, 8.0, 12.0] ) .unwrap() @@ -524,6 +537,7 @@ pub fn init() { LazyLock::force(&SIGNING_DURATION_SECONDS); LazyLock::force(&REMOTE_SIGNER_REQUEST_DURATION_SECONDS); LazyLock::force(&PUBLICATION_DELAY_SECONDS); + LazyLock::force(&VOTE_PUBLICATION_DELAY_SECONDS); LazyLock::force(&SLASHING_PROTECTION_WRITE_SECONDS); LazyLock::force(&SLASHING_PROTECTION_WRITE_FAILURES_TOTAL); // A labelled series exists only once a label pair is touched. @@ -730,11 +744,19 @@ impl Drop for OpenEventStream { } } -/// Record how long after a slot's start its attestations were accepted. +/// Record how long after a slot's start its attestations were accepted: the +/// last of them, from PQ on, where they go out as they are signed. pub fn observe_publication_delay(seconds: f64) { PUBLICATION_DELAY_SECONDS.observe(seconds); } +/// Record `votes` attestations accepted `seconds` after their slot started. +pub fn observe_vote_publication_delay(seconds: f64, votes: usize) { + for _ in 0..votes { + VOTE_PUBLICATION_DELAY_SECONDS.observe(seconds); + } +} + /// A Prometheus endpoint for this process. /// /// Deliberately not `ethlambda-rpc`'s router: reaching that would put the diff --git a/crates/validator/src/pq.rs b/crates/validator/src/pq.rs index 7d0b1ca52..195e29bd0 100644 --- a/crates/validator/src/pq.rs +++ b/crates/validator/src/pq.rs @@ -954,13 +954,70 @@ pub struct SignRequest { /// Every leaf the batch spends is recorded with one write and one flush /// before any of its signatures exists, then the keys sign in parallel on /// rayon's global pool (leanVM signs on one thread, and different keys share -/// nothing). One signature recomputes a `2^8`-leaf subtree of its bottom -/// tree, a 256th of building the tree: roughly 10 ms on a core. +/// nothing). +/// +/// # What a signature costs +/// +/// About 0.3 s of one core on the devnet's 8-vCPU hosts, and it varies a lot +/// from one signature to the next. Most of it is not the Merkle path (a +/// `2^8`-leaf subtree, a 256th of building the bottom tree): leanVM grinds the +/// one-time signature's randomizer until the message digest is a codeword, +/// which takes about a million Keccak permutations on average (a digest is a +/// codeword with probability `2^-12` times that of 58 two-bit digits summing +/// to 106, about `9.5e-7`). The number of trials is geometric, so one +/// signature in ten takes more than 2.3 times the mean and one in a hundred +/// more than 4.6 times. A batch is as slow as its slowest signature: a duty +/// whose messages are due early hands them on one by one with [`sign_each`] +/// rather than waiting for this. /// /// Blocking, for the batch's slowest signature: [`sign_all`] runs it off /// the async runtime. pub fn sign_batch(requests: &[SignRequest]) -> Vec> { use rayon::prelude::*; + let checked = claim_batch(requests); + requests + .par_iter() + .zip(checked) + .map(|(request, checked)| { + let (key, leaf_index) = checked?; + Ok(sign_claimed(request, &key, leaf_index)) + }) + .collect() +} + +/// [`sign_batch`], handing each signature to `signed` as soon as it exists, +/// with its request's position, rather than all of them once the slowest is +/// done. Every request is answered exactly once, a refused one before any +/// signature. Leaves are recorded as [`sign_batch`] records them: all of the +/// batch's with one flush, before any signature exists. +/// +/// Blocking, until the last signature: [`sign_streamed`] runs it off the +/// async runtime. +pub fn sign_each( + requests: &[SignRequest], + signed: impl Fn(usize, Result) + Sync, +) { + use rayon::prelude::*; + let mut signable = Vec::with_capacity(requests.len()); + for (position, checked) in claim_batch(requests).into_iter().enumerate() { + match checked { + Ok(claimed) => signable.push((position, claimed)), + Err(err) => signed(position, Err(err)), + } + } + signable + .into_par_iter() + .for_each(|(position, (key, leaf_index))| { + let signature = sign_claimed(&requests[position], &key, leaf_index); + signed(position, Ok(signature)); + }); +} + +/// Each request's key and leaf index once its leaf is recorded, or why it +/// cannot be signed: an unknown key, a leaf out of range, or one already +/// spent on another root. All the batch's leaves are recorded with one write +/// and one flush. +fn claim_batch(requests: &[SignRequest]) -> Vec, u32), PqSignError>> { let mut checked: Vec, u32), PqSignError>> = requests .iter() .map(|request| { @@ -987,14 +1044,29 @@ pub fn sign_batch(requests: &[SignRequest]) -> Vec); + +/// [`sign_each`] on tokio's blocking pool, started at once: each answer comes +/// out of the receiver as soon as it exists. The channel closes after the +/// last one, or early if the signing task dies, in which case the requests +/// that never answered have no signature. +pub fn sign_streamed(requests: Vec) -> tokio::sync::mpsc::UnboundedReceiver { + let (sender, receiver) = tokio::sync::mpsc::unbounded_channel(); + if !requests.is_empty() { + tokio::task::spawn_blocking(move || { + sign_each(&requests, |position, signature| { + // A receiver gone means the duty was abandoned; the leaf is + // spent either way. + let _ = sender.send((position, signature)); + }); + }); + } + receiver } /// [`sign_batch`] on tokio's blocking pool, so neither the flush nor the @@ -1167,6 +1239,68 @@ mod tests { ); } + /// Signing one by one answers every request exactly once, at its + /// position, with what the batch would have given: the refusals as + /// refusals, and the same bytes for each signature. + #[test] + fn signing_one_by_one_answers_each_request_once_in_its_place() { + let pubkey = BlsPubkey([25; 48]); + let unknown = BlsPubkey([26; 48]); + derive_and_register(pubkey, &[25; 32], 0, None); + let spent = slot_leaf(1, LEAF_OFFSET_PTC_ATTESTER); + let free = slot_leaf(2, LEAF_OFFSET_PTC_ATTESTER); + let other = slot_leaf(3, LEAF_OFFSET_AGGREGATE_AND_PROOF); + sign_now(&pubkey, spent, Root::from([1; 32])).unwrap(); + + let requests = [ + request(pubkey, free, 1), + request(pubkey, spent, 2), + request(unknown, free, 1), + request(pubkey, other, 3), + ]; + let answers = Mutex::new(Vec::new()); + sign_each(&requests, |position, signature| { + answers.lock().unwrap().push((position, signature)); + }); + let mut answers = answers.into_inner().unwrap(); + answers.sort_by_key(|(position, _)| *position); + let positions: Vec = answers.iter().map(|(position, _)| *position).collect(); + assert_eq!(positions, vec![0, 1, 2, 3]); + assert!(matches!(answers[1].1, Err(PqSignError::LeafUsed(_)))); + assert!(matches!(answers[2].1, Err(PqSignError::UnknownValidator))); + + // Signing is deterministic, so the batch path re-signs the same + // leaves for the same roots and must give the same bytes. + let again = sign_batch(&[requests[0], requests[3]]); + for (answer, batch) in [(&answers[0].1, &again[0]), (&answers[3].1, &again[1])] { + assert_eq!( + answer.as_ref().unwrap().0.to_vec(), + batch.as_ref().unwrap().0.to_vec() + ); + } + } + + /// The async wrapper starts signing at once and closes its channel after + /// the last answer. + #[tokio::test] + async fn a_streamed_batch_answers_every_request_and_then_closes() { + let pubkey = BlsPubkey([27; 48]); + derive_and_register(pubkey, &[27; 32], 0, None); + let requests = vec![ + request(pubkey, slot_leaf(4, LEAF_OFFSET_PTC_ATTESTER), 1), + request(pubkey, slot_leaf(5, LEAF_OFFSET_PTC_ATTESTER), 2), + ]; + let mut signed = sign_streamed(requests); + let mut positions = Vec::new(); + while let Some((position, signature)) = signed.recv().await { + assert!(signature.is_ok()); + positions.push(position); + } + positions.sort_unstable(); + assert_eq!(positions, vec![0, 1]); + assert!(sign_streamed(Vec::new()).recv().await.is_none()); + } + /// A batch cannot spend one leaf on two roots, and what it claims is /// written once and found again after a restart. #[test] diff --git a/docs/metrics.md b/docs/metrics.md index e5ae3164c..545485d76 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -948,7 +948,8 @@ and absent is not the same as zero. | `ethlambda_validator_remote_signer_request_duration_seconds` | Histogram | Time one signing request to a remote signer took, from sending it to its answer or failure, not counting the wait for one of the signer's 64 request slots. The number to watch for a slow signer; empty when every key is local | | `ethlambda_validator_slashing_protection_write_seconds` | Histogram | Time to durably write the slashing-protection record, once per slot's attestation batch and once per block, before signing. Milliseconds on a local disk; worth an alert above about a second, since the duty waits for it and a write held past 3 s is refused | | `ethlambda_validator_slashing_protection_write_failures_total` | Counter | Slashing-protection writes that failed, each leaving its messages unsigned. Should read zero; anything else points at the disk under `--validators-dir` | -| `ethlambda_validator_publication_delay_seconds` | Histogram | Slot start to attestations accepted. The headline health number: it should sit shortly after the slot's block arrives, and no later than just past the one-third-slot duty offset, where it sits for a slot whose block came late or not at all, or with `--disable-event-stream` | +| `ethlambda_validator_publication_delay_seconds` | Histogram | Slot start to attestations accepted. The headline health number: it should sit shortly after the slot's block arrives, and no later than just past the one-third-slot duty offset, where it sits for a slot whose block came late or not at all, or with `--disable-event-stream`. From PQ, where a slot's votes go out as each is signed, it is the last vote's | +| `ethlambda_validator_attestation_vote_delay_seconds` | Histogram | Slot start to each attestation accepted, one observation per vote. Before PQ every vote of a slot goes out together, so it matches `publication_delay_seconds` weighted by votes. From PQ a leanXMSS signature costs about 0.3 s of a core and votes go out as they are signed, spread over a second or more, and this one's median is the median vote's, the number Dora's attester view compares clients by | | `ethlambda_validator_duty_triggers_total` | Counter | What started each slot's duty, once per duty per slot. `duty`: `attestation`, `sync_committee_message`, `payload_attestation`. `trigger`: `event` (a beacon node's `head` for the slot, or its `execution_payload_available` for the vote, borne out by the node's answer), `deadline` (no event for the slot before the offset: every slot with `--disable-event-stream` or the streams down) or `mismatch` (an event the node's answer did not bear out, or had not answered by the offset, so the duty waited for its offset after all). A steady `mismatch` share points at beacon nodes that disagree with each other, or payloads announced and not seen present | | `ethlambda_validator_event_streams_open` | Gauge | Beacon node event streams open: one per node for `head`, and one more per node for `execution_payload_available` on a network that schedules gloas. A stream missing from that count costs its node's early starts, not a duty |