Skip to content

Commit d464e78

Browse files
authored
Fix benchmarks (#1919)
* fixed benchmarks broken by rejecting storage proofs with excessive trie nodes and justifications with extra prevotes * update weights * fmt * accidental paste * revert changes to millau runtime (separate PR) * revert comment change
1 parent 74574d5 commit d464e78

File tree

11 files changed

+159
-173
lines changed

11 files changed

+159
-173
lines changed

bin/runtime-common/src/messages_benchmarking.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ use crate::{
2525
AccountIdOf, BridgedChain, HashOf, HasherOf, MessageBridge, ThisChain,
2626
},
2727
messages_generation::{
28-
encode_all_messages, encode_lane_data, grow_trie, prepare_messages_storage_proof,
28+
encode_all_messages, encode_lane_data, grow_trie_leaf_value, prepare_messages_storage_proof,
2929
},
3030
};
3131

@@ -204,11 +204,12 @@ where
204204
{
205205
let mut trie =
206206
TrieDBMutBuilderV1::<HasherOf<BridgedChain<B>>>::new(&mut mdb, &mut root).build();
207-
trie.insert(&storage_key, &params.inbound_lane_data.encode())
207+
let inbound_lane_data =
208+
grow_trie_leaf_value(params.inbound_lane_data.encode(), params.size);
209+
trie.insert(&storage_key, &inbound_lane_data)
208210
.map_err(|_| "TrieMut::insert has failed")
209211
.expect("TrieMut::insert should not fail in benchmarks");
210212
}
211-
root = grow_trie(root, &mut mdb, params.size);
212213

213214
// generate storage proof to be delivered to This chain
214215
let storage_proof = record_all_trie_keys::<LayoutV1<HasherOf<BridgedChain<B>>>, _>(&mdb, &root)

bin/runtime-common/src/messages_generation.rs

Lines changed: 16 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ use bp_messages::{
2525
};
2626
use bp_runtime::{record_all_trie_keys, RawStorageProof, StorageProofSize};
2727
use codec::Encode;
28-
use sp_core::Hasher;
2928
use sp_std::{ops::RangeInclusive, prelude::*};
3029
use sp_trie::{trie_types::TrieDBMutBuilderV1, LayoutV1, MemoryDB, TrieMut};
3130

@@ -65,10 +64,15 @@ where
6564
TrieDBMutBuilderV1::<HasherOf<BridgedChain<B>>>::new(&mut mdb, &mut root).build();
6665

6766
// insert messages
68-
for nonce in message_nonces {
67+
for (i, nonce) in message_nonces.into_iter().enumerate() {
6968
let message_key = MessageKey { lane_id: lane, nonce };
7069
let message_payload = match encode_message(nonce, &message_payload) {
71-
Some(message_payload) => message_payload,
70+
Some(message_payload) =>
71+
if i == 0 {
72+
grow_trie_leaf_value(message_payload, size)
73+
} else {
74+
message_payload
75+
},
7276
None => continue,
7377
};
7478
let storage_key = storage_keys::message_key(
@@ -94,46 +98,22 @@ where
9498
storage_keys.push(storage_key);
9599
}
96100
}
97-
root = grow_trie(root, &mut mdb, size);
98101

99102
// generate storage proof to be delivered to This chain
100103
let storage_proof = record_all_trie_keys::<LayoutV1<HasherOf<BridgedChain<B>>>, _>(&mdb, &root)
101104
.map_err(|_| "record_all_trie_keys has failed")
102105
.expect("record_all_trie_keys should not fail in benchmarks");
103-
104106
(root, storage_proof)
105107
}
106108

107-
/// Populate trie with dummy keys+values until trie has at least given size.
108-
pub fn grow_trie<H: Hasher>(
109-
mut root: H::Out,
110-
mdb: &mut MemoryDB<H>,
111-
trie_size: StorageProofSize,
112-
) -> H::Out {
113-
let (iterations, leaf_size, minimal_trie_size) = match trie_size {
114-
StorageProofSize::Minimal(_) => return root,
115-
StorageProofSize::HasLargeLeaf(size) => (1, size, size),
116-
StorageProofSize::HasExtraNodes(size) => (8, 1, size),
117-
};
118-
119-
let mut key_index = 0;
120-
loop {
121-
// generate storage proof to be delivered to This chain
122-
let storage_proof = record_all_trie_keys::<LayoutV1<H>, _>(mdb, &root)
123-
.map_err(|_| "record_all_trie_keys has failed")
124-
.expect("record_all_trie_keys should not fail in benchmarks");
125-
let size: usize = storage_proof.iter().map(|n| n.len()).sum();
126-
if size > minimal_trie_size as _ {
127-
return root
128-
}
129-
130-
let mut trie = TrieDBMutBuilderV1::<H>::from_existing(mdb, &mut root).build();
131-
for _ in 0..iterations {
132-
trie.insert(&key_index.encode(), &vec![42u8; leaf_size as _])
133-
.map_err(|_| "TrieMut::insert has failed")
134-
.expect("TrieMut::insert should not fail in benchmarks");
135-
key_index += 1;
136-
}
137-
trie.commit();
109+
/// Add extra data to the trie leaf value so that it'll be of given size.
110+
pub fn grow_trie_leaf_value(mut value: Vec<u8>, size: StorageProofSize) -> Vec<u8> {
111+
match size {
112+
StorageProofSize::Minimal(_) => (),
113+
StorageProofSize::HasLargeLeaf(size) if size as usize > value.len() => {
114+
value.extend(sp_std::iter::repeat(42u8).take(size as usize - value.len()));
115+
},
116+
StorageProofSize::HasLargeLeaf(_) => (),
138117
}
118+
value
139119
}

bin/runtime-common/src/parachains_benchmarking.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,8 @@
1919
#![cfg(feature = "runtime-benchmarks")]
2020

2121
use crate::{
22-
messages_benchmarking::insert_header_to_grandpa_pallet, messages_generation::grow_trie,
22+
messages_benchmarking::insert_header_to_grandpa_pallet,
23+
messages_generation::grow_trie_leaf_value,
2324
};
2425

2526
use bp_parachains::parachain_head_storage_key_at_source;
@@ -59,17 +60,21 @@ where
5960
TrieDBMutBuilderV1::<RelayBlockHasher>::new(&mut mdb, &mut state_root).build();
6061

6162
// insert parachain heads
62-
for parachain in parachains {
63+
for (i, parachain) in parachains.into_iter().enumerate() {
6364
let storage_key =
6465
parachain_head_storage_key_at_source(R::ParasPalletName::get(), *parachain);
65-
trie.insert(&storage_key.0, &parachain_head.encode())
66+
let leaf_data = if i == 0 {
67+
grow_trie_leaf_value(parachain_head.encode(), size)
68+
} else {
69+
parachain_head.encode()
70+
};
71+
trie.insert(&storage_key.0, &leaf_data)
6672
.map_err(|_| "TrieMut::insert has failed")
6773
.expect("TrieMut::insert should not fail in benchmarks");
6874
storage_keys.push(storage_key);
6975
parachain_heads.push((*parachain, parachain_head.hash()))
7076
}
7177
}
72-
state_root = grow_trie(state_root, &mut mdb, size);
7378

7479
// generate heads storage proof
7580
let proof = record_all_trie_keys::<LayoutV1<RelayBlockHasher>, _>(&mdb, &state_root)

modules/grandpa/src/benchmarking.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
4242
use crate::*;
4343

44+
use bp_header_chain::justification::required_justification_precommits;
4445
use bp_runtime::BasicOperatingMode;
4546
use bp_test_utils::{
4647
accounts, make_justification_for_header, JustificationGeneratorParams, TEST_GRANDPA_ROUND,
@@ -66,21 +67,25 @@ const MAX_VOTE_ANCESTRIES_RANGE_END: u32 =
6667
MAX_VOTE_ANCESTRIES_RANGE_BEGIN + MAX_VOTE_ANCESTRIES_RANGE_BEGIN;
6768

6869
// the same with validators - if there are too much validators, let's run benchmarks on subrange
69-
fn validator_set_range_end<T: Config<I>, I: 'static>() -> u32 {
70+
fn precommits_range_end<T: Config<I>, I: 'static>() -> u32 {
7071
let max_bridged_authorities = T::BridgedChain::MAX_AUTHORITIES_COUNT;
7172
if max_bridged_authorities > 128 {
7273
sp_std::cmp::max(128, max_bridged_authorities / 5)
7374
} else {
7475
max_bridged_authorities
75-
}
76+
};
77+
required_justification_precommits(max_bridged_authorities)
7678
}
7779

7880
/// Prepare header and its justification to submit using `submit_finality_proof`.
7981
fn prepare_benchmark_data<T: Config<I>, I: 'static>(
8082
precommits: u32,
8183
ancestors: u32,
8284
) -> (BridgedHeader<T, I>, GrandpaJustification<BridgedHeader<T, I>>) {
83-
let authority_list = accounts(precommits as u16)
85+
// going from precommits to total authorities count
86+
let total_authorities_count = (3 * precommits - 1) / 2;
87+
88+
let authority_list = accounts(total_authorities_count as u16)
8489
.iter()
8590
.map(|id| (AuthorityId::from(*id), 1))
8691
.collect::<Vec<_>>();
@@ -114,7 +119,7 @@ benchmarks_instance_pallet! {
114119
// This is the "gold standard" benchmark for this extrinsic, and it's what should be used to
115120
// annotate the weight in the pallet.
116121
submit_finality_proof {
117-
let p in 1 .. validator_set_range_end::<T, I>();
122+
let p in 1 .. precommits_range_end::<T, I>();
118123
let v in MAX_VOTE_ANCESTRIES_RANGE_BEGIN..MAX_VOTE_ANCESTRIES_RANGE_END;
119124
let caller: T::AccountId = whitelisted_caller();
120125
let (header, justification) = prepare_benchmark_data::<T, I>(p, v);

modules/grandpa/src/weights.rs

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
//! Autogenerated weights for pallet_bridge_grandpa
1818
//!
1919
//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev
20-
//! DATE: 2023-02-07, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
20+
//! DATE: 2023-03-01, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]`
2121
//! WORST CASE MAP SIZE: `1000000`
2222
//! HOSTNAME: `covid`, CPU: `11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz`
2323
//! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024
@@ -93,19 +93,19 @@ impl<T: frame_system::Config> WeightInfo for BridgeWeight<T> {
9393
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
9494
/// added: 2048, mode: MaxEncodedLen)
9595
///
96-
/// The range of component `p` is `[1, 5]`.
96+
/// The range of component `p` is `[1, 4]`.
9797
///
9898
/// The range of component `v` is `[50, 100]`.
9999
fn submit_finality_proof(p: u32, v: u32) -> Weight {
100100
// Proof Size summary in bytes:
101-
// Measured: `416 + p * (40 ±0)`
101+
// Measured: `394 + p * (60 ±0)`
102102
// Estimated: `4745`
103-
// Minimum execution time: 221_703 nanoseconds.
104-
Weight::from_parts(39_358_497, 4745)
105-
// Standard Error: 85_573
106-
.saturating_add(Weight::from_ref_time(40_593_280).saturating_mul(p.into()))
107-
// Standard Error: 7_808
108-
.saturating_add(Weight::from_ref_time(1_529_400).saturating_mul(v.into()))
103+
// Minimum execution time: 221_810 nanoseconds.
104+
Weight::from_parts(33_157_392, 4745)
105+
// Standard Error: 109_045
106+
.saturating_add(Weight::from_ref_time(41_100_656).saturating_mul(p.into()))
107+
// Standard Error: 7_754
108+
.saturating_add(Weight::from_ref_time(1_534_466).saturating_mul(v.into()))
109109
.saturating_add(T::DbWeight::get().reads(6_u64))
110110
.saturating_add(T::DbWeight::get().writes(6_u64))
111111
}
@@ -148,19 +148,19 @@ impl WeightInfo for () {
148148
/// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68),
149149
/// added: 2048, mode: MaxEncodedLen)
150150
///
151-
/// The range of component `p` is `[1, 5]`.
151+
/// The range of component `p` is `[1, 4]`.
152152
///
153153
/// The range of component `v` is `[50, 100]`.
154154
fn submit_finality_proof(p: u32, v: u32) -> Weight {
155155
// Proof Size summary in bytes:
156-
// Measured: `416 + p * (40 ±0)`
156+
// Measured: `394 + p * (60 ±0)`
157157
// Estimated: `4745`
158-
// Minimum execution time: 221_703 nanoseconds.
159-
Weight::from_parts(39_358_497, 4745)
160-
// Standard Error: 85_573
161-
.saturating_add(Weight::from_ref_time(40_593_280).saturating_mul(p.into()))
162-
// Standard Error: 7_808
163-
.saturating_add(Weight::from_ref_time(1_529_400).saturating_mul(v.into()))
158+
// Minimum execution time: 221_810 nanoseconds.
159+
Weight::from_parts(33_157_392, 4745)
160+
// Standard Error: 109_045
161+
.saturating_add(Weight::from_ref_time(41_100_656).saturating_mul(p.into()))
162+
// Standard Error: 7_754
163+
.saturating_add(Weight::from_ref_time(1_534_466).saturating_mul(v.into()))
164164
.saturating_add(RocksDbWeight::get().reads(6_u64))
165165
.saturating_add(RocksDbWeight::get().writes(6_u64))
166166
}

modules/messages/src/benchmarking.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ benchmarks_instance_pallet! {
238238
lane: T::bench_lane_id(),
239239
message_nonces: 21..=21,
240240
outbound_lane_data: None,
241-
size: StorageProofSize::HasExtraNodes(1024),
241+
size: StorageProofSize::HasLargeLeaf(1024),
242242
});
243243
}: receive_messages_proof(RawOrigin::Signed(relayer_id_on_target), relayer_id_on_source, proof, 1, dispatch_weight)
244244
verify {
@@ -272,7 +272,7 @@ benchmarks_instance_pallet! {
272272
lane: T::bench_lane_id(),
273273
message_nonces: 21..=21,
274274
outbound_lane_data: None,
275-
size: StorageProofSize::HasExtraNodes(16 * 1024),
275+
size: StorageProofSize::HasLargeLeaf(16 * 1024),
276276
});
277277
}: receive_messages_proof(RawOrigin::Signed(relayer_id_on_target), relayer_id_on_source, proof, 1, dispatch_weight)
278278
verify {

0 commit comments

Comments
 (0)