mirror of
https://github.com/pezkuwichain/pezkuwi-subxt.git
synced 2026-06-16 13:11:15 +00:00
Multi-Block-Migrations, poll hook and new System callbacks (#1781)
This MR is the merge of https://github.com/paritytech/substrate/pull/14414 and https://github.com/paritytech/substrate/pull/14275. It implements [RFC#13](https://github.com/polkadot-fellows/RFCs/pull/13), closes https://github.com/paritytech/polkadot-sdk/issues/198. ----- This Merge request introduces three major topicals: 1. Multi-Block-Migrations 1. New pallet `poll` hook for periodic service work 1. Replacement hooks for `on_initialize` and `on_finalize` in cases where `poll` cannot be used and some more general changes to FRAME. The changes for each topical span over multiple crates. They are listed in topical order below. # 1.) Multi-Block-Migrations Multi-Block-Migrations are facilitated by creating `pallet_migrations` and configuring `System::Config::MultiBlockMigrator` to point to it. Executive picks this up and triggers one step of the migrations pallet per block. The chain is in lockdown mode for as long as an MBM is ongoing. Executive does this by polling `MultiBlockMigrator::ongoing` and not allowing any transaction in a block, if true. A MBM is defined through trait `SteppedMigration`. A condensed version looks like this: ```rust /// A migration that can proceed in multiple steps. pub trait SteppedMigration { type Cursor: FullCodec + MaxEncodedLen; type Identifier: FullCodec + MaxEncodedLen; fn id() -> Self::Identifier; fn max_steps() -> Option<u32>; fn step( cursor: Option<Self::Cursor>, meter: &mut WeightMeter, ) -> Result<Option<Self::Cursor>, SteppedMigrationError>; } ``` `pallet_migrations` can be configured with an aggregated tuple of these migrations. It then starts to migrate them one-by-one on the next runtime upgrade. Two things are important here: - 1. Doing another runtime upgrade while MBMs are ongoing is not a good idea and can lead to messed up state. - 2. **Pallet Migrations MUST BE CONFIGURED IN `System::Config`, otherwise it is not used.** The pallet supports an `UpgradeStatusHandler` that can be used to notify external logic of upgrade start/finish (for example to pause XCM dispatch). Error recovery is very limited in the case that a migration errors or times out (exceeds its `max_steps`). Currently the runtime dev can decide in `FailedMigrationHandler::failed` how to handle this. One follow-up would be to pair this with the `SafeMode` pallet and enact safe mode when an upgrade fails, to allow governance to rescue the chain. This is currently not possible, since governance is not `Mandatory`. ## Runtime API - `Core`: `initialize_block` now returns `ExtrinsicInclusionMode` to inform the Block Author whether they can push transactions. ### Integration Add it to your runtime implementation of `Core` and `BlockBuilder`: ```patch diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs @@ impl_runtime_apis! { impl sp_block_builder::Core<Block> for Runtime { - fn initialize_block(header: &<Block as BlockT>::Header) { + fn initialize_block(header: &<Block as BlockT>::Header) -> RuntimeExecutiveMode { Executive::initialize_block(header) } ... } ``` # 2.) `poll` hook A new pallet hook is introduced: `poll`. `Poll` is intended to replace mostly all usage of `on_initialize`. The reason for this is that any code that can be called from `on_initialize` cannot be migrated through an MBM. Currently there is no way to statically check this; the implication is to use `on_initialize` as rarely as possible. Failing to do so can result in broken storage invariants. The implementation of the poll hook depends on the `Runtime API` changes that are explained above. # 3.) Hard-Deadline callbacks Three new callbacks are introduced and configured on `System::Config`: `PreInherents`, `PostInherents` and `PostTransactions`. These hooks are meant as replacement for `on_initialize` and `on_finalize` in cases where the code that runs cannot be moved to `poll`. The reason for this is to make the usage of HD-code (hard deadline) more explicit - again to prevent broken invariants by MBMs. # 4.) FRAME (general changes) ## `frame_system` pallet A new memorize storage item `InherentsApplied` is added. It is used by executive to track whether inherents have already been applied. Executive and can then execute the MBMs directly between inherents and transactions. The `Config` gets five new items: - `SingleBlockMigrations` this is the new way of configuring migrations that run in a single block. Previously they were defined as last generic argument of `Executive`. This shift is brings all central configuration about migrations closer into view of the developer (migrations that are configured in `Executive` will still work for now but is deprecated). - `MultiBlockMigrator` this can be configured to an engine that drives MBMs. One example would be the `pallet_migrations`. Note that this is only the engine; the exact MBMs are injected into the engine. - `PreInherents` a callback that executes after `on_initialize` but before inherents. - `PostInherents` a callback that executes after all inherents ran (including MBMs and `poll`). - `PostTransactions` in symmetry to `PreInherents`, this one is called before `on_finalize` but after all transactions. A sane default is to set all of these to `()`. Example diff suitable for any chain: ```patch @@ impl frame_system::Config for Test { type MaxConsumers = ConstU32<16>; + type SingleBlockMigrations = (); + type MultiBlockMigrator = (); + type PreInherents = (); + type PostInherents = (); + type PostTransactions = (); } ``` An overview of how the block execution now looks like is here. The same graph is also in the rust doc. <details><summary>Block Execution Flow</summary> <p>  </p> </details> ## Inherent Order Moved to https://github.com/paritytech/polkadot-sdk/pull/2154 --------------- ## TODO - [ ] Check that `try-runtime` still works - [ ] Ensure backwards compatibility with old Runtime APIs - [x] Consume weight correctly - [x] Cleanup --------- Signed-off-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io> Co-authored-by: Liam Aharon <liam.aharon@hotmail.com> Co-authored-by: Juan Girini <juangirini@gmail.com> Co-authored-by: command-bot <> Co-authored-by: Francisco Aguirre <franciscoaguirreperez@gmail.com> Co-authored-by: Gavin Wood <gavin@parity.io> Co-authored-by: Bastian Köcher <git@kchr.de>
This commit is contained in:
committed by
GitHub
parent
576681b867
commit
eefd5fe449
@@ -0,0 +1,163 @@
|
||||
// This file is part of Substrate.
|
||||
|
||||
// Copyright (C) Parity Technologies (UK) Ltd.
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Mocked runtime for testing the migrations pallet.
|
||||
|
||||
#![cfg(test)]
|
||||
|
||||
use crate::{mock_helpers::*, Event, Historic};
|
||||
|
||||
use frame_support::{
|
||||
derive_impl,
|
||||
migrations::*,
|
||||
traits::{OnFinalize, OnInitialize},
|
||||
weights::Weight,
|
||||
};
|
||||
use frame_system::EventRecord;
|
||||
use sp_core::{ConstU32, H256};
|
||||
|
||||
type Block = frame_system::mocking::MockBlock<Test>;
|
||||
|
||||
// Configure a mock runtime to test the pallet.
|
||||
frame_support::construct_runtime!(
|
||||
pub enum Test {
|
||||
System: frame_system,
|
||||
Migrations: crate,
|
||||
}
|
||||
);
|
||||
|
||||
#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)]
|
||||
impl frame_system::Config for Test {
|
||||
type Block = Block;
|
||||
type PalletInfo = PalletInfo;
|
||||
type MultiBlockMigrator = Migrations;
|
||||
}
|
||||
|
||||
frame_support::parameter_types! {
|
||||
pub const MaxServiceWeight: Weight = Weight::MAX.div(10);
|
||||
}
|
||||
|
||||
impl crate::Config for Test {
|
||||
type RuntimeEvent = RuntimeEvent;
|
||||
type Migrations = MockedMigrations;
|
||||
type CursorMaxLen = ConstU32<65_536>;
|
||||
type IdentifierMaxLen = ConstU32<256>;
|
||||
type MigrationStatusHandler = MockedMigrationStatusHandler;
|
||||
type FailedMigrationHandler = MockedFailedMigrationHandler;
|
||||
type MaxServiceWeight = MaxServiceWeight;
|
||||
type WeightInfo = ();
|
||||
}
|
||||
|
||||
frame_support::parameter_types! {
|
||||
/// The number of started upgrades.
|
||||
pub static UpgradesStarted: u32 = 0;
|
||||
/// The number of completed upgrades.
|
||||
pub static UpgradesCompleted: u32 = 0;
|
||||
/// The migrations that failed.
|
||||
pub static UpgradesFailed: Vec<Option<u32>> = vec![];
|
||||
/// Return value of [`MockedFailedMigrationHandler::failed`].
|
||||
pub static FailedUpgradeResponse: FailedMigrationHandling = FailedMigrationHandling::KeepStuck;
|
||||
}
|
||||
|
||||
/// Records all started and completed upgrades in `UpgradesStarted` and `UpgradesCompleted`.
|
||||
pub struct MockedMigrationStatusHandler;
|
||||
impl MigrationStatusHandler for MockedMigrationStatusHandler {
|
||||
fn started() {
|
||||
log::info!("MigrationStatusHandler started");
|
||||
UpgradesStarted::mutate(|v| *v += 1);
|
||||
}
|
||||
|
||||
fn completed() {
|
||||
log::info!("MigrationStatusHandler completed");
|
||||
UpgradesCompleted::mutate(|v| *v += 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Records all failed upgrades in `UpgradesFailed`.
|
||||
pub struct MockedFailedMigrationHandler;
|
||||
impl FailedMigrationHandler for MockedFailedMigrationHandler {
|
||||
fn failed(migration: Option<u32>) -> FailedMigrationHandling {
|
||||
UpgradesFailed::mutate(|v| v.push(migration));
|
||||
let res = FailedUpgradeResponse::get();
|
||||
log::error!("FailedMigrationHandler failed at: {migration:?}, handling as {res:?}");
|
||||
res
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the number of `(started, completed, failed)` upgrades and resets their numbers.
|
||||
pub fn upgrades_started_completed_failed() -> (u32, u32, u32) {
|
||||
(UpgradesStarted::take(), UpgradesCompleted::take(), UpgradesFailed::take().len() as u32)
|
||||
}
|
||||
|
||||
/// Build genesis storage according to the mock runtime.
|
||||
pub fn new_test_ext() -> sp_io::TestExternalities {
|
||||
sp_io::TestExternalities::new(Default::default())
|
||||
}
|
||||
|
||||
/// Run this closure in test externalities.
|
||||
pub fn test_closure<R>(f: impl FnOnce() -> R) -> R {
|
||||
let mut ext = new_test_ext();
|
||||
ext.execute_with(f)
|
||||
}
|
||||
|
||||
pub fn run_to_block(n: u32) {
|
||||
while System::block_number() < n as u64 {
|
||||
log::debug!("Block {}", System::block_number());
|
||||
System::set_block_number(System::block_number() + 1);
|
||||
System::on_initialize(System::block_number());
|
||||
Migrations::on_initialize(System::block_number());
|
||||
// Executive calls this:
|
||||
<Migrations as MultiStepMigrator>::step();
|
||||
|
||||
Migrations::on_finalize(System::block_number());
|
||||
System::on_finalize(System::block_number());
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the historic migrations, sorted by their identifier.
|
||||
pub fn historic() -> Vec<MockedIdentifier> {
|
||||
let mut historic = Historic::<Test>::iter_keys().collect::<Vec<_>>();
|
||||
historic.sort();
|
||||
historic
|
||||
}
|
||||
|
||||
// Traits to make using events less insufferable:
|
||||
pub trait IntoRecord {
|
||||
fn into_record(self) -> EventRecord<<Test as frame_system::Config>::RuntimeEvent, H256>;
|
||||
}
|
||||
|
||||
impl IntoRecord for Event<Test> {
|
||||
fn into_record(self) -> EventRecord<<Test as frame_system::Config>::RuntimeEvent, H256> {
|
||||
let re: <Test as frame_system::Config>::RuntimeEvent = self.into();
|
||||
EventRecord { phase: frame_system::Phase::Initialization, event: re, topics: vec![] }
|
||||
}
|
||||
}
|
||||
|
||||
pub trait IntoRecords {
|
||||
fn into_records(self) -> Vec<EventRecord<<Test as frame_system::Config>::RuntimeEvent, H256>>;
|
||||
}
|
||||
|
||||
impl<E: IntoRecord> IntoRecords for Vec<E> {
|
||||
fn into_records(self) -> Vec<EventRecord<<Test as frame_system::Config>::RuntimeEvent, H256>> {
|
||||
self.into_iter().map(|e| e.into_record()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn assert_events<E: IntoRecord>(events: Vec<E>) {
|
||||
pretty_assertions::assert_eq!(events.into_records(), System::events());
|
||||
System::reset_events();
|
||||
}
|
||||
Reference in New Issue
Block a user