Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

move paras inherent filtering to runtime #4028

Merged
merged 112 commits into from
Nov 16, 2021
Merged
Show file tree
Hide file tree
Changes from 105 commits
Commits
Show all changes
112 commits
Select commit Hold shift + click to select a range
87b6cde
move things around, add filter methods
drahnr Oct 6, 2021
bf1f98b
validator keys, modify availability bitfields according to disputes
drahnr Oct 8, 2021
7c2711d
simplify, keep the filter -> sanitize generic for both usecases
drahnr Oct 13, 2021
702bceb
minor
drahnr Oct 13, 2021
de29623
assure tests still work, reduce changeset
drahnr Oct 13, 2021
98271ae
integration
drahnr Oct 13, 2021
f7003e8
start entropy passing
drahnr Oct 13, 2021
eb27dbb
fixins
drahnr Oct 14, 2021
0e5d2ff
compile, 1 failing test
drahnr Oct 14, 2021
ceaefae
filter with coverage
drahnr Oct 15, 2021
2f8385f
fixins
drahnr Oct 15, 2021
c169ae0
Update runtime/parachains/src/paras_inherent.rs
drahnr Oct 18, 2021
623a283
slip of the pen
drahnr Oct 18, 2021
9e1cb25
improve test cases
drahnr Oct 18, 2021
e0f4b9e
misc
drahnr Oct 18, 2021
9ec43fa
fix
drahnr Oct 18, 2021
8bd9af6
fixins
drahnr Oct 18, 2021
2c23251
test avoid extra into() calls in assert_noop!
drahnr Oct 18, 2021
b815172
chores
drahnr Oct 18, 2021
903382b
ff
drahnr Oct 18, 2021
75b48eb
test fixup superfluous into call
drahnr Oct 18, 2021
1c2b4de
chore: pfmt
drahnr Oct 18, 2021
c38771f
improve apply_block_weight_limit to try to maximize the number of suf…
drahnr Oct 18, 2021
2908356
new code treats the lack of backed candidates as ok
drahnr Oct 18, 2021
82617f2
Use vrf based entropy
drahnr Oct 18, 2021
1b236a5
fixup vrf random
drahnr Oct 19, 2021
56d2752
add warn
drahnr Oct 19, 2021
e11c985
slip of the pen
drahnr Oct 19, 2021
4e13c1b
fixup
drahnr Oct 19, 2021
7d00562
assure ordering
drahnr Oct 19, 2021
4e06e8d
rethink apply_weights
drahnr Oct 19, 2021
383711d
mock
drahnr Oct 19, 2021
bcd70eb
use a closure as predicate check
drahnr Oct 20, 2021
84cbec3
extract and use DisputedBitfield
drahnr Oct 20, 2021
f347b3f
chore: simplify
drahnr Oct 20, 2021
0df5cf4
remove stray dbg
drahnr Oct 20, 2021
376d158
chore: fmt
drahnr Oct 20, 2021
2d2f8a8
address feedback
drahnr Oct 20, 2021
a1a567c
fix test, halfway there
drahnr Oct 20, 2021
64a759a
stage1
drahnr Oct 21, 2021
98fb6d4
dbg stuff
drahnr Oct 21, 2021
2085069
make group selection align
drahnr Oct 21, 2021
2795af0
fix session index
drahnr Oct 22, 2021
3271fd3
fix wrongly returned candidates
drahnr Oct 22, 2021
4375b83
cleanup
drahnr Oct 22, 2021
cbed703
chore fmt
drahnr Oct 22, 2021
88a7ee1
fix ensure check
drahnr Oct 24, 2021
a7332e0
make good case test work
drahnr Oct 24, 2021
849af66
more tests for bitfields
drahnr Oct 24, 2021
bfa1f1a
create sanitize_backed_candidates
drahnr Oct 29, 2021
c2826a7
fixup tests
drahnr Oct 29, 2021
d2f03f4
update guide
drahnr Oct 31, 2021
209e267
add check referenced in the guide
drahnr Oct 31, 2021
03e77ad
improve weights code
drahnr Oct 31, 2021
3b89d79
fmt
drahnr Oct 31, 2021
20249dd
fixins
drahnr Oct 31, 2021
57e8daa
Update roadmap/implementers-guide/src/runtime/inclusion.md
drahnr Nov 1, 2021
352872b
compiling + address review
drahnr Nov 1, 2021
c592b48
add comments
drahnr Nov 1, 2021
7dd4773
fix weight calc
drahnr Nov 1, 2021
6cb7b8a
Merge remote-tracking branch 'origin/master' into bernhard-inherent-f…
drahnr Nov 3, 2021
ca447a8
address review comments and test failure
drahnr Nov 3, 2021
7b75f7a
fix
drahnr Nov 3, 2021
d524b34
fix: condition
drahnr Nov 5, 2021
0e637ae
Fix random_sel function
Lldenaurois Nov 5, 2021
8113944
Fix overlength block check
Lldenaurois Nov 5, 2021
d290479
Merge remote-tracking branch 'parity/master' into bernhard-inherent-f…
Lldenaurois Nov 6, 2021
9671728
Zeke + Ladi commit for disputes filtering + integration test builder …
Lldenaurois Nov 6, 2021
a8b4771
Add benchmarks for code upgrades
Lldenaurois Nov 6, 2021
70feb6e
Code upgrade bench; Feature gate TestWeightInfo
emostov Nov 6, 2021
f861c2c
Try and make CI happier
emostov Nov 6, 2021
35407fc
Feature gate enter test to not(benchmarks)
emostov Nov 8, 2021
6c0c078
Make sure no unused imports/fn
emostov Nov 8, 2021
0e88948
refactor, re-use, the beginning
drahnr Nov 5, 2021
aecdd96
Fix issue with frame benchmarking dep compilation
emostov Nov 8, 2021
ef35d97
More precise feature gating for some derives
emostov Nov 8, 2021
4536741
integrate piece-wise
drahnr Nov 8, 2021
5b1f1c0
foo
drahnr Nov 8, 2021
fa0de2e
fixins
drahnr Nov 8, 2021
55a7f71
chore fmt
drahnr Nov 8, 2021
dac3b8e
fixins
drahnr Nov 8, 2021
61db8a7
rename const generic
drahnr Nov 8, 2021
80174ec
Merge branch 'bernhard-inherent-filtering2' into bernhard-inherent-fi…
emostov Nov 8, 2021
7f1293b
Update runtime/parachains/src/paras_inherent.rs
drahnr Nov 10, 2021
60a9be5
Fix compilation
bkchr Nov 11, 2021
e36e12a
limit to test
drahnr Nov 11, 2021
a2dcd20
remove unused spam slots
drahnr Nov 11, 2021
9a9eb22
spellcheck
drahnr Nov 11, 2021
f1ef3e1
remove a tick, fix a typo
drahnr Nov 11, 2021
c9e5872
Add Code upgrade weights
Lldenaurois Nov 11, 2021
a7a835c
Merge remote-tracking branch 'parity/master' into bernhard-inherent-f…
Lldenaurois Nov 11, 2021
8f1ad09
comment improvements + >=
drahnr Nov 12, 2021
8ac5e56
remove another tick
drahnr Nov 12, 2021
ee89736
Update runtime/parachains/src/paras_inherent/benchmarking.rs
drahnr Nov 12, 2021
ca5cc54
saturating fixins + some spaces
drahnr Nov 12, 2021
c18e141
fix
drahnr Nov 13, 2021
ba34d06
benchmarking - preliminary results
drahnr Nov 14, 2021
f71e233
Add training wheels
Lldenaurois Nov 12, 2021
8a42171
Refactor some early exit logic for enter
emostov Nov 15, 2021
ac0c325
Gracefully handle filtering bitfields & candidates (#4280)
emostov Nov 15, 2021
e566544
Refactor inherent data weight limiting logic (#4287)
emostov Nov 15, 2021
62cda42
Apply suggestions from code review
emostov Nov 15, 2021
933cba7
Update runtime/parachains/src/builder.rs
drahnr Nov 15, 2021
2c85807
Update runtime/parachains/src/builder.rs
emostov Nov 15, 2021
168ac98
Update runtime/parachains/src/paras_inherent.rs
emostov Nov 16, 2021
2a0869b
final pass
drahnr Nov 16, 2021
811f168
Run cargo +nightly-2021-10-29 fmt
emostov Nov 16, 2021
e12bc31
Update implementors guide with `sanitize_*` & `enter` (#4294)
emostov Nov 16, 2021
a52ffb7
Make spell check happier
emostov Nov 16, 2021
53fcce5
Merge branch 'zeke-bernhard-inherent-filtering-go-green' into bernhar…
emostov Nov 16, 2021
9e7eed5
Make wasm runtimes compile with benchmarks enabled (#4303)
emostov Nov 16, 2021
3d760b6
Update weight files for runtime
emostov Nov 16, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ impl Requester {
// Just book keeping - we are already requesting that chunk:
{
e.get_mut().add_leaf(leaf);
}
},
Entry::Vacant(e) => {
let tx = self.tx.clone();
let metrics = self.metrics.clone();
Expand Down
1 change: 1 addition & 0 deletions parachain/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,4 @@ std = [
"polkadot-core-primitives/std",
"frame-support/std",
]
runtime-benchmarks = []
3 changes: 2 additions & 1 deletion parachain/src/primitives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ pub use polkadot_core_primitives::BlockNumber as RelayChainBlockNumber;
#[derive(
PartialEq, Eq, Clone, PartialOrd, Ord, Encode, Decode, RuntimeDebug, derive_more::From, TypeInfo,
)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Default, Hash, MallocSizeOf))]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize, Hash, MallocSizeOf))]
#[cfg_attr(any(feature = "std", feature = "runtime-benchmarks"), derive(Default))]
pub struct HeadData(#[cfg_attr(feature = "std", serde(with = "bytes"))] pub Vec<u8>);

impl HeadData {
Expand Down
4 changes: 3 additions & 1 deletion primitives/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ frame-system = { git = "https://github.com/paritytech/substrate", branch = "mast
hex-literal = "0.3.3"
parity-util-mem = { version = "0.10.0", default-features = false, optional = true }


[features]
default = ["std"]
std = [
Expand All @@ -56,3 +55,6 @@ std = [
"bitvec/std",
"frame-system/std",
]
runtime-benchmarks = [
"polkadot-parachain/runtime-benchmarks",
]
11 changes: 8 additions & 3 deletions primitives/src/v1/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,8 @@ fn check_collator_signature<H: AsRef<[u8]>>(

/// A unique descriptor of the candidate receipt.
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std", derive(Debug, Default, Hash, MallocSizeOf))]
#[cfg_attr(feature = "std", derive(Debug, Hash, MallocSizeOf))]
#[cfg_attr(any(feature = "std", feature = "runtime-benchmarks"), derive(Default))]
pub struct CandidateDescriptor<H = Hash> {
/// The ID of the para this is a candidate for.
pub para_id: Id,
Expand Down Expand Up @@ -408,7 +409,8 @@ pub struct FullCandidateReceipt<H = Hash, N = BlockNumber> {

/// A candidate-receipt with commitments directly included.
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std", derive(Debug, Default, Hash, MallocSizeOf))]
#[cfg_attr(feature = "std", derive(Debug, Hash, MallocSizeOf))]
#[cfg_attr(any(feature = "std", feature = "runtime-benchmarks"), derive(Default))]
pub struct CommittedCandidateReceipt<H = Hash> {
/// The descriptor of the candidate.
pub descriptor: CandidateDescriptor<H>,
Expand Down Expand Up @@ -510,7 +512,8 @@ impl<H: Encode, N: Encode> PersistedValidationData<H, N> {

/// Commitments made in a `CandidateReceipt`. Many of these are outputs of validation.
#[derive(PartialEq, Eq, Clone, Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "std", derive(Debug, Default, Hash, MallocSizeOf))]
#[cfg_attr(feature = "std", derive(Debug, Hash, MallocSizeOf))]
#[cfg_attr(any(feature = "std", feature = "runtime-benchmarks"), derive(Default))]
pub struct CandidateCommitments<N = BlockNumber> {
/// Messages destined to be interpreted by the Relay chain itself.
pub upward_messages: Vec<UpwardMessage>,
Expand All @@ -534,6 +537,8 @@ impl CandidateCommitments {
}

/// A bitfield concerning availability of backed candidates.
///
/// Every bit refers to an availability core index.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug, TypeInfo)]
pub struct AvailabilityBitfield(pub BitVec<bitvec::order::Lsb0, u8>);

Expand Down
34 changes: 34 additions & 0 deletions primitives/src/v1/signed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ use crate::v0::{SigningContext, ValidatorId, ValidatorIndex, ValidatorSignature}
#[derive(Clone, PartialEq, Eq, RuntimeDebug)]
pub struct Signed<Payload, RealPayload = Payload>(UncheckedSigned<Payload, RealPayload>);

impl<Payload, RealPayload> Signed<Payload, RealPayload> {
/// Convert back to an unchecked type.
pub fn into_unchecked(self) -> UncheckedSigned<Payload, RealPayload> {
self.0
}
}

/// Unchecked signed data, can be converted to `Signed` by checking the signature.
#[derive(Clone, PartialEq, Eq, RuntimeDebug, Encode, Decode, TypeInfo)]
pub struct UncheckedSigned<Payload, RealPayload = Payload> {
Expand Down Expand Up @@ -253,6 +260,33 @@ impl<Payload: EncodeAs<RealPayload>, RealPayload: Encode> UncheckedSigned<Payloa
Err(())
}
}

/// Sign this payload with the given context and pair.
#[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
pub fn benchmark_sign<H: Encode>(
public: &crate::v0::ValidatorId,
payload: Payload,
context: &SigningContext<H>,
validator_index: ValidatorIndex,
) -> Self {
use application_crypto::RuntimeAppPublic;
let data = Self::payload_data(&payload, context);
let signature = public.sign(&data).unwrap();

Self { payload, validator_index, signature, real_payload: sp_std::marker::PhantomData }
}

/// Immutably access the signature.
#[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
pub fn benchmark_signature(&self) -> ValidatorSignature {
self.signature.clone()
}

/// Set the signature. Only should be used for creating testing mocks.
#[cfg(feature = "std")]
pub fn set_signature(&mut self, signature: ValidatorSignature) {
self.signature = signature
}
}

impl<Payload, RealPayload> From<Signed<Payload, RealPayload>>
Expand Down
34 changes: 31 additions & 3 deletions roadmap/implementers-guide/src/runtime/inclusion.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,38 @@ PendingAvailabilityCommitments: map ParaId => CandidateCommitments;
All failed checks should lead to an unrecoverable error making the block invalid.

* `process_bitfields(expected_bits, Bitfields, core_lookup: Fn(CoreIndex) -> Option<ParaId>)`:
1. check that there is at most 1 bitfield per validator and that the number of bits in each bitfield is equal to `expected_bits`.
1. check that there are no duplicates
1. check all validator signatures.
1. call `sanitize_bitfields<true>` and use the sanitized `signed_bitfields` from now on.
1. call `sanitize_backed_candidates<true>` and use the sanitized `backed_candidates` from now on.
1. apply each bit of bitfield to the corresponding pending candidate. looking up parathread cores using the `core_lookup`. Disregard bitfields that have a `1` bit for any free cores.
1. For each applied bit of each availability-bitfield, set the bit for the validator in the `CandidatePendingAvailability`'s `availability_votes` bitfield. Track all candidates that now have >2/3 of bits set in their `availability_votes`. These candidates are now available and can be enacted.
1. For all now-available candidates, invoke the `enact_candidate` routine with the candidate and relay-parent number.
1. Return a list of `(CoreIndex, CandidateHash)` from freed cores consisting of the cores where candidates have become available.
* `sanitize_bitfields<const EARLY_RETURN>(
usab: UncheckedSignedAvailabilityBitfields,
db: DisputedBitfield,
expected_bits: usize,
parent_hash: Hash,
session_index: SessionIndex,
validators: &[ValidatorId]
)`:
1. if `EARLY_RETURN` is `true`, return an error when encountering a bitfield that does not pass the checks, if `false`, drop the bitfield from the set that will be returned.
1. check that there is at most 1 bitfield per validator and that the number of bits in each bitfield is equal to `expected_bits`.
1. check that there are no duplicates
1. check that the validator bit index is not out of bounds
1. check all validator signatures, iff `EARLY_RETURN=true`, since in the other case, checking is supposed to be done before the call
1. check that there are no bits set that reference a disputed candidate

* `sanitize_backed_candidates<const EARLY_RETURN: bool>(
relay_parent: Hash,
mut backed_candidates: Vec<BackedCandidate>,
candidate_has_concluded_invalid_dispute: Fn(CandidateHash) -> bool,
scheduled: &[CoreAssignment],
)`
1. if `EARLY_RETURN` is `true`, return an error when encountering a backed candidates that does not pass the checks, if `false`, drop the backed candidates from the set that will be returned.
1. check all backed candidates have no concluded invalid dispute by means of the provided closure `candidate_has_concluded_invalid_dispute`
1. check all backed candidates have the matching `relay_parent`
1. check all backed candidates paraid was scheduled by means of the provided `scheduled` parameter

* `process_candidates(parent_storage_root, BackedCandidates, scheduled: Vec<CoreAssignment>, group_validators: Fn(GroupIndex) -> Option<Vec<ValidatorIndex>>)`:
1. check that each candidate corresponds to a scheduled core and that they are ordered in the same order the cores appear in assignments in `scheduled`.
1. check that `scheduled` is sorted ascending by `CoreIndex`, without duplicates.
Expand All @@ -78,6 +103,9 @@ All failed checks should lead to an unrecoverable error making the block invalid
1. call `Hrmp::prune_hrmp` with the para id of the candiate and the candidate's `hrmp_watermark`.
1. call `Hrmp::queue_outbound_hrmp` with the para id of the candidate and the list of horizontal messages taken from the commitment,
1. Call `Paras::note_new_head` using the `HeadData` from the receipt and `relay_parent_number`.

* `fn sanitize_bitfields`
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FIXME this is a stub and needs some attention


* `collect_pending`:

```rust
Expand Down
19 changes: 19 additions & 0 deletions roadmap/implementers-guide/src/runtime/parainherent.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,22 @@ OnChainVotes: Option<ScrapedOnChainVotes>,
1. Call `Scheduler::occupied` using the `occupied` core indices of the returned above, first sorting the list of assigned core indices.
1. Call the `Ump::process_pending_upward_messages` routine to execute all messages in upward dispatch queues.
1. If all of the above succeeds, set `Included` to `Some(())`.


* `create_inherent`: This entry-point accepts one parameter: `InherentData`.
1. Unpack `InherentData` into its parts, `bitfields`, `backed_candidates`, `disputes` and the `parent_header`.
1. Hash the `parent_header` and make sure that it corresponds to the block hash of the parent (tracked by the `frame_system` FRAME module),
1. Invoke `Disputes::filter_multi_dispute_data` to remove duplicates et al from `disputes`.
1. Run the following within a `with_transaction` closure to avoid side effects:
1. Invoke `Disputes::provide_multi_dispute_data`.
1. Collect the newly concluded disputes as `current_concluded_invalid_disputes`.
1. If there are any concluded disputes from the current session, invoke `Inclusion::collect_disputed` with the newly disputed candidates. Annotate each returned core with `FreedReason::Concluded`, sort them, and invoke `Scheduler::free_cores` with them.
1. Collect the concluded invalid disputes in the current session as `conlcuded_invalid_disputes`.
1. Return `TransactionOutcome::Rollback(freed_cores, concluded_invalid_disputes)`.
1. Call `sanitize_bitfields<false>` and only use the sanitized set of bitfields afterwards.
1. Call `sanitize_backed_candidates<false>`.
1. Collect entropy based on `CurrentBlockRandomness::random`.
1. Call `apply_weight_limit` to utilize the block as well as possible, with a randomized heuristic.
1. Re-create a `InherentData` from the sanitized and weight bounded information.
1. Call `Self::enter` which now should not error anymore, but we do this call anyways for now.
1. Return `Call::enter { .. }`.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unify this with the latest changes.

1 change: 1 addition & 0 deletions runtime/kusama/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ runtime-benchmarks = [
"xcm-builder/runtime-benchmarks",
"frame-election-provider-support/runtime-benchmarks",
"pallet-bags-list/runtime-benchmarks",
"runtime-parachains/runtime-benchmarks",
]
try-runtime = [
"frame-executive/try-runtime",
Expand Down
6 changes: 5 additions & 1 deletion runtime/kusama/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1201,7 +1201,9 @@ impl parachains_hrmp::Config for Runtime {
type Currency = Balances;
}

impl parachains_paras_inherent::Config for Runtime {}
impl parachains_paras_inherent::Config for Runtime {
type WeightInfo = weights::runtime_parachains_paras_inherent::WeightInfo<Runtime>;
}

impl parachains_scheduler::Config for Runtime {}

Expand Down Expand Up @@ -1933,6 +1935,7 @@ sp_api::impl_runtime_apis! {
list_benchmark!(list, extra, runtime_common::paras_registrar, Registrar);
list_benchmark!(list, extra, runtime_parachains::configuration, Configuration);
list_benchmark!(list, extra, runtime_parachains::initializer, Initializer);
list_benchmark!(list, extra, runtime_parachains::paras_inherent, ParaInherent);
list_benchmark!(list, extra, runtime_parachains::paras, Paras);
// Substrate
list_benchmark!(list, extra, pallet_bags_list, BagsList);
Expand Down Expand Up @@ -2010,6 +2013,7 @@ sp_api::impl_runtime_apis! {
add_benchmark!(params, batches, runtime_common::paras_registrar, Registrar);
add_benchmark!(params, batches, runtime_parachains::configuration, Configuration);
add_benchmark!(params, batches, runtime_parachains::initializer, Initializer);
add_benchmark!(params, batches, runtime_parachains::paras_inherent, ParaInherent);
add_benchmark!(params, batches, runtime_parachains::paras, Paras);
// Substrate
add_benchmark!(params, batches, pallet_balances, Balances);
Expand Down
1 change: 1 addition & 0 deletions runtime/kusama/src/weights/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,4 @@ pub mod runtime_common_slots;
pub mod runtime_parachains_configuration;
pub mod runtime_parachains_initializer;
pub mod runtime_parachains_paras;
pub mod runtime_parachains_paras_inherent;
Loading