diff --git a/bin/ethlambda/src/main.rs b/bin/ethlambda/src/main.rs index e06d7671e..9c70b382a 100644 --- a/bin/ethlambda/src/main.rs +++ b/bin/ethlambda/src/main.rs @@ -933,6 +933,9 @@ async fn run_node(options: Options) -> eyre::Result<()> { // block production collects. let prepared_payloads = ethlambda_blockchain::PreparedPayloads::default(); let rpc_prepared_payloads = prepared_payloads.clone(); + // And the attestations of the next PQ block, packed alongside its build. + let prepared_pq_attestations = ethlambda_blockchain::PreparedPqAttestations::default(); + let rpc_prepared_pq_attestations = prepared_pq_attestations.clone(); let rpc_p2p = p2p.actor_ref().to_rpc_to_p2p_ref(); let rpc_custody_columns = match &setup.chain { ChainActor::Beacon { @@ -979,6 +982,7 @@ async fn run_node(options: Options) -> eyre::Result<()> { sync_committee_pool: sync_committee_pool.clone(), fee_recipients: rpc_fee_recipients, prepared_payloads: rpc_prepared_payloads, + prepared_pq_attestations: rpc_prepared_pq_attestations, custody_columns: rpc_custody_columns, engine: rpc_engine, events: rpc_events, @@ -1034,6 +1038,7 @@ async fn run_node(options: Options) -> eyre::Result<()> { builder_market, always_prepare: always_prepare_payload, prepared_payloads, + prepared_pq_attestations, }, ) } diff --git a/crates/blockchain/src/lib.rs b/crates/blockchain/src/lib.rs index 1246fbc02..c5779c60b 100644 --- a/crates/blockchain/src/lib.rs +++ b/crates/blockchain/src/lib.rs @@ -60,6 +60,7 @@ use crate::store::StoreError; pub use events::{ChainEvent, EventBus, Topic, UnknownTopic}; pub use payload_attributes::{FeeRecipients, PayloadPreparation, PreparedPayloads}; +pub use pq_attestation_packing::PreparedPqAttestations; pub mod aggregation; mod beacon_aggregates; @@ -79,6 +80,7 @@ pub mod import_timing; pub mod key_manager; pub mod metrics; pub mod payload_attributes; +pub mod pq_attestation_packing; pub mod reaggregate; pub mod spec_test_runner; pub mod store; diff --git a/crates/blockchain/src/payload_attributes.rs b/crates/blockchain/src/payload_attributes.rs index 807bfba97..c8a10af2f 100644 --- a/crates/blockchain/src/payload_attributes.rs +++ b/crates/blockchain/src/payload_attributes.rs @@ -110,6 +110,10 @@ pub struct PayloadPreparation { /// The payload builds the actor started ahead of their slots, shared /// with block production. pub prepared_payloads: PreparedPayloads, + /// The attestations of the next PQ block, packed and merged ahead of its + /// slot alongside its payload build, shared with block production. See + /// [`crate::pq_attestation_packing`]. + pub prepared_pq_attestations: crate::pq_attestation_packing::PreparedPqAttestations, } /// Payload builds started ahead of their slot, by the payload id the @@ -1022,6 +1026,22 @@ impl BlockChainServer { let prepared = preparation.prepared_payloads.clone(); let custody = CustodyColumns::from_indices(self.custody_columns.iter().copied()); tokio::spawn(start_build(engine, prepared, custody, key, build)); + + // A PQ block's attestation proofs are merged now too, rather than at + // the slot: everything the merge reads is already here (see + // `pq_attestation_packing`). Only for a proposer a validator client + // registered here, not for every slot `--always-prepare-payload` + // builds for: a merge is ~0.6 s of the prover nobody would collect. + let proposal_epoch = compute_epoch_at_slot(key.proposal_slot); + if self.store.config().fork_at_epoch(proposal_epoch) == ForkName::Pq + && key.fee_recipient.is_some() + { + preparation.prepared_pq_attestations.start( + self.store.clone(), + key.head_root, + key.proposal_slot, + ); + } } } diff --git a/crates/blockchain/src/pq_attestation_packing.rs b/crates/blockchain/src/pq_attestation_packing.rs new file mode 100644 index 000000000..32e5d7e92 --- /dev/null +++ b/crates/blockchain/src/pq_attestation_packing.rs @@ -0,0 +1,718 @@ +//! The attestations a PQ block packs and their proofs merged into the block's +//! one `proof`, prepared ahead of the slot when this node proposes it. +//! +//! # Why ahead of the slot +//! +//! The merge folds the selected aggregates' proofs into one on the proving +//! sidecar: about 0.6 s for two children on pq-devnet-0. Block production used +//! to run it when the validator client asked for the block, at the slot's +//! start, so every block this node proposed waited for it. Its blocks reached +//! the network at about 1.0 to 1.2 s, against 0.15 to 0.4 s for Prysm's, +//! Teku's, Lighthouse's and Silver's, which carry the same merged proof. +//! +//! Nothing the merge reads is new at the slot. A block at slot `S` packs +//! aggregates from `S - MIN_ATTESTATION_INCLUSION_DELAY_PQ` (two slots) and +//! earlier, which this node has held since about half way through `S - 2`, +//! and the state they are selected against is the head's, advanced to `S`. So +//! when the chain actor starts `S`'s payload build, a third of a slot ahead +//! (`crate::payload_attributes`), it starts packing `S`'s attestations too +//! ([`PreparedPqAttestations::start`]). Block production takes the result +//! when it is for the head it builds on and the pool still holds what it was +//! packed from, waiting for a packing still running up to its merge budget +//! ([`PreparedPqAttestations::take`]). A packing production does not use is +//! abandoned. +//! +//! Anything else packs at production, as before: another head (the parent +//! arrived after the preparation started, or a reorg), aggregates that +//! arrived or changed since, a preparation that did not pack everything it +//! selected, or none at all. +//! +//! # One merge at a time +//! +//! The sidecar proves one request after another, so the merges share one +//! permit ([`MERGE_PERMIT`]). A packing replaced by another (the head moved) +//! is abandoned and does not start its merge; one already merging finishes, +//! unheard. A packing ahead of the slot waits for the permit, having seconds +//! to spare; production tries it once and packs one committee's attestation +//! when it is held, as it always has. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use ethlambda_state_transition::beacon::fork_choice::get_attestation_due_ms; +use ethlambda_state_transition::beacon::pq_block_production::{PqPacked, select_pq_attestations}; +use ethlambda_storage::Store; +use ethlambda_storage::pools::PooledPqAggregate; +use ethlambda_types::ShortRoot; +use ethlambda_types::beacon::config::Config; +use ethlambda_types::beacon::containers::{BeaconState, pq}; +use ethlambda_types::beacon::preset::MIN_ATTESTATION_INCLUSION_DELAY_PQ; +use ethlambda_types::beacon::primitives::Slot; +use ethlambda_types::beacon::signing::compute_epoch_at_slot; +use ethlambda_types::primitives::H256; +use tokio::sync::{Semaphore, SemaphorePermit, watch}; +use tracing::{debug, info, warn}; + +use crate::payload_attributes::advance_for_proposal; + +/// What a PQ block packs: its attestations and the proof of all of them. +#[derive(Debug, Clone, Default)] +pub struct PackedAttestations { + pub attestations: Vec, + pub proof: Vec, + /// Whether this is everything the selection picked. `false` when the + /// merge was skipped, failed or ran out of time and one committee's + /// attestation was packed alone, or when nothing could be selected: a + /// prepared result like that is not used, and production packs again. + pub complete: bool, + /// The pool's candidates the selection ran over, held so production can + /// tell whether the pool changed since: by identity, and holding them + /// keeps an address from being reused in between. + candidates: Vec>, +} + +impl PackedAttestations { + fn new( + attestations: Vec, + proof: Vec, + complete: bool, + candidates: Vec>, + ) -> Self { + Self { + attestations, + proof, + complete, + candidates, + } + } + + /// Whether the pool's `current` candidates are the ones this was packed + /// from. + fn packed_from(&self, current: &[Arc]) -> bool { + same_aggregates(&self.candidates, current) + } +} + +/// Whether `a` and `b` hold the same pooled aggregates, in any order. +fn same_aggregates(a: &[Arc], b: &[Arc]) -> bool { + if a.len() != b.len() { + return false; + } + let addresses = |held: &[Arc]| { + let mut addresses: Vec = held + .iter() + .map(|aggregate| Arc::as_ptr(aggregate) as usize) + .collect(); + addresses.sort_unstable(); + addresses + }; + addresses(a) == addresses(b) +} + +/// One merge at a time: the sidecar proves one request after another, so a +/// second merge started while one runs would only push both past their +/// deadlines. A merge that missed its deadline keeps the permit until it +/// ends. Shared by the merge ahead of the slot and the one at production. +static MERGE_PERMIT: Semaphore = Semaphore::const_new(1); + +/// How [`pack_attestations`] gets the merge permit. +#[derive(Debug, Clone, Copy)] +pub enum PermitWait<'a> { + /// Try once and pack one committee's attestation when it is held: block + /// production, which must not hold the block back for another merge. + TryOnce, + /// Wait for it within the merge budget, giving up first if `abandoned` + /// is set: a packing ahead of the slot. + Wait { abandoned: &'a AtomicBool }, +} + +/// 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> { + let latest = slot.saturating_sub(MIN_ATTESTATION_INCLUSION_DELAY_PQ); + store.pq_aggregate_pool().candidates(latest) +} + +/// The attestations a PQ block at `state`'s slot packs and the merged proof +/// of their aggregates. Empty when there are none or the selection fails; +/// one committee's attestation alone when the merge misses its deadline +/// ([`merge_budget`]), fails, or does not get the merge permit. +pub async fn pack_attestations( + store: &Store, + state: &BeaconState, + config: &Config, + permit_wait: PermitWait<'_>, +) -> PackedAttestations { + let slot = state.slot(); + let candidates = candidates_for(store, slot); + if candidates.is_empty() { + return PackedAttestations::new(Vec::new(), Vec::new(), true, candidates); + } + let selected = { + let (store, state, selected_from) = (store.clone(), state.clone(), candidates.clone()); + tokio::task::spawn_blocking(move || { + select_pq_attestations(&state, selected_from, &store.committee_cache()) + }) + .await + }; + let packed = match selected { + Ok(Ok(packed)) => packed, + Ok(Err(err)) => { + warn!(%slot, %err, "Selecting the PQ attestations failed"); + return PackedAttestations::new(Vec::new(), Vec::new(), false, candidates); + } + Err(err) => { + warn!(%slot, %err, "The PQ attestation selection task failed"); + return PackedAttestations::new(Vec::new(), Vec::new(), false, candidates); + } + }; + if packed.attestations.is_empty() { + return PackedAttestations::new(Vec::new(), Vec::new(), true, candidates); + } + // One child's proof is the block's as it is; more must be merged. + let fallback = packed.first_unmerged(); + if packed.children.len() == 1 { + return unmerged(slot, packed, true, candidates); + } + let children = packed.children.len(); + let fall_back = |reason: &str| { + warn!(%slot, children, reason, "Packing one PQ attestation instead of merging every proof"); + match fallback.clone() { + Some(single) => unmerged(slot, single, false, candidates.clone()), + None => PackedAttestations::new(Vec::new(), Vec::new(), false, candidates.clone()), + } + }; + let Some(remaining) = merge_budget(config, slot) else { + return fall_back("no time left to merge"); + }; + let permit = match merge_permit(permit_wait, remaining).await { + Ok(permit) => permit, + // Nobody reads it: no fallback to pack, nothing to warn about. + Err(NoPermit::Abandoned) => { + 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), + }; + // 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"); + }; + let budget_ms = remaining.as_millis() as u64; + let job = tokio::task::spawn_blocking(move || { + let _permit = permit; + 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 signatures: usize = packed + .children + .iter() + .flat_map(|(statements, _)| statements) + .map(|statement| statement.pubkeys.len()) + .sum(); + info!( + %slot, + attestations = packed.attestations.len(), + children, + signatures, + proof_bytes = proof.as_ref().map_or(0, Vec::len), + took_ms = started.elapsed().as_millis() as u64, + budget_ms, + ok = proof.is_ok(), + "Merged PQ attestation proofs" + ); + proof.map(|proof| (packed, proof)) + }); + match tokio::time::timeout(remaining, job).await { + Ok(Ok(Ok((packed, proof)))) => { + info!( + %slot, + attestations = packed.attestations.len(), + children, + proof_bytes = proof.len(), + "Packed PQ 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() + )), + } +} + +/// Why [`merge_permit`] gave no permit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum NoPermit { + /// The packing was replaced or given up on: nobody reads its result. + Abandoned, + /// The merge cannot run now; the block packs one committee's attestation. + Refused(&'static str), +} + +/// The merge permit, as `permit_wait` says to get it, or why not. +async fn merge_permit( + permit_wait: PermitWait<'_>, + budget: Duration, +) -> Result, NoPermit> { + match permit_wait { + PermitWait::TryOnce => MERGE_PERMIT + .try_acquire() + .map_err(|_| NoPermit::Refused("a merge is still running")), + PermitWait::Wait { abandoned } => { + if abandoned.load(Ordering::Acquire) { + return Err(NoPermit::Abandoned); + } + let permit = tokio::time::timeout(budget, MERGE_PERMIT.acquire()) + .await + .map_err(|_| NoPermit::Refused("no merge permit within the budget"))? + .map_err(|_| NoPermit::Refused("the merge permit is closed"))?; + // Abandoned while it waited: leave the permit to whoever needs it. + if abandoned.load(Ordering::Acquire) { + return Err(NoPermit::Abandoned); + } + Ok(permit) + } + } +} + +/// `packed` with its one child's proof as the block's, nothing merged: +/// everything selected when `complete`, a fallback otherwise. +fn unmerged( + slot: Slot, + packed: PqPacked, + complete: bool, + candidates: Vec>, +) -> PackedAttestations { + match packed.merge() { + Ok(proof) => { + info!( + %slot, + attestations = packed.attestations.len(), + proof_bytes = proof.len(), + "Packed PQ attestations" + ); + PackedAttestations::new(packed.attestations, proof, complete, candidates) + } + Err(err) => { + warn!(%slot, %err, "A single PQ proof would not pass through the merge"); + PackedAttestations::new(Vec::new(), Vec::new(), false, candidates) + } + } +} + +/// How long a merge for a block at `slot` may take: until three quarters of +/// the slot's attestation deadline, so the block still reaches the attesters +/// in time. `None` once that point has passed. A merge started ahead of the +/// slot gets the same deadline, and so the whole lead on top. +pub fn merge_budget(config: &Config, slot: Slot) -> Option { + let due_ms = get_attestation_due_ms(compute_epoch_at_slot(slot), config); + let deadline_ms = config + .genesis_time + .saturating_mul(1000) + .saturating_add(slot.saturating_mul(config.slot_duration_ms)) + .saturating_add(due_ms.saturating_mul(3) / 4); + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| elapsed.as_millis() as u64); + deadline_ms + .checked_sub(now_ms) + .filter(|&left| left > 0) + .map(Duration::from_millis) +} + +/// The packing the chain actor started ahead of the next PQ proposal of this +/// node, shared with block production. Holds one: the latest started. +#[derive(Clone, Default)] +pub struct PreparedPqAttestations(Arc>>); + +struct Prepared { + slot: Slot, + head_root: H256, + /// `None` until the packing ends. Closed without a value when it could + /// not start (no head state, or it would not advance to the slot). + packed: watch::Receiver>>, + /// Set when another packing replaces this one, so it does not take the + /// merge permit from it. + abandoned: Arc, +} + +/// What [`PreparedPqAttestations::claim`] hands the packing it registers. +struct Claim { + packed: watch::Sender>>, + abandoned: Arc, +} + +impl PreparedPqAttestations { + /// Start packing, off the caller, the attestations of a block at `slot` + /// on `head_root`. Nothing happens when the same packing is already under + /// way or done; a packing for another slot or head is replaced and + /// abandoned (one already merging finishes, unheard). + pub fn start(&self, store: Store, head_root: H256, slot: Slot) { + let Some(claim) = self.claim(slot, head_root) else { + return; + }; + let prepared = self.clone(); + tokio::spawn(async move { + let started = Instant::now(); + let config = store.config(); + let advanced = { + let (store, config) = (store.clone(), config.clone()); + tokio::task::spawn_blocking(move || { + let head_state = store + .get_state(&head_root) + .map_err(|err| err.to_string())? + .ok_or_else(|| "the head state is not held".to_string())?; + advance_for_proposal(&store, head_root, &head_state, slot, &config) + .map_err(|err| err.to_string()) + }) + .await + .map_err(|err| err.to_string()) + .flatten() + }; + let state = match advanced { + Ok(state) => state, + Err(err) => { + warn!(%slot, %err, "Could not advance the head state to pack the next PQ block's attestations ahead"); + // So a later start for the same slot and head can try + // again rather than find this one registered. + prepared.release(&claim.abandoned); + return; + } + }; + let wait = PermitWait::Wait { + abandoned: &claim.abandoned, + }; + let packed = pack_attestations(&store, &state, &config, wait).await; + if claim.abandoned.load(Ordering::Acquire) { + debug!(%slot, head_root = %ShortRoot(&head_root.0), "Abandoned the next PQ block's attestation packing"); + return; + } + info!( + %slot, + head_root = %ShortRoot(&head_root.0), + attestations = packed.attestations.len(), + complete = packed.complete, + took_ms = started.elapsed().as_millis() as u64, + "Packed the next PQ block's attestations ahead of its slot" + ); + let _ = claim.packed.send(Some(Arc::new(packed))); + }); + } + + /// Takes the attestations packed ahead of a block at `slot` on + /// `head_root`, waiting up to `budget` for a packing still under way. + /// `None` when none was started for that slot and head, it did not pack + /// everything it selected, the pool's candidates changed since, or it did + /// not end in time: block production packs them itself then. + /// + /// Taken once either way, as [`crate::PreparedPayloads::take`] is. A + /// packing production does not use (for this slot on another head, for an + /// earlier slot, or one it gave up waiting for) is abandoned as it goes, + /// so it does not take the merge permit production may need next. + pub async fn take( + &self, + store: &Store, + slot: Slot, + head_root: H256, + budget: Duration, + ) -> Option { + let (mut receiver, abandoned) = { + let mut held = self + .0 + .lock() + .expect("prepared PQ attestations lock poisoned"); + // One for a later slot is the next proposal's: left alone. + if held.as_ref()?.slot > slot { + return None; + } + let prepared = held.take()?; + if prepared.slot != slot || prepared.head_root != head_root { + prepared.abandoned.store(true, Ordering::Release); + return None; + } + (prepared.packed, prepared.abandoned) + }; + let ready = match tokio::time::timeout(budget, receiver.wait_for(Option::is_some)).await { + Ok(Ok(ready)) => ready.clone()?, + // Gave up waiting, or it never started. + _ => { + abandoned.store(true, Ordering::Release); + return None; + } + }; + // The last holder but this one, once the receiver goes: the sender + // dropped after sending. + drop(receiver); + let packed = Arc::try_unwrap(ready).unwrap_or_else(|shared| (*shared).clone()); + (packed.complete && packed.packed_from(&candidates_for(store, slot))).then_some(packed) + } + + /// Register a packing for `slot` on `head_root` and hand back what it + /// sends its result through, or `None` when one for those is already + /// registered. The packing it replaces, if any, is abandoned. + fn claim(&self, slot: Slot, head_root: H256) -> Option { + let mut held = self + .0 + .lock() + .expect("prepared PQ attestations lock poisoned"); + if let Some(prepared) = held.as_ref() { + if prepared.slot == slot && prepared.head_root == head_root { + return None; + } + prepared.abandoned.store(true, Ordering::Release); + } + let (packed, receiver) = watch::channel(None); + let abandoned = Arc::new(AtomicBool::new(false)); + *held = Some(Prepared { + slot, + head_root, + packed: receiver, + abandoned: abandoned.clone(), + }); + Some(Claim { packed, abandoned }) + } + + /// Forget the packing `abandoned` belongs to, when it is still the one + /// held. + fn release(&self, abandoned: &Arc) { + let mut held = self + .0 + .lock() + .expect("prepared PQ attestations lock poisoned"); + if held + .as_ref() + .is_some_and(|prepared| Arc::ptr_eq(&prepared.abandoned, abandoned)) + { + *held = None; + } + } + + /// Whether a packing for `slot` on `head_root` is registered. + #[cfg(test)] + fn holds(&self, slot: Slot, head_root: H256) -> bool { + self.0 + .lock() + .expect("prepared PQ attestations lock poisoned") + .as_ref() + .is_some_and(|prepared| prepared.slot == slot && prepared.head_root == head_root) + } +} + +#[cfg(test)] +mod tests { + use ethlambda_types::beacon::containers::pq::{AggregationBits, Attestation}; + use ethlambda_types::beacon::containers::shared::AttestationData; + + use super::*; + + fn aggregate() -> Arc { + Arc::new(PooledPqAggregate { + attestation: Attestation { + aggregation_bits: AggregationBits::default(), + data: AttestationData::default(), + committee_bits: Default::default(), + }, + committee_index: 0, + attesting_indices: Vec::new(), + proof: Default::default(), + }) + } + + fn packing(complete: bool) -> PackedAttestations { + PackedAttestations::new(Vec::new(), vec![1, 2, 3], complete, Vec::new()) + } + + /// A preparation holding `packed` (still under way when `None`) for + /// `slot` on `head_root`, the sender a packing would answer through, and + /// the packing's abandoned flag. + fn held( + slot: Slot, + head_root: H256, + packed: Option, + ) -> ( + PreparedPqAttestations, + watch::Sender>>, + Arc, + ) { + let (sender, receiver) = watch::channel(packed.map(Arc::new)); + let abandoned = Arc::new(AtomicBool::new(false)); + let prepared = PreparedPqAttestations(Arc::new(Mutex::new(Some(Prepared { + slot, + head_root, + packed: receiver, + abandoned: abandoned.clone(), + })))); + (prepared, sender, abandoned) + } + + fn empty_pool_store() -> Store { + crate::tests::beacon_store(0, 0) + } + + #[test] + fn candidates_are_the_same_by_identity_in_any_order() { + let (a, b) = (aggregate(), aggregate()); + assert!(same_aggregates( + &[a.clone(), b.clone()], + &[b.clone(), a.clone()] + )); + assert!( + !same_aggregates(std::slice::from_ref(&a), std::slice::from_ref(&b)), + "equal content, another aggregate" + ); + assert!(!same_aggregates(std::slice::from_ref(&a), &[a.clone(), b])); + assert!(same_aggregates(&[], &[])); + } + + #[tokio::test] + async fn a_complete_packing_is_taken_once_for_its_own_slot_and_head() { + let root = H256::repeat_byte(1); + let store = empty_pool_store(); + let budget = Duration::from_millis(50); + let (prepared, _sender, abandoned) = held(10, root, Some(packing(true))); + let taken = prepared.take(&store, 10, root, budget).await; + assert_eq!(taken.map(|packed| packed.proof), Some(vec![1, 2, 3])); + assert!(!abandoned.load(Ordering::Acquire)); + assert!( + prepared.take(&store, 10, root, budget).await.is_none(), + "taken once" + ); + assert!( + PreparedPqAttestations::default() + .take(&store, 10, root, budget) + .await + .is_none() + ); + } + + /// A packing production does not use is dropped and abandoned, so it + /// does not take the merge permit production may need: one for this slot + /// on another head, one for an earlier slot, and one it gave up waiting + /// for. The next proposal's is left alone. + #[tokio::test] + async fn a_packing_production_does_not_use_is_abandoned() { + let (root, other) = (H256::repeat_byte(1), H256::repeat_byte(2)); + let store = empty_pool_store(); + let budget = Duration::from_millis(20); + + let (prepared, _sender, abandoned) = held(10, root, None); + assert!(prepared.take(&store, 10, other, budget).await.is_none()); + assert!(abandoned.load(Ordering::Acquire), "another head"); + assert!(!prepared.holds(10, root)); + + let (prepared, _sender, abandoned) = held(10, root, None); + assert!(prepared.take(&store, 11, root, budget).await.is_none()); + assert!(abandoned.load(Ordering::Acquire), "an earlier slot"); + + let (prepared, _sender, abandoned) = held(10, root, None); + assert!(prepared.take(&store, 10, root, budget).await.is_none()); + assert!(abandoned.load(Ordering::Acquire), "gave up waiting"); + + let (prepared, _sender, abandoned) = held(11, root, None); + assert!(prepared.take(&store, 10, root, budget).await.is_none()); + assert!(!abandoned.load(Ordering::Acquire), "the next proposal's"); + assert!(prepared.holds(11, root)); + } + + /// A packing that fell back to one committee's attestation is left to + /// production, which may yet merge everything. + #[tokio::test] + async fn a_partial_packing_is_not_taken() { + let root = H256::repeat_byte(1); + let (prepared, _sender, _) = held(10, root, Some(packing(false))); + let taken = prepared + .take(&empty_pool_store(), 10, root, Duration::from_millis(50)) + .await; + assert!(taken.is_none()); + } + + /// A packing made from other candidates than the pool's now is stale: an + /// aggregate arrived or was replaced since, so production packs again. + #[tokio::test] + async fn a_packing_from_other_candidates_is_not_taken() { + let root = H256::repeat_byte(1); + let mut stale = packing(true); + stale.candidates = vec![aggregate()]; + let (prepared, _sender, _) = held(10, root, Some(stale)); + let taken = prepared + .take(&empty_pool_store(), 10, root, Duration::from_millis(50)) + .await; + assert!(taken.is_none(), "the pool is empty now"); + } + + /// A packing still under way is waited for, up to the budget. + #[tokio::test] + async fn a_packing_under_way_is_waited_for_up_to_the_budget() { + let root = H256::repeat_byte(1); + let store = empty_pool_store(); + let (prepared, sender, abandoned) = held(10, root, None); + let waiting = { + let (prepared, store) = (prepared.clone(), store.clone()); + tokio::spawn(async move { + prepared + .take(&store, 10, root, Duration::from_secs(5)) + .await + }) + }; + sender.send(Some(Arc::new(packing(true)))).unwrap(); + let taken = waiting.await.unwrap(); + assert_eq!(taken.map(|packed| packed.proof), Some(vec![1, 2, 3])); + assert!(!abandoned.load(Ordering::Acquire)); + } + + /// A packing that never started (its sender gone without a value) gives + /// nothing at once rather than holding production to its budget. + #[tokio::test] + async fn a_packing_that_never_started_gives_nothing_at_once() { + let root = H256::repeat_byte(1); + let (prepared, sender, _) = held(10, root, None); + drop(sender); + let started = Instant::now(); + let taken = prepared + .take(&empty_pool_store(), 10, root, Duration::from_secs(5)) + .await; + assert!(taken.is_none()); + assert!(started.elapsed() < Duration::from_secs(1)); + } + + /// A packing is claimed once per slot and head. Another head or slot + /// replaces it and abandons it, and one released after failing to start + /// can be claimed again. + #[test] + fn a_packing_is_claimed_once_per_slot_and_head() { + let (root, other) = (H256::repeat_byte(1), H256::repeat_byte(2)); + let prepared = PreparedPqAttestations::default(); + let first = prepared.claim(10, root).expect("first claim"); + assert!(prepared.claim(10, root).is_none(), "already under way"); + assert!(prepared.holds(10, root)); + + let second = prepared.claim(10, other).expect("another head"); + assert!(first.abandoned.load(Ordering::Acquire), "replaced"); + assert!(!second.abandoned.load(Ordering::Acquire)); + assert!(prepared.holds(10, other) && !prepared.holds(10, root)); + + // A replaced packing's release leaves its replacement alone. + prepared.release(&first.abandoned); + assert!(prepared.holds(10, other)); + prepared.release(&second.abandoned); + assert!(!prepared.holds(10, other)); + assert!(prepared.claim(10, other).is_some(), "claimable again"); + } + + /// An abandoned packing gives the merge permit up without taking it. + #[tokio::test] + async fn an_abandoned_packing_does_not_take_the_merge_permit() { + let abandoned = AtomicBool::new(true); + let wait = PermitWait::Wait { + abandoned: &abandoned, + }; + let refused = merge_permit(wait, Duration::from_secs(1)).await.err(); + assert_eq!(refused, Some(NoPermit::Abandoned)); + assert_eq!(MERGE_PERMIT.available_permits(), 1); + } +} diff --git a/crates/net/rpc/src/beacon/pq_proposal.rs b/crates/net/rpc/src/beacon/pq_proposal.rs index b802f2881..ea943e0e3 100644 --- a/crates/net/rpc/src/beacon/pq_proposal.rs +++ b/crates/net/rpc/src/beacon/pq_proposal.rs @@ -15,18 +15,21 @@ //! appended, as every other block this node builds does. //! //! The attestations come from the pool of validated network aggregates, and -//! their proofs are merged into the block's one `proof` while the execution -//! client builds the payload. A merge runs on the proving sidecar and costs -//! seconds when there is more than one child, so it is bounded by a deadline -//! three quarters of the way to the slot's attestation deadline (Lighthouse's -//! PQ branch uses the same one). A merge that misses it or fails is dropped -//! for the most valuable single-committee attestation alone, whose proof -//! needs no merging; a block `process_stark` refuses is built again without -//! attestations, so the block goes out rather than not at all. +//! their proofs are merged into the block's one `proof`. The chain actor does +//! that ahead of the slot, alongside the payload build, for the slots this +//! node's proposers hold, and production collects it when it was for the head +//! it builds on (`ethlambda_blockchain::pq_attestation_packing`); otherwise +//! it merges here while the execution client builds the payload. A merge runs +//! on the proving sidecar and costs about 0.6 s with two children, so it is +//! bounded by a deadline three quarters of the way to the slot's attestation +//! deadline (Lighthouse's PQ branch uses the same one). A merge that misses +//! it or fails is dropped for the most valuable single-committee attestation +//! alone, whose proof needs no merging; a block `process_stark` refuses is +//! built again without attestations, so the block goes out rather than not +//! at all. use std::collections::BTreeMap; use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use axum::{ Extension, Json, Router, @@ -35,31 +38,26 @@ use axum::{ routing::post, }; use ethlambda_blockchain::{ - PreparedPayloads, SyncStatusController, + PreparedPayloads, PreparedPqAttestations, SyncStatusController, metrics::SyncStatus, payload_attributes::{PqProposal, ProposalError, prepare_pq_proposal, prepared_fee_recipient}, + pq_attestation_packing::{PermitWait, merge_budget, pack_attestations}, }; use ethlambda_engine::{EngineClient, types::ClientVersionV1}; use ethlambda_state_transition::beacon::{ - fork_choice::get_attestation_due_ms, helpers::pq::is_valid_vrf_proof, - pq_block_production::{ - PqBlockInputs, PqPacked, assemble_pq_block, parse_pq_execution_requests, - select_pq_attestations, - }, + pq_block_production::{PqBlockInputs, assemble_pq_block, parse_pq_execution_requests}, }; use ethlambda_storage::Store; use ethlambda_types::beacon::{ config::Config, containers::{BeaconState, pq}, fork::ForkName, - preset::MIN_ATTESTATION_INCLUSION_DELAY_PQ, primitives::{Bytes32, ExecutionAddress, HashTreeRoot as _, KzgProof, Root, Slot}, signing::compute_epoch_at_slot, }; use libssz::SszEncode as _; use serde::Deserialize; -use tokio::sync::Semaphore; use tracing::{info, warn}; use crate::CustodyColumns as NodeCustodyColumns; @@ -135,6 +133,7 @@ async fn post_produce_pq_block( Extension(sync_status): Extension, blob_cache: Option>, ahead: Option>, + ahead_attestations: Option>, Json(request): Json, ) -> Response { let Ok(slot) = slot.parse::() else { @@ -165,6 +164,7 @@ async fn post_produce_pq_block( &fee_recipients, &custody, ahead.as_ref().map(|Extension(ahead)| ahead), + ahead_attestations.as_ref().map(|Extension(ahead)| ahead), &own_version, slot, randao_reveal, @@ -195,6 +195,7 @@ async fn produce( fee_recipients: &FeeRecipients, custody: &NodeCustodyColumns, ahead: Option<&PreparedPayloads>, + ahead_attestations: Option<&PreparedPqAttestations>, own_version: &ClientVersionV1, slot: Slot, randao_reveal: pq::VrfProof, @@ -226,7 +227,7 @@ async fn produce( // the build, as gloas's production does. let (built, (attestations, proof), el_version) = tokio::join!( build_payload(store, engine, fee_recipient, custody, &inputs, ahead), - pack_attestations(store, &state, &config), + attestations_for_block(store, &state, &config, head_root, ahead_attestations), graffiti::execution_client_version(engine, own_version), ); let graffiti = graffiti::with_client_versions(graffiti, el_version.as_ref(), own_version); @@ -291,145 +292,35 @@ async fn produce( Ok((contents, blobs)) } -/// One merge at a time: the sidecar proves one request after another, so a -/// second merge started while one runs would only push both past their -/// deadlines. A merge that missed its deadline keeps the permit until it -/// ends. -static MERGE_PERMIT: Semaphore = Semaphore::const_new(1); - /// The attestations a PQ block at `state`'s slot packs and the merged proof -/// of their aggregates, or none when there are none, the merge misses its -/// deadline, or it fails. -async fn pack_attestations( +/// of their aggregates: the ones the chain actor packed ahead of the slot for +/// this head when it did, and otherwise packed now +/// (`ethlambda_blockchain::pq_attestation_packing`). +async fn attestations_for_block( store: &Store, state: &BeaconState, config: &Config, + head_root: Root, + prepared: Option<&PreparedPqAttestations>, ) -> (Vec, Vec) { let slot = state.slot(); - let latest = slot.saturating_sub(MIN_ATTESTATION_INCLUSION_DELAY_PQ); - let candidates = store.pq_aggregate_pool().candidates(latest); - if candidates.is_empty() { - return Default::default(); - } - let selected = { - let (store, state) = (store.clone(), state.clone()); - tokio::task::spawn_blocking(move || { - select_pq_attestations(&state, candidates, &store.committee_cache()) - }) - .await - }; - let packed = match selected { - Ok(Ok(packed)) => packed, - Ok(Err(err)) => { - warn!(%slot, %err, "Selecting the PQ attestations failed"); - return Default::default(); - } - Err(err) => { - warn!(%slot, %err, "The PQ attestation selection task failed"); - return Default::default(); - } - }; - if packed.attestations.is_empty() { - return Default::default(); - } - // One child's proof is the block's as it is; more must be merged. - let fallback = packed.first_unmerged(); - if packed.children.len() == 1 { - return unmerged(slot, packed); - } - let children = packed.children.len(); - let fall_back = |reason: &str| { - warn!(%slot, children, reason, "Packing one PQ attestation instead of merging every proof"); - fallback - .clone() - .map_or_else(Default::default, |single| unmerged(slot, single)) - }; - let Some(remaining) = merge_budget(config, slot) else { - return fall_back("no time left to merge"); - }; - let Ok(permit) = MERGE_PERMIT.try_acquire() else { - return fall_back("a merge is still running"); - }; - let budget_ms = remaining.as_millis() as u64; - let job = tokio::task::spawn_blocking(move || { - let _permit = permit; - 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 signatures: usize = packed - .children - .iter() - .flat_map(|(statements, _)| statements) - .map(|statement| statement.pubkeys.len()) - .sum(); - info!( - %slot, - attestations = packed.attestations.len(), - children, - signatures, - proof_bytes = proof.as_ref().map_or(0, Vec::len), - took_ms = started.elapsed().as_millis() as u64, - budget_ms, - ok = proof.is_ok(), - "Merged PQ attestation proofs" - ); - proof.map(|proof| (packed, proof)) - }); - match tokio::time::timeout(remaining, job).await { - Ok(Ok(Ok((packed, proof)))) => { + if let Some(prepared) = prepared { + // The whole merge budget: a packing under way for this slot and head + // computes what production would, and holds the one merge permit + // production would need, so production could not do better by + // giving up on it early. One that ends partial or stale still leaves + // production whatever time is left, with the permit free. + let budget = merge_budget(config, slot).unwrap_or_default(); + if let Some(packed) = prepared.take(store, slot, head_root, budget).await { info!( %slot, attestations = packed.attestations.len(), - children, - proof_bytes = proof.len(), - "Packed PQ attestations" + proof_bytes = packed.proof.len(), + "Collected the PQ attestations packed ahead of the slot" ); - (packed.attestations, proof) + return (packed.attestations, packed.proof); } - 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() - )), } -} - -/// `packed` with its one child's proof as the block's, nothing merged. -fn unmerged(slot: Slot, packed: PqPacked) -> (Vec, Vec) { - match packed.merge() { - Ok(proof) => { - info!( - %slot, - attestations = packed.attestations.len(), - proof_bytes = proof.len(), - "Packed PQ attestations" - ); - (packed.attestations, proof) - } - Err(err) => { - warn!(%slot, %err, "A single PQ proof would not pass through the merge"); - Default::default() - } - } -} - -/// How long a merge for a block at `slot` may take: until three quarters of -/// the slot's attestation deadline, so the block still reaches the attesters -/// in time. `None` once that point has passed. -fn merge_budget(config: &Config, slot: Slot) -> Option { - let due_ms = get_attestation_due_ms(compute_epoch_at_slot(slot), config); - let deadline_ms = config - .genesis_time - .saturating_mul(1000) - .saturating_add(slot.saturating_mul(config.slot_duration_ms)) - .saturating_add(due_ms.saturating_mul(3) / 4); - let now_ms = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |elapsed| elapsed.as_millis() as u64); - deadline_ms - .checked_sub(now_ms) - .filter(|&left| left > 0) - .map(Duration::from_millis) + let packed = pack_attestations(store, state, config, PermitWait::TryOnce).await; + (packed.attestations, packed.proof) } diff --git a/crates/net/rpc/src/lib.rs b/crates/net/rpc/src/lib.rs index 32d2520af..74e763767 100644 --- a/crates/net/rpc/src/lib.rs +++ b/crates/net/rpc/src/lib.rs @@ -293,6 +293,9 @@ pub struct BeaconApiHandles { /// The payload builds the chain actor started ahead of their slots, which /// block production collects instead of starting its own. pub prepared_payloads: ethlambda_blockchain::PreparedPayloads, + /// The attestations of the next PQ block, which the chain actor packs and + /// merges ahead of the slot and PQ block production collects. + pub prepared_pq_attestations: ethlambda_blockchain::PreparedPqAttestations, /// The columns this node custodies: what `payload_attestation_data` checks /// a block's blob availability against, and what block production tells /// the execution client it samples for when asking it to build a gloas @@ -352,6 +355,7 @@ pub async fn start_beacon_rpc_server( .layer(Extension(handles.custody_columns)) .layer(Extension(handles.fee_recipients)) .layer(Extension(handles.prepared_payloads)) + .layer(Extension(handles.prepared_pq_attestations)) .layer(Extension(handles.engine)) .layer(Extension(handles.events)) .layer(Extension(handles.identity)) diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index 78f164aae..14d1a6d3f 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -401,16 +401,22 @@ asks for again. - **Proposing**: the client sends its VRF proof for the slot (the RANDAO reveal) to `POST /eth/v1/validator/pq_blocks/{slot}`, signs the block and the envelope revealing its self-built payload at their leaves, and publishes - both. The beacon node builds the block while the execution client builds - the payload, and meanwhile packs attestations: it picks, from the - aggregates it validated, what `process_attestation` accepts at the slot and - credits someone new, as `compute_on_chain_aggregate` shapes them, and merges - their proofs in `process_stark`'s order on the sidecar. A merge must end - three quarters of the way to the attestation deadline (Lighthouse's bound). - One child needs no merge; when more do not finish in time, the block packs - the most valuable single-committee attestation alone, whose proof is the - block's as it is. On the devnet's VM a two-child merge takes about four - seconds, for Lighthouse too, so blocks there carry one attestation each. + both. The block's attestations are packed a third of a slot ahead, when + the chain actor starts the slot's payload build for a proposer a validator + client registered here (`ethlambda_blockchain::pq_attestation_packing`): + it picks, from the aggregates it validated, what `process_attestation` + accepts at the slot and credits someone new, as `compute_on_chain_aggregate` + shapes them, and merges their proofs in `process_stark`'s order on the + sidecar. A block at `N` packs aggregates from `N - 2` and earlier, all held + by then. Production takes that result when it is for the head it builds on + and the pool still holds what it was packed from, and otherwise packs + while the execution client builds the payload, as it always did. A merge + must end three quarters of the way to the attestation deadline + (Lighthouse's bound). One child needs no merge; when more do not finish in + time, the block packs the most valuable single-committee attestation + alone, whose proof is the block's as it is. A two-child merge takes about + 0.6 s on pq-devnet-0's hosts (about four seconds on the local devnet's VM), + which is what packing ahead takes off every block's path. A payload with blobs keeps them on the node that built it, and the envelope's publication builds the data columns from them and gossips them with it (PQ keeps gloas's sidecar). @@ -598,10 +604,6 @@ generated. - The ENR's `attnets` keeps the pre-PQ backbone across the PQ boundary: ethrex's `DiscoveryServer` cannot replace the served record at runtime (the same gap as its `eth2` entry, see `CLAUDE.md`). -- Merging ahead of a proposal: the aggregates a slot-`N` block may pack are - all known a slot earlier, so a node could merge during slot `N - 1` for a - proposer it serves, where today a slow merge costs every attestation but - one. - PQ block production does not weigh builder bids: it self-builds, and the PQ builder market it would read is filled but unused. - The pubkey index cache keys a pubkey by bytes 1 to 9, all zero for a PQ