Skip to main content

reth_engine_tree/tree/
metrics.rs

1use crate::tree::{payload_processor::reuse::ReuseMiss, TreeOutcome};
2use alloy_rpc_types_engine::{PayloadStatus, PayloadStatusEnum};
3use reth_concurrency::sync::time::FastInstant as Instant;
4use reth_engine_primitives::{ForkchoiceStatus, InsertBlockProcessingError, OnForkChoiceUpdated};
5use reth_errors::ProviderError;
6use reth_evm::metrics::ExecutorMetrics;
7use reth_execution_types::BlockExecutionOutput;
8use reth_metrics::{
9    metrics::{Counter, Gauge, Histogram},
10    thread::{ThreadResourceUsage, ThreadResourceUsageDelta},
11    Metrics,
12};
13use reth_primitives_traits::constants::gas_units::MEGAGAS;
14use reth_trie::updates::TrieUpdates;
15use std::time::Duration;
16
17/// Upper bounds for each gas bucket. The last bucket is a catch-all for
18/// everything above the final threshold: <5M, 5-10M, 10-20M, 20-30M, 30-40M, >40M.
19const GAS_BUCKET_THRESHOLDS: [u64; 5] =
20    [5 * MEGAGAS, 10 * MEGAGAS, 20 * MEGAGAS, 30 * MEGAGAS, 40 * MEGAGAS];
21
22/// Total number of gas buckets (thresholds + 1 catch-all).
23const NUM_GAS_BUCKETS: usize = GAS_BUCKET_THRESHOLDS.len() + 1;
24
25/// Metrics for the `EngineApi`.
26#[derive(Debug, Default)]
27pub struct EngineApiMetrics {
28    /// Engine API-specific metrics.
29    pub engine: EngineMetrics,
30    /// Block executor metrics.
31    pub executor: ExecutorMetrics,
32    /// Metrics for block validation
33    pub block_validation: BlockValidationMetrics,
34    /// Canonical chain and reorg related metrics
35    pub tree: TreeMetrics,
36    /// Metrics for EIP-7928 Block-Level Access Lists (BAL).
37    #[allow(dead_code)]
38    pub(crate) bal: BalMetrics,
39    /// Gas-bucketed execution sub-phase metrics.
40    pub(crate) execution_gas_buckets: ExecutionGasBucketMetrics,
41    /// Gas-bucketed block validation sub-phase metrics.
42    pub(crate) block_validation_gas_buckets: BlockValidationGasBucketMetrics,
43    /// Metrics for reusing transaction prewarming results.
44    pub(crate) prewarm_reuse: PrewarmReuseMetrics,
45}
46
47impl EngineApiMetrics {
48    /// Records metrics for block execution.
49    ///
50    /// This method updates metrics for execution time, gas usage, and the number
51    /// of accounts, storage slots and bytecodes updated.
52    pub fn record_block_execution<R>(
53        &self,
54        output: &BlockExecutionOutput<R>,
55        execution_duration: Duration,
56    ) {
57        let execution_secs = execution_duration.as_secs_f64();
58        let gas_used = output.result.gas_used;
59
60        // Update gas metrics
61        self.executor.gas_processed_total.increment(gas_used);
62        self.executor.gas_per_second.set(gas_used as f64 / execution_secs);
63        self.executor.gas_used_histogram.record(gas_used as f64);
64        self.executor.execution_histogram.record(execution_secs);
65        self.executor.execution_duration.set(execution_secs);
66
67        // Update the metrics for the number of accounts, storage slots and bytecodes
68        let accounts = output.state.len();
69        let storage_slots =
70            output.state.state.values().map(|account| account.storage.len()).sum::<usize>();
71        let bytecodes = output.state.contracts.len();
72
73        self.executor.accounts_updated_histogram.record(accounts as f64);
74        self.executor.storage_slots_updated_histogram.record(storage_slots as f64);
75        self.executor.bytecodes_updated_histogram.record(bytecodes as f64);
76    }
77
78    /// Returns a reference to the executor metrics for use in state hooks.
79    pub const fn executor_metrics(&self) -> &ExecutorMetrics {
80        &self.executor
81    }
82
83    /// Records the duration of block pre-execution changes (e.g., beacon root update).
84    pub fn record_pre_execution(&self, elapsed: Duration) {
85        self.executor.pre_execution_histogram.record(elapsed);
86    }
87
88    /// Records the duration of block post-execution changes (e.g., finalization).
89    pub fn record_post_execution(&self, elapsed: Duration) {
90        self.executor.post_execution_histogram.record(elapsed);
91    }
92
93    /// Records execution duration into the gas-bucketed execution histogram.
94    pub fn record_block_execution_gas_bucket(&self, gas_used: u64, elapsed: Duration) {
95        let idx = GasBucketMetrics::bucket_index(gas_used);
96        self.execution_gas_buckets.buckets[idx]
97            .execution_gas_bucket_histogram
98            .record(elapsed.as_secs_f64());
99    }
100
101    /// Records state root duration into the gas-bucketed block validation histogram.
102    pub fn record_state_root_gas_bucket(&self, gas_used: u64, elapsed_secs: f64) {
103        let idx = GasBucketMetrics::bucket_index(gas_used);
104        self.block_validation_gas_buckets.buckets[idx]
105            .state_root_gas_bucket_histogram
106            .record(elapsed_secs);
107    }
108
109    /// Records the time spent waiting for the next transaction from the iterator.
110    pub fn record_transaction_wait(&self, elapsed: Duration) {
111        self.executor.transaction_wait_histogram.record(elapsed);
112    }
113
114    /// Records the duration of a single transaction execution.
115    pub fn record_transaction_execution(&self, elapsed: Duration) {
116        self.executor.transaction_execution_histogram.record(elapsed);
117    }
118}
119
120/// Metrics for reusing transaction prewarming results during block execution.
121#[derive(Metrics)]
122#[metrics(scope = "sync.prewarm.reuse")]
123pub(crate) struct PrewarmReuseMetrics {
124    /// Transactions committed from prewarm results.
125    reused_transactions: Counter,
126    /// Transactions executed because prewarming had not finished them.
127    missing_transactions: Counter,
128    /// Transactions executed because a prewarm result was unusable or failed reuse checks.
129    stale_transactions: Counter,
130}
131
132impl PrewarmReuseMetrics {
133    /// Records the reuse outcomes of a block.
134    pub(crate) fn record(&self, stats: PrewarmReuseStats) {
135        self.reused_transactions.increment(stats.reused);
136        self.missing_transactions.increment(stats.missing);
137        self.stale_transactions.increment(stats.stale);
138    }
139}
140
141/// Prewarm result reuse outcomes of a block.
142#[derive(Debug, Default, Clone, Copy)]
143pub(crate) struct PrewarmReuseStats {
144    reused: u64,
145    missing: u64,
146    stale: u64,
147}
148
149impl PrewarmReuseStats {
150    /// Records the reuse outcome of a transaction.
151    pub(crate) const fn record(&mut self, outcome: Result<(), ReuseMiss>) {
152        match outcome {
153            Ok(()) => self.reused += 1,
154            Err(ReuseMiss::Missing) => self.missing += 1,
155            Err(ReuseMiss::Stale) => self.stale += 1,
156        }
157    }
158}
159
160/// Metrics for the entire blockchain tree
161#[derive(Metrics)]
162#[metrics(scope = "blockchain_tree")]
163pub struct TreeMetrics {
164    /// The highest block number in the canonical chain
165    pub canonical_chain_height: Gauge,
166    /// Metrics for reorgs.
167    #[metric(skip)]
168    pub reorgs: ReorgMetrics,
169    /// The latest reorg depth
170    pub latest_reorg_depth: Gauge,
171    /// The current safe block height (this is required by optimism)
172    pub safe_block_height: Gauge,
173    /// The current finalized block height (this is required by optimism)
174    pub finalized_block_height: Gauge,
175}
176
177/// Metrics for reorgs.
178#[derive(Debug)]
179pub struct ReorgMetrics {
180    /// The number of head block reorgs
181    pub head: Counter,
182    /// The number of safe block reorgs
183    pub safe: Counter,
184    /// The number of finalized block reorgs
185    pub finalized: Counter,
186}
187
188impl Default for ReorgMetrics {
189    fn default() -> Self {
190        Self {
191            head: metrics::counter!("blockchain_tree_reorgs", "commitment" => "head"),
192            safe: metrics::counter!("blockchain_tree_reorgs", "commitment" => "safe"),
193            finalized: metrics::counter!("blockchain_tree_reorgs", "commitment" => "finalized"),
194        }
195    }
196}
197
198/// Metrics for the `EngineApi`.
199#[derive(Metrics)]
200#[metrics(scope = "consensus.engine.beacon")]
201pub struct EngineMetrics {
202    /// Engine API forkchoiceUpdated response type metrics
203    #[metric(skip)]
204    pub(crate) forkchoice_updated: ForkchoiceUpdatedMetrics,
205    /// Engine API newPayload response type metrics
206    #[metric(skip)]
207    pub(crate) new_payload: NewPayloadStatusMetrics,
208    /// How many executed blocks are currently stored.
209    pub(crate) executed_blocks: Gauge,
210    /// How many already executed blocks were directly inserted into the tree.
211    pub(crate) inserted_already_executed_blocks: Counter,
212    /// The number of times the pipeline was run.
213    pub(crate) pipeline_runs: Counter,
214    /// Newly arriving block hash is not present in executed blocks cache storage
215    pub(crate) executed_new_block_cache_miss: Counter,
216    /// Histogram of persistence operation durations (in seconds)
217    pub(crate) persistence_duration: Histogram,
218    /// Whether the engine loop is currently stalled on persistence backpressure.
219    pub(crate) backpressure_active: Gauge,
220    /// Time spent blocked waiting on persistence because backpressure was active.
221    pub(crate) backpressure_stall_duration: Histogram,
222    /// Tracks the how often we failed to deliver a newPayload response.
223    ///
224    /// This effectively tracks how often the message sender dropped the channel and indicates a CL
225    /// request timeout (e.g. it took more than 8s to send the response and the CL terminated the
226    /// request which resulted in a closed channel).
227    pub(crate) failed_new_payload_response_deliveries: Counter,
228    /// Tracks the how often we failed to deliver a forkchoice update response.
229    pub(crate) failed_forkchoice_updated_response_deliveries: Counter,
230    /// block insert duration
231    pub(crate) block_insert_total_duration: Histogram,
232}
233
234/// Metrics for engine forkchoiceUpdated responses.
235#[derive(Metrics)]
236#[metrics(scope = "consensus.engine.beacon")]
237pub(crate) struct ForkchoiceUpdatedMetrics {
238    /// Finish time of the latest forkchoice updated call.
239    #[metric(skip)]
240    pub(crate) latest_finish_at: Option<Instant>,
241    /// Start time of the latest forkchoice updated call.
242    #[metric(skip)]
243    pub(crate) latest_start_at: Option<Instant>,
244    /// The total count of forkchoice updated messages received.
245    pub(crate) forkchoice_updated_messages: Counter,
246    /// The total count of forkchoice updated messages with payload received.
247    pub(crate) forkchoice_with_attributes_updated_messages: Counter,
248    /// The total count of forkchoice updated messages that we responded to with
249    /// [`Valid`](ForkchoiceStatus::Valid).
250    pub(crate) forkchoice_updated_valid: Counter,
251    /// The total count of forkchoice updated messages that we responded to with
252    /// [`Invalid`](ForkchoiceStatus::Invalid).
253    pub(crate) forkchoice_updated_invalid: Counter,
254    /// The total count of forkchoice updated messages that we responded to with
255    /// [`Syncing`](ForkchoiceStatus::Syncing).
256    pub(crate) forkchoice_updated_syncing: Counter,
257    /// The total count of forkchoice updated messages that were unsuccessful, i.e. we responded
258    /// with an error type that is not a [`PayloadStatusEnum`].
259    pub(crate) forkchoice_updated_error: Counter,
260    /// Latency for the forkchoice updated calls.
261    pub(crate) forkchoice_updated_latency: Histogram,
262    /// Latency for the last forkchoice updated call.
263    pub(crate) forkchoice_updated_last: Gauge,
264    /// Time diff between new payload call response and the next forkchoice updated call request.
265    pub(crate) new_payload_forkchoice_updated_time_diff: Histogram,
266    /// Time from previous forkchoice updated finish to current forkchoice updated start (idle
267    /// time).
268    pub(crate) time_between_forkchoice_updated: Histogram,
269    /// Time from previous forkchoice updated start to current forkchoice updated start (total
270    /// interval).
271    pub(crate) forkchoice_updated_interval: Histogram,
272}
273
274impl ForkchoiceUpdatedMetrics {
275    /// Increment the forkchoiceUpdated counter based on the given result
276    pub(crate) fn update_response_metrics(
277        &mut self,
278        start: Instant,
279        latest_new_payload_at: &mut Option<Instant>,
280        has_attrs: bool,
281        result: &Result<TreeOutcome<OnForkChoiceUpdated>, ProviderError>,
282    ) {
283        let finish = Instant::now();
284        let elapsed = finish - start;
285
286        if let Some(prev_finish) = self.latest_finish_at {
287            self.time_between_forkchoice_updated.record(start - prev_finish);
288        }
289        if let Some(prev_start) = self.latest_start_at {
290            self.forkchoice_updated_interval.record(start - prev_start);
291        }
292        self.latest_finish_at = Some(finish);
293        self.latest_start_at = Some(start);
294
295        match result {
296            Ok(outcome) => match outcome.outcome.forkchoice_status() {
297                ForkchoiceStatus::Valid => self.forkchoice_updated_valid.increment(1),
298                ForkchoiceStatus::Invalid => self.forkchoice_updated_invalid.increment(1),
299                ForkchoiceStatus::Syncing => self.forkchoice_updated_syncing.increment(1),
300            },
301            Err(_) => self.forkchoice_updated_error.increment(1),
302        }
303        self.forkchoice_updated_messages.increment(1);
304        if has_attrs {
305            self.forkchoice_with_attributes_updated_messages.increment(1);
306        }
307        self.forkchoice_updated_latency.record(elapsed);
308        self.forkchoice_updated_last.set(elapsed);
309        if let Some(latest_new_payload_at) = latest_new_payload_at.take() {
310            self.new_payload_forkchoice_updated_time_diff.record(start - latest_new_payload_at);
311        }
312    }
313}
314
315/// Per-gas-bucket newPayload metrics, initialized once via [`Self::new_with_labels`].
316#[derive(Clone, Metrics)]
317#[metrics(scope = "consensus.engine.beacon")]
318pub(crate) struct NewPayloadGasBucketMetrics {
319    /// Latency for new payload calls in this gas bucket.
320    pub(crate) new_payload_gas_bucket_latency: Histogram,
321    /// Gas per second for new payload calls in this gas bucket.
322    pub(crate) new_payload_gas_bucket_gas_per_second: Histogram,
323}
324
325/// Holds pre-initialized [`NewPayloadGasBucketMetrics`] instances, one per gas bucket.
326#[derive(Debug)]
327pub(crate) struct GasBucketMetrics {
328    buckets: [NewPayloadGasBucketMetrics; NUM_GAS_BUCKETS],
329}
330
331impl Default for GasBucketMetrics {
332    fn default() -> Self {
333        Self {
334            buckets: std::array::from_fn(|i| {
335                let label = Self::bucket_label(i);
336                NewPayloadGasBucketMetrics::new_with_labels(&[("gas_bucket", label)])
337            }),
338        }
339    }
340}
341
342impl GasBucketMetrics {
343    fn record(&self, gas_used: u64, elapsed: Duration) {
344        let idx = Self::bucket_index(gas_used);
345        self.buckets[idx].new_payload_gas_bucket_latency.record(elapsed);
346        self.buckets[idx]
347            .new_payload_gas_bucket_gas_per_second
348            .record(gas_used as f64 / elapsed.as_secs_f64());
349    }
350
351    /// Returns the bucket index for a given gas value.
352    pub(crate) fn bucket_index(gas_used: u64) -> usize {
353        GAS_BUCKET_THRESHOLDS
354            .iter()
355            .position(|&threshold| gas_used < threshold)
356            .unwrap_or(GAS_BUCKET_THRESHOLDS.len())
357    }
358
359    /// Returns a human-readable label like `<5M`, `5-10M`, … `>40M`.
360    pub(crate) fn bucket_label(index: usize) -> String {
361        if index == 0 {
362            let hi = GAS_BUCKET_THRESHOLDS[0] / MEGAGAS;
363            format!("<{hi}M")
364        } else if index < GAS_BUCKET_THRESHOLDS.len() {
365            let lo = GAS_BUCKET_THRESHOLDS[index - 1] / MEGAGAS;
366            let hi = GAS_BUCKET_THRESHOLDS[index] / MEGAGAS;
367            format!("{lo}-{hi}M")
368        } else {
369            let lo = GAS_BUCKET_THRESHOLDS[GAS_BUCKET_THRESHOLDS.len() - 1] / MEGAGAS;
370            format!(">{lo}M")
371        }
372    }
373}
374
375/// Per-gas-bucket execution duration metric.
376#[derive(Clone, Metrics)]
377#[metrics(scope = "sync.execution")]
378pub(crate) struct ExecutionGasBucketSeries {
379    /// Gas-bucketed EVM execution duration.
380    pub(crate) execution_gas_bucket_histogram: Histogram,
381}
382
383/// Holds pre-initialized [`ExecutionGasBucketSeries`] instances, one per gas bucket.
384#[derive(Debug)]
385pub(crate) struct ExecutionGasBucketMetrics {
386    buckets: [ExecutionGasBucketSeries; NUM_GAS_BUCKETS],
387}
388
389impl Default for ExecutionGasBucketMetrics {
390    fn default() -> Self {
391        Self {
392            buckets: std::array::from_fn(|i| {
393                let label = GasBucketMetrics::bucket_label(i);
394                ExecutionGasBucketSeries::new_with_labels(&[("gas_bucket", label)])
395            }),
396        }
397    }
398}
399
400/// Per-gas-bucket block validation metrics (state root).
401#[derive(Clone, Metrics)]
402#[metrics(scope = "sync.block_validation")]
403pub(crate) struct BlockValidationGasBucketSeries {
404    /// Gas-bucketed state root computation duration.
405    pub(crate) state_root_gas_bucket_histogram: Histogram,
406}
407
408/// Holds pre-initialized [`BlockValidationGasBucketSeries`] instances, one per gas bucket.
409#[derive(Debug)]
410pub(crate) struct BlockValidationGasBucketMetrics {
411    buckets: [BlockValidationGasBucketSeries; NUM_GAS_BUCKETS],
412}
413
414impl Default for BlockValidationGasBucketMetrics {
415    fn default() -> Self {
416        Self {
417            buckets: std::array::from_fn(|i| {
418                let label = GasBucketMetrics::bucket_label(i);
419                BlockValidationGasBucketSeries::new_with_labels(&[("gas_bucket", label)])
420            }),
421        }
422    }
423}
424
425/// Metrics for engine newPayload responses.
426#[derive(Metrics)]
427#[metrics(scope = "consensus.engine.beacon")]
428pub(crate) struct NewPayloadStatusMetrics {
429    /// Finish time of the latest new payload call.
430    #[metric(skip)]
431    pub(crate) latest_finish_at: Option<Instant>,
432    /// Start time of the latest new payload call.
433    #[metric(skip)]
434    pub(crate) latest_start_at: Option<Instant>,
435    /// Gas-bucket-labeled latency and gas/s histograms.
436    #[metric(skip)]
437    pub(crate) gas_bucket: GasBucketMetrics,
438    /// Resource usage on the engine thread while processing new payloads.
439    #[metric(skip)]
440    thread_resource_usage: NewPayloadThreadResourceMetrics,
441    /// The total count of new payload messages received.
442    pub(crate) new_payload_messages: Counter,
443    /// The total count of new payload messages that we responded to with
444    /// [Valid](PayloadStatusEnum::Valid).
445    pub(crate) new_payload_valid: Counter,
446    /// The total count of new payload messages that we responded to with
447    /// [Invalid](PayloadStatusEnum::Invalid).
448    pub(crate) new_payload_invalid: Counter,
449    /// The total count of new payload messages that we responded to with
450    /// [Syncing](PayloadStatusEnum::Syncing).
451    pub(crate) new_payload_syncing: Counter,
452    /// The total count of new payload messages that we responded to with
453    /// [Accepted](PayloadStatusEnum::Accepted).
454    pub(crate) new_payload_accepted: Counter,
455    /// The total count of new payload messages that were unsuccessful, i.e. we responded with an
456    /// error type that is not a [`PayloadStatusEnum`].
457    pub(crate) new_payload_error: Counter,
458    /// The total gas of valid new payload messages received.
459    pub(crate) new_payload_total_gas: Histogram,
460    /// The gas used for the last valid new payload.
461    pub(crate) new_payload_total_gas_last: Gauge,
462    /// The gas per second of valid new payload messages received.
463    pub(crate) new_payload_gas_per_second: Histogram,
464    /// The gas per second for the last new payload call.
465    pub(crate) new_payload_gas_per_second_last: Gauge,
466    /// Latency for the new payload calls.
467    pub(crate) new_payload_latency: Histogram,
468    /// Latency for the last new payload call.
469    pub(crate) new_payload_last: Gauge,
470    /// Time from previous payload finish to current payload start (idle time).
471    pub(crate) time_between_new_payloads: Histogram,
472    /// Time from previous payload start to current payload start (total interval).
473    pub(crate) new_payload_interval: Histogram,
474    /// Time diff between forkchoice updated call response and the next new payload call request.
475    pub(crate) forkchoice_updated_new_payload_time_diff: Histogram,
476}
477
478impl NewPayloadStatusMetrics {
479    /// Starts measuring resource usage on the current thread.
480    pub(crate) fn measure_thread_resource_usage(&self) -> NewPayloadThreadResourceGuard {
481        self.thread_resource_usage.measure()
482    }
483
484    /// Increment the newPayload counter based on the given result
485    pub(crate) fn update_response_metrics(
486        &mut self,
487        start: Instant,
488        latest_forkchoice_updated_at: &mut Option<Instant>,
489        result: &Result<TreeOutcome<PayloadStatus>, InsertBlockProcessingError>,
490        gas_used: u64,
491    ) {
492        let finish = Instant::now();
493        let elapsed = finish - start;
494
495        if let Some(prev_finish) = self.latest_finish_at {
496            self.time_between_new_payloads.record(start - prev_finish);
497        }
498        if let Some(prev_start) = self.latest_start_at {
499            self.new_payload_interval.record(start - prev_start);
500        }
501        self.latest_finish_at = Some(finish);
502        self.latest_start_at = Some(start);
503        match result {
504            Ok(outcome) => match outcome.outcome.status {
505                PayloadStatusEnum::Valid => {
506                    self.new_payload_valid.increment(1);
507                    if !outcome.already_seen {
508                        self.new_payload_total_gas.record(gas_used as f64);
509                        self.new_payload_total_gas_last.set(gas_used as f64);
510                        let gas_per_second = gas_used as f64 / elapsed.as_secs_f64();
511                        self.new_payload_gas_per_second.record(gas_per_second);
512                        self.new_payload_gas_per_second_last.set(gas_per_second);
513
514                        self.new_payload_latency.record(elapsed);
515                        self.new_payload_last.set(elapsed);
516                        self.gas_bucket.record(gas_used, elapsed);
517                    }
518                }
519                PayloadStatusEnum::Syncing => self.new_payload_syncing.increment(1),
520                PayloadStatusEnum::Accepted => self.new_payload_accepted.increment(1),
521                PayloadStatusEnum::Invalid { .. } => self.new_payload_invalid.increment(1),
522            },
523            Err(_) => self.new_payload_error.increment(1),
524        }
525        self.new_payload_messages.increment(1);
526        if let Some(latest_forkchoice_updated_at) = latest_forkchoice_updated_at.take() {
527            self.forkchoice_updated_new_payload_time_diff
528                .record(start - latest_forkchoice_updated_at);
529        }
530    }
531}
532
533/// Per-newPayload engine thread resource usage metrics.
534#[derive(Clone, Metrics)]
535#[metrics(scope = "consensus.engine.beacon")]
536struct NewPayloadThreadResourceMetrics {
537    /// User-mode CPU time used while processing a new payload.
538    new_payload_thread_user_cpu_seconds: Histogram,
539    /// Kernel-mode CPU time used while processing a new payload.
540    new_payload_thread_system_cpu_seconds: Histogram,
541    /// Minor page faults incurred while processing a new payload.
542    new_payload_thread_minor_page_faults: Histogram,
543    /// Major page faults incurred while processing a new payload.
544    new_payload_thread_major_page_faults: Histogram,
545    /// Voluntary context switches while processing a new payload.
546    new_payload_thread_voluntary_context_switches: Histogram,
547    /// Involuntary context switches while processing a new payload.
548    new_payload_thread_involuntary_context_switches: Histogram,
549    /// Block input operations while processing a new payload.
550    new_payload_thread_block_input_operations: Histogram,
551    /// Block output operations while processing a new payload.
552    new_payload_thread_block_output_operations: Histogram,
553}
554
555impl NewPayloadThreadResourceMetrics {
556    fn measure(&self) -> NewPayloadThreadResourceGuard {
557        let metrics = self.clone();
558        let start = ThreadResourceUsage::now();
559        NewPayloadThreadResourceGuard { start, metrics }
560    }
561
562    fn record(&self, usage: &ThreadResourceUsageDelta) {
563        self.new_payload_thread_user_cpu_seconds.record(usage.user_cpu_time);
564        self.new_payload_thread_system_cpu_seconds.record(usage.system_cpu_time);
565        self.new_payload_thread_minor_page_faults.record(usage.minor_page_faults as f64);
566        self.new_payload_thread_major_page_faults.record(usage.major_page_faults as f64);
567        self.new_payload_thread_voluntary_context_switches
568            .record(usage.voluntary_context_switches as f64);
569        self.new_payload_thread_involuntary_context_switches
570            .record(usage.involuntary_context_switches as f64);
571        self.new_payload_thread_block_input_operations.record(usage.block_input_operations as f64);
572        self.new_payload_thread_block_output_operations
573            .record(usage.block_output_operations as f64);
574    }
575}
576
577/// Records engine thread resource usage when dropped.
578pub(crate) struct NewPayloadThreadResourceGuard {
579    start: ThreadResourceUsage,
580    metrics: NewPayloadThreadResourceMetrics,
581}
582
583impl Drop for NewPayloadThreadResourceGuard {
584    fn drop(&mut self) {
585        if let Some(usage) = self.start.elapsed() {
586            self.metrics.record(&usage);
587        }
588    }
589}
590
591/// Metrics for EIP-7928 Block-Level Access Lists (BAL).
592///
593/// See also <https://github.com/ethereum/execution-metrics/issues/5>
594#[allow(dead_code)]
595#[derive(Metrics, Clone)]
596#[metrics(scope = "execution.block_access_list")]
597pub(crate) struct BalMetrics {
598    /// Size of the BAL in bytes for the current block.
599    pub(crate) size_bytes: Gauge,
600    /// Total number of blocks with valid BALs.
601    pub(crate) valid_total: Counter,
602    /// Total number of blocks with invalid BALs.
603    pub(crate) invalid_total: Counter,
604    /// Time taken to validate the BAL against actual execution.
605    pub(crate) validation_time_seconds: Histogram,
606    /// Number of account changes in the BAL.
607    pub(crate) account_changes: Gauge,
608    /// Number of storage changes in the BAL.
609    pub(crate) storage_changes: Gauge,
610    /// Number of balance changes in the BAL.
611    pub(crate) balance_changes: Gauge,
612    /// Number of nonce changes in the BAL.
613    pub(crate) nonce_changes: Gauge,
614    /// Number of code changes in the BAL.
615    pub(crate) code_changes: Gauge,
616}
617
618/// Metrics for non-execution related block validation.
619#[derive(Metrics, Clone)]
620#[metrics(scope = "sync.block_validation")]
621pub struct BlockValidationMetrics {
622    /// Total number of storage tries updated in the state root calculation
623    pub state_root_storage_tries_updated_total: Counter,
624    /// Total number of times the state root task failed but the fallback succeeded.
625    pub state_root_task_fallback_success_total: Counter,
626    /// Total number of times the state root task timed out and a sequential fallback was spawned.
627    pub state_root_task_timeout_total: Counter,
628    /// Latest state root duration, ie the time spent blocked waiting for the state root.
629    pub state_root_duration: Gauge,
630    /// Histogram for state root duration ie the time spent blocked waiting for the state root
631    pub state_root_histogram: Histogram,
632    /// Histogram of deferred trie computation duration.
633    pub deferred_trie_compute_duration: Histogram,
634    /// Payload conversion and validation latency
635    pub payload_validation_duration: Gauge,
636    /// Histogram of payload validation latency
637    pub payload_validation_histogram: Histogram,
638    /// Payload processor spawning duration
639    pub spawn_payload_processor: Histogram,
640    /// Post-execution validation duration
641    pub post_execution_validation_duration: Histogram,
642    /// Total duration of the new payload call
643    pub total_duration: Histogram,
644    /// Size of `HashedPostStateSorted` (`total_len`)
645    pub hashed_post_state_size: Histogram,
646    /// Size of `TrieUpdatesSorted` (`total_len`)
647    pub trie_updates_sorted_size: Histogram,
648}
649
650impl BlockValidationMetrics {
651    /// Records a new state root time, updating both the histogram and state root gauge
652    pub fn record_state_root(&self, trie_output: &TrieUpdates, elapsed_as_secs: f64) {
653        self.state_root_storage_tries_updated_total
654            .increment(trie_output.storage_tries_ref().len() as u64);
655        self.state_root_duration.set(elapsed_as_secs);
656        self.state_root_histogram.record(elapsed_as_secs);
657    }
658
659    /// Records a new payload validation time, updating both the histogram and the payload
660    /// validation gauge
661    pub fn record_payload_validation(&self, elapsed_as_secs: f64) {
662        self.payload_validation_duration.set(elapsed_as_secs);
663        self.payload_validation_histogram.record(elapsed_as_secs);
664    }
665}
666
667/// Metrics for the blockchain tree block buffer
668#[derive(Metrics)]
669#[metrics(scope = "blockchain_tree.block_buffer")]
670pub(crate) struct BlockBufferMetrics {
671    /// Total blocks in the block buffer
672    pub blocks: Gauge,
673}
674
675#[cfg(test)]
676mod tests {
677    use super::*;
678    use alloy_eips::eip7685::Requests;
679    use metrics_util::debugging::{DebuggingRecorder, Snapshotter};
680    use reth_ethereum_primitives::Receipt;
681    use reth_execution_types::BlockExecutionResult;
682    use reth_trie_common::bundle_state::BundleState;
683
684    fn setup_test_recorder() -> Snapshotter {
685        let recorder = DebuggingRecorder::new();
686        let snapshotter = recorder.snapshotter();
687        recorder.install().unwrap();
688        snapshotter
689    }
690
691    #[test]
692    fn test_record_block_execution_metrics() {
693        let snapshotter = setup_test_recorder();
694        let metrics = EngineApiMetrics::default();
695
696        // Pre-populate some metrics to ensure they exist
697        metrics.executor.gas_processed_total.increment(0);
698        metrics.executor.gas_per_second.set(0.0);
699        metrics.executor.gas_used_histogram.record(0.0);
700
701        let output = BlockExecutionOutput::<Receipt> {
702            state: BundleState::default(),
703            result: BlockExecutionResult {
704                receipts: vec![],
705                requests: Requests::default(),
706                gas_used: 21000,
707                blob_gas_used: 0,
708            },
709        };
710
711        metrics.record_block_execution(&output, Duration::from_millis(100));
712        metrics.engine.new_payload.thread_resource_usage.record(&ThreadResourceUsageDelta {
713            user_cpu_time: Duration::from_millis(1),
714            system_cpu_time: Duration::from_millis(2),
715            minor_page_faults: 3,
716            major_page_faults: 4,
717            voluntary_context_switches: 5,
718            involuntary_context_switches: 6,
719            block_input_operations: 7,
720            block_output_operations: 8,
721        });
722
723        let snapshot = snapshotter.snapshot().into_vec();
724
725        // Verify that metrics were registered
726        let mut found_execution_metrics = false;
727        let mut found_thread_resource_metrics = false;
728        for (key, _unit, _desc, _value) in snapshot {
729            let metric_name = key.key().name();
730            if metric_name.starts_with("sync.execution") {
731                found_execution_metrics = true;
732            }
733            if metric_name == "consensus.engine.beacon.new_payload_thread_major_page_faults" {
734                found_thread_resource_metrics = true;
735            }
736        }
737
738        assert!(found_execution_metrics, "Expected to find sync.execution metrics");
739        assert!(found_thread_resource_metrics, "Expected to find thread resource metrics");
740    }
741}