Skip to main content

reth_engine_primitives/
config.rs

1//! Engine tree configuration.
2
3use alloy_eips::merge::EPOCH_SLOTS;
4use core::{num::NonZeroUsize, time::Duration};
5
6/// Triggers persistence when the number of canonical blocks in memory exceeds this threshold.
7pub const DEFAULT_PERSISTENCE_THRESHOLD: u64 = 50;
8
9/// Number of persisted blocks whose state/trie writes are masked by an in-memory suffix.
10pub const DEFAULT_NUM_STATE_MASKING_BLOCKS: u64 = 30;
11
12/// The engine stalls API processing when this many blocks are awaiting persistence beyond the
13/// in-memory buffer target.
14pub const MIN_PERSISTENCE_BACKPRESSURE_THRESHOLD: u64 = 16;
15
16/// How close to the canonical head we persist blocks.
17pub const DEFAULT_MEMORY_BLOCK_BUFFER_TARGET: u64 = 5;
18
19/// The largest gap for which the tree will be used to sync individual blocks by downloading them.
20///
21/// This is the default threshold, and represents the distance (gap) from the local head to a
22/// new (canonical) block, e.g. the forkchoice head block. If the block distance from the local head
23/// exceeds this threshold, the pipeline will be used to backfill the gap more efficiently.
24///
25/// E.g.: Local head `block.number` is 100 and the forkchoice head `block.number` is 133 (more than
26/// an epoch has slots), then this exceeds the threshold at which the pipeline should be used to
27/// backfill this gap.
28pub const DEFAULT_BACKFILL_RUN_THRESHOLD: u64 = EPOCH_SLOTS;
29
30/// Largest supported live-sync gap, matching the peer header response limit of 1024.
31pub const MAX_BACKFILL_RUN_THRESHOLD: u64 = 1024;
32
33/// The size of proof targets chunk to spawn in one multiproof calculation.
34pub const DEFAULT_MULTIPROOF_TASK_CHUNK_SIZE: usize = 5;
35
36/// Default number of cache hits before an invalid header entry is evicted and reprocessed.
37pub const DEFAULT_INVALID_HEADER_HIT_EVICTION_THRESHOLD: u8 = 128;
38
39/// Gas threshold below which the small block chunk size is used.
40pub const SMALL_BLOCK_GAS_THRESHOLD: u64 = 20_000_000;
41
42/// Default number of reserved CPU cores for non-reth processes.
43///
44/// This will be deducted from the thread count of main reth global threadpool.
45pub const DEFAULT_RESERVED_CPU_CORES: usize = 1;
46
47/// Default depth for sparse trie pruning.
48///
49/// Nodes at this depth and below are converted to hash stubs to reduce memory.
50/// Depth 4 means we keep roughly 16^4 = 65536 potential branch paths at most.
51pub const DEFAULT_SPARSE_TRIE_PRUNE_DEPTH: usize = 4;
52
53/// Default timeout for the state root task before spawning a sequential fallback.
54pub const DEFAULT_STATE_ROOT_TASK_TIMEOUT: Duration = Duration::from_secs(1);
55
56const DEFAULT_BLOCK_BUFFER_LIMIT: u32 = EPOCH_SLOTS as u32 * 2;
57const DEFAULT_MAX_INVALID_HEADER_CACHE_LENGTH: u32 = 256;
58const DEFAULT_MAX_EXECUTE_BLOCK_BATCH_SIZE: usize = 4;
59const DEFAULT_CROSS_BLOCK_CACHE_SIZE: usize = default_cross_block_cache_size();
60
61const fn assert_backpressure_threshold_invariant(
62    persistence_threshold: u64,
63    persistence_backpressure_threshold: u64,
64) {
65    debug_assert!(
66        persistence_backpressure_threshold > persistence_threshold,
67        "persistence_backpressure_threshold must be greater than persistence_threshold",
68    );
69}
70
71const fn assert_state_masking_invariant(
72    persistence_threshold: u64,
73    num_state_masking_blocks: u64,
74    memory_block_buffer_target: u64,
75) {
76    let valid_window = match num_state_masking_blocks.checked_add(memory_block_buffer_target) {
77        Some(window) => window < persistence_threshold,
78        None => false,
79    };
80    debug_assert!(
81        num_state_masking_blocks == 0 || valid_window,
82        "num_state_masking_blocks + memory_block_buffer_target must be less than persistence_threshold",
83    );
84}
85
86const fn default_cross_block_cache_size() -> usize {
87    if cfg!(test) {
88        1024 * 1024 // 1 MB in tests
89    } else if cfg!(target_pointer_width = "32") {
90        usize::MAX // max possible on wasm32 / 32-bit
91    } else {
92        4 * 1024 * 1024 * 1024 // 4 GB on 64-bit
93    }
94}
95
96/// Determines if the host has enough parallelism to run the payload processor.
97///
98/// It requires at least 5 parallel threads:
99/// - Engine in main thread that spawns the state root task.
100/// - Multiproof task in payload processor
101/// - Sparse Trie task in payload processor
102/// - Multiproof computation spawned in payload processor
103/// - Storage root computation spawned in trie parallel proof
104pub fn has_enough_parallelism() -> bool {
105    #[cfg(feature = "std")]
106    {
107        std::thread::available_parallelism().is_ok_and(|num| num.get() >= 5)
108    }
109    #[cfg(not(feature = "std"))]
110    false
111}
112
113/// The configuration of the engine tree.
114#[derive(Debug, Clone)]
115pub struct TreeConfig {
116    /// Maximum number of blocks to be kept only in memory without triggering
117    /// persistence.
118    persistence_threshold: u64,
119    /// Number of persisted blocks whose state/trie writes are masked instead of being durably
120    /// written in the current cycle.
121    num_state_masking_blocks: u64,
122    /// How close to the canonical head we persist blocks. Represents the ideal
123    /// number of most recent blocks to keep in memory for quick access and reorgs.
124    ///
125    /// Note: this should be less than or equal to `persistence_threshold`.
126    memory_block_buffer_target: u64,
127    /// Maximum number of blocks beyond the in-memory buffer target awaiting persistence before
128    /// engine API processing is stalled.
129    persistence_backpressure_threshold: u64,
130    /// Number of pending blocks that cannot be executed due to missing parent and
131    /// are kept in cache.
132    block_buffer_limit: u32,
133    /// Largest gap between the local head and a new canonical block that is closed by downloading
134    /// the missing blocks. Larger gaps trigger a pipeline (backfill) run instead.
135    backfill_run_threshold: u64,
136    /// Number of invalid headers to keep in cache.
137    max_invalid_header_cache_length: u32,
138    /// Number of cache hits before an invalid header entry is evicted and reprocessed.
139    ///
140    /// Setting this to `0` effectively disables the cache because entries are evicted on the
141    /// first lookup.
142    invalid_header_hit_eviction_threshold: u8,
143    /// Maximum number of blocks to execute sequentially in a batch.
144    ///
145    /// This is used as a cutoff to prevent long-running sequential block execution when we receive
146    /// a batch of downloaded blocks.
147    max_execute_block_batch_size: usize,
148    /// Whether to disable state cache.
149    disable_state_cache: bool,
150    /// Whether to disable parallel prewarming.
151    disable_prewarming: bool,
152    /// Whether txpool-driven prewarming between payloads is enabled.
153    txpool_prewarming: bool,
154    /// Whether to enable state provider metrics.
155    state_provider_metrics: bool,
156    /// Cross-block cache size in bytes.
157    cross_block_cache_size: usize,
158    /// Whether the host has enough parallelism to run the state root task, see
159    /// [`has_enough_parallelism`].
160    ///
161    /// The state root task pipeline occupies at least 5 threads that block on each other (engine
162    /// main thread, multiproof task, sparse trie task, multiproof computation, storage root
163    /// computation). On hosts with fewer parallel threads these components can starve each other
164    /// and stall payload validation entirely, so state-root strategy selection
165    /// ([`Self::use_state_root_task`]) must keep falling back to synchronous state root
166    /// computation when this is `false`.
167    has_enough_parallelism: bool,
168    /// Multiproof task chunk size for proof targets.
169    multiproof_chunk_size: usize,
170    /// Number of reserved CPU cores for non-reth processes
171    reserved_cpu_cores: usize,
172    /// Whether to disable the precompile cache
173    precompile_cache_disabled: bool,
174    /// Whether to use state root fallback for testing
175    state_root_fallback: bool,
176    /// Whether to always process payload attributes and begin a payload build process
177    /// even if `forkchoiceState.headBlockHash` is already the canonical head or an ancestor.
178    ///
179    /// The Engine API specification generally states that client software "MUST NOT begin a
180    /// payload build process if `forkchoiceState.headBlockHash` references a `VALID`
181    /// ancestor of the head of canonical chain".
182    /// See: <https://github.com/ethereum/execution-apis/blob/main/src/engine/paris.md#engine_forkchoiceupdatedv1> (Rule 2)
183    ///
184    /// This flag allows overriding that behavior.
185    /// This is useful for specific chain configurations (e.g., OP Stack where proposers
186    /// can reorg their own chain), various custom chains, or for development/testing purposes
187    /// where immediate payload regeneration is desired despite the head not changing or moving to
188    /// an ancestor.
189    always_process_payload_attributes_on_canonical_head: bool,
190    /// Whether to unwind canonical header to ancestor during forkchoice updates.
191    allow_unwind_canonical_header: bool,
192    /// Whether to disable cache metrics recording (can be expensive with large cached state).
193    disable_cache_metrics: bool,
194    /// Depth for sparse trie pruning after state root computation.
195    sparse_trie_prune_depth: usize,
196    /// When set, blocks whose total processing time (execution + state reads + state root +
197    /// DB commit) exceeds this duration trigger a structured `warn!` log with detailed timing,
198    /// state-operation counts, and cache hit-rate metrics. `Duration::ZERO` logs every block.
199    slow_block_threshold: Option<Duration>,
200    /// Whether to fully disable sparse trie cache pruning between blocks.
201    disable_sparse_trie_cache_pruning: bool,
202    /// Timeout for the state root task before spawning a sequential fallback computation.
203    /// If `Some`, after waiting this duration for the state root task, a sequential state root
204    /// computation is spawned in parallel and whichever finishes first is used.
205    /// If `None`, the timeout fallback is disabled.
206    state_root_task_timeout: Option<Duration>,
207    /// Whether to share execution cache with the payload builder.
208    share_execution_cache_with_payload_builder: bool,
209    /// Whether to share sparse trie with the payload builder.
210    share_sparse_trie_with_payload_builder: bool,
211    /// Whether to suppress persistence cycles while building a payload.
212    ///
213    /// When enabled, persistence is deferred while a payload job is active. This avoids
214    /// persistence I/O competing with block building on latency-sensitive chains.
215    suppress_persistence_during_build: bool,
216    /// Whether to disable BAL (Block Access List, EIP-7928) based parallel execution.
217    /// When disabled, uses the sequential execution path even when a BAL is available.
218    disable_bal_parallel_execution: bool,
219    /// Whether to disable BAL-driven parallel state root computation.
220    /// Only valid when BAL parallel execution is also disabled.
221    disable_bal_parallel_state_root: bool,
222    /// Whether to disable BAL (Block Access List) storage prefetch IO during prewarming.
223    /// When set, BAL storage slots are not read into the execution cache. BAL hashed-state
224    /// streaming for parallel state-root computation is controlled separately.
225    disable_bal_batch_io: bool,
226    /// BAL read-set prewarm threads; `None` uses the production pool's default.
227    bal_prewarm_threads: Option<NonZeroUsize>,
228    /// Whether block execution reuses transaction prewarming results.
229    prewarm_reuse: bool,
230    /// Whether to skip trie state-root computation during engine validation.
231    ///
232    /// This trusts the block header's state root. It is intended for experiments that measure
233    /// execution without trie state-root work.
234    skip_state_root: bool,
235    /// Maximum random jitter applied before each proof computation (trie-debug only).
236    /// When set, each proof worker sleeps for a random duration up to this value
237    /// before starting a proof calculation.
238    #[cfg(feature = "trie-debug")]
239    proof_jitter: Option<Duration>,
240}
241
242impl Default for TreeConfig {
243    fn default() -> Self {
244        assert_backpressure_threshold_invariant(
245            DEFAULT_PERSISTENCE_THRESHOLD,
246            DEFAULT_PERSISTENCE_THRESHOLD * 2,
247        );
248        assert_state_masking_invariant(
249            DEFAULT_PERSISTENCE_THRESHOLD,
250            DEFAULT_NUM_STATE_MASKING_BLOCKS,
251            DEFAULT_MEMORY_BLOCK_BUFFER_TARGET,
252        );
253        Self {
254            persistence_threshold: DEFAULT_PERSISTENCE_THRESHOLD,
255            num_state_masking_blocks: DEFAULT_NUM_STATE_MASKING_BLOCKS,
256            memory_block_buffer_target: DEFAULT_MEMORY_BLOCK_BUFFER_TARGET,
257            persistence_backpressure_threshold: DEFAULT_PERSISTENCE_THRESHOLD * 2,
258            block_buffer_limit: DEFAULT_BLOCK_BUFFER_LIMIT,
259            backfill_run_threshold: DEFAULT_BACKFILL_RUN_THRESHOLD,
260            max_invalid_header_cache_length: DEFAULT_MAX_INVALID_HEADER_CACHE_LENGTH,
261            invalid_header_hit_eviction_threshold: DEFAULT_INVALID_HEADER_HIT_EVICTION_THRESHOLD,
262            max_execute_block_batch_size: DEFAULT_MAX_EXECUTE_BLOCK_BATCH_SIZE,
263            disable_state_cache: false,
264            disable_prewarming: false,
265            txpool_prewarming: false,
266            state_provider_metrics: false,
267            cross_block_cache_size: DEFAULT_CROSS_BLOCK_CACHE_SIZE,
268            has_enough_parallelism: has_enough_parallelism(),
269            multiproof_chunk_size: DEFAULT_MULTIPROOF_TASK_CHUNK_SIZE,
270            reserved_cpu_cores: DEFAULT_RESERVED_CPU_CORES,
271            precompile_cache_disabled: false,
272            state_root_fallback: false,
273            always_process_payload_attributes_on_canonical_head: false,
274            allow_unwind_canonical_header: false,
275            disable_cache_metrics: false,
276            sparse_trie_prune_depth: DEFAULT_SPARSE_TRIE_PRUNE_DEPTH,
277            slow_block_threshold: None,
278            disable_sparse_trie_cache_pruning: false,
279            state_root_task_timeout: Some(DEFAULT_STATE_ROOT_TASK_TIMEOUT),
280            share_execution_cache_with_payload_builder: false,
281            share_sparse_trie_with_payload_builder: false,
282            suppress_persistence_during_build: false,
283            disable_bal_parallel_execution: false,
284            disable_bal_parallel_state_root: false,
285            disable_bal_batch_io: false,
286            bal_prewarm_threads: None,
287            prewarm_reuse: false,
288            skip_state_root: false,
289            #[cfg(feature = "trie-debug")]
290            proof_jitter: None,
291        }
292    }
293}
294
295impl TreeConfig {
296    /// Create engine tree configuration.
297    ///
298    /// The backfill run threshold is clamped to [`MAX_BACKFILL_RUN_THRESHOLD`].
299    ///
300    /// # Panics
301    ///
302    /// Panics if `multiproof_chunk_size` is zero or the persistence thresholds are inconsistent.
303    #[expect(clippy::too_many_arguments)]
304    pub const fn new(
305        persistence_threshold: u64,
306        num_state_masking_blocks: u64,
307        memory_block_buffer_target: u64,
308        persistence_backpressure_threshold: u64,
309        block_buffer_limit: u32,
310        backfill_run_threshold: u64,
311        max_invalid_header_cache_length: u32,
312        invalid_header_hit_eviction_threshold: u8,
313        max_execute_block_batch_size: usize,
314        disable_state_cache: bool,
315        disable_prewarming: bool,
316        state_provider_metrics: bool,
317        cross_block_cache_size: usize,
318        has_enough_parallelism: bool,
319        multiproof_chunk_size: usize,
320        reserved_cpu_cores: usize,
321        precompile_cache_disabled: bool,
322        state_root_fallback: bool,
323        always_process_payload_attributes_on_canonical_head: bool,
324        allow_unwind_canonical_header: bool,
325        disable_cache_metrics: bool,
326        sparse_trie_prune_depth: usize,
327        slow_block_threshold: Option<Duration>,
328        state_root_task_timeout: Option<Duration>,
329        share_execution_cache_with_payload_builder: bool,
330        share_sparse_trie_with_payload_builder: bool,
331    ) -> Self {
332        assert!(multiproof_chunk_size > 0, "multiproof chunk size must be non-zero");
333        let num_state_masking_blocks =
334            if persistence_threshold == 0 { 0 } else { num_state_masking_blocks };
335        assert_backpressure_threshold_invariant(
336            persistence_threshold,
337            persistence_backpressure_threshold,
338        );
339        assert_state_masking_invariant(
340            persistence_threshold,
341            num_state_masking_blocks,
342            memory_block_buffer_target,
343        );
344        Self {
345            persistence_threshold,
346            num_state_masking_blocks,
347            memory_block_buffer_target,
348            persistence_backpressure_threshold,
349            block_buffer_limit,
350            backfill_run_threshold: clamp_backfill_run_threshold(backfill_run_threshold),
351            max_invalid_header_cache_length,
352            invalid_header_hit_eviction_threshold,
353            max_execute_block_batch_size,
354            disable_state_cache,
355            disable_prewarming,
356            txpool_prewarming: false,
357            state_provider_metrics,
358            cross_block_cache_size,
359            has_enough_parallelism,
360            multiproof_chunk_size,
361            reserved_cpu_cores,
362            precompile_cache_disabled,
363            state_root_fallback,
364            always_process_payload_attributes_on_canonical_head,
365            allow_unwind_canonical_header,
366            disable_cache_metrics,
367            sparse_trie_prune_depth,
368            slow_block_threshold,
369            disable_sparse_trie_cache_pruning: false,
370            state_root_task_timeout,
371            share_execution_cache_with_payload_builder,
372            share_sparse_trie_with_payload_builder,
373            suppress_persistence_during_build: false,
374            disable_bal_parallel_execution: false,
375            disable_bal_parallel_state_root: false,
376            disable_bal_batch_io: false,
377            bal_prewarm_threads: None,
378            prewarm_reuse: false,
379            skip_state_root: false,
380            #[cfg(feature = "trie-debug")]
381            proof_jitter: None,
382        }
383    }
384
385    /// Return the persistence threshold.
386    pub const fn persistence_threshold(&self) -> u64 {
387        self.persistence_threshold
388    }
389
390    /// Return the number of persisted blocks whose state/trie writes are masked.
391    pub const fn num_state_masking_blocks(&self) -> u64 {
392        self.num_state_masking_blocks
393    }
394
395    /// Return the memory block buffer target.
396    pub const fn memory_block_buffer_target(&self) -> u64 {
397        self.memory_block_buffer_target
398    }
399
400    /// Return the persistence backpressure threshold.
401    pub const fn persistence_backpressure_threshold(&self) -> u64 {
402        self.persistence_backpressure_threshold
403    }
404
405    /// Return the block buffer limit.
406    pub const fn block_buffer_limit(&self) -> u32 {
407        self.block_buffer_limit
408    }
409
410    /// Return the backfill run threshold.
411    pub const fn backfill_run_threshold(&self) -> u64 {
412        self.backfill_run_threshold
413    }
414
415    /// Return the maximum invalid cache header length.
416    pub const fn max_invalid_header_cache_length(&self) -> u32 {
417        self.max_invalid_header_cache_length
418    }
419
420    /// Return the invalid header cache hit eviction threshold.
421    ///
422    /// Setting this to `0` effectively disables the cache because entries are evicted on the
423    /// first lookup.
424    pub const fn invalid_header_hit_eviction_threshold(&self) -> u8 {
425        self.invalid_header_hit_eviction_threshold
426    }
427
428    /// Return the maximum execute block batch size.
429    pub const fn max_execute_block_batch_size(&self) -> usize {
430        self.max_execute_block_batch_size
431    }
432
433    /// Return the multiproof task chunk size.
434    pub const fn multiproof_chunk_size(&self) -> usize {
435        self.multiproof_chunk_size
436    }
437
438    /// Return the effective multiproof task chunk size.
439    pub const fn effective_multiproof_chunk_size(&self) -> usize {
440        self.multiproof_chunk_size
441    }
442
443    /// Return the number of reserved CPU cores for non-reth processes
444    pub const fn reserved_cpu_cores(&self) -> usize {
445        self.reserved_cpu_cores
446    }
447
448    /// Returns whether or not state provider metrics are enabled.
449    pub const fn state_provider_metrics(&self) -> bool {
450        self.state_provider_metrics
451    }
452
453    /// Returns whether or not state cache is disabled.
454    pub const fn disable_state_cache(&self) -> bool {
455        self.disable_state_cache
456    }
457
458    /// Returns whether or not parallel prewarming is disabled.
459    pub const fn disable_prewarming(&self) -> bool {
460        self.disable_prewarming
461    }
462
463    /// Returns whether txpool prewarming is enabled.
464    pub const fn txpool_prewarming(&self) -> bool {
465        self.txpool_prewarming
466    }
467
468    /// Returns the cross-block cache size.
469    pub const fn cross_block_cache_size(&self) -> usize {
470        self.cross_block_cache_size
471    }
472
473    /// Returns whether precompile cache is disabled.
474    pub const fn precompile_cache_disabled(&self) -> bool {
475        self.precompile_cache_disabled
476    }
477
478    /// Returns whether to use state root fallback.
479    pub const fn state_root_fallback(&self) -> bool {
480        self.state_root_fallback
481    }
482
483    /// Sets whether to always process payload attributes when the FCU head is already canonical.
484    pub const fn with_always_process_payload_attributes_on_canonical_head(
485        mut self,
486        always_process_payload_attributes_on_canonical_head: bool,
487    ) -> Self {
488        self.always_process_payload_attributes_on_canonical_head =
489            always_process_payload_attributes_on_canonical_head;
490        self
491    }
492
493    /// Returns true if payload attributes should always be processed even when the FCU head is
494    /// canonical.
495    pub const fn always_process_payload_attributes_on_canonical_head(&self) -> bool {
496        self.always_process_payload_attributes_on_canonical_head
497    }
498
499    /// Returns true if canonical header should be unwound to ancestor during forkchoice updates.
500    pub const fn unwind_canonical_header(&self) -> bool {
501        self.allow_unwind_canonical_header
502    }
503
504    /// Setter for persistence threshold. Setting this to zero disables state masking.
505    pub const fn with_persistence_threshold(mut self, persistence_threshold: u64) -> Self {
506        self.persistence_threshold = persistence_threshold;
507        if persistence_threshold == 0 {
508            self.num_state_masking_blocks = 0;
509        }
510        assert_backpressure_threshold_invariant(
511            self.persistence_threshold,
512            self.persistence_backpressure_threshold,
513        );
514        assert_state_masking_invariant(
515            self.persistence_threshold,
516            self.num_state_masking_blocks,
517            self.memory_block_buffer_target,
518        );
519        self
520    }
521
522    /// Setter for the number of persisted blocks whose state/trie writes are masked.
523    /// State masking is disabled when the persistence threshold is zero.
524    pub const fn with_num_state_masking_blocks(mut self, num_state_masking_blocks: u64) -> Self {
525        self.num_state_masking_blocks =
526            if self.persistence_threshold == 0 { 0 } else { num_state_masking_blocks };
527        assert_state_masking_invariant(
528            self.persistence_threshold,
529            self.num_state_masking_blocks,
530            self.memory_block_buffer_target,
531        );
532        self
533    }
534
535    /// Setter for memory block buffer target.
536    pub const fn with_memory_block_buffer_target(
537        mut self,
538        memory_block_buffer_target: u64,
539    ) -> Self {
540        self.memory_block_buffer_target = memory_block_buffer_target;
541        assert_state_masking_invariant(
542            self.persistence_threshold,
543            self.num_state_masking_blocks,
544            self.memory_block_buffer_target,
545        );
546        self
547    }
548
549    /// Setter for persistence backpressure threshold.
550    pub const fn with_persistence_backpressure_threshold(
551        mut self,
552        persistence_backpressure_threshold: u64,
553    ) -> Self {
554        self.persistence_backpressure_threshold = persistence_backpressure_threshold;
555        assert_backpressure_threshold_invariant(
556            self.persistence_threshold,
557            self.persistence_backpressure_threshold,
558        );
559        self
560    }
561
562    /// Setter for block buffer limit.
563    pub const fn with_block_buffer_limit(mut self, block_buffer_limit: u32) -> Self {
564        self.block_buffer_limit = block_buffer_limit;
565        self
566    }
567
568    /// Setter for backfill run threshold.
569    ///
570    /// Clamps the threshold to [`MAX_BACKFILL_RUN_THRESHOLD`] and grows the block buffer to twice
571    /// the clamped threshold so it can retain disconnected blocks while downloading the gap,
572    /// with room for incoming payloads.
573    pub const fn with_backfill_run_threshold(mut self, backfill_run_threshold: u64) -> Self {
574        self.backfill_run_threshold = clamp_backfill_run_threshold(backfill_run_threshold);
575        let buffer_limit = self.backfill_run_threshold as u32 * 2;
576        if buffer_limit > self.block_buffer_limit {
577            self.block_buffer_limit = buffer_limit;
578        }
579        self
580    }
581
582    /// Setter for maximum invalid header cache length.
583    pub const fn with_max_invalid_header_cache_length(
584        mut self,
585        max_invalid_header_cache_length: u32,
586    ) -> Self {
587        self.max_invalid_header_cache_length = max_invalid_header_cache_length;
588        self
589    }
590
591    /// Setter for the invalid header cache hit eviction threshold.
592    pub const fn with_invalid_header_hit_eviction_threshold(
593        mut self,
594        invalid_header_hit_eviction_threshold: u8,
595    ) -> Self {
596        self.invalid_header_hit_eviction_threshold = invalid_header_hit_eviction_threshold;
597        self
598    }
599
600    /// Setter for maximum execute block batch size.
601    pub const fn with_max_execute_block_batch_size(
602        mut self,
603        max_execute_block_batch_size: usize,
604    ) -> Self {
605        self.max_execute_block_batch_size = max_execute_block_batch_size;
606        self
607    }
608
609    /// Setter for whether to disable state cache.
610    pub const fn without_state_cache(mut self, disable_state_cache: bool) -> Self {
611        self.disable_state_cache = disable_state_cache;
612        self
613    }
614
615    /// Setter for whether to disable parallel prewarming.
616    pub const fn without_prewarming(mut self, disable_prewarming: bool) -> Self {
617        self.disable_prewarming = disable_prewarming;
618        self
619    }
620
621    /// Enables or disables txpool transaction prewarming.
622    pub const fn with_txpool_prewarming(mut self, enabled: bool) -> Self {
623        self.txpool_prewarming = enabled;
624        self
625    }
626
627    /// Setter for cross block cache size.
628    pub const fn with_cross_block_cache_size(mut self, cross_block_cache_size: usize) -> Self {
629        self.cross_block_cache_size = cross_block_cache_size;
630        self
631    }
632
633    /// Setter for has enough parallelism.
634    pub const fn with_has_enough_parallelism(mut self, has_enough_parallelism: bool) -> Self {
635        self.has_enough_parallelism = has_enough_parallelism;
636        self
637    }
638
639    /// Returns whether the host has enough parallelism to run the state root task.
640    pub const fn has_enough_parallelism(&self) -> bool {
641        self.has_enough_parallelism
642    }
643
644    /// Returns whether engine validation should use the state root task.
645    ///
646    /// The state root task requires at least 5 parallel threads, see
647    /// [`has_enough_parallelism`].
648    pub const fn use_state_root_task(&self) -> bool {
649        !self.skip_state_root && !self.state_root_fallback && self.has_enough_parallelism
650    }
651
652    /// Setter for state provider metrics.
653    pub const fn with_state_provider_metrics(mut self, state_provider_metrics: bool) -> Self {
654        self.state_provider_metrics = state_provider_metrics;
655        self
656    }
657
658    /// Setter for multiproof task chunk size for proof targets.
659    ///
660    /// # Panics
661    ///
662    /// Panics if `multiproof_chunk_size` is zero.
663    pub const fn with_multiproof_chunk_size(mut self, multiproof_chunk_size: usize) -> Self {
664        assert!(multiproof_chunk_size > 0, "multiproof chunk size must be non-zero");
665        self.multiproof_chunk_size = multiproof_chunk_size;
666        self
667    }
668
669    /// Setter for the number of reserved CPU cores for any non-reth processes
670    pub const fn with_reserved_cpu_cores(mut self, reserved_cpu_cores: usize) -> Self {
671        self.reserved_cpu_cores = reserved_cpu_cores;
672        self
673    }
674
675    /// Setter for whether to disable the precompile cache.
676    pub const fn without_precompile_cache(mut self, precompile_cache_disabled: bool) -> Self {
677        self.precompile_cache_disabled = precompile_cache_disabled;
678        self
679    }
680
681    /// Setter for whether to use state root fallback, useful for testing.
682    pub const fn with_state_root_fallback(mut self, state_root_fallback: bool) -> Self {
683        self.state_root_fallback = state_root_fallback;
684        self
685    }
686
687    /// Setter for whether to unwind canonical header to ancestor during forkchoice updates.
688    pub const fn with_unwind_canonical_header(mut self, unwind_canonical_header: bool) -> Self {
689        self.allow_unwind_canonical_header = unwind_canonical_header;
690        self
691    }
692
693    /// Returns whether cache metrics recording is disabled.
694    pub const fn disable_cache_metrics(&self) -> bool {
695        self.disable_cache_metrics
696    }
697
698    /// Setter for whether to disable cache metrics recording.
699    pub const fn without_cache_metrics(mut self, disable_cache_metrics: bool) -> Self {
700        self.disable_cache_metrics = disable_cache_metrics;
701        self
702    }
703
704    /// Returns the sparse trie prune depth.
705    pub const fn sparse_trie_prune_depth(&self) -> usize {
706        self.sparse_trie_prune_depth
707    }
708
709    /// Setter for sparse trie prune depth.
710    pub const fn with_sparse_trie_prune_depth(mut self, depth: usize) -> Self {
711        self.sparse_trie_prune_depth = depth;
712        self
713    }
714
715    /// Returns the slow block threshold, if configured.
716    ///
717    /// When `Some`, blocks whose total processing time exceeds this duration emit a structured
718    /// warning with timing, state-operation, and cache-hit-rate details. `Duration::ZERO` logs
719    /// every block.
720    pub const fn slow_block_threshold(&self) -> Option<Duration> {
721        self.slow_block_threshold
722    }
723
724    /// Setter for slow block threshold.
725    pub const fn with_slow_block_threshold(
726        mut self,
727        slow_block_threshold: Option<Duration>,
728    ) -> Self {
729        self.slow_block_threshold = slow_block_threshold;
730        self
731    }
732
733    /// Returns whether sparse trie cache pruning is disabled.
734    pub const fn disable_sparse_trie_cache_pruning(&self) -> bool {
735        self.disable_sparse_trie_cache_pruning
736    }
737
738    /// Setter for whether to disable sparse trie cache pruning.
739    pub const fn with_disable_sparse_trie_cache_pruning(mut self, value: bool) -> Self {
740        self.disable_sparse_trie_cache_pruning = value;
741        self
742    }
743
744    /// Returns the state root task timeout.
745    pub const fn state_root_task_timeout(&self) -> Option<Duration> {
746        self.state_root_task_timeout
747    }
748
749    /// Setter for state root task timeout.
750    pub const fn with_state_root_task_timeout(mut self, timeout: Option<Duration>) -> Self {
751        self.state_root_task_timeout = timeout;
752        self
753    }
754
755    /// Returns whether to share execution cache with the payload builder.
756    pub const fn share_execution_cache_with_payload_builder(&self) -> bool {
757        self.share_execution_cache_with_payload_builder
758    }
759
760    /// Returns whether to share sparse trie with the payload builder.
761    pub const fn share_sparse_trie_with_payload_builder(&self) -> bool {
762        self.share_sparse_trie_with_payload_builder
763    }
764
765    /// Setter for whether to share execution cache with the payload builder.
766    pub const fn with_share_execution_cache_with_payload_builder(
767        mut self,
768        share_execution_cache_with_payload_builder: bool,
769    ) -> Self {
770        self.share_execution_cache_with_payload_builder =
771            share_execution_cache_with_payload_builder;
772        self
773    }
774
775    /// Setter for whether to share sparse trie with the payload builder.
776    pub const fn with_share_sparse_trie_with_payload_builder(
777        mut self,
778        share_sparse_trie_with_payload_builder: bool,
779    ) -> Self {
780        self.share_sparse_trie_with_payload_builder = share_sparse_trie_with_payload_builder;
781        self
782    }
783
784    /// Returns whether persistence is suppressed during payload building.
785    pub const fn suppress_persistence_during_build(&self) -> bool {
786        self.suppress_persistence_during_build
787    }
788
789    /// Setter for whether to suppress persistence during payload building.
790    pub const fn with_suppress_persistence_during_build(mut self, value: bool) -> Self {
791        self.suppress_persistence_during_build = value;
792        self
793    }
794
795    /// Returns whether BAL-based parallel execution is disabled.
796    pub const fn disable_bal_parallel_execution(&self) -> bool {
797        self.disable_bal_parallel_execution
798    }
799
800    /// Setter for whether to disable BAL-based parallel execution.
801    pub const fn without_bal_parallel_execution(
802        mut self,
803        disable_bal_parallel_execution: bool,
804    ) -> Self {
805        self.disable_bal_parallel_execution = disable_bal_parallel_execution;
806        self
807    }
808
809    /// Returns whether BAL-driven parallel state root computation is disabled.
810    pub const fn disable_bal_parallel_state_root(&self) -> bool {
811        self.disable_bal_parallel_state_root
812    }
813
814    /// Setter for whether to disable BAL-driven parallel state root computation.
815    pub const fn without_bal_parallel_state_root(
816        mut self,
817        disable_bal_parallel_state_root: bool,
818    ) -> Self {
819        self.disable_bal_parallel_state_root = disable_bal_parallel_state_root;
820        self
821    }
822
823    /// Returns whether BAL state prefetching during prewarm is disabled.
824    pub const fn disable_bal_batch_io(&self) -> bool {
825        self.disable_bal_batch_io
826    }
827
828    /// Setter for whether to disable BAL state prefetching during prewarm.
829    pub const fn without_bal_batch_io(mut self, disable_bal_batch_io: bool) -> Self {
830        self.disable_bal_batch_io = disable_bal_batch_io;
831        self
832    }
833
834    /// Returns the BAL read-set prewarm pool size, or `None` for the production default.
835    pub const fn bal_prewarm_threads(&self) -> Option<NonZeroUsize> {
836        self.bal_prewarm_threads
837    }
838
839    /// Sets the nonzero number of BAL read-set prewarm workers per engine.
840    pub const fn with_bal_prewarm_threads(mut self, threads: NonZeroUsize) -> Self {
841        self.bal_prewarm_threads = Some(threads);
842        self
843    }
844
845    /// Returns whether block execution reuses transaction prewarming results.
846    pub const fn prewarm_reuse(&self) -> bool {
847        self.prewarm_reuse
848    }
849
850    /// Setter for whether block execution reuses transaction prewarming results.
851    pub const fn with_prewarm_reuse(mut self, prewarm_reuse: bool) -> Self {
852        self.prewarm_reuse = prewarm_reuse;
853        self
854    }
855
856    /// Returns whether trie state-root computation is skipped during engine validation.
857    pub const fn skip_state_root(&self) -> bool {
858        self.skip_state_root
859    }
860
861    /// Setter for whether to skip trie state-root computation during engine validation.
862    pub const fn with_skip_state_root(mut self, skip_state_root: bool) -> Self {
863        self.skip_state_root = skip_state_root;
864        self
865    }
866
867    /// Returns the proof jitter duration, if configured (trie-debug only).
868    #[cfg(feature = "trie-debug")]
869    pub const fn proof_jitter(&self) -> Option<Duration> {
870        self.proof_jitter
871    }
872
873    /// Setter for proof jitter (trie-debug only).
874    #[cfg(feature = "trie-debug")]
875    pub const fn with_proof_jitter(mut self, proof_jitter: Option<Duration>) -> Self {
876        self.proof_jitter = proof_jitter;
877        self
878    }
879}
880
881/// Clamps the threshold to [`MAX_BACKFILL_RUN_THRESHOLD`].
882///
883/// The live-sync range downloader holds every header and body of a gap in memory until the whole
884/// range is complete, so the clamp bounds that memory.
885const fn clamp_backfill_run_threshold(threshold: u64) -> u64 {
886    if threshold > MAX_BACKFILL_RUN_THRESHOLD {
887        MAX_BACKFILL_RUN_THRESHOLD
888    } else {
889        threshold
890    }
891}
892
893#[cfg(test)]
894mod tests {
895    use super::*;
896
897    #[test]
898    fn backfill_threshold_grows_block_buffer() {
899        let default = TreeConfig::default();
900        for (threshold, expected, buffer_limit) in
901            [(0, 0, 64), (500, 500, 1000), (1024, 1024, 2048), (u64::MAX, 1024, 2048)]
902        {
903            let config = default.clone().with_backfill_run_threshold(threshold);
904            assert_eq!(config.backfill_run_threshold(), expected);
905            assert_eq!(config.block_buffer_limit(), buffer_limit);
906        }
907        let config = default.with_block_buffer_limit(2000).with_backfill_run_threshold(500);
908        assert_eq!(config.block_buffer_limit(), 2000);
909    }
910
911    #[test]
912    #[should_panic(
913        expected = "persistence_backpressure_threshold must be greater than persistence_threshold"
914    )]
915    fn rejects_backpressure_threshold_at_or_below_persistence_threshold() {
916        let _ = TreeConfig::default()
917            .with_num_state_masking_blocks(0)
918            .with_persistence_threshold(4)
919            .with_persistence_backpressure_threshold(4);
920    }
921
922    #[test]
923    fn zero_persistence_threshold_disables_state_masking() {
924        let config = TreeConfig::default().with_persistence_threshold(0);
925        assert_eq!(config.num_state_masking_blocks(), 0);
926        let config = config.with_num_state_masking_blocks(u64::MAX);
927        assert_eq!(config.num_state_masking_blocks(), 0);
928        let config = config.with_memory_block_buffer_target(0);
929        assert_eq!(config.num_state_masking_blocks(), 0);
930    }
931
932    #[test]
933    #[should_panic(
934        expected = "num_state_masking_blocks + memory_block_buffer_target must be less than persistence_threshold"
935    )]
936    fn rejects_state_masking_window_at_or_above_persistence_threshold() {
937        let _ = TreeConfig::default()
938            .with_num_state_masking_blocks(0)
939            .with_persistence_threshold(4)
940            .with_memory_block_buffer_target(2)
941            .with_num_state_masking_blocks(2);
942    }
943
944    #[test]
945    #[should_panic(
946        expected = "num_state_masking_blocks + memory_block_buffer_target must be less than persistence_threshold"
947    )]
948    fn rejects_overflowing_state_masking_window() {
949        let _ = TreeConfig::default().with_num_state_masking_blocks(u64::MAX);
950    }
951}