diff --git a/CLAUDE.md b/CLAUDE.md index b703ca42c..4e4fb0b09 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -671,6 +671,16 @@ recomputation), and p2p's column rows: `column_checks::column_rows` (after the c `passed_rows` called directly by the gossip-accept path and by this node's own fulu columns. See [`docs/telemetry.md`](docs/telemetry.md). +The same crate holds the **PQ timing export** (`ethlambda_telemetry::pq_timing`, +`--pq-timing-output`): PQ vote receipts and verdicts and every attestation proof, as JSON-lines +events in a run directory, in the schema the PQ devnets' clients share (Lighthouse's +`scripts/pq-measurement`, 1). Another global sink, installed in `run_node` after leanVM and closed +in `wait_for_shutdown`; its emitters (`message_received`, `validated`, `Job`, `proposal_snapshot`) +build nothing when it is off. The emit sites are p2p's `beacon::pq::triage` and `verdict::report`, +rpc's seat prover and `pq_proposal`, and `pq_attestation_packing`. Tests of an emit site capture +the events in memory (`pq_timing::testing::capture`, behind the crate's `test-utils` feature); the +session is the process's, so one capture runs at a time. See [`docs/pq_timing.md`](docs/pq_timing.md). + ## Beacon Chain types (`crates/common/types/src/beacon/`) `ethlambda-types` carries the **Ethereum Beacon Chain** containers (phase0 diff --git a/Cargo.lock b/Cargo.lock index 18bcc9fd6..8f732cc82 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2189,6 +2189,7 @@ dependencies = [ "ethlambda-network-api", "ethlambda-state-transition", "ethlambda-storage", + "ethlambda-telemetry", "ethlambda-test-fixtures", "ethlambda-types", "ethlambda-validator", @@ -2286,8 +2287,11 @@ dependencies = [ "reqwest", "serde", "serde_json", + "sha2", + "tempfile", "tokio", "tracing", + "zstd", ] [[package]] @@ -8973,6 +8977,24 @@ version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" +[[package]] +name = "zstd" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50adf04cf3ec914b0b9905c9dde90c80fe74bfd701e331fc80a39c512c525278" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "7.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498d94ad68720c89b4fbe41b9090850651e68cb2dd9210ce7ffbff3a94653819" +dependencies = [ + "zstd-sys", +] + [[package]] name = "zstd-sys" version = "2.1.2+zstd.1.5.7" diff --git a/Cargo.toml b/Cargo.toml index 05a8eb9a6..9dfbbd5bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -88,6 +88,9 @@ thiserror = "2.0.9" serde = { version = "1", features = ["derive"] } serde_json = "1.0.117" serde_yaml_ng = "0.10" +# The PQ timing export's chunks (`ethlambda-telemetry`). `zstd-sys` is already +# built for RocksDB; this adds the two safe wrappers over it. +zstd = "0.13" hex = "0.4" hmac = "0.12" base64 = "0.22" diff --git a/bin/ethlambda/src/cli.rs b/bin/ethlambda/src/cli.rs index 5f86eec0e..5e485dd5c 100644 --- a/bin/ethlambda/src/cli.rs +++ b/bin/ethlambda/src/cli.rs @@ -427,6 +427,18 @@ pub(crate) struct MainnetOptions { #[arg(long, default_value_t = 0)] pub(crate) pq_prover_threads: usize, + /// Record PQ gossip and proving timings under this directory, one + /// sub-directory per run, in the format the PQ devnets' clients share + /// (schema 1 of Lighthouse's `scripts/pq-measurement`): when each PQ + /// attestation and aggregate arrived and what validation made of it, and + /// every committee proof and block-proof merge this node made. + /// + /// Off when unset, and read only on a network that schedules the PQ + /// fork. A run keeps at most 8 GiB, removing its oldest events first. See + /// `docs/pq_timing.md`. + #[arg(long, value_name = "DIR")] + pub(crate) pq_timing_output: Option, + /// Base URL of a builder API endpoint, normally MEV-Boost (for example /// `http://127.0.0.1:18550`) or a relay directly. Without it every block /// is built locally, and `register_validator` answers 500 so a validator @@ -1209,6 +1221,18 @@ mod tests { } } + /// `--pq-timing-output` names a directory, and is off without it. + #[test] + fn the_pq_timing_output_is_a_directory_and_off_by_default() { + assert_eq!(parse_beacon(beacon_args()).mainnet.pq_timing_output, None); + let mut args = beacon_args(); + args.extend(["--pq-timing-output", "/data/pq-timing"]); + assert_eq!( + parse_beacon(args).mainnet.pq_timing_output, + Some(PathBuf::from("/data/pq-timing")) + ); + } + /// A client name alone configures nothing, so it is a usage error rather /// than a flag silently ignored. /// diff --git a/bin/ethlambda/src/main.rs b/bin/ethlambda/src/main.rs index 349b83989..054ff7f1a 100644 --- a/bin/ethlambda/src/main.rs +++ b/bin/ethlambda/src/main.rs @@ -10,6 +10,7 @@ mod keygen; mod network; mod pq_keys; mod pq_prover_check; +mod pq_timing; mod shutdown; mod slashing_protection; mod validator; @@ -494,6 +495,28 @@ async fn run_node(options: Options) -> eyre::Result<()> { ); stark::install_leanvm(config).wrap_err("cannot start leanVM's prover")?; } + // After the prover, whose backend the run names. + if let Some(output) = &mainnet.pq_timing_output { + if pq_epoch == ethlambda_types::beacon::constants::FAR_FUTURE_EPOCH { + warn!( + network = source.name(), + "--pq-timing-output is set, but this network does not schedule the PQ fork: nothing to record" + ); + } else { + let run = pq_timing::run( + output.clone(), + source.name(), + source.genesis(), + source.config(), + mainnet.pq_prover_threads, + ); + let run_dir = + ethlambda_telemetry::pq_timing::install(run).wrap_err_with(|| { + format!("cannot record PQ timing under {}", output.display()) + })?; + info!(run_dir = %run_dir.display(), "Recording PQ timing"); + } + } (Some(source), bootnodes) } }; @@ -1242,6 +1265,9 @@ async fn wait_for_shutdown(node: RunningNode) { let _ = node.http.await; // After the actors, which are the only emitters, have stopped. ethlambda_telemetry::shutdown(TELEMETRY_FLUSH_TIMEOUT).await; + // The PQ timing run's last chunk and its end. A proof still running on a + // blocking thread reports to nobody after this. + ethlambda_telemetry::pq_timing::close(); info!("Shutdown complete"); } diff --git a/bin/ethlambda/src/pq_timing.rs b/bin/ethlambda/src/pq_timing.rs new file mode 100644 index 000000000..4cb34c9a9 --- /dev/null +++ b/bin/ethlambda/src/pq_timing.rs @@ -0,0 +1,101 @@ +//! What a `--pq-timing-output` run records about itself: the network, the +//! prover, and where in a slot this node does each step of PQ aggregation. +//! The export itself is `ethlambda_telemetry::pq_timing`; see +//! `docs/pq_timing.md`. + +use std::path::PathBuf; +use std::time::Duration; + +use ethlambda_blockchain::payload_attributes::lookahead_start; +use ethlambda_crypto::stark::{ + self, + leanvm::{LEANVM_REV, LeanVmConfig, PROTOCOL_VERSION}, +}; +use ethlambda_state_transition::beacon::fork_choice::{ + get_aggregation_cutoff_ms, get_attestation_due_ms, get_pq_aggregate_due_ms, +}; +use ethlambda_telemetry::pq_timing::{Prover, Run, Timing}; +use ethlambda_types::beacon::{ + config::Config, fork::ForkName, preset::MIN_ATTESTATION_INCLUSION_DELAY_PQ, +}; + +use crate::beacon::Genesis; + +/// The run for a node on `network`, recording under `output`, whose prover +/// was asked for `prover_threads` threads (0 for one per core). Call after +/// the prover is installed: the run names the backend in use. +pub(crate) fn run( + output: PathBuf, + network: &str, + genesis: Genesis, + config: &Config, + prover_threads: usize, +) -> Run { + let cores = std::thread::available_parallelism().map_or(1, usize::from); + Run { + output, + network: network.to_string(), + client_version: crate::version::client_version().to_string(), + genesis_time: genesis.genesis_time, + genesis_validators_root: genesis.genesis_validators_root.0, + prover: Prover { + backend: stark::backend_name(), + leanvm_revision: LEANVM_REV, + leanvm_protocol_version: PROTOCOL_VERSION, + log_inv_rate: LeanVmConfig::default().log_inv_rate, + // Left to leanVM, the count is its own: one per physical core. + threads: (prover_threads > 0).then(|| prover_threads.min(cores)), + threads_configured: prover_threads, + }, + timing: timing(config), + } +} + +/// Where in a slot this node does each step, on `config`'s PQ timing: the +/// first aggregator seat's cutoff and broadcast, and when the merge ahead of +/// a proposal starts, counted from the start of its votes' slot. +fn timing(config: &Config) -> Timing { + let ms = Duration::from_millis; + let slot_ms = config.slot_duration_ms; + let pq_epoch = config.fork_epoch(ForkName::Pq); + let aggregate_due = get_pq_aggregate_due_ms(0, config); + // A block packs votes from `MIN_ATTESTATION_INCLUSION_DELAY_PQ` slots + // back, and its packing starts with its payload build, in the slot + // before it. + let slots_before_packing = MIN_ATTESTATION_INCLUSION_DELAY_PQ.saturating_sub(1); + Timing { + slot: ms(slot_ms), + attestation_due: ms(get_attestation_due_ms(pq_epoch, config)), + committee_collection: ms(get_aggregation_cutoff_ms(0, config)), + aggregator_delay: ms(get_pq_aggregate_due_ms(1, config).saturating_sub(aggregate_due)), + aggregate_due: ms(aggregate_due), + initial_merge: ms(slots_before_packing.saturating_mul(slot_ms)) + lookahead_start(slot_ms), + proposal_lag_slots: MIN_ATTESTATION_INCLUSION_DELAY_PQ, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A 12-second slot: attestations due at 3 s, the first seat collects + /// until 4.8 s and broadcasts at 7.2 s, each next seat 0.6 s later, and a + /// block's packing starts 8 s into the slot before it, 20 s after its + /// newest votes' slot began. + #[test] + fn the_timing_is_the_pq_slots_own() { + let config = Config::mainnet() + .with_fork_epoch(ForkName::Gloas, 0) + .with_fork_epoch(ForkName::Eip8483, 0) + .with_fork_epoch(ForkName::Pq, 0); + let timing = timing(&config); + let ms = Duration::from_millis; + assert_eq!(timing.slot, ms(12_000)); + assert_eq!(timing.attestation_due, ms(3_000)); + assert_eq!(timing.committee_collection, ms(4_800)); + assert_eq!(timing.aggregator_delay, ms(600)); + assert_eq!(timing.aggregate_due, ms(7_200)); + assert_eq!(timing.initial_merge, ms(20_000)); + assert_eq!(timing.proposal_lag_slots, 2); + } +} diff --git a/crates/blockchain/Cargo.toml b/crates/blockchain/Cargo.toml index d19d963be..e0f66b6bf 100644 --- a/crates/blockchain/Cargo.toml +++ b/crates/blockchain/Cargo.toml @@ -39,6 +39,9 @@ hex.workspace = true # `test_state`'s validator keys, so a test can sign a block that has to pass # the proposer-signature precheck before its blobs are asked for. ethlambda-state-transition = { workspace = true, features = ["test-utils"] } +# `test-utils` for `pq_timing::testing`: the PQ timing events a packing emits, +# captured in memory. +ethlambda-telemetry = { workspace = true, features = ["test-utils"] } hex = { workspace = true } libssz.workspace = true libssz-types.workspace = true diff --git a/crates/blockchain/src/payload_attributes.rs b/crates/blockchain/src/payload_attributes.rs index c8a10af2f..62eab8566 100644 --- a/crates/blockchain/src/payload_attributes.rs +++ b/crates/blockchain/src/payload_attributes.rs @@ -724,7 +724,7 @@ pub(crate) fn next_payload( /// How far into a slot the next slot's attributes are first published: a /// third of a slot before it ends, Lighthouse's default lookahead. -pub(crate) fn lookahead_start(slot_duration_ms: u64) -> Duration { +pub fn lookahead_start(slot_duration_ms: u64) -> Duration { Duration::from_millis(slot_duration_ms - slot_duration_ms / 3) } diff --git a/crates/blockchain/src/pq_attestation_packing.rs b/crates/blockchain/src/pq_attestation_packing.rs index 019d236d1..5055d750c 100644 --- a/crates/blockchain/src/pq_attestation_packing.rs +++ b/crates/blockchain/src/pq_attestation_packing.rs @@ -54,6 +54,7 @@ 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_telemetry::pq_timing; use ethlambda_types::ShortRoot; use ethlambda_types::beacon::config::Config; use ethlambda_types::beacon::containers::{BeaconState, pq}; @@ -146,6 +147,16 @@ impl PermitWait<'_> { Self::Wait { .. } => "ahead", } } + + /// What the timing export calls this packing's merge: the first round + /// ahead of the slot, the second at production, which runs only when the + /// first cannot be used. + fn work(self) -> pq_timing::Work { + match self { + Self::TryOnce => pq_timing::Work::Improvement, + Self::Wait { .. } => pq_timing::Work::Initial, + } + } } /// The pool's candidates for a block at `slot`: aggregates from @@ -191,16 +202,29 @@ pub async fn pack_attestations( if packed.attestations.is_empty() { return PackedAttestations::new(Vec::new(), Vec::new(), true, candidates); } + // The timing export's job for this packing: its votes are of the newest + // slot a block at `slot` may include. + let reference_slot = slot.saturating_sub(MIN_ATTESTATION_INCLUSION_DELAY_PQ); + let job = pq_timing::job(permit_wait.work(), slot, reference_slot, Instant::now()); // One child's proof is the block's as it is; more must be merged. let fallback = packed.first_unmerged(); if packed.children.len() == 1 { - return unmerged(slot, packed, true, candidates); + let packed = unmerged(slot, packed, true, candidates); + if packed.complete { + job.ready(|| ready_fields(&packed, false)); + } + return packed; } let children = packed.children.len(); 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); + // A failed or late merge has its own `proof_finished` event. + if outcome == "skipped" { + let fields = || pq_timing::json!({"reason": reason, "input_proof_count": children}); + job.outcome("skipped", fields); + } warn!(%slot, children, reason, "Packing one PQ attestation instead of merging every proof"); match fallback.clone() { Some(single) => unmerged(slot, single, false, candidates.clone()), @@ -224,20 +248,32 @@ pub async fn pack_attestations( 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 merging = job.clone(); + let merge = tokio::task::spawn_blocking(move || { let _permit = permit; - let started = Instant::now(); - let proof = packed.merge().map_err(|err| err.to_string()); - 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() .flat_map(|(statements, _)| statements) .map(|statement| statement.pubkeys.len()) .sum(); + let records = packed.attestations.len(); + let timing_fields = move || { + pq_timing::json!({ + "input_proof_count": children, + "records": records, + "claims": signatures, + }) + }; + merging.started(timing_fields); + let started = Instant::now(); + let proof = packed.merge().map_err(|err| err.to_string()); + 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 late = took >= remaining; + merging.finished(took, late, proof.as_deref().ok(), timing_fields); info!( %slot, attestations = packed.attestations.len(), @@ -251,7 +287,7 @@ pub async fn pack_attestations( ); proof.map(|proof| (packed, proof)) }); - match tokio::time::timeout(remaining, job).await { + match tokio::time::timeout(remaining, merge).await { Ok(Ok(Ok((packed, proof)))) => { metrics::inc_pq_merges(phase, "merged"); info!( @@ -261,7 +297,9 @@ pub async fn pack_attestations( proof_bytes = proof.len(), "Packed PQ attestations" ); - PackedAttestations::new(packed.attestations, proof, true, candidates) + let packed = PackedAttestations::new(packed.attestations, proof, true, candidates); + job.ready(|| ready_fields(&packed, true)); + packed } Ok(Ok(Err(err))) => fall_back("failed", &format!("the merge failed: {err}")), Ok(Err(err)) => fall_back("failed", &format!("the merge task failed: {err}")), @@ -272,6 +310,18 @@ pub async fn pack_attestations( } } +/// What a `candidate_ready` event says of a complete packing: the proof the +/// block would carry, how many attestations it covers, and whether leanVM +/// was called for it (`merged`) or one child's proof is the block's as it is. +fn ready_fields(packed: &PackedAttestations, merged: bool) -> pq_timing::Value { + pq_timing::json!({ + "proof_id": pq_timing::proof_id(&packed.proof), + "records": packed.attestations.len(), + "recursive_depth": u64::from(merged), + "backend_call": merged, + }) +} + /// Why [`merge_permit`] gave no permit. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum NoPermit { @@ -768,7 +818,8 @@ mod tests { /// 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. + /// packing's phase: ahead of the slot, or at production. The timing + /// export gets a job outcome for each, as the round it would have been. #[tokio::test] async fn a_merge_with_no_time_left_is_counted_as_skipped_by_phase() { use ethlambda_metrics::series_value; @@ -820,6 +871,9 @@ mod tests { }, ), ]; + // Nothing else in this crate's tests packs, so every event captured + // is this test's. + let capture = pq_timing::testing::capture(); for (phase, wait) in waits { let before = skipped(phase); let packed = pack_attestations(&store, &state, &config, wait).await; @@ -827,6 +881,21 @@ mod tests { assert!(packed.proof.is_empty(), "{phase}"); assert_eq!(skipped(phase) - before, 1.0, "{phase}"); } + + let events = capture.events(); + assert_eq!(events.len(), 2, "{events:?}"); + let slot = state.slot(); + for (event, (work, round)) in events.iter().zip([("improvement", 2), ("initial", 1)]) { + assert_eq!(event["kind"], "job_outcome"); + assert_eq!(event["outcome"], "skipped"); + assert_eq!(event["work"], work); + assert_eq!(event["round"], round); + assert_eq!(event["slot"], slot); + assert_eq!(event["reference_slot"], data_slot); + assert_eq!(event["sequence_id"], format!("production:{slot}")); + assert_eq!(event["input_proof_count"], 2); + assert_eq!(event["reason"], "no time left to merge"); + } } #[tokio::test] diff --git a/crates/common/telemetry/Cargo.toml b/crates/common/telemetry/Cargo.toml index c543a2d96..a06e2df79 100644 --- a/crates/common/telemetry/Cargo.toml +++ b/crates/common/telemetry/Cargo.toml @@ -5,12 +5,20 @@ edition.workspace = true rust-version.workspace = true license.workspace = true +[features] +# Exposes `pq_timing::testing`, which records the PQ timing events into +# memory, for the crates whose tests check their own emit sites. +test-utils = [] + [dependencies] ethlambda-metrics.workspace = true hex.workspace = true reqwest.workspace = true serde.workspace = true serde_json.workspace = true +# The PQ timing export: proof ids, and its chunks' compression. +sha2.workspace = true +zstd.workspace = true tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] } tracing.workspace = true @@ -18,4 +26,5 @@ tracing.workspace = true # A stand-in ClickHouse HTTP endpoint for the writer tests. Already in the # lockfile through ethlambda-rpc, so this adds no new crate. axum = "0.8.1" +tempfile = "3" tokio = { workspace = true, features = ["macros", "net", "rt", "sync", "time"] } diff --git a/crates/common/telemetry/src/lib.rs b/crates/common/telemetry/src/lib.rs index 14537154e..1515bbc64 100644 --- a/crates/common/telemetry/src/lib.rs +++ b/crates/common/telemetry/src/lib.rs @@ -7,6 +7,7 @@ mod event; mod metrics; +pub mod pq_timing; mod writer; use std::sync::{Arc, Mutex, OnceLock}; diff --git a/crates/common/telemetry/src/metrics.rs b/crates/common/telemetry/src/metrics.rs index 32a58d79d..b23601281 100644 --- a/crates/common/telemetry/src/metrics.rs +++ b/crates/common/telemetry/src/metrics.rs @@ -44,3 +44,18 @@ pub(crate) fn inc_rows_dropped(rows: u64) { pub(crate) fn inc_insert_failures() { INSERT_FAILURES.inc(); } + +/// Count one PQ timing event the export's queue had no room for, by class +/// (`receipt`, `validation`, `work`, `status`). The run's `run.json` counts +/// them too; this is where a running node says its export is falling behind. +pub(crate) fn inc_pq_timing_dropped(class: &str) { + static DROPPED: LazyLock = LazyLock::new(|| { + register_int_counter_vec!( + "lean_beacon_pq_timing_dropped_events_total", + "PQ timing events the export dropped because its queue was full, by class", + &["class"] + ) + .unwrap() + }); + DROPPED.with_label_values(&[class]).inc(); +} diff --git a/crates/common/telemetry/src/pq_timing.rs b/crates/common/telemetry/src/pq_timing.rs new file mode 100644 index 000000000..889e077c4 --- /dev/null +++ b/crates/common/telemetry/src/pq_timing.rs @@ -0,0 +1,935 @@ +//! PQ gossip and proving timings, exported to a local directory in the format +//! the PQ devnets' clients share (`--pq-timing-output`). +//! +//! Schema 1 of Lighthouse's `scripts/pq-measurement`, which Prysm, Teku and +//! Lodestar write too, so one report script draws every client's runs side by +//! side. A run is a directory holding `run.json` (what ran, on what, and the +//! slot's timing) and `events-NNNNNN.jsonl.zst` chunks of JSON lines: +//! +//! - `message_received`: a PQ attestation or aggregate reached this node from +//! gossip, stamped when gossipsub delivered it. +//! - `validated`: the verdict that message got, and how long after. +//! - `proof_started`, `proof_finished`: one leanVM proof, of a committee's +//! signatures (`work: "committee"`) or of a block's merged attestation +//! proofs (`"initial"` ahead of the slot, `"improvement"` at production). +//! - `candidate_ready`: a proof is where its consumer takes it from. +//! - `job_outcome`: a proof that was due and was not made, and why. +//! - `proposal_snapshot`: what block production had when it built the block. +//! +//! Every proof event carries the job's fields ([`Job`]). An event is placed +//! on a timeline by its `reference_slot`, the slot of the votes it is about: +//! a committee's own slot, and two slots before the block a merge is for. +//! +//! Off unless [`install`] ran. Every emitter then returns before it builds +//! anything, so a node that does not record pays one atomic load per call. +//! See `docs/pq_timing.md`. + +mod hardware; +mod recorder; + +use std::io; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, RwLock}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use recorder::{Class, Limits, Record, Recorder}; +use sha2::{Digest as _, Sha256}; + +/// Re-exported for the emit sites, whose fields are JSON objects. +pub use serde_json::{Value, json}; + +/// The schema this module writes: Lighthouse's `scripts/pq-measurement`, 1. +pub const SCHEMA_VERSION: u64 = 1; + +/// What a run records about itself in `run.json`. +#[derive(Debug, Clone)] +pub struct Run { + /// The directory runs are created in, one sub-directory each. + pub output: PathBuf, + /// The network's `CONFIG_NAME`. + pub network: String, + pub client_version: String, + /// Seconds since the UNIX epoch. + pub genesis_time: u64, + pub genesis_validators_root: [u8; 32], + pub prover: Prover, + pub timing: Timing, +} + +/// The prover the run's proofs were made with. +#[derive(Debug, Clone)] +pub struct Prover { + /// `leanvm`, or `reference` on a network that never installed it. + pub backend: &'static str, + pub leanvm_revision: &'static str, + pub leanvm_protocol_version: u32, + pub log_inv_rate: u8, + /// The prover's threads, when the operator set them. `None` when leanVM + /// chose, one per core. + pub threads: Option, + /// What the operator asked for, 0 for one per core. + pub threads_configured: usize, +} + +/// Where in a slot this client does each step, from the start of the vote +/// slot: what a report draws its reference lines at. +#[derive(Debug, Clone, Copy)] +pub struct Timing { + pub slot: Duration, + /// The attestation deadline. + pub attestation_due: Duration, + /// When the first aggregator seat stops collecting signatures. + pub committee_collection: Duration, + /// How much later each following seat does. + pub aggregator_delay: Duration, + /// When the first seat broadcasts. + pub aggregate_due: Duration, + /// When the merge ahead of a proposal starts, counted from the start of + /// the slot `proposal_lag_slots` before the proposal's. + pub initial_merge: Duration, + /// How many slots after its votes a block may first include them. + pub proposal_lag_slots: u64, +} + +/// Where events go: a run on disk, or memory for a test. +#[derive(Debug)] +enum Sink { + Disk(Recorder), + #[cfg(any(test, feature = "test-utils"))] + Memory(std::sync::Mutex>), +} + +#[derive(Debug)] +struct Session { + sink: Sink, + /// What every event's `mono_ns` counts from. + origin: Instant, + next_job: AtomicU64, +} + +impl Session { + fn new(sink: Sink) -> Arc { + Arc::new(Self { + sink, + origin: Instant::now(), + next_job: AtomicU64::new(0), + }) + } + + fn healthy(&self) -> bool { + match &self.sink { + Sink::Disk(recorder) => recorder.healthy(), + #[cfg(any(test, feature = "test-utils"))] + Sink::Memory(_) => true, + } + } + + fn emit(&self, class: Class, kind: &'static str, wall_ns: u64, at: Instant, fields: Value) { + let record = Record { + kind, + wall_ns, + mono_ns: ns(at.saturating_duration_since(self.origin)), + fields, + }; + match &self.sink { + Sink::Disk(recorder) => recorder.emit(class, record), + #[cfg(any(test, feature = "test-utils"))] + Sink::Memory(events) => { + let event = serde_json::to_value(&record).expect("a record is a JSON object"); + events.lock().expect("captured events lock").push(event); + } + } + } + + fn emit_now(&self, class: Class, kind: &'static str, fields: Value) { + self.emit(class, kind, wall_now_ns(), Instant::now(), fields); + } +} + +/// The session events go to. `ENABLED` is read first, so a node that does +/// not record takes no lock. +static ACTIVE: RwLock>> = RwLock::new(None); +static ENABLED: AtomicBool = AtomicBool::new(false); + +fn active() -> Option> { + if !ENABLED.load(Ordering::Relaxed) { + return None; + } + let session = ACTIVE.read().expect("PQ timing session lock").clone()?; + session.healthy().then_some(session) +} + +fn activate(session: Arc) -> bool { + let mut active = ACTIVE.write().expect("PQ timing session lock"); + if active.is_some() { + return false; + } + *active = Some(session); + ENABLED.store(true, Ordering::Relaxed); + true +} + +fn deactivate() -> Option> { + let mut active = ACTIVE.write().expect("PQ timing session lock"); + ENABLED.store(false, Ordering::Relaxed); + active.take() +} + +/// Start a run under `run.output` and route every later event to it. Returns +/// the run's directory. +/// +/// Fails when the directory cannot be created or written, or a run is +/// already being recorded. +pub fn install(run: Run) -> io::Result { + let already = || { + io::Error::new( + io::ErrorKind::AlreadyExists, + "a PQ timing run is already being recorded", + ) + }; + // Before a directory is made for a run that would not be recorded. + if ACTIVE.read().expect("PQ timing session lock").is_some() { + return Err(already()); + } + let started = wall_now_ns(); + let id = format!("{started}-{:016x}", random_u64()); + let manifest = metadata(&run, &id, started); + let recorder = Recorder::open(&run.output, &id, manifest, Limits::DEFAULT)?; + let directory = recorder.directory().to_path_buf(); + if !activate(Session::new(Sink::Disk(recorder))) { + return Err(already()); + } + Ok(directory) +} + +/// Finish the run: its last chunk is closed and listed, and `run.json` gets +/// its end. Waits for the writer. Events emitted afterwards go nowhere. A +/// no-op without [`install`]. +pub fn close() { + if let Some(session) = deactivate() + && let Sink::Disk(recorder) = &session.sink + { + recorder.close(); + } +} + +/// Whether a run is being recorded. The emitters check it themselves; this +/// is for a caller that would otherwise compute something only they read. +pub fn enabled() -> bool { + active().is_some() +} + +fn metadata(run: &Run, id: &str, started_unix_ns: u64) -> Value { + let timing = &run.timing; + json!({ + "schema_version": SCHEMA_VERSION, + "run_id": id, + "started_unix_ns": started_unix_ns, + // No observer mode: every event is this node's own workload. + "observer": false, + "network": run.network, + "genesis_time": run.genesis_time, + "genesis_slot": 0, + "genesis_validators_root": hex_0x(&run.genesis_validators_root), + "client": "ethlambda", + "ethlambda_version": run.client_version, + "leanvm_revision": run.prover.leanvm_revision, + "leanvm_protocol_version": run.prover.leanvm_protocol_version, + "prover_backend": run.prover.backend, + "prover_log_inv_rate": run.prover.log_inv_rate, + // leanVM picks its CPU tier itself and does not report it. + "prover_cpu_profile": null, + "prover_cpu_profile_requested": std::env::var("LEANVM_TIER").ok(), + "prover_threads": run.prover.threads, + "prover_threads_configured": run.prover.threads_configured, + "hardware": hardware::hardware(), + "timing": { + "slot_ns": ns(timing.slot), + "attestation_ns": ns(timing.attestation_due), + "committee_collection_ns": ns(timing.committee_collection), + "aggregator_position": 0, + "aggregator_delay_ns": ns(timing.aggregator_delay), + "aggregate_ns": ns(timing.aggregate_due), + "initial_merge_ns": ns(timing.initial_merge), + "proposal_lag_slots": timing.proposal_lag_slots, + }, + "receive_point": "gossipsub delivery, stamped before Snappy decompression and SSZ \ + decode and after gossipsub's duplicate cache", + }) +} + +/// Which of the two vote messages a receipt is of, as the schema names them. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MessageKind { + /// A single attestation, from a subnet. + Individual, + /// A committee's aggregate and its proof. + Aggregate, +} + +impl MessageKind { + fn label(self) -> &'static str { + match self { + Self::Individual => "individual", + Self::Aggregate => "aggregate", + } + } +} + +/// A vote whose receipt was recorded: what its `validated` event names it by. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Vote { + kind: MessageKind, + slot: u64, +} + +/// A PQ attestation or aggregate as it arrived. +#[derive(Debug, Clone, Copy)] +pub struct Receipt<'a> { + pub kind: MessageKind, + /// The gossipsub message id. + pub message_id: &'a [u8], + /// The slot of the vote. + pub slot: u64, + pub committee: Option, + /// The attestation subnet, for a single attestation. + pub subnet: Option, + /// The decompressed SSZ's length. + pub message_bytes: usize, + /// One for a single attestation, the aggregate's attesters otherwise. + pub signer_count: usize, + /// `hash_tree_root` of the attestation data. + pub vote_data_root: [u8; 32], +} + +/// Record that the vote `build` describes reached this node at +/// `received_at`. Returns what [`validated`] needs once it has a verdict, or +/// `None` when nothing is recorded, in which case `build` did not run. +pub fn message_received<'a>( + received_at: Instant, + build: impl FnOnce() -> Receipt<'a>, +) -> Option { + let session = active()?; + let receipt = build(); + let wall_ns = wall_now_ns().saturating_sub(ns(received_at.elapsed())); + let fields = json!({ + "message_kind": receipt.kind.label(), + "message_id": hex_0x(receipt.message_id), + "source": "network", + "reference_slot": receipt.slot, + "slot": receipt.slot, + "committee": receipt.committee, + "subnet": receipt.subnet, + "message_bytes": receipt.message_bytes, + "byte_basis": "decoded_ssz", + "signer_count": receipt.signer_count, + "vote_data_root": hex_0x(&receipt.vote_data_root), + }); + session.emit( + Class::Receipt, + "message_received", + wall_ns, + received_at, + fields, + ); + Some(Vote { + kind: receipt.kind, + slot: receipt.slot, + }) +} + +/// Record the verdict of a vote whose receipt was recorded. `outcome` is one +/// of the schema's: `accepted`, `duplicate`, `rejected`, `ignored`, +/// `queue_dropped`. +pub fn validated(vote: Vote, message_id: &[u8], received_at: Instant, outcome: &'static str) { + let Some(session) = active() else { + return; + }; + let fields = json!({ + "message_kind": vote.kind.label(), + "message_id": hex_0x(message_id), + "source": "network", + "reference_slot": vote.slot, + "slot": vote.slot, + "outcome": outcome, + "receipt_to_validation_ns": ns(received_at.elapsed()), + }); + session.emit_now(Class::Validation, "validated", fields); +} + +/// What a proof is of. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Work { + /// One committee's signatures, for an aggregator seat of this node. + Committee, + /// A block's attestation proofs merged ahead of its slot: round 1. + Initial, + /// The same at block production, when the merge ahead cannot be used: + /// round 2. + Improvement, +} + +impl Work { + fn label(self) -> &'static str { + match self { + Self::Committee => "committee", + Self::Initial => "initial", + Self::Improvement => "improvement", + } + } + + fn round(self) -> u64 { + match self { + Self::Committee | Self::Initial => 1, + Self::Improvement => 2, + } + } +} + +/// One proof this node set out to make, and the events about it. Every +/// method is a no-op, and builds nothing, when no run is being recorded. +#[derive(Debug, Clone)] +pub struct Job { + session: Option>, + id: u64, + work: Work, + slot: u64, + reference_slot: u64, + enqueued: Instant, + enqueued_wall_ns: u64, +} + +/// A job of `work` for `slot` (the committee's slot, or the block's), whose +/// votes are of `reference_slot`, wanted since `enqueued`: what its proof's +/// `queue_wait_ns` is counted from. +pub fn job(work: Work, slot: u64, reference_slot: u64, enqueued: Instant) -> Job { + let session = active(); + let id = session.as_ref().map_or(0, |session| { + session.next_job.fetch_add(1, Ordering::Relaxed) + 1 + }); + let enqueued_wall_ns = if session.is_some() { + wall_now_ns().saturating_sub(ns(enqueued.elapsed())) + } else { + 0 + }; + Job { + session, + id, + work, + slot, + reference_slot, + enqueued, + enqueued_wall_ns, + } +} + +impl Job { + /// Emit `kind` with this job's fields over `fields`' (a JSON object). + fn emit( + &self, + class: Class, + kind: &'static str, + outcome: &str, + fields: impl FnOnce() -> Value, + ) { + let Some(session) = &self.session else { + return; + }; + let mut fields = fields(); + let job = json!({ + "outcome": outcome, + "job_id": self.id, + "work": self.work.label(), + "origin": "production", + "slot": self.slot, + "reference_slot": self.reference_slot, + "round": self.work.round(), + "previous_recursive_depth": 0, + "experiment_id": null, + "sequence_id": format!("production:{}", self.slot), + "scenario": "production", + "committee_count": null, + "active_validators": null, + "enqueued_wall_ns": self.enqueued_wall_ns, + }); + if let (Value::Object(fields), Value::Object(job)) = (&mut fields, job) { + fields.extend(job); + } + session.emit_now(class, kind, fields); + } + + /// `proof_started`: the prover is about to be called. + pub fn started(&self, fields: impl FnOnce() -> Value) { + self.emit(Class::Work, "proof_started", "started", || { + let mut fields = fields(); + fields["queue_wait_ns"] = json!(ns(self.enqueued.elapsed())); + fields + }); + } + + /// `proof_finished`: the prover returned after `backend`, with `proof` + /// or without one. `late` when that was past the job's deadline. + pub fn finished( + &self, + backend: Duration, + late: bool, + proof: Option<&[u8]>, + fields: impl FnOnce() -> Value, + ) { + let outcome = if proof.is_some() { "success" } else { "failed" }; + self.emit(Class::Work, "proof_finished", outcome, || { + let mut fields = fields(); + fields["backend_duration_ns"] = json!(ns(backend)); + fields["late"] = json!(late); + fields["proof_bytes"] = json!(proof.map(<[u8]>::len)); + fields["proof_id"] = json!(proof.map(proof_id)); + fields + }); + } + + /// `candidate_ready`: the proof is where its consumer takes it from. + pub fn ready(&self, fields: impl FnOnce() -> Value) { + self.emit(Class::Work, "candidate_ready", "ready", fields); + } + + /// `job_outcome`: the job ended without a proof being made, as `outcome` + /// says. + pub fn outcome(&self, outcome: &str, fields: impl FnOnce() -> Value) { + self.emit(Class::Work, "job_outcome", outcome, fields); + } +} + +/// `proposal_snapshot`: block production took what it has for the block at +/// `slot`, whose newest votes are of `reference_slot`. `outcome` is +/// `candidate` when the block carries attestations and `no_candidate` when +/// it carries none. It ends the sequence the slot's merges belong to. +pub fn proposal_snapshot( + slot: u64, + reference_slot: u64, + outcome: &str, + fields: impl FnOnce() -> Value, +) { + let Some(session) = active() else { + return; + }; + let mut fields = fields(); + let sequence = json!({ + "outcome": outcome, + "origin": "production", + "scenario": "production", + "sequence_id": format!("production:{slot}"), + "slot": slot, + "reference_slot": reference_slot, + "experiment_id": null, + }); + if let (Value::Object(fields), Value::Object(sequence)) = (&mut fields, sequence) { + fields.extend(sequence); + } + session.emit_now(Class::Status, "proposal_snapshot", fields); +} + +/// What events name a proof by: its SHA-256, so a proof can be followed from +/// the job that made it to the block that carries it without exporting it. +/// Empty for an empty proof. +pub fn proof_id(proof: &[u8]) -> String { + if proof.is_empty() { + return String::new(); + } + hex_0x(&Sha256::digest(proof)) +} + +fn hex_0x(bytes: &[u8]) -> String { + format!("0x{}", hex::encode(bytes)) +} + +fn ns(duration: Duration) -> u64 { + u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX) +} + +fn wall_now_ns() -> u64 { + ns(SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default()) +} + +/// Sixty-four bits that differ between runs, for the run's name: a fresh +/// `RandomState`'s keys, which the standard library seeds from the operating +/// system. Nothing reads them as secret. +fn random_u64() -> u64 { + use std::hash::{BuildHasher as _, Hasher as _}; + std::collections::hash_map::RandomState::new() + .build_hasher() + .finish() +} + +/// Recording into memory, for tests of the emit sites. +#[cfg(any(test, feature = "test-utils"))] +pub mod testing { + use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; + + use super::{Session, Sink, Value, activate, deactivate}; + + /// One capture at a time: the session is the process's. + static SERIAL: Mutex<()> = Mutex::new(()); + + /// Every event emitted while it lives, by any thread of the process. A + /// test reads the ones about its own messages and jobs: another test's + /// emit sites record here too. + pub struct Capture { + session: Arc, + _serial: MutexGuard<'static, ()>, + } + + /// Start capturing. Waits for another capture of this process to end. + pub fn capture() -> Capture { + let serial = SERIAL.lock().unwrap_or_else(PoisonError::into_inner); + let session = Session::new(Sink::Memory(Mutex::new(Vec::new()))); + assert!( + activate(session.clone()), + "a PQ timing run is being recorded" + ); + Capture { + session, + _serial: serial, + } + } + + impl Capture { + /// The events so far, in the order they were emitted. + pub fn events(&self) -> Vec { + let Sink::Memory(events) = &self.session.sink else { + unreachable!("a capture records into memory"); + }; + events + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + } + + /// The events of `kind` so far. + pub fn of_kind(&self, kind: &str) -> Vec { + let mut events = self.events(); + events.retain(|event| event["kind"] == kind); + events + } + } + + impl Drop for Capture { + fn drop(&mut self) { + deactivate(); + } + } + + /// Hold the capture lock without capturing, for a test that installs a + /// run on disk. + #[cfg(test)] + pub(super) fn serial() -> MutexGuard<'static, ()> { + SERIAL.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +#[cfg(test)] +mod tests { + use std::fs::File; + + use super::*; + + fn run(output: &std::path::Path) -> Run { + Run { + output: output.to_path_buf(), + network: "pq-devnet-1".into(), + client_version: "ethlambda/v1.0.0".into(), + genesis_time: 1_700_000_000, + genesis_validators_root: [0xab; 32], + prover: Prover { + backend: "leanvm", + leanvm_revision: "351f7ae4", + leanvm_protocol_version: 1, + log_inv_rate: 2, + threads: Some(8), + threads_configured: 8, + }, + timing: Timing { + slot: Duration::from_secs(12), + attestation_due: Duration::from_millis(4_000), + committee_collection: Duration::from_millis(4_800), + aggregator_delay: Duration::from_millis(600), + aggregate_due: Duration::from_millis(7_200), + initial_merge: Duration::from_secs(20), + proposal_lag_slots: 2, + }, + } + } + + /// Nothing is built, and no job is numbered, while no run is recorded. + #[test] + fn the_emitters_build_nothing_when_no_run_is_recorded() { + let _serial = testing::serial(); + assert!(!enabled()); + let received = message_received(Instant::now(), || unreachable!("not recording")); + assert_eq!(received, None); + let job = job(Work::Committee, 5, 5, Instant::now()); + assert_eq!(job.id, 0); + job.started(|| unreachable!("not recording")); + job.finished(Duration::ZERO, false, None, || { + unreachable!("not recording") + }); + job.ready(|| unreachable!("not recording")); + job.outcome("unproved", || unreachable!("not recording")); + proposal_snapshot(7, 5, "candidate", || unreachable!("not recording")); + } + + /// The manifest carries what a report reads: the schema, an id usable as + /// a file name, genesis, the slot's timing in nanoseconds, the hardware + /// and the prover. + #[test] + fn a_run_describes_itself() { + let _serial = testing::serial(); + let root = tempfile::tempdir().unwrap(); + let directory = install(run(root.path())).unwrap(); + assert!(enabled()); + // A second run is refused while the first records, and leaves it be. + let second = install(run(root.path())).unwrap_err(); + assert_eq!(second.kind(), io::ErrorKind::AlreadyExists); + assert!(enabled()); + close(); + assert!(!enabled()); + + let manifest: Value = + serde_json::from_reader(File::open(directory.join("run.json")).unwrap()).unwrap(); + assert_eq!(manifest["schema_version"], 1); + let id = manifest["run_id"].as_str().unwrap(); + assert_eq!(directory.file_name().unwrap().to_str(), Some(id)); + assert!( + id.bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-') + ); + assert_eq!(manifest["client"], "ethlambda"); + assert_eq!(manifest["observer"], false); + assert_eq!(manifest["genesis_time"], 1_700_000_000u64); + assert_eq!(manifest["genesis_slot"], 0); + assert_eq!( + manifest["genesis_validators_root"], + format!("0x{}", "ab".repeat(32)) + ); + assert_eq!( + manifest["timing"], + json!({ + "slot_ns": 12_000_000_000u64, + "attestation_ns": 4_000_000_000u64, + "committee_collection_ns": 4_800_000_000u64, + "aggregator_position": 0, + "aggregator_delay_ns": 600_000_000u64, + "aggregate_ns": 7_200_000_000u64, + "initial_merge_ns": 20_000_000_000u64, + "proposal_lag_slots": 2, + }) + ); + assert_eq!(manifest["prover_threads"], 8); + assert_eq!(manifest["hardware"]["architecture"], std::env::consts::ARCH); + assert!(manifest["ended_unix_ns"].is_number()); + assert_eq!(manifest["chunks"], json!([])); + } + + /// A receipt is stamped when the message arrived, not when it was + /// recorded, and its verdict is tied to it by kind and message id. + #[test] + fn a_vote_is_received_then_validated() { + let capture = testing::capture(); + let before_ns = wall_now_ns(); + let received_at = Instant::now(); + std::thread::sleep(Duration::from_millis(20)); + let vote = message_received(received_at, || Receipt { + kind: MessageKind::Aggregate, + message_id: &[0x01, 0x02], + slot: 7, + committee: Some(3), + subnet: None, + message_bytes: 4_096, + signer_count: 120, + vote_data_root: [0xcd; 32], + }) + .expect("recording"); + validated(vote, &[0x01, 0x02], received_at, "accepted"); + + let events = capture.events(); + assert_eq!(events.len(), 2); + let received = &events[0]; + assert_eq!(received["kind"], "message_received"); + assert_eq!(received["message_kind"], "aggregate"); + assert_eq!(received["message_id"], "0x0102"); + assert_eq!(received["source"], "network"); + assert_eq!( + (&received["slot"], &received["reference_slot"]), + (&json!(7), &json!(7)) + ); + assert_eq!(received["committee"], 3); + assert_eq!(received["subnet"], Value::Null); + assert_eq!(received["message_bytes"], 4_096); + assert_eq!(received["byte_basis"], "decoded_ssz"); + assert_eq!(received["signer_count"], 120); + assert_eq!(received["vote_data_root"], format!("0x{}", "cd".repeat(32))); + let stamped = received["wall_ns"].as_u64().unwrap(); + // Within a millisecond of when it arrived, 20 ms before the record. + assert!(stamped.abs_diff(before_ns) < 5_000_000, "stamped {stamped}"); + + let verdict = &events[1]; + assert_eq!(verdict["kind"], "validated"); + assert_eq!(verdict["message_kind"], "aggregate"); + assert_eq!(verdict["message_id"], "0x0102"); + assert_eq!(verdict["outcome"], "accepted"); + assert_eq!(verdict["slot"], 7); + assert!(verdict["receipt_to_validation_ns"].as_u64().unwrap() >= 20_000_000); + assert!(verdict["mono_ns"].as_u64() > received["mono_ns"].as_u64()); + } + + /// A job's events share its id and fields; the proof events add the + /// queue wait, the backend's time and what identifies the proof. + #[test] + fn a_jobs_events_carry_its_fields() { + let capture = testing::capture(); + let enqueued = Instant::now(); + std::thread::sleep(Duration::from_millis(10)); + let merge = job(Work::Improvement, 12, 10, enqueued); + merge.started(|| json!({"input_proof_count": 3})); + merge.finished( + Duration::from_millis(700), + true, + Some(&[1, 2, 3]), + || json!({"input_proof_count": 3}), + ); + merge.ready(|| json!({"records": 2})); + proposal_snapshot(12, 10, "candidate", || json!({"records": 2})); + let committee = job(Work::Committee, 10, 10, enqueued); + committee.finished(Duration::from_millis(80), false, None, || json!({})); + committee.outcome("unproved", || json!({"committee": 4})); + + let events = capture.events(); + let kinds: Vec<&str> = events.iter().map(|e| e["kind"].as_str().unwrap()).collect(); + assert_eq!( + kinds, + [ + "proof_started", + "proof_finished", + "candidate_ready", + "proposal_snapshot", + "proof_finished", + "job_outcome" + ] + ); + // The snapshot is the sequence's, not a job's: no work, no job id. + assert_eq!(events[3]["job_id"], Value::Null); + assert_eq!(events[3]["work"], Value::Null); + for event in &events[..3] { + assert_eq!(event["job_id"], 1); + assert_eq!(event["work"], "improvement"); + assert_eq!(event["round"], 2); + } + for event in &events[..4] { + assert_eq!(event["origin"], "production"); + assert_eq!(event["scenario"], "production"); + assert_eq!(event["sequence_id"], "production:12"); + assert_eq!( + (&event["slot"], &event["reference_slot"]), + (&json!(12), &json!(10)) + ); + assert_eq!(event["experiment_id"], Value::Null); + } + assert_eq!(events[0]["outcome"], "started"); + assert_eq!(events[0]["input_proof_count"], 3); + assert!(events[0]["queue_wait_ns"].as_u64().unwrap() >= 10_000_000); + let finished = &events[1]; + assert_eq!(finished["outcome"], "success"); + assert_eq!(finished["backend_duration_ns"], 700_000_000u64); + assert_eq!(finished["late"], true); + assert_eq!(finished["proof_bytes"], 3); + assert_eq!(finished["proof_id"], proof_id(&[1, 2, 3])); + assert_eq!(events[2]["outcome"], "ready"); + assert_eq!(events[3]["outcome"], "candidate"); + + assert_eq!(events[4]["job_id"], 2); + assert_eq!(events[4]["work"], "committee"); + assert_eq!(events[4]["round"], 1); + assert_eq!(events[4]["outcome"], "failed"); + assert_eq!(events[4]["proof_id"], Value::Null); + assert_eq!(events[5]["outcome"], "unproved"); + assert_eq!(events[5]["committee"], 4); + } + + /// A run on disk reads back the way the report script reads one: the + /// manifest lists a chunk by name, the chunk is a zstd stream of JSON + /// lines, and every line has its sequence number, kind and both clocks. + #[test] + fn a_recorded_run_reads_back_from_its_listed_chunk() { + let _serial = testing::serial(); + let root = tempfile::tempdir().unwrap(); + let directory = install(run(root.path())).unwrap(); + let received_at = Instant::now(); + let vote = message_received(received_at, || Receipt { + kind: MessageKind::Individual, + message_id: &[0xee], + slot: 3, + committee: Some(0), + subnet: Some(1), + message_bytes: 100, + signer_count: 1, + vote_data_root: [0; 32], + }) + .expect("recording"); + validated(vote, &[0xee], received_at, "accepted"); + let proof = job(Work::Committee, 3, 3, Instant::now()); + proof.started(|| json!({"committee": 0})); + proof.finished( + Duration::from_millis(5), + false, + Some(&[9; 16]), + || json!({}), + ); + proof.ready(|| json!({})); + proposal_snapshot(5, 3, "candidate", || json!({"records": 1})); + close(); + + let manifest: Value = + serde_json::from_reader(File::open(directory.join("run.json")).unwrap()).unwrap(); + let chunks = manifest["chunks"].as_array().unwrap(); + assert_eq!(chunks.len(), 1); + let name = chunks[0]["name"].as_str().unwrap(); + assert!(name.ends_with(".jsonl.zst")); + let bytes = zstd::stream::decode_all(File::open(directory.join(name)).unwrap()).unwrap(); + let lines: Vec = bytes + .split(|&byte| byte == b'\n') + .filter(|line| !line.is_empty()) + .map(|line| serde_json::from_slice(line).unwrap()) + .collect(); + let kinds: Vec<&str> = lines.iter().map(|l| l["kind"].as_str().unwrap()).collect(); + assert_eq!( + kinds, + [ + "message_received", + "validated", + "proof_started", + "proof_finished", + "candidate_ready", + "proposal_snapshot" + ] + ); + for (index, line) in lines.iter().enumerate() { + assert_eq!(line["seq"], index as u64 + 1); + assert!(line["wall_ns"].as_u64().unwrap() > 1_700_000_000_000_000_000); + assert!(line["mono_ns"].is_u64()); + assert!(line["reference_slot"].is_u64()); + } + assert_eq!(manifest["recorder_status"]["submitted_sequence"], 6); + assert_eq!(manifest["recorder_status"]["dropped"]["work"], 0); + } + + #[test] + fn a_proof_is_named_by_its_sha_256() { + assert_eq!(proof_id(&[]), ""); + assert_eq!( + proof_id(b"abc"), + "0xba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + } +} diff --git a/crates/common/telemetry/src/pq_timing/hardware.rs b/crates/common/telemetry/src/pq_timing/hardware.rs new file mode 100644 index 000000000..f7ad51e30 --- /dev/null +++ b/crates/common/telemetry/src/pq_timing/hardware.rs @@ -0,0 +1,134 @@ +//! What the run's timings were measured on, for `run.json`. +//! +//! Read from `/proc` and the cgroup v2 tree, so a container reports the CPU +//! and memory it was given and not only the host's. Off Linux every field but +//! the architecture, the operating system and the core count is null. + +use std::fs; +use std::path::Path; + +use serde_json::{Value, json}; + +pub(super) fn hardware() -> Value { + let cpu_model = + field("/proc/cpuinfo", "model name").or_else(|| field("/proc/cpuinfo", "Hardware")); + let visible_memory_bytes = field("/proc/meminfo", "MemTotal") + .and_then(|value| value.split_whitespace().next()?.parse::().ok()) + .and_then(|kib| kib.checked_mul(1024)); + let (cpu_quota, memory_limit) = cgroup_limits(Path::new("/sys/fs/cgroup"), &own_cgroup()); + json!({ + "architecture": std::env::consts::ARCH, + "os": std::env::consts::OS, + "kernel": read_trimmed("/proc/sys/kernel/osrelease"), + "cpu_model": cpu_model, + "available_parallelism": std::thread::available_parallelism().ok().map(usize::from), + "cpu_affinity": field("/proc/self/status", "Cpus_allowed_list"), + "cgroup_cpu_equivalents": cpu_quota, + "visible_memory_bytes": visible_memory_bytes, + "cgroup_memory_bytes": memory_limit, + }) +} + +fn read_trimmed(file: &str) -> Option { + Some(fs::read_to_string(file).ok()?.trim().to_string()) +} + +/// The value of the first `key: value` line of `file`. +fn field(file: &str, key: &str) -> Option { + let text = fs::read_to_string(file).ok()?; + value_of(&text, key) +} + +fn value_of(text: &str, key: &str) -> Option { + text.lines().find_map(|line| { + let (name, value) = line.split_once(':')?; + (name.trim() == key).then(|| value.trim().to_string()) + }) +} + +/// This process's cgroup, relative to the cgroup root: the `0::/...` line of +/// `/proc/self/cgroup`. Empty when there is none, which reads the root. +fn own_cgroup() -> String { + fs::read_to_string("/proc/self/cgroup") + .ok() + .and_then(|text| { + text.lines() + .find_map(|line| line.strip_prefix("0::/").map(str::to_owned)) + }) + .unwrap_or_default() +} + +/// The tightest CPU quota, in CPUs, and memory limit, in bytes, among +/// `group` and its ancestors under `root`. `None` where none sets one: an +/// unlimited `cpu.max` or `memory.max` reads `max`, which is not a number. +fn cgroup_limits(root: &Path, group: &str) -> (Option, Option) { + let mut path = root.join(group); + if !path.is_dir() { + path = root.to_path_buf(); + } + let cpu = |path: &Path| { + let value = fs::read_to_string(path.join("cpu.max")).ok()?; + let (quota, period) = value.trim().split_once(' ')?; + let period = period.parse::().ok().filter(|&period| period > 0)?; + Some(quota.parse::().ok()? as f64 / period as f64) + }; + let memory = |path: &Path| { + fs::read_to_string(path.join("memory.max")) + .ok()? + .trim() + .parse::() + .ok() + }; + let levels = || { + path.ancestors() + .take_while(|ancestor| ancestor.starts_with(root)) + }; + ( + levels().filter_map(cpu).reduce(f64::min), + levels().filter_map(memory).min(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_proc_field_is_read_by_its_key() { + let cpuinfo = + "processor\t: 0\nmodel name\t: AMD EPYC 9454P 48-Core Processor\nflags\t: fpu"; + assert_eq!( + value_of(cpuinfo, "model name").as_deref(), + Some("AMD EPYC 9454P 48-Core Processor") + ); + assert_eq!(value_of(cpuinfo, "model"), None); + } + + /// A container's limits are the tightest of its own cgroup's and its + /// ancestors': here the parent caps CPU at 4 and the leaf memory at 8 GiB. + #[test] + fn the_tightest_cgroup_limit_among_the_ancestors_wins() { + let root = tempfile::tempdir().unwrap(); + let leaf = root.path().join("kubepods/pod1"); + fs::create_dir_all(&leaf).unwrap(); + fs::write(root.path().join("cpu.max"), "max 100000\n").unwrap(); + fs::write(root.path().join("kubepods/cpu.max"), "400000 100000\n").unwrap(); + fs::write(leaf.join("cpu.max"), "800000 100000\n").unwrap(); + fs::write(root.path().join("kubepods/memory.max"), "max\n").unwrap(); + fs::write(leaf.join("memory.max"), "8589934592\n").unwrap(); + + let limits = cgroup_limits(root.path(), "kubepods/pod1"); + assert_eq!(limits, (Some(4.0), Some(8 << 30))); + // No cgroup of its own, or one that is not there: the root's, which + // sets none. + assert_eq!(cgroup_limits(root.path(), ""), (None, None)); + assert_eq!(cgroup_limits(root.path(), "elsewhere"), (None, None)); + } + + #[test] + fn the_report_names_the_architecture_everywhere() { + let report = hardware(); + assert_eq!(report["architecture"], std::env::consts::ARCH); + assert!(report["available_parallelism"].is_number()); + } +} diff --git a/crates/common/telemetry/src/pq_timing/recorder.rs b/crates/common/telemetry/src/pq_timing/recorder.rs new file mode 100644 index 000000000..ff8f5ae36 --- /dev/null +++ b/crates/common/telemetry/src/pq_timing/recorder.rs @@ -0,0 +1,582 @@ +//! The run directory: `run.json` and its `events-NNNNNN.jsonl.zst` chunks. +//! +//! Emitting never waits: an event goes into a bounded queue, and one the +//! queue has no room for is dropped and counted in the manifest. A writer +//! thread serializes and compresses, so neither is paid on the emitting +//! thread, and rewrites the manifest whenever a chunk is finished. + +use std::collections::VecDeque; +use std::fs::{self, File}; +use std::io::{self, BufWriter, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, TrySendError, sync_channel}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::{Duration, Instant}; + +use serde::Serialize; +use serde_json::{Value, json}; + +use super::wall_now_ns; + +/// What bounds a run on disk and in memory. +#[derive(Debug, Clone, Copy)] +pub(super) struct Limits { + /// Events waiting for the writer. One more is dropped. + pub queue: usize, + /// A chunk is finished once it holds this many uncompressed bytes, + pub rotate_bytes: usize, + /// or has been open this long. + pub rotate_time: Duration, + /// The oldest chunks are removed while the finished ones exceed this, + /// down to the newest one. + pub retain_bytes: u64, + /// How often the manifest's status is rewritten and the open chunk + /// flushed, with or without events. + pub status_interval: Duration, +} + +impl Limits { + /// The other clients' numbers: a 16,384-event queue, chunks of 64 MiB or + /// five minutes, 8 GiB kept, a status every ten seconds. + pub(super) const DEFAULT: Self = Self { + queue: 16_384, + rotate_bytes: 64 << 20, + rotate_time: Duration::from_secs(300), + retain_bytes: 8 << 30, + status_interval: Duration::from_secs(10), + }; +} + +/// What an event is about, for the dropped-event counts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Class { + Receipt, + Validation, + Work, + Status, +} + +impl Class { + const ALL: [Class; 4] = [ + Class::Receipt, + Class::Validation, + Class::Work, + Class::Status, + ]; + + pub(super) fn label(self) -> &'static str { + match self { + Self::Receipt => "receipt", + Self::Validation => "validation", + Self::Work => "work", + Self::Status => "status", + } + } +} + +/// One line of a chunk, before its sequence number. +#[derive(Debug, Serialize)] +pub(super) struct Record { + pub kind: &'static str, + pub wall_ns: u64, + pub mono_ns: u64, + /// A JSON object, whose members become the line's own. + #[serde(flatten)] + pub fields: Value, +} + +#[derive(Debug, Serialize)] +struct Envelope { + seq: u64, + #[serde(flatten)] + record: Record, +} + +/// The first and last events the queue had no room for. +#[derive(Debug, Default)] +struct Dropped { + first_sequence: Option, + last_sequence: u64, + first_wall_ns: u64, + last_wall_ns: u64, +} + +#[derive(Debug, Default)] +struct Health { + failed: AtomicBool, + next_sequence: AtomicU64, + drops: [AtomicU64; Class::ALL.len()], + dropped: Mutex, +} + +impl Health { + fn status(&self) -> Value { + let drops = |class: Class| self.drops[class as usize].load(Ordering::Relaxed); + let dropped = self.dropped.lock().expect("PQ timing drop record lock"); + json!({ + "disk_failed": self.failed.load(Ordering::Relaxed), + "dropped": { + "receipt": drops(Class::Receipt), + "validation": drops(Class::Validation), + "work": drops(Class::Work), + "status": drops(Class::Status), + }, + "first_dropped_sequence": dropped.first_sequence, + "last_dropped_sequence": dropped.last_sequence, + "submitted_sequence": self.next_sequence.load(Ordering::Relaxed), + "first_dropped_wall_ns": dropped.first_wall_ns, + "last_dropped_wall_ns": dropped.last_wall_ns, + }) + } + + fn drop_event(&self, sequence: u64, wall_ns: u64, class: Class) { + self.drops[class as usize].fetch_add(1, Ordering::Relaxed); + crate::metrics::inc_pq_timing_dropped(class.label()); + let mut dropped = self.dropped.lock().expect("PQ timing drop record lock"); + if dropped.first_sequence.is_none() { + dropped.first_sequence = Some(sequence); + dropped.first_wall_ns = wall_ns; + } + dropped.last_sequence = dropped.last_sequence.max(sequence); + dropped.last_wall_ns = dropped.last_wall_ns.max(wall_ns); + } +} + +/// An open run. Dropping it finishes the last chunk and the manifest. +#[derive(Debug)] +pub(super) struct Recorder { + /// `None` once closed: the writer ends when its last sender goes. + sender: Mutex>>, + writer: Mutex>>, + health: Arc, + directory: PathBuf, +} + +impl Recorder { + /// Create `root/id`, write its first `run.json` from `metadata` (a JSON + /// object) and start the writer thread. + pub(super) fn open( + root: &Path, + id: &str, + mut metadata: Value, + limits: Limits, + ) -> io::Result { + let directory = root.join(id); + fs::create_dir_all(root)?; + fs::create_dir(&directory)?; + let health = Arc::new(Health::default()); + metadata["recorder_status"] = health.status(); + metadata["chunks"] = json!([]); + write_metadata(&directory, &metadata)?; + let (sender, receiver) = sync_channel(limits.queue); + let writer = { + let (directory, health) = (directory.clone(), health.clone()); + thread::Builder::new() + .name("pq-timing-writer".into()) + .spawn(move || { + let written = + write_events(&directory, &receiver, &health, &mut metadata, limits); + if let Err(err) = written { + health.failed.store(true, Ordering::Release); + tracing::error!(%err, "PQ timing export disabled after a write failed"); + metadata["recorder_status"] = health.status(); + let _ = write_metadata(&directory, &metadata).inspect_err( + |err| tracing::warn!(%err, "Could not record the PQ timing export's failure"), + ); + } + })? + }; + Ok(Self { + sender: Mutex::new(Some(sender)), + writer: Mutex::new(Some(writer)), + health, + directory, + }) + } + + pub(super) fn directory(&self) -> &Path { + &self.directory + } + + /// Whether events still reach the disk: not after a write failed, and + /// not once closed. + pub(super) fn healthy(&self) -> bool { + !self.health.failed.load(Ordering::Acquire) + } + + /// Queue `record`, or count it as dropped when the queue is full. One + /// emitted after [`Self::close`] is neither written nor counted. + pub(super) fn emit(&self, class: Class, record: Record) { + let sender = self.sender.lock().expect("PQ timing sender lock"); + let Some(sender) = sender.as_ref() else { + return; + }; + let sequence = self.health.next_sequence.fetch_add(1, Ordering::Relaxed) + 1; + let envelope = Envelope { + seq: sequence, + record, + }; + if let Err(TrySendError::Full(envelope) | TrySendError::Disconnected(envelope)) = + sender.try_send(envelope) + { + self.health + .drop_event(sequence, envelope.record.wall_ns, class); + } + } + + /// Finish the open chunk and the manifest, and wait for the writer. + pub(super) fn close(&self) { + self.sender.lock().expect("PQ timing sender lock").take(); + let writer = self.writer.lock().expect("PQ timing writer lock").take(); + if let Some(writer) = writer { + let _ = writer.join(); + } + } +} + +impl Drop for Recorder { + fn drop(&mut self) { + self.close(); + } +} + +#[derive(Debug, Serialize)] +struct ChunkInfo { + name: String, + bytes: u64, + first: u64, + last: u64, +} + +struct Chunk { + temporary: PathBuf, + name: String, + stream: zstd::stream::write::Encoder<'static, BufWriter>, + started: Instant, + /// Uncompressed bytes written. + bytes: usize, + /// Whether events were written since the last flush. + unflushed: bool, + first: u64, + last: u64, +} + +impl Chunk { + fn new(directory: &Path, number: u64) -> io::Result { + let name = format!("events-{number:06}.jsonl.zst"); + let temporary = directory.join(format!("{name}.partial")); + let file = BufWriter::new(File::create(&temporary)?); + Ok(Self { + temporary, + name, + stream: zstd::stream::write::Encoder::new(file, 1)?, + started: Instant::now(), + bytes: 0, + unflushed: false, + first: u64::MAX, + last: 0, + }) + } + + fn write(&mut self, envelope: &Envelope, line: &mut Vec) -> io::Result<()> { + line.clear(); + serde_json::to_writer(&mut *line, envelope)?; + line.push(b'\n'); + self.stream.write_all(line)?; + self.bytes = self.bytes.saturating_add(line.len()); + self.unflushed = true; + self.first = self.first.min(envelope.seq); + self.last = self.last.max(envelope.seq); + Ok(()) + } + + /// End the compressed block and hand it to the file, so the `.partial` + /// of a node that is killed reads up to here. + fn flush(&mut self) -> io::Result<()> { + if self.unflushed { + self.stream.flush()?; + self.unflushed = false; + } + Ok(()) + } + + fn finish(self, directory: &Path) -> io::Result { + let mut file = self.stream.finish()?; + file.flush()?; + let bytes = file.get_ref().metadata()?.len(); + fs::rename(&self.temporary, directory.join(&self.name))?; + Ok(ChunkInfo { + name: self.name, + bytes, + first: self.first, + last: self.last, + }) + } +} + +/// Replace `run.json` whole: a reader never sees half of one. +fn write_metadata(directory: &Path, metadata: &Value) -> io::Result<()> { + let temporary = directory.join("run.json.partial"); + let mut file = BufWriter::new(File::create(&temporary)?); + serde_json::to_writer_pretty(&mut file, metadata)?; + file.write_all(b"\n")?; + file.flush()?; + fs::rename(temporary, directory.join("run.json")) +} + +/// The writer thread: until every sender is gone, write events into chunks, +/// finish a chunk when it is full or old, remove the oldest past the +/// retention bound, and keep the manifest's chunk list and status current. +fn write_events( + directory: &Path, + receiver: &Receiver, + health: &Health, + metadata: &mut Value, + limits: Limits, +) -> io::Result<()> { + let mut current = None::; + let mut number = 0u64; + let mut retained = VecDeque::::new(); + let mut retained_bytes = 0u64; + let mut evicted_chunks = 0u64; + let (mut evicted_first, mut evicted_last) = (u64::MAX, 0u64); + let mut line = Vec::new(); + let mut last_status = Instant::now(); + loop { + let closing = match receiver.recv_timeout(limits.status_interval) { + Ok(envelope) => { + if current.is_none() { + number += 1; + current = Some(Chunk::new(directory, number)?); + } + if let Some(chunk) = current.as_mut() { + chunk.write(&envelope, &mut line)?; + } + false + } + Err(RecvTimeoutError::Timeout) => false, + Err(RecvTimeoutError::Disconnected) => true, + }; + let rotate = current.as_ref().is_some_and(|chunk| { + closing + || chunk.bytes >= limits.rotate_bytes + || chunk.started.elapsed() >= limits.rotate_time + }); + if rotate && let Some(chunk) = current.take() { + let chunk = chunk.finish(directory)?; + retained_bytes = retained_bytes.saturating_add(chunk.bytes); + retained.push_back(chunk); + while retained_bytes > limits.retain_bytes && retained.len() > 1 { + let Some(old) = retained.pop_front() else { + break; + }; + fs::remove_file(directory.join(&old.name))?; + retained_bytes = retained_bytes.saturating_sub(old.bytes); + evicted_chunks += 1; + evicted_first = evicted_first.min(old.first); + evicted_last = evicted_last.max(old.last); + } + } + if rotate || closing || last_status.elapsed() >= limits.status_interval { + if let Some(chunk) = current.as_mut() { + chunk.flush()?; + } + let mut status = health.status(); + status["evicted_chunks"] = json!(evicted_chunks); + status["evicted_sequence_bounds"] = + json!((evicted_chunks != 0).then_some([evicted_first, evicted_last])); + status["checked_unix_ns"] = json!(wall_now_ns()); + metadata["chunks"] = json!(retained); + metadata["recorder_status"] = status; + if closing { + metadata["ended_unix_ns"] = json!(wall_now_ns()); + } + write_metadata(directory, metadata)?; + last_status = Instant::now(); + } + if closing { + return Ok(()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn record(kind: &'static str, fields: Value) -> Record { + Record { + kind, + wall_ns: 9, + mono_ns: 8, + fields, + } + } + + fn manifest(directory: &Path) -> Value { + serde_json::from_reader(File::open(directory.join("run.json")).unwrap()).unwrap() + } + + /// Every event of `directory`'s listed chunks, in order. + fn events(directory: &Path) -> Vec { + let manifest = manifest(directory); + let mut events = Vec::new(); + for chunk in manifest["chunks"].as_array().unwrap() { + let name = chunk["name"].as_str().unwrap(); + let bytes = zstd::stream::decode_all(File::open(directory.join(name)).unwrap()); + for line in bytes.unwrap().split(|&byte| byte == b'\n') { + if !line.is_empty() { + events.push(serde_json::from_slice(line).unwrap()); + } + } + } + events + } + + /// Closing a run finishes its chunk under its final name, lists it in the + /// manifest with the sequence numbers it holds, and stamps the end. + #[test] + fn closing_a_run_finishes_a_readable_chunk() { + let root = tempfile::tempdir().unwrap(); + let metadata = json!({"schema_version": 1}); + let recorder = Recorder::open(root.path(), "run", metadata, Limits::DEFAULT).unwrap(); + let directory = recorder.directory().to_path_buf(); + assert_eq!(manifest(&directory)["chunks"], json!([])); + recorder.emit( + Class::Status, + record("proposal_snapshot", json!({"round": 2})), + ); + recorder.emit( + Class::Work, + record("proof_finished", json!({"late": false})), + ); + recorder.close(); + + let manifest = manifest(&directory); + assert_eq!(manifest["schema_version"], 1); + assert!(manifest["ended_unix_ns"].is_number()); + let chunk = &manifest["chunks"][0]; + assert_eq!(chunk["name"], "events-000001.jsonl.zst"); + assert_eq!((&chunk["first"], &chunk["last"]), (&json!(1), &json!(2))); + assert!(!directory.join("events-000001.jsonl.zst.partial").exists()); + + let events = events(&directory); + assert_eq!(events.len(), 2); + assert_eq!( + events[0], + json!({"seq": 1, "kind": "proposal_snapshot", "wall_ns": 9, "mono_ns": 8, "round": 2}) + ); + assert_eq!(events[1]["seq"], 2); + // Nothing after the close is written, or counted as dropped. + recorder.emit(Class::Work, record("proof_started", json!({}))); + assert_eq!(recorder.health.status()["dropped"]["work"], 0); + } + + /// A full queue drops the event at once and says so in the status, by + /// class and by the first and last sequence numbers lost. + #[test] + fn a_full_queue_drops_and_counts_without_waiting() { + let (sender, receiver) = sync_channel(1); + let recorder = Recorder { + sender: Mutex::new(Some(sender)), + writer: Mutex::new(None), + health: Arc::default(), + directory: PathBuf::new(), + }; + for _ in 0..3 { + recorder.emit(Class::Receipt, record("message_received", json!({}))); + } + assert_eq!(receiver.try_recv().unwrap().seq, 1); + let status = recorder.health.status(); + assert_eq!(status["dropped"]["receipt"], 2); + assert_eq!(status["dropped"]["work"], 0); + assert_eq!(status["first_dropped_sequence"], 2); + assert_eq!(status["last_dropped_sequence"], 3); + assert_eq!(status["submitted_sequence"], 3); + } + + /// A chunk past its size is finished and the next one started; past the + /// retention bound the oldest are removed, down to the newest, and the + /// manifest says how many went and which events they held. + #[test] + fn chunks_rotate_by_size_and_the_oldest_are_evicted() { + let root = tempfile::tempdir().unwrap(); + let limits = Limits { + rotate_bytes: 1, + retain_bytes: 1, + ..Limits::DEFAULT + }; + let recorder = Recorder::open(root.path(), "run", json!({}), limits).unwrap(); + let directory = recorder.directory().to_path_buf(); + for _ in 0..3 { + recorder.emit(Class::Work, record("proof_started", json!({}))); + } + recorder.close(); + + let manifest = manifest(&directory); + let chunks = manifest["chunks"].as_array().unwrap(); + assert_eq!(chunks.len(), 1); + assert_eq!(chunks[0]["name"], "events-000003.jsonl.zst"); + assert_eq!(manifest["recorder_status"]["evicted_chunks"], 2); + assert_eq!( + manifest["recorder_status"]["evicted_sequence_bounds"], + json!([1, 2]) + ); + assert!(!directory.join("events-000001.jsonl.zst").exists()); + assert_eq!(events(&directory)[0]["seq"], 3); + } + + /// With no event for a status interval, the open chunk is flushed: the + /// `.partial` of a node killed afterwards decodes up to its last event, + /// though no manifest lists it. + #[test] + fn an_open_chunk_is_flushed_with_every_status() { + let root = tempfile::tempdir().unwrap(); + let limits = Limits { + status_interval: Duration::from_millis(20), + ..Limits::DEFAULT + }; + let recorder = Recorder::open(root.path(), "run", json!({}), limits).unwrap(); + let directory = recorder.directory().to_path_buf(); + recorder.emit(Class::Work, record("proof_started", json!({"job_id": 7}))); + let partial = directory.join("events-000001.jsonl.zst.partial"); + // The frame is still open, so read what it holds so far as a stream. + let flushed = || { + use std::io::Read as _; + let mut decoded = Vec::new(); + let file = File::open(&partial).ok()?; + let _ = zstd::stream::read::Decoder::new(file) + .ok()? + .read_to_end(&mut decoded); + decoded.ends_with(b"\n").then_some(decoded) + }; + let deadline = Instant::now() + Duration::from_secs(10); + let decoded = loop { + if let Some(decoded) = flushed() { + break decoded; + } + assert!( + Instant::now() < deadline, + "the open chunk was never flushed" + ); + thread::sleep(Duration::from_millis(10)); + }; + let event: Value = serde_json::from_slice(decoded.trim_ascii_end()).unwrap(); + assert_eq!(event["job_id"], 7); + assert_eq!(manifest(&directory)["chunks"], json!([])); + recorder.close(); + } + + /// A run directory that already exists is refused, so two runs never + /// write into one. + #[test] + fn an_existing_run_directory_is_refused() { + let root = tempfile::tempdir().unwrap(); + let open = || Recorder::open(root.path(), "run", json!({}), Limits::DEFAULT); + let first = open().unwrap(); + assert!(open().is_err()); + first.close(); + } +} diff --git a/crates/net/p2p/Cargo.toml b/crates/net/p2p/Cargo.toml index e23778579..8a8aced97 100644 --- a/crates/net/p2p/Cargo.toml +++ b/crates/net/p2p/Cargo.toml @@ -91,3 +91,6 @@ hex.workspace = true # `test-utils` for `helpers::test_state`: a test that needs a stored post-state # builds one with it. ethlambda-state-transition = { workspace = true, features = ["test-utils"] } +# `test-utils` for `pq_timing::testing`: the PQ timing events a gossip path +# emits, captured in memory. +ethlambda-telemetry = { workspace = true, features = ["test-utils"] } diff --git a/crates/net/p2p/src/beacon/parked_votes.rs b/crates/net/p2p/src/beacon/parked_votes.rs index 5b2eb1c26..15581439f 100644 --- a/crates/net/p2p/src/beacon/parked_votes.rs +++ b/crates/net/p2p/src/beacon/parked_votes.rs @@ -218,6 +218,7 @@ mod tests { propagation_source: PeerId::random(), received_at, kind: "beacon_attestation", + pq_vote: None, }, object: Validated::Attestation { attestation: Box::new(SingleAttestation { @@ -265,6 +266,7 @@ mod tests { propagation_source: PeerId::random(), received_at, kind: "beacon_aggregate_and_proof", + pq_vote: None, }, object: Validated::Aggregate { aggregate: Box::new(aggregate), diff --git a/crates/net/p2p/src/beacon/pq.rs b/crates/net/p2p/src/beacon/pq.rs index 623893313..3f8d74b6d 100644 --- a/crates/net/p2p/src/beacon/pq.rs +++ b/crates/net/p2p/src/beacon/pq.rs @@ -11,7 +11,7 @@ //! (queued ones too, as for gloas). Blocks and data column sidecars take the //! shared path. -use std::time::{Duration, Instant}; +use std::time::Duration; use std::time::Instant as StdInstant; @@ -20,15 +20,16 @@ use ethlambda_state_transition::beacon::builder_market::SharedPqBuilderMarket; use ethlambda_state_transition::beacon::gossip::{self, IgnoreReason, Outcome}; use ethlambda_state_transition::beacon::helpers::pq::get_committee_indices; use ethlambda_storage::{Store, pools::PooledPqAggregate}; +use ethlambda_telemetry::pq_timing; use ethlambda_types::beacon::containers::{SignedExecutionPayloadEnvelope, pq}; -use ethlambda_types::beacon::primitives::{Slot, ValidatorIndex}; +use ethlambda_types::beacon::primitives::{HashTreeRoot as _, Slot, ValidatorIndex}; use ethlambda_types::chain_config::ChainConfig; use ethlambda_types::time::unix_now_ms; use tracing::{debug, trace, warn}; use crate::beacon::decode::{self as beacon_decode, PqGossip}; use crate::beacon::topics as beacon_topics; -use crate::beacon::verdict::{Dispatch, Validated}; +use crate::beacon::verdict::{Dispatch, GossipId, Validated}; use crate::{P2PServer, metrics}; /// A PQ message whose stateful checks run on a blocking thread. The one @@ -254,12 +255,16 @@ fn pool_aggregate( /// every topic of a fork this node does not follow: its containers are /// modelled from a moving specification branch, and a peer must not be /// scored down for this build's gap. +/// +/// A vote that decodes is noted in `id` when the timing export recorded its +/// receipt, for the verdict's own event. pub(crate) fn triage( server: &P2PServer, kind: &str, payload: &[u8], - received_at: Instant, + id: &mut GossipId, ) -> Option { + let received_at = id.received_at; if !beacon_decode::is_pq_reshaped(kind) { return None; } @@ -294,6 +299,7 @@ pub(crate) fn triage( let arrived_ms = now_ms.saturating_sub(received_at.elapsed().as_millis() as u64); let offset = arrival_offset(&store.config().time_grid(), slot, arrived_ms); metrics::observe_pq_gossip_arrival_offset(metric_kind, offset); + id.pq_vote = record_receipt(&decoded, kind, payload.len(), id); } let cheap = match &decoded { PqGossip::Aggregate(signed) => { @@ -362,6 +368,47 @@ pub(crate) fn triage( Some(Dispatch::Validate(Validated::Pq(Box::new(object)))) } +/// Record a decoded vote's receipt in the timing export, if one is being +/// written. `None` otherwise, or for a message that is not a vote. +fn record_receipt( + decoded: &PqGossip, + kind: &str, + message_bytes: usize, + id: &GossipId, +) -> Option { + let message_id = id.message_id.0.as_slice(); + match decoded { + PqGossip::Attestation(attestation) => { + pq_timing::message_received(id.received_at, || pq_timing::Receipt { + kind: pq_timing::MessageKind::Individual, + message_id, + slot: attestation.data.slot, + committee: Some(attestation.committee_index), + subnet: beacon_topics::attestation_subnet(kind), + message_bytes, + signer_count: 1, + vote_data_root: attestation.data.hash_tree_root().0, + }) + } + PqGossip::Aggregate(signed) => pq_timing::message_received(id.received_at, || { + let aggregate = &signed.message.aggregate; + let bits = gossip::pq::aggregation_bits(signed); + pq_timing::Receipt { + kind: pq_timing::MessageKind::Aggregate, + message_id, + slot: aggregate.data.slot, + // The one committee it names, when it names one. + committee: gossip::pq::aggregate_key(signed).map(|key| key.committee_index), + subnet: None, + message_bytes, + signer_count: bits.iter().filter(|&&bit| bit).count(), + vote_data_root: aggregate.data.hash_tree_root().0, + } + }), + _ => None, + } +} + /// How far into `slot` the wall clock read `arrived_ms`. Zero for a message /// that arrived ahead of its slot, which gossip allows by the clock disparity. fn arrival_offset(grid: &ChainConfig, slot: Slot, arrived_ms: u64) -> Duration { @@ -488,6 +535,8 @@ mod tests { use ethlambda_types::beacon::fork::ForkName; use libssz::SszEncode as _; + use std::time::Instant; + use super::*; use crate::test_support::unconnected_beacon_server; @@ -498,8 +547,30 @@ mod tests { .with_fork_epoch(ForkName::Pq, 0) } + fn gossip_id(byte: u8, kind: &'static str) -> GossipId { + GossipId { + message_id: libp2p::gossipsub::MessageId::new(&[byte; 20]), + propagation_source: libp2p::PeerId::random(), + received_at: Instant::now(), + kind, + pq_vote: None, + } + } + + /// The tests that triage votes run one at a time: each reads what this + /// module recorded for votes, in the metrics or the timing export, and + /// counts on the others not adding to it meanwhile. Taken after the + /// server is built, so it is never held across an `await`. + fn one_vote_test_at_a_time() -> std::sync::MutexGuard<'static, ()> { + static VOTE_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(()); + VOTE_TESTS + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + fn triage_now(server: &P2PServer, kind: &str, payload: &[u8]) -> Option { - triage(server, kind, payload, Instant::now()) + let metric_kind = beacon_topics::metric_kind(kind).expect("a beacon topic"); + triage(server, kind, payload, &mut gossip_id(0, metric_kind)) } /// A vote's arrival is measured from the start of its own slot, not the @@ -540,6 +611,7 @@ mod tests { #[tokio::test] async fn a_decoded_votes_arrival_is_recorded_under_its_topic_kind() { let server = unconnected_beacon_server(config(), 0).await; + let _votes = one_vote_test_at_a_time(); let arrivals = |kind: &str| { let series = format!(r#"lean_beacon_pq_gossip_arrival_offset_seconds_count{{kind="{kind}"}}"#); @@ -591,6 +663,124 @@ mod tests { ); } + /// With the timing export on, a vote that decodes leaves its receipt + /// (when it arrived, what it is, how big, who signed) and, once judged, + /// its verdict under the same message id. A vote the node had already + /// seen is a duplicate there, not an ignored message. + #[tokio::test] + async fn a_votes_receipt_and_verdict_are_exported() { + use crate::beacon::verdict; + + let server = unconnected_beacon_server(config(), 0).await; + let _votes = one_vote_test_at_a_time(); + let capture = pq_timing::testing::capture(); + let mine = |events: Vec, message_id: &str| -> Vec { + let of = |event: &pq_timing::Value| event["message_id"] == message_id; + events.into_iter().filter(of).collect() + }; + + let mut attestation = pq::SingleAttestation { + committee_index: 2, + attester_index: 9, + data: Default::default(), + signature: Default::default(), + }; + attestation.data.slot = 5; + let payload = attestation.to_ssz(); + let topic = format!("{}3", beacon_topics::BEACON_ATTESTATION_PREFIX); + let mut id = gossip_id(0xa1, beacon_topics::BEACON_ATTESTATION_KIND); + assert!(triage(&server, &topic, &payload, &mut id).is_some()); + assert!(id.pq_vote.is_some()); + verdict::report(&server, id, Outcome::Ignore(IgnoreReason::AlreadySeen)); + + let message_id = format!("0x{}", "a1".repeat(20)); + let events = mine(capture.events(), &message_id); + assert_eq!(events.len(), 2, "{events:?}"); + let received = &events[0]; + assert_eq!(received["kind"], "message_received"); + assert_eq!(received["message_kind"], "individual"); + assert_eq!(received["source"], "network"); + assert_eq!(received["slot"], 5); + assert_eq!(received["reference_slot"], 5); + assert_eq!(received["committee"], 2); + assert_eq!(received["subnet"], 3); + assert_eq!(received["message_bytes"], payload.len()); + assert_eq!(received["signer_count"], 1); + let root = attestation.data.hash_tree_root(); + assert_eq!( + received["vote_data_root"], + format!("0x{}", hex::encode(root.0)) + ); + let validated = &events[1]; + assert_eq!(validated["kind"], "validated"); + assert_eq!(validated["message_kind"], "individual"); + assert_eq!(validated["outcome"], "duplicate"); + assert_eq!(validated["slot"], 5); + + // An aggregate of three attesters in committee 1. + let mut bits = pq::AggregationBits::with_length(8); + for position in [0, 3, 4] { + bits.set(position, true).unwrap(); + } + let mut committee_bits = pq::CommitteeBits::default(); + committee_bits.set(1, true).unwrap(); + let aggregate = pq::SignedAggregateAndProof { + message: pq::AggregateAndProof { + aggregator_index: 0, + aggregate: pq::Attestation { + aggregation_bits: bits, + data: attestation.data, + committee_bits, + }, + proof: Default::default(), + }, + signature: Default::default(), + }; + let topic = beacon_topics::BEACON_AGGREGATE_AND_PROOF; + let mut id = gossip_id(0xa2, topic); + assert!(triage(&server, topic, &aggregate.to_ssz(), &mut id).is_some()); + verdict::report(&server, id, Outcome::Accept); + + let events = mine(capture.events(), &format!("0x{}", "a2".repeat(20))); + assert_eq!(events.len(), 2, "{events:?}"); + assert_eq!(events[0]["message_kind"], "aggregate"); + assert_eq!(events[0]["committee"], 1); + assert_eq!(events[0]["subnet"], pq_timing::Value::Null); + assert_eq!(events[0]["signer_count"], 3); + assert_eq!(events[1]["outcome"], "accepted"); + + // Not a vote: nothing recorded, and its verdict leaves nothing. + let slashing = pq::ProposerSlashing::default(); + let mut id = gossip_id(0xa3, beacon_topics::PROPOSER_SLASHING); + triage( + &server, + beacon_topics::PROPOSER_SLASHING, + &slashing.to_ssz(), + &mut id, + ); + assert!(id.pq_vote.is_none()); + verdict::report(&server, id, Outcome::Ignore(IgnoreReason::AlreadySeen)); + assert!(mine(capture.events(), &format!("0x{}", "a3".repeat(20))).is_empty()); + } + + /// Without the export, a decoded vote is not noted for one. + #[tokio::test] + async fn a_vote_is_not_noted_when_no_run_is_recorded() { + let server = unconnected_beacon_server(config(), 0).await; + // The one test of this crate that captures holds the same lock. + let _votes = one_vote_test_at_a_time(); + let attestation = pq::SingleAttestation { + committee_index: 0, + attester_index: 0, + data: Default::default(), + signature: Default::default(), + }; + let topic = format!("{}0", beacon_topics::BEACON_ATTESTATION_PREFIX); + let mut id = gossip_id(0xa4, beacon_topics::BEACON_ATTESTATION_KIND); + assert!(triage(&server, &topic, &attestation.to_ssz(), &mut id).is_some()); + assert!(id.pq_vote.is_none()); + } + /// A block or a column takes the shared path under a PQ digest too. #[tokio::test] async fn a_pq_digests_block_topic_is_not_triaged_here() { diff --git a/crates/net/p2p/src/beacon/verdict.rs b/crates/net/p2p/src/beacon/verdict.rs index beedb9fd4..b2ba1028d 100644 --- a/crates/net/p2p/src/beacon/verdict.rs +++ b/crates/net/p2p/src/beacon/verdict.rs @@ -24,6 +24,7 @@ use ethlambda_state_transition::beacon::builder_market::SharedBuilderMarket; use ethlambda_state_transition::beacon::gossip::{self, IgnoreReason, Outcome}; use ethlambda_state_transition::beacon::helpers::accessors::CommitteeCacheExt as _; use ethlambda_storage::{CacheKey, Store}; +use ethlambda_telemetry::pq_timing; use ethlambda_types::beacon::containers::altair::{ SignedContributionAndProof, SyncCommitteeMessage, }; @@ -57,6 +58,9 @@ pub(crate) struct GossipId { pub(crate) received_at: Instant, /// The topic kind, as a metric label. See [`crate::beacon::topics::metric_kind`]. pub(crate) kind: &'static str, + /// The PQ vote this message decoded as, when the timing export recorded + /// its receipt: what [`report`] names it by in the `validated` event. + pub(crate) pq_vote: Option, } /// An object whose stateful checks run on a blocking thread. @@ -897,6 +901,24 @@ const RECHECK_POOL: &str = "recheck"; /// How many released votes one blocking task checks again. const RECHECK_BATCH: usize = 64; +/// A PQ vote's verdict as the timing export names it. A vote the node had +/// already seen, or whose bits an accepted aggregate covers, is a +/// `duplicate` rather than `ignored`, and one refused for want of a +/// validation permit is `queue_dropped`: neither says anything about the +/// message. A vote is never queued, so `deferred` is only for completeness. +fn pq_timing_outcome(outcome: Outcome) -> &'static str { + match outcome { + Outcome::Accept => "accepted", + Outcome::Reject(_) => "rejected", + Outcome::Queue(_) => "deferred", + Outcome::Ignore( + IgnoreReason::AlreadySeen | IgnoreReason::AlreadyStored | IgnoreReason::CoveredBits, + ) => "duplicate", + Outcome::Ignore(IgnoreReason::Overloaded) => "queue_dropped", + Outcome::Ignore(_) => "ignored", + } +} + /// How an outcome maps onto gossipsub, and whether the object still goes on /// towards the chain actor (see [`Validated::forward`] for the route). pub(crate) fn disposition(outcome: Outcome) -> (MessageAcceptance, bool) { @@ -919,6 +941,10 @@ pub(crate) fn report(server: &P2PServer, id: GossipId, outcome: Outcome) -> bool reason, id.received_at.elapsed(), ); + if let Some(vote) = id.pq_vote { + let outcome = pq_timing_outcome(outcome); + pq_timing::validated(vote, &id.message_id.0, id.received_at, outcome); + } server.swarm_handle.report_validation( id.message_id, id.propagation_source, @@ -2038,6 +2064,7 @@ mod tests { propagation_source: PeerId::random(), received_at, kind, + pq_vote: None, } } diff --git a/crates/net/p2p/src/gossipsub/handler.rs b/crates/net/p2p/src/gossipsub/handler.rs index 7eb04ceec..db4a9965c 100644 --- a/crates/net/p2p/src/gossipsub/handler.rs +++ b/crates/net/p2p/src/gossipsub/handler.rs @@ -82,6 +82,7 @@ pub async fn handle_gossip_message( propagation_source, received_at: wire_at, kind: metric_kind, + pq_vote: None, }); trace!( kind, @@ -230,7 +231,7 @@ async fn handle_lean_attestation(server: &mut P2PServer, payload: &[u8], compres fn handle_beacon_gossip( server: &P2PServer, ctx: &Context, - id: GossipId, + mut id: GossipId, topic: &str, kind: &str, payload: &[u8], @@ -250,7 +251,7 @@ fn handle_beacon_gossip( // A PQ digest's reshaped topics decode as PQ's containers; its block and // column topics take the shared path below. let pq_dispatch = (topic_fork == ForkName::Pq) - .then(|| crate::beacon::pq::triage(server, kind, payload, id.received_at)) + .then(|| crate::beacon::pq::triage(server, kind, payload, &mut id)) .flatten(); let dispatch = if let Some(dispatch) = pq_dispatch { dispatch diff --git a/crates/net/rpc/Cargo.toml b/crates/net/rpc/Cargo.toml index de9576f21..c4f23742d 100644 --- a/crates/net/rpc/Cargo.toml +++ b/crates/net/rpc/Cargo.toml @@ -20,6 +20,7 @@ ethlambda-blockchain.workspace = true ethlambda-engine.workspace = true ethlambda-fork-choice.workspace = true ethlambda-metrics.workspace = true +ethlambda-telemetry.workspace = true ethlambda-network-api.workspace = true ethlambda-state-transition.workspace = true ethlambda-storage.workspace = true @@ -44,6 +45,9 @@ rayon.workspace = true ethlambda-validator = { workspace = true, features = ["test-utils"] } spawned-concurrency.workspace = true ethlambda-state-transition = { workspace = true, features = ["test-utils"] } +# `test-utils` for `pq_timing::testing`: the PQ timing events the seat prover +# emits, captured in memory. +ethlambda-telemetry = { workspace = true, features = ["test-utils"] } ethlambda-types.workspace = true libssz-types.workspace = true tower = { version = "0.5", features = ["util"] } diff --git a/crates/net/rpc/src/beacon/pq_aggregation.rs b/crates/net/rpc/src/beacon/pq_aggregation.rs index 1b37fe3ed..93ad3b013 100644 --- a/crates/net/rpc/src/beacon/pq_aggregation.rs +++ b/crates/net/rpc/src/beacon/pq_aggregation.rs @@ -34,6 +34,7 @@ use ethlambda_storage::{ Store, pools::{CommitteeSignatures, PooledPqAggregate}, }; +use ethlambda_telemetry::pq_timing; use ethlambda_types::beacon::{ config::Config, constants::AGGREGATORS_PER_COMMITTEE, @@ -132,9 +133,26 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { let state_ms = started.elapsed().as_millis() as u64; let mut groups = store.pq_signature_pool().collected(slot, &committees); let committees = groups.len(); + // The timing export's job for one committee of this seat: wanted + // since the seat's cutoff, when this pass was spawned. + let seat_job = || pq_timing::job(pq_timing::Work::Committee, slot, slot, spawned); + let seat_fields = |committee: u64, signatures: usize| { + pq_timing::json!({ + "committee": committee, + "aggregator_position": position, + "signatures": signatures, + }) + }; // What an earlier seat of this node already proved in full is not // proved again: see `PqSignaturePool::is_proven`. - groups.retain(|group| !store.pq_signature_pool().is_proven(group)); + groups.retain(|group| { + let proven = store.pq_signature_pool().is_proven(group); + if proven { + let fields = || seat_fields(group.committee_index, group.signatures.len()); + seat_job().outcome("already_proven", fields); + } + !proven + }); let already_proven = committees - groups.len(); let signatures: usize = groups.iter().map(|group| group.signatures.len()).sum(); // The larger groups first, in case not every one fits before the @@ -142,15 +160,18 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { groups.sort_by_key(|group| std::cmp::Reverse(group.signatures.len())); let (mut proved, mut failed, mut late) = (0usize, 0usize, 0usize); let mut prove_ms_total = 0u64; - for group in groups { - if Instant::now() >= deadline { - warn!(%slot, position, "The PQ aggregate deadline passed with committees left to prove"); - break; - } + let mut groups = groups.into_iter().peekable(); + while let Some(group) = groups.next_if(|_| Instant::now() < deadline) { let committee = group.committee_index; let collected = group.signatures.len(); let committee_started = Instant::now(); - let result = prove_committee(&store, &state, group); + let job = seat_job(); + let timing = SeatTiming { + job: &job, + position, + deadline, + }; + let result = prove_committee(&store, &state, group, &timing); let took_ms = committee_started.elapsed().as_millis() as u64; let on_time = Instant::now() < deadline; // Every proof made, late ones too: a late one is what the seat's @@ -179,6 +200,13 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { took_ms, "Proved a PQ aggregate" ); + job.ready(|| { + let mut fields = seat_fields(committee, collected); + fields["claims"] = pq_timing::json!(aggregate.attesting_indices.len()); + fields["proof_id"] = + pq_timing::json!(pq_timing::proof_id(&aggregate.proof)); + fields + }); store.pq_aggregate_pool().insert((*aggregate).clone()); store.pq_signature_pool().insert_proven(aggregate); } @@ -211,6 +239,14 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { } } } + // Whatever the deadline, or a proof that ran past it, left unproved. + if groups.peek().is_some() { + warn!(%slot, position, "The PQ aggregate deadline passed with committees left to prove"); + } + for group in groups { + let fields = || seat_fields(group.committee_index, group.signatures.len()); + seat_job().outcome("unproved", fields); + } let unproved = committees - already_proven - proved - failed - late; let outcomes = [ ("proved", proved), @@ -251,11 +287,13 @@ async fn prove_seat(store: &Store, config: &Config, slot: Slot, position: u64) { /// `get_attestation_statements` lists their keys in. /// /// Also returns how long the proof itself took: the rest of the call is -/// reading the committee and assembling the statements. +/// reading the committee and assembling the statements. `timing` is told +/// when the prover is called and when it returns. fn prove_committee( store: &Store, state: &BeaconState, group: CommitteeSignatures, + timing: &SeatTiming<'_>, ) -> Result<(Arc, Duration), String> { let committees = store.committee_cache(); let epoch_committees = committees.committees(state, group.data.target.epoch); @@ -288,13 +326,30 @@ fn prove_committee( }; let statements = get_attestation_statements(state, &attestation, &committees) .map_err(|err| err.to_string())?; + let timing_fields = { + let (committee_size, signatures) = (committee.len(), signatures.len()); + move || { + pq_timing::json!({ + "committee": group.committee_index, + "aggregator_position": timing.position, + "signatures": signatures, + "committee_size": committee_size, + }) + } + }; + timing.job.started(timing_fields); let proving = Instant::now(); let proof = ethlambda_state_transition::beacon::helpers::pq::prove_aggregates( &statements, &[signatures], ) - .map_err(|err| err.to_string())?; + .map_err(|err| err.to_string()); let proving = proving.elapsed(); + let late = Instant::now() >= timing.deadline; + timing + .job + .finished(proving, late, proof.as_deref().ok(), timing_fields); + let proof = proof?; attesting_indices.sort_unstable(); let aggregate = Arc::new(PooledPqAggregate { attestation, @@ -307,6 +362,15 @@ fn prove_committee( Ok((aggregate, proving)) } +/// What [`prove_committee`] reports its proof to the timing export with. +struct SeatTiming<'a> { + job: &'a pq_timing::Job, + /// The aggregator's seat. + position: u64, + /// The seat's broadcast time: a proof finished after it is late. + deadline: Instant, +} + fn now_ms() -> u64 { SystemTime::now() .duration_since(UNIX_EPOCH) @@ -352,6 +416,10 @@ mod tests { /// position, and each committee it was due to prove under its outcome. /// The next seat, with nothing new to prove, counts the committee as /// already proven and times nothing. + /// + /// The timing export gets the same story as events: the proof started, + /// finished and ready for seat 0's job, and the committee already proven + /// for seat 1's. #[tokio::test] async fn a_seats_proving_pass_is_timed_and_counted() { let mut state = with_validators_at(ForkName::Pq, 256); @@ -417,6 +485,9 @@ mod tests { }; let signatures_before = series_value("lean_beacon_pq_committee_proof_signatures_sum").unwrap_or(0.0); + // Nothing else in this crate's tests proves a seat, so every work + // event captured is this test's. + let capture = pq_timing::testing::capture(); prove_seat(&store, &config, slot, 0).await; assert_eq!(store.pq_aggregate_pool().candidates(slot).len(), 1); @@ -442,6 +513,47 @@ mod tests { assert_eq!(count("already_proven", 1), 1.0); assert_eq!(count("proved", 1), 0.0); assert_eq!(timed(1), 0.0); + + let events = capture.events(); + let kinds: Vec<&str> = events.iter().map(|e| e["kind"].as_str().unwrap()).collect(); + assert_eq!( + kinds, + [ + "proof_started", + "proof_finished", + "candidate_ready", + "job_outcome" + ] + ); + for event in &events { + assert_eq!(event["work"], "committee"); + assert_eq!(event["origin"], "production"); + assert_eq!(event["slot"], slot); + assert_eq!(event["reference_slot"], slot); + assert_eq!(event["sequence_id"], format!("production:{slot}")); + assert_eq!(event["committee"], committee); + assert_eq!(event["signatures"], members.len()); + } + let (started, finished, ready, already) = (&events[0], &events[1], &events[2], &events[3]); + for event in [started, finished, ready] { + assert_eq!(event["job_id"], started["job_id"]); + assert_eq!(event["aggregator_position"], 0); + } + assert_eq!(started["committee_size"], members.len()); + assert!(started["queue_wait_ns"].is_u64()); + assert_eq!(finished["outcome"], "success"); + assert_eq!(finished["late"], false); + let proof = store.pq_aggregate_pool().candidates(slot)[0].proof.clone(); + assert_eq!(finished["proof_bytes"], proof.len()); + assert_eq!(finished["proof_id"], pq_timing::proof_id(&proof)); + assert!(finished["backend_duration_ns"].is_u64()); + assert_eq!(ready["outcome"], "ready"); + assert_eq!(ready["proof_id"], finished["proof_id"]); + assert_eq!(ready["claims"], members.len()); + // Seat 1 made no proof: its own job says why. + assert_eq!(already["outcome"], "already_proven"); + assert_eq!(already["aggregator_position"], 1); + assert_ne!(already["job_id"], started["job_id"]); } #[test] diff --git a/crates/net/rpc/src/beacon/pq_proposal.rs b/crates/net/rpc/src/beacon/pq_proposal.rs index ce98e052b..a5cbfdc52 100644 --- a/crates/net/rpc/src/beacon/pq_proposal.rs +++ b/crates/net/rpc/src/beacon/pq_proposal.rs @@ -319,9 +319,34 @@ async fn attestations_for_block( proof_bytes = packed.proof.len(), "Collected the PQ attestations packed ahead of the slot" ); + proposal_snapshot(slot, &packed.attestations, &packed.proof, true); return (packed.attestations, packed.proof); } } let packed = pack_attestations(store, state, config, PermitWait::TryOnce).await; + proposal_snapshot(slot, &packed.attestations, &packed.proof, false); (packed.attestations, packed.proof) } + +/// Tell the timing export what a block at `slot` was built with: the +/// attestations and proof production took, and whether they are the ones +/// packed ahead of the slot. +fn proposal_snapshot(slot: Slot, attestations: &[pq::Attestation], proof: &[u8], ahead: bool) { + use ethlambda_telemetry::pq_timing; + use ethlambda_types::beacon::preset::MIN_ATTESTATION_INCLUSION_DELAY_PQ; + + let outcome = if attestations.is_empty() { + "no_candidate" + } else { + "candidate" + }; + let reference_slot = slot.saturating_sub(MIN_ATTESTATION_INCLUSION_DELAY_PQ); + pq_timing::proposal_snapshot(slot, reference_slot, outcome, || { + pq_timing::json!({ + "proof_id": pq_timing::proof_id(proof), + "proof_bytes": proof.len(), + "records": attestations.len(), + "packed_ahead": ahead, + }) + }); +} diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md index da5ce005b..8c05c964c 100644 --- a/docs/SUMMARY.md +++ b/docs/SUMMARY.md @@ -25,6 +25,7 @@ - [HTTP API](./rpc.md) - [Metrics](./metrics.md) - [Block telemetry (ClickHouse)](./telemetry.md) +- [PQ timing export](./pq_timing.md) - [Checkpoint Sync](./checkpoint_sync.md) - [Fork Choice Visualization](./fork_choice_visualization.md) - [Data Storage](./data_storage.md) diff --git a/docs/beacon_pq.md b/docs/beacon_pq.md index 434b4362b..6a58deff7 100644 --- a/docs/beacon_pq.md +++ b/docs/beacon_pq.md @@ -191,7 +191,9 @@ proofs through one of two backends, chosen once per process: - **What it costs on a running node.** The node's `/metrics` times every committee proof, block-proof merge and proof verification, and when in the slot attestations and aggregates arrive: see - [metrics.md](./metrics.md#pq-aggregation-timing). + [metrics.md](./metrics.md#pq-aggregation-timing). `--pq-timing-output` + records the same as events, in the format the PQ devnets' clients share: + see [pq_timing.md](./pq_timing.md). pq-devnet-0 ran the prover as a separate `leanvm-sidecar` (bindings v0.15.0), which the image built and its `ethlambda-pq` supervisor started and diff --git a/docs/cli.md b/docs/cli.md index 5d70b2a2e..33095c381 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -166,6 +166,7 @@ something specific here. | `--network` | `mainnet` | A built-in network name (`mainnet`, `sepolia`, `hoodi` or `plataberget`), or a path to a directory of published network files. A value containing a slash is always a path, so `mainnet` is the built-in and `./mainnet` is a directory. The directory must hold `config.yaml` and `genesis.ssz`, and may hold `bootstrap_nodes.yaml` or `bootstrap_nodes.txt` | | `--bootnodes` | none: the network's own list alone | Extra bootnodes: ENRs and multiaddrs, comma-separated, and the flag may be repeated. Added to the resolved network's own list, never replacing it. A bad entry is a startup error, and a file path is no longer accepted. See [Bootnodes on `beacon`](#bootnodes-on-beacon) | | `--pq-prover-threads` | `0` | How many threads leanVM's in-process prover runs on, 0 for one per core; more than the machine's cores are lowered to them with a warning. Read only on a network that schedules PQ, where the node makes and checks the fork's attestation proofs with leanVM bindings v0.19.0 (`351f7ae4`, the release pq-devnet-1 runs, and the only one it takes). The node proves and verifies one signature at startup and refuses to start if that fails. The image's `ethlambda-pq` script, pq-devnet-0's sidecar supervisor, is now a shim that execs `ethlambda` and maps `LEANVM_THREADS` to this flag | +| `--pq-timing-output` | off | A directory to record PQ gossip and proving timings under, one sub-directory per run, in the format the PQ devnets' clients share (schema 1 of Lighthouse's `scripts/pq-measurement`): when each PQ attestation and aggregate arrived and what validation made of it, and every committee proof and block-proof merge this node made. Read only on a network that schedules PQ; a directory that cannot be created is a startup error. A run keeps at most 8 GiB. See [pq_timing.md](./pq_timing.md) | `genesis_validators_root` and `genesis_time`, which the fork digest that keys every gossip topic, the ENR `eth2` entry and discv5 admission is computed from, diff --git a/docs/metrics.md b/docs/metrics.md index 40cdecb4d..5cd3c8c39 100644 --- a/docs/metrics.md +++ b/docs/metrics.md @@ -921,6 +921,7 @@ once the node has done the work they measure, and lean nodes never emit them. | `lean_beacon_pq_merges_total` | Counter | Packings with several proofs to merge, by what became of the merge | Once per such packing | phase=ahead,production, outcome=merged,failed,late,skipped | | | `lean_beacon_pq_proof_verification_seconds` | Histogram | Time to verify one attestation proof | On each aggregate that reached the proof check, and each block with attestations whose transition ran | kind=aggregate,block | 0.001, 0.0025, 0.005, 0.0075, 0.01, 0.015, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2 | | `lean_beacon_pq_gossip_arrival_offset_seconds` | Histogram | How far into its vote's slot an attestation or aggregate arrived on gossip | On each one decoded, before any rule judges it | kind=beacon_attestation,beacon_aggregate_and_proof | 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 4.8, 6, 7.2, 7.5, 7.8, 8.1, 8.4, 8.7, 9, 9.5, 10, 12, 24 | +| `lean_beacon_pq_timing_dropped_events_total` | Counter | Events the PQ timing export dropped because its queue was full | On each such event, only with `--pq-timing-output` | class=receipt,validation,work,status | | **Committee proofs.** `position` is the aggregator's seat in its committee's aggregation committee. Seat `p` stops collecting at 40% + `p` × 5% of the slot @@ -964,6 +965,11 @@ whatever validation then makes of it, and none of this node's own: gossip never hands a node its messages back. The time from arrival to verdict is `lean_beacon_gossip_validation_seconds`, under the same `kind` values. +**The export.** `--pq-timing-output` writes each of these as an event rather +than a sample (see [pq_timing.md](./pq_timing.md)). +`lean_beacon_pq_timing_dropped_events_total` rising means its writer is not +keeping up and the run has gaps, which its `run.json` counts too. + --- ✅(*) **Partial support**: These metrics are implemented but not collected "on scrape" as the spec requires. They are updated on specific events (e.g., on tick, on block processing) rather than being computed fresh on each Prometheus scrape. diff --git a/docs/pq_timing.md b/docs/pq_timing.md new file mode 100644 index 000000000..21c992ee1 --- /dev/null +++ b/docs/pq_timing.md @@ -0,0 +1,177 @@ +# PQ timing export + +On a network that schedules the PQ fork, `ethlambda beacon --pq-timing-output +` records when PQ attestations and aggregates reach the node, what +validation makes of them, and every attestation proof the node makes, as +events in a local directory. + +The format is the one the PQ devnets' clients share: schema 1 of Lighthouse's +[`scripts/pq-measurement`](https://github.com/sigp/lighthouse/tree/pq-devnet-1/scripts/pq-measurement), +which Prysm, Teku and Lodestar write too. One report script then draws every +client's runs side by side, which is how the devnets compare aggregation +timings between clients. The Prometheus metrics in +[metrics.md](./metrics.md#pq-aggregation-timing) answer the same questions as +distributions; this export keeps each event. + +## Recording a run + +```sh +ethlambda beacon --network /path/to/devnet --pq-timing-output /data/pq-timing ... +``` + +Each start creates one run directory under it, named +`-<16 hex digits>`, and logs it as `Recording PQ timing`. +The flag is off by default, a directory that cannot be created is a startup +error, and on a network that does not schedule PQ the flag only logs a warning. + +Stop the node normally (`SIGTERM` or ctrl+c) and the run is finished: its last +chunk is closed and listed in `run.json`, which gets an `ended_unix_ns`. A node +that is killed leaves its last chunk as `events-NNNNNN.jsonl.zst.partial`, +which no manifest lists; it is flushed every 10 seconds, so it still decodes up +to its last flush. + +## Reading a run + +Lighthouse's report script reads a run directory as it is: + +```sh +python3 -m pip install 'matplotlib>=3.10,<4' 'zstandard>=0.20,<1' +python3 scripts/pq-measurement/plot.py /data/pq-timing/ --output reports +``` + +It needs Python 3.10 or newer. A chunk is also readable by hand: +`zstd -dc events-000001.jsonl.zst | jq .` + +## The run directory + +| File | What it is | +|---|---| +| `run.json` | The manifest, rewritten whole whenever a chunk is finished and every 10 seconds | +| `events-NNNNNN.jsonl.zst` | A finished chunk: zstd-compressed JSON lines, one event each | +| `events-NNNNNN.jsonl.zst.partial` | The chunk being written | + +A chunk is finished after 64 MiB of events (before compression) or five +minutes. A run keeps at most 8 GiB of finished chunks: past that the oldest +are removed, and `recorder_status` says how many and which events they held. + +`run.json` holds: + +- **What ran**: `schema_version` (1), `run_id`, `client` (`ethlambda`), + `ethlambda_version`, `network`, `genesis_time`, `genesis_slot`, + `genesis_validators_root`, `started_unix_ns`, `ended_unix_ns`, and + `observer` (always `false`: every event is this node's own workload). +- **The prover**: `prover_backend`, `leanvm_revision`, + `leanvm_protocol_version`, `prover_log_inv_rate`, `prover_threads` (null + when `--pq-prover-threads` left the count to leanVM) and + `prover_threads_configured`. `prover_cpu_profile` is null, since leanVM + picks its CPU tier itself; `prover_cpu_profile_requested` is `LEANVM_TIER` + when that is set. +- **`hardware`**: architecture, operating system, kernel, CPU model, cores, + CPU affinity and memory, and the cgroup's CPU quota and memory limit, so a + container reports what it was given. Read from `/proc` and the cgroup v2 + tree: off Linux most of it is null. +- **`timing`**: where in a slot this node does each step, in nanoseconds from + the start of the vote's slot. A report draws its reference lines there. +- **`receive_point`**: where a receipt is stamped (see `message_received`). +- **`chunks`**: the finished chunks, each with its name, size and the first + and last sequence numbers it holds. A reader takes the events from these. +- **`recorder_status`**: events submitted, events dropped by class, chunks + removed, and whether a write failed (after which the export stops). + +`timing` on a 12-second slot: + +| Key | Value | What happens then | +|---|---|---| +| `slot_ns` | 12 s | | +| `attestation_ns` | 3 s | Attestations are due | +| `committee_collection_ns` | 4.8 s | The first aggregator seat stops collecting and proves | +| `aggregator_delay_ns` | 0.6 s | Each following seat does so this much later | +| `aggregate_ns` | 7.2 s | The first seat broadcasts | +| `initial_merge_ns` | 20 s | The merge ahead of the block two slots later starts | +| `proposal_lag_slots` | 2 | A block's newest votes are two slots old | + +## Events + +Every line has `seq` (the order events were submitted in), `kind`, `wall_ns` +(UNIX time) and `mono_ns` (a monotonic clock, from the run's start), and +`reference_slot`: the slot of the votes the event is about, which is what a +report places it on a timeline by. + +| `kind` | When | Fields of its own | +|---|---|---| +| `message_received` | A PQ attestation or aggregate arrived from gossip | `message_kind` (`individual`, `aggregate`), `message_id`, `source` (`network`), `slot`, `committee`, `subnet`, `message_bytes`, `byte_basis` (`decoded_ssz`), `signer_count`, `vote_data_root` | +| `validated` | That message got its verdict | `message_kind`, `message_id`, `outcome`, `receipt_to_validation_ns` | +| `proof_started` | leanVM is about to be called | the job's fields, `queue_wait_ns`, and the proof's inputs | +| `proof_finished` | It returned | the job's fields, `outcome` (`success`, `failed`), `backend_duration_ns`, `late`, `proof_bytes`, `proof_id` | +| `candidate_ready` | The proof is where its consumer takes it from | the job's fields, `proof_id` | +| `job_outcome` | A proof that was due was not made | the job's fields, `outcome` | +| `proposal_snapshot` | Block production took what it has for the block | `outcome` (`candidate`, `no_candidate`), `sequence_id`, `proof_id`, `proof_bytes`, `records`, `packed_ahead` | + +**Receipts.** `message_received` is stamped when gossipsub delivered the +message: before Snappy decompression and SSZ decode, and after gossipsub's +duplicate cache, so each message is received once. It is recorded for every +vote that decodes, whatever validation then decides. This node's own +attestations and aggregates are not in the export: gossip never hands a node +its messages back. + +**Verdicts.** `outcome` is `accepted`, `rejected`, `ignored`, `duplicate` (the +node had already seen the vote, or an accepted aggregate covers its bits) or +`queue_dropped` (no validation permit was free). A single attestation for a +block still being imported waits for it and gets its verdict then, so its +`receipt_to_validation_ns` includes that wait. + +**Jobs.** The proof events share the fields of the job they belong to: +`job_id`, `work`, `round`, `slot`, `reference_slot`, `origin` (`production`), +`scenario` (`production`), `sequence_id` (`production:`) and +`enqueued_wall_ns`. `work` is what the proof is of: + +| `work` | `round` | The proof | `slot` | `reference_slot` | +|---|---|---|---|---| +| `committee` | 1 | One committee's signatures, for an aggregator seat of this node | the votes' | the same | +| `initial` | 1 | A block's attestation proofs merged ahead of its slot | the block's | two slots before | +| `improvement` | 2 | The same at block production, when the merge ahead cannot be used | the block's | two slots before | + +A committee job's events also carry `committee`, `aggregator_position` (the +seat) and `signatures`, and its two proof events `committee_size`. A merge's +proof events carry `input_proof_count`, `records` (attestations) and `claims` +(signatures). + +- **`queue_wait_ns`**: for a committee, the time since its seat's cutoff, so a + seat's second committee waits for its first; for a merge, the wait for the + one merge permit and a blocking thread. +- **`backend_duration_ns`**: the call into leanVM, which includes any wait for + a proof it was already making: it makes one at a time. +- **`late`**: a committee proof finished after its seat's broadcast time (it + is discarded), or a merge outlived its budget (the block packs one + committee's attestation). +- **`proof_id`**: the SHA-256 of the proof, which follows a proof from the job + that made it to the snapshot of the block that carries it. No proof or + signature is exported. +- **`candidate_ready`**: a committee's aggregate is in the pool the validator + client's `aggregate_attestation` reads, or a block's packing is complete. + `backend_call` is `false` for a packing of one proof, which is the block's + as it is and makes no proof event. +- **`job_outcome`**: `already_proven` (an earlier seat of this node proved + every vote collected), `unproved` (the seat's time ran out first), or + `skipped` (a merge with no time left, or with another merge holding + leanVM; its `reason` says which). + +## What it costs + +Nothing is built for a node that does not record: each emitter returns after +one atomic load. For one that does, an event is a JSON object pushed onto a +queue of 16,384; a writer thread serializes, compresses and writes. A full +queue drops the event and never waits: the drop is counted in +`recorder_status.dropped` and in `lean_beacon_pq_timing_dropped_events_total`. + +## What is not recorded + +- **An observer mode.** The other clients' `--pq-measurement` makes a node + without validators prove what the network sends, every third slot, and + publish nothing. ethlambda records only its real workload, so a node with no + aggregators or proposers writes receipts and verdicts and no proof events. +- **`fallback` proofs.** Some clients prove a committee's raw signatures while + packing a block. ethlambda's block production merges aggregates only, so it + never emits that kind of work. +- **A later verdict of the same message.** Each message gets one `validated` + event; none is `deferred`.