Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions crates/blockchain/src/metrics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1770,6 +1770,82 @@ pub fn observe_beacon_aggregate_end_to_end(duration: Duration) {
LEAN_BEACON_AGGREGATE_END_TO_END_SECONDS.observe(duration.as_secs_f64());
}

/// Record one merge of a PQ block's attestation proofs, when it ends: how
/// long leanVM took, how many child proofs it folded, and the merged proof's
/// size when there is one.
///
/// `phase` is `ahead` for a packing started ahead of the slot and
/// `production` for one block production ran itself. A merge that failed or
/// outlived its budget is observed like any other: its cost is still cost,
/// and [`inc_pq_merges`] says what became of it.
pub fn observe_pq_merge(
phase: &str,
elapsed: Duration,
children: usize,
proof_bytes: Option<usize>,
) {
static LEAN_BEACON_PQ_MERGE_SECONDS: std::sync::LazyLock<HistogramVec> =
std::sync::LazyLock::new(|| {
register_histogram_vec!(
"lean_beacon_pq_merge_seconds",
"Time leanVM took to merge a PQ block's attestation proofs into one, by phase",
&["phase"],
vec![
0.1, 0.2, 0.4, 0.6, 0.8, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0
]
)
.unwrap()
});
static LEAN_BEACON_PQ_MERGE_CHILDREN: std::sync::LazyLock<Histogram> =
std::sync::LazyLock::new(|| {
register_histogram!(
"lean_beacon_pq_merge_children",
"Child proofs one merge of a PQ block's attestation proofs folded",
vec![2.0, 3.0, 4.0, 6.0, 8.0, 12.0, 16.0, 24.0, 32.0, 48.0, 64.0]
)
.unwrap()
});
static LEAN_BEACON_PQ_MERGED_PROOF_SIZE_BYTES: std::sync::LazyLock<Histogram> =
std::sync::LazyLock::new(|| {
register_histogram!(
"lean_beacon_pq_merged_proof_size_bytes",
"Bytes size of a PQ block's merged attestation proof",
vec![
131072.0, 163840.0, 196608.0, 229376.0, 262144.0, 327680.0, 393216.0, 524288.0,
786432.0, 1048576.0
]
)
.unwrap()
});
LEAN_BEACON_PQ_MERGE_SECONDS
.with_label_values(&[phase])
.observe(elapsed.as_secs_f64());
LEAN_BEACON_PQ_MERGE_CHILDREN.observe(children as f64);
if let Some(bytes) = proof_bytes {
LEAN_BEACON_PQ_MERGED_PROOF_SIZE_BYTES.observe(bytes as f64);
}
}

/// Count one packing that had several proofs to merge, by phase (see
/// [`observe_pq_merge`]) and by what became of the merge: `merged`, `failed`,
/// `late` (it outlived its budget) or `skipped` (no time left for it, or
/// another merge held leanVM). All but `merged` pack one committee's
/// attestation in place of everything selected.
pub fn inc_pq_merges(phase: &str, outcome: &str) {
static LEAN_BEACON_PQ_MERGES_TOTAL: std::sync::LazyLock<IntCounterVec> =
std::sync::LazyLock::new(|| {
register_int_counter_vec!(
"lean_beacon_pq_merges_total",
"Packings of a PQ block's attestations with several proofs to merge, by phase and outcome",
&["phase", "outcome"]
)
.unwrap()
});
LEAN_BEACON_PQ_MERGES_TOTAL
.with_label_values(&[phase, outcome])
.inc();
}

/// Count one `engine_getBlobsV2` attempt for a held fulu block, by what came
/// back: `hit` (every blob), `miss` (the execution client answered `null`, so
/// at least one blob is not in its pool) or `error` (transport, timeout or a
Expand Down
140 changes: 127 additions & 13 deletions crates/blockchain/src/pq_attestation_packing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ use ethlambda_types::primitives::H256;
use tokio::sync::{Semaphore, SemaphorePermit, watch};
use tracing::{debug, info, warn};

use crate::metrics;
use crate::payload_attributes::advance_for_proposal;

/// What a PQ block packs: its attestations and the proof of all of them.
Expand Down Expand Up @@ -137,6 +138,16 @@ pub enum PermitWait<'a> {
Wait { abandoned: &'a AtomicBool },
}

impl PermitWait<'_> {
/// The `phase` label the merge metrics record this packing under.
fn phase(self) -> &'static str {
match self {
Self::TryOnce => "production",
Self::Wait { .. } => "ahead",
}
}
}

/// The pool's candidates for a block at `slot`: aggregates from
/// `slot - MIN_ATTESTATION_INCLUSION_DELAY_PQ` and earlier.
fn candidates_for(store: &Store, slot: Slot) -> Vec<Arc<PooledPqAggregate>> {
Expand Down Expand Up @@ -186,15 +197,18 @@ pub async fn pack_attestations(
return unmerged(slot, packed, true, candidates);
}
let children = packed.children.len();
let fall_back = |reason: &str| {
let phase = permit_wait.phase();
// `outcome` is the merge's, as `metrics::inc_pq_merges` counts it.
let fall_back = |outcome: &str, reason: &str| {
metrics::inc_pq_merges(phase, outcome);
warn!(%slot, children, reason, "Packing one PQ attestation instead of merging every proof");
match fallback.clone() {
Some(single) => unmerged(slot, single, false, candidates.clone()),
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");
return fall_back("skipped", "no time left to merge");
};
let permit = match merge_permit(permit_wait, remaining).await {
Ok(permit) => permit,
Expand All @@ -203,19 +217,21 @@ pub async fn pack_attestations(
debug!(%slot, "A PQ attestation packing was abandoned before its merge");
return PackedAttestations::new(Vec::new(), Vec::new(), false, candidates);
}
Err(NoPermit::Refused(reason)) => return fall_back(reason),
Err(NoPermit::Refused(reason)) => return fall_back("skipped", reason),
};
// The wait for the permit came out of the budget.
let Some(remaining) = merge_budget(config, slot) else {
return fall_back("no time left to merge");
return fall_back("skipped", "no time left to merge");
};
let budget_ms = remaining.as_millis() as u64;
let 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 took = started.elapsed();
// Recorded and logged when it ends, deadline or not: what a merge
// costs here, how big it was and how much of the budget it used.
metrics::observe_pq_merge(phase, took, children, proof.as_ref().ok().map(Vec::len));
let signatures: usize = packed
.children
.iter()
Expand All @@ -228,7 +244,7 @@ pub async fn pack_attestations(
children,
signatures,
proof_bytes = proof.as_ref().map_or(0, Vec::len),
took_ms = started.elapsed().as_millis() as u64,
took_ms = took.as_millis() as u64,
budget_ms,
ok = proof.is_ok(),
"Merged PQ attestation proofs"
Expand All @@ -237,6 +253,7 @@ pub async fn pack_attestations(
});
match tokio::time::timeout(remaining, job).await {
Ok(Ok(Ok((packed, proof)))) => {
metrics::inc_pq_merges(phase, "merged");
info!(
%slot,
attestations = packed.attestations.len(),
Expand All @@ -246,12 +263,12 @@ pub async fn pack_attestations(
);
PackedAttestations::new(packed.attestations, proof, true, candidates)
}
Ok(Ok(Err(err))) => fall_back(&format!("the merge failed: {err}")),
Ok(Err(err)) => fall_back(&format!("the merge task failed: {err}")),
Err(_) => fall_back(&format!(
"the merge missed its {} ms budget",
remaining.as_millis()
)),
Ok(Ok(Err(err))) => fall_back("failed", &format!("the merge failed: {err}")),
Ok(Err(err)) => fall_back("failed", &format!("the merge task failed: {err}")),
Err(_) => fall_back(
"late",
&format!("the merge missed its {} ms budget", remaining.as_millis()),
),
}
}

Expand Down Expand Up @@ -715,6 +732,103 @@ mod tests {
}

/// An abandoned packing gives the merge permit up without taking it.
/// A network aggregate of every member of `committee` at `data`'s slot.
fn full_aggregate(
state: &BeaconState,
store: &Store,
data: AttestationData,
committee: u64,
) -> PooledPqAggregate {
use ethlambda_state_transition::beacon::helpers::accessors::CommitteeCacheExt as _;
let members = store
.committee_cache()
.committees(state, data.target.epoch)
.committee(data.slot, committee)
.unwrap()
.to_vec();
let mut aggregation_bits = AggregationBits::with_length(members.len());
for position in 0..members.len() {
aggregation_bits.set(position, true).unwrap();
}
let mut committee_bits = pq::CommitteeBits::new();
committee_bits.set(committee as usize, true).unwrap();
let mut attesting_indices = members;
attesting_indices.sort_unstable();
PooledPqAggregate {
attestation: Attestation {
aggregation_bits,
data,
committee_bits,
},
committee_index: committee,
attesting_indices,
proof: vec![committee as u8; 4].try_into().unwrap(),
}
}

/// A packing with two proofs to merge and no time left for it packs
/// without them, and `/metrics` counts the merge as skipped under the
/// packing's phase: ahead of the slot, or at production.
#[tokio::test]
async fn a_merge_with_no_time_left_is_counted_as_skipped_by_phase() {
use ethlambda_metrics::series_value;
use ethlambda_state_transition::beacon::helpers::accessors::{
get_block_root, get_block_root_at_slot,
};
use ethlambda_state_transition::beacon::helpers::test_state::with_validators_at;
use ethlambda_types::beacon::containers::shared::Checkpoint;
use ethlambda_types::beacon::fork::ForkName;
use ethlambda_types::beacon::preset;

// Two committees per slot under either preset.
let validators = 2 * preset::slots_per_epoch() * preset::target_committee_size();
let state = with_validators_at(ForkName::Pq, validators as usize);
let store = empty_pool_store();
let data_slot = state.slot() - MIN_ATTESTATION_INCLUSION_DELAY_PQ;
let epoch = compute_epoch_at_slot(data_slot);
let data = AttestationData {
slot: data_slot,
index: 0,
beacon_block_root: get_block_root_at_slot(&state, data_slot).unwrap(),
source: state.current_justified_checkpoint(),
target: Checkpoint {
epoch,
root: get_block_root(&state, epoch).unwrap(),
},
};
for committee in 0..2 {
let aggregate = full_aggregate(&state, &store, data, committee);
store.pq_aggregate_pool().insert(aggregate);
}
// Genesis at the UNIX epoch: the state's slot ended long ago.
let mut config = Config::mainnet();
config.genesis_time = 0;
assert!(merge_budget(&config, state.slot()).is_none());

let skipped = |phase: &str| {
let series =
format!(r#"lean_beacon_pq_merges_total{{outcome="skipped",phase="{phase}"}}"#);
series_value(&series).unwrap_or(0.0)
};
let abandoned = AtomicBool::new(false);
let waits = [
("production", PermitWait::TryOnce),
(
"ahead",
PermitWait::Wait {
abandoned: &abandoned,
},
),
];
for (phase, wait) in waits {
let before = skipped(phase);
let packed = pack_attestations(&store, &state, &config, wait).await;
assert!(!packed.complete, "{phase}");
assert!(packed.proof.is_empty(), "{phase}");
assert_eq!(skipped(phase) - before, 1.0, "{phase}");
}
}

#[tokio::test]
async fn an_abandoned_packing_does_not_take_the_merge_permit() {
let abandoned = AtomicBool::new(true);
Expand Down
14 changes: 13 additions & 1 deletion crates/blockchain/state_transition/src/beacon/gossip/pq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,10 @@ pub fn aggregate_stateful_checks(
// [Modified in PQ] [REJECT] The aggregate stark is valid.
let statements = get_attestation_statements(&state, aggregate, &committees)
.map_err(|_| Outcome::Reject(RejectReason::AggregateProof))?;
if !verify_aggregates(&statements, &aggregate_and_proof.proof) {
let verifying = std::time::Instant::now();
let proven = verify_aggregates(&statements, &aggregate_and_proof.proof);
crate::metrics::observe_pq_proof_verification("aggregate", verifying.elapsed());
if !proven {
return Err(Outcome::Reject(RejectReason::AggregateProof));
}
let attesting_indices = get_attesting_indices(&state, aggregate, &committees)
Expand Down Expand Up @@ -1127,6 +1130,14 @@ mod tests {
message: vote_root.0,
};
let proof = stark::prove_aggregates(&[statement], &[vec![vote.0.to_vec()]]).unwrap();
// An aggregate that reaches the proof check has its verification
// timed: the valid one and the unproven one below, not the two
// refused before it.
let verifications = || {
let series = r#"lean_beacon_pq_proof_verification_seconds_count{kind="aggregate"}"#;
ethlambda_metrics::series_value(series).unwrap_or(0.0)
};
let verified_before = verifications();

let valid = aggregate(
&state,
Expand Down Expand Up @@ -1175,6 +1186,7 @@ mod tests {
aggregate_stateful_checks(&store, &unproven),
Err(Outcome::Reject(RejectReason::AggregateProof))
);
assert_eq!(verifications() - verified_before, 2.0);
}

#[test]
Expand Down
15 changes: 14 additions & 1 deletion crates/blockchain/state_transition/src/beacon/stf/pq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,14 @@ pub fn process_stark(
for attestation in body.attestations.iter() {
statements.extend(get_attestation_statements(state, attestation, committees)?);
}
let verifying = std::time::Instant::now();
let proven = verify_aggregates(&statements, &body.proof);
// A block without attestations has nothing to verify: not a sample.
if !statements.is_empty() {
crate::metrics::observe_pq_proof_verification("block", verifying.elapsed());
}
verify(
verify_aggregates(&statements, &body.proof),
proven,
"process_stark: stark.VerifyAggregates(statements, body.proof)",
)
}
Expand Down Expand Up @@ -1203,6 +1209,12 @@ mod tests {
proof: proof.try_into().expect("far below MAX_STARK_PROOF_SIZE"),
..pq::BeaconBlockBody::empty()
};
// Each verification is timed as a block's, a refused proof's too.
let timed = || {
let series = r#"lean_beacon_pq_proof_verification_seconds_count{kind="block"}"#;
ethlambda_metrics::series_value(series).unwrap_or(0.0)
};
let before = timed();
// The reference encoding: the signatures, in statement order.
let proof = signatures.concat();
assert!(process_stark(&state, &body_with(proof.clone()), &committees).is_ok());
Expand All @@ -1213,6 +1225,7 @@ mod tests {
reversed.reverse();
let reversed = reversed.concat();
assert!(process_stark(&state, &body_with(reversed), &committees).is_err());
assert!(timed() - before >= 3.0);
}

/// A full-committee attestation to `data_slot` voting for the head and
Expand Down
Loading
Loading