forked from solana-labs/solana
-
Notifications
You must be signed in to change notification settings - Fork 232
/
accounts_db.rs
9638 lines (8896 loc) · 406 KB
/
accounts_db.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Persistent accounts are stored at this path location:
//! `<path>/<pid>/data/`
//!
//! The persistent store would allow for this mode of operation:
//! - Concurrent single thread append with many concurrent readers.
//!
//! The underlying memory is memory mapped to a file. The accounts would be
//! stored across multiple files and the mappings of file and offset of a
//! particular account would be stored in a shared index. This will allow for
//! concurrent commits without blocking reads, which will sequentially write
//! to memory, ssd or disk, and should be as fast as the hardware allow for.
//! The only required in memory data structure with a write lock is the index,
//! which should be fast to update.
//!
//! [`AppendVec`]'s only store accounts for single slots. To bootstrap the
//! index from a persistent store of [`AppendVec`]'s, the entries include
//! a "write_version". A single global atomic `AccountsDb::write_version`
//! tracks the number of commits to the entire data store. So the latest
//! commit for each slot entry would be indexed.
mod geyser_plugin_utils;
mod scan_account_storage;
pub mod stats;
pub mod tests;
#[cfg(feature = "dev-context-only-utils")]
use qualifier_attr::qualifiers;
use {
crate::{
account_info::{AccountInfo, Offset, StorageLocation},
account_storage::{
meta::StoredAccountMeta, AccountStorage, AccountStorageStatus, ShrinkInProgress,
},
accounts_cache::{AccountsCache, CachedAccount, SlotCache},
accounts_db::stats::{
AccountsStats, BankHashStats, CleanAccountsStats, FlushStats, PurgeStats,
ShrinkAncientStats, ShrinkStats, ShrinkStatsSub, StoreAccountsTiming,
},
accounts_file::{
AccountsFile, AccountsFileError, AccountsFileProvider, MatchAccountOwnerError,
StorageAccess, ALIGN_BOUNDARY_OFFSET,
},
accounts_hash::{
AccountHash, AccountLtHash, AccountsDeltaHash, AccountsHash, AccountsHashKind,
AccountsHasher, AccountsLtHash, CalcAccountsHashConfig, CalculateHashIntermediate,
HashStats, IncrementalAccountsHash, SerdeAccountsDeltaHash, SerdeAccountsHash,
SerdeIncrementalAccountsHash, ZeroLamportAccounts, ZERO_LAMPORT_ACCOUNT_HASH,
ZERO_LAMPORT_ACCOUNT_LT_HASH,
},
accounts_index::{
in_mem_accounts_index::StartupStats, AccountSecondaryIndexes, AccountsIndex,
AccountsIndexConfig, AccountsIndexRootsStats, AccountsIndexScanResult, DiskIndexValue,
IndexKey, IndexValue, IsCached, RefCount, ScanConfig, ScanFilter, ScanResult, SlotList,
UpsertReclaim, ZeroLamport, ACCOUNTS_INDEX_CONFIG_FOR_BENCHMARKS,
ACCOUNTS_INDEX_CONFIG_FOR_TESTING,
},
accounts_index_storage::Startup,
accounts_partition::RentPayingAccountsByPartition,
accounts_update_notifier_interface::AccountsUpdateNotifier,
active_stats::{ActiveStatItem, ActiveStats},
ancestors::Ancestors,
ancient_append_vecs::{
get_ancient_append_vec_capacity, is_ancient, AccountsToStore, StorageSelector,
},
append_vec::{aligned_stored_size, STORE_META_OVERHEAD},
cache_hash_data::{CacheHashData, DeletionPolicy as CacheHashDeletionPolicy},
contains::Contains,
epoch_accounts_hash::EpochAccountsHashManager,
partitioned_rewards::{PartitionedEpochRewardsConfig, TestPartitionedEpochRewards},
read_only_accounts_cache::ReadOnlyAccountsCache,
sorted_storages::SortedStorages,
storable_accounts::{StorableAccounts, StorableAccountsBySlot},
u64_align, utils,
verify_accounts_hash_in_background::VerifyAccountsHashInBackground,
},
crossbeam_channel::{unbounded, Receiver, Sender},
dashmap::{DashMap, DashSet},
log::*,
rand::{thread_rng, Rng},
rayon::{prelude::*, ThreadPool},
seqlock::SeqLock,
smallvec::SmallVec,
solana_lattice_hash::lt_hash::LtHash,
solana_measure::{meas_dur, measure::Measure, measure_us},
solana_nohash_hasher::{IntMap, IntSet},
solana_rayon_threadlimit::get_thread_count,
solana_sdk::{
account::{Account, AccountSharedData, ReadableAccount},
clock::{BankId, Epoch, Slot},
epoch_schedule::EpochSchedule,
genesis_config::GenesisConfig,
hash::Hash,
pubkey::Pubkey,
rent_collector::RentCollector,
saturating_add_assign,
transaction::SanitizedTransaction,
},
std::{
borrow::Cow,
boxed::Box,
collections::{BTreeSet, HashMap, HashSet, VecDeque},
fs,
hash::{Hash as StdHash, Hasher as StdHasher},
io::Result as IoResult,
num::{NonZeroUsize, Saturating},
ops::{Range, RangeBounds},
path::{Path, PathBuf},
sync::{
atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering},
Arc, Condvar, Mutex, RwLock,
},
thread::{sleep, Builder},
time::{Duration, Instant},
},
tempfile::TempDir,
};
// when the accounts write cache exceeds this many bytes, we will flush it
// this can be specified on the command line, too (--accounts-db-cache-limit-mb)
const WRITE_CACHE_LIMIT_BYTES_DEFAULT: u64 = 15_000_000_000;
const SCAN_SLOT_PAR_ITER_THRESHOLD: usize = 4000;
const UNREF_ACCOUNTS_BATCH_SIZE: usize = 10_000;
const DEFAULT_FILE_SIZE: u64 = 4 * 1024 * 1024;
const DEFAULT_NUM_DIRS: u32 = 4;
// When calculating hashes, it is helpful to break the pubkeys found into bins based on the pubkey value.
// More bins means smaller vectors to sort, copy, etc.
pub const DEFAULT_HASH_CALCULATION_PUBKEY_BINS: usize = 65536;
// Without chunks, we end up with 1 output vec for each outer snapshot storage.
// This results in too many vectors to be efficient.
// Chunks when scanning storages to calculate hashes.
// If this is too big, we don't get enough parallelism of scanning storages.
// If this is too small, then we produce too many output vectors to iterate.
// Metrics indicate a sweet spot in the 2.5k-5k range for mnb.
const MAX_ITEMS_PER_CHUNK: Slot = 2_500;
// When getting accounts for shrinking from the index, this is the # of accounts to lookup per thread.
// This allows us to split up accounts index accesses across multiple threads.
const SHRINK_COLLECT_CHUNK_SIZE: usize = 50;
/// The number of shrink candidate slots that is small enough so that
/// additional storages from ancient slots can be added to the
/// candidates for shrinking.
const SHRINK_INSERT_ANCIENT_THRESHOLD: usize = 10;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum CreateAncientStorage {
/// ancient storages are created by appending
Append,
/// ancient storages are created by 1-shot write to pack multiple accounts together more efficiently with new formats
#[default]
Pack,
}
#[derive(Debug)]
enum StoreTo<'a> {
/// write to cache
Cache,
/// write to storage
Storage(&'a Arc<AccountStorageEntry>),
}
impl<'a> StoreTo<'a> {
fn is_cached(&self) -> bool {
matches!(self, StoreTo::Cache)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ScanAccountStorageData {
/// callback for accounts in storage will not include `data`
NoData,
/// return data (&[u8]) for each account.
/// This can be expensive to get and is not necessary for many scan operations.
DataRefForStorage,
}
#[derive(Default, Debug)]
/// hold alive accounts
/// alive means in the accounts index
pub(crate) struct AliveAccounts<'a> {
/// slot the accounts are currently stored in
pub(crate) slot: Slot,
pub(crate) accounts: Vec<&'a AccountFromStorage>,
pub(crate) bytes: usize,
}
/// separate pubkeys into those with a single refcount and those with > 1 refcount
#[derive(Debug)]
pub(crate) struct ShrinkCollectAliveSeparatedByRefs<'a> {
/// accounts where ref_count = 1
pub(crate) one_ref: AliveAccounts<'a>,
/// account where ref_count > 1, but this slot contains the alive entry with the highest slot
pub(crate) many_refs_this_is_newest_alive: AliveAccounts<'a>,
/// account where ref_count > 1, and this slot is NOT the highest alive entry in the index for the pubkey
pub(crate) many_refs_old_alive: AliveAccounts<'a>,
}
/// Configuration Parameters for running accounts hash and total lamports verification
#[derive(Debug, Clone)]
pub struct VerifyAccountsHashAndLamportsConfig<'a> {
/// bank ancestors
pub ancestors: &'a Ancestors,
/// true to verify hash calculation
pub test_hash_calculation: bool,
/// epoch_schedule
pub epoch_schedule: &'a EpochSchedule,
/// rent_collector
pub rent_collector: &'a RentCollector,
/// true to ignore mismatches
pub ignore_mismatch: bool,
/// true to dump debug log if mismatch happens
pub store_detailed_debug_info: bool,
/// true to use dedicated background thread pool for verification
pub use_bg_thread_pool: bool,
}
pub(crate) trait ShrinkCollectRefs<'a>: Sync + Send {
fn with_capacity(capacity: usize, slot: Slot) -> Self;
fn collect(&mut self, other: Self);
fn add(
&mut self,
ref_count: u64,
account: &'a AccountFromStorage,
slot_list: &[(Slot, AccountInfo)],
);
fn len(&self) -> usize;
fn alive_bytes(&self) -> usize;
fn alive_accounts(&self) -> &Vec<&'a AccountFromStorage>;
}
impl<'a> ShrinkCollectRefs<'a> for AliveAccounts<'a> {
fn collect(&mut self, mut other: Self) {
self.bytes = self.bytes.saturating_add(other.bytes);
self.accounts.append(&mut other.accounts);
}
fn with_capacity(capacity: usize, slot: Slot) -> Self {
Self {
accounts: Vec::with_capacity(capacity),
bytes: 0,
slot,
}
}
fn add(
&mut self,
_ref_count: u64,
account: &'a AccountFromStorage,
_slot_list: &[(Slot, AccountInfo)],
) {
self.accounts.push(account);
self.bytes = self.bytes.saturating_add(account.stored_size());
}
fn len(&self) -> usize {
self.accounts.len()
}
fn alive_bytes(&self) -> usize {
self.bytes
}
fn alive_accounts(&self) -> &Vec<&'a AccountFromStorage> {
&self.accounts
}
}
impl<'a> ShrinkCollectRefs<'a> for ShrinkCollectAliveSeparatedByRefs<'a> {
fn collect(&mut self, other: Self) {
self.one_ref.collect(other.one_ref);
self.many_refs_this_is_newest_alive
.collect(other.many_refs_this_is_newest_alive);
self.many_refs_old_alive.collect(other.many_refs_old_alive);
}
fn with_capacity(capacity: usize, slot: Slot) -> Self {
Self {
one_ref: AliveAccounts::with_capacity(capacity, slot),
many_refs_this_is_newest_alive: AliveAccounts::with_capacity(0, slot),
many_refs_old_alive: AliveAccounts::with_capacity(0, slot),
}
}
fn add(
&mut self,
ref_count: u64,
account: &'a AccountFromStorage,
slot_list: &[(Slot, AccountInfo)],
) {
let other = if ref_count == 1 {
&mut self.one_ref
} else if slot_list.len() == 1
|| !slot_list
.iter()
.any(|(slot_list_slot, _info)| slot_list_slot > &self.many_refs_old_alive.slot)
{
// this entry is alive but is newer than any other slot in the index
&mut self.many_refs_this_is_newest_alive
} else {
// This entry is alive but is older than at least one other slot in the index.
// We would expect clean to get rid of the entry for THIS slot at some point, but clean hasn't done that yet.
&mut self.many_refs_old_alive
};
other.add(ref_count, account, slot_list);
}
fn len(&self) -> usize {
self.one_ref
.len()
.saturating_add(self.many_refs_old_alive.len())
.saturating_add(self.many_refs_this_is_newest_alive.len())
}
fn alive_bytes(&self) -> usize {
self.one_ref
.alive_bytes()
.saturating_add(self.many_refs_old_alive.alive_bytes())
.saturating_add(self.many_refs_this_is_newest_alive.alive_bytes())
}
fn alive_accounts(&self) -> &Vec<&'a AccountFromStorage> {
unimplemented!("illegal use");
}
}
pub enum StoreReclaims {
/// normal reclaim mode
Default,
/// do not return reclaims from accounts index upsert
Ignore,
}
/// while combining into ancient append vecs, we need to keep track of the current one that is receiving new data
/// The pattern for callers is:
/// 1. this is a mut local
/// 2. do some version of create/new
/// 3. use it (slot, append_vec, etc.)
/// 4. re-create it sometimes
/// 5. goto 3
///
/// If a caller uses it before initializing it, it will be a runtime unwrap() error, similar to an assert.
/// That condition is an illegal use pattern and is justifiably an assertable condition.
#[derive(Default)]
struct CurrentAncientAccountsFile {
slot_and_accounts_file: Option<(Slot, Arc<AccountStorageEntry>)>,
}
impl CurrentAncientAccountsFile {
fn new(slot: Slot, append_vec: Arc<AccountStorageEntry>) -> CurrentAncientAccountsFile {
Self {
slot_and_accounts_file: Some((slot, append_vec)),
}
}
/// Create ancient accounts file for a slot
/// min_bytes: the new accounts file needs to have at least this capacity
#[must_use]
fn create_ancient_accounts_file<'a>(
&mut self,
slot: Slot,
db: &'a AccountsDb,
min_bytes: usize,
) -> ShrinkInProgress<'a> {
let size = get_ancient_append_vec_capacity().max(min_bytes as u64);
let shrink_in_progress = db.get_store_for_shrink(slot, size);
*self = Self::new(slot, Arc::clone(shrink_in_progress.new_storage()));
shrink_in_progress
}
#[must_use]
fn create_if_necessary<'a>(
&mut self,
slot: Slot,
db: &'a AccountsDb,
min_bytes: usize,
) -> Option<ShrinkInProgress<'a>> {
if self.slot_and_accounts_file.is_none() {
Some(self.create_ancient_accounts_file(slot, db, min_bytes))
} else {
None
}
}
/// note this requires that 'slot_and_accounts_file' is Some
fn slot(&self) -> Slot {
self.slot_and_accounts_file.as_ref().unwrap().0
}
/// note this requires that 'slot_and_accounts_file' is Some
fn accounts_file(&self) -> &Arc<AccountStorageEntry> {
&self.slot_and_accounts_file.as_ref().unwrap().1
}
/// helper function to cleanup call to 'store_accounts_frozen'
/// return timing and bytes written
fn store_ancient_accounts(
&self,
db: &AccountsDb,
accounts_to_store: &AccountsToStore,
storage_selector: StorageSelector,
) -> (StoreAccountsTiming, u64) {
let accounts = accounts_to_store.get(storage_selector);
let previous_available = self.accounts_file().accounts.remaining_bytes();
let accounts = [(accounts_to_store.slot(), accounts)];
let storable_accounts = StorableAccountsBySlot::new(self.slot(), &accounts, db);
let timing = db.store_accounts_frozen(storable_accounts, self.accounts_file());
let bytes_written =
previous_available.saturating_sub(self.accounts_file().accounts.remaining_bytes());
assert_eq!(
bytes_written,
u64_align!(accounts_to_store.get_bytes(storage_selector)) as u64
);
(timing, bytes_written)
}
}
/// specifies how to return zero lamport accounts from a load
#[derive(Clone, Copy)]
enum LoadZeroLamports {
/// return None if loaded account has zero lamports
None,
/// return Some(account with zero lamports) if loaded account has zero lamports
/// This used to be the only behavior.
/// Note that this is non-deterministic if clean is running asynchronously.
/// If a zero lamport account exists in the index, then Some is returned.
/// Once it is cleaned from the index, None is returned.
#[cfg(feature = "dev-context-only-utils")]
SomeWithZeroLamportAccountForTests,
}
#[derive(Debug)]
struct AncientSlotPubkeysInner {
pubkeys: HashSet<Pubkey>,
slot: Slot,
}
#[derive(Debug, Default)]
struct AncientSlotPubkeys {
inner: Option<AncientSlotPubkeysInner>,
}
impl AncientSlotPubkeys {
/// All accounts in 'slot' will be moved to 'current_ancient'
/// If 'slot' is different than the 'current_ancient'.slot, then an account in 'slot' may ALREADY be in the current ancient append vec.
/// In that case, we need to unref the pubkey because it will now only be referenced from 'current_ancient'.slot and no longer from 'slot'.
/// 'self' is also changed to accumulate the pubkeys that now exist in 'current_ancient'
/// When 'slot' differs from the previous inner slot, then we have moved to a new ancient append vec, and inner.pubkeys gets reset to the
/// pubkeys in the new 'current_ancient'.append_vec
fn maybe_unref_accounts_already_in_ancient(
&mut self,
slot: Slot,
db: &AccountsDb,
current_ancient: &CurrentAncientAccountsFile,
to_store: &AccountsToStore,
) {
if slot != current_ancient.slot() {
// we are taking accounts from 'slot' and putting them into 'current_ancient.slot()'
// StorageSelector::Primary here because only the accounts that are moving from 'slot' to 'current_ancient.slot()'
// Any overflow accounts will get written into a new append vec AT 'slot', so they don't need to be unrefed
let accounts = to_store.get(StorageSelector::Primary);
if Some(current_ancient.slot()) != self.inner.as_ref().map(|ap| ap.slot) {
let mut pubkeys = HashSet::new();
current_ancient
.accounts_file()
.accounts
.scan_pubkeys(|pubkey| {
pubkeys.insert(*pubkey);
});
self.inner = Some(AncientSlotPubkeysInner {
pubkeys,
slot: current_ancient.slot(),
});
}
// accounts in 'slot' but ALSO already in the ancient append vec at a different slot need to be unref'd since 'slot' is going away
// unwrap cannot fail because the code above will cause us to set it to Some(...) if it is None
db.unref_accounts_already_in_storage(
accounts,
self.inner.as_mut().map(|p| &mut p.pubkeys).unwrap(),
);
}
}
}
#[derive(Debug)]
pub(crate) struct ShrinkCollect<'a, T: ShrinkCollectRefs<'a>> {
pub(crate) slot: Slot,
pub(crate) capacity: u64,
pub(crate) pubkeys_to_unref: Vec<&'a Pubkey>,
pub(crate) zero_lamport_single_ref_pubkeys: Vec<&'a Pubkey>,
pub(crate) alive_accounts: T,
/// total size in storage of all alive accounts
pub(crate) alive_total_bytes: usize,
pub(crate) total_starting_accounts: usize,
/// true if all alive accounts are zero lamports
pub(crate) all_are_zero_lamports: bool,
}
pub const ACCOUNTS_DB_CONFIG_FOR_TESTING: AccountsDbConfig = AccountsDbConfig {
index: Some(ACCOUNTS_INDEX_CONFIG_FOR_TESTING),
account_indexes: None,
base_working_path: None,
accounts_hash_cache_path: None,
shrink_paths: None,
shrink_ratio: DEFAULT_ACCOUNTS_SHRINK_THRESHOLD_OPTION,
read_cache_limit_bytes: None,
write_cache_limit_bytes: None,
ancient_append_vec_offset: None,
ancient_storage_ideal_size: None,
max_ancient_storages: None,
skip_initial_hash_calc: false,
exhaustively_verify_refcounts: false,
create_ancient_storage: CreateAncientStorage::Pack,
test_partitioned_epoch_rewards: TestPartitionedEpochRewards::CompareResults,
test_skip_rewrites_but_include_in_bank_hash: false,
storage_access: StorageAccess::Mmap,
scan_filter_for_shrinking: ScanFilter::OnlyAbnormalWithVerify,
enable_experimental_accumulator_hash: false,
verify_experimental_accumulator_hash: false,
num_clean_threads: None,
num_foreground_threads: None,
num_hash_threads: None,
hash_calculation_pubkey_bins: Some(4),
};
pub const ACCOUNTS_DB_CONFIG_FOR_BENCHMARKS: AccountsDbConfig = AccountsDbConfig {
index: Some(ACCOUNTS_INDEX_CONFIG_FOR_BENCHMARKS),
account_indexes: None,
base_working_path: None,
accounts_hash_cache_path: None,
shrink_paths: None,
shrink_ratio: DEFAULT_ACCOUNTS_SHRINK_THRESHOLD_OPTION,
read_cache_limit_bytes: None,
write_cache_limit_bytes: None,
ancient_append_vec_offset: None,
ancient_storage_ideal_size: None,
max_ancient_storages: None,
skip_initial_hash_calc: false,
exhaustively_verify_refcounts: false,
create_ancient_storage: CreateAncientStorage::Pack,
test_partitioned_epoch_rewards: TestPartitionedEpochRewards::None,
test_skip_rewrites_but_include_in_bank_hash: false,
storage_access: StorageAccess::Mmap,
scan_filter_for_shrinking: ScanFilter::OnlyAbnormalWithVerify,
enable_experimental_accumulator_hash: false,
verify_experimental_accumulator_hash: false,
num_clean_threads: None,
num_foreground_threads: None,
num_hash_threads: None,
hash_calculation_pubkey_bins: None,
};
pub type BinnedHashData = Vec<Vec<CalculateHashIntermediate>>;
struct LoadAccountsIndexForShrink<'a, T: ShrinkCollectRefs<'a>> {
/// all alive accounts
alive_accounts: T,
/// pubkeys that are going to be unref'd in the accounts index after we are
/// done with shrinking, because they are dead
pubkeys_to_unref: Vec<&'a Pubkey>,
/// pubkeys that are the last remaining zero lamport instance of an account
zero_lamport_single_ref_pubkeys: Vec<&'a Pubkey>,
/// true if all alive accounts are zero lamport accounts
all_are_zero_lamports: bool,
}
/// reference an account found during scanning a storage. This is a byval struct to replace
/// `StoredAccountMeta`
#[derive(Debug, PartialEq, Copy, Clone)]
pub struct AccountFromStorage {
pub index_info: AccountInfo,
pub data_len: u64,
pub pubkey: Pubkey,
}
impl ZeroLamport for AccountFromStorage {
fn is_zero_lamport(&self) -> bool {
self.index_info.is_zero_lamport()
}
}
impl AccountFromStorage {
pub fn pubkey(&self) -> &Pubkey {
&self.pubkey
}
pub fn stored_size(&self) -> usize {
aligned_stored_size(self.data_len as usize)
}
pub fn data_len(&self) -> usize {
self.data_len as usize
}
pub fn new(account: &StoredAccountMeta) -> Self {
// the id is irrelevant in this account info. This structure is only used DURING shrink operations.
// In those cases, there is only 1 append vec id per slot when we read the accounts.
// Any value of storage id in account info works fine when we want the 'normal' storage.
let storage_id = 0;
AccountFromStorage {
index_info: AccountInfo::new(
StorageLocation::AppendVec(storage_id, account.offset()),
account.lamports(),
),
pubkey: *account.pubkey(),
data_len: account.data_len() as u64,
}
}
}
pub struct GetUniqueAccountsResult {
pub stored_accounts: Vec<AccountFromStorage>,
pub capacity: u64,
pub num_duplicated_accounts: usize,
}
pub struct AccountsAddRootTiming {
pub index_us: u64,
pub cache_us: u64,
pub store_us: u64,
}
/// Slots older the "number of slots in an epoch minus this number"
/// than max root are treated as ancient and subject to packing.
/// | older |<- slots in an epoch ->| max root
/// | older |<- offset ->| |
/// | ancient | modern |
///
/// If this is negative, this many slots older than the number of
/// slots in epoch are still treated as modern (ie. non-ancient).
/// | older |<- abs(offset) ->|<- slots in an epoch ->| max root
/// | ancient | modern |
///
/// Note that another constant DEFAULT_MAX_ANCIENT_STORAGES sets a
/// threshold for combining ancient storages so that their overall
/// number is under a certain limit, whereas this constant establishes
/// the distance from the max root slot beyond which storages holding
/// the account data for the slots are considered ancient by the
/// shrinking algorithm.
const ANCIENT_APPEND_VEC_DEFAULT_OFFSET: Option<i64> = Some(100_000);
/// The smallest size of ideal ancient storage.
/// The setting can be overridden on the command line
/// with --accounts-db-ancient-ideal-storage-size option.
const DEFAULT_ANCIENT_STORAGE_IDEAL_SIZE: u64 = 100_000;
/// Default value for the number of ancient storages the ancient slot
/// combining should converge to.
pub const DEFAULT_MAX_ANCIENT_STORAGES: usize = 100_000;
#[derive(Debug, Default, Clone)]
pub struct AccountsDbConfig {
pub index: Option<AccountsIndexConfig>,
pub account_indexes: Option<AccountSecondaryIndexes>,
/// Base directory for various necessary files
pub base_working_path: Option<PathBuf>,
pub accounts_hash_cache_path: Option<PathBuf>,
pub shrink_paths: Option<Vec<PathBuf>>,
pub shrink_ratio: AccountShrinkThreshold,
/// The low and high watermark sizes for the read cache, in bytes.
/// If None, defaults will be used.
pub read_cache_limit_bytes: Option<(usize, usize)>,
pub write_cache_limit_bytes: Option<u64>,
/// if None, ancient append vecs are set to ANCIENT_APPEND_VEC_DEFAULT_OFFSET
/// Some(offset) means include slots up to (max_slot - (slots_per_epoch - 'offset'))
pub ancient_append_vec_offset: Option<i64>,
pub ancient_storage_ideal_size: Option<u64>,
pub max_ancient_storages: Option<usize>,
pub hash_calculation_pubkey_bins: Option<usize>,
pub test_skip_rewrites_but_include_in_bank_hash: bool,
pub skip_initial_hash_calc: bool,
pub exhaustively_verify_refcounts: bool,
/// how to create ancient storages
pub create_ancient_storage: CreateAncientStorage,
pub test_partitioned_epoch_rewards: TestPartitionedEpochRewards,
pub storage_access: StorageAccess,
pub scan_filter_for_shrinking: ScanFilter,
pub enable_experimental_accumulator_hash: bool,
pub verify_experimental_accumulator_hash: bool,
/// Number of threads for background cleaning operations (`thread_pool_clean')
pub num_clean_threads: Option<NonZeroUsize>,
/// Number of threads for foreground operations (`thread_pool`)
pub num_foreground_threads: Option<NonZeroUsize>,
/// Number of threads for background accounts hashing (`thread_pool_hash`)
pub num_hash_threads: Option<NonZeroUsize>,
}
#[cfg(not(test))]
const ABSURD_CONSECUTIVE_FAILED_ITERATIONS: usize = 100;
#[derive(Debug, Clone, Copy)]
pub enum AccountShrinkThreshold {
/// Measure the total space sparseness across all candidates
/// And select the candidates by using the top sparse account storage entries to shrink.
/// The value is the overall shrink threshold measured as ratio of the total live bytes
/// over the total bytes.
TotalSpace { shrink_ratio: f64 },
/// Use the following option to shrink all stores whose alive ratio is below
/// the specified threshold.
IndividualStore { shrink_ratio: f64 },
}
pub const DEFAULT_ACCOUNTS_SHRINK_OPTIMIZE_TOTAL_SPACE: bool = true;
pub const DEFAULT_ACCOUNTS_SHRINK_RATIO: f64 = 0.80;
// The default extra account space in percentage from the ideal target
const DEFAULT_ACCOUNTS_SHRINK_THRESHOLD_OPTION: AccountShrinkThreshold =
AccountShrinkThreshold::TotalSpace {
shrink_ratio: DEFAULT_ACCOUNTS_SHRINK_RATIO,
};
impl Default for AccountShrinkThreshold {
fn default() -> AccountShrinkThreshold {
DEFAULT_ACCOUNTS_SHRINK_THRESHOLD_OPTION
}
}
pub enum ScanStorageResult<R, B> {
Cached(Vec<R>),
Stored(B),
}
#[derive(Debug, Default)]
pub struct IndexGenerationInfo {
pub accounts_data_len: u64,
pub rent_paying_accounts_by_partition: RentPayingAccountsByPartition,
/// The lt hash of the old/duplicate accounts identified during index generation.
/// Will be used when verifying the accounts lt hash, after rebuilding a Bank.
pub duplicates_lt_hash: Option<Box<DuplicatesLtHash>>,
}
#[derive(Debug, Default)]
struct SlotIndexGenerationInfo {
insert_time_us: u64,
num_accounts: u64,
num_accounts_rent_paying: usize,
accounts_data_len: u64,
amount_to_top_off_rent: u64,
rent_paying_accounts_by_partition: Vec<Pubkey>,
zero_lamport_pubkeys: Vec<Pubkey>,
all_accounts_are_zero_lamports: bool,
}
/// The lt hash of old/duplicate accounts
///
/// Accumulation of all the duplicate accounts found during index generation.
/// These accounts need to have their lt hashes mixed *out*.
/// This is the final value, that when applied to all the storages at startup,
/// will produce the correct accounts lt hash.
#[derive(Debug, Clone)]
pub struct DuplicatesLtHash(pub LtHash);
impl Default for DuplicatesLtHash {
fn default() -> Self {
Self(LtHash::identity())
}
}
#[derive(Default, Debug)]
struct GenerateIndexTimings {
pub total_time_us: u64,
pub index_time: u64,
pub scan_time: u64,
pub insertion_time_us: u64,
pub min_bin_size_in_mem: usize,
pub max_bin_size_in_mem: usize,
pub total_items_in_mem: usize,
pub storage_size_storages_us: u64,
pub index_flush_us: u64,
pub rent_paying: AtomicUsize,
pub amount_to_top_off_rent: AtomicU64,
pub total_including_duplicates: u64,
pub accounts_data_len_dedup_time_us: u64,
pub total_duplicate_slot_keys: u64,
pub total_num_unique_duplicate_keys: u64,
pub num_duplicate_accounts: u64,
pub populate_duplicate_keys_us: u64,
pub total_slots: u64,
pub slots_to_clean: u64,
pub par_duplicates_lt_hash_us: AtomicU64,
pub visit_zero_lamports_us: u64,
pub num_zero_lamport_single_refs: u64,
pub all_accounts_are_zero_lamports_slots: u64,
}
#[derive(Default, Debug, PartialEq, Eq)]
struct StorageSizeAndCount {
/// total size stored, including both alive and dead bytes
pub stored_size: usize,
/// number of accounts in the storage including both alive and dead accounts
pub count: usize,
}
type StorageSizeAndCountMap = DashMap<AccountsFileId, StorageSizeAndCount>;
impl GenerateIndexTimings {
pub fn report(&self, startup_stats: &StartupStats) {
datapoint_info!(
"generate_index",
("overall_us", self.total_time_us, i64),
// we cannot accurately measure index insertion time because of many threads and lock contention
("total_us", self.index_time, i64),
("scan_stores_us", self.scan_time, i64),
("insertion_time_us", self.insertion_time_us, i64),
("min_bin_size_in_mem", self.min_bin_size_in_mem as i64, i64),
("max_bin_size_in_mem", self.max_bin_size_in_mem as i64, i64),
(
"storage_size_storages_us",
self.storage_size_storages_us as i64,
i64
),
("index_flush_us", self.index_flush_us as i64, i64),
(
"total_rent_paying",
self.rent_paying.load(Ordering::Relaxed) as i64,
i64
),
(
"amount_to_top_off_rent",
self.amount_to_top_off_rent.load(Ordering::Relaxed) as i64,
i64
),
(
"total_items_including_duplicates",
self.total_including_duplicates as i64,
i64
),
("total_items_in_mem", self.total_items_in_mem as i64, i64),
(
"accounts_data_len_dedup_time_us",
self.accounts_data_len_dedup_time_us as i64,
i64
),
(
"total_duplicate_slot_keys",
self.total_duplicate_slot_keys as i64,
i64
),
(
"total_num_unique_duplicate_keys",
self.total_num_unique_duplicate_keys as i64,
i64
),
(
"num_duplicate_accounts",
self.num_duplicate_accounts as i64,
i64
),
(
"populate_duplicate_keys_us",
self.populate_duplicate_keys_us as i64,
i64
),
("total_slots", self.total_slots, i64),
("slots_to_clean", self.slots_to_clean, i64),
(
"copy_data_us",
startup_stats.copy_data_us.swap(0, Ordering::Relaxed),
i64
),
(
"par_duplicates_lt_hash_us",
self.par_duplicates_lt_hash_us.load(Ordering::Relaxed),
i64
),
(
"num_zero_lamport_single_refs",
self.num_zero_lamport_single_refs as i64,
i64
),
(
"visit_zero_lamports_us",
self.visit_zero_lamports_us as i64,
i64
),
(
"all_accounts_are_zero_lamports_slots",
self.all_accounts_are_zero_lamports_slots,
i64
),
);
}
}
impl IndexValue for AccountInfo {}
impl DiskIndexValue for AccountInfo {}
impl ZeroLamport for AccountSharedData {
fn is_zero_lamport(&self) -> bool {
self.lamports() == 0
}
}
impl ZeroLamport for Account {
fn is_zero_lamport(&self) -> bool {
self.lamports() == 0
}
}
struct MultiThreadProgress<'a> {
last_update: Instant,
my_last_report_count: u64,
total_count: &'a AtomicU64,
report_delay_secs: u64,
first_caller: bool,
ultimate_count: u64,
start_time: Instant,
}
impl<'a> MultiThreadProgress<'a> {
fn new(total_count: &'a AtomicU64, report_delay_secs: u64, ultimate_count: u64) -> Self {
Self {
last_update: Instant::now(),
my_last_report_count: 0,
total_count,
report_delay_secs,
first_caller: false,
ultimate_count,
start_time: Instant::now(),
}
}
fn report(&mut self, my_current_count: u64) {
let now = Instant::now();
if now.duration_since(self.last_update).as_secs() >= self.report_delay_secs {
let my_total_newly_processed_slots_since_last_report =
my_current_count - self.my_last_report_count;
self.my_last_report_count = my_current_count;
let previous_total_processed_slots_across_all_threads = self.total_count.fetch_add(
my_total_newly_processed_slots_since_last_report,
Ordering::Relaxed,
);
self.first_caller =
self.first_caller || 0 == previous_total_processed_slots_across_all_threads;
if self.first_caller {
let total = previous_total_processed_slots_across_all_threads
+ my_total_newly_processed_slots_since_last_report;
info!(
"generating index: {}/{} slots... ({}/s)",
total,
self.ultimate_count,
total / self.start_time.elapsed().as_secs().max(1),
);
}
self.last_update = now;
}
}
}
/// An offset into the AccountsDb::storage vector
pub type AtomicAccountsFileId = AtomicU32;
pub type AccountsFileId = u32;
type AccountSlots = HashMap<Pubkey, IntSet<Slot>>;
type SlotOffsets = IntMap<Slot, IntSet<Offset>>;
type ReclaimResult = (AccountSlots, SlotOffsets);
type PubkeysRemovedFromAccountsIndex = HashSet<Pubkey>;
type ShrinkCandidates = IntSet<Slot>;
// Some hints for applicability of additional sanity checks for the do_load fast-path;
// Slower fallback code path will be taken if the fast path has failed over the retry
// threshold, regardless of these hints. Also, load cannot fail not-deterministically
// even under very rare circumstances, unlike previously did allow.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LoadHint {
// Caller hints that it's loading transactions for a block which is
// descended from the current root, and at the tip of its fork.
// Thereby, further this assumes AccountIndex::max_root should not increase
// during this load, meaning there should be no squash.
// Overall, this enables us to assert!() strictly while running the fast-path for
// account loading, while maintaining the determinism of account loading and resultant
// transaction execution thereof.
FixedMaxRoot,
/// same as `FixedMaxRoot`, except do not populate the read cache on load
FixedMaxRootDoNotPopulateReadCache,
// Caller can't hint the above safety assumption. Generally RPC and miscellaneous
// other call-site falls into this category. The likelihood of slower path is slightly
// increased as well.
Unspecified,
}
#[derive(Debug)]
pub enum LoadedAccountAccessor<'a> {
// StoredAccountMeta can't be held directly here due to its lifetime dependency to
// AccountStorageEntry
Stored(Option<(Arc<AccountStorageEntry>, usize)>),
// None value in Cached variant means the cache was flushed
Cached(Option<Cow<'a, CachedAccount>>),
}
impl<'a> LoadedAccountAccessor<'a> {
fn check_and_get_loaded_account_shared_data(&mut self) -> AccountSharedData {
// all of these following .expect() and .unwrap() are like serious logic errors,
// ideal for representing this as rust type system....
match self {
LoadedAccountAccessor::Stored(Some((maybe_storage_entry, offset))) => {
// If we do find the storage entry, we can guarantee that the storage entry is
// safe to read from because we grabbed a reference to the storage entry while it
// was still in the storage map. This means even if the storage entry is removed
// from the storage map after we grabbed the storage entry, the recycler should not
// reset the storage entry until we drop the reference to the storage entry.
maybe_storage_entry.get_account_shared_data(*offset).expect(
"If a storage entry was found in the storage map, it must not have been reset \
yet",
)
}
_ => self.check_and_get_loaded_account(|loaded_account| loaded_account.take_account()),
}
}
fn check_and_get_loaded_account<T>(
&mut self,
callback: impl for<'local> FnMut(LoadedAccount<'local>) -> T,