Skip to main content

reth_provider/providers/rocksdb/
provider.rs

1use super::metrics::{RocksDBMetrics, RocksDBOperation, ROCKSDB_TABLES};
2use crate::providers::{compute_history_rank, needs_prev_shard_check, HistoryInfo};
3use alloy_consensus::transaction::TxHashRef;
4use alloy_primitives::{
5    map::{AddressMap, HashMap},
6    Address, BlockNumber, TxNumber, B256,
7};
8use itertools::Itertools;
9use metrics::Label;
10use parking_lot::Mutex;
11use reth_chain_state::ExecutedBlock;
12use reth_concurrency::sync::rayon::prelude::*;
13use reth_db_api::{
14    database_metrics::DatabaseMetrics,
15    models::{
16        sharded_key::NUM_OF_INDICES_IN_SHARD, storage_sharded_key::StorageShardedKey, ShardedKey,
17        StorageSettings,
18    },
19    table::{Compress, Decode, Decompress, Encode, Table},
20    tables, BlockNumberList, DatabaseError,
21};
22use reth_primitives_traits::{BlockBody as _, FastInstant as Instant};
23use reth_prune_types::PruneMode;
24use reth_storage_errors::{
25    db::{DatabaseErrorInfo, DatabaseWriteError, DatabaseWriteOperation, LogLevel},
26    provider::{ProviderError, ProviderResult},
27};
28use rocksdb::{
29    statistics::StatsLevel, BlockBasedOptions, Cache, ColumnFamilyDescriptor, CompactionPri,
30    DBCompressionType, DBRawIteratorWithThreadMode, IteratorMode, OptimisticTransactionDB,
31    OptimisticTransactionOptions, Options, ReadOptions, SnapshotWithThreadMode, Transaction,
32    WriteBatchWithTransaction, WriteBufferManager, WriteOptions, DB, DEFAULT_COLUMN_FAMILY_NAME,
33};
34use std::{
35    collections::BTreeMap,
36    fmt,
37    path::{Path, PathBuf},
38    sync::Arc,
39};
40use tracing::instrument;
41
42/// Returns [`WriteOptions`] with WAL sync enabled for crash durability.
43fn synced_write_options() -> WriteOptions {
44    let mut opts = WriteOptions::default();
45    opts.set_sync(true);
46    opts
47}
48
49/// Pending `RocksDB` batches type alias.
50pub(crate) type PendingRocksDBBatches = Arc<Mutex<Vec<WriteBatchWithTransaction<true>>>>;
51
52/// Raw key-value result from a `RocksDB` iterator.
53type RawKVResult = Result<(Box<[u8]>, Box<[u8]>), rocksdb::Error>;
54
55/// Statistics for a single `RocksDB` table (column family).
56#[derive(Debug, Clone)]
57pub struct RocksDBTableStats {
58    /// Size of SST files on disk in bytes.
59    pub sst_size_bytes: u64,
60    /// Size of memtables in memory in bytes.
61    pub memtable_size_bytes: u64,
62    /// Name of the table/column family.
63    pub name: String,
64    /// Estimated number of keys in the table.
65    pub estimated_num_keys: u64,
66    /// Estimated size of live data in bytes (SST files + memtables).
67    pub estimated_size_bytes: u64,
68    /// Estimated bytes pending compaction (reclaimable space).
69    pub pending_compaction_bytes: u64,
70}
71
72/// Database-level statistics for `RocksDB`.
73///
74/// Contains both per-table statistics and DB-level metrics like WAL size.
75#[derive(Debug, Clone)]
76pub struct RocksDBStats {
77    /// Statistics for each table (column family).
78    pub tables: Vec<RocksDBTableStats>,
79    /// Total size of WAL (Write-Ahead Log) files in bytes.
80    ///
81    /// WAL is shared across all tables and not included in per-table metrics.
82    pub wal_size_bytes: u64,
83}
84
85/// Context for `RocksDB` block writes.
86#[derive(Clone)]
87pub(crate) struct RocksDBWriteCtx {
88    /// The first block number being written.
89    pub first_block_number: BlockNumber,
90    /// The prune mode for transaction lookup, if any.
91    pub prune_tx_lookup: Option<PruneMode>,
92    /// Storage settings determining what goes to `RocksDB`.
93    pub storage_settings: StorageSettings,
94    /// Pending batches to push to after writing.
95    pub pending_batches: PendingRocksDBBatches,
96}
97
98impl fmt::Debug for RocksDBWriteCtx {
99    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100        f.debug_struct("RocksDBWriteCtx")
101            .field("first_block_number", &self.first_block_number)
102            .field("prune_tx_lookup", &self.prune_tx_lookup)
103            .field("storage_settings", &self.storage_settings)
104            .field("pending_batches", &"<pending batches>")
105            .finish()
106    }
107}
108
109/// Default cache size for `RocksDB` block cache (128 MB).
110const DEFAULT_CACHE_SIZE: usize = 128 << 20;
111
112/// Default block size for `RocksDB` tables (16 KB).
113const DEFAULT_BLOCK_SIZE: usize = 16 * 1024;
114
115/// Default max background jobs for `RocksDB` compaction and flushing.
116const DEFAULT_MAX_BACKGROUND_JOBS: i32 = 6;
117
118/// Max open file descriptors for `RocksDB` when the process limit is low.
119///
120/// Caps the number of SST file handles `RocksDB` keeps open simultaneously.
121/// Set to 512 to stay within the common default OS `ulimit -n` of 1024,
122/// leaving headroom for MDBX, static files, and other I/O.
123const LIMITED_MAX_OPEN_FILES: i32 = 512;
124
125/// Keeps all `RocksDB` files open and avoids table cache lookups.
126const KEEP_ALL_FILES_OPEN: i32 = -1;
127
128/// Minimum process file descriptor limit for keeping all `RocksDB` files open.
129///
130/// Mature archive databases can use tens of thousands of file descriptors. This threshold keeps
131/// unlimited mode for hosts configured for that workload while retaining a bounded table cache on
132/// systems with low limits.
133const HIGH_FILE_DESCRIPTOR_LIMIT: u64 = 128 * 1024;
134
135/// Default bytes per sync for `RocksDB` WAL writes (1 MB).
136const DEFAULT_BYTES_PER_SYNC: u64 = 1_048_576;
137
138/// Default write buffer size for `RocksDB` memtables (128 MB).
139///
140/// Larger memtables reduce flush frequency during burst writes, providing more consistent
141/// tail latency. Benchmarks showed 128 MB reduces p99 latency variance by ~80% compared
142/// to 64 MB default, with negligible impact on mean throughput.
143const DEFAULT_WRITE_BUFFER_SIZE: usize = 128 << 20;
144
145/// Default total `RocksDB` memtable memory budget across column families (4 GiB).
146///
147/// This is a soft limit; with write stalls enabled, `RocksDB` waits for flushes once
148/// memtable arena usage exceeds the budget.
149const DEFAULT_WRITE_BUFFER_MANAGER_SIZE: usize = 4 * 1024 * 1024 * 1024;
150
151/// Default buffer capacity for compression in batches.
152/// 4 KiB matches common block/page sizes and comfortably holds typical history values,
153/// reducing the first few reallocations without over-allocating.
154const DEFAULT_COMPRESS_BUF_CAPACITY: usize = 4096;
155
156/// Default auto-commit threshold for batch writes (512 MiB).
157///
158/// When a batch exceeds this size, it is automatically committed to prevent OOM
159/// during large bulk writes. Keep this below the `RocksDB` write buffer manager
160/// budget so stalls can recover without waiting on a single large flush.
161/// The consistency check on startup heals any crash that occurs between auto-commits.
162const DEFAULT_AUTO_COMMIT_THRESHOLD: usize = 512 * 1024 * 1024;
163
164/// Minimum BAL value size stored in `BlobDB` files.
165///
166/// Smaller BALs stay inline. Larger payloads avoid regular LSM value compaction.
167const DEFAULT_BAL_MIN_BLOB_SIZE: u64 = 4 * 1024;
168
169/// Target BAL blob file size.
170const DEFAULT_BAL_BLOB_FILE_SIZE: u64 = 256 * 1024 * 1024;
171
172/// Builder for [`RocksDBProvider`].
173pub struct RocksDBBuilder {
174    path: PathBuf,
175    column_families: Vec<String>,
176    enable_metrics: bool,
177    enable_statistics: bool,
178    log_level: rocksdb::LogLevel,
179    block_cache: Cache,
180    read_only: bool,
181}
182
183impl fmt::Debug for RocksDBBuilder {
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        f.debug_struct("RocksDBBuilder")
186            .field("path", &self.path)
187            .field("column_families", &self.column_families)
188            .field("enable_metrics", &self.enable_metrics)
189            .finish()
190    }
191}
192
193impl RocksDBBuilder {
194    /// Creates a new builder with optimized default options.
195    pub fn new(path: impl AsRef<Path>) -> Self {
196        let cache = Cache::new_lru_cache(DEFAULT_CACHE_SIZE);
197        Self {
198            path: path.as_ref().to_path_buf(),
199            column_families: Vec::new(),
200            enable_metrics: false,
201            enable_statistics: false,
202            log_level: rocksdb::LogLevel::Info,
203            block_cache: cache,
204            read_only: false,
205        }
206    }
207
208    /// Creates default table options with shared block cache.
209    fn default_table_options(cache: &Cache) -> BlockBasedOptions {
210        let mut table_options = BlockBasedOptions::default();
211        table_options.set_block_size(DEFAULT_BLOCK_SIZE);
212        table_options.set_cache_index_and_filter_blocks(true);
213        table_options.set_pin_l0_filter_and_index_blocks_in_cache(true);
214        // Shared block cache for all column families.
215        table_options.set_block_cache(cache);
216        table_options
217    }
218
219    /// Creates optimized `RocksDB` options per `RocksDB` wiki recommendations.
220    fn default_options(
221        log_level: rocksdb::LogLevel,
222        cache: &Cache,
223        enable_statistics: bool,
224    ) -> Options {
225        // Follow recommend tuning guide from RocksDB wiki, see https://github.com/facebook/rocksdb/wiki/Setup-Options-and-Basic-Tuning
226        let table_options = Self::default_table_options(cache);
227
228        let mut options = Options::default();
229        options.set_block_based_table_factory(&table_options);
230        options.create_if_missing(true);
231        options.create_missing_column_families(true);
232        options.set_max_background_jobs(DEFAULT_MAX_BACKGROUND_JOBS);
233        options.set_bytes_per_sync(DEFAULT_BYTES_PER_SYNC);
234        let write_buffer_manager =
235            WriteBufferManager::new_write_buffer_manager(DEFAULT_WRITE_BUFFER_MANAGER_SIZE, true);
236        options.set_write_buffer_manager(&write_buffer_manager);
237
238        options.set_bottommost_compression_type(DBCompressionType::Zstd);
239        options.set_bottommost_zstd_max_train_bytes(0, true);
240        options.set_compression_type(DBCompressionType::Lz4);
241        options.set_compaction_pri(CompactionPri::MinOverlappingRatio);
242
243        options.set_log_level(log_level);
244
245        options.set_max_open_files(select_max_open_files());
246
247        // Delete obsolete WAL files immediately after all column families have flushed.
248        // Both set to 0 means "delete ASAP, no archival".
249        options.set_wal_ttl_seconds(0);
250        options.set_wal_size_limit_mb(0);
251
252        // Statistics can view from RocksDB log file
253        if enable_statistics {
254            options.enable_statistics();
255            // Nothing reads the statistics programmatically, they only end up in the periodic
256            // LOG dump, so collect the counters but not the timer histograms: at the default
257            // level every `Get`, `Seek` and write wraps itself in a `StopWatch` that reads the
258            // clock twice, while the tickers are plain atomic increments.
259            //
260            // Note: the discriminants of `rocksdb::StatsLevel` are one higher than the levels the
261            // C API defines, so this variant selects "except timers". Should that ever be
262            // corrected upstream it selects "except histogram or timers", which also keeps the
263            // tickers and drops the timers.
264            options.set_statistics_level(StatsLevel::ExceptHistogramOrTimers);
265        }
266
267        options
268    }
269
270    /// Creates optimized column family options.
271    fn default_column_family_options(cache: &Cache) -> Options {
272        // Follow recommend tuning guide from RocksDB wiki, see https://github.com/facebook/rocksdb/wiki/Setup-Options-and-Basic-Tuning
273        let table_options = Self::default_table_options(cache);
274
275        let mut cf_options = Options::default();
276        cf_options.set_block_based_table_factory(&table_options);
277        cf_options.set_level_compaction_dynamic_level_bytes(true);
278        // Recommend to use Zstd for bottommost compression and Lz4 for other levels, see https://github.com/facebook/rocksdb/wiki/Compression#configuration
279        cf_options.set_compression_type(DBCompressionType::Lz4);
280        cf_options.set_bottommost_compression_type(DBCompressionType::Zstd);
281        // Only use Zstd compression, disable dictionary training
282        cf_options.set_bottommost_zstd_max_train_bytes(0, true);
283        cf_options.set_write_buffer_size(DEFAULT_WRITE_BUFFER_SIZE);
284
285        cf_options
286    }
287
288    /// Creates column family options for block access list payloads.
289    fn block_access_lists_column_family_options(cache: &Cache) -> Options {
290        let mut cf_options = Self::default_column_family_options(cache);
291        cf_options.set_enable_blob_files(true);
292        cf_options.set_min_blob_size(DEFAULT_BAL_MIN_BLOB_SIZE);
293        cf_options.set_blob_file_size(DEFAULT_BAL_BLOB_FILE_SIZE);
294        cf_options.set_blob_compression_type(DBCompressionType::Lz4);
295        cf_options
296    }
297
298    /// Creates optimized column family options for `TransactionHashNumbers`.
299    ///
300    /// This table stores `B256 -> TxNumber` mappings where:
301    /// - Keys are incompressible 32-byte hashes (compression wastes CPU for zero benefit)
302    /// - Values are varint-encoded `u64` (a few bytes - too small to benefit from compression)
303    /// - Every lookup expects a hit (bloom filters only help when checking non-existent keys)
304    fn tx_hash_numbers_column_family_options(cache: &Cache) -> Options {
305        let mut table_options = BlockBasedOptions::default();
306        table_options.set_block_size(DEFAULT_BLOCK_SIZE);
307        table_options.set_cache_index_and_filter_blocks(true);
308        table_options.set_pin_l0_filter_and_index_blocks_in_cache(true);
309        table_options.set_block_cache(cache);
310        // Disable bloom filter: every lookup expects a hit, so bloom filters provide no benefit
311        // and waste memory
312
313        let mut cf_options = Options::default();
314        cf_options.set_block_based_table_factory(&table_options);
315        cf_options.set_level_compaction_dynamic_level_bytes(true);
316        // Disable compression: B256 keys are incompressible hashes, TxNumber values are
317        // varint-encoded u64 (a few bytes). Compression wastes CPU cycles for zero space savings.
318        cf_options.set_compression_type(DBCompressionType::None);
319        cf_options.set_bottommost_compression_type(DBCompressionType::None);
320
321        cf_options
322    }
323
324    /// Adds a column family for a specific table type.
325    pub fn with_table<T: Table>(mut self) -> Self {
326        self.column_families.push(T::NAME.to_string());
327        self
328    }
329
330    /// Registers the default tables used by reth for `RocksDB` storage.
331    ///
332    /// This registers:
333    /// - [`tables::TransactionHashNumbers`] - Transaction hash to number mapping
334    /// - [`tables::AccountsHistory`] - Account history index
335    /// - [`tables::StoragesHistory`] - Storage history index
336    /// - [`tables::BlockAccessLists`] - Block access list payloads
337    /// - [`tables::BlockAccessListBlockNumbers`] - Block access list hash index
338    pub fn with_default_tables(self) -> Self {
339        self.with_table::<tables::TransactionHashNumbers>()
340            .with_table::<tables::AccountsHistory>()
341            .with_table::<tables::StoragesHistory>()
342            .with_table::<tables::BlockAccessLists>()
343            .with_table::<tables::BlockAccessListBlockNumbers>()
344    }
345
346    /// Enables metrics.
347    pub const fn with_metrics(mut self) -> Self {
348        self.enable_metrics = true;
349        self
350    }
351
352    /// Enables `RocksDB` internal statistics collection.
353    pub const fn with_statistics(mut self) -> Self {
354        self.enable_statistics = true;
355        self
356    }
357
358    /// Sets the log level from `DatabaseArgs` configuration.
359    pub const fn with_database_log_level(mut self, log_level: Option<LogLevel>) -> Self {
360        if let Some(level) = log_level {
361            self.log_level = convert_log_level(level);
362        }
363        self
364    }
365
366    /// Sets a custom block cache size.
367    pub fn with_block_cache_size(mut self, capacity_bytes: usize) -> Self {
368        self.block_cache = Cache::new_lru_cache(capacity_bytes);
369        self
370    }
371
372    /// Sets a custom block cache size if provided, otherwise keeps the current cache.
373    pub fn with_block_cache_size_opt(self, capacity_bytes: Option<usize>) -> Self {
374        if let Some(capacity_bytes) = capacity_bytes {
375            self.with_block_cache_size(capacity_bytes)
376        } else {
377            self
378        }
379    }
380
381    /// Sets read-only mode.
382    ///
383    /// Opens the database as a secondary instance, which supports catching up
384    /// with the primary via [`RocksDBProvider::try_catch_up_with_primary`].
385    /// A temporary directory is created automatically for the secondary's LOG files.
386    ///
387    /// Note: Write operations on a read-only provider will panic at runtime.
388    pub const fn with_read_only(mut self, read_only: bool) -> Self {
389        self.read_only = read_only;
390        self
391    }
392
393    /// Builds the [`RocksDBProvider`].
394    pub fn build(self) -> ProviderResult<RocksDBProvider> {
395        let options =
396            Self::default_options(self.log_level, &self.block_cache, self.enable_statistics);
397
398        let mut cf_descriptors: Vec<ColumnFamilyDescriptor> = self
399            .column_families
400            .iter()
401            .map(|name| {
402                let cf_options = if name == tables::TransactionHashNumbers::NAME {
403                    Self::tx_hash_numbers_column_family_options(&self.block_cache)
404                } else if name == tables::BlockAccessLists::NAME {
405                    Self::block_access_lists_column_family_options(&self.block_cache)
406                } else {
407                    Self::default_column_family_options(&self.block_cache)
408                };
409                ColumnFamilyDescriptor::new(name.clone(), cf_options)
410            })
411            .collect();
412
413        // RocksDB requires every existing column family to be opened. Preserve column families
414        // unknown to this configuration so databases remain openable after a downgrade.
415        if RocksDBProvider::exists(&self.path) {
416            let existing_column_families = DB::list_cf(&options, &self.path).map_err(|e| {
417                ProviderError::Database(DatabaseError::Open(DatabaseErrorInfo {
418                    message: e.to_string().into(),
419                    code: -1,
420                }))
421            })?;
422            if self.read_only {
423                // Legacy databases have no BAL tables; secondary opens cannot create them.
424                // Keep existing BAL tables; only omit those absent from disk.
425                cf_descriptors.retain(|cf| {
426                    !matches!(
427                        cf.name(),
428                        tables::BlockAccessLists::NAME | tables::BlockAccessListBlockNumbers::NAME
429                    ) || existing_column_families.iter().any(|name| name == cf.name())
430                });
431            }
432            let unknown_column_families: Vec<String> = existing_column_families
433                .into_iter()
434                .filter(|name| {
435                    name != DEFAULT_COLUMN_FAMILY_NAME && !self.column_families.contains(name)
436                })
437                .collect();
438            if !unknown_column_families.is_empty() {
439                tracing::debug!(
440                    target: "providers::rocksdb",
441                    column_families = ?unknown_column_families,
442                    "Preserving unknown column families"
443                );
444                cf_descriptors.extend(unknown_column_families.into_iter().map(|name| {
445                    ColumnFamilyDescriptor::new(
446                        name,
447                        Self::default_column_family_options(&self.block_cache),
448                    )
449                }));
450            }
451        }
452
453        let metrics = self.enable_metrics.then(RocksDBMetrics::default);
454
455        if self.read_only {
456            // Open as secondary instance for catch-up capability.
457            // Secondary needs max_open_files = -1 to keep all FDs open.
458            let mut options = options;
459            options.set_max_open_files(KEEP_ALL_FILES_OPEN);
460
461            let secondary_path = self
462                .path
463                .parent()
464                .unwrap_or(&self.path)
465                .join(format!("rocksdb-secondary-tmp-{}", std::process::id()));
466            reth_fs_util::create_dir_all(&secondary_path).map_err(ProviderError::other)?;
467
468            let db = DB::open_cf_descriptors_as_secondary(
469                &options,
470                &self.path,
471                &secondary_path,
472                cf_descriptors,
473            )
474            .map_err(|e| {
475                ProviderError::Database(DatabaseError::Open(DatabaseErrorInfo {
476                    message: e.to_string().into(),
477                    code: -1,
478                }))
479            })?;
480            Ok(RocksDBProvider(Arc::new(RocksDBProviderInner::Secondary {
481                db,
482                metrics,
483                secondary_path,
484            })))
485        } else {
486            // Use OptimisticTransactionDB for MDBX-like transaction semantics (read-your-writes,
487            // rollback) OptimisticTransactionDB uses optimistic concurrency control (conflict
488            // detection at commit) and is backed by DBCommon, giving us access to
489            // cancel_all_background_work for clean shutdown.
490            let db =
491                OptimisticTransactionDB::open_cf_descriptors(&options, &self.path, cf_descriptors)
492                    .map_err(|e| {
493                        ProviderError::Database(DatabaseError::Open(DatabaseErrorInfo {
494                            message: e.to_string().into(),
495                            code: -1,
496                        }))
497                    })?;
498            Ok(RocksDBProvider(Arc::new(RocksDBProviderInner::ReadWrite { db, metrics })))
499        }
500    }
501}
502
503/// Some types don't support compression (eg. B256), and we don't want to be copying them to the
504/// allocated buffer when we can just use their reference.
505macro_rules! compress_to_buf_or_ref {
506    ($buf:expr, $value:expr) => {
507        if let Some(value) = $value.uncompressable_ref() {
508            Some(value)
509        } else {
510            $buf.clear();
511            $value.compress_to_buf(&mut $buf);
512            None
513        }
514    };
515}
516
517/// `RocksDB` provider for auxiliary storage layer beside main database MDBX.
518#[derive(Debug)]
519pub struct RocksDBProvider(Arc<RocksDBProviderInner>);
520
521/// Inner state for `RocksDB` provider.
522enum RocksDBProviderInner {
523    /// Read-write mode using `OptimisticTransactionDB`.
524    ReadWrite {
525        /// `RocksDB` database instance with optimistic transaction support.
526        db: OptimisticTransactionDB,
527        /// Metrics latency & operations.
528        metrics: Option<RocksDBMetrics>,
529    },
530    /// Secondary mode using `DB` opened with `open_cf_descriptors_as_secondary`.
531    /// Supports catching up with the primary via `try_catch_up_with_primary`.
532    /// Does not support snapshots; consistency is guaranteed externally.
533    Secondary {
534        /// Secondary `RocksDB` database instance.
535        db: DB,
536        /// Metrics latency & operations.
537        metrics: Option<RocksDBMetrics>,
538        /// Temporary directory for secondary LOG files, removed on drop.
539        secondary_path: PathBuf,
540    },
541}
542
543impl RocksDBProviderInner {
544    /// Returns the metrics for this provider.
545    const fn metrics(&self) -> Option<&RocksDBMetrics> {
546        match self {
547            Self::ReadWrite { metrics, .. } | Self::Secondary { metrics, .. } => metrics.as_ref(),
548        }
549    }
550
551    /// Returns the read-write database, panicking if in read-only mode.
552    fn db_rw(&self) -> &OptimisticTransactionDB {
553        match self {
554            Self::ReadWrite { db, .. } => db,
555            Self::Secondary { .. } => {
556                panic!("Cannot perform write operation on secondary RocksDB provider")
557            }
558        }
559    }
560
561    /// Gets the column family handle for a table.
562    fn cf_handle<T: Table>(&self) -> Result<&rocksdb::ColumnFamily, DatabaseError> {
563        let cf = match self {
564            Self::ReadWrite { db, .. } => db.cf_handle(T::NAME),
565            Self::Secondary { db, .. } => db.cf_handle(T::NAME),
566        };
567        cf.ok_or_else(|| DatabaseError::Other(format!("Column family '{}' not found", T::NAME)))
568    }
569
570    /// Gets a value from a column family.
571    fn get_cf(
572        &self,
573        cf: &rocksdb::ColumnFamily,
574        key: impl AsRef<[u8]>,
575    ) -> Result<Option<Vec<u8>>, rocksdb::Error> {
576        match self {
577            Self::ReadWrite { db, .. } => db.get_cf(cf, key),
578            Self::Secondary { db, .. } => db.get_cf(cf, key),
579        }
580    }
581
582    /// Puts a value into a column family.
583    fn put_cf(
584        &self,
585        cf: &rocksdb::ColumnFamily,
586        key: impl AsRef<[u8]>,
587        value: impl AsRef<[u8]>,
588    ) -> Result<(), rocksdb::Error> {
589        self.db_rw().put_cf(cf, key, value)
590    }
591
592    /// Deletes a value from a column family.
593    fn delete_cf(
594        &self,
595        cf: &rocksdb::ColumnFamily,
596        key: impl AsRef<[u8]>,
597    ) -> Result<(), rocksdb::Error> {
598        self.db_rw().delete_cf(cf, key)
599    }
600
601    /// Deletes a range of values from a column family.
602    fn delete_range_cf<K: AsRef<[u8]>>(
603        &self,
604        cf: &rocksdb::ColumnFamily,
605        from: K,
606        to: K,
607    ) -> Result<(), rocksdb::Error> {
608        self.db_rw().delete_range_cf(cf, from, to)
609    }
610
611    /// Returns an iterator over a column family.
612    fn iterator_cf(
613        &self,
614        cf: &rocksdb::ColumnFamily,
615        mode: IteratorMode<'_>,
616    ) -> RocksDBIterEnum<'_> {
617        match self {
618            Self::ReadWrite { db, .. } => RocksDBIterEnum::ReadWrite(db.iterator_cf(cf, mode)),
619            Self::Secondary { db, .. } => RocksDBIterEnum::ReadOnly(db.iterator_cf(cf, mode)),
620        }
621    }
622
623    /// Returns a raw iterator over a column family.
624    ///
625    /// Unlike [`Self::iterator_cf`], raw iterators support `seek()` for efficient
626    /// repositioning without creating a new iterator.
627    fn raw_iterator_cf(&self, cf: &rocksdb::ColumnFamily) -> RocksDBRawIterEnum<'_> {
628        match self {
629            Self::ReadWrite { db, .. } => RocksDBRawIterEnum::ReadWrite(db.raw_iterator_cf(cf)),
630            Self::Secondary { db, .. } => RocksDBRawIterEnum::ReadOnly(db.raw_iterator_cf(cf)),
631        }
632    }
633
634    /// Returns a forward iterator over a column family over the keys in `[from, last]`.
635    ///
636    /// The bound matters when the range is followed by many deleted keys: an unbounded iterator
637    /// that runs out of live keys in the range skips every tombstone after it until it finds the
638    /// next live key, whereas a bounded one stops at the bound.
639    fn iterator_cf_inclusive_range(
640        &self,
641        cf: &rocksdb::ColumnFamily,
642        from: &[u8],
643        last: &[u8],
644    ) -> RocksDBIterEnum<'_> {
645        // The smallest key greater than `last` is `last` followed by a zero byte.
646        let mut upper_bound = Vec::with_capacity(last.len() + 1);
647        upper_bound.extend_from_slice(last);
648        upper_bound.push(0);
649
650        let mut opts = ReadOptions::default();
651        opts.set_iterate_upper_bound(upper_bound);
652        let mode = IteratorMode::From(from, rocksdb::Direction::Forward);
653        match self {
654            Self::ReadWrite { db, .. } => {
655                RocksDBIterEnum::ReadWrite(db.iterator_cf_opt(cf, opts, mode))
656            }
657            Self::Secondary { db, .. } => {
658                RocksDBIterEnum::ReadOnly(db.iterator_cf_opt(cf, opts, mode))
659            }
660        }
661    }
662
663    /// Returns a read-only, point-in-time snapshot of the database.
664    fn snapshot(&self) -> RocksReadSnapshotInner<'_> {
665        match self {
666            Self::ReadWrite { db, .. } => RocksReadSnapshotInner::ReadWrite(db.snapshot()),
667            Self::Secondary { db, .. } => RocksReadSnapshotInner::Secondary(db),
668        }
669    }
670
671    /// Returns the path to the database directory.
672    fn path(&self) -> &Path {
673        match self {
674            Self::ReadWrite { db, .. } => db.path(),
675            Self::Secondary { db, .. } => db.path(),
676        }
677    }
678
679    /// Returns the total size of WAL (Write-Ahead Log) files in bytes.
680    ///
681    /// WAL files have a `.log` extension in the `RocksDB` directory.
682    fn wal_size_bytes(&self) -> u64 {
683        let path = self.path();
684
685        match std::fs::read_dir(path) {
686            Ok(entries) => entries
687                .filter_map(|e| e.ok())
688                .filter(|e| e.path().extension().is_some_and(|ext| ext == "log"))
689                .filter_map(|e| e.metadata().ok())
690                .map(|m| m.len())
691                .sum(),
692            Err(_) => 0,
693        }
694    }
695
696    /// Returns statistics for all column families in the database.
697    fn table_stats(&self) -> Vec<RocksDBTableStats> {
698        let mut stats = Vec::new();
699
700        macro_rules! collect_stats {
701            ($db:expr) => {
702                for cf_name in ROCKSDB_TABLES {
703                    if let Some(cf) = $db.cf_handle(cf_name) {
704                        let estimated_num_keys = $db
705                            .property_int_value_cf(cf, rocksdb::properties::ESTIMATE_NUM_KEYS)
706                            .ok()
707                            .flatten()
708                            .unwrap_or(0);
709
710                        // SST files size (on-disk) + memtable size (in-memory)
711                        let sst_size = $db
712                            .property_int_value_cf(cf, rocksdb::properties::LIVE_SST_FILES_SIZE)
713                            .ok()
714                            .flatten()
715                            .unwrap_or(0);
716
717                        let memtable_size = $db
718                            .property_int_value_cf(cf, rocksdb::properties::SIZE_ALL_MEM_TABLES)
719                            .ok()
720                            .flatten()
721                            .unwrap_or(0);
722
723                        let estimated_size_bytes = sst_size + memtable_size;
724
725                        let pending_compaction_bytes = $db
726                            .property_int_value_cf(
727                                cf,
728                                rocksdb::properties::ESTIMATE_PENDING_COMPACTION_BYTES,
729                            )
730                            .ok()
731                            .flatten()
732                            .unwrap_or(0);
733
734                        stats.push(RocksDBTableStats {
735                            sst_size_bytes: sst_size,
736                            memtable_size_bytes: memtable_size,
737                            name: cf_name.to_string(),
738                            estimated_num_keys,
739                            estimated_size_bytes,
740                            pending_compaction_bytes,
741                        });
742                    }
743                }
744            };
745        }
746
747        match self {
748            Self::ReadWrite { db, .. } => collect_stats!(db),
749            Self::Secondary { db, .. } => collect_stats!(db),
750        }
751
752        stats
753    }
754
755    /// Returns database-level statistics including per-table stats and WAL size.
756    fn db_stats(&self) -> RocksDBStats {
757        RocksDBStats { tables: self.table_stats(), wal_size_bytes: self.wal_size_bytes() }
758    }
759}
760
761impl fmt::Debug for RocksDBProviderInner {
762    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
763        match self {
764            Self::ReadWrite { metrics, .. } => f
765                .debug_struct("RocksDBProviderInner::ReadWrite")
766                .field("db", &"<OptimisticTransactionDB>")
767                .field("metrics", metrics)
768                .finish(),
769            Self::Secondary { metrics, .. } => f
770                .debug_struct("RocksDBProviderInner::Secondary")
771                .field("db", &"<DB (secondary)>")
772                .field("metrics", metrics)
773                .finish(),
774        }
775    }
776}
777
778impl Drop for RocksDBProviderInner {
779    fn drop(&mut self) {
780        match self {
781            Self::ReadWrite { db, .. } => {
782                // Flush all memtables if possible. If not, they will be rebuilt from the WAL on
783                // restart
784                if let Err(e) = db.flush_wal(true) {
785                    tracing::warn!(target: "providers::rocksdb", ?e, "Failed to flush WAL on drop");
786                }
787                for cf_name in ROCKSDB_TABLES {
788                    if let Some(cf) = db.cf_handle(cf_name) &&
789                        let Err(e) = db.flush_cf(&cf)
790                    {
791                        tracing::warn!(target: "providers::rocksdb", cf = cf_name, ?e, "Failed to flush CF on drop");
792                    }
793                }
794                db.cancel_all_background_work(true);
795            }
796            Self::Secondary { db, secondary_path, .. } => {
797                db.cancel_all_background_work(true);
798                let _ = std::fs::remove_dir_all(secondary_path);
799            }
800        }
801    }
802}
803
804impl Clone for RocksDBProvider {
805    fn clone(&self) -> Self {
806        Self(self.0.clone())
807    }
808}
809
810impl DatabaseMetrics for RocksDBProvider {
811    fn gauge_metrics(&self) -> Vec<(&'static str, f64, Vec<Label>)> {
812        let mut metrics = Vec::new();
813
814        for stat in self.table_stats() {
815            metrics.push((
816                "rocksdb.table_size",
817                stat.estimated_size_bytes as f64,
818                vec![Label::new("table", stat.name.clone())],
819            ));
820            metrics.push((
821                "rocksdb.table_entries",
822                stat.estimated_num_keys as f64,
823                vec![Label::new("table", stat.name.clone())],
824            ));
825            metrics.push((
826                "rocksdb.pending_compaction_bytes",
827                stat.pending_compaction_bytes as f64,
828                vec![Label::new("table", stat.name.clone())],
829            ));
830            metrics.push((
831                "rocksdb.sst_size",
832                stat.sst_size_bytes as f64,
833                vec![Label::new("table", stat.name.clone())],
834            ));
835            metrics.push((
836                "rocksdb.memtable_size",
837                stat.memtable_size_bytes as f64,
838                vec![Label::new("table", stat.name)],
839            ));
840        }
841
842        // WAL size (DB-level, shared across all tables)
843        metrics.push(("rocksdb.wal_size", self.wal_size_bytes() as f64, vec![]));
844
845        metrics
846    }
847}
848
849impl RocksDBProvider {
850    /// Creates a new `RocksDB` provider.
851    pub fn new(path: impl AsRef<Path>) -> ProviderResult<Self> {
852        RocksDBBuilder::new(path).build()
853    }
854
855    /// Creates a new `RocksDB` provider builder.
856    pub fn builder(path: impl AsRef<Path>) -> RocksDBBuilder {
857        RocksDBBuilder::new(path)
858    }
859
860    /// Returns `true` if a `RocksDB` database exists at the given path.
861    ///
862    /// Checks for the presence of the `CURRENT` file, which `RocksDB` creates
863    /// when initializing a database.
864    pub fn exists(path: impl AsRef<Path>) -> bool {
865        path.as_ref().join("CURRENT").exists()
866    }
867
868    /// Returns `true` if this is the only handle to the database, so that dropping it closes the
869    /// database on the current thread.
870    pub fn is_last_handle(&self) -> bool {
871        Arc::strong_count(&self.0) == 1
872    }
873
874    /// Returns `true` if this provider is in read-only mode.
875    pub fn is_read_only(&self) -> bool {
876        matches!(self.0.as_ref(), RocksDBProviderInner::Secondary { .. })
877    }
878
879    /// Tries to catch up with the primary instance by reading new WAL and MANIFEST entries.
880    ///
881    /// This is a no-op for read-write and read-only providers.
882    /// For secondary providers, this incrementally syncs with the primary's latest state.
883    pub fn try_catch_up_with_primary(&self) -> ProviderResult<()> {
884        match self.0.as_ref() {
885            RocksDBProviderInner::Secondary { db, .. } => {
886                db.try_catch_up_with_primary().map_err(|e| {
887                    ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
888                        message: e.to_string().into(),
889                        code: -1,
890                    }))
891                })
892            }
893            _ => Ok(()),
894        }
895    }
896
897    /// Returns a read-only, point-in-time snapshot of the database.
898    ///
899    /// Lighter weight than [`RocksTx`] — no write-conflict tracking, and `Send + Sync`.
900    pub fn snapshot(&self) -> RocksReadSnapshot<'_> {
901        RocksReadSnapshot {
902            accounts_history_iter: Mutex::new(None),
903            storages_history_iter: Mutex::new(None),
904            inner: self.0.snapshot(),
905            provider: &self.0,
906        }
907    }
908
909    /// Returns a read-only, point-in-time snapshot that owns the provider handle it reads through.
910    ///
911    /// Lets a reader keep one snapshot (and the iterators cached in it) alive for its whole
912    /// lifetime, instead of creating a snapshot per lookup.
913    pub fn owned_snapshot(&self) -> OwnedRocksReadSnapshot {
914        OwnedRocksReadSnapshot::new(self)
915    }
916
917    /// Creates a new transaction with MDBX-like semantics (read-your-writes, rollback).
918    ///
919    /// Note: With `OptimisticTransactionDB`, commits may fail if there are conflicts.
920    /// Conflict detection happens at commit time, not at write time.
921    ///
922    /// # Panics
923    /// Panics if the provider is in read-only mode.
924    pub fn tx(&self) -> RocksTx<'_> {
925        let write_options = synced_write_options();
926        let txn_options = OptimisticTransactionOptions::default();
927        let inner = self.0.db_rw().transaction_opt(&write_options, &txn_options);
928        RocksTx { inner, provider: self }
929    }
930
931    /// Creates a new batch for atomic writes.
932    ///
933    /// Use [`Self::write_batch`] for closure-based atomic writes.
934    /// Use this method when the batch needs to be held by [`crate::EitherWriter`].
935    ///
936    /// # Panics
937    /// Panics if the provider is in read-only mode when attempting to commit.
938    pub fn batch(&self) -> RocksDBBatch<'_> {
939        RocksDBBatch {
940            provider: self,
941            inner: WriteBatchWithTransaction::<true>::default(),
942            buf: Vec::with_capacity(DEFAULT_COMPRESS_BUF_CAPACITY),
943            auto_commit_threshold: None,
944        }
945    }
946
947    /// Creates a new batch with auto-commit enabled.
948    ///
949    /// When the batch size exceeds the threshold (4 GiB), the batch is automatically
950    /// committed and reset. This prevents OOM during large bulk writes while maintaining
951    /// crash-safety via the consistency check on startup.
952    pub fn batch_with_auto_commit(&self) -> RocksDBBatch<'_> {
953        RocksDBBatch {
954            provider: self,
955            inner: WriteBatchWithTransaction::<true>::default(),
956            buf: Vec::with_capacity(DEFAULT_COMPRESS_BUF_CAPACITY),
957            auto_commit_threshold: Some(DEFAULT_AUTO_COMMIT_THRESHOLD),
958        }
959    }
960
961    /// Gets the column family handle for a table.
962    fn get_cf_handle<T: Table>(&self) -> Result<&rocksdb::ColumnFamily, DatabaseError> {
963        self.0.cf_handle::<T>()
964    }
965
966    /// Returns whether this provider opened the given table.
967    pub(crate) fn has_table<T: Table>(&self) -> bool {
968        match self.0.as_ref() {
969            RocksDBProviderInner::ReadWrite { db, .. } => db.cf_handle(T::NAME).is_some(),
970            RocksDBProviderInner::Secondary { db, .. } => db.cf_handle(T::NAME).is_some(),
971        }
972    }
973
974    /// Executes a function and records metrics with the given operation and table name.
975    fn execute_with_operation_metric<R>(
976        &self,
977        operation: RocksDBOperation,
978        table: &'static str,
979        f: impl FnOnce(&Self) -> R,
980    ) -> R {
981        let start = self.0.metrics().map(|_| Instant::now());
982        let res = f(self);
983
984        if let (Some(start), Some(metrics)) = (start, self.0.metrics()) {
985            metrics.record_operation(operation, table, start.elapsed());
986        }
987
988        res
989    }
990
991    /// Gets a value from the specified table.
992    pub fn get<T: Table>(&self, key: T::Key) -> ProviderResult<Option<T::Value>> {
993        self.get_encoded::<T>(&key.encode())
994    }
995
996    /// Gets a value from the specified table using pre-encoded key.
997    pub fn get_encoded<T: Table>(
998        &self,
999        key: &<T::Key as Encode>::Encoded,
1000    ) -> ProviderResult<Option<T::Value>> {
1001        self.execute_with_operation_metric(RocksDBOperation::Get, T::NAME, |this| {
1002            let result = this.0.get_cf(this.get_cf_handle::<T>()?, key.as_ref()).map_err(|e| {
1003                ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
1004                    message: e.to_string().into(),
1005                    code: -1,
1006                }))
1007            })?;
1008
1009            Ok(result.and_then(|value| T::Value::decompress(&value).ok()))
1010        })
1011    }
1012
1013    /// Gets raw bytes from the specified table without decompressing.
1014    pub fn get_raw<T: Table>(&self, key: T::Key) -> ProviderResult<Option<Vec<u8>>> {
1015        let encoded = key.encode();
1016        self.execute_with_operation_metric(RocksDBOperation::Get, T::NAME, |this| {
1017            this.0.get_cf(this.get_cf_handle::<T>()?, encoded.as_ref()).map_err(|e| {
1018                ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
1019                    message: e.to_string().into(),
1020                    code: -1,
1021                }))
1022            })
1023        })
1024    }
1025
1026    /// Puts upsert a value into the specified table with the given key.
1027    ///
1028    /// # Panics
1029    /// Panics if the provider is in read-only mode.
1030    pub fn put<T: Table>(&self, key: T::Key, value: &T::Value) -> ProviderResult<()> {
1031        let encoded_key = key.encode();
1032        self.put_encoded::<T>(&encoded_key, value)
1033    }
1034
1035    /// Puts a value into the specified table using pre-encoded key.
1036    ///
1037    /// # Panics
1038    /// Panics if the provider is in read-only mode.
1039    pub fn put_encoded<T: Table>(
1040        &self,
1041        key: &<T::Key as Encode>::Encoded,
1042        value: &T::Value,
1043    ) -> ProviderResult<()> {
1044        self.execute_with_operation_metric(RocksDBOperation::Put, T::NAME, |this| {
1045            // for simplify the code, we need allocate buf here each time because `RocksDBProvider`
1046            // is thread safe if user want to avoid allocate buf each time, they can use
1047            // write_batch api
1048            let mut buf = Vec::new();
1049            let value_bytes = compress_to_buf_or_ref!(buf, value).unwrap_or(&buf);
1050
1051            this.0.put_cf(this.get_cf_handle::<T>()?, key, value_bytes).map_err(|e| {
1052                ProviderError::Database(DatabaseError::Write(Box::new(DatabaseWriteError {
1053                    info: DatabaseErrorInfo { message: e.to_string().into(), code: -1 },
1054                    operation: DatabaseWriteOperation::PutUpsert,
1055                    table_name: T::NAME,
1056                    key: key.as_ref().to_vec(),
1057                })))
1058            })
1059        })
1060    }
1061
1062    /// Deletes a value from the specified table.
1063    ///
1064    /// # Panics
1065    /// Panics if the provider is in read-only mode.
1066    pub fn delete<T: Table>(&self, key: T::Key) -> ProviderResult<()> {
1067        self.execute_with_operation_metric(RocksDBOperation::Delete, T::NAME, |this| {
1068            this.0.delete_cf(this.get_cf_handle::<T>()?, key.encode().as_ref()).map_err(|e| {
1069                ProviderError::Database(DatabaseError::Delete(DatabaseErrorInfo {
1070                    message: e.to_string().into(),
1071                    code: -1,
1072                }))
1073            })
1074        })
1075    }
1076
1077    /// Clears all entries from the specified table.
1078    ///
1079    /// Uses `delete_range_cf` from empty key to a max key (256 bytes of 0xFF).
1080    /// This end key must exceed the maximum encoded key size for any table.
1081    /// Current max is ~60 bytes (`StorageShardedKey` = 20 + 32 + 8).
1082    pub fn clear<T: Table>(&self) -> ProviderResult<()> {
1083        let cf = self.get_cf_handle::<T>()?;
1084
1085        self.0.delete_range_cf(cf, &[] as &[u8], &[0xFF; 256]).map_err(|e| {
1086            ProviderError::Database(DatabaseError::Delete(DatabaseErrorInfo {
1087                message: e.to_string().into(),
1088                code: -1,
1089            }))
1090        })?;
1091
1092        Ok(())
1093    }
1094
1095    /// Retrieves the first or last entry from a table based on the iterator mode.
1096    fn get_boundary<T: Table>(
1097        &self,
1098        mode: IteratorMode<'_>,
1099    ) -> ProviderResult<Option<(T::Key, T::Value)>> {
1100        self.execute_with_operation_metric(RocksDBOperation::Get, T::NAME, |this| {
1101            let cf = this.get_cf_handle::<T>()?;
1102            let mut iter = this.0.iterator_cf(cf, mode);
1103
1104            match iter.next() {
1105                Some(Ok((key_bytes, value_bytes))) => {
1106                    let key = <T::Key as reth_db_api::table::Decode>::decode(&key_bytes)
1107                        .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
1108                    let value = T::Value::decompress(&value_bytes)
1109                        .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
1110                    Ok(Some((key, value)))
1111                }
1112                Some(Err(e)) => {
1113                    Err(ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
1114                        message: e.to_string().into(),
1115                        code: -1,
1116                    })))
1117                }
1118                None => Ok(None),
1119            }
1120        })
1121    }
1122
1123    /// Gets the first (smallest key) entry from the specified table.
1124    #[inline]
1125    pub fn first<T: Table>(&self) -> ProviderResult<Option<(T::Key, T::Value)>> {
1126        self.get_boundary::<T>(IteratorMode::Start)
1127    }
1128
1129    /// Gets the last (largest key) entry from the specified table.
1130    #[inline]
1131    pub fn last<T: Table>(&self) -> ProviderResult<Option<(T::Key, T::Value)>> {
1132        self.get_boundary::<T>(IteratorMode::End)
1133    }
1134
1135    /// Creates an iterator over all entries in the specified table.
1136    ///
1137    /// Returns decoded `(Key, Value)` pairs in key order.
1138    pub fn iter<T: Table>(&self) -> ProviderResult<RocksDBIter<'_, T>> {
1139        let cf = self.get_cf_handle::<T>()?;
1140        let iter = self.0.iterator_cf(cf, IteratorMode::Start);
1141        Ok(RocksDBIter { inner: iter, _marker: std::marker::PhantomData })
1142    }
1143
1144    /// Creates an iterator starting from the given key (inclusive, seek forward).
1145    ///
1146    /// Returns decoded `(Key, Value)` pairs starting from the first key >= `key`.
1147    pub fn iter_from<T: Table>(&self, key: T::Key) -> ProviderResult<RocksDBIter<'_, T>> {
1148        let cf = self.get_cf_handle::<T>()?;
1149        let encoded_key = key.encode();
1150        let iter = self
1151            .0
1152            .iterator_cf(cf, IteratorMode::From(encoded_key.as_ref(), rocksdb::Direction::Forward));
1153        Ok(RocksDBIter { inner: iter, _marker: std::marker::PhantomData })
1154    }
1155
1156    /// Returns statistics for all column families in the database.
1157    ///
1158    /// Returns a vector of (`table_name`, `estimated_keys`, `estimated_size_bytes`) tuples.
1159    pub fn table_stats(&self) -> Vec<RocksDBTableStats> {
1160        self.0.table_stats()
1161    }
1162
1163    /// Returns the total size of WAL (Write-Ahead Log) files in bytes.
1164    ///
1165    /// This scans the `RocksDB` directory for `.log` files and sums their sizes.
1166    /// WAL files can be significant (e.g., 2.7GB observed) and are not included
1167    /// in `table_size`, `sst_size`, or `memtable_size` metrics.
1168    pub fn wal_size_bytes(&self) -> u64 {
1169        self.0.wal_size_bytes()
1170    }
1171
1172    /// Returns database-level statistics including per-table stats and WAL size.
1173    ///
1174    /// This combines [`Self::table_stats`] and [`Self::wal_size_bytes`] into a single struct.
1175    pub fn db_stats(&self) -> RocksDBStats {
1176        self.0.db_stats()
1177    }
1178
1179    /// Flushes pending writes for the specified tables to disk.
1180    ///
1181    /// This performs a flush of:
1182    /// 1. The column family memtables for the specified table names to SST files
1183    /// 2. The Write-Ahead Log (WAL) with sync
1184    ///
1185    /// After this call completes, all data for the specified tables is durably persisted to disk.
1186    ///
1187    /// # Panics
1188    /// Panics if the provider is in read-only mode.
1189    #[instrument(level = "debug", target = "providers::rocksdb", skip_all, fields(tables = ?tables))]
1190    pub fn flush(&self, tables: &[&'static str]) -> ProviderResult<()> {
1191        let db = self.0.db_rw();
1192
1193        for cf_name in tables {
1194            if let Some(cf) = db.cf_handle(cf_name) {
1195                db.flush_cf(&cf).map_err(|e| {
1196                    ProviderError::Database(DatabaseError::Write(Box::new(DatabaseWriteError {
1197                        info: DatabaseErrorInfo { message: e.to_string().into(), code: -1 },
1198                        operation: DatabaseWriteOperation::Flush,
1199                        table_name: cf_name,
1200                        key: Vec::new(),
1201                    })))
1202                })?;
1203            }
1204        }
1205
1206        db.flush_wal(true).map_err(|e| {
1207            ProviderError::Database(DatabaseError::Write(Box::new(DatabaseWriteError {
1208                info: DatabaseErrorInfo { message: e.to_string().into(), code: -1 },
1209                operation: DatabaseWriteOperation::Flush,
1210                table_name: "WAL",
1211                key: Vec::new(),
1212            })))
1213        })?;
1214
1215        Ok(())
1216    }
1217
1218    /// Flushes and compacts all tables in `RocksDB`.
1219    ///
1220    /// This:
1221    /// 1. Flushes all column family memtables to SST files
1222    /// 2. Flushes the Write-Ahead Log (WAL) with sync
1223    /// 3. Triggers manual compaction on all column families to reclaim disk space
1224    ///
1225    /// Use this after large delete operations (like pruning) to reclaim disk space.
1226    ///
1227    /// # Panics
1228    /// Panics if the provider is in read-only mode.
1229    #[instrument(level = "debug", target = "providers::rocksdb", skip_all)]
1230    pub fn flush_and_compact(&self) -> ProviderResult<()> {
1231        self.flush(ROCKSDB_TABLES)?;
1232
1233        let db = self.0.db_rw();
1234
1235        for cf_name in ROCKSDB_TABLES {
1236            if let Some(cf) = db.cf_handle(cf_name) {
1237                db.compact_range_cf(&cf, None::<&[u8]>, None::<&[u8]>);
1238            }
1239        }
1240
1241        Ok(())
1242    }
1243
1244    /// Creates a raw iterator over all entries in the specified table.
1245    ///
1246    /// Returns raw `(key_bytes, value_bytes)` pairs without decoding.
1247    pub fn raw_iter<T: Table>(&self) -> ProviderResult<RocksDBRawIter<'_>> {
1248        let cf = self.get_cf_handle::<T>()?;
1249        let iter = self.0.iterator_cf(cf, IteratorMode::Start);
1250        Ok(RocksDBRawIter { inner: iter })
1251    }
1252
1253    /// Creates a raw key iterator positioned at `key`.
1254    pub(crate) fn raw_key_iter_from<T: Table>(
1255        &self,
1256        key: T::Key,
1257    ) -> ProviderResult<RocksDBRawKeyIter<'_>> {
1258        let cf = self.get_cf_handle::<T>()?;
1259        let encoded_key = key.encode();
1260        let mut iter = self.0.raw_iterator_cf(cf);
1261        iter.seek(encoded_key.as_ref());
1262        Ok(RocksDBRawKeyIter { inner: iter })
1263    }
1264
1265    /// Returns all account history shards for the given address in ascending key order.
1266    ///
1267    /// This is used for unwind operations where we need to scan all shards for an address
1268    /// and potentially delete or truncate them.
1269    pub fn account_history_shards(
1270        &self,
1271        address: Address,
1272    ) -> ProviderResult<Vec<(ShardedKey<Address>, BlockNumberList)>> {
1273        // Get the column family handle for the AccountsHistory table.
1274        let cf = self.get_cf_handle::<tables::AccountsHistory>()?;
1275
1276        // Build a seek key starting at the first shard (highest_block_number = 0) for this address.
1277        // ShardedKey is (address, highest_block_number) so this positions us at the beginning.
1278        let start_key = ShardedKey::new(address, 0u64);
1279        let start_bytes = start_key.encode();
1280        // The sentinel shard is the last possible key for this address.
1281        let last_bytes = ShardedKey::new(address, u64::MAX).encode();
1282
1283        // Create a forward iterator over this address's shards only, so an address without live
1284        // shards does not scan the tombstones of the addresses after it.
1285        let iter =
1286            self.0.iterator_cf_inclusive_range(cf, start_bytes.as_ref(), last_bytes.as_ref());
1287
1288        let mut result = Vec::new();
1289        for item in iter {
1290            match item {
1291                Ok((key_bytes, value_bytes)) => {
1292                    // Decode the sharded key to check if we're still on the same address.
1293                    let key = ShardedKey::<Address>::decode(&key_bytes)
1294                        .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
1295
1296                    // Stop when we reach a different address (keys are sorted by address first).
1297                    if key.key != address {
1298                        break;
1299                    }
1300
1301                    // Decompress the block number list stored in this shard.
1302                    let value = BlockNumberList::decompress(&value_bytes)
1303                        .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
1304
1305                    result.push((key, value));
1306                }
1307                Err(e) => {
1308                    return Err(ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
1309                        message: e.to_string().into(),
1310                        code: -1,
1311                    })));
1312                }
1313            }
1314        }
1315
1316        Ok(result)
1317    }
1318
1319    /// Returns all storage history shards for the given `(address, storage_key)` pair.
1320    ///
1321    /// Iterates through all shards in ascending `highest_block_number` order until
1322    /// a different `(address, storage_key)` is encountered.
1323    pub fn storage_history_shards(
1324        &self,
1325        address: Address,
1326        storage_key: B256,
1327    ) -> ProviderResult<Vec<(StorageShardedKey, BlockNumberList)>> {
1328        let cf = self.get_cf_handle::<tables::StoragesHistory>()?;
1329
1330        let start_key = StorageShardedKey::new(address, storage_key, 0u64);
1331        let start_bytes = start_key.encode();
1332        let last_bytes = StorageShardedKey::new(address, storage_key, u64::MAX).encode();
1333
1334        // Bounded to this slot's shards, see `account_history_shards`.
1335        let iter =
1336            self.0.iterator_cf_inclusive_range(cf, start_bytes.as_ref(), last_bytes.as_ref());
1337
1338        let mut result = Vec::new();
1339        for item in iter {
1340            match item {
1341                Ok((key_bytes, value_bytes)) => {
1342                    let key = StorageShardedKey::decode(&key_bytes)
1343                        .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
1344
1345                    if key.address != address || key.sharded_key.key != storage_key {
1346                        break;
1347                    }
1348
1349                    let value = BlockNumberList::decompress(&value_bytes)
1350                        .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
1351
1352                    result.push((key, value));
1353                }
1354                Err(e) => {
1355                    return Err(ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
1356                        message: e.to_string().into(),
1357                        code: -1,
1358                    })));
1359                }
1360            }
1361        }
1362
1363        Ok(result)
1364    }
1365
1366    /// Unwinds account history indices for the given `(address, block_number)` pairs.
1367    ///
1368    /// Groups addresses by their minimum block number and calls the appropriate unwind
1369    /// operations. For each address, keeps only blocks less than the minimum block
1370    /// (i.e., removes the minimum block and all higher blocks).
1371    ///
1372    /// Returns a `WriteBatchWithTransaction` that can be committed later.
1373    #[instrument(level = "debug", target = "providers::rocksdb", skip_all)]
1374    pub fn unwind_account_history_indices(
1375        &self,
1376        last_indices: &[(Address, BlockNumber)],
1377    ) -> ProviderResult<WriteBatchWithTransaction<true>> {
1378        let mut address_min_block: AddressMap<BlockNumber> =
1379            AddressMap::with_capacity_and_hasher(last_indices.len(), Default::default());
1380        for &(address, block_number) in last_indices {
1381            address_min_block
1382                .entry(address)
1383                .and_modify(|min| *min = (*min).min(block_number))
1384                .or_insert(block_number);
1385        }
1386
1387        let mut batch = self.batch();
1388        for (address, min_block) in address_min_block {
1389            match min_block.checked_sub(1) {
1390                Some(keep_to) => batch.unwind_account_history_to(address, keep_to)?,
1391                None => batch.clear_account_history(address)?,
1392            }
1393        }
1394
1395        Ok(batch.into_inner())
1396    }
1397
1398    /// Unwinds storage history indices for the given `(address, storage_key, block_number)` tuples.
1399    ///
1400    /// Groups by `(address, storage_key)` and finds the minimum block number for each.
1401    /// For each key, keeps only blocks less than the minimum block
1402    /// (i.e., removes the minimum block and all higher blocks).
1403    ///
1404    /// Returns a `WriteBatchWithTransaction` that can be committed later.
1405    pub fn unwind_storage_history_indices(
1406        &self,
1407        storage_changesets: &[(Address, B256, BlockNumber)],
1408    ) -> ProviderResult<WriteBatchWithTransaction<true>> {
1409        let mut key_min_block: HashMap<(Address, B256), BlockNumber> =
1410            HashMap::with_capacity_and_hasher(storage_changesets.len(), Default::default());
1411        for &(address, storage_key, block_number) in storage_changesets {
1412            key_min_block
1413                .entry((address, storage_key))
1414                .and_modify(|min| *min = (*min).min(block_number))
1415                .or_insert(block_number);
1416        }
1417
1418        let mut batch = self.batch();
1419        for ((address, storage_key), min_block) in key_min_block {
1420            match min_block.checked_sub(1) {
1421                Some(keep_to) => batch.unwind_storage_history_to(address, storage_key, keep_to)?,
1422                None => batch.clear_storage_history(address, storage_key)?,
1423            }
1424        }
1425
1426        Ok(batch.into_inner())
1427    }
1428
1429    /// Writes a batch of operations atomically.
1430    #[instrument(level = "debug", target = "providers::rocksdb", skip_all)]
1431    pub fn write_batch<F>(&self, f: F) -> ProviderResult<()>
1432    where
1433        F: FnOnce(&mut RocksDBBatch<'_>) -> ProviderResult<()>,
1434    {
1435        self.execute_with_operation_metric(RocksDBOperation::BatchWrite, "Batch", |this| {
1436            let mut batch_handle = this.batch();
1437            f(&mut batch_handle)?;
1438            batch_handle.commit()
1439        })
1440    }
1441
1442    /// Commits a raw `WriteBatchWithTransaction` to `RocksDB`.
1443    ///
1444    /// This is used when the batch was extracted via [`RocksDBBatch::into_inner`]
1445    /// and needs to be committed at a later point (e.g., at provider commit time).
1446    ///
1447    /// # Panics
1448    /// Panics if the provider is in read-only mode.
1449    #[instrument(level = "debug", target = "providers::rocksdb", skip_all, fields(batch_len = batch.len(), batch_size = batch.size_in_bytes()))]
1450    pub fn commit_batch(&self, batch: WriteBatchWithTransaction<true>) -> ProviderResult<()> {
1451        self.0.db_rw().write_opt(batch, &synced_write_options()).map_err(|e| {
1452            ProviderError::Database(DatabaseError::Commit(DatabaseErrorInfo {
1453                message: e.to_string().into(),
1454                code: -1,
1455            }))
1456        })
1457    }
1458
1459    /// Writes all `RocksDB` data for multiple blocks in parallel.
1460    ///
1461    /// This handles transaction hash numbers, account history, and storage history based on
1462    /// the provided storage settings. Each operation runs in parallel with its own batch,
1463    /// pushing to `ctx.pending_batches` for later commit.
1464    #[instrument(level = "debug", target = "providers::rocksdb", skip_all, fields(num_blocks = blocks.len(), first_block = ctx.first_block_number))]
1465    pub(crate) fn write_blocks_data<N: reth_node_types::NodePrimitives>(
1466        &self,
1467        blocks: &[ExecutedBlock<N>],
1468        tx_nums: &[TxNumber],
1469        ctx: RocksDBWriteCtx,
1470        runtime: &reth_tasks::Runtime,
1471    ) -> ProviderResult<()> {
1472        if !ctx.storage_settings.storage_v2 {
1473            return Ok(());
1474        }
1475
1476        let mut r_tx_hash = None;
1477        let mut r_account_history = None;
1478        let mut r_storage_history = None;
1479
1480        let write_tx_hash =
1481            ctx.storage_settings.storage_v2 && ctx.prune_tx_lookup.is_none_or(|m| !m.is_full());
1482        let write_account_history = ctx.storage_settings.storage_v2;
1483        let write_storage_history = ctx.storage_settings.storage_v2;
1484
1485        // Propagate tracing context into rayon-spawned threads so that RocksDB
1486        // write spans appear as children of write_blocks_data in traces.
1487        let span = tracing::Span::current();
1488        runtime.storage_pool().in_place_scope(|s| {
1489            if write_tx_hash {
1490                s.spawn(|_| {
1491                    let _guard = span.enter();
1492                    r_tx_hash = Some(self.write_tx_hash_numbers(blocks, tx_nums, &ctx));
1493                });
1494            }
1495
1496            if write_account_history {
1497                s.spawn(|_| {
1498                    let _guard = span.enter();
1499                    r_account_history = Some(self.write_account_history(blocks, &ctx));
1500                });
1501            }
1502
1503            if write_storage_history {
1504                s.spawn(|_| {
1505                    let _guard = span.enter();
1506                    r_storage_history = Some(self.write_storage_history(blocks, &ctx));
1507                });
1508            }
1509        });
1510
1511        if write_tx_hash {
1512            r_tx_hash.ok_or_else(|| {
1513                ProviderError::Database(DatabaseError::Other(
1514                    "rocksdb tx-hash write thread panicked".into(),
1515                ))
1516            })??;
1517        }
1518        if write_account_history {
1519            r_account_history.ok_or_else(|| {
1520                ProviderError::Database(DatabaseError::Other(
1521                    "rocksdb account-history write thread panicked".into(),
1522                ))
1523            })??;
1524        }
1525        if write_storage_history {
1526            r_storage_history.ok_or_else(|| {
1527                ProviderError::Database(DatabaseError::Other(
1528                    "rocksdb storage-history write thread panicked".into(),
1529                ))
1530            })??;
1531        }
1532
1533        Ok(())
1534    }
1535
1536    /// Writes transaction hash to number mappings for the given blocks.
1537    #[instrument(level = "debug", target = "providers::rocksdb", skip_all)]
1538    fn write_tx_hash_numbers<N: reth_node_types::NodePrimitives>(
1539        &self,
1540        blocks: &[ExecutedBlock<N>],
1541        tx_nums: &[TxNumber],
1542        ctx: &RocksDBWriteCtx,
1543    ) -> ProviderResult<()> {
1544        let mut batch = self.batch();
1545        for (block, &first_tx_num) in blocks.iter().zip(tx_nums) {
1546            let body = block.recovered_block().body();
1547            for (tx_num, transaction) in (first_tx_num..).zip(body.transactions_iter()) {
1548                batch.put::<tables::TransactionHashNumbers>(*transaction.tx_hash(), &tx_num)?;
1549            }
1550        }
1551        ctx.pending_batches.lock().push(batch.into_inner());
1552        Ok(())
1553    }
1554
1555    /// Writes account history indices for the given blocks.
1556    ///
1557    /// Derives history indices from reverts (same source as changesets) to ensure consistency.
1558    #[instrument(level = "debug", target = "providers::rocksdb", skip_all)]
1559    fn write_account_history<N: reth_node_types::NodePrimitives>(
1560        &self,
1561        blocks: &[ExecutedBlock<N>],
1562        ctx: &RocksDBWriteCtx,
1563    ) -> ProviderResult<()> {
1564        let mut batch = self.batch();
1565        let mut account_history: BTreeMap<Address, Vec<u64>> = BTreeMap::new();
1566
1567        for (block_idx, block) in blocks.iter().enumerate() {
1568            let block_number = ctx.first_block_number + block_idx as u64;
1569            let reverts = block.execution_outcome().state.reverts.to_plain_state_reverts();
1570
1571            // Iterate through account reverts - these are exactly the accounts that have
1572            // changesets written, ensuring history indices match changeset entries.
1573            for account_block_reverts in reverts.accounts {
1574                for (address, _) in account_block_reverts {
1575                    account_history.entry(address).or_default().push(block_number);
1576                }
1577            }
1578        }
1579
1580        // Write account history using proper shard append logic
1581        for (address, indices) in account_history {
1582            batch.append_account_history_shard(address, indices)?;
1583        }
1584        ctx.pending_batches.lock().push(batch.into_inner());
1585        Ok(())
1586    }
1587
1588    /// Writes storage history indices for the given blocks.
1589    ///
1590    /// Derives history indices from reverts (same source as changesets) to ensure consistency.
1591    #[instrument(level = "debug", target = "providers::rocksdb", skip_all)]
1592    fn write_storage_history<N: reth_node_types::NodePrimitives>(
1593        &self,
1594        blocks: &[ExecutedBlock<N>],
1595        ctx: &RocksDBWriteCtx,
1596    ) -> ProviderResult<()> {
1597        let mut storage_history: BTreeMap<(Address, B256), Vec<u64>> = BTreeMap::new();
1598
1599        for (block_idx, block) in blocks.iter().enumerate() {
1600            let block_number = ctx.first_block_number + block_idx as u64;
1601            let reverts = block.execution_outcome().state.reverts.to_plain_state_reverts();
1602
1603            // Iterate through storage reverts - these are exactly the slots that have
1604            // changesets written, ensuring history indices match changeset entries.
1605            for storage_block_reverts in reverts.storage {
1606                for revert in storage_block_reverts {
1607                    for (slot, _) in revert.storage_revert {
1608                        let plain_key = B256::from(slot);
1609                        storage_history
1610                            .entry((revert.address, plain_key))
1611                            .or_default()
1612                            .push(block_number);
1613                    }
1614                }
1615            }
1616        }
1617
1618        let shard_puts = storage_history
1619            .into_par_iter()
1620            .map(|((address, slot), indices)| {
1621                self.storage_history_shards_to_put(address, slot, indices)
1622            })
1623            .collect::<ProviderResult<Vec<_>>>()?;
1624
1625        let mut batch = self.batch();
1626        for shards in shard_puts {
1627            for (key, shard) in shards {
1628                batch.put::<tables::StoragesHistory>(key, &shard)?;
1629            }
1630        }
1631        ctx.pending_batches.lock().push(batch.into_inner());
1632        Ok(())
1633    }
1634
1635    /// Prepares storage history shard writes by reading the current last shard and appending
1636    /// indices.
1637    fn storage_history_shards_to_put(
1638        &self,
1639        address: Address,
1640        storage_key: B256,
1641        indices: Vec<u64>,
1642    ) -> ProviderResult<Vec<(StorageShardedKey, BlockNumberList)>> {
1643        if indices.is_empty() {
1644            return Ok(Vec::new());
1645        }
1646
1647        debug_assert!(
1648            indices.windows(2).all(|w| w[0] < w[1]),
1649            "indices must be strictly increasing: {:?}",
1650            indices
1651        );
1652
1653        let last_key = StorageShardedKey::last(address, storage_key);
1654        let last_shard_opt = self.get::<tables::StoragesHistory>(last_key.clone())?;
1655        let mut last_shard = last_shard_opt.unwrap_or_else(BlockNumberList::empty);
1656
1657        last_shard.append(indices).map_err(ProviderError::other)?;
1658
1659        if last_shard.len() <= NUM_OF_INDICES_IN_SHARD as u64 {
1660            return Ok(vec![(last_key, last_shard)]);
1661        }
1662
1663        let chunks = last_shard.iter().chunks(NUM_OF_INDICES_IN_SHARD);
1664        let mut chunks_peekable = chunks.into_iter().peekable();
1665        let mut shards = Vec::new();
1666
1667        while let Some(chunk) = chunks_peekable.next() {
1668            let shard = BlockNumberList::new_pre_sorted(chunk);
1669            let highest_block_number = if chunks_peekable.peek().is_some() {
1670                shard.iter().next_back().expect("`chunks` does not return empty list")
1671            } else {
1672                u64::MAX
1673            };
1674
1675            shards
1676                .push((StorageShardedKey::new(address, storage_key, highest_block_number), shard));
1677        }
1678
1679        Ok(shards)
1680    }
1681}
1682
1683/// A point-in-time read snapshot of the `RocksDB` database.
1684///
1685/// All reads through this snapshot see a consistent view of the database at the point
1686/// the snapshot was created, regardless of concurrent writes. This is the primary reader
1687/// used by [`EitherReader::RocksDB`](crate::either_writer::EitherReader) for history lookups.
1688///
1689/// Lighter weight than [`RocksTx`] — no transaction overhead, no write support.
1690pub struct RocksReadSnapshot<'db> {
1691    /// Raw iterator reused across account history lookups.
1692    ///
1693    /// Declared before `inner` so it is dropped before the snapshot it reads from.
1694    accounts_history_iter: Mutex<Option<RocksDBRawIterEnum<'db>>>,
1695    /// Raw iterator reused across storage history lookups.
1696    ///
1697    /// Declared before `inner` so it is dropped before the snapshot it reads from.
1698    storages_history_iter: Mutex<Option<RocksDBRawIterEnum<'db>>>,
1699    inner: RocksReadSnapshotInner<'db>,
1700    provider: &'db RocksDBProviderInner,
1701}
1702
1703/// Inner enum to hold the snapshot for either read-write or secondary mode.
1704enum RocksReadSnapshotInner<'db> {
1705    /// Snapshot from read-write `OptimisticTransactionDB`.
1706    ReadWrite(SnapshotWithThreadMode<'db, OptimisticTransactionDB>),
1707    /// Direct reads from a secondary `DB` instance (no snapshot).
1708    Secondary(&'db DB),
1709}
1710
1711impl fmt::Debug for RocksReadSnapshot<'_> {
1712    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1713        f.debug_struct("RocksReadSnapshot")
1714            .field("provider", &self.provider)
1715            .finish_non_exhaustive()
1716    }
1717}
1718
1719impl<'db> RocksReadSnapshot<'db> {
1720    /// Gets the column family handle for a table.
1721    fn cf_handle<T: Table>(&self) -> Result<&'db rocksdb::ColumnFamily, DatabaseError> {
1722        self.provider.cf_handle::<T>()
1723    }
1724
1725    /// Creates a raw iterator over `cf` that observes this snapshot.
1726    ///
1727    /// The iterator is created from the database handle rather than from the snapshot value, so
1728    /// its lifetime is tied to the database and it can be cached in `self`. The snapshot is
1729    /// attached through [`ReadOptions`], giving the same point-in-time view as reading through the
1730    /// snapshot directly.
1731    fn new_raw_iterator_cf(&self, cf: &rocksdb::ColumnFamily) -> RocksDBRawIterEnum<'db> {
1732        match &self.inner {
1733            RocksReadSnapshotInner::ReadWrite(snap) => {
1734                let mut readopts = ReadOptions::default();
1735                readopts.set_snapshot(snap);
1736                RocksDBRawIterEnum::ReadWrite(
1737                    self.provider.db_rw().raw_iterator_cf_opt(cf, readopts),
1738                )
1739            }
1740            RocksReadSnapshotInner::Secondary(db) => {
1741                RocksDBRawIterEnum::ReadOnly((*db).raw_iterator_cf(cf))
1742            }
1743        }
1744    }
1745
1746    /// Gets a value from the specified table.
1747    pub fn get<T: Table>(&self, key: T::Key) -> ProviderResult<Option<T::Value>> {
1748        let encoded_key = key.encode();
1749        let cf = self.cf_handle::<T>()?;
1750        let result = match &self.inner {
1751            RocksReadSnapshotInner::ReadWrite(snap) => snap.get_cf(cf, encoded_key.as_ref()),
1752            RocksReadSnapshotInner::Secondary(db) => db.get_cf(cf, encoded_key.as_ref()),
1753        }
1754        .map_err(|e| {
1755            ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
1756                message: e.to_string().into(),
1757                code: -1,
1758            }))
1759        })?;
1760
1761        Ok(result.and_then(|value| T::Value::decompress(&value).ok()))
1762    }
1763
1764    /// Lookup account history and return [`HistoryInfo`] directly.
1765    ///
1766    /// `visible_tip` is the highest block considered visible from the companion MDBX snapshot.
1767    /// History entries above it are ignored even if they already exist in `RocksDB`.
1768    pub fn account_history_info(
1769        &self,
1770        address: Address,
1771        block_number: BlockNumber,
1772        lowest_available_block_number: Option<BlockNumber>,
1773        visible_tip: BlockNumber,
1774    ) -> ProviderResult<HistoryInfo> {
1775        let key = ShardedKey::new(address, block_number);
1776        self.history_info::<tables::AccountsHistory>(
1777            &self.accounts_history_iter,
1778            key.encode().as_ref(),
1779            block_number,
1780            lowest_available_block_number,
1781            visible_tip,
1782            |key_bytes| Ok(<ShardedKey<Address> as Decode>::decode(key_bytes)?.key == address),
1783            |prev_bytes| {
1784                <ShardedKey<Address> as Decode>::decode(prev_bytes)
1785                    .map(|k| k.key == address)
1786                    .unwrap_or(false)
1787            },
1788        )
1789    }
1790
1791    /// Lookup storage history and return [`HistoryInfo`] directly.
1792    ///
1793    /// `visible_tip` is the highest block considered visible from the companion MDBX snapshot.
1794    /// History entries above it are ignored even if they already exist in `RocksDB`.
1795    pub fn storage_history_info(
1796        &self,
1797        address: Address,
1798        storage_key: B256,
1799        block_number: BlockNumber,
1800        lowest_available_block_number: Option<BlockNumber>,
1801        visible_tip: BlockNumber,
1802    ) -> ProviderResult<HistoryInfo> {
1803        let key = StorageShardedKey::new(address, storage_key, block_number);
1804        self.history_info::<tables::StoragesHistory>(
1805            &self.storages_history_iter,
1806            key.encode().as_ref(),
1807            block_number,
1808            lowest_available_block_number,
1809            visible_tip,
1810            |key_bytes| {
1811                let k = <StorageShardedKey as Decode>::decode(key_bytes)?;
1812                Ok(k.address == address && k.sharded_key.key == storage_key)
1813            },
1814            |prev_bytes| {
1815                <StorageShardedKey as Decode>::decode(prev_bytes)
1816                    .map(|k| k.address == address && k.sharded_key.key == storage_key)
1817                    .unwrap_or(false)
1818            },
1819        )
1820    }
1821
1822    /// Generic history lookup using the snapshot's raw iterator.
1823    ///
1824    /// The result is derived from the history that is visible through `visible_tip`, not from the
1825    /// full contents of `RocksDB`. This lets a reader combine an older MDBX snapshot with a newer
1826    /// Rocks snapshot without routing through history entries that MDBX cannot see yet.
1827    ///
1828    /// `iter_cache` holds the raw iterator for `T`'s column family. Seeking an existing iterator
1829    /// is much cheaper than constructing one, so the iterator is created on the first lookup and
1830    /// reused by every later lookup through this snapshot. A lookup that finds the cache held by
1831    /// another thread uses a private iterator instead of waiting.
1832    #[expect(clippy::too_many_arguments)]
1833    fn history_info<T>(
1834        &self,
1835        iter_cache: &Mutex<Option<RocksDBRawIterEnum<'db>>>,
1836        encoded_key: &[u8],
1837        block_number: BlockNumber,
1838        lowest_available_block_number: Option<BlockNumber>,
1839        visible_tip: BlockNumber,
1840        key_matches: impl FnOnce(&[u8]) -> Result<bool, reth_db_api::DatabaseError>,
1841        prev_key_matches: impl Fn(&[u8]) -> bool,
1842    ) -> ProviderResult<HistoryInfo>
1843    where
1844        T: Table<Value = BlockNumberList>,
1845    {
1846        let is_maybe_pruned = lowest_available_block_number.is_some();
1847        let fallback = || {
1848            Ok(if is_maybe_pruned {
1849                HistoryInfo::MaybeInPlainState
1850            } else {
1851                HistoryInfo::NotYetWritten
1852            })
1853        };
1854
1855        let cf = self.cf_handle::<T>()?;
1856        // A lookup on another thread may be holding the cached iterator; a private iterator costs
1857        // what every lookup used to cost, whereas waiting would serialize the two lookups.
1858        let mut guard = iter_cache.try_lock();
1859        let mut private_iter;
1860        let iter = match guard.as_mut() {
1861            Some(cached) => cached.get_or_insert_with(|| self.new_raw_iterator_cf(cf)),
1862            None => {
1863                private_iter = self.new_raw_iterator_cf(cf);
1864                &mut private_iter
1865            }
1866        };
1867
1868        iter.seek(encoded_key);
1869        iter.status().map_err(|e| {
1870            ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
1871                message: e.to_string().into(),
1872                code: -1,
1873            }))
1874        })?;
1875
1876        if !iter.valid() {
1877            return fallback();
1878        }
1879
1880        let Some(key_bytes) = iter.key() else {
1881            return fallback();
1882        };
1883        if !key_matches(key_bytes)? {
1884            return fallback();
1885        }
1886
1887        let Some(value_bytes) = iter.value() else {
1888            return fallback();
1889        };
1890        let chunk = BlockNumberList::decompress(value_bytes)?;
1891
1892        let (rank, found_block) = compute_history_rank(&chunk, block_number);
1893        // Ignore later Rocks history that is ahead of the companion MDBX snapshot.
1894        let found_block = found_block.filter(|block| *block <= visible_tip);
1895
1896        let is_before_first_write = if needs_prev_shard_check(rank, found_block, block_number) {
1897            iter.prev();
1898            iter.status().map_err(|e| {
1899                ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
1900                    message: e.to_string().into(),
1901                    code: -1,
1902                }))
1903            })?;
1904            let has_prev = iter.valid() && iter.key().is_some_and(&prev_key_matches);
1905
1906            // If the current shard only contains history above `visible_tip`, there is no usable
1907            // later change. Without a previous shard for the same key, fall back to the existing
1908            // not-written / maybe-pruned result instead of routing into plain state.
1909            if found_block.is_none() && !has_prev {
1910                return fallback()
1911            }
1912
1913            !has_prev
1914        } else {
1915            false
1916        };
1917
1918        Ok(HistoryInfo::from_lookup(
1919            found_block,
1920            is_before_first_write,
1921            lowest_available_block_number,
1922        ))
1923    }
1924}
1925
1926/// A [`RocksReadSnapshot`] that owns the [`RocksDBProvider`] handle it reads through.
1927///
1928/// [`RocksDBProvider::snapshot`] borrows the provider, so a reader that wants to keep a single
1929/// snapshot alive has to keep the provider handle next to it. This type does that, which lets the
1930/// snapshot cache its history iterators across lookups.
1931pub struct OwnedRocksReadSnapshot {
1932    /// Borrows the allocation retained by `provider`. Declared first so the snapshot and its
1933    /// iterators are released before the owning database handle. Boxing keeps its internal
1934    /// references out of the movable owner, including when the owner is passed by value.
1935    snapshot: Box<RocksReadSnapshot<'static>>,
1936    provider: RocksDBProvider,
1937}
1938
1939impl fmt::Debug for OwnedRocksReadSnapshot {
1940    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1941        f.debug_struct("OwnedRocksReadSnapshot").field("provider", &self.provider).finish()
1942    }
1943}
1944
1945impl OwnedRocksReadSnapshot {
1946    fn new(provider: &RocksDBProvider) -> Self {
1947        let provider = provider.clone();
1948        let snapshot = provider.snapshot();
1949        // SAFETY: Every reference in `snapshot` points into the Arc allocation retained by
1950        // `provider`, not into the movable provider handle. The handle is private and never
1951        // replaced, and `snapshot` is dropped before it. `as_snapshot` restricts access to the
1952        // lifetime of a borrow of this owner.
1953        let snapshot = unsafe {
1954            std::mem::transmute::<RocksReadSnapshot<'_>, RocksReadSnapshot<'static>>(snapshot)
1955        };
1956        Self { snapshot: Box::new(snapshot), provider }
1957    }
1958
1959    /// Returns the borrowed snapshot.
1960    pub fn as_snapshot(&self) -> &RocksReadSnapshot<'_> {
1961        // SAFETY: shortening the snapshot's lifetime to this borrow of `self` is sound; the owned
1962        // provider handle keeps the database open for at least that long.
1963        unsafe {
1964            std::mem::transmute::<&RocksReadSnapshot<'static>, &RocksReadSnapshot<'_>>(
1965                &self.snapshot,
1966            )
1967        }
1968    }
1969}
1970
1971/// Outcome of pruning a history shard in `RocksDB`.
1972#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1973pub enum PruneShardOutcome {
1974    /// Shard was deleted entirely.
1975    Deleted,
1976    /// Shard was updated with filtered block numbers.
1977    Updated,
1978    /// Shard was unchanged (no blocks <= `to_block`).
1979    Unchanged,
1980}
1981
1982/// Tracks pruning outcomes for batch operations.
1983#[derive(Debug, Default, Clone, Copy)]
1984pub struct PrunedIndices {
1985    /// Number of shards completely deleted.
1986    pub deleted: usize,
1987    /// Number of shards that were updated (filtered but still have entries).
1988    pub updated: usize,
1989    /// Number of shards that were unchanged.
1990    pub unchanged: usize,
1991}
1992
1993/// Handle for building a batch of operations atomically.
1994///
1995/// Uses `WriteBatchWithTransaction` for atomic writes without full transaction overhead.
1996/// Unlike [`RocksTx`], this does NOT support read-your-writes. Use for write-only flows
1997/// where you don't need to read back uncommitted data within the same operation
1998/// (e.g., history index writes).
1999///
2000/// When `auto_commit_threshold` is set, the batch will automatically commit and reset
2001/// when the batch size exceeds the threshold. This prevents OOM during large bulk writes.
2002#[must_use = "batch must be committed"]
2003pub struct RocksDBBatch<'a> {
2004    provider: &'a RocksDBProvider,
2005    inner: WriteBatchWithTransaction<true>,
2006    buf: Vec<u8>,
2007    /// If set, batch auto-commits when size exceeds this threshold (in bytes).
2008    auto_commit_threshold: Option<usize>,
2009}
2010
2011impl fmt::Debug for RocksDBBatch<'_> {
2012    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2013        f.debug_struct("RocksDBBatch")
2014            .field("provider", &self.provider)
2015            .field("batch", &"<WriteBatchWithTransaction>")
2016            // Number of operations in this batch
2017            .field("length", &self.inner.len())
2018            // Total serialized size (encoded key + compressed value + metadata) of this batch
2019            // in bytes
2020            .field("size_in_bytes", &self.inner.size_in_bytes())
2021            .finish()
2022    }
2023}
2024
2025impl<'a> RocksDBBatch<'a> {
2026    /// Puts a value into the batch.
2027    ///
2028    /// If auto-commit is enabled and the batch exceeds the threshold, commits and resets.
2029    pub fn put<T: Table>(&mut self, key: T::Key, value: &T::Value) -> ProviderResult<()> {
2030        let encoded_key = key.encode();
2031        self.put_encoded::<T>(&encoded_key, value)
2032    }
2033
2034    /// Puts a value into the batch using pre-encoded key.
2035    ///
2036    /// If auto-commit is enabled and the batch exceeds the threshold, commits and resets.
2037    pub fn put_encoded<T: Table>(
2038        &mut self,
2039        key: &<T::Key as Encode>::Encoded,
2040        value: &T::Value,
2041    ) -> ProviderResult<()> {
2042        let value_bytes = compress_to_buf_or_ref!(self.buf, value).unwrap_or(&self.buf);
2043        self.inner.put_cf(self.provider.get_cf_handle::<T>()?, key, value_bytes);
2044        self.maybe_auto_commit()?;
2045        Ok(())
2046    }
2047
2048    /// Deletes a value from the batch.
2049    ///
2050    /// If auto-commit is enabled and the batch exceeds the threshold, commits and resets.
2051    pub fn delete<T: Table>(&mut self, key: T::Key) -> ProviderResult<()> {
2052        self.inner.delete_cf(self.provider.get_cf_handle::<T>()?, key.encode().as_ref());
2053        self.maybe_auto_commit()?;
2054        Ok(())
2055    }
2056
2057    /// Commits and resets the batch if it exceeds the auto-commit threshold.
2058    ///
2059    /// This is called after each `put` or `delete` operation to prevent unbounded memory growth.
2060    /// Returns immediately if auto-commit is disabled or threshold not reached.
2061    fn maybe_auto_commit(&mut self) -> ProviderResult<()> {
2062        if let Some(threshold) = self.auto_commit_threshold &&
2063            self.inner.size_in_bytes() >= threshold
2064        {
2065            tracing::debug!(
2066                target: "providers::rocksdb",
2067                batch_size = self.inner.size_in_bytes(),
2068                threshold,
2069                "Auto-committing RocksDB batch"
2070            );
2071            let old_batch = std::mem::take(&mut self.inner);
2072            self.provider.0.db_rw().write_opt(old_batch, &synced_write_options()).map_err(|e| {
2073                ProviderError::Database(DatabaseError::Commit(DatabaseErrorInfo {
2074                    message: e.to_string().into(),
2075                    code: -1,
2076                }))
2077            })?;
2078        }
2079        Ok(())
2080    }
2081
2082    /// Commits the batch to the database.
2083    ///
2084    /// This consumes the batch and writes all operations atomically to `RocksDB`.
2085    ///
2086    /// # Panics
2087    /// Panics if the provider is in read-only mode.
2088    #[instrument(level = "debug", target = "providers::rocksdb", skip_all, fields(batch_len = self.inner.len(), batch_size = self.inner.size_in_bytes()))]
2089    pub fn commit(self) -> ProviderResult<()> {
2090        self.provider.0.db_rw().write_opt(self.inner, &synced_write_options()).map_err(|e| {
2091            ProviderError::Database(DatabaseError::Commit(DatabaseErrorInfo {
2092                message: e.to_string().into(),
2093                code: -1,
2094            }))
2095        })
2096    }
2097
2098    /// Returns the number of write operations (puts + deletes) queued in this batch.
2099    pub fn len(&self) -> usize {
2100        self.inner.len()
2101    }
2102
2103    /// Returns `true` if the batch contains no operations.
2104    pub fn is_empty(&self) -> bool {
2105        self.inner.is_empty()
2106    }
2107
2108    /// Returns the size of the batch in bytes.
2109    pub fn size_in_bytes(&self) -> usize {
2110        self.inner.size_in_bytes()
2111    }
2112
2113    /// Returns a reference to the underlying `RocksDB` provider.
2114    pub const fn provider(&self) -> &RocksDBProvider {
2115        self.provider
2116    }
2117
2118    /// Consumes the batch and returns the underlying `WriteBatchWithTransaction`.
2119    ///
2120    /// This is used to defer commits to the provider level.
2121    pub fn into_inner(self) -> WriteBatchWithTransaction<true> {
2122        self.inner
2123    }
2124
2125    /// Gets a value from the database.
2126    ///
2127    /// **Important constraint:** This reads only committed state, not pending writes in this
2128    /// batch or other pending batches in `pending_rocksdb_batches`.
2129    pub fn get<T: Table>(&self, key: T::Key) -> ProviderResult<Option<T::Value>> {
2130        self.provider.get::<T>(key)
2131    }
2132
2133    /// Appends indices to an account history shard with proper shard management.
2134    ///
2135    /// Loads the existing shard (if any), appends new indices, and rechunks into
2136    /// multiple shards if needed (respecting `NUM_OF_INDICES_IN_SHARD` limit).
2137    ///
2138    /// # Requirements
2139    ///
2140    /// - The `indices` MUST be strictly increasing and contain no duplicates.
2141    /// - This method MUST only be called once per address per batch. The batch reads existing
2142    ///   shards from committed DB state, not from pending writes. Calling twice for the same
2143    ///   address will cause the second call to overwrite the first.
2144    pub fn append_account_history_shard(
2145        &mut self,
2146        address: Address,
2147        indices: impl IntoIterator<Item = u64>,
2148    ) -> ProviderResult<()> {
2149        let indices: Vec<u64> = indices.into_iter().collect();
2150
2151        if indices.is_empty() {
2152            return Ok(());
2153        }
2154
2155        debug_assert!(
2156            indices.windows(2).all(|w| w[0] < w[1]),
2157            "indices must be strictly increasing: {:?}",
2158            indices
2159        );
2160
2161        let last_key = ShardedKey::new(address, u64::MAX);
2162        let last_shard_opt = self.provider.get::<tables::AccountsHistory>(last_key.clone())?;
2163        let mut last_shard = last_shard_opt.unwrap_or_else(BlockNumberList::empty);
2164
2165        last_shard.append(indices).map_err(ProviderError::other)?;
2166
2167        // Fast path: all indices fit in one shard
2168        if last_shard.len() <= NUM_OF_INDICES_IN_SHARD as u64 {
2169            self.put::<tables::AccountsHistory>(last_key, &last_shard)?;
2170            return Ok(());
2171        }
2172
2173        // Slow path: rechunk into multiple shards
2174        let chunks = last_shard.iter().chunks(NUM_OF_INDICES_IN_SHARD);
2175        let mut chunks_peekable = chunks.into_iter().peekable();
2176
2177        while let Some(chunk) = chunks_peekable.next() {
2178            let shard = BlockNumberList::new_pre_sorted(chunk);
2179            let highest_block_number = if chunks_peekable.peek().is_some() {
2180                shard.iter().next_back().expect("`chunks` does not return empty list")
2181            } else {
2182                u64::MAX
2183            };
2184
2185            self.put::<tables::AccountsHistory>(
2186                ShardedKey::new(address, highest_block_number),
2187                &shard,
2188            )?;
2189        }
2190
2191        Ok(())
2192    }
2193
2194    /// Appends indices to a storage history shard with proper shard management.
2195    ///
2196    /// Loads the existing shard (if any), appends new indices, and rechunks into
2197    /// multiple shards if needed (respecting `NUM_OF_INDICES_IN_SHARD` limit).
2198    ///
2199    /// # Requirements
2200    ///
2201    /// - The `indices` MUST be strictly increasing and contain no duplicates.
2202    /// - This method MUST only be called once per (address, `storage_key`) pair per batch. The
2203    ///   batch reads existing shards from committed DB state, not from pending writes. Calling
2204    ///   twice for the same key will cause the second call to overwrite the first.
2205    pub fn append_storage_history_shard(
2206        &mut self,
2207        address: Address,
2208        storage_key: B256,
2209        indices: impl IntoIterator<Item = u64>,
2210    ) -> ProviderResult<()> {
2211        let indices: Vec<u64> = indices.into_iter().collect();
2212
2213        for (key, shard) in
2214            self.provider.storage_history_shards_to_put(address, storage_key, indices)?
2215        {
2216            self.put::<tables::StoragesHistory>(key, &shard)?;
2217        }
2218
2219        Ok(())
2220    }
2221
2222    /// Unwinds account history for the given address, keeping only blocks <= `keep_to`.
2223    ///
2224    /// Mirrors MDBX `unwind_history_shards` behavior:
2225    /// - Deletes shards entirely above `keep_to`
2226    /// - Truncates boundary shards and re-keys to `u64::MAX` sentinel
2227    /// - Preserves shards entirely below `keep_to`
2228    pub fn unwind_account_history_to(
2229        &mut self,
2230        address: Address,
2231        keep_to: BlockNumber,
2232    ) -> ProviderResult<()> {
2233        if self.unwind_last_history_shard::<tables::AccountsHistory>(
2234            |highest| ShardedKey::new(address, highest),
2235            keep_to,
2236        )? {
2237            return Ok(());
2238        }
2239        let shards = self.provider.account_history_shards(address)?;
2240        if shards.is_empty() {
2241            return Ok(());
2242        }
2243
2244        // Find the first shard that might contain blocks > keep_to.
2245        // A shard is affected if it's the sentinel (u64::MAX) or its highest_block_number > keep_to
2246        let boundary_idx = shards.iter().position(|(key, _)| {
2247            key.highest_block_number == u64::MAX || key.highest_block_number > keep_to
2248        });
2249
2250        // Repair path: no shards affected means all blocks <= keep_to, just ensure sentinel exists
2251        let Some(boundary_idx) = boundary_idx else {
2252            let (last_key, last_value) = shards.last().expect("shards is non-empty");
2253            if last_key.highest_block_number != u64::MAX {
2254                self.delete::<tables::AccountsHistory>(last_key.clone())?;
2255                self.put::<tables::AccountsHistory>(
2256                    ShardedKey::new(address, u64::MAX),
2257                    last_value,
2258                )?;
2259            }
2260            return Ok(());
2261        };
2262
2263        // Delete all shards strictly after the boundary (they are entirely > keep_to)
2264        for (key, _) in shards.iter().skip(boundary_idx + 1) {
2265            self.delete::<tables::AccountsHistory>(key.clone())?;
2266        }
2267
2268        // Process the boundary shard: filter out blocks > keep_to
2269        let (boundary_key, boundary_list) = &shards[boundary_idx];
2270
2271        // Delete the boundary shard (we'll either drop it or rewrite at u64::MAX)
2272        self.delete::<tables::AccountsHistory>(boundary_key.clone())?;
2273
2274        // Build truncated list once; check emptiness directly (avoids double iteration)
2275        let new_last =
2276            BlockNumberList::new_pre_sorted(boundary_list.iter().take_while(|&b| b <= keep_to));
2277
2278        if new_last.is_empty() {
2279            // Boundary shard is now empty. Previous shard becomes the last and must be keyed
2280            // u64::MAX.
2281            if boundary_idx == 0 {
2282                // Nothing left for this address
2283                return Ok(());
2284            }
2285
2286            let (prev_key, prev_value) = &shards[boundary_idx - 1];
2287            if prev_key.highest_block_number != u64::MAX {
2288                self.delete::<tables::AccountsHistory>(prev_key.clone())?;
2289                self.put::<tables::AccountsHistory>(
2290                    ShardedKey::new(address, u64::MAX),
2291                    prev_value,
2292                )?;
2293            }
2294            return Ok(());
2295        }
2296
2297        self.put::<tables::AccountsHistory>(ShardedKey::new(address, u64::MAX), &new_last)?;
2298
2299        Ok(())
2300    }
2301
2302    /// Prunes history shards, removing blocks <= `to_block`.
2303    ///
2304    /// Generic implementation for both account and storage history pruning.
2305    /// Mirrors MDBX `prune_shard` semantics. After pruning, the last remaining shard
2306    /// (if any) will have the sentinel key (`u64::MAX`).
2307    ///
2308    /// `shards_complete` must be `false` when `shards` stops short of the key's last shard, so the
2309    /// survivor is not re-keyed over a sentinel that is still on disk.
2310    #[expect(clippy::too_many_arguments)]
2311    fn prune_history_shards_inner<K>(
2312        &mut self,
2313        shards: Vec<(K, BlockNumberList)>,
2314        shards_complete: bool,
2315        to_block: BlockNumber,
2316        get_highest: impl Fn(&K) -> u64,
2317        is_sentinel: impl Fn(&K) -> bool,
2318        delete_shard: impl Fn(&mut Self, K) -> ProviderResult<()>,
2319        put_shard: impl Fn(&mut Self, K, &BlockNumberList) -> ProviderResult<()>,
2320        create_sentinel: impl Fn() -> K,
2321    ) -> ProviderResult<PruneShardOutcome>
2322    where
2323        K: Clone,
2324    {
2325        if shards.is_empty() {
2326            return Ok(PruneShardOutcome::Unchanged);
2327        }
2328
2329        let mut deleted = false;
2330        let mut updated = false;
2331        let mut last_remaining: Option<(K, BlockNumberList)> = None;
2332
2333        for (key, mut block_list) in shards {
2334            if !is_sentinel(&key) && get_highest(&key) <= to_block {
2335                delete_shard(self, key)?;
2336                deleted = true;
2337            } else {
2338                let removed = block_list.remove_range(0..=to_block);
2339
2340                if block_list.is_empty() {
2341                    delete_shard(self, key)?;
2342                    deleted = true;
2343                } else if removed > 0 {
2344                    put_shard(self, key.clone(), &block_list)?;
2345                    last_remaining = Some((key, block_list));
2346                    updated = true;
2347                } else {
2348                    last_remaining = Some((key, block_list));
2349                }
2350            }
2351        }
2352
2353        if shards_complete &&
2354            let Some((last_key, last_value)) = last_remaining &&
2355            !is_sentinel(&last_key)
2356        {
2357            delete_shard(self, last_key)?;
2358            put_shard(self, create_sentinel(), &last_value)?;
2359            updated = true;
2360        }
2361
2362        if deleted {
2363            Ok(PruneShardOutcome::Deleted)
2364        } else if updated {
2365            Ok(PruneShardOutcome::Updated)
2366        } else {
2367            Ok(PruneShardOutcome::Unchanged)
2368        }
2369    }
2370
2371    /// Prunes account history for the given address, removing blocks <= `to_block`.
2372    ///
2373    /// Mirrors MDBX `prune_shard` semantics. After pruning, the last remaining shard
2374    /// (if any) will have the sentinel key (`u64::MAX`).
2375    pub fn prune_account_history_to(
2376        &mut self,
2377        address: Address,
2378        to_block: BlockNumber,
2379    ) -> ProviderResult<PruneShardOutcome> {
2380        let shards = self.provider.account_history_shards(address)?;
2381        self.prune_history_shards_inner(
2382            shards,
2383            true,
2384            to_block,
2385            |key| key.highest_block_number,
2386            |key| key.highest_block_number == u64::MAX,
2387            |batch, key| batch.delete::<tables::AccountsHistory>(key),
2388            |batch, key, value| batch.put::<tables::AccountsHistory>(key, value),
2389            || ShardedKey::new(address, u64::MAX),
2390        )
2391    }
2392
2393    /// Prunes account history for multiple addresses in a single iterator pass.
2394    ///
2395    /// This is more efficient than calling [`Self::prune_account_history_to`] repeatedly
2396    /// because it reuses a single raw iterator and skips seeks when the iterator is already
2397    /// positioned correctly (which happens when targets are sorted and adjacent in key order).
2398    ///
2399    /// `targets` MUST be sorted by address and contain each address at most once, for
2400    /// correctness and optimal performance (matches on-disk key order).
2401    pub fn prune_account_history_batch(
2402        &mut self,
2403        targets: &[(Address, BlockNumber)],
2404    ) -> ProviderResult<PrunedIndices> {
2405        if targets.is_empty() {
2406            return Ok(PrunedIndices::default());
2407        }
2408
2409        debug_assert!(
2410            targets.windows(2).all(|w| w[0].0 < w[1].0),
2411            "prune_account_history_batch: targets must be sorted and unique"
2412        );
2413
2414        // ShardedKey<Address> layout: [address: 20][block: 8] = 28 bytes
2415        // The first 20 bytes are the "prefix" that identifies the address
2416        const PREFIX_LEN: usize = 20;
2417
2418        let cf = self.provider.get_cf_handle::<tables::AccountsHistory>()?;
2419        let mut iter = self.provider.0.raw_iterator_cf(cf);
2420        let mut outcomes = PrunedIndices::default();
2421
2422        for (address, to_block) in targets {
2423            // Build the target prefix (first 20 bytes = address)
2424            let start_key = ShardedKey::new(*address, 0u64).encode();
2425            let target_prefix = &start_key[..PREFIX_LEN];
2426
2427            // Check if we need to seek or if the iterator is already positioned correctly.
2428            // After processing the previous target, the iterator is either:
2429            // 1. Positioned at a key with a different prefix (we iterated past our shards)
2430            // 2. Positioned on a later shard of the previous target (we stopped early), whose
2431            //    prefix is below ours because targets are sorted and unique
2432            // 3. Invalid (no more keys)
2433            // If the current key's prefix >= our target prefix, we may be able to skip the seek.
2434            let needs_seek = if iter.valid() {
2435                // If current key's prefix < target prefix, we need to seek forward
2436                // If current key's prefix > target prefix, this target has no shards (skip)
2437                // If current key's prefix == target prefix, we're already positioned
2438                iter.key().is_none_or(|current_key| {
2439                    current_key.get(..PREFIX_LEN).is_none_or(|p| p < target_prefix)
2440                })
2441            } else {
2442                true
2443            };
2444
2445            if needs_seek {
2446                iter.seek(start_key);
2447                iter.status().map_err(|e| {
2448                    ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
2449                        message: e.to_string().into(),
2450                        code: -1,
2451                    }))
2452                })?;
2453            }
2454
2455            // Collect the shards for this address that pruning can touch, using raw prefix
2456            // comparison
2457            let mut shards = Vec::new();
2458            let mut shards_complete = true;
2459            while iter.valid() {
2460                let Some(key_bytes) = iter.key() else { break };
2461
2462                // Use raw prefix comparison instead of full decode for the prefix check
2463                let current_prefix = key_bytes.get(..PREFIX_LEN);
2464                if current_prefix != Some(target_prefix) {
2465                    break;
2466                }
2467
2468                // Now decode the full key (we need the block number)
2469                let key = ShardedKey::<Address>::decode(key_bytes)
2470                    .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
2471
2472                let Some(value_bytes) = iter.value() else { break };
2473                let value = BlockNumberList::decompress(value_bytes)
2474                    .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
2475
2476                let highest = key.highest_block_number;
2477                shards.push((key, value));
2478
2479                iter.next();
2480
2481                // Shards are ordered by their highest block and their contents partition the
2482                // address's history, so this is the last shard holding anything at or below the
2483                // target. Peek past it only to tell whether it was the address's last shard,
2484                // which decides whether a survivor may be re-keyed to the sentinel.
2485                if highest > *to_block {
2486                    shards_complete = iter.key().and_then(|next_key| next_key.get(..PREFIX_LEN)) !=
2487                        Some(target_prefix);
2488                    break;
2489                }
2490            }
2491
2492            // The iterator also goes invalid on a read error, which would otherwise pass a
2493            // truncated shard list off as the key's complete one.
2494            if !iter.valid() {
2495                iter.status().map_err(|e| {
2496                    ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
2497                        message: e.to_string().into(),
2498                        code: -1,
2499                    }))
2500                })?;
2501            }
2502
2503            match self.prune_history_shards_inner(
2504                shards,
2505                shards_complete,
2506                *to_block,
2507                |key| key.highest_block_number,
2508                |key| key.highest_block_number == u64::MAX,
2509                |batch, key| batch.delete::<tables::AccountsHistory>(key),
2510                |batch, key, value| batch.put::<tables::AccountsHistory>(key, value),
2511                || ShardedKey::new(*address, u64::MAX),
2512            )? {
2513                PruneShardOutcome::Deleted => outcomes.deleted += 1,
2514                PruneShardOutcome::Updated => outcomes.updated += 1,
2515                PruneShardOutcome::Unchanged => outcomes.unchanged += 1,
2516            }
2517        }
2518
2519        Ok(outcomes)
2520    }
2521
2522    /// Prunes storage history for the given address and storage key, removing blocks <=
2523    /// `to_block`.
2524    ///
2525    /// Mirrors MDBX `prune_shard` semantics. After pruning, the last remaining shard
2526    /// (if any) will have the sentinel key (`u64::MAX`).
2527    pub fn prune_storage_history_to(
2528        &mut self,
2529        address: Address,
2530        storage_key: B256,
2531        to_block: BlockNumber,
2532    ) -> ProviderResult<PruneShardOutcome> {
2533        let shards = self.provider.storage_history_shards(address, storage_key)?;
2534        self.prune_history_shards_inner(
2535            shards,
2536            true,
2537            to_block,
2538            |key| key.sharded_key.highest_block_number,
2539            |key| key.sharded_key.highest_block_number == u64::MAX,
2540            |batch, key| batch.delete::<tables::StoragesHistory>(key),
2541            |batch, key, value| batch.put::<tables::StoragesHistory>(key, value),
2542            || StorageShardedKey::last(address, storage_key),
2543        )
2544    }
2545
2546    /// Prunes storage history for multiple (address, `storage_key`) pairs in a single iterator
2547    /// pass.
2548    ///
2549    /// This is more efficient than calling [`Self::prune_storage_history_to`] repeatedly
2550    /// because it reuses a single raw iterator and skips seeks when the iterator is already
2551    /// positioned correctly (which happens when targets are sorted and adjacent in key order).
2552    ///
2553    /// `targets` MUST be sorted by (address, `storage_key`) and contain each pair at most once,
2554    /// for correctness and optimal performance (matches on-disk key order).
2555    pub fn prune_storage_history_batch(
2556        &mut self,
2557        targets: &[((Address, B256), BlockNumber)],
2558    ) -> ProviderResult<PrunedIndices> {
2559        if targets.is_empty() {
2560            return Ok(PrunedIndices::default());
2561        }
2562
2563        debug_assert!(
2564            targets.windows(2).all(|w| w[0].0 < w[1].0),
2565            "prune_storage_history_batch: targets must be sorted and unique"
2566        );
2567
2568        // StorageShardedKey layout: [address: 20][storage_key: 32][block: 8] = 60 bytes
2569        // The first 52 bytes are the "prefix" that identifies (address, storage_key)
2570        const PREFIX_LEN: usize = 52;
2571
2572        let cf = self.provider.get_cf_handle::<tables::StoragesHistory>()?;
2573        let mut iter = self.provider.0.raw_iterator_cf(cf);
2574        let mut outcomes = PrunedIndices::default();
2575
2576        for ((address, storage_key), to_block) in targets {
2577            // Build the target prefix (first 52 bytes of encoded key)
2578            let start_key = StorageShardedKey::new(*address, *storage_key, 0u64).encode();
2579            let target_prefix = &start_key[..PREFIX_LEN];
2580
2581            // Check if we need to seek or if the iterator is already positioned correctly.
2582            // After processing the previous target, the iterator is either:
2583            // 1. Positioned at a key with a different prefix (we iterated past our shards)
2584            // 2. Positioned on a later shard of the previous target (we stopped early), whose
2585            //    prefix is below ours because targets are sorted and unique
2586            // 3. Invalid (no more keys)
2587            // If the current key's prefix >= our target prefix, we may be able to skip the seek.
2588            let needs_seek = if iter.valid() {
2589                // If current key's prefix < target prefix, we need to seek forward
2590                // If current key's prefix > target prefix, this target has no shards (skip)
2591                // If current key's prefix == target prefix, we're already positioned
2592                iter.key().is_none_or(|current_key| {
2593                    current_key.get(..PREFIX_LEN).is_none_or(|p| p < target_prefix)
2594                })
2595            } else {
2596                true
2597            };
2598
2599            if needs_seek {
2600                iter.seek(start_key);
2601                iter.status().map_err(|e| {
2602                    ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
2603                        message: e.to_string().into(),
2604                        code: -1,
2605                    }))
2606                })?;
2607            }
2608
2609            // Collect the shards for this (address, storage_key) pair that pruning can touch,
2610            // using prefix comparison
2611            let mut shards = Vec::new();
2612            let mut shards_complete = true;
2613            while iter.valid() {
2614                let Some(key_bytes) = iter.key() else { break };
2615
2616                // Use raw prefix comparison instead of full decode for the prefix check
2617                let current_prefix = key_bytes.get(..PREFIX_LEN);
2618                if current_prefix != Some(target_prefix) {
2619                    break;
2620                }
2621
2622                // Now decode the full key (we need the block number)
2623                let key = StorageShardedKey::decode(key_bytes)
2624                    .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
2625
2626                let Some(value_bytes) = iter.value() else { break };
2627                let value = BlockNumberList::decompress(value_bytes)
2628                    .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
2629
2630                let highest = key.sharded_key.highest_block_number;
2631                shards.push((key, value));
2632
2633                iter.next();
2634
2635                // Shards are ordered by their highest block and their contents partition the
2636                // key's history, so this is the last shard holding anything at or below the
2637                // target. Peek past it only to tell whether it was the key's last shard, which
2638                // decides whether a survivor may be re-keyed to the sentinel.
2639                if highest > *to_block {
2640                    shards_complete = iter.key().and_then(|next_key| next_key.get(..PREFIX_LEN)) !=
2641                        Some(target_prefix);
2642                    break;
2643                }
2644            }
2645
2646            // The iterator also goes invalid on a read error, which would otherwise pass a
2647            // truncated shard list off as the key's complete one.
2648            if !iter.valid() {
2649                iter.status().map_err(|e| {
2650                    ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
2651                        message: e.to_string().into(),
2652                        code: -1,
2653                    }))
2654                })?;
2655            }
2656
2657            // Use existing prune_history_shards_inner logic
2658            match self.prune_history_shards_inner(
2659                shards,
2660                shards_complete,
2661                *to_block,
2662                |key| key.sharded_key.highest_block_number,
2663                |key| key.sharded_key.highest_block_number == u64::MAX,
2664                |batch, key| batch.delete::<tables::StoragesHistory>(key),
2665                |batch, key, value| batch.put::<tables::StoragesHistory>(key, value),
2666                || StorageShardedKey::last(*address, *storage_key),
2667            )? {
2668                PruneShardOutcome::Deleted => outcomes.deleted += 1,
2669                PruneShardOutcome::Updated => outcomes.updated += 1,
2670                PruneShardOutcome::Unchanged => outcomes.unchanged += 1,
2671            }
2672        }
2673
2674        Ok(outcomes)
2675    }
2676
2677    /// Unwinds storage history to keep only blocks `<= keep_to`.
2678    ///
2679    /// Shards are handled as in [`Self::unwind_account_history_to`].
2680    pub fn unwind_storage_history_to(
2681        &mut self,
2682        address: Address,
2683        storage_key: B256,
2684        keep_to: BlockNumber,
2685    ) -> ProviderResult<()> {
2686        if self.unwind_last_history_shard::<tables::StoragesHistory>(
2687            |highest| StorageShardedKey::new(address, storage_key, highest),
2688            keep_to,
2689        )? {
2690            return Ok(());
2691        }
2692        let shards = self.provider.storage_history_shards(address, storage_key)?;
2693        if shards.is_empty() {
2694            return Ok(());
2695        }
2696
2697        // Find the first shard that might contain blocks > keep_to.
2698        // A shard is affected if it's the sentinel (u64::MAX) or its highest_block_number > keep_to
2699        let boundary_idx = shards.iter().position(|(key, _)| {
2700            key.sharded_key.highest_block_number == u64::MAX ||
2701                key.sharded_key.highest_block_number > keep_to
2702        });
2703
2704        // Repair path: no shards affected means all blocks <= keep_to, just ensure sentinel exists
2705        let Some(boundary_idx) = boundary_idx else {
2706            let (last_key, last_value) = shards.last().expect("shards is non-empty");
2707            if last_key.sharded_key.highest_block_number != u64::MAX {
2708                self.delete::<tables::StoragesHistory>(last_key.clone())?;
2709                self.put::<tables::StoragesHistory>(
2710                    StorageShardedKey::last(address, storage_key),
2711                    last_value,
2712                )?;
2713            }
2714            return Ok(());
2715        };
2716
2717        // Delete all shards strictly after the boundary (they are entirely > keep_to)
2718        for (key, _) in shards.iter().skip(boundary_idx + 1) {
2719            self.delete::<tables::StoragesHistory>(key.clone())?;
2720        }
2721
2722        // Process the boundary shard: filter out blocks > keep_to
2723        let (boundary_key, boundary_list) = &shards[boundary_idx];
2724
2725        // Delete the boundary shard (we'll either drop it or rewrite at u64::MAX)
2726        self.delete::<tables::StoragesHistory>(boundary_key.clone())?;
2727
2728        // Build truncated list once; check emptiness directly (avoids double iteration)
2729        let new_last =
2730            BlockNumberList::new_pre_sorted(boundary_list.iter().take_while(|&b| b <= keep_to));
2731
2732        if new_last.is_empty() {
2733            // Boundary shard is now empty. Previous shard becomes the last and must be keyed
2734            // u64::MAX.
2735            if boundary_idx == 0 {
2736                // Nothing left for this (address, storage_key) pair
2737                return Ok(());
2738            }
2739
2740            let (prev_key, prev_value) = &shards[boundary_idx - 1];
2741            if prev_key.sharded_key.highest_block_number != u64::MAX {
2742                self.delete::<tables::StoragesHistory>(prev_key.clone())?;
2743                self.put::<tables::StoragesHistory>(
2744                    StorageShardedKey::last(address, storage_key),
2745                    prev_value,
2746                )?;
2747            }
2748            return Ok(());
2749        }
2750
2751        self.put::<tables::StoragesHistory>(
2752            StorageShardedKey::last(address, storage_key),
2753            &new_last,
2754        )?;
2755
2756        Ok(())
2757    }
2758
2759    /// Clears all account history shards for the given address.
2760    ///
2761    /// Used when unwinding from block 0 (i.e., removing all history).
2762    pub fn clear_account_history(&mut self, address: Address) -> ProviderResult<()> {
2763        let shards = self.provider.account_history_shards(address)?;
2764        for (key, _) in shards {
2765            self.delete::<tables::AccountsHistory>(key)?;
2766        }
2767        Ok(())
2768    }
2769
2770    /// Clears all storage history shards for the given `(address, storage_key)` pair.
2771    ///
2772    /// Used when unwinding from block 0 (i.e., removing all history for this storage slot).
2773    pub fn clear_storage_history(
2774        &mut self,
2775        address: Address,
2776        storage_key: B256,
2777    ) -> ProviderResult<()> {
2778        let shards = self.provider.storage_history_shards(address, storage_key)?;
2779        for (key, _) in shards {
2780            self.delete::<tables::StoragesHistory>(key)?;
2781        }
2782        Ok(())
2783    }
2784
2785    /// Trims the last shard if it is the only shard holding blocks above `keep_to`.
2786    ///
2787    /// Seeks to the first shard that can hold a block above `keep_to`, which is the shard the full
2788    /// scan picks as its boundary. This is not always the last shard: a crash between two
2789    /// auto-commits can leave a newly split shard next to the last shard it was split from.
2790    ///
2791    /// Returns `false` without writing if the full scan is needed.
2792    fn unwind_last_history_shard<T: Table<Value = BlockNumberList>>(
2793        &mut self,
2794        shard_key: impl Fn(BlockNumber) -> T::Key,
2795        keep_to: BlockNumber,
2796    ) -> ProviderResult<bool> {
2797        let cf = self.provider.get_cf_handle::<T>()?;
2798        let last_bytes = shard_key(u64::MAX).encode();
2799        let boundary = self
2800            .provider
2801            .0
2802            .iterator_cf_inclusive_range(
2803                cf,
2804                shard_key(keep_to.saturating_add(1)).encode().as_ref(),
2805                last_bytes.as_ref(),
2806            )
2807            .next()
2808            .transpose()
2809            .map_err(|e| {
2810                ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
2811                    message: e.to_string().into(),
2812                    code: -1,
2813                }))
2814            })?;
2815        let Some((key, value)) = boundary else { return Ok(false) };
2816        if *key != *last_bytes.as_ref() {
2817            return Ok(false);
2818        }
2819
2820        let shard = BlockNumberList::decompress(&value)
2821            .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
2822        if shard.min().is_none_or(|first| first > keep_to) {
2823            return Ok(false);
2824        }
2825        if shard.max().is_some_and(|last| last > keep_to) {
2826            let kept =
2827                BlockNumberList::new_pre_sorted(shard.iter().take_while(|&block| block <= keep_to));
2828            self.put::<T>(shard_key(u64::MAX), &kept)?;
2829        }
2830        Ok(true)
2831    }
2832}
2833
2834/// `RocksDB` transaction wrapper providing MDBX-like semantics.
2835///
2836/// Supports:
2837/// - Read-your-writes: reads see uncommitted writes within the same transaction
2838/// - Atomic commit/rollback
2839/// - Iteration over uncommitted data
2840///
2841/// Note: `Transaction` is `Send` but NOT `Sync`. This wrapper does not implement
2842/// `DbTx`/`DbTxMut` traits directly; use RocksDB-specific methods instead.
2843pub struct RocksTx<'db> {
2844    inner: Transaction<'db, OptimisticTransactionDB>,
2845    provider: &'db RocksDBProvider,
2846}
2847
2848impl fmt::Debug for RocksTx<'_> {
2849    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2850        f.debug_struct("RocksTx").field("provider", &self.provider).finish_non_exhaustive()
2851    }
2852}
2853
2854impl<'db> RocksTx<'db> {
2855    /// Gets a value from the specified table. Sees uncommitted writes in this transaction.
2856    pub fn get<T: Table>(&self, key: T::Key) -> ProviderResult<Option<T::Value>> {
2857        let encoded_key = key.encode();
2858        self.get_encoded::<T>(&encoded_key)
2859    }
2860
2861    /// Gets a value using pre-encoded key. Sees uncommitted writes in this transaction.
2862    pub fn get_encoded<T: Table>(
2863        &self,
2864        key: &<T::Key as Encode>::Encoded,
2865    ) -> ProviderResult<Option<T::Value>> {
2866        let cf = self.provider.get_cf_handle::<T>()?;
2867        let result = self.inner.get_cf(cf, key.as_ref()).map_err(|e| {
2868            ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
2869                message: e.to_string().into(),
2870                code: -1,
2871            }))
2872        })?;
2873
2874        Ok(result.and_then(|value| T::Value::decompress(&value).ok()))
2875    }
2876
2877    /// Puts a value into the specified table.
2878    pub fn put<T: Table>(&self, key: T::Key, value: &T::Value) -> ProviderResult<()> {
2879        let encoded_key = key.encode();
2880        self.put_encoded::<T>(&encoded_key, value)
2881    }
2882
2883    /// Puts a value using pre-encoded key.
2884    pub fn put_encoded<T: Table>(
2885        &self,
2886        key: &<T::Key as Encode>::Encoded,
2887        value: &T::Value,
2888    ) -> ProviderResult<()> {
2889        let cf = self.provider.get_cf_handle::<T>()?;
2890        let mut buf = Vec::new();
2891        let value_bytes = compress_to_buf_or_ref!(buf, value).unwrap_or(&buf);
2892
2893        self.inner.put_cf(cf, key.as_ref(), value_bytes).map_err(|e| {
2894            ProviderError::Database(DatabaseError::Write(Box::new(DatabaseWriteError {
2895                info: DatabaseErrorInfo { message: e.to_string().into(), code: -1 },
2896                operation: DatabaseWriteOperation::PutUpsert,
2897                table_name: T::NAME,
2898                key: key.as_ref().to_vec(),
2899            })))
2900        })
2901    }
2902
2903    /// Deletes a value from the specified table.
2904    pub fn delete<T: Table>(&self, key: T::Key) -> ProviderResult<()> {
2905        let cf = self.provider.get_cf_handle::<T>()?;
2906        self.inner.delete_cf(cf, key.encode().as_ref()).map_err(|e| {
2907            ProviderError::Database(DatabaseError::Delete(DatabaseErrorInfo {
2908                message: e.to_string().into(),
2909                code: -1,
2910            }))
2911        })
2912    }
2913
2914    /// Creates an iterator for the specified table. Sees uncommitted writes in this transaction.
2915    ///
2916    /// Returns an iterator that yields `(encoded_key, compressed_value)` pairs.
2917    pub fn iter<T: Table>(&self) -> ProviderResult<RocksTxIter<'_, T>> {
2918        let cf = self.provider.get_cf_handle::<T>()?;
2919        let iter = self.inner.iterator_cf(cf, IteratorMode::Start);
2920        Ok(RocksTxIter { inner: iter, _marker: std::marker::PhantomData })
2921    }
2922
2923    /// Creates an iterator starting from the given key (inclusive).
2924    pub fn iter_from<T: Table>(&self, key: T::Key) -> ProviderResult<RocksTxIter<'_, T>> {
2925        let cf = self.provider.get_cf_handle::<T>()?;
2926        let encoded_key = key.encode();
2927        let iter = self
2928            .inner
2929            .iterator_cf(cf, IteratorMode::From(encoded_key.as_ref(), rocksdb::Direction::Forward));
2930        Ok(RocksTxIter { inner: iter, _marker: std::marker::PhantomData })
2931    }
2932
2933    /// Commits the transaction, persisting all changes.
2934    #[instrument(level = "debug", target = "providers::rocksdb", skip_all)]
2935    pub fn commit(self) -> ProviderResult<()> {
2936        self.inner.commit().map_err(|e| {
2937            ProviderError::Database(DatabaseError::Commit(DatabaseErrorInfo {
2938                message: e.to_string().into(),
2939                code: -1,
2940            }))
2941        })
2942    }
2943
2944    /// Rolls back the transaction, discarding all changes.
2945    #[instrument(level = "debug", target = "providers::rocksdb", skip_all)]
2946    pub fn rollback(self) -> ProviderResult<()> {
2947        self.inner.rollback().map_err(|e| {
2948            ProviderError::Database(DatabaseError::Other(format!("rollback failed: {e}")))
2949        })
2950    }
2951}
2952
2953/// Wrapper enum for `RocksDB` iterators that works in both read-write and read-only modes.
2954enum RocksDBIterEnum<'db> {
2955    /// Iterator from read-write `OptimisticTransactionDB`.
2956    ReadWrite(rocksdb::DBIteratorWithThreadMode<'db, OptimisticTransactionDB>),
2957    /// Iterator from read-only `DB`.
2958    ReadOnly(rocksdb::DBIteratorWithThreadMode<'db, DB>),
2959}
2960
2961impl Iterator for RocksDBIterEnum<'_> {
2962    type Item = Result<(Box<[u8]>, Box<[u8]>), rocksdb::Error>;
2963
2964    fn next(&mut self) -> Option<Self::Item> {
2965        match self {
2966            Self::ReadWrite(iter) => iter.next(),
2967            Self::ReadOnly(iter) => iter.next(),
2968        }
2969    }
2970}
2971
2972/// Wrapper enum for raw `RocksDB` iterators that works in both read-write and read-only modes.
2973///
2974/// Unlike [`RocksDBIterEnum`], raw iterators expose `seek()` for efficient repositioning
2975/// without reinitializing the iterator.
2976enum RocksDBRawIterEnum<'db> {
2977    /// Raw iterator from read-write `OptimisticTransactionDB`.
2978    ReadWrite(DBRawIteratorWithThreadMode<'db, OptimisticTransactionDB>),
2979    /// Raw iterator from read-only `DB`.
2980    ReadOnly(DBRawIteratorWithThreadMode<'db, DB>),
2981}
2982
2983impl RocksDBRawIterEnum<'_> {
2984    /// Positions the iterator at the first key >= `key`.
2985    fn seek(&mut self, key: impl AsRef<[u8]>) {
2986        match self {
2987            Self::ReadWrite(iter) => iter.seek(key),
2988            Self::ReadOnly(iter) => iter.seek(key),
2989        }
2990    }
2991
2992    /// Returns true if the iterator is positioned at a valid key-value pair.
2993    fn valid(&self) -> bool {
2994        match self {
2995            Self::ReadWrite(iter) => iter.valid(),
2996            Self::ReadOnly(iter) => iter.valid(),
2997        }
2998    }
2999
3000    /// Returns the current key, if valid.
3001    fn key(&self) -> Option<&[u8]> {
3002        match self {
3003            Self::ReadWrite(iter) => iter.key(),
3004            Self::ReadOnly(iter) => iter.key(),
3005        }
3006    }
3007
3008    /// Returns the current value, if valid.
3009    fn value(&self) -> Option<&[u8]> {
3010        match self {
3011            Self::ReadWrite(iter) => iter.value(),
3012            Self::ReadOnly(iter) => iter.value(),
3013        }
3014    }
3015
3016    /// Advances the iterator to the next key.
3017    fn next(&mut self) {
3018        match self {
3019            Self::ReadWrite(iter) => iter.next(),
3020            Self::ReadOnly(iter) => iter.next(),
3021        }
3022    }
3023
3024    /// Moves the iterator to the previous key.
3025    fn prev(&mut self) {
3026        match self {
3027            Self::ReadWrite(iter) => iter.prev(),
3028            Self::ReadOnly(iter) => iter.prev(),
3029        }
3030    }
3031
3032    /// Returns the status of the iterator.
3033    fn status(&self) -> Result<(), rocksdb::Error> {
3034        match self {
3035            Self::ReadWrite(iter) => iter.status(),
3036            Self::ReadOnly(iter) => iter.status(),
3037        }
3038    }
3039}
3040
3041/// Iterator over a `RocksDB` table (non-transactional).
3042///
3043/// Yields decoded `(Key, Value)` pairs in key order.
3044pub struct RocksDBIter<'db, T: Table> {
3045    inner: RocksDBIterEnum<'db>,
3046    _marker: std::marker::PhantomData<T>,
3047}
3048
3049impl<T: Table> fmt::Debug for RocksDBIter<'_, T> {
3050    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3051        f.debug_struct("RocksDBIter").field("table", &T::NAME).finish_non_exhaustive()
3052    }
3053}
3054
3055impl<T: Table> Iterator for RocksDBIter<'_, T> {
3056    type Item = ProviderResult<(T::Key, T::Value)>;
3057
3058    fn next(&mut self) -> Option<Self::Item> {
3059        Some(decode_iter_item::<T>(self.inner.next()?))
3060    }
3061}
3062
3063/// Raw iterator over a `RocksDB` table (non-transactional).
3064///
3065/// Yields raw `(key_bytes, value_bytes)` pairs without decoding.
3066pub struct RocksDBRawIter<'db> {
3067    inner: RocksDBIterEnum<'db>,
3068}
3069
3070impl fmt::Debug for RocksDBRawIter<'_> {
3071    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3072        f.debug_struct("RocksDBRawIter").finish_non_exhaustive()
3073    }
3074}
3075
3076impl Iterator for RocksDBRawIter<'_> {
3077    type Item = ProviderResult<(Box<[u8]>, Box<[u8]>)>;
3078
3079    fn next(&mut self) -> Option<Self::Item> {
3080        match self.inner.next()? {
3081            Ok(kv) => Some(Ok(kv)),
3082            Err(e) => Some(Err(ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
3083                message: e.to_string().into(),
3084                code: -1,
3085            })))),
3086        }
3087    }
3088}
3089
3090/// Raw key iterator over a `RocksDB` table (non-transactional).
3091pub(crate) struct RocksDBRawKeyIter<'db> {
3092    inner: RocksDBRawIterEnum<'db>,
3093}
3094
3095impl fmt::Debug for RocksDBRawKeyIter<'_> {
3096    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3097        f.debug_struct("RocksDBRawKeyIter").finish_non_exhaustive()
3098    }
3099}
3100
3101impl Iterator for RocksDBRawKeyIter<'_> {
3102    type Item = ProviderResult<Box<[u8]>>;
3103
3104    fn next(&mut self) -> Option<Self::Item> {
3105        if !self.inner.valid() {
3106            return self.inner.status().err().map(|e| {
3107                Err(ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
3108                    message: e.to_string().into(),
3109                    code: -1,
3110                })))
3111            })
3112        }
3113
3114        let Some(key) = self.inner.key() else {
3115            return Some(Err(ProviderError::Database(DatabaseError::Decode)))
3116        };
3117        let key = Box::from(key);
3118        self.inner.next();
3119        Some(Ok(key))
3120    }
3121}
3122
3123/// Iterator over a `RocksDB` table within a transaction.
3124///
3125/// Yields decoded `(Key, Value)` pairs. Sees uncommitted writes.
3126pub struct RocksTxIter<'tx, T: Table> {
3127    inner: rocksdb::DBIteratorWithThreadMode<'tx, Transaction<'tx, OptimisticTransactionDB>>,
3128    _marker: std::marker::PhantomData<T>,
3129}
3130
3131impl<T: Table> fmt::Debug for RocksTxIter<'_, T> {
3132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3133        f.debug_struct("RocksTxIter").field("table", &T::NAME).finish_non_exhaustive()
3134    }
3135}
3136
3137impl<T: Table> Iterator for RocksTxIter<'_, T> {
3138    type Item = ProviderResult<(T::Key, T::Value)>;
3139
3140    fn next(&mut self) -> Option<Self::Item> {
3141        Some(decode_iter_item::<T>(self.inner.next()?))
3142    }
3143}
3144
3145/// Decodes a raw key-value pair from a `RocksDB` iterator into typed table entries.
3146///
3147/// Handles both error propagation from the underlying iterator and
3148/// decoding/decompression of the key and value bytes.
3149fn decode_iter_item<T: Table>(result: RawKVResult) -> ProviderResult<(T::Key, T::Value)> {
3150    let (key_bytes, value_bytes) = result.map_err(|e| {
3151        ProviderError::Database(DatabaseError::Read(DatabaseErrorInfo {
3152            message: e.to_string().into(),
3153            code: -1,
3154        }))
3155    })?;
3156
3157    let key = <T::Key as reth_db_api::table::Decode>::decode(&key_bytes)
3158        .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
3159
3160    let value = T::Value::decompress(&value_bytes)
3161        .map_err(|_| ProviderError::Database(DatabaseError::Decode))?;
3162
3163    Ok((key, value))
3164}
3165
3166/// Converts Reth's [`LogLevel`] to `RocksDB`'s [`rocksdb::LogLevel`].
3167const fn convert_log_level(level: LogLevel) -> rocksdb::LogLevel {
3168    match level {
3169        LogLevel::Fatal => rocksdb::LogLevel::Fatal,
3170        LogLevel::Error => rocksdb::LogLevel::Error,
3171        LogLevel::Warn => rocksdb::LogLevel::Warn,
3172        LogLevel::Notice | LogLevel::Verbose => rocksdb::LogLevel::Info,
3173        LogLevel::Debug | LogLevel::Trace | LogLevel::Extra => rocksdb::LogLevel::Debug,
3174    }
3175}
3176
3177/// Selects the `RocksDB` `max_open_files` setting from the current file descriptor limit
3178/// balancing performance vs. compatibility.
3179///
3180/// A mature database can use tens of thousands of file descriptors. With a
3181/// finite `max_open_files` value, `RocksDB` performs additional table-cache checks
3182/// even when enough capacity is available. The value `-1` keeps all table files
3183/// open and avoids this overhead.
3184///
3185/// During normal startup, Reth raises the soft file descriptor limit to the
3186/// system hard limit before it opens `RocksDB`. Therefore, we expect the current
3187/// limit to be the hard limit. A survey of modern Linux distributions shows
3188/// common default limits of `1024:524288`.
3189///
3190/// We use `-1` only when the current limit is above a conservative threshold.
3191/// This keeps enough file descriptors for other parts of the process. When the
3192/// limit is lower or cannot be read, we use a stricter fixed limit.
3193fn select_max_open_files() -> i32 {
3194    let file_descriptor_limit = current_file_descriptor_limit();
3195    let max_open_files = max_open_files_for_limit(file_descriptor_limit);
3196
3197    if max_open_files == LIMITED_MAX_OPEN_FILES {
3198        tracing::warn!(
3199            target: "providers::rocksdb",
3200            ?file_descriptor_limit,
3201            threshold = HIGH_FILE_DESCRIPTOR_LIMIT,
3202            max_open_files,
3203            "RocksDB will not keep all files open; performance may be reduced"
3204        );
3205    }
3206
3207    max_open_files
3208}
3209
3210const fn max_open_files_for_limit(file_descriptor_limit: Option<u64>) -> i32 {
3211    match file_descriptor_limit {
3212        Some(limit) if limit >= HIGH_FILE_DESCRIPTOR_LIMIT => KEEP_ALL_FILES_OPEN,
3213        _ => LIMITED_MAX_OPEN_FILES,
3214    }
3215}
3216
3217#[cfg(unix)]
3218#[allow(clippy::useless_conversion)]
3219fn current_file_descriptor_limit() -> Option<u64> {
3220    let mut limit = libc::rlimit { rlim_cur: 0, rlim_max: 0 };
3221    // SAFETY: `limit` points to initialized writable memory for the kernel to populate.
3222    let result = unsafe { libc::getrlimit(libc::RLIMIT_NOFILE, &raw mut limit) };
3223    (result == 0).then(|| limit.rlim_cur.into())
3224}
3225
3226#[cfg(not(unix))]
3227const fn current_file_descriptor_limit() -> Option<u64> {
3228    None
3229}
3230
3231#[cfg(test)]
3232mod tests {
3233    use super::*;
3234    use crate::providers::HistoryInfo;
3235    use alloy_primitives::{Address, Bytes, TxHash, B256};
3236    use reth_db_api::{
3237        models::{
3238            sharded_key::{ShardedKey, NUM_OF_INDICES_IN_SHARD},
3239            storage_sharded_key::StorageShardedKey,
3240            IntegerList,
3241        },
3242        table::Table,
3243        tables,
3244    };
3245    use rocksdb::{
3246        perf::{set_perf_stats, PerfContext, PerfMetric, PerfStatsLevel},
3247        statistics::{Histogram, Ticker},
3248    };
3249    use tempfile::TempDir;
3250
3251    /// Number of deleted keys `RocksDB` skipped on this thread while running `f`.
3252    fn deleted_keys_skipped<R>(f: impl FnOnce() -> R) -> (R, u64) {
3253        set_perf_stats(PerfStatsLevel::EnableCount);
3254        let mut ctx = PerfContext::default();
3255        ctx.reset();
3256        let result = f();
3257        let skipped = ctx.metric(PerfMetric::InternalDeleteSkippedCount);
3258        set_perf_stats(PerfStatsLevel::Disable);
3259        (result, skipped)
3260    }
3261
3262    fn address_at(i: u64) -> Address {
3263        let mut bytes = [0u8; 20];
3264        bytes[12..].copy_from_slice(&i.to_be_bytes());
3265        Address::from(bytes)
3266    }
3267
3268    /// Looking up the shards of an address whose history was already removed must not scan the
3269    /// deleted history of every address after it. This happens when an unwind (or the startup
3270    /// heal) removes the history of a large state import: each address's shards are looked up
3271    /// in turn, so an unbounded scan makes the whole unwind quadratic in the number of accounts.
3272    #[test]
3273    fn test_history_shards_lookup_skips_only_own_deleted_keys() {
3274        const ADDRESSES: u64 = 5_000;
3275
3276        let temp_dir = TempDir::new().unwrap();
3277        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
3278        let storage_key = B256::with_last_byte(1);
3279        let list = BlockNumberList::new_pre_sorted([1]);
3280
3281        // History for many addresses, then a live address after all of them.
3282        let mut batch = provider.batch();
3283        for i in 0..ADDRESSES {
3284            let address = address_at(i);
3285            batch
3286                .put::<tables::AccountsHistory>(ShardedKey::new(address, u64::MAX), &list)
3287                .unwrap();
3288            batch
3289                .put::<tables::StoragesHistory>(
3290                    StorageShardedKey::new(address, storage_key, u64::MAX),
3291                    &list,
3292                )
3293                .unwrap();
3294        }
3295        let live = Address::repeat_byte(0xff);
3296        batch.put::<tables::AccountsHistory>(ShardedKey::new(live, u64::MAX), &list).unwrap();
3297        batch
3298            .put::<tables::StoragesHistory>(
3299                StorageShardedKey::new(live, storage_key, u64::MAX),
3300                &list,
3301            )
3302            .unwrap();
3303        batch.commit().unwrap();
3304
3305        // Remove the history of all but the live address, as an unwind would.
3306        let mut batch = provider.batch();
3307        for i in 0..ADDRESSES {
3308            batch.clear_account_history(address_at(i)).unwrap();
3309            batch.clear_storage_history(address_at(i), storage_key).unwrap();
3310        }
3311        batch.commit().unwrap();
3312
3313        let (shards, skipped) =
3314            deleted_keys_skipped(|| provider.account_history_shards(address_at(0)));
3315        assert!(shards.unwrap().is_empty());
3316        assert!(skipped <= 1, "account lookup skipped {skipped} deleted keys");
3317
3318        let (shards, skipped) =
3319            deleted_keys_skipped(|| provider.storage_history_shards(address_at(0), storage_key));
3320        assert!(shards.unwrap().is_empty());
3321        assert!(skipped <= 1, "storage lookup skipped {skipped} deleted keys");
3322
3323        // The live address after the deleted range is still found.
3324        assert_eq!(provider.account_history_shards(live).unwrap().len(), 1);
3325        assert_eq!(provider.storage_history_shards(live, storage_key).unwrap().len(), 1);
3326    }
3327
3328    #[test]
3329    fn max_open_files_adapts_to_file_descriptor_limit() {
3330        assert_eq!(max_open_files_for_limit(Some(HIGH_FILE_DESCRIPTOR_LIMIT)), KEEP_ALL_FILES_OPEN);
3331        assert_eq!(
3332            max_open_files_for_limit(Some(HIGH_FILE_DESCRIPTOR_LIMIT - 1)),
3333            LIMITED_MAX_OPEN_FILES
3334        );
3335        assert_eq!(max_open_files_for_limit(None), LIMITED_MAX_OPEN_FILES);
3336    }
3337
3338    #[test]
3339    fn test_with_default_tables_registers_required_column_families() {
3340        let temp_dir = TempDir::new().unwrap();
3341
3342        // Build with default tables
3343        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
3344
3345        // Should be able to write/read TransactionHashNumbers
3346        let tx_hash = TxHash::from(B256::repeat_byte(1u8));
3347        provider.put::<tables::TransactionHashNumbers>(tx_hash, &100).unwrap();
3348        assert_eq!(provider.get::<tables::TransactionHashNumbers>(tx_hash).unwrap(), Some(100));
3349
3350        // Should be able to write/read AccountsHistory
3351        let key = ShardedKey::new(Address::ZERO, 100);
3352        let value = IntegerList::default();
3353        provider.put::<tables::AccountsHistory>(key.clone(), &value).unwrap();
3354        assert!(provider.get::<tables::AccountsHistory>(key).unwrap().is_some());
3355
3356        // Should be able to write/read StoragesHistory
3357        let key = StorageShardedKey::new(Address::ZERO, B256::ZERO, 100);
3358        provider.put::<tables::StoragesHistory>(key.clone(), &value).unwrap();
3359        assert!(provider.get::<tables::StoragesHistory>(key).unwrap().is_some());
3360
3361        let bal_key =
3362            reth_db_api::models::StoredBlockAccessListKey::new(1, B256::with_last_byte(1));
3363        let bal_value =
3364            reth_db_api::models::StoredBlockAccessList::new(Bytes::from_static(&[0xc0]));
3365        provider.put::<tables::BlockAccessLists>(bal_key, &bal_value).unwrap();
3366        assert_eq!(provider.get::<tables::BlockAccessLists>(bal_key).unwrap(), Some(bal_value));
3367        provider
3368            .put::<tables::BlockAccessListBlockNumbers>(bal_key.hash(), &bal_key.number())
3369            .unwrap();
3370        assert_eq!(
3371            provider.get::<tables::BlockAccessListBlockNumbers>(bal_key.hash()).unwrap(),
3372            Some(bal_key.number())
3373        );
3374    }
3375
3376    #[test]
3377    fn block_access_lists_store_large_payloads_in_blob_files() {
3378        let temp_dir = TempDir::new().unwrap();
3379        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
3380        let bal_key =
3381            reth_db_api::models::StoredBlockAccessListKey::new(1, B256::with_last_byte(1));
3382        let bal_value = reth_db_api::models::StoredBlockAccessList::new(Bytes::from(vec![
3383            0;
3384            DEFAULT_BAL_MIN_BLOB_SIZE as usize +
3385                1
3386        ]));
3387
3388        provider.put::<tables::BlockAccessLists>(bal_key, &bal_value).unwrap();
3389        provider.flush(&[tables::BlockAccessLists::NAME]).unwrap();
3390
3391        let has_blob_file = std::fs::read_dir(temp_dir.path()).unwrap().any(|entry| {
3392            entry.unwrap().path().extension().is_some_and(|extension| extension == "blob")
3393        });
3394        assert!(has_blob_file);
3395    }
3396
3397    #[derive(Debug)]
3398    struct TestTable;
3399
3400    impl Table for TestTable {
3401        const NAME: &'static str = "TestTable";
3402        const DUPSORT: bool = false;
3403        type Key = u64;
3404        type Value = Vec<u8>;
3405    }
3406
3407    #[test]
3408    fn test_reopens_with_unknown_column_family() {
3409        let temp_dir = TempDir::new().unwrap();
3410        let value = b"test_value".to_vec();
3411
3412        let provider = RocksDBBuilder::new(temp_dir.path())
3413            .with_default_tables()
3414            .with_table::<TestTable>()
3415            .build()
3416            .unwrap();
3417        provider.put::<TestTable>(42, &value).unwrap();
3418        drop(provider);
3419
3420        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
3421        assert_eq!(provider.get::<TestTable>(42).unwrap(), Some(value));
3422    }
3423
3424    #[test]
3425    fn test_reopens_blob_column_family_with_legacy_table_set() {
3426        let temp_dir = TempDir::new().unwrap();
3427        let bal_key =
3428            reth_db_api::models::StoredBlockAccessListKey::new(1, B256::with_last_byte(1));
3429        let bal_value = reth_db_api::models::StoredBlockAccessList::new(Bytes::from(vec![
3430            0;
3431            DEFAULT_BAL_MIN_BLOB_SIZE as usize +
3432                1
3433        ]));
3434
3435        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
3436        provider.put::<tables::BlockAccessLists>(bal_key, &bal_value).unwrap();
3437        provider
3438            .put::<tables::BlockAccessListBlockNumbers>(bal_key.hash(), &bal_key.number())
3439            .unwrap();
3440        provider.flush(&[tables::BlockAccessLists::NAME]).unwrap();
3441        drop(provider);
3442
3443        let provider = RocksDBBuilder::new(temp_dir.path())
3444            .with_table::<tables::TransactionHashNumbers>()
3445            .with_table::<tables::AccountsHistory>()
3446            .with_table::<tables::StoragesHistory>()
3447            .build()
3448            .unwrap();
3449        assert_eq!(provider.get::<tables::BlockAccessLists>(bal_key).unwrap(), Some(bal_value));
3450        assert_eq!(
3451            provider.get::<tables::BlockAccessListBlockNumbers>(bal_key.hash()).unwrap(),
3452            Some(bal_key.number())
3453        );
3454    }
3455
3456    #[test]
3457    fn test_basic_operations() {
3458        let temp_dir = TempDir::new().unwrap();
3459
3460        let provider = RocksDBBuilder::new(temp_dir.path())
3461            .with_table::<TestTable>() // Type-safe!
3462            .build()
3463            .unwrap();
3464
3465        let key = 42u64;
3466        let value = b"test_value".to_vec();
3467
3468        // Test write
3469        provider.put::<TestTable>(key, &value).unwrap();
3470
3471        // Test read
3472        let result = provider.get::<TestTable>(key).unwrap();
3473        assert_eq!(result, Some(value));
3474
3475        // Test delete
3476        provider.delete::<TestTable>(key).unwrap();
3477
3478        // Verify deletion
3479        assert_eq!(provider.get::<TestTable>(key).unwrap(), None);
3480    }
3481
3482    #[test]
3483    fn test_batch_operations() {
3484        let temp_dir = TempDir::new().unwrap();
3485        let provider =
3486            RocksDBBuilder::new(temp_dir.path()).with_table::<TestTable>().build().unwrap();
3487
3488        // Write multiple entries in a batch
3489        provider
3490            .write_batch(|batch| {
3491                for i in 0..10u64 {
3492                    let value = format!("value_{i}").into_bytes();
3493                    batch.put::<TestTable>(i, &value)?;
3494                }
3495                Ok(())
3496            })
3497            .unwrap();
3498
3499        // Read all entries
3500        for i in 0..10u64 {
3501            let value = format!("value_{i}").into_bytes();
3502            assert_eq!(provider.get::<TestTable>(i).unwrap(), Some(value));
3503        }
3504
3505        // Delete all entries in a batch
3506        provider
3507            .write_batch(|batch| {
3508                for i in 0..10u64 {
3509                    batch.delete::<TestTable>(i)?;
3510                }
3511                Ok(())
3512            })
3513            .unwrap();
3514
3515        // Verify all deleted
3516        for i in 0..10u64 {
3517            assert_eq!(provider.get::<TestTable>(i).unwrap(), None);
3518        }
3519    }
3520
3521    #[test]
3522    fn test_with_real_table() {
3523        let temp_dir = TempDir::new().unwrap();
3524        let provider = RocksDBBuilder::new(temp_dir.path())
3525            .with_table::<tables::TransactionHashNumbers>()
3526            .with_metrics()
3527            .build()
3528            .unwrap();
3529
3530        let tx_hash = TxHash::from(B256::repeat_byte(1u8));
3531
3532        // Insert and retrieve
3533        provider.put::<tables::TransactionHashNumbers>(tx_hash, &100).unwrap();
3534        assert_eq!(provider.get::<tables::TransactionHashNumbers>(tx_hash).unwrap(), Some(100));
3535
3536        // Batch insert multiple transactions
3537        provider
3538            .write_batch(|batch| {
3539                for i in 0..10u64 {
3540                    let hash = TxHash::from(B256::repeat_byte(i as u8));
3541                    let value = i * 100;
3542                    batch.put::<tables::TransactionHashNumbers>(hash, &value)?;
3543                }
3544                Ok(())
3545            })
3546            .unwrap();
3547
3548        // Verify batch insertions
3549        for i in 0..10u64 {
3550            let hash = TxHash::from(B256::repeat_byte(i as u8));
3551            assert_eq!(
3552                provider.get::<tables::TransactionHashNumbers>(hash).unwrap(),
3553                Some(i * 100)
3554            );
3555        }
3556    }
3557    #[test]
3558    fn test_statistics_enabled() {
3559        let temp_dir = TempDir::new().unwrap();
3560        // Just verify that building with statistics doesn't panic
3561        let provider = RocksDBBuilder::new(temp_dir.path())
3562            .with_table::<TestTable>()
3563            .with_statistics()
3564            .build()
3565            .unwrap();
3566
3567        // Do operations - data should be immediately readable with OptimisticTransactionDB
3568        for i in 0..10 {
3569            let value = vec![i as u8];
3570            provider.put::<TestTable>(i, &value).unwrap();
3571            // Verify write is visible
3572            assert_eq!(provider.get::<TestTable>(i).unwrap(), Some(value));
3573        }
3574    }
3575
3576    /// Guards the statistics level: the counters must keep working, the per-operation timer
3577    /// histograms must stay empty. `rocksdb`'s `StatsLevel` discriminants do not line up with the
3578    /// levels the C API defines, so the variant name alone does not tell us what was selected.
3579    #[test]
3580    fn test_statistics_level_skips_timers() {
3581        let temp_dir = TempDir::new().unwrap();
3582        let cache = Cache::new_lru_cache(1 << 20);
3583        let options = RocksDBBuilder::default_options(rocksdb::LogLevel::Info, &cache, true);
3584
3585        let db = DB::open(&options, temp_dir.path()).unwrap();
3586        for i in 0..10u8 {
3587            db.put([i], [i]).unwrap();
3588            assert_eq!(db.get([i]).unwrap(), Some(vec![i]));
3589        }
3590
3591        assert!(options.get_ticker_count(Ticker::NumberKeysRead) > 0);
3592        assert_eq!(options.get_histogram_data(Histogram::DbGet).count(), 0);
3593    }
3594
3595    #[test]
3596    fn test_data_persistence() {
3597        let temp_dir = TempDir::new().unwrap();
3598        let provider =
3599            RocksDBBuilder::new(temp_dir.path()).with_table::<TestTable>().build().unwrap();
3600
3601        // Insert data - OptimisticTransactionDB writes are immediately visible
3602        let value = vec![42u8; 1000];
3603        for i in 0..100 {
3604            provider.put::<TestTable>(i, &value).unwrap();
3605        }
3606
3607        // Verify data is readable
3608        for i in 0..100 {
3609            assert!(provider.get::<TestTable>(i).unwrap().is_some(), "Data should be readable");
3610        }
3611    }
3612
3613    #[test]
3614    fn test_transaction_read_your_writes() {
3615        let temp_dir = TempDir::new().unwrap();
3616        let provider =
3617            RocksDBBuilder::new(temp_dir.path()).with_table::<TestTable>().build().unwrap();
3618
3619        // Create a transaction
3620        let tx = provider.tx();
3621
3622        // Write data within the transaction
3623        let key = 42u64;
3624        let value = b"test_value".to_vec();
3625        tx.put::<TestTable>(key, &value).unwrap();
3626
3627        // Read-your-writes: should see uncommitted data in same transaction
3628        let result = tx.get::<TestTable>(key).unwrap();
3629        assert_eq!(
3630            result,
3631            Some(value.clone()),
3632            "Transaction should see its own uncommitted writes"
3633        );
3634
3635        // Data should NOT be visible via provider (outside transaction)
3636        let provider_result = provider.get::<TestTable>(key).unwrap();
3637        assert_eq!(provider_result, None, "Uncommitted data should not be visible outside tx");
3638
3639        // Commit the transaction
3640        tx.commit().unwrap();
3641
3642        // Now data should be visible via provider
3643        let committed_result = provider.get::<TestTable>(key).unwrap();
3644        assert_eq!(committed_result, Some(value), "Committed data should be visible");
3645    }
3646
3647    #[test]
3648    fn test_transaction_rollback() {
3649        let temp_dir = TempDir::new().unwrap();
3650        let provider =
3651            RocksDBBuilder::new(temp_dir.path()).with_table::<TestTable>().build().unwrap();
3652
3653        // First, put some initial data
3654        let key = 100u64;
3655        let initial_value = b"initial".to_vec();
3656        provider.put::<TestTable>(key, &initial_value).unwrap();
3657
3658        // Create a transaction and modify data
3659        let tx = provider.tx();
3660        let new_value = b"modified".to_vec();
3661        tx.put::<TestTable>(key, &new_value).unwrap();
3662
3663        // Verify modification is visible within transaction
3664        assert_eq!(tx.get::<TestTable>(key).unwrap(), Some(new_value));
3665
3666        // Rollback instead of commit
3667        tx.rollback().unwrap();
3668
3669        // Data should be unchanged (initial value)
3670        let result = provider.get::<TestTable>(key).unwrap();
3671        assert_eq!(result, Some(initial_value), "Rollback should preserve original data");
3672    }
3673
3674    #[test]
3675    fn test_transaction_iterator() {
3676        let temp_dir = TempDir::new().unwrap();
3677        let provider =
3678            RocksDBBuilder::new(temp_dir.path()).with_table::<TestTable>().build().unwrap();
3679
3680        // Create a transaction
3681        let tx = provider.tx();
3682
3683        // Write multiple entries
3684        for i in 0..5u64 {
3685            let value = format!("value_{i}").into_bytes();
3686            tx.put::<TestTable>(i, &value).unwrap();
3687        }
3688
3689        // Iterate - should see uncommitted writes
3690        let mut count = 0;
3691        for result in tx.iter::<TestTable>().unwrap() {
3692            let (key, value) = result.unwrap();
3693            assert_eq!(value, format!("value_{key}").into_bytes());
3694            count += 1;
3695        }
3696        assert_eq!(count, 5, "Iterator should see all uncommitted writes");
3697
3698        // Commit
3699        tx.commit().unwrap();
3700    }
3701
3702    #[test]
3703    fn test_batch_manual_commit() {
3704        let temp_dir = TempDir::new().unwrap();
3705        let provider =
3706            RocksDBBuilder::new(temp_dir.path()).with_table::<TestTable>().build().unwrap();
3707
3708        // Create a batch via provider.batch()
3709        let mut batch = provider.batch();
3710
3711        // Add entries
3712        for i in 0..10u64 {
3713            let value = format!("batch_value_{i}").into_bytes();
3714            batch.put::<TestTable>(i, &value).unwrap();
3715        }
3716
3717        // Verify len/is_empty
3718        assert_eq!(batch.len(), 10);
3719        assert!(!batch.is_empty());
3720
3721        // Data should NOT be visible before commit
3722        assert_eq!(provider.get::<TestTable>(0).unwrap(), None);
3723
3724        // Commit the batch
3725        batch.commit().unwrap();
3726
3727        // Now data should be visible
3728        for i in 0..10u64 {
3729            let value = format!("batch_value_{i}").into_bytes();
3730            assert_eq!(provider.get::<TestTable>(i).unwrap(), Some(value));
3731        }
3732    }
3733
3734    #[test]
3735    fn test_first_and_last_entry() {
3736        let temp_dir = TempDir::new().unwrap();
3737        let provider =
3738            RocksDBBuilder::new(temp_dir.path()).with_table::<TestTable>().build().unwrap();
3739
3740        // Empty table should return None for both
3741        assert_eq!(provider.first::<TestTable>().unwrap(), None);
3742        assert_eq!(provider.last::<TestTable>().unwrap(), None);
3743
3744        // Insert some entries
3745        provider.put::<TestTable>(10, &b"value_10".to_vec()).unwrap();
3746        provider.put::<TestTable>(20, &b"value_20".to_vec()).unwrap();
3747        provider.put::<TestTable>(5, &b"value_5".to_vec()).unwrap();
3748
3749        // First should return the smallest key
3750        let first = provider.first::<TestTable>().unwrap();
3751        assert_eq!(first, Some((5, b"value_5".to_vec())));
3752
3753        // Last should return the largest key
3754        let last = provider.last::<TestTable>().unwrap();
3755        assert_eq!(last, Some((20, b"value_20".to_vec())));
3756    }
3757
3758    #[test]
3759    fn test_owned_history_snapshot_outlives_provider() {
3760        let temp_dir = TempDir::new().unwrap();
3761        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
3762        let address = Address::repeat_byte(0x42);
3763        let slot = B256::repeat_byte(0x43);
3764        let chunk = IntegerList::new([100, 200, 300]).unwrap();
3765        provider
3766            .put::<tables::AccountsHistory>(ShardedKey::new(address, u64::MAX), &chunk)
3767            .unwrap();
3768        provider
3769            .put::<tables::StoragesHistory>(StorageShardedKey::new(address, slot, u64::MAX), &chunk)
3770            .unwrap();
3771
3772        let owned = provider.owned_snapshot();
3773        let snapshot = owned.as_snapshot();
3774        assert_eq!(
3775            snapshot.account_history_info(address, 200, None, u64::MAX).unwrap(),
3776            HistoryInfo::InChangeset(200)
3777        );
3778        assert_eq!(
3779            snapshot.storage_history_info(address, slot, 200, None, u64::MAX).unwrap(),
3780            HistoryInfo::InChangeset(200)
3781        );
3782        drop(provider);
3783
3784        // Move the owner with populated iterator caches, then seek both forwards and backwards.
3785        std::thread::spawn(move || {
3786            let snapshot = owned.as_snapshot();
3787            for (block, expected) in [
3788                (400, HistoryInfo::InPlainState),
3789                (50, HistoryInfo::NotYetWritten),
3790                (200, HistoryInfo::InChangeset(200)),
3791            ] {
3792                assert_eq!(
3793                    snapshot.account_history_info(address, block, None, u64::MAX).unwrap(),
3794                    expected
3795                );
3796                assert_eq!(
3797                    snapshot.storage_history_info(address, slot, block, None, u64::MAX).unwrap(),
3798                    expected
3799                );
3800            }
3801        })
3802        .join()
3803        .unwrap();
3804    }
3805
3806    #[test]
3807    fn test_history_snapshot_cached_and_private_iterators_keep_same_view() {
3808        let temp_dir = TempDir::new().unwrap();
3809        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
3810        let address = Address::repeat_byte(0x42);
3811        let slot = B256::repeat_byte(0x43);
3812        let account_key = ShardedKey::new(address, u64::MAX);
3813        let storage_key = StorageShardedKey::new(address, slot, u64::MAX);
3814        let chunk = IntegerList::new([100, 200]).unwrap();
3815        provider.put::<tables::AccountsHistory>(account_key.clone(), &chunk).unwrap();
3816        provider.put::<tables::StoragesHistory>(storage_key.clone(), &chunk).unwrap();
3817
3818        let owned = provider.owned_snapshot();
3819        let snapshot = owned.as_snapshot();
3820        let check = |snapshot: &RocksReadSnapshot<'_>, expected| {
3821            assert_eq!(
3822                snapshot.account_history_info(address, 125, None, u64::MAX).unwrap(),
3823                expected
3824            );
3825            assert_eq!(
3826                snapshot.storage_history_info(address, slot, 125, None, u64::MAX).unwrap(),
3827                expected
3828            );
3829        };
3830        check(snapshot, HistoryInfo::InChangeset(200));
3831
3832        let updated = IntegerList::new([100, 150, 200]).unwrap();
3833        provider.put::<tables::AccountsHistory>(account_key, &updated).unwrap();
3834        provider.put::<tables::StoragesHistory>(storage_key, &updated).unwrap();
3835        check(&provider.snapshot(), HistoryInfo::InChangeset(150));
3836        check(snapshot, HistoryInfo::InChangeset(200));
3837
3838        // Force another thread to use private iterators after the database has changed.
3839        let _accounts = snapshot.accounts_history_iter.lock();
3840        let _storages = snapshot.storages_history_iter.lock();
3841        std::thread::scope(|scope| {
3842            scope.spawn(|| check(snapshot, HistoryInfo::InChangeset(200))).join().unwrap();
3843        });
3844    }
3845
3846    /// Tests the edge case where block < `lowest_available_block_number`.
3847    ///
3848    /// State queries reject this before the `RocksDB` lookup, so this verifies the low-level
3849    /// behavior directly.
3850    #[test]
3851    fn test_account_history_info_pruned_before_first_entry() {
3852        let temp_dir = TempDir::new().unwrap();
3853        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
3854
3855        let address = Address::repeat_byte(0x42);
3856
3857        // Create a single shard starting at block 100
3858        let chunk = IntegerList::new([100, 200, 300]).unwrap();
3859        let shard_key = ShardedKey::new(address, u64::MAX);
3860        provider.put::<tables::AccountsHistory>(shard_key, &chunk).unwrap();
3861
3862        // Query for block 50 with lowest_available_block_number = 100
3863        // This simulates a pruned state where data before block 100 is not available.
3864        // Since we're before the first write AND pruning boundary is set, we need to
3865        // check the changeset at the first write block.
3866        let result =
3867            provider.snapshot().account_history_info(address, 50, Some(100), u64::MAX).unwrap();
3868        assert_eq!(result, HistoryInfo::InChangeset(100));
3869    }
3870
3871    /// Verifies that a read-only (secondary) provider can catch up with primary writes.
3872    #[test]
3873    fn test_account_history_info_read_only_and_catch_up() {
3874        let temp_dir = TempDir::new().unwrap();
3875        let address = Address::repeat_byte(0x42);
3876        let chunk = IntegerList::new([100, 200, 300]).unwrap();
3877        let shard_key = ShardedKey::new(address, u64::MAX);
3878
3879        // Write data with a read-write provider
3880        let rw_provider =
3881            RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
3882        rw_provider.put::<tables::AccountsHistory>(shard_key, &chunk).unwrap();
3883
3884        // Open read-only provider — it sees the initial data.
3885        let ro_provider = RocksDBBuilder::new(temp_dir.path())
3886            .with_default_tables()
3887            .with_read_only(true)
3888            .build()
3889            .unwrap();
3890
3891        let result =
3892            ro_provider.snapshot().account_history_info(address, 200, None, u64::MAX).unwrap();
3893        assert_eq!(result, HistoryInfo::InChangeset(200));
3894
3895        let result =
3896            ro_provider.snapshot().account_history_info(address, 50, None, u64::MAX).unwrap();
3897        assert_eq!(result, HistoryInfo::NotYetWritten);
3898
3899        let result =
3900            ro_provider.snapshot().account_history_info(address, 400, None, u64::MAX).unwrap();
3901        assert_eq!(result, HistoryInfo::InPlainState);
3902
3903        // Write new data via the primary.
3904        let address2 = Address::repeat_byte(0x43);
3905        let chunk2 = IntegerList::new([500, 600]).unwrap();
3906        let shard_key2 = ShardedKey::new(address2, u64::MAX);
3907        rw_provider.put::<tables::AccountsHistory>(shard_key2, &chunk2).unwrap();
3908
3909        // Read-only doesn't see the new data yet.
3910        let result =
3911            ro_provider.snapshot().account_history_info(address2, 500, None, u64::MAX).unwrap();
3912        assert_eq!(result, HistoryInfo::NotYetWritten);
3913
3914        // Catch up — now it sees the new data.
3915        ro_provider.try_catch_up_with_primary().unwrap();
3916
3917        let result =
3918            ro_provider.snapshot().account_history_info(address2, 500, None, u64::MAX).unwrap();
3919        assert_eq!(result, HistoryInfo::InChangeset(500));
3920    }
3921
3922    #[test]
3923    fn test_account_history_info_ignores_blocks_above_visible_tip() {
3924        let temp_dir = TempDir::new().unwrap();
3925        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
3926
3927        let address = Address::repeat_byte(0x42);
3928
3929        provider
3930            .put::<tables::AccountsHistory>(
3931                ShardedKey::new(address, 110),
3932                &IntegerList::new([100, 110]).unwrap(),
3933            )
3934            .unwrap();
3935        provider
3936            .put::<tables::AccountsHistory>(
3937                ShardedKey::new(address, u64::MAX),
3938                &IntegerList::new([200, 210]).unwrap(),
3939            )
3940            .unwrap();
3941
3942        let result = provider.snapshot().account_history_info(address, 150, None, 150).unwrap();
3943        assert_eq!(result, HistoryInfo::InPlainState);
3944    }
3945
3946    #[test]
3947    fn test_account_history_info_mixed_shard_respects_visible_tip() {
3948        let temp_dir = TempDir::new().unwrap();
3949        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
3950
3951        let address = Address::repeat_byte(0x42);
3952        provider
3953            .put::<tables::AccountsHistory>(
3954                ShardedKey::new(address, u64::MAX),
3955                &IntegerList::new([100, 150, 300]).unwrap(),
3956            )
3957            .unwrap();
3958
3959        let result = provider.snapshot().account_history_info(address, 120, None, 200).unwrap();
3960        assert_eq!(result, HistoryInfo::InChangeset(150));
3961
3962        let result = provider.snapshot().account_history_info(address, 201, None, 200).unwrap();
3963        assert_eq!(result, HistoryInfo::InPlainState);
3964    }
3965
3966    #[test]
3967    fn test_account_history_info_only_stale_entries_use_fallback() {
3968        let temp_dir = TempDir::new().unwrap();
3969        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
3970
3971        let address = Address::repeat_byte(0x42);
3972        provider
3973            .put::<tables::AccountsHistory>(
3974                ShardedKey::new(address, u64::MAX),
3975                &IntegerList::new([200, 210]).unwrap(),
3976            )
3977            .unwrap();
3978
3979        let result = provider.snapshot().account_history_info(address, 150, None, 150).unwrap();
3980        assert_eq!(result, HistoryInfo::NotYetWritten);
3981
3982        let result =
3983            provider.snapshot().account_history_info(address, 150, Some(100), 150).unwrap();
3984        assert_eq!(result, HistoryInfo::MaybeInPlainState);
3985    }
3986
3987    #[test]
3988    fn test_account_history_shard_split_at_boundary() {
3989        let temp_dir = TempDir::new().unwrap();
3990        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
3991
3992        let address = Address::repeat_byte(0x42);
3993        let limit = NUM_OF_INDICES_IN_SHARD;
3994
3995        // Add exactly NUM_OF_INDICES_IN_SHARD + 1 indices to trigger a split
3996        let indices: Vec<u64> = (0..=(limit as u64)).collect();
3997        let mut batch = provider.batch();
3998        batch.append_account_history_shard(address, indices).unwrap();
3999        batch.commit().unwrap();
4000
4001        // Should have 2 shards: one completed shard and one sentinel shard
4002        let completed_key = ShardedKey::new(address, (limit - 1) as u64);
4003        let sentinel_key = ShardedKey::new(address, u64::MAX);
4004
4005        let completed_shard = provider.get::<tables::AccountsHistory>(completed_key).unwrap();
4006        let sentinel_shard = provider.get::<tables::AccountsHistory>(sentinel_key).unwrap();
4007
4008        assert!(completed_shard.is_some(), "completed shard should exist");
4009        assert!(sentinel_shard.is_some(), "sentinel shard should exist");
4010
4011        let completed_shard = completed_shard.unwrap();
4012        let sentinel_shard = sentinel_shard.unwrap();
4013
4014        assert_eq!(completed_shard.len(), limit as u64, "completed shard should be full");
4015        assert_eq!(sentinel_shard.len(), 1, "sentinel shard should have 1 element");
4016    }
4017
4018    #[test]
4019    fn test_account_history_multiple_shard_splits() {
4020        let temp_dir = TempDir::new().unwrap();
4021        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4022
4023        let address = Address::repeat_byte(0x43);
4024        let limit = NUM_OF_INDICES_IN_SHARD;
4025
4026        // First batch: add NUM_OF_INDICES_IN_SHARD indices
4027        let first_batch_indices: Vec<u64> = (0..limit as u64).collect();
4028        let mut batch = provider.batch();
4029        batch.append_account_history_shard(address, first_batch_indices).unwrap();
4030        batch.commit().unwrap();
4031
4032        // Should have just a sentinel shard (exactly at limit, not over)
4033        let sentinel_key = ShardedKey::new(address, u64::MAX);
4034        let shard = provider.get::<tables::AccountsHistory>(sentinel_key.clone()).unwrap();
4035        assert!(shard.is_some());
4036        assert_eq!(shard.unwrap().len(), limit as u64);
4037
4038        // Second batch: add another NUM_OF_INDICES_IN_SHARD + 1 indices (causing 2 more shards)
4039        let second_batch_indices: Vec<u64> = (limit as u64..=(2 * limit) as u64).collect();
4040        let mut batch = provider.batch();
4041        batch.append_account_history_shard(address, second_batch_indices).unwrap();
4042        batch.commit().unwrap();
4043
4044        // Now we should have: 2 completed shards + 1 sentinel shard
4045        let first_completed = ShardedKey::new(address, (limit - 1) as u64);
4046        let second_completed = ShardedKey::new(address, (2 * limit - 1) as u64);
4047
4048        assert!(
4049            provider.get::<tables::AccountsHistory>(first_completed).unwrap().is_some(),
4050            "first completed shard should exist"
4051        );
4052        assert!(
4053            provider.get::<tables::AccountsHistory>(second_completed).unwrap().is_some(),
4054            "second completed shard should exist"
4055        );
4056        assert!(
4057            provider.get::<tables::AccountsHistory>(sentinel_key).unwrap().is_some(),
4058            "sentinel shard should exist"
4059        );
4060    }
4061
4062    #[test]
4063    fn test_storage_history_shard_split_at_boundary() {
4064        let temp_dir = TempDir::new().unwrap();
4065        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4066
4067        let address = Address::repeat_byte(0x44);
4068        let slot = B256::repeat_byte(0x55);
4069        let limit = NUM_OF_INDICES_IN_SHARD;
4070
4071        // Add exactly NUM_OF_INDICES_IN_SHARD + 1 indices to trigger a split
4072        let indices: Vec<u64> = (0..=(limit as u64)).collect();
4073        let mut batch = provider.batch();
4074        batch.append_storage_history_shard(address, slot, indices).unwrap();
4075        batch.commit().unwrap();
4076
4077        // Should have 2 shards: one completed shard and one sentinel shard
4078        let completed_key = StorageShardedKey::new(address, slot, (limit - 1) as u64);
4079        let sentinel_key = StorageShardedKey::new(address, slot, u64::MAX);
4080
4081        let completed_shard = provider.get::<tables::StoragesHistory>(completed_key).unwrap();
4082        let sentinel_shard = provider.get::<tables::StoragesHistory>(sentinel_key).unwrap();
4083
4084        assert!(completed_shard.is_some(), "completed shard should exist");
4085        assert!(sentinel_shard.is_some(), "sentinel shard should exist");
4086
4087        let completed_shard = completed_shard.unwrap();
4088        let sentinel_shard = sentinel_shard.unwrap();
4089
4090        assert_eq!(completed_shard.len(), limit as u64, "completed shard should be full");
4091        assert_eq!(sentinel_shard.len(), 1, "sentinel shard should have 1 element");
4092    }
4093
4094    #[test]
4095    fn test_storage_history_multiple_shard_splits() {
4096        let temp_dir = TempDir::new().unwrap();
4097        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4098
4099        let address = Address::repeat_byte(0x46);
4100        let slot = B256::repeat_byte(0x57);
4101        let limit = NUM_OF_INDICES_IN_SHARD;
4102
4103        // First batch: add NUM_OF_INDICES_IN_SHARD indices
4104        let first_batch_indices: Vec<u64> = (0..limit as u64).collect();
4105        let mut batch = provider.batch();
4106        batch.append_storage_history_shard(address, slot, first_batch_indices).unwrap();
4107        batch.commit().unwrap();
4108
4109        // Should have just a sentinel shard (exactly at limit, not over)
4110        let sentinel_key = StorageShardedKey::new(address, slot, u64::MAX);
4111        let shard = provider.get::<tables::StoragesHistory>(sentinel_key.clone()).unwrap();
4112        assert!(shard.is_some());
4113        assert_eq!(shard.unwrap().len(), limit as u64);
4114
4115        // Second batch: add another NUM_OF_INDICES_IN_SHARD + 1 indices (causing 2 more shards)
4116        let second_batch_indices: Vec<u64> = (limit as u64..=(2 * limit) as u64).collect();
4117        let mut batch = provider.batch();
4118        batch.append_storage_history_shard(address, slot, second_batch_indices).unwrap();
4119        batch.commit().unwrap();
4120
4121        // Now we should have: 2 completed shards + 1 sentinel shard
4122        let first_completed = StorageShardedKey::new(address, slot, (limit - 1) as u64);
4123        let second_completed = StorageShardedKey::new(address, slot, (2 * limit - 1) as u64);
4124
4125        assert!(
4126            provider.get::<tables::StoragesHistory>(first_completed).unwrap().is_some(),
4127            "first completed shard should exist"
4128        );
4129        assert!(
4130            provider.get::<tables::StoragesHistory>(second_completed).unwrap().is_some(),
4131            "second completed shard should exist"
4132        );
4133        assert!(
4134            provider.get::<tables::StoragesHistory>(sentinel_key).unwrap().is_some(),
4135            "sentinel shard should exist"
4136        );
4137    }
4138
4139    #[test]
4140    fn test_clear_table() {
4141        let temp_dir = TempDir::new().unwrap();
4142        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4143
4144        let address = Address::repeat_byte(0x42);
4145        let key = ShardedKey::new(address, u64::MAX);
4146        let blocks = BlockNumberList::new_pre_sorted([1, 2, 3]);
4147
4148        provider.put::<tables::AccountsHistory>(key.clone(), &blocks).unwrap();
4149        assert!(provider.get::<tables::AccountsHistory>(key.clone()).unwrap().is_some());
4150
4151        provider.clear::<tables::AccountsHistory>().unwrap();
4152
4153        assert!(
4154            provider.get::<tables::AccountsHistory>(key).unwrap().is_none(),
4155            "table should be empty after clear"
4156        );
4157        assert!(
4158            provider.first::<tables::AccountsHistory>().unwrap().is_none(),
4159            "first() should return None after clear"
4160        );
4161    }
4162
4163    #[test]
4164    fn test_clear_empty_table() {
4165        let temp_dir = TempDir::new().unwrap();
4166        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4167
4168        assert!(provider.first::<tables::AccountsHistory>().unwrap().is_none());
4169
4170        provider.clear::<tables::AccountsHistory>().unwrap();
4171
4172        assert!(provider.first::<tables::AccountsHistory>().unwrap().is_none());
4173    }
4174
4175    #[test]
4176    fn test_unwind_account_history_to_basic() {
4177        let temp_dir = TempDir::new().unwrap();
4178        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4179
4180        let address = Address::repeat_byte(0x42);
4181
4182        // Add blocks 0-10
4183        let mut batch = provider.batch();
4184        batch.append_account_history_shard(address, 0..=10).unwrap();
4185        batch.commit().unwrap();
4186
4187        // Verify we have blocks 0-10
4188        let key = ShardedKey::new(address, u64::MAX);
4189        let result = provider.get::<tables::AccountsHistory>(key.clone()).unwrap();
4190        assert!(result.is_some());
4191        let blocks: Vec<u64> = result.unwrap().iter().collect();
4192        assert_eq!(blocks, (0..=10).collect::<Vec<_>>());
4193
4194        // Unwind to block 5 (keep blocks 0-5, remove 6-10)
4195        let mut batch = provider.batch();
4196        batch.unwind_account_history_to(address, 5).unwrap();
4197        batch.commit().unwrap();
4198
4199        // Verify only blocks 0-5 remain
4200        let result = provider.get::<tables::AccountsHistory>(key).unwrap();
4201        assert!(result.is_some());
4202        let blocks: Vec<u64> = result.unwrap().iter().collect();
4203        assert_eq!(blocks, (0..=5).collect::<Vec<_>>());
4204    }
4205
4206    #[test]
4207    fn test_unwind_account_history_to_removes_all() {
4208        let temp_dir = TempDir::new().unwrap();
4209        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4210
4211        let address = Address::repeat_byte(0x42);
4212
4213        // Add blocks 5-10
4214        let mut batch = provider.batch();
4215        batch.append_account_history_shard(address, 5..=10).unwrap();
4216        batch.commit().unwrap();
4217
4218        // Unwind to block 4 (removes all blocks since they're all > 4)
4219        let mut batch = provider.batch();
4220        batch.unwind_account_history_to(address, 4).unwrap();
4221        batch.commit().unwrap();
4222
4223        // Verify no data remains for this address
4224        let key = ShardedKey::new(address, u64::MAX);
4225        let result = provider.get::<tables::AccountsHistory>(key).unwrap();
4226        assert!(result.is_none(), "Should have no data after full unwind");
4227    }
4228
4229    #[test]
4230    fn test_unwind_account_history_to_no_op() {
4231        let temp_dir = TempDir::new().unwrap();
4232        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4233
4234        let address = Address::repeat_byte(0x42);
4235
4236        // Add blocks 0-5
4237        let mut batch = provider.batch();
4238        batch.append_account_history_shard(address, 0..=5).unwrap();
4239        batch.commit().unwrap();
4240
4241        // Unwind to block 10 (no-op since all blocks are <= 10)
4242        let mut batch = provider.batch();
4243        batch.unwind_account_history_to(address, 10).unwrap();
4244        batch.commit().unwrap();
4245
4246        // Verify blocks 0-5 still remain
4247        let key = ShardedKey::new(address, u64::MAX);
4248        let result = provider.get::<tables::AccountsHistory>(key).unwrap();
4249        assert!(result.is_some());
4250        let blocks: Vec<u64> = result.unwrap().iter().collect();
4251        assert_eq!(blocks, (0..=5).collect::<Vec<_>>());
4252    }
4253
4254    #[test]
4255    fn test_unwind_account_history_to_block_zero() {
4256        let temp_dir = TempDir::new().unwrap();
4257        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4258
4259        let address = Address::repeat_byte(0x42);
4260
4261        // Add blocks 0-5 (including block 0)
4262        let mut batch = provider.batch();
4263        batch.append_account_history_shard(address, 0..=5).unwrap();
4264        batch.commit().unwrap();
4265
4266        // Unwind to block 0 (keep only block 0, remove 1-5)
4267        // This simulates the caller doing: unwind_to = min_block.checked_sub(1) where min_block = 1
4268        let mut batch = provider.batch();
4269        batch.unwind_account_history_to(address, 0).unwrap();
4270        batch.commit().unwrap();
4271
4272        // Verify only block 0 remains
4273        let key = ShardedKey::new(address, u64::MAX);
4274        let result = provider.get::<tables::AccountsHistory>(key).unwrap();
4275        assert!(result.is_some());
4276        let blocks: Vec<u64> = result.unwrap().iter().collect();
4277        assert_eq!(blocks, vec![0]);
4278    }
4279
4280    #[test]
4281    fn test_unwind_account_history_to_multi_shard() {
4282        let temp_dir = TempDir::new().unwrap();
4283        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4284
4285        let address = Address::repeat_byte(0x42);
4286
4287        // Create multiple shards by adding more than NUM_OF_INDICES_IN_SHARD entries
4288        // For testing, we'll manually create shards with specific keys
4289        let mut batch = provider.batch();
4290
4291        // First shard: blocks 1-50, keyed by 50
4292        let shard1 = BlockNumberList::new_pre_sorted(1..=50);
4293        batch.put::<tables::AccountsHistory>(ShardedKey::new(address, 50), &shard1).unwrap();
4294
4295        // Second shard: blocks 51-100, keyed by MAX (sentinel)
4296        let shard2 = BlockNumberList::new_pre_sorted(51..=100);
4297        batch.put::<tables::AccountsHistory>(ShardedKey::new(address, u64::MAX), &shard2).unwrap();
4298
4299        batch.commit().unwrap();
4300
4301        // Verify we have 2 shards
4302        let shards = provider.account_history_shards(address).unwrap();
4303        assert_eq!(shards.len(), 2);
4304
4305        // Unwind to block 75 (keep 1-75, remove 76-100)
4306        let mut batch = provider.batch();
4307        batch.unwind_account_history_to(address, 75).unwrap();
4308        batch.commit().unwrap();
4309
4310        // Verify: shard1 should be untouched, shard2 should be truncated
4311        let shards = provider.account_history_shards(address).unwrap();
4312        assert_eq!(shards.len(), 2);
4313
4314        // First shard unchanged
4315        assert_eq!(shards[0].0.highest_block_number, 50);
4316        assert_eq!(shards[0].1.iter().collect::<Vec<_>>(), (1..=50).collect::<Vec<_>>());
4317
4318        // Second shard truncated and re-keyed to MAX
4319        assert_eq!(shards[1].0.highest_block_number, u64::MAX);
4320        assert_eq!(shards[1].1.iter().collect::<Vec<_>>(), (51..=75).collect::<Vec<_>>());
4321    }
4322
4323    #[test]
4324    fn test_unwind_account_history_to_multi_shard_boundary_empty() {
4325        let temp_dir = TempDir::new().unwrap();
4326        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4327
4328        let address = Address::repeat_byte(0x42);
4329
4330        // Create two shards
4331        let mut batch = provider.batch();
4332
4333        // First shard: blocks 1-50, keyed by 50
4334        let shard1 = BlockNumberList::new_pre_sorted(1..=50);
4335        batch.put::<tables::AccountsHistory>(ShardedKey::new(address, 50), &shard1).unwrap();
4336
4337        // Second shard: blocks 75-100, keyed by MAX
4338        let shard2 = BlockNumberList::new_pre_sorted(75..=100);
4339        batch.put::<tables::AccountsHistory>(ShardedKey::new(address, u64::MAX), &shard2).unwrap();
4340
4341        batch.commit().unwrap();
4342
4343        // Unwind to block 60 (removes all of shard2 since 75 > 60, promotes shard1 to MAX)
4344        let mut batch = provider.batch();
4345        batch.unwind_account_history_to(address, 60).unwrap();
4346        batch.commit().unwrap();
4347
4348        // Verify: only shard1 remains, now keyed as MAX
4349        let shards = provider.account_history_shards(address).unwrap();
4350        assert_eq!(shards.len(), 1);
4351        assert_eq!(shards[0].0.highest_block_number, u64::MAX);
4352        assert_eq!(shards[0].1.iter().collect::<Vec<_>>(), (1..=50).collect::<Vec<_>>());
4353    }
4354
4355    #[test]
4356    fn test_account_history_shards_iterator() {
4357        let temp_dir = TempDir::new().unwrap();
4358        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4359
4360        let address = Address::repeat_byte(0x42);
4361        let other_address = Address::repeat_byte(0x43);
4362
4363        // Add data for two addresses
4364        let mut batch = provider.batch();
4365        batch.append_account_history_shard(address, 0..=5).unwrap();
4366        batch.append_account_history_shard(other_address, 10..=15).unwrap();
4367        batch.commit().unwrap();
4368
4369        // Query shards for first address only
4370        let shards = provider.account_history_shards(address).unwrap();
4371        assert_eq!(shards.len(), 1);
4372        assert_eq!(shards[0].0.key, address);
4373
4374        // Query shards for second address only
4375        let shards = provider.account_history_shards(other_address).unwrap();
4376        assert_eq!(shards.len(), 1);
4377        assert_eq!(shards[0].0.key, other_address);
4378
4379        // Query shards for non-existent address
4380        let non_existent = Address::repeat_byte(0x99);
4381        let shards = provider.account_history_shards(non_existent).unwrap();
4382        assert!(shards.is_empty());
4383    }
4384
4385    #[test]
4386    fn test_clear_account_history() {
4387        let temp_dir = TempDir::new().unwrap();
4388        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4389
4390        let address = Address::repeat_byte(0x42);
4391
4392        // Add blocks 0-10
4393        let mut batch = provider.batch();
4394        batch.append_account_history_shard(address, 0..=10).unwrap();
4395        batch.commit().unwrap();
4396
4397        // Clear all history (simulates unwind from block 0)
4398        let mut batch = provider.batch();
4399        batch.clear_account_history(address).unwrap();
4400        batch.commit().unwrap();
4401
4402        // Verify no data remains
4403        let shards = provider.account_history_shards(address).unwrap();
4404        assert!(shards.is_empty(), "All shards should be deleted");
4405    }
4406
4407    #[test]
4408    fn test_unwind_non_sentinel_boundary() {
4409        let temp_dir = TempDir::new().unwrap();
4410        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4411
4412        let address = Address::repeat_byte(0x42);
4413
4414        // Create three shards with non-sentinel boundary
4415        let mut batch = provider.batch();
4416
4417        // Shard 1: blocks 1-50, keyed by 50
4418        let shard1 = BlockNumberList::new_pre_sorted(1..=50);
4419        batch.put::<tables::AccountsHistory>(ShardedKey::new(address, 50), &shard1).unwrap();
4420
4421        // Shard 2: blocks 51-100, keyed by 100 (non-sentinel, will be boundary)
4422        let shard2 = BlockNumberList::new_pre_sorted(51..=100);
4423        batch.put::<tables::AccountsHistory>(ShardedKey::new(address, 100), &shard2).unwrap();
4424
4425        // Shard 3: blocks 101-150, keyed by MAX (will be deleted)
4426        let shard3 = BlockNumberList::new_pre_sorted(101..=150);
4427        batch.put::<tables::AccountsHistory>(ShardedKey::new(address, u64::MAX), &shard3).unwrap();
4428
4429        batch.commit().unwrap();
4430
4431        // Verify 3 shards
4432        let shards = provider.account_history_shards(address).unwrap();
4433        assert_eq!(shards.len(), 3);
4434
4435        // Unwind to block 75 (truncates shard2, deletes shard3)
4436        let mut batch = provider.batch();
4437        batch.unwind_account_history_to(address, 75).unwrap();
4438        batch.commit().unwrap();
4439
4440        // Verify: shard1 unchanged, shard2 truncated and re-keyed to MAX, shard3 deleted
4441        let shards = provider.account_history_shards(address).unwrap();
4442        assert_eq!(shards.len(), 2);
4443
4444        // First shard unchanged
4445        assert_eq!(shards[0].0.highest_block_number, 50);
4446        assert_eq!(shards[0].1.iter().collect::<Vec<_>>(), (1..=50).collect::<Vec<_>>());
4447
4448        // Second shard truncated and re-keyed to MAX
4449        assert_eq!(shards[1].0.highest_block_number, u64::MAX);
4450        assert_eq!(shards[1].1.iter().collect::<Vec<_>>(), (51..=75).collect::<Vec<_>>());
4451    }
4452
4453    #[test]
4454    fn test_batch_auto_commit_on_threshold() {
4455        let temp_dir = TempDir::new().unwrap();
4456        let provider =
4457            RocksDBBuilder::new(temp_dir.path()).with_table::<TestTable>().build().unwrap();
4458
4459        // Create batch with tiny threshold (1KB) to force auto-commits
4460        let mut batch = RocksDBBatch {
4461            provider: &provider,
4462            inner: WriteBatchWithTransaction::<true>::default(),
4463            buf: Vec::new(),
4464            auto_commit_threshold: Some(1024), // 1KB
4465        };
4466
4467        // Write entries until we exceed threshold multiple times
4468        // Each entry is ~20 bytes, so 100 entries = ~2KB = 2 auto-commits
4469        for i in 0..100u64 {
4470            let value = format!("value_{i:04}").into_bytes();
4471            batch.put::<TestTable>(i, &value).unwrap();
4472        }
4473
4474        // Data should already be visible (auto-committed) even before final commit
4475        // At least some entries should be readable
4476        let first_visible = provider.get::<TestTable>(0).unwrap();
4477        assert!(first_visible.is_some(), "Auto-committed data should be visible");
4478
4479        // Final commit for remaining batch
4480        batch.commit().unwrap();
4481
4482        // All entries should now be visible
4483        for i in 0..100u64 {
4484            let value = format!("value_{i:04}").into_bytes();
4485            assert_eq!(provider.get::<TestTable>(i).unwrap(), Some(value));
4486        }
4487    }
4488
4489    // ==================== PARAMETERIZED PRUNE TESTS ====================
4490
4491    /// Test case for account history pruning
4492    struct AccountPruneCase {
4493        name: &'static str,
4494        initial_shards: &'static [(u64, &'static [u64])],
4495        prune_to: u64,
4496        expected_outcome: PruneShardOutcome,
4497        expected_shards: &'static [(u64, &'static [u64])],
4498    }
4499
4500    /// Test case for storage history pruning
4501    struct StoragePruneCase {
4502        name: &'static str,
4503        initial_shards: &'static [(u64, &'static [u64])],
4504        prune_to: u64,
4505        expected_outcome: PruneShardOutcome,
4506        expected_shards: &'static [(u64, &'static [u64])],
4507    }
4508
4509    #[test]
4510    fn test_prune_account_history_cases() {
4511        const MAX: u64 = u64::MAX;
4512        const CASES: &[AccountPruneCase] = &[
4513            AccountPruneCase {
4514                name: "single_shard_truncate",
4515                initial_shards: &[(MAX, &[10, 20, 30, 40])],
4516                prune_to: 25,
4517                expected_outcome: PruneShardOutcome::Updated,
4518                expected_shards: &[(MAX, &[30, 40])],
4519            },
4520            AccountPruneCase {
4521                name: "single_shard_delete_all",
4522                initial_shards: &[(MAX, &[10, 20])],
4523                prune_to: 20,
4524                expected_outcome: PruneShardOutcome::Deleted,
4525                expected_shards: &[],
4526            },
4527            AccountPruneCase {
4528                name: "single_shard_noop",
4529                initial_shards: &[(MAX, &[10, 20])],
4530                prune_to: 5,
4531                expected_outcome: PruneShardOutcome::Unchanged,
4532                expected_shards: &[(MAX, &[10, 20])],
4533            },
4534            AccountPruneCase {
4535                name: "no_shards",
4536                initial_shards: &[],
4537                prune_to: 100,
4538                expected_outcome: PruneShardOutcome::Unchanged,
4539                expected_shards: &[],
4540            },
4541            AccountPruneCase {
4542                name: "multi_shard_truncate_first",
4543                initial_shards: &[(30, &[10, 20, 30]), (MAX, &[40, 50, 60])],
4544                prune_to: 25,
4545                expected_outcome: PruneShardOutcome::Updated,
4546                expected_shards: &[(30, &[30]), (MAX, &[40, 50, 60])],
4547            },
4548            AccountPruneCase {
4549                name: "delete_first_shard_sentinel_unchanged",
4550                initial_shards: &[(20, &[10, 20]), (MAX, &[30, 40])],
4551                prune_to: 20,
4552                expected_outcome: PruneShardOutcome::Deleted,
4553                expected_shards: &[(MAX, &[30, 40])],
4554            },
4555            AccountPruneCase {
4556                name: "multi_shard_delete_all_but_last",
4557                initial_shards: &[(10, &[5, 10]), (20, &[15, 20]), (MAX, &[25, 30])],
4558                prune_to: 22,
4559                expected_outcome: PruneShardOutcome::Deleted,
4560                expected_shards: &[(MAX, &[25, 30])],
4561            },
4562            AccountPruneCase {
4563                name: "mid_shard_preserves_key",
4564                initial_shards: &[(50, &[10, 20, 30, 40, 50]), (MAX, &[60, 70])],
4565                prune_to: 25,
4566                expected_outcome: PruneShardOutcome::Updated,
4567                expected_shards: &[(50, &[30, 40, 50]), (MAX, &[60, 70])],
4568            },
4569            // Equivalence tests
4570            AccountPruneCase {
4571                name: "equiv_delete_early_shards_keep_sentinel",
4572                initial_shards: &[(20, &[10, 15, 20]), (50, &[30, 40, 50]), (MAX, &[60, 70])],
4573                prune_to: 55,
4574                expected_outcome: PruneShardOutcome::Deleted,
4575                expected_shards: &[(MAX, &[60, 70])],
4576            },
4577            AccountPruneCase {
4578                name: "equiv_sentinel_becomes_empty_with_prev",
4579                initial_shards: &[(50, &[30, 40, 50]), (MAX, &[35])],
4580                prune_to: 40,
4581                expected_outcome: PruneShardOutcome::Deleted,
4582                expected_shards: &[(MAX, &[50])],
4583            },
4584            AccountPruneCase {
4585                name: "equiv_all_shards_become_empty",
4586                initial_shards: &[(50, &[30, 40, 50]), (MAX, &[51])],
4587                prune_to: 51,
4588                expected_outcome: PruneShardOutcome::Deleted,
4589                expected_shards: &[],
4590            },
4591            AccountPruneCase {
4592                name: "equiv_non_sentinel_last_shard_promoted",
4593                initial_shards: &[(100, &[50, 75, 100])],
4594                prune_to: 60,
4595                expected_outcome: PruneShardOutcome::Updated,
4596                expected_shards: &[(MAX, &[75, 100])],
4597            },
4598            AccountPruneCase {
4599                name: "equiv_filter_within_shard",
4600                initial_shards: &[(MAX, &[10, 20, 30, 40])],
4601                prune_to: 25,
4602                expected_outcome: PruneShardOutcome::Updated,
4603                expected_shards: &[(MAX, &[30, 40])],
4604            },
4605            AccountPruneCase {
4606                name: "equiv_multi_shard_partial_delete",
4607                initial_shards: &[(20, &[10, 20]), (50, &[30, 40, 50]), (MAX, &[60, 70])],
4608                prune_to: 35,
4609                expected_outcome: PruneShardOutcome::Deleted,
4610                expected_shards: &[(50, &[40, 50]), (MAX, &[60, 70])],
4611            },
4612        ];
4613
4614        let address = Address::repeat_byte(0x42);
4615
4616        for case in CASES {
4617            let temp_dir = TempDir::new().unwrap();
4618            let provider =
4619                RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4620
4621            // Setup initial shards
4622            let mut batch = provider.batch();
4623            for (highest, blocks) in case.initial_shards {
4624                let shard = BlockNumberList::new_pre_sorted(blocks.iter().copied());
4625                batch
4626                    .put::<tables::AccountsHistory>(ShardedKey::new(address, *highest), &shard)
4627                    .unwrap();
4628            }
4629            batch.commit().unwrap();
4630
4631            // Prune
4632            let mut batch = provider.batch();
4633            let outcome = batch.prune_account_history_to(address, case.prune_to).unwrap();
4634            batch.commit().unwrap();
4635
4636            // Assert outcome
4637            assert_eq!(outcome, case.expected_outcome, "case '{}': wrong outcome", case.name);
4638
4639            // Assert final shards
4640            let shards = provider.account_history_shards(address).unwrap();
4641            assert_eq!(
4642                shards.len(),
4643                case.expected_shards.len(),
4644                "case '{}': wrong shard count",
4645                case.name
4646            );
4647            for (i, ((key, blocks), (exp_key, exp_blocks))) in
4648                shards.iter().zip(case.expected_shards.iter()).enumerate()
4649            {
4650                assert_eq!(
4651                    key.highest_block_number, *exp_key,
4652                    "case '{}': shard {} wrong key",
4653                    case.name, i
4654                );
4655                assert_eq!(
4656                    blocks.iter().collect::<Vec<_>>(),
4657                    *exp_blocks,
4658                    "case '{}': shard {} wrong blocks",
4659                    case.name,
4660                    i
4661                );
4662            }
4663        }
4664    }
4665
4666    #[test]
4667    fn test_prune_storage_history_cases() {
4668        const MAX: u64 = u64::MAX;
4669        const CASES: &[StoragePruneCase] = &[
4670            StoragePruneCase {
4671                name: "single_shard_truncate",
4672                initial_shards: &[(MAX, &[10, 20, 30, 40])],
4673                prune_to: 25,
4674                expected_outcome: PruneShardOutcome::Updated,
4675                expected_shards: &[(MAX, &[30, 40])],
4676            },
4677            StoragePruneCase {
4678                name: "single_shard_delete_all",
4679                initial_shards: &[(MAX, &[10, 20])],
4680                prune_to: 20,
4681                expected_outcome: PruneShardOutcome::Deleted,
4682                expected_shards: &[],
4683            },
4684            StoragePruneCase {
4685                name: "noop",
4686                initial_shards: &[(MAX, &[10, 20])],
4687                prune_to: 5,
4688                expected_outcome: PruneShardOutcome::Unchanged,
4689                expected_shards: &[(MAX, &[10, 20])],
4690            },
4691            StoragePruneCase {
4692                name: "no_shards",
4693                initial_shards: &[],
4694                prune_to: 100,
4695                expected_outcome: PruneShardOutcome::Unchanged,
4696                expected_shards: &[],
4697            },
4698            StoragePruneCase {
4699                name: "mid_shard_preserves_key",
4700                initial_shards: &[(50, &[10, 20, 30, 40, 50]), (MAX, &[60, 70])],
4701                prune_to: 25,
4702                expected_outcome: PruneShardOutcome::Updated,
4703                expected_shards: &[(50, &[30, 40, 50]), (MAX, &[60, 70])],
4704            },
4705            // Equivalence tests
4706            StoragePruneCase {
4707                name: "equiv_sentinel_promotion",
4708                initial_shards: &[(100, &[50, 75, 100])],
4709                prune_to: 60,
4710                expected_outcome: PruneShardOutcome::Updated,
4711                expected_shards: &[(MAX, &[75, 100])],
4712            },
4713            StoragePruneCase {
4714                name: "equiv_delete_early_shards_keep_sentinel",
4715                initial_shards: &[(20, &[10, 15, 20]), (50, &[30, 40, 50]), (MAX, &[60, 70])],
4716                prune_to: 55,
4717                expected_outcome: PruneShardOutcome::Deleted,
4718                expected_shards: &[(MAX, &[60, 70])],
4719            },
4720            StoragePruneCase {
4721                name: "equiv_sentinel_becomes_empty_with_prev",
4722                initial_shards: &[(50, &[30, 40, 50]), (MAX, &[35])],
4723                prune_to: 40,
4724                expected_outcome: PruneShardOutcome::Deleted,
4725                expected_shards: &[(MAX, &[50])],
4726            },
4727            StoragePruneCase {
4728                name: "equiv_all_shards_become_empty",
4729                initial_shards: &[(50, &[30, 40, 50]), (MAX, &[51])],
4730                prune_to: 51,
4731                expected_outcome: PruneShardOutcome::Deleted,
4732                expected_shards: &[],
4733            },
4734            StoragePruneCase {
4735                name: "equiv_filter_within_shard",
4736                initial_shards: &[(MAX, &[10, 20, 30, 40])],
4737                prune_to: 25,
4738                expected_outcome: PruneShardOutcome::Updated,
4739                expected_shards: &[(MAX, &[30, 40])],
4740            },
4741            StoragePruneCase {
4742                name: "equiv_multi_shard_partial_delete",
4743                initial_shards: &[(20, &[10, 20]), (50, &[30, 40, 50]), (MAX, &[60, 70])],
4744                prune_to: 35,
4745                expected_outcome: PruneShardOutcome::Deleted,
4746                expected_shards: &[(50, &[40, 50]), (MAX, &[60, 70])],
4747            },
4748        ];
4749
4750        let address = Address::repeat_byte(0x42);
4751        let storage_key = B256::repeat_byte(0x01);
4752
4753        for case in CASES {
4754            let temp_dir = TempDir::new().unwrap();
4755            let provider =
4756                RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4757
4758            // Setup initial shards
4759            let mut batch = provider.batch();
4760            for (highest, blocks) in case.initial_shards {
4761                let shard = BlockNumberList::new_pre_sorted(blocks.iter().copied());
4762                let key = if *highest == MAX {
4763                    StorageShardedKey::last(address, storage_key)
4764                } else {
4765                    StorageShardedKey::new(address, storage_key, *highest)
4766                };
4767                batch.put::<tables::StoragesHistory>(key, &shard).unwrap();
4768            }
4769            batch.commit().unwrap();
4770
4771            // Prune
4772            let mut batch = provider.batch();
4773            let outcome =
4774                batch.prune_storage_history_to(address, storage_key, case.prune_to).unwrap();
4775            batch.commit().unwrap();
4776
4777            // Assert outcome
4778            assert_eq!(outcome, case.expected_outcome, "case '{}': wrong outcome", case.name);
4779
4780            // Assert final shards
4781            let shards = provider.storage_history_shards(address, storage_key).unwrap();
4782            assert_eq!(
4783                shards.len(),
4784                case.expected_shards.len(),
4785                "case '{}': wrong shard count",
4786                case.name
4787            );
4788            for (i, ((key, blocks), (exp_key, exp_blocks))) in
4789                shards.iter().zip(case.expected_shards.iter()).enumerate()
4790            {
4791                assert_eq!(
4792                    key.sharded_key.highest_block_number, *exp_key,
4793                    "case '{}': shard {} wrong key",
4794                    case.name, i
4795                );
4796                assert_eq!(
4797                    blocks.iter().collect::<Vec<_>>(),
4798                    *exp_blocks,
4799                    "case '{}': shard {} wrong blocks",
4800                    case.name,
4801                    i
4802                );
4803            }
4804        }
4805    }
4806
4807    #[test]
4808    fn test_prune_storage_history_does_not_affect_other_slots() {
4809        let temp_dir = TempDir::new().unwrap();
4810        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4811
4812        let address = Address::repeat_byte(0x42);
4813        let slot1 = B256::repeat_byte(0x01);
4814        let slot2 = B256::repeat_byte(0x02);
4815
4816        // Two different storage slots
4817        let mut batch = provider.batch();
4818        batch
4819            .put::<tables::StoragesHistory>(
4820                StorageShardedKey::last(address, slot1),
4821                &BlockNumberList::new_pre_sorted([10u64, 20]),
4822            )
4823            .unwrap();
4824        batch
4825            .put::<tables::StoragesHistory>(
4826                StorageShardedKey::last(address, slot2),
4827                &BlockNumberList::new_pre_sorted([30u64, 40]),
4828            )
4829            .unwrap();
4830        batch.commit().unwrap();
4831
4832        // Prune slot1 to block 20 (deletes all)
4833        let mut batch = provider.batch();
4834        let outcome = batch.prune_storage_history_to(address, slot1, 20).unwrap();
4835        batch.commit().unwrap();
4836
4837        assert_eq!(outcome, PruneShardOutcome::Deleted);
4838
4839        // slot1 should be empty
4840        let shards1 = provider.storage_history_shards(address, slot1).unwrap();
4841        assert!(shards1.is_empty());
4842
4843        // slot2 should be unchanged
4844        let shards2 = provider.storage_history_shards(address, slot2).unwrap();
4845        assert_eq!(shards2.len(), 1);
4846        assert_eq!(shards2[0].1.iter().collect::<Vec<_>>(), vec![30, 40]);
4847    }
4848
4849    #[test]
4850    fn test_prune_invariants() {
4851        // Test invariants: no empty shards, sentinel is always last
4852        let address = Address::repeat_byte(0x42);
4853        let storage_key = B256::repeat_byte(0x01);
4854
4855        // Test cases that exercise invariants
4856        #[expect(clippy::type_complexity)]
4857        let invariant_cases: &[(&[(u64, &[u64])], u64)] = &[
4858            // Account: shards where middle becomes empty
4859            (&[(10, &[5, 10]), (20, &[15, 20]), (u64::MAX, &[25, 30])], 20),
4860            // Account: non-sentinel shard only, partial prune -> must become sentinel
4861            (&[(100, &[50, 100])], 60),
4862        ];
4863
4864        for (initial_shards, prune_to) in invariant_cases {
4865            // Test account history invariants
4866            {
4867                let temp_dir = TempDir::new().unwrap();
4868                let provider =
4869                    RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4870
4871                let mut batch = provider.batch();
4872                for (highest, blocks) in *initial_shards {
4873                    let shard = BlockNumberList::new_pre_sorted(blocks.iter().copied());
4874                    batch
4875                        .put::<tables::AccountsHistory>(ShardedKey::new(address, *highest), &shard)
4876                        .unwrap();
4877                }
4878                batch.commit().unwrap();
4879
4880                let mut batch = provider.batch();
4881                batch.prune_account_history_to(address, *prune_to).unwrap();
4882                batch.commit().unwrap();
4883
4884                let shards = provider.account_history_shards(address).unwrap();
4885
4886                // Invariant 1: no empty shards
4887                for (key, blocks) in &shards {
4888                    assert!(
4889                        !blocks.is_empty(),
4890                        "Account: empty shard at key {}",
4891                        key.highest_block_number
4892                    );
4893                }
4894
4895                // Invariant 2: last shard is sentinel
4896                if !shards.is_empty() {
4897                    let last = shards.last().unwrap();
4898                    assert_eq!(
4899                        last.0.highest_block_number,
4900                        u64::MAX,
4901                        "Account: last shard must be sentinel"
4902                    );
4903                }
4904            }
4905
4906            // Test storage history invariants
4907            {
4908                let temp_dir = TempDir::new().unwrap();
4909                let provider =
4910                    RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4911
4912                let mut batch = provider.batch();
4913                for (highest, blocks) in *initial_shards {
4914                    let shard = BlockNumberList::new_pre_sorted(blocks.iter().copied());
4915                    let key = if *highest == u64::MAX {
4916                        StorageShardedKey::last(address, storage_key)
4917                    } else {
4918                        StorageShardedKey::new(address, storage_key, *highest)
4919                    };
4920                    batch.put::<tables::StoragesHistory>(key, &shard).unwrap();
4921                }
4922                batch.commit().unwrap();
4923
4924                let mut batch = provider.batch();
4925                batch.prune_storage_history_to(address, storage_key, *prune_to).unwrap();
4926                batch.commit().unwrap();
4927
4928                let shards = provider.storage_history_shards(address, storage_key).unwrap();
4929
4930                // Invariant 1: no empty shards
4931                for (key, blocks) in &shards {
4932                    assert!(
4933                        !blocks.is_empty(),
4934                        "Storage: empty shard at key {}",
4935                        key.sharded_key.highest_block_number
4936                    );
4937                }
4938
4939                // Invariant 2: last shard is sentinel
4940                if !shards.is_empty() {
4941                    let last = shards.last().unwrap();
4942                    assert_eq!(
4943                        last.0.sharded_key.highest_block_number,
4944                        u64::MAX,
4945                        "Storage: last shard must be sentinel"
4946                    );
4947                }
4948            }
4949        }
4950    }
4951
4952    #[test]
4953    fn test_prune_account_history_batch_multiple_sorted_targets() {
4954        let temp_dir = TempDir::new().unwrap();
4955        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
4956
4957        let addr1 = Address::repeat_byte(0x01);
4958        let addr2 = Address::repeat_byte(0x02);
4959        let addr3 = Address::repeat_byte(0x03);
4960
4961        // Setup shards for each address
4962        let mut batch = provider.batch();
4963        batch
4964            .put::<tables::AccountsHistory>(
4965                ShardedKey::new(addr1, u64::MAX),
4966                &BlockNumberList::new_pre_sorted([10, 20, 30]),
4967            )
4968            .unwrap();
4969        batch
4970            .put::<tables::AccountsHistory>(
4971                ShardedKey::new(addr2, u64::MAX),
4972                &BlockNumberList::new_pre_sorted([5, 10, 15]),
4973            )
4974            .unwrap();
4975        batch
4976            .put::<tables::AccountsHistory>(
4977                ShardedKey::new(addr3, u64::MAX),
4978                &BlockNumberList::new_pre_sorted([100, 200]),
4979            )
4980            .unwrap();
4981        batch.commit().unwrap();
4982
4983        // Prune all three (sorted by address)
4984        let mut targets = vec![(addr1, 15), (addr2, 10), (addr3, 50)];
4985        targets.sort_by_key(|(addr, _)| *addr);
4986
4987        let mut batch = provider.batch();
4988        let outcomes = batch.prune_account_history_batch(&targets).unwrap();
4989        batch.commit().unwrap();
4990
4991        // addr1: prune <=15, keep [20, 30] -> updated
4992        // addr2: prune <=10, keep [15] -> updated
4993        // addr3: prune <=50, keep [100, 200] -> unchanged
4994        assert_eq!(outcomes.updated, 2);
4995        assert_eq!(outcomes.unchanged, 1);
4996
4997        let shards1 = provider.account_history_shards(addr1).unwrap();
4998        assert_eq!(shards1[0].1.iter().collect::<Vec<_>>(), vec![20, 30]);
4999
5000        let shards2 = provider.account_history_shards(addr2).unwrap();
5001        assert_eq!(shards2[0].1.iter().collect::<Vec<_>>(), vec![15]);
5002
5003        let shards3 = provider.account_history_shards(addr3).unwrap();
5004        assert_eq!(shards3[0].1.iter().collect::<Vec<_>>(), vec![100, 200]);
5005    }
5006
5007    #[test]
5008    fn test_prune_account_history_batch_target_with_no_shards() {
5009        let temp_dir = TempDir::new().unwrap();
5010        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
5011
5012        let addr1 = Address::repeat_byte(0x01);
5013        let addr2 = Address::repeat_byte(0x02); // No shards for this one
5014        let addr3 = Address::repeat_byte(0x03);
5015
5016        // Only setup shards for addr1 and addr3
5017        let mut batch = provider.batch();
5018        batch
5019            .put::<tables::AccountsHistory>(
5020                ShardedKey::new(addr1, u64::MAX),
5021                &BlockNumberList::new_pre_sorted([10, 20]),
5022            )
5023            .unwrap();
5024        batch
5025            .put::<tables::AccountsHistory>(
5026                ShardedKey::new(addr3, u64::MAX),
5027                &BlockNumberList::new_pre_sorted([30, 40]),
5028            )
5029            .unwrap();
5030        batch.commit().unwrap();
5031
5032        // Prune all three (addr2 has no shards - tests p > target_prefix case)
5033        let mut targets = vec![(addr1, 15), (addr2, 100), (addr3, 35)];
5034        targets.sort_by_key(|(addr, _)| *addr);
5035
5036        let mut batch = provider.batch();
5037        let outcomes = batch.prune_account_history_batch(&targets).unwrap();
5038        batch.commit().unwrap();
5039
5040        // addr1: updated (keep [20])
5041        // addr2: unchanged (no shards)
5042        // addr3: updated (keep [40])
5043        assert_eq!(outcomes.updated, 2);
5044        assert_eq!(outcomes.unchanged, 1);
5045
5046        let shards1 = provider.account_history_shards(addr1).unwrap();
5047        assert_eq!(shards1[0].1.iter().collect::<Vec<_>>(), vec![20]);
5048
5049        let shards3 = provider.account_history_shards(addr3).unwrap();
5050        assert_eq!(shards3[0].1.iter().collect::<Vec<_>>(), vec![40]);
5051    }
5052
5053    #[test]
5054    fn test_prune_storage_history_batch_multiple_sorted_targets() {
5055        let temp_dir = TempDir::new().unwrap();
5056        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
5057
5058        let addr = Address::repeat_byte(0x42);
5059        let slot1 = B256::repeat_byte(0x01);
5060        let slot2 = B256::repeat_byte(0x02);
5061
5062        // Setup shards
5063        let mut batch = provider.batch();
5064        batch
5065            .put::<tables::StoragesHistory>(
5066                StorageShardedKey::new(addr, slot1, u64::MAX),
5067                &BlockNumberList::new_pre_sorted([10, 20, 30]),
5068            )
5069            .unwrap();
5070        batch
5071            .put::<tables::StoragesHistory>(
5072                StorageShardedKey::new(addr, slot2, u64::MAX),
5073                &BlockNumberList::new_pre_sorted([5, 15, 25]),
5074            )
5075            .unwrap();
5076        batch.commit().unwrap();
5077
5078        // Prune both (sorted)
5079        let mut targets = vec![((addr, slot1), 15), ((addr, slot2), 10)];
5080        targets.sort_by_key(|((a, s), _)| (*a, *s));
5081
5082        let mut batch = provider.batch();
5083        let outcomes = batch.prune_storage_history_batch(&targets).unwrap();
5084        batch.commit().unwrap();
5085
5086        assert_eq!(outcomes.updated, 2);
5087
5088        let shards1 = provider.storage_history_shards(addr, slot1).unwrap();
5089        assert_eq!(shards1[0].1.iter().collect::<Vec<_>>(), vec![20, 30]);
5090
5091        let shards2 = provider.storage_history_shards(addr, slot2).unwrap();
5092        assert_eq!(shards2[0].1.iter().collect::<Vec<_>>(), vec![15, 25]);
5093    }
5094
5095    /// Shards for one address, keyed by highest block, as `(highest, blocks)`.
5096    fn account_shard_layout(provider: &RocksDBProvider, address: Address) -> Vec<(u64, Vec<u64>)> {
5097        provider
5098            .account_history_shards(address)
5099            .unwrap()
5100            .into_iter()
5101            .map(|(key, list)| (key.highest_block_number, list.iter().collect::<Vec<_>>()))
5102            .collect()
5103    }
5104
5105    /// Shards for one storage slot, keyed by highest block, as `(highest, blocks)`.
5106    fn storage_shard_layout(
5107        provider: &RocksDBProvider,
5108        address: Address,
5109        storage_key: B256,
5110    ) -> Vec<(u64, Vec<u64>)> {
5111        provider
5112            .storage_history_shards(address, storage_key)
5113            .unwrap()
5114            .into_iter()
5115            .map(|(key, list)| {
5116                (key.sharded_key.highest_block_number, list.iter().collect::<Vec<_>>())
5117            })
5118            .collect()
5119    }
5120
5121    fn seed_three_storage_shards(provider: &RocksDBProvider, address: Address, storage_key: B256) {
5122        let mut batch = provider.batch();
5123        batch
5124            .put::<tables::StoragesHistory>(
5125                StorageShardedKey::new(address, storage_key, 100),
5126                &BlockNumberList::new_pre_sorted([10, 50, 100]),
5127            )
5128            .unwrap();
5129        batch
5130            .put::<tables::StoragesHistory>(
5131                StorageShardedKey::new(address, storage_key, 200),
5132                &BlockNumberList::new_pre_sorted([150, 200]),
5133            )
5134            .unwrap();
5135        batch
5136            .put::<tables::StoragesHistory>(
5137                StorageShardedKey::last(address, storage_key),
5138                &BlockNumberList::new_pre_sorted([250, 300]),
5139            )
5140            .unwrap();
5141        batch.commit().unwrap();
5142    }
5143
5144    #[test]
5145    fn test_prune_storage_history_batch_trims_sentinel_once_earlier_shards_expire() {
5146        let temp_dir = TempDir::new().unwrap();
5147        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
5148
5149        let addr = Address::repeat_byte(0x42);
5150        let slot = B256::repeat_byte(0x01);
5151        seed_three_storage_shards(&provider, addr, slot);
5152
5153        // Every non-sentinel shard expires whole and the sentinel loses its lowest block.
5154        let mut batch = provider.batch();
5155        let outcomes = batch.prune_storage_history_batch(&[((addr, slot), 250)]).unwrap();
5156        batch.commit().unwrap();
5157
5158        assert_eq!(outcomes.deleted, 1);
5159        assert_eq!(storage_shard_layout(&provider, addr, slot), vec![(u64::MAX, vec![300])]);
5160    }
5161
5162    #[test]
5163    fn test_prune_account_history_batch_seeks_after_stopping_early() {
5164        let temp_dir = TempDir::new().unwrap();
5165        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
5166
5167        let addr1 = Address::repeat_byte(0x01);
5168        let addr2 = Address::repeat_byte(0x02);
5169
5170        let mut batch = provider.batch();
5171        batch
5172            .put::<tables::AccountsHistory>(
5173                ShardedKey::new(addr1, 100),
5174                &BlockNumberList::new_pre_sorted([10, 50, 100]),
5175            )
5176            .unwrap();
5177        batch
5178            .put::<tables::AccountsHistory>(
5179                ShardedKey::new(addr1, u64::MAX),
5180                &BlockNumberList::new_pre_sorted([250, 300]),
5181            )
5182            .unwrap();
5183        batch
5184            .put::<tables::AccountsHistory>(
5185                ShardedKey::new(addr2, u64::MAX),
5186                &BlockNumberList::new_pre_sorted([5, 10, 15]),
5187            )
5188            .unwrap();
5189        batch.commit().unwrap();
5190
5191        // The first target stops on addr1's oldest shard, leaving the iterator on addr1's
5192        // sentinel. The second target must seek past it instead of skipping addr2.
5193        let mut batch = provider.batch();
5194        let outcomes = batch.prune_account_history_batch(&[(addr1, 50), (addr2, 10)]).unwrap();
5195        batch.commit().unwrap();
5196
5197        assert_eq!(outcomes.updated, 2);
5198        assert_eq!(
5199            account_shard_layout(&provider, addr1),
5200            vec![(100, vec![100]), (u64::MAX, vec![250, 300])]
5201        );
5202        assert_eq!(account_shard_layout(&provider, addr2), vec![(u64::MAX, vec![15])]);
5203    }
5204
5205    #[test]
5206    fn test_prune_storage_history_batch_seeks_after_stopping_early() {
5207        let temp_dir = TempDir::new().unwrap();
5208        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
5209
5210        let addr = Address::repeat_byte(0x42);
5211        let slot1 = B256::repeat_byte(0x01);
5212        let slot2 = B256::repeat_byte(0x02);
5213        seed_three_storage_shards(&provider, addr, slot1);
5214
5215        let mut batch = provider.batch();
5216        batch
5217            .put::<tables::StoragesHistory>(
5218                StorageShardedKey::last(addr, slot2),
5219                &BlockNumberList::new_pre_sorted([20, 40]),
5220            )
5221            .unwrap();
5222        batch.commit().unwrap();
5223
5224        // The first target stops on slot1's oldest shard, leaving the iterator on slot1's next
5225        // shard. The second target must seek past it instead of skipping slot2.
5226        let mut batch = provider.batch();
5227        let outcomes =
5228            batch.prune_storage_history_batch(&[((addr, slot1), 50), ((addr, slot2), 30)]).unwrap();
5229        batch.commit().unwrap();
5230
5231        assert_eq!(outcomes.updated, 2);
5232        assert_eq!(
5233            storage_shard_layout(&provider, addr, slot1),
5234            vec![(100, vec![100]), (200, vec![150, 200]), (u64::MAX, vec![250, 300])]
5235        );
5236        assert_eq!(storage_shard_layout(&provider, addr, slot2), vec![(u64::MAX, vec![40])]);
5237    }
5238
5239    /// An unwind that keeps blocks in the last shard reads no other shard. The earlier shard here
5240    /// is not a valid block list, so reading it fails.
5241    #[test]
5242    fn test_unwind_reads_only_last_history_shard() {
5243        let temp_dir = TempDir::new().unwrap();
5244        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
5245        let address = Address::ZERO;
5246        let slot = B256::ZERO;
5247        let last = BlockNumberList::new_pre_sorted([50, 70]);
5248
5249        let mut batch = provider.batch();
5250        batch.inner.put_cf(
5251            provider.get_cf_handle::<tables::AccountsHistory>().unwrap(),
5252            ShardedKey::new(address, 30).encode(),
5253            [0xff],
5254        );
5255        batch.inner.put_cf(
5256            provider.get_cf_handle::<tables::StoragesHistory>().unwrap(),
5257            StorageShardedKey::new(address, slot, 30).encode(),
5258            [0xff],
5259        );
5260        batch.put::<tables::AccountsHistory>(ShardedKey::last(address), &last).unwrap();
5261        batch
5262            .put::<tables::StoragesHistory>(StorageShardedKey::last(address, slot), &last)
5263            .unwrap();
5264        batch.commit().unwrap();
5265        assert!(matches!(
5266            provider.account_history_shards(address),
5267            Err(ProviderError::Database(DatabaseError::Decode))
5268        ));
5269
5270        let mut batch = provider.batch();
5271        batch.unwind_account_history_to(address, 50).unwrap();
5272        batch.unwind_storage_history_to(address, slot, 50).unwrap();
5273        batch.commit().unwrap();
5274
5275        let trimmed = Some(BlockNumberList::new_pre_sorted([50]));
5276        assert_eq!(
5277            provider.get::<tables::AccountsHistory>(ShardedKey::last(address)).unwrap(),
5278            trimmed
5279        );
5280        assert_eq!(
5281            provider
5282                .get::<tables::StoragesHistory>(StorageShardedKey::last(address, slot))
5283                .unwrap(),
5284            trimmed
5285        );
5286
5287        // Nothing above block 50 is left, so unwinding again writes nothing.
5288        let mut batch = provider.batch();
5289        batch.unwind_account_history_to(address, 50).unwrap();
5290        batch.unwind_storage_history_to(address, slot, 50).unwrap();
5291        assert!(batch.is_empty());
5292    }
5293
5294    /// A crash between two auto-commits of the history index stages can persist a newly split
5295    /// shard while the last shard still holds the list it was split from. Unwinding to the stage
5296    /// checkpoint must remove the split shard.
5297    #[test]
5298    fn test_unwind_history_removes_shard_split_before_crash() {
5299        let temp_dir = TempDir::new().unwrap();
5300        let provider = RocksDBBuilder::new(temp_dir.path()).with_default_tables().build().unwrap();
5301        let address = Address::ZERO;
5302        let slot = B256::ZERO;
5303
5304        // At checkpoint 30 the last shard held [10, 20, 30]. The stage merged block 40 into it
5305        // and split off a shard under key 40, then crashed before rewriting the last shard.
5306        let mut batch = provider.batch();
5307        for (highest, blocks) in [(40, vec![10, 20, 30, 40]), (u64::MAX, vec![10, 20, 30])] {
5308            let list = BlockNumberList::new_pre_sorted(blocks);
5309            batch.put::<tables::AccountsHistory>(ShardedKey::new(address, highest), &list).unwrap();
5310            batch
5311                .put::<tables::StoragesHistory>(
5312                    StorageShardedKey::new(address, slot, highest),
5313                    &list,
5314                )
5315                .unwrap();
5316        }
5317        batch.commit().unwrap();
5318
5319        let mut batch = provider.batch();
5320        batch.unwind_account_history_to(address, 30).unwrap();
5321        batch.unwind_storage_history_to(address, slot, 30).unwrap();
5322        batch.commit().unwrap();
5323
5324        let expected = vec![(u64::MAX, vec![10, 20, 30])];
5325        assert_eq!(account_shard_layout(&provider, address), expected);
5326        assert_eq!(storage_shard_layout(&provider, address, slot), expected);
5327    }
5328}