From 2c01eac7af4029053a929e9523ae62497a30ca3f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Thu, 26 Nov 2026 21:57:05 -0300 Subject: [PATCH 1/4] perf(pq): merge a block's attestation proofs ahead of its slot Block production merged the packed aggregates' proofs into the block's one proof when the validator client asked for the block, at the slot's start: about 0.58 s on the sidecar (533-656 ms over geth-2's 19 proposals), on the path of every block this node proposed. ethlambda's blocks reached Dora's nodes at a 1.24 s median against 0.36-0.47 s for Lighthouse, Prysm, Teku, Silver and Grandine, whose blocks carry the same merged proof (one attestation over both committees, ~185 KB). Nothing the merge reads is new at the slot: a block at S packs aggregates from S-2 and earlier, against the head's state advanced to S. So when the chain actor starts S's payload build a third of a slot ahead, it now also starts packing S's attestations (PreparedPqAttestations::start), and production collects the result when it is for the head it builds on, waiting for one still running up to the merge budget. Anything else (another head, a packing that fell back to one committee, none at all) packs at production as before. pack_attestations, merge_budget and the one-merge-at-a-time permit move from rpc's pq_proposal to the new ethlambda_blockchain::pq_attestation_packing, unchanged except that the result says whether it is complete. --- bin/ethlambda/src/main.rs | 5 + crates/blockchain/src/lib.rs | 2 + crates/blockchain/src/payload_attributes.rs | 19 + .../blockchain/src/pq_attestation_packing.rs | 474 ++++++++++++++++++ crates/net/rpc/src/beacon/pq_proposal.rs | 182 ++----- crates/net/rpc/src/lib.rs | 4 + 6 files changed, 539 insertions(+), 147 deletions(-) create mode 100644 crates/blockchain/src/pq_attestation_packing.rs 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..702195e3f 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,21 @@ 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`). + let proposal_epoch = compute_epoch_at_slot(key.proposal_slot); + if self.store.config().fork_at_epoch(proposal_epoch) == ForkName::Pq + && let Ok(Some(head_state)) = self.store.get_state(&key.head_root) + { + preparation.prepared_pq_attestations.start( + self.store.clone(), + key.head_root, + head_state, + 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..834bb1865 --- /dev/null +++ b/crates/blockchain/src/pq_attestation_packing.rs @@ -0,0 +1,474 @@ +//! 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 collects the result +//! when it is for the head it builds on, waiting for it if it is still +//! running ([`PreparedPqAttestations::collect`]). +//! +//! Anything else packs at production, as before: another head (the parent +//! arrived after the preparation started, or a reorg), a preparation that did +//! not pack everything it selected, or none at all. + +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_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, watch}; +use tracing::{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, PartialEq, Eq)] +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, +} + +impl PackedAttestations { + fn complete(attestations: Vec, proof: Vec) -> Self { + Self { + attestations, + proof, + complete: true, + } + } + + fn partial(attestations: Vec, proof: Vec) -> Self { + Self { + attestations, + proof, + complete: false, + } + } +} + +/// 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); + +/// 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 finds another merge running. +pub async fn pack_attestations( + store: &Store, + state: &BeaconState, + config: &Config, +) -> PackedAttestations { + 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 PackedAttestations::complete(Vec::new(), Vec::new()); + } + 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 PackedAttestations::default(); + } + Err(err) => { + warn!(%slot, %err, "The PQ attestation selection task failed"); + return PackedAttestations::default(); + } + }; + if packed.attestations.is_empty() { + return PackedAttestations::complete(Vec::new(), Vec::new()); + } + // 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); + } + 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(PackedAttestations::default, |single| { + unmerged(slot, single, false) + }) + }; + 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)))) => { + info!( + %slot, + attestations = packed.attestations.len(), + children, + proof_bytes = proof.len(), + "Packed PQ attestations" + ); + PackedAttestations::complete(packed.attestations, 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: +/// everything selected when `complete`, a fallback otherwise. +fn unmerged(slot: Slot, packed: PqPacked, complete: bool) -> PackedAttestations { + match packed.merge() { + Ok(proof) => { + info!( + %slot, + attestations = packed.attestations.len(), + proof_bytes = proof.len(), + "Packed PQ attestations" + ); + PackedAttestations { + attestations: packed.attestations, + proof, + complete, + } + } + Err(err) => { + warn!(%slot, %err, "A single PQ proof would not pass through the merge"); + PackedAttestations::partial(Vec::new(), Vec::new()) + } + } +} + +/// 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 (the head state would not advance to the slot). + packed: watch::Receiver>>, +} + +impl PreparedPqAttestations { + /// Start packing, off the caller, the attestations of a block at `slot` + /// on `head_root`, whose post-state is `head_state`. Nothing happens when + /// the same packing is already under way or done; a packing for another + /// slot or head is replaced (one already running finishes, unheard). + pub fn start(&self, store: Store, head_root: H256, head_state: Arc, slot: Slot) { + let Some(sender) = self.claim(slot, head_root) else { + return; + }; + 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 || { + advance_for_proposal(&store, head_root, &head_state, slot, &config) + }) + .await + }; + let state = match advanced { + Ok(Ok(state)) => state, + Ok(Err(err)) => { + warn!(%slot, %err, "Advancing the head state to pack the next PQ block's attestations failed"); + return; + } + Err(err) => { + warn!(%slot, %err, "The task advancing the head state to pack the next PQ block's attestations failed"); + return; + } + }; + let packed = pack_attestations(&store, &state, &config).await; + 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 _ = sender.send(Some(Arc::new(packed))); + }); + } + + /// Register a packing for `slot` on `head_root` and hand back where its + /// result goes, or `None` when one for those is already registered. + fn claim( + &self, + slot: Slot, + head_root: H256, + ) -> Option>>> { + let mut held = self + .0 + .lock() + .expect("prepared PQ attestations lock poisoned"); + if held + .as_ref() + .is_some_and(|prepared| prepared.slot == slot && prepared.head_root == head_root) + { + return None; + } + let (sender, receiver) = watch::channel(None); + *held = Some(Prepared { + slot, + head_root, + packed: receiver, + }); + Some(sender) + } + + /// 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, or it did not end in time: block production packs them + /// itself then. + pub async fn collect( + &self, + slot: Slot, + head_root: H256, + budget: Duration, + ) -> Option> { + let mut packed = { + let held = self + .0 + .lock() + .expect("prepared PQ attestations lock poisoned"); + let prepared = held + .as_ref() + .filter(|prepared| prepared.slot == slot && prepared.head_root == head_root)?; + prepared.packed.clone() + }; + let ready = tokio::time::timeout(budget, packed.wait_for(Option::is_some)) + .await + .ok()? + .ok()? + .clone()?; + ready.complete.then_some(ready) + } + + /// Whether a packing for `slot` on `head_root` was started. + #[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 super::*; + + /// A preparation stands in place of the packing it holds, under its own + /// slot and head only. + fn held( + slot: Slot, + head_root: H256, + packed: Option, + ) -> PreparedPqAttestations { + let (sender, receiver) = watch::channel(packed.map(Arc::new)); + // Kept open, as a packing under way keeps its sender. + std::mem::forget(sender); + PreparedPqAttestations(Arc::new(Mutex::new(Some(Prepared { + slot, + head_root, + packed: receiver, + })))) + } + + fn some_packing(complete: bool) -> PackedAttestations { + PackedAttestations { + attestations: Vec::new(), + proof: vec![1, 2, 3], + complete, + } + } + + #[tokio::test] + async fn a_complete_packing_is_collected_for_its_own_slot_and_head() { + let root = H256::repeat_byte(1); + let prepared = held(10, root, Some(some_packing(true))); + let budget = Duration::from_millis(50); + let collected = prepared.collect(10, root, budget).await; + assert_eq!(collected.as_deref(), Some(&some_packing(true))); + assert!(prepared.collect(11, root, budget).await.is_none()); + assert!( + prepared + .collect(10, H256::repeat_byte(2), budget) + .await + .is_none() + ); + assert!( + PreparedPqAttestations::default() + .collect(10, root, budget) + .await + .is_none() + ); + } + + /// 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_collected() { + let root = H256::repeat_byte(1); + let prepared = held(10, root, Some(some_packing(false))); + let collected = prepared.collect(10, root, Duration::from_millis(50)).await; + assert!(collected.is_none()); + } + + /// 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 (sender, receiver) = watch::channel(None); + let prepared = PreparedPqAttestations(Arc::new(Mutex::new(Some(Prepared { + slot: 10, + head_root: root, + packed: receiver, + })))); + assert!( + prepared + .collect(10, root, Duration::from_millis(20)) + .await + .is_none(), + "nothing yet, and the budget runs out" + ); + let waiting = { + let prepared = prepared.clone(); + tokio::spawn(async move { prepared.collect(10, root, Duration::from_secs(5)).await }) + }; + sender.send(Some(Arc::new(some_packing(true)))).unwrap(); + let collected = waiting.await.unwrap(); + assert_eq!(collected.as_deref(), Some(&some_packing(true))); + } + + /// 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 (sender, receiver) = watch::channel(None); + drop(sender); + let prepared = PreparedPqAttestations(Arc::new(Mutex::new(Some(Prepared { + slot: 10, + head_root: root, + packed: receiver, + })))); + let started = Instant::now(); + assert!( + prepared + .collect(10, root, Duration::from_secs(5)) + .await + .is_none() + ); + assert!(started.elapsed() < Duration::from_secs(1)); + } + + /// A packing is claimed once per slot and head: claiming the same again + /// leaves the first under way, and another head or slot replaces it. + #[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); + assert!(first.is_some()); + assert!(prepared.claim(10, root).is_none(), "already under way"); + assert!(prepared.holds(10, root)); + assert!(prepared.claim(10, other).is_some()); + assert!(prepared.holds(10, other)); + assert!(!prepared.holds(10, root)); + assert!(prepared.claim(11, other).is_some()); + assert!(prepared.holds(11, other)); + } +} diff --git a/crates/net/rpc/src/beacon/pq_proposal.rs b/crates/net/rpc/src/beacon/pq_proposal.rs index b802f2881..4d1f80c01 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::{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,32 @@ 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 { + // Bounded like a merge here would be: one still running ahead holds + // the merge permit, so starting another would only fall back. + let budget = merge_budget(config, slot).unwrap_or_default(); + if let Some(packed) = prepared.collect(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.clone(), packed.proof.clone()); } - 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).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)) From 1b215deafe78a713cc22df96626cb3d76ecde0fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:03:36 -0300 Subject: [PATCH 2/4] fix(pq): only take a merge packed ahead that still matches the pool, and keep the permit for the packing that counts Review round 1 on the ahead-of-slot packing: - Production takes the prepared result only when the pool's candidates are the ones it was packed from (held Arcs compared by identity), so an aggregate that arrived or was replaced since, or a pool that was empty then, is packed at production instead of being dropped. - A packing replaced by another (the head moved) is abandoned and does not start its merge; one ahead of the slot waits for the merge permit within its budget instead of falling back at once. Production still tries the permit once, as before. - Production waits for a packing under way for half its merge budget at most, leaving it time to pack itself. - Only for a proposer with a registered fee recipient, not every slot --always-prepare-payload builds for. - A packing that could not start releases its claim, so it can be tried again; production takes the result instead of cloning it; the head state is read in the packing's task, not on the chain actor. --- crates/blockchain/src/payload_attributes.rs | 7 +- .../blockchain/src/pq_attestation_packing.rs | 494 ++++++++++++------ crates/net/rpc/src/beacon/pq_proposal.rs | 14 +- 3 files changed, 356 insertions(+), 159 deletions(-) diff --git a/crates/blockchain/src/payload_attributes.rs b/crates/blockchain/src/payload_attributes.rs index 702195e3f..c8a10af2f 100644 --- a/crates/blockchain/src/payload_attributes.rs +++ b/crates/blockchain/src/payload_attributes.rs @@ -1029,15 +1029,16 @@ impl BlockChainServer { // 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`). + // `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 - && let Ok(Some(head_state)) = self.store.get_state(&key.head_root) + && key.fee_recipient.is_some() { preparation.prepared_pq_attestations.start( self.store.clone(), key.head_root, - head_state, key.proposal_slot, ); } diff --git a/crates/blockchain/src/pq_attestation_packing.rs b/crates/blockchain/src/pq_attestation_packing.rs index 834bb1865..a83068c34 100644 --- a/crates/blockchain/src/pq_attestation_packing.rs +++ b/crates/blockchain/src/pq_attestation_packing.rs @@ -16,20 +16,33 @@ //! 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 collects the result -//! when it is for the head it builds on, waiting for it if it is still -//! running ([`PreparedPqAttestations::collect`]). +//! ([`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 for at most half its +//! merge budget ([`PreparedPqAttestations::take`]). //! //! Anything else packs at production, as before: another head (the parent -//! arrived after the preparation started, or a reorg), a preparation that did -//! not pack everything it selected, or none at all. +//! 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}; @@ -37,13 +50,13 @@ 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, watch}; +use tokio::sync::{Semaphore, SemaphorePermit, watch}; use tracing::{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, PartialEq, Eq)] +#[derive(Debug, Clone, Default)] pub struct PackedAttestations { pub attestations: Vec, pub proof: Vec, @@ -52,51 +65,93 @@ pub struct PackedAttestations { /// 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 complete(attestations: Vec, proof: Vec) -> Self { + fn new( + attestations: Vec, + proof: Vec, + complete: bool, + candidates: Vec>, + ) -> Self { Self { attestations, proof, - complete: true, + complete, + candidates, } } - fn partial(attestations: Vec, proof: Vec) -> Self { - Self { - attestations, - proof, - complete: false, - } + /// 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 finds another merge running. +/// ([`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 latest = slot.saturating_sub(MIN_ATTESTATION_INCLUSION_DELAY_PQ); - let candidates = store.pq_aggregate_pool().candidates(latest); + let candidates = candidates_for(store, slot); if candidates.is_empty() { - return PackedAttestations::complete(Vec::new(), Vec::new()); + return PackedAttestations::new(Vec::new(), Vec::new(), true, candidates); } let selected = { - let (store, state) = (store.clone(), state.clone()); + let (store, state, selected_from) = (store.clone(), state.clone(), candidates.clone()); tokio::task::spawn_blocking(move || { - select_pq_attestations(&state, candidates, &store.committee_cache()) + select_pq_attestations(&state, selected_from, &store.committee_cache()) }) .await }; @@ -104,35 +159,39 @@ pub async fn pack_attestations( Ok(Ok(packed)) => packed, Ok(Err(err)) => { warn!(%slot, %err, "Selecting the PQ attestations failed"); - return PackedAttestations::default(); + return PackedAttestations::new(Vec::new(), Vec::new(), false, candidates); } Err(err) => { warn!(%slot, %err, "The PQ attestation selection task failed"); - return PackedAttestations::default(); + return PackedAttestations::new(Vec::new(), Vec::new(), false, candidates); } }; if packed.attestations.is_empty() { - return PackedAttestations::complete(Vec::new(), Vec::new()); + 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); + 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"); - fallback - .clone() - .map_or_else(PackedAttestations::default, |single| { - unmerged(slot, single, false) - }) + 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 Ok(permit) = MERGE_PERMIT.try_acquire() else { - return fall_back("a merge is still running"); + let permit = match merge_permit(permit_wait, remaining).await { + Ok(permit) => permit, + Err(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 || { @@ -169,7 +228,7 @@ pub async fn pack_attestations( proof_bytes = proof.len(), "Packed PQ attestations" ); - PackedAttestations::complete(packed.attestations, proof) + 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}")), @@ -180,9 +239,40 @@ pub async fn pack_attestations( } } +/// The merge permit, as `permit_wait` says to get it, or why not. +async fn merge_permit( + permit_wait: PermitWait<'_>, + budget: Duration, +) -> Result, &'static str> { + match permit_wait { + PermitWait::TryOnce => MERGE_PERMIT + .try_acquire() + .map_err(|_| "a merge is still running"), + PermitWait::Wait { abandoned } => { + if abandoned.load(Ordering::Acquire) { + return Err("the packing was replaced before its merge"); + } + let permit = tokio::time::timeout(budget, MERGE_PERMIT.acquire()) + .await + .map_err(|_| "no merge permit within the budget")? + .map_err(|_| "the merge permit is closed")?; + // Replaced while it waited: leave the permit to the replacement. + if abandoned.load(Ordering::Acquire) { + return Err("the packing was replaced before its merge"); + } + 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) -> PackedAttestations { +fn unmerged( + slot: Slot, + packed: PqPacked, + complete: bool, + candidates: Vec>, +) -> PackedAttestations { match packed.merge() { Ok(proof) => { info!( @@ -191,15 +281,11 @@ fn unmerged(slot: Slot, packed: PqPacked, complete: bool) -> PackedAttestations proof_bytes = proof.len(), "Packed PQ attestations" ); - PackedAttestations { - attestations: packed.attestations, - proof, - complete, - } + PackedAttestations::new(packed.attestations, proof, complete, candidates) } Err(err) => { warn!(%slot, %err, "A single PQ proof would not pass through the merge"); - PackedAttestations::partial(Vec::new(), Vec::new()) + PackedAttestations::new(Vec::new(), Vec::new(), false, candidates) } } } @@ -233,41 +319,60 @@ struct Prepared { slot: Slot, head_root: H256, /// `None` until the packing ends. Closed without a value when it could - /// not start (the head state would not advance to the slot). + /// 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`, whose post-state is `head_state`. Nothing happens when - /// the same packing is already under way or done; a packing for another - /// slot or head is replaced (one already running finishes, unheard). - pub fn start(&self, store: Store, head_root: H256, head_state: Arc, slot: Slot) { - let Some(sender) = self.claim(slot, head_root) else { + /// 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(Ok(state)) => state, - Ok(Err(err)) => { - warn!(%slot, %err, "Advancing the head state to pack the next PQ block's attestations failed"); - return; - } + Ok(state) => state, Err(err) => { - warn!(%slot, %err, "The task advancing the head state to pack the next PQ block's attestations failed"); + 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 packed = pack_attestations(&store, &state, &config).await; + let wait = PermitWait::Wait { + abandoned: &claim.abandoned, + }; + let packed = pack_attestations(&store, &state, &config, wait).await; info!( %slot, head_root = %ShortRoot(&head_root.0), @@ -276,66 +381,89 @@ impl PreparedPqAttestations { took_ms = started.elapsed().as_millis() as u64, "Packed the next PQ block's attestations ahead of its slot" ); - let _ = sender.send(Some(Arc::new(packed))); + let _ = claim.packed.send(Some(Arc::new(packed))); }); } - /// Register a packing for `slot` on `head_root` and hand back where its - /// result goes, or `None` when one for those is already registered. - fn claim( + /// 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. + pub async fn take( &self, + store: &Store, slot: Slot, head_root: H256, - ) -> Option>>> { + budget: Duration, + ) -> Option { + let mut receiver = { + let mut held = self + .0 + .lock() + .expect("prepared PQ attestations lock poisoned"); + if !held + .as_ref() + .is_some_and(|prepared| prepared.slot == slot && prepared.head_root == head_root) + { + return None; + } + held.take()?.packed + }; + let ready = tokio::time::timeout(budget, receiver.wait_for(Option::is_some)) + .await + .ok()? + .ok()? + .clone()?; + // 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 held - .as_ref() - .is_some_and(|prepared| prepared.slot == slot && prepared.head_root == head_root) - { - return None; + 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 (sender, receiver) = watch::channel(None); + 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(sender) + Some(Claim { packed, abandoned }) } - /// 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, or it did not end in time: block production packs them - /// itself then. - pub async fn collect( - &self, - slot: Slot, - head_root: H256, - budget: Duration, - ) -> Option> { - let mut packed = { - let held = self - .0 - .lock() - .expect("prepared PQ attestations lock poisoned"); - let prepared = held - .as_ref() - .filter(|prepared| prepared.slot == slot && prepared.head_root == head_root)?; - prepared.packed.clone() - }; - let ready = tokio::time::timeout(budget, packed.wait_for(Option::is_some)) - .await - .ok()? - .ok()? - .clone()?; - ready.complete.then_some(ready) + /// 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` was started. + /// Whether a packing for `slot` on `head_root` is registered. #[cfg(test)] fn holds(&self, slot: Slot, head_root: H256) -> bool { self.0 @@ -348,50 +476,89 @@ impl PreparedPqAttestations { #[cfg(test)] mod tests { + use ethlambda_types::beacon::containers::pq::{AggregationBits, Attestation}; + use ethlambda_types::beacon::containers::shared::AttestationData; + use super::*; - /// A preparation stands in place of the packing it holds, under its own - /// slot and head only. + 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`, and the sender a packing would answer through. fn held( slot: Slot, head_root: H256, packed: Option, - ) -> PreparedPqAttestations { + ) -> ( + PreparedPqAttestations, + watch::Sender>>, + ) { let (sender, receiver) = watch::channel(packed.map(Arc::new)); - // Kept open, as a packing under way keeps its sender. - std::mem::forget(sender); - PreparedPqAttestations(Arc::new(Mutex::new(Some(Prepared { + let prepared = PreparedPqAttestations(Arc::new(Mutex::new(Some(Prepared { slot, head_root, packed: receiver, - })))) + abandoned: Arc::new(AtomicBool::new(false)), + })))); + (prepared, sender) } - fn some_packing(complete: bool) -> PackedAttestations { - PackedAttestations { - attestations: Vec::new(), - proof: vec![1, 2, 3], - complete, - } + 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(&[a.clone()], &[b.clone()]), + "equal content, another aggregate" + ); + assert!(!same_aggregates(&[a.clone()], &[a.clone(), b])); + assert!(same_aggregates(&[], &[])); } #[tokio::test] - async fn a_complete_packing_is_collected_for_its_own_slot_and_head() { + async fn a_complete_packing_is_taken_once_for_its_own_slot_and_head() { let root = H256::repeat_byte(1); - let prepared = held(10, root, Some(some_packing(true))); + let store = empty_pool_store(); let budget = Duration::from_millis(50); - let collected = prepared.collect(10, root, budget).await; - assert_eq!(collected.as_deref(), Some(&some_packing(true))); - assert!(prepared.collect(11, root, budget).await.is_none()); + let (prepared, _sender) = held(10, root, Some(packing(true))); + assert!(prepared.take(&store, 11, root, budget).await.is_none()); assert!( prepared - .collect(10, H256::repeat_byte(2), budget) + .take(&store, 10, H256::repeat_byte(2), budget) .await .is_none() ); + let taken = prepared.take(&store, 10, root, budget).await; + assert_eq!(taken.map(|packed| packed.proof), Some(vec![1, 2, 3])); + assert!( + prepared.take(&store, 10, root, budget).await.is_none(), + "taken once" + ); assert!( PreparedPqAttestations::default() - .collect(10, root, budget) + .take(&store, 10, root, budget) .await .is_none() ); @@ -400,37 +567,55 @@ mod tests { /// 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_collected() { + async fn a_partial_packing_is_not_taken() { let root = H256::repeat_byte(1); - let prepared = held(10, root, Some(some_packing(false))); - let collected = prepared.collect(10, root, Duration::from_millis(50)).await; - assert!(collected.is_none()); + 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 (sender, receiver) = watch::channel(None); - let prepared = PreparedPqAttestations(Arc::new(Mutex::new(Some(Prepared { - slot: 10, - head_root: root, - packed: receiver, - })))); + let store = empty_pool_store(); + let (prepared, _sender) = held(10, root, None); assert!( prepared - .collect(10, root, Duration::from_millis(20)) + .take(&store, 10, root, Duration::from_millis(20)) .await .is_none(), "nothing yet, and the budget runs out" ); + + let (prepared, sender) = held(10, root, None); let waiting = { - let prepared = prepared.clone(); - tokio::spawn(async move { prepared.collect(10, root, Duration::from_secs(5)).await }) + 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(some_packing(true)))).unwrap(); - let collected = waiting.await.unwrap(); - assert_eq!(collected.as_deref(), Some(&some_packing(true))); + 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])); } /// A packing that never started (its sender gone without a value) gives @@ -438,37 +623,48 @@ mod tests { #[tokio::test] async fn a_packing_that_never_started_gives_nothing_at_once() { let root = H256::repeat_byte(1); - let (sender, receiver) = watch::channel(None); + let (prepared, sender) = held(10, root, None); drop(sender); - let prepared = PreparedPqAttestations(Arc::new(Mutex::new(Some(Prepared { - slot: 10, - head_root: root, - packed: receiver, - })))); let started = Instant::now(); - assert!( - prepared - .collect(10, root, Duration::from_secs(5)) - .await - .is_none() - ); + 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: claiming the same again - /// leaves the first under way, and another head or slot replaces it. + /// 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); - assert!(first.is_some()); + let first = prepared.claim(10, root).expect("first claim"); assert!(prepared.claim(10, root).is_none(), "already under way"); assert!(prepared.holds(10, root)); - assert!(prepared.claim(10, other).is_some()); + + 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)); - assert!(!prepared.holds(10, root)); - assert!(prepared.claim(11, other).is_some()); - assert!(prepared.holds(11, 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, + }; + assert!(merge_permit(wait, Duration::from_secs(1)).await.is_err()); + 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 4d1f80c01..e91349b1e 100644 --- a/crates/net/rpc/src/beacon/pq_proposal.rs +++ b/crates/net/rpc/src/beacon/pq_proposal.rs @@ -41,7 +41,7 @@ use ethlambda_blockchain::{ PreparedPayloads, PreparedPqAttestations, SyncStatusController, metrics::SyncStatus, payload_attributes::{PqProposal, ProposalError, prepare_pq_proposal, prepared_fee_recipient}, - pq_attestation_packing::{merge_budget, pack_attestations}, + pq_attestation_packing::{PermitWait, merge_budget, pack_attestations}, }; use ethlambda_engine::{EngineClient, types::ClientVersionV1}; use ethlambda_state_transition::beacon::{ @@ -305,19 +305,19 @@ async fn attestations_for_block( ) -> (Vec, Vec) { let slot = state.slot(); if let Some(prepared) = prepared { - // Bounded like a merge here would be: one still running ahead holds - // the merge permit, so starting another would only fall back. - let budget = merge_budget(config, slot).unwrap_or_default(); - if let Some(packed) = prepared.collect(slot, head_root, budget).await { + // Half the merge budget at most, so a packing that does not come + // through still leaves production the time to pack and merge itself. + let budget = merge_budget(config, slot).unwrap_or_default() / 2; + if let Some(packed) = prepared.take(store, slot, head_root, budget).await { info!( %slot, attestations = packed.attestations.len(), proof_bytes = packed.proof.len(), "Collected the PQ attestations packed ahead of the slot" ); - return (packed.attestations.clone(), packed.proof.clone()); + return (packed.attestations, packed.proof); } } - let packed = pack_attestations(store, state, config).await; + let packed = pack_attestations(store, state, config, PermitWait::TryOnce).await; (packed.attestations, packed.proof) } From e2d77175a914d37af4402b4fe785abb4b8371484 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:08:52 -0300 Subject: [PATCH 3/4] fix(pq): abandon a packing production does not use, and wait for a matching one for the whole merge budget Review round 2 on the ahead-of-slot packing: - take() abandons every packing it does not hand over (this slot on another head, an earlier slot, one it gave up waiting for), so it does not take the merge permit from production's own merge. - Production waits for a packing under way for this slot and head up to the whole merge budget: it computes what production would and holds the merge permit production would need, so giving up early could only leave the block with one committee's attestation. - An abandoned packing returns quietly (debug), without the one-attestation fallback warning or the 'packed ahead' line. - docs/beacon_pq.md describes packing ahead and drops it from the known gaps. --- .../blockchain/src/pq_attestation_packing.rs | 146 ++++++++++++------ crates/net/rpc/src/beacon/pq_proposal.rs | 9 +- docs/beacon_pq.md | 30 ++-- 3 files changed, 119 insertions(+), 66 deletions(-) diff --git a/crates/blockchain/src/pq_attestation_packing.rs b/crates/blockchain/src/pq_attestation_packing.rs index a83068c34..bf4fd6f0e 100644 --- a/crates/blockchain/src/pq_attestation_packing.rs +++ b/crates/blockchain/src/pq_attestation_packing.rs @@ -18,8 +18,9 @@ //! (`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 for at most half its -//! merge budget ([`PreparedPqAttestations::take`]). +//! 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 @@ -51,7 +52,7 @@ 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::{info, warn}; +use tracing::{debug, info, warn}; use crate::payload_attributes::advance_for_proposal; @@ -187,7 +188,12 @@ pub async fn pack_attestations( }; let permit = match merge_permit(permit_wait, remaining).await { Ok(permit) => permit, - Err(reason) => return fall_back(reason), + // 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 { @@ -239,26 +245,35 @@ pub async fn pack_attestations( } } +/// 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, &'static str> { +) -> Result, NoPermit> { match permit_wait { PermitWait::TryOnce => MERGE_PERMIT .try_acquire() - .map_err(|_| "a merge is still running"), + .map_err(|_| NoPermit::Refused("a merge is still running")), PermitWait::Wait { abandoned } => { if abandoned.load(Ordering::Acquire) { - return Err("the packing was replaced before its merge"); + return Err(NoPermit::Abandoned); } let permit = tokio::time::timeout(budget, MERGE_PERMIT.acquire()) .await - .map_err(|_| "no merge permit within the budget")? - .map_err(|_| "the merge permit is closed")?; - // Replaced while it waited: leave the permit to the replacement. + .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("the packing was replaced before its merge"); + return Err(NoPermit::Abandoned); } Ok(permit) } @@ -373,6 +388,10 @@ impl PreparedPqAttestations { 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), @@ -389,8 +408,12 @@ impl PreparedPqAttestations { /// `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. + /// 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, @@ -398,24 +421,30 @@ impl PreparedPqAttestations { head_root: H256, budget: Duration, ) -> Option { - let mut receiver = { + let (mut receiver, abandoned) = { let mut held = self .0 .lock() .expect("prepared PQ attestations lock poisoned"); - if !held - .as_ref() - .is_some_and(|prepared| prepared.slot == slot && prepared.head_root == head_root) - { + // 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; } - held.take()?.packed }; - let ready = tokio::time::timeout(budget, receiver.wait_for(Option::is_some)) - .await - .ok()? - .ok()? - .clone()?; // The last holder but this one, once the receiver goes: the sender // dropped after sending. drop(receiver); @@ -499,7 +528,8 @@ mod tests { } /// A preparation holding `packed` (still under way when `None`) for - /// `slot` on `head_root`, and the sender a packing would answer through. + /// `slot` on `head_root`, the sender a packing would answer through, and + /// the packing's abandoned flag. fn held( slot: Slot, head_root: H256, @@ -507,15 +537,17 @@ mod tests { ) -> ( 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: Arc::new(AtomicBool::new(false)), + abandoned: abandoned.clone(), })))); - (prepared, sender) + (prepared, sender, abandoned) } fn empty_pool_store() -> Store { @@ -542,16 +574,10 @@ mod tests { let root = H256::repeat_byte(1); let store = empty_pool_store(); let budget = Duration::from_millis(50); - let (prepared, _sender) = held(10, root, Some(packing(true))); - assert!(prepared.take(&store, 11, root, budget).await.is_none()); - assert!( - prepared - .take(&store, 10, H256::repeat_byte(2), budget) - .await - .is_none() - ); + 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" @@ -564,12 +590,41 @@ mod tests { ); } + /// 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 (prepared, _sender, _) = held(10, root, Some(packing(false))); let taken = prepared .take(&empty_pool_store(), 10, root, Duration::from_millis(50)) .await; @@ -583,7 +638,7 @@ mod tests { let root = H256::repeat_byte(1); let mut stale = packing(true); stale.candidates = vec![aggregate()]; - let (prepared, _sender) = held(10, root, Some(stale)); + let (prepared, _sender, _) = held(10, root, Some(stale)); let taken = prepared .take(&empty_pool_store(), 10, root, Duration::from_millis(50)) .await; @@ -595,16 +650,7 @@ mod tests { 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) = held(10, root, None); - assert!( - prepared - .take(&store, 10, root, Duration::from_millis(20)) - .await - .is_none(), - "nothing yet, and the budget runs out" - ); - - let (prepared, sender) = held(10, root, None); + let (prepared, sender, abandoned) = held(10, root, None); let waiting = { let (prepared, store) = (prepared.clone(), store.clone()); tokio::spawn(async move { @@ -616,6 +662,7 @@ mod tests { 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 @@ -623,7 +670,7 @@ mod tests { #[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); + let (prepared, sender, _) = held(10, root, None); drop(sender); let started = Instant::now(); let taken = prepared @@ -664,7 +711,8 @@ mod tests { let wait = PermitWait::Wait { abandoned: &abandoned, }; - assert!(merge_permit(wait, Duration::from_secs(1)).await.is_err()); + 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 e91349b1e..ea943e0e3 100644 --- a/crates/net/rpc/src/beacon/pq_proposal.rs +++ b/crates/net/rpc/src/beacon/pq_proposal.rs @@ -305,9 +305,12 @@ async fn attestations_for_block( ) -> (Vec, Vec) { let slot = state.slot(); if let Some(prepared) = prepared { - // Half the merge budget at most, so a packing that does not come - // through still leaves production the time to pack and merge itself. - let budget = merge_budget(config, slot).unwrap_or_default() / 2; + // 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, 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 From e0c0a09fff61b624037dead5342fb6c491ff1eda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s=20Gr=C3=BCner?= <47506558+MegaRedHand@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:09:58 -0300 Subject: [PATCH 4/4] test(pq): slices from references in the candidates test (clippy) --- crates/blockchain/src/pq_attestation_packing.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/blockchain/src/pq_attestation_packing.rs b/crates/blockchain/src/pq_attestation_packing.rs index bf4fd6f0e..32e5d7e92 100644 --- a/crates/blockchain/src/pq_attestation_packing.rs +++ b/crates/blockchain/src/pq_attestation_packing.rs @@ -562,10 +562,10 @@ mod tests { &[b.clone(), a.clone()] )); assert!( - !same_aggregates(&[a.clone()], &[b.clone()]), + !same_aggregates(std::slice::from_ref(&a), std::slice::from_ref(&b)), "equal content, another aggregate" ); - assert!(!same_aggregates(&[a.clone()], &[a.clone(), b])); + assert!(!same_aggregates(std::slice::from_ref(&a), &[a.clone(), b])); assert!(same_aggregates(&[], &[])); }