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
use hash_db::Prefix;
use kvdb::KeyValueDB;
use lazy_static::lazy_static;
use rand::Rng;
use sp_state_machine::Backend as _;
use sp_trie::{trie_types::TrieDBMut, TrieMut as _};
use std::{borrow::Cow, collections::HashMap, sync::Arc};
use node_primitives::Hash;
use crate::{
core::{self, Mode, Path},
generator::generate_trie,
simple_trie::SimpleTrie,
tempdb::{DatabaseType, TempDatabase},
};
pub const SAMPLE_SIZE: usize = 100;
pub const TEST_WRITE_SIZE: usize = 128;
pub type KeyValue = (Vec<u8>, Vec<u8>);
pub type KeyValues = Vec<KeyValue>;
#[derive(Clone, Copy, Debug, derive_more::Display)]
pub enum DatabaseSize {
#[display(fmt = "empty")]
Empty,
#[display(fmt = "smallest")]
Smallest,
#[display(fmt = "small")]
Small,
#[display(fmt = "medium")]
Medium,
#[display(fmt = "large")]
Large,
#[display(fmt = "huge")]
Huge,
}
lazy_static! {
static ref KUSAMA_STATE_DISTRIBUTION: SizePool =
SizePool::from_histogram(crate::state_sizes::KUSAMA_STATE_DISTRIBUTION);
}
impl DatabaseSize {
fn keys(&self) -> usize {
let val = match *self {
Self::Empty => 200,
Self::Smallest => 1_000,
Self::Small => 10_000,
Self::Medium => 100_000,
Self::Large => 200_000,
Self::Huge => 1_000_000,
};
assert_eq!(val % SAMPLE_SIZE, 0);
val
}
}
fn pretty_print(v: usize) -> String {
let mut print = String::new();
for (idx, val) in v.to_string().chars().rev().enumerate() {
if idx != 0 && idx % 3 == 0 {
print.insert(0, ',');
}
print.insert(0, val);
}
print
}
pub struct TrieReadBenchmarkDescription {
pub database_size: DatabaseSize,
pub database_type: DatabaseType,
}
pub struct TrieReadBenchmark {
database: TempDatabase,
root: Hash,
warmup_keys: KeyValues,
query_keys: KeyValues,
database_type: DatabaseType,
}
impl core::BenchmarkDescription for TrieReadBenchmarkDescription {
fn path(&self) -> Path {
let mut path = Path::new(&["trie", "read"]);
path.push(&format!("{}", self.database_size));
path
}
fn setup(self: Box<Self>) -> Box<dyn core::Benchmark> {
let mut database = TempDatabase::new();
let mut rng = rand::thread_rng();
let warmup_prefix = KUSAMA_STATE_DISTRIBUTION.key(&mut rng);
let mut key_values = KeyValues::new();
let mut warmup_keys = KeyValues::new();
let mut query_keys = KeyValues::new();
let every_x_key = self.database_size.keys() / SAMPLE_SIZE;
for idx in 0..self.database_size.keys() {
let kv = (
KUSAMA_STATE_DISTRIBUTION.key(&mut rng).to_vec(),
KUSAMA_STATE_DISTRIBUTION.value(&mut rng),
);
if idx % every_x_key == 0 {
let mut actual_warmup_key = warmup_prefix.clone();
actual_warmup_key[16..].copy_from_slice(&kv.0[16..]);
warmup_keys.push((actual_warmup_key.clone(), kv.1.clone()));
key_values.push((actual_warmup_key.clone(), kv.1.clone()));
} else if idx % every_x_key == 1 {
query_keys.push(kv.clone());
}
key_values.push(kv)
}
assert_eq!(warmup_keys.len(), SAMPLE_SIZE);
assert_eq!(query_keys.len(), SAMPLE_SIZE);
let root = generate_trie(database.open(self.database_type), key_values);
Box::new(TrieReadBenchmark {
database,
root,
warmup_keys,
query_keys,
database_type: self.database_type,
})
}
fn name(&self) -> Cow<'static, str> {
format!(
"Trie read benchmark({} database ({} keys), db_type: {})",
self.database_size,
pretty_print(self.database_size.keys()),
self.database_type,
)
.into()
}
}
struct Storage(Arc<dyn KeyValueDB>);
impl sp_state_machine::Storage<sp_core::Blake2Hasher> for Storage {
fn get(&self, key: &Hash, prefix: Prefix) -> Result<Option<Vec<u8>>, String> {
let key = sp_trie::prefixed_key::<sp_core::Blake2Hasher>(key, prefix);
self.0.get(0, &key).map_err(|e| format!("Database backend error: {:?}", e))
}
}
impl core::Benchmark for TrieReadBenchmark {
fn run(&mut self, mode: Mode) -> std::time::Duration {
let mut db = self.database.clone();
let storage: Arc<dyn sp_state_machine::Storage<sp_core::Blake2Hasher>> =
Arc::new(Storage(db.open(self.database_type)));
let trie_backend = sp_state_machine::TrieBackend::new(storage, self.root);
for (warmup_key, warmup_value) in self.warmup_keys.iter() {
let value = trie_backend
.storage(&warmup_key[..])
.expect("Failed to get key: db error")
.expect("Warmup key should exist");
assert_eq!(&value, warmup_value);
}
if mode == Mode::Profile {
std::thread::park_timeout(std::time::Duration::from_secs(3));
}
let started = std::time::Instant::now();
for (key, _) in self.query_keys.iter() {
let _ = trie_backend.storage(&key[..]);
}
let elapsed = started.elapsed();
if mode == Mode::Profile {
std::thread::park_timeout(std::time::Duration::from_secs(1));
}
elapsed / (SAMPLE_SIZE as u32)
}
}
pub struct TrieWriteBenchmarkDescription {
pub database_size: DatabaseSize,
pub database_type: DatabaseType,
}
impl core::BenchmarkDescription for TrieWriteBenchmarkDescription {
fn path(&self) -> Path {
let mut path = Path::new(&["trie", "write"]);
path.push(&format!("{}", self.database_size));
path
}
fn setup(self: Box<Self>) -> Box<dyn core::Benchmark> {
let mut database = TempDatabase::new();
let mut rng = rand::thread_rng();
let warmup_prefix = KUSAMA_STATE_DISTRIBUTION.key(&mut rng);
let mut key_values = KeyValues::new();
let mut warmup_keys = KeyValues::new();
let every_x_key = self.database_size.keys() / SAMPLE_SIZE;
for idx in 0..self.database_size.keys() {
let kv = (
KUSAMA_STATE_DISTRIBUTION.key(&mut rng).to_vec(),
KUSAMA_STATE_DISTRIBUTION.value(&mut rng),
);
if idx % every_x_key == 0 {
let mut actual_warmup_key = warmup_prefix.clone();
actual_warmup_key[16..].copy_from_slice(&kv.0[16..]);
warmup_keys.push((actual_warmup_key.clone(), kv.1.clone()));
key_values.push((actual_warmup_key.clone(), kv.1.clone()));
}
key_values.push(kv)
}
assert_eq!(warmup_keys.len(), SAMPLE_SIZE);
let root = generate_trie(database.open(self.database_type), key_values);
Box::new(TrieWriteBenchmark {
database,
root,
warmup_keys,
database_type: self.database_type,
})
}
fn name(&self) -> Cow<'static, str> {
format!(
"Trie write benchmark({} database ({} keys), db_type = {})",
self.database_size,
pretty_print(self.database_size.keys()),
self.database_type,
)
.into()
}
}
struct TrieWriteBenchmark {
database: TempDatabase,
root: Hash,
warmup_keys: KeyValues,
database_type: DatabaseType,
}
impl core::Benchmark for TrieWriteBenchmark {
fn run(&mut self, mode: Mode) -> std::time::Duration {
let mut rng = rand::thread_rng();
let mut db = self.database.clone();
let kvdb = db.open(self.database_type);
let mut new_root = self.root.clone();
let mut overlay = HashMap::new();
let mut trie = SimpleTrie { db: kvdb.clone(), overlay: &mut overlay };
let mut trie_db_mut =
TrieDBMut::from_existing(&mut trie, &mut new_root).expect("Failed to create TrieDBMut");
for (warmup_key, warmup_value) in self.warmup_keys.iter() {
let value = trie_db_mut
.get(&warmup_key[..])
.expect("Failed to get key: db error")
.expect("Warmup key should exist");
assert_eq!(&value, warmup_value);
}
let test_key = random_vec(&mut rng, 32);
let test_val = random_vec(&mut rng, TEST_WRITE_SIZE);
if mode == Mode::Profile {
std::thread::park_timeout(std::time::Duration::from_secs(3));
}
let started = std::time::Instant::now();
trie_db_mut.insert(&test_key, &test_val).expect("Should be inserted ok");
trie_db_mut.commit();
drop(trie_db_mut);
let mut transaction = kvdb.transaction();
for (key, value) in overlay.into_iter() {
match value {
Some(value) => transaction.put(0, &key[..], &value[..]),
None => transaction.delete(0, &key[..]),
}
}
kvdb.write(transaction).expect("Failed to write transaction");
let elapsed = started.elapsed();
assert!(new_root != self.root);
if mode == Mode::Profile {
std::thread::park_timeout(std::time::Duration::from_secs(1));
}
elapsed
}
}
fn random_vec<R: Rng>(rng: &mut R, len: usize) -> Vec<u8> {
let mut val = vec![0u8; len];
rng.fill_bytes(&mut val[..]);
val
}
struct SizePool {
distribution: std::collections::BTreeMap<u32, u32>,
total: u32,
}
impl SizePool {
fn from_histogram(h: &[(u32, u32)]) -> SizePool {
let mut distribution = std::collections::BTreeMap::default();
let mut total = 0;
for (size, count) in h {
total += count;
distribution.insert(total, *size);
}
SizePool { distribution, total }
}
fn value<R: Rng>(&self, rng: &mut R) -> Vec<u8> {
let sr = (rng.next_u64() % self.total as u64) as u32;
let mut range = self
.distribution
.range((std::ops::Bound::Included(sr), std::ops::Bound::Unbounded));
let size = *range.next().unwrap().1 as usize;
random_vec(rng, size)
}
fn key<R: Rng>(&self, rng: &mut R) -> Vec<u8> {
random_vec(rng, 32)
}
}