Skip to main content

reth_stages/stages/
utils.rs

1//! Utils for `stages`.
2use alloy_primitives::{
3    map::{AddressMap, HashMap},
4    Address, BlockNumber, TxNumber, B256,
5};
6use reth_config::config::EtlConfig;
7use reth_db_api::{
8    cursor::{DbCursorRO, DbCursorRW},
9    models::{
10        sharded_key::NUM_OF_INDICES_IN_SHARD, storage_sharded_key::StorageShardedKey,
11        AccountBeforeTx, AddressStorageKey, BlockNumberAddress, ShardedKey,
12    },
13    table::{Decode, Decompress, Key, Table},
14    transaction::DbTx,
15    BlockNumberList,
16};
17use reth_etl::Collector;
18use reth_primitives_traits::NodePrimitives;
19use reth_provider::{
20    providers::StaticFileProvider, to_range, BlockReader, DBProvider, EitherWriter, ProviderError,
21    StaticFileProviderFactory,
22};
23use reth_stages_api::StageError;
24use reth_static_file_types::StaticFileSegment;
25use reth_storage_api::{ChangeSetReader, StorageChangeSetReader};
26use std::{
27    hash::{BuildHasher, Hash},
28    mem::size_of,
29    ops::RangeBounds,
30};
31use tracing::{debug, info};
32
33/// Number of blocks before pushing indices from cache to [`Collector`]
34const DEFAULT_CACHE_THRESHOLD: u64 = 100_000;
35
36/// Collects all history (`H`) indices for a range of changesets (`CS`) and stores them in a
37/// [`Collector`].
38///
39/// ## Process
40/// The function utilizes a [`HistoryIndexCache`] with a structure of `PartialKey` (`P`) (Address or
41/// Address.StorageKey) to block numbers. When the cache exceeds its capacity, its contents are
42/// moved to a [`Collector`]. Here, each entry's key is a concatenation of `PartialKey` and the
43/// highest block number in its list.
44///
45/// ## Example
46/// 1. Initial Cache State: `{ Address1: [1,2,3], ... }`
47/// 2. Cache is flushed to the `Collector`.
48/// 3. Updated Cache State: `{ Address1: [100,300], ... }`
49/// 4. Cache is flushed again.
50///
51/// As a result, the `Collector` will contain entries such as `(Address1.3, [1,2,3])` and
52/// `(Address1.300, [100,300])`. The entries may be stored across one or more files.
53pub(crate) fn collect_history_indices<Provider, CS, H, P>(
54    provider: &Provider,
55    range: impl RangeBounds<CS::Key>,
56    sharded_key_factory: impl Fn(P, BlockNumber) -> H::Key,
57    partial_key_factory: impl Fn((CS::Key, CS::Value)) -> (u64, P),
58    etl_config: &EtlConfig,
59) -> Result<Collector<H::Key, H::Value>, StageError>
60where
61    Provider: DBProvider,
62    CS: Table,
63    H: Table<Value = BlockNumberList>,
64    P: Copy + Eq + Hash,
65{
66    let mut changeset_cursor = provider.tx_ref().cursor_read::<CS>()?;
67
68    let mut cache =
69        HistoryIndexCache::new(etl_config, HashMap::<_, _>::default(), sharded_key_factory);
70
71    // observability
72    let total_changesets = provider.tx_ref().entries::<CS>()?;
73    let interval = (total_changesets / 1000).max(1);
74
75    for (idx, entry) in changeset_cursor.walk_range(range)?.enumerate() {
76        let (block_number, key) = partial_key_factory(entry?);
77        cache.insert(block_number, key)?;
78
79        if idx > 0 && idx.is_multiple_of(interval) && total_changesets > 1000 {
80            info!(target: "sync::stages::index_history", progress = %format_args!("{:.4}%", (idx as f64 / total_changesets as f64) * 100.0), "Collecting indices");
81        }
82    }
83
84    cache.finish()
85}
86
87/// Collects account history indices using a provider that implements `ChangeSetReader`.
88pub(crate) fn collect_account_history_indices<Provider>(
89    provider: &Provider,
90    range: impl RangeBounds<BlockNumber>,
91    etl_config: &EtlConfig,
92) -> Result<Collector<ShardedKey<Address>, BlockNumberList>, StageError>
93where
94    Provider: DBProvider + ChangeSetReader + StaticFileProviderFactory,
95{
96    let mut cache = HistoryIndexCache::new(etl_config, AddressMap::default(), ShardedKey::new);
97
98    // Convert range bounds to concrete range
99    let range = to_range(range);
100    let start_block = range.start;
101
102    // Use the new walker for lazy iteration over static file changesets
103    let static_file_provider = provider.static_file_provider();
104
105    let walker = static_file_provider.walk_account_changeset_range(range);
106
107    for changeset_result in walker {
108        let (block_number, AccountBeforeTx { address, .. }) = changeset_result?;
109        if cache.insert(block_number, address)? {
110            info!(
111                target: "sync::stages::index_history",
112                processed_blocks = block_number.saturating_sub(start_block),
113                current_block = block_number,
114                "Collecting indices"
115            );
116        }
117    }
118
119    cache.finish()
120}
121
122/// Collects storage history indices using a provider that implements `StorageChangeSetReader`.
123pub(crate) fn collect_storage_history_indices<Provider>(
124    provider: &Provider,
125    range: impl RangeBounds<BlockNumber>,
126    etl_config: &EtlConfig,
127) -> Result<Collector<StorageShardedKey, BlockNumberList>, StageError>
128where
129    Provider: DBProvider + StorageChangeSetReader + StaticFileProviderFactory,
130{
131    let mut cache = HistoryIndexCache::new(
132        etl_config,
133        HashMap::<_, _>::default(),
134        |AddressStorageKey((address, storage_key)), highest_block_number| {
135            StorageShardedKey::new(address, storage_key, highest_block_number)
136        },
137    );
138
139    let range = to_range(range);
140    let start_block = range.start;
141    let static_file_provider = provider.static_file_provider();
142
143    let walker = static_file_provider.walk_storage_changeset_range(range);
144
145    for changeset_result in walker {
146        let (BlockNumberAddress((block_number, address)), storage) = changeset_result?;
147        if cache.insert(block_number, AddressStorageKey((address, storage.key)))? {
148            info!(
149                target: "sync::stages::index_history",
150                processed_blocks = block_number.saturating_sub(start_block),
151                current_block = block_number,
152                "Collecting indices"
153            );
154        }
155    }
156
157    cache.finish()
158}
159
160/// Loads account history indices into the database via `EitherWriter`.
161///
162/// Works with [`EitherWriter`] to support both MDBX and `RocksDB` backends.
163///
164/// ## Process
165/// Iterates over elements, grouping indices by their address. It flushes indices to disk
166/// when reaching a shard's max length (`NUM_OF_INDICES_IN_SHARD`) or when the address changes,
167/// ensuring the last previous address shard is stored.
168///
169/// Uses `Option<Address>` instead of `Address::default()` as the sentinel to avoid
170/// incorrectly treating `Address::ZERO` as "no previous address".
171pub(crate) fn load_account_history<N, CURSOR>(
172    mut collector: Collector<ShardedKey<Address>, BlockNumberList>,
173    append_only: bool,
174    writer: &mut EitherWriter<'_, CURSOR, N>,
175) -> Result<(), StageError>
176where
177    N: NodePrimitives,
178    CURSOR: DbCursorRW<reth_db_api::tables::AccountsHistory>
179        + DbCursorRO<reth_db_api::tables::AccountsHistory>,
180{
181    let mut current_address: Option<Address> = None;
182    // Accumulator for block numbers where the current address changed.
183    let mut current_list = Vec::<u64>::new();
184
185    let total_entries = collector.len();
186    let interval = (total_entries / 10).max(1);
187
188    for (index, element) in collector.iter()?.enumerate() {
189        let (k, v) = element?;
190        let sharded_key = ShardedKey::<Address>::decode_owned(k)?;
191        let new_list = BlockNumberList::decompress_owned(v)?;
192
193        if index > 0 && index.is_multiple_of(interval) && total_entries > 10 {
194            info!(target: "sync::stages::index_history", progress = %format_args!("{:.2}%", (index as f64 / total_entries as f64) * 100.0), "Writing indices");
195        }
196
197        let address = sharded_key.key;
198
199        // When address changes, flush the previous address's shards and start fresh.
200        if current_address != Some(address) {
201            // Flush all remaining shards for the previous address (uses u64::MAX for last shard).
202            if let Some(prev_addr) = current_address {
203                flush_account_history_shards(prev_addr, &mut current_list, append_only, writer)?;
204            }
205
206            current_address = Some(address);
207            current_list.clear();
208
209            // On incremental sync, merge with the existing last shard from the database.
210            // The last shard is stored with key (address, u64::MAX) so we can find it.
211            if !append_only &&
212                let Some(last_shard) = writer.get_last_account_history_shard(address)?
213            {
214                current_list.extend(last_shard.iter());
215            }
216        }
217
218        // Append new block numbers to the accumulator.
219        current_list.extend(new_list.iter());
220
221        // Flush complete shards, keeping the last (partial) shard buffered.
222        flush_account_history_shards_partial(address, &mut current_list, append_only, writer)?;
223    }
224
225    // Flush the final address's remaining shard.
226    if let Some(addr) = current_address {
227        flush_account_history_shards(addr, &mut current_list, append_only, writer)?;
228    }
229
230    Ok(())
231}
232
233/// Flushes complete shards for account history, keeping the trailing partial shard buffered.
234///
235/// Only flushes when we have more than one shard's worth of data, keeping the last
236/// (possibly partial) shard for continued accumulation. This avoids writing a shard
237/// that may need to be updated when more indices arrive.
238fn flush_account_history_shards_partial<N, CURSOR>(
239    address: Address,
240    list: &mut Vec<u64>,
241    append_only: bool,
242    writer: &mut EitherWriter<'_, CURSOR, N>,
243) -> Result<(), StageError>
244where
245    N: NodePrimitives,
246    CURSOR: DbCursorRW<reth_db_api::tables::AccountsHistory>
247        + DbCursorRO<reth_db_api::tables::AccountsHistory>,
248{
249    // Nothing to flush if we haven't filled a complete shard yet.
250    if list.len() <= NUM_OF_INDICES_IN_SHARD {
251        return Ok(());
252    }
253
254    let num_full_shards = list.len() / NUM_OF_INDICES_IN_SHARD;
255
256    // Always keep at least one shard buffered for continued accumulation.
257    // If len is exact multiple of shard size, keep the last full shard.
258    let shards_to_flush = if list.len().is_multiple_of(NUM_OF_INDICES_IN_SHARD) {
259        num_full_shards - 1
260    } else {
261        num_full_shards
262    };
263
264    if shards_to_flush == 0 {
265        return Ok(());
266    }
267
268    // Split: flush the first N shards, keep the remainder buffered.
269    let flush_len = shards_to_flush * NUM_OF_INDICES_IN_SHARD;
270    let remainder = list.split_off(flush_len);
271
272    // Write each complete shard with its highest block number as the key.
273    for chunk in list.chunks(NUM_OF_INDICES_IN_SHARD) {
274        let highest = *chunk.last().expect("chunk is non-empty");
275        let key = ShardedKey::new(address, highest);
276        let value = BlockNumberList::new_pre_sorted(chunk.iter().copied());
277
278        if append_only {
279            writer.append_account_history(key, &value)?;
280        } else {
281            writer.upsert_account_history(key, &value)?;
282        }
283    }
284
285    // Keep the remaining indices for the next iteration.
286    *list = remainder;
287    Ok(())
288}
289
290/// Flushes all remaining shards for account history, using `u64::MAX` for the last shard.
291///
292/// The `u64::MAX` key for the final shard is an invariant that allows `seek_exact(address,
293/// u64::MAX)` to find the last shard during incremental sync for merging with new indices.
294fn flush_account_history_shards<N, CURSOR>(
295    address: Address,
296    list: &mut Vec<u64>,
297    append_only: bool,
298    writer: &mut EitherWriter<'_, CURSOR, N>,
299) -> Result<(), StageError>
300where
301    N: NodePrimitives,
302    CURSOR: DbCursorRW<reth_db_api::tables::AccountsHistory>
303        + DbCursorRO<reth_db_api::tables::AccountsHistory>,
304{
305    if list.is_empty() {
306        return Ok(());
307    }
308
309    let num_chunks = list.len().div_ceil(NUM_OF_INDICES_IN_SHARD);
310
311    for (i, chunk) in list.chunks(NUM_OF_INDICES_IN_SHARD).enumerate() {
312        let is_last = i == num_chunks - 1;
313
314        // Use u64::MAX for the final shard's key. This invariant allows incremental sync
315        // to find the last shard via seek_exact(address, u64::MAX) for merging.
316        let highest = if is_last { u64::MAX } else { *chunk.last().expect("chunk is non-empty") };
317
318        let key = ShardedKey::new(address, highest);
319        let value = BlockNumberList::new_pre_sorted(chunk.iter().copied());
320
321        if append_only {
322            writer.append_account_history(key, &value)?;
323        } else {
324            writer.upsert_account_history(key, &value)?;
325        }
326    }
327
328    list.clear();
329    Ok(())
330}
331
332/// Called when database is ahead of static files. Attempts to find the first block we are missing
333/// transactions for.
334pub(crate) fn missing_static_data_error<Provider>(
335    last_tx_num: TxNumber,
336    static_file_provider: &StaticFileProvider<Provider::Primitives>,
337    provider: &Provider,
338    segment: StaticFileSegment,
339) -> Result<StageError, ProviderError>
340where
341    Provider: BlockReader + StaticFileProviderFactory,
342{
343    let mut last_block =
344        static_file_provider.get_highest_static_file_block(segment).unwrap_or_default();
345
346    // To be extra safe, we make sure that the last tx num matches the last block from its indices.
347    // If not, get it.
348    loop {
349        if let Some(indices) = provider.block_body_indices(last_block)? &&
350            indices.last_tx_num() <= last_tx_num
351        {
352            break
353        }
354        if last_block == 0 {
355            break
356        }
357        last_block -= 1;
358    }
359
360    let missing_block = Box::new(provider.sealed_header(last_block + 1)?.unwrap_or_default());
361
362    Ok(StageError::MissingStaticFileData {
363        block: Box::new(missing_block.block_with_parent()),
364        segment,
365    })
366}
367
368/// Loads storage history indices into the database via `EitherWriter`.
369///
370/// Works with [`EitherWriter`] to support both MDBX and `RocksDB` backends.
371///
372/// ## Process
373/// Iterates over elements, grouping indices by their (address, `storage_key`) pairs. It flushes
374/// indices to disk when reaching a shard's max length (`NUM_OF_INDICES_IN_SHARD`) or when the
375/// (address, `storage_key`) pair changes, ensuring the last previous shard is stored.
376///
377/// Uses `Option<(Address, B256)>` instead of default values as the sentinel to avoid
378/// incorrectly treating `(Address::ZERO, B256::ZERO)` as "no previous key".
379pub(crate) fn load_storage_history<N, CURSOR>(
380    mut collector: Collector<StorageShardedKey, BlockNumberList>,
381    append_only: bool,
382    writer: &mut EitherWriter<'_, CURSOR, N>,
383) -> Result<(), StageError>
384where
385    N: NodePrimitives,
386    CURSOR: DbCursorRW<reth_db_api::tables::StoragesHistory>
387        + DbCursorRO<reth_db_api::tables::StoragesHistory>,
388{
389    let mut current_key: Option<(Address, B256)> = None;
390    // Accumulator for block numbers where the current (address, storage_key) changed.
391    let mut current_list = Vec::<u64>::new();
392
393    let total_entries = collector.len();
394    let interval = (total_entries / 10).max(1);
395
396    for (index, element) in collector.iter()?.enumerate() {
397        let (k, v) = element?;
398        let sharded_key = StorageShardedKey::decode_owned(k)?;
399        let new_list = BlockNumberList::decompress_owned(v)?;
400
401        if index > 0 && index.is_multiple_of(interval) && total_entries > 10 {
402            info!(target: "sync::stages::index_history", progress = %format_args!("{:.2}%", (index as f64 / total_entries as f64) * 100.0), "Writing indices");
403        }
404
405        let partial_key = (sharded_key.address, sharded_key.sharded_key.key);
406
407        // When (address, storage_key) changes, flush the previous key's shards and start fresh.
408        if current_key != Some(partial_key) {
409            // Flush all remaining shards for the previous key (uses u64::MAX for last shard).
410            if let Some((prev_addr, prev_storage_key)) = current_key {
411                flush_storage_history_shards(
412                    prev_addr,
413                    prev_storage_key,
414                    &mut current_list,
415                    append_only,
416                    writer,
417                )?;
418            }
419
420            current_key = Some(partial_key);
421            current_list.clear();
422
423            // On incremental sync, merge with the existing last shard from the database.
424            // The last shard is stored with key (address, storage_key, u64::MAX) so we can find it.
425            if !append_only &&
426                let Some(last_shard) =
427                    writer.get_last_storage_history_shard(partial_key.0, partial_key.1)?
428            {
429                current_list.extend(last_shard.iter());
430            }
431        }
432
433        // Append new block numbers to the accumulator.
434        current_list.extend(new_list.iter());
435
436        // Flush complete shards, keeping the last (partial) shard buffered.
437        flush_storage_history_shards_partial(
438            partial_key.0,
439            partial_key.1,
440            &mut current_list,
441            append_only,
442            writer,
443        )?;
444    }
445
446    // Flush the final key's remaining shard.
447    if let Some((addr, storage_key)) = current_key {
448        flush_storage_history_shards(addr, storage_key, &mut current_list, append_only, writer)?;
449    }
450
451    Ok(())
452}
453
454/// Flushes complete shards for storage history, keeping the trailing partial shard buffered.
455///
456/// Only flushes when we have more than one shard's worth of data, keeping the last
457/// (possibly partial) shard for continued accumulation. This avoids writing a shard
458/// that may need to be updated when more indices arrive.
459fn flush_storage_history_shards_partial<N, CURSOR>(
460    address: Address,
461    storage_key: B256,
462    list: &mut Vec<u64>,
463    append_only: bool,
464    writer: &mut EitherWriter<'_, CURSOR, N>,
465) -> Result<(), StageError>
466where
467    N: NodePrimitives,
468    CURSOR: DbCursorRW<reth_db_api::tables::StoragesHistory>
469        + DbCursorRO<reth_db_api::tables::StoragesHistory>,
470{
471    // Nothing to flush if we haven't filled a complete shard yet.
472    if list.len() <= NUM_OF_INDICES_IN_SHARD {
473        return Ok(());
474    }
475
476    let num_full_shards = list.len() / NUM_OF_INDICES_IN_SHARD;
477
478    // Always keep at least one shard buffered for continued accumulation.
479    // If len is exact multiple of shard size, keep the last full shard.
480    let shards_to_flush = if list.len().is_multiple_of(NUM_OF_INDICES_IN_SHARD) {
481        num_full_shards - 1
482    } else {
483        num_full_shards
484    };
485
486    if shards_to_flush == 0 {
487        return Ok(());
488    }
489
490    // Split: flush the first N shards, keep the remainder buffered.
491    let flush_len = shards_to_flush * NUM_OF_INDICES_IN_SHARD;
492    let remainder = list.split_off(flush_len);
493
494    // Write each complete shard with its highest block number as the key.
495    for chunk in list.chunks(NUM_OF_INDICES_IN_SHARD) {
496        let highest = *chunk.last().expect("chunk is non-empty");
497        let key = StorageShardedKey::new(address, storage_key, highest);
498        let value = BlockNumberList::new_pre_sorted(chunk.iter().copied());
499
500        if append_only {
501            writer.append_storage_history(key, &value)?;
502        } else {
503            writer.upsert_storage_history(key, &value)?;
504        }
505    }
506
507    // Keep the remaining indices for the next iteration.
508    *list = remainder;
509    Ok(())
510}
511
512/// Flushes all remaining shards for storage history, using `u64::MAX` for the last shard.
513///
514/// The `u64::MAX` key for the final shard is an invariant that allows
515/// `seek_exact(address, storage_key, u64::MAX)` to find the last shard during incremental
516/// sync for merging with new indices.
517fn flush_storage_history_shards<N, CURSOR>(
518    address: Address,
519    storage_key: B256,
520    list: &mut Vec<u64>,
521    append_only: bool,
522    writer: &mut EitherWriter<'_, CURSOR, N>,
523) -> Result<(), StageError>
524where
525    N: NodePrimitives,
526    CURSOR: DbCursorRW<reth_db_api::tables::StoragesHistory>
527        + DbCursorRO<reth_db_api::tables::StoragesHistory>,
528{
529    if list.is_empty() {
530        return Ok(());
531    }
532
533    let num_chunks = list.len().div_ceil(NUM_OF_INDICES_IN_SHARD);
534
535    for (i, chunk) in list.chunks(NUM_OF_INDICES_IN_SHARD).enumerate() {
536        let is_last = i == num_chunks - 1;
537
538        // Use u64::MAX for the final shard's key. This invariant allows incremental sync
539        // to find the last shard via seek_exact(address, storage_key, u64::MAX) for merging.
540        let highest = if is_last { u64::MAX } else { *chunk.last().expect("chunk is non-empty") };
541
542        let key = StorageShardedKey::new(address, storage_key, highest);
543        let value = BlockNumberList::new_pre_sorted(chunk.iter().copied());
544
545        if append_only {
546            writer.append_storage_history(key, &value)?;
547        } else {
548            writer.upsert_storage_history(key, &value)?;
549        }
550    }
551
552    list.clear();
553    Ok(())
554}
555
556/// Buffers the block numbers of each history key before they move to an ETL [`Collector`].
557///
558/// The cache moves its entries to the collector at the first block boundary after
559/// [`DEFAULT_CACHE_THRESHOLD`] blocks, or after its estimated heap use reaches half the ETL file
560/// size, whichever comes first, so the cache does not grow with the number of distinct keys in the
561/// block range. Entries move only at block boundaries, so two collector entries of one key never
562/// end at the same block.
563struct HistoryIndexCache<P, K: Key, F, S> {
564    collector: Collector<K, BlockNumberList>,
565    /// Creates the collector key from a partial key and its highest block number.
566    sharded_key: F,
567    indices: HashMap<P, Vec<u64>, S>,
568    /// Estimated heap bytes held by `indices`.
569    size_bytes: usize,
570    /// Value of `size_bytes` at which the cache flushes on the next block boundary.
571    max_size_bytes: usize,
572    /// Number of blocks inserted since the last [`DEFAULT_CACHE_THRESHOLD`] flush.
573    blocks: u64,
574    /// Block number of the last insert.
575    current_block: Option<BlockNumber>,
576}
577
578impl<P, K, F, S> HistoryIndexCache<P, K, F, S>
579where
580    P: Eq + Hash,
581    K: Key,
582    F: Fn(P, BlockNumber) -> K,
583    S: BuildHasher,
584{
585    fn new(etl_config: &EtlConfig, indices: HashMap<P, Vec<u64>, S>, sharded_key: F) -> Self {
586        Self {
587            collector: Collector::new(etl_config.file_size, etl_config.dir.clone()),
588            sharded_key,
589            indices,
590            size_bytes: 0,
591            max_size_bytes: etl_config.file_size / 2,
592            blocks: 0,
593            current_block: None,
594        }
595    }
596
597    /// Adds `block_number` to the indices of `key`.
598    ///
599    /// Block numbers must not decrease between calls. Returns `true` if the cache reached
600    /// [`DEFAULT_CACHE_THRESHOLD`] blocks and flushed to the collector before the insert. A flush
601    /// at the size bound does not reset the block count, so the `true` results keep a fixed cadence
602    /// for progress logs.
603    fn insert(&mut self, block_number: BlockNumber, key: P) -> Result<bool, StageError> {
604        let mut flushed = false;
605        if self.current_block != Some(block_number) {
606            if self.blocks >= DEFAULT_CACHE_THRESHOLD {
607                self.flush()?;
608                self.blocks = 0;
609                flushed = true;
610            } else if self.size_bytes >= self.max_size_bytes {
611                debug!(
612                    target: "sync::stages::index_history",
613                    current_block = block_number,
614                    size_bytes = self.size_bytes,
615                    "Flushing history index cache at size bound"
616                );
617                self.flush()?;
618            }
619            self.current_block = Some(block_number);
620            self.blocks += 1;
621        }
622
623        let indices = self.indices.entry(key).or_default();
624        let capacity = indices.capacity();
625        if capacity == 0 {
626            // A new key: its map slot plus one hashbrown control byte.
627            self.size_bytes += size_of::<(P, Vec<u64>)>() + 1;
628        }
629        indices.push(block_number);
630        self.size_bytes += (indices.capacity() - capacity) * size_of::<u64>();
631
632        Ok(flushed)
633    }
634
635    /// Moves all buffered indices to the collector.
636    fn flush(&mut self) -> Result<(), StageError> {
637        for (key, indices) in self.indices.drain() {
638            let last = *indices.last().expect("indices is non-empty");
639            self.collector
640                .insert((self.sharded_key)(key, last), BlockNumberList::new_pre_sorted(indices))?;
641        }
642        self.size_bytes = 0;
643        Ok(())
644    }
645
646    /// Flushes the remaining indices and returns the collector.
647    fn finish(mut self) -> Result<Collector<K, BlockNumberList>, StageError> {
648        self.flush()?;
649        Ok(self.collector)
650    }
651}
652
653#[cfg(test)]
654mod tests {
655    use super::*;
656    use rand::Rng;
657    use reth_testing_utils::generators;
658    use std::collections::{BTreeMap, BTreeSet};
659
660    #[test]
661    fn history_index_cache_flushes_by_size() {
662        const KEYS_PER_BLOCK: usize = 50;
663        const BLOCKS: u64 = 2_000;
664
665        let mut rng = generators::rng();
666        let mut cache = HistoryIndexCache::new(
667            &EtlConfig::new(None, 128 * 1024),
668            AddressMap::default(),
669            ShardedKey::new,
670        );
671        let mut history = BTreeMap::<Address, Vec<u64>>::new();
672        let mut flushes = 0;
673        for block in 0..BLOCKS {
674            let addresses = (0..KEYS_PER_BLOCK)
675                .map(|_| Address::left_padding_from(&rng.random_range(0..20_000u64).to_be_bytes()))
676                .collect::<BTreeSet<_>>();
677            for address in addresses {
678                let size_bytes = cache.size_bytes;
679                // The block threshold does not fire in `BLOCKS` blocks, so all flushes come from
680                // the size bound.
681                assert!(!cache.insert(block, address).unwrap());
682                flushes += (cache.size_bytes < size_bytes) as usize;
683                history.entry(address).or_default().push(block);
684            }
685        }
686        assert!(flushes > 10, "cache flushed {flushes} times");
687
688        // The collector entries of each key hold its blocks in order.
689        let mut collector = cache.finish().unwrap();
690        let mut collected = BTreeMap::<Address, Vec<u64>>::new();
691        for entry in collector.iter().unwrap() {
692            let (key, value) = entry.unwrap();
693            let key = ShardedKey::<Address>::decode_owned(key).unwrap();
694            let blocks =
695                BlockNumberList::decompress_owned(value).unwrap().iter().collect::<Vec<_>>();
696            assert_eq!(key.highest_block_number, *blocks.last().unwrap());
697            collected.entry(key.key).or_default().extend(blocks);
698        }
699        assert_eq!(collected, history);
700    }
701}