From ffe6a3696fdea73e71f2c10aba9d907785cedbb1 Mon Sep 17 00:00:00 2001 From: Tsvetomir Dimitrov Date: Fri, 16 Aug 2024 01:27:47 +0300 Subject: [PATCH] Proper handling for legacy parachain leases with gaps in coretime migration (#426) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit While testing https://github.com/polkadot-fellows/runtimes/pull/401 I noticed that there are two parachains with gaps in their leases which are not migrated to coretime correctly. These are para ids 3359 and 3388. The problem is that the migration obtains the list of parachain ids which should be migrated from `paras::Parachains` ([here](https://github.com/paritytech/polkadot-sdk/blob/1f49358db0033e57a790eac6daccc45beba81863/polkadot/runtime/parachains/src/coretime/migration.rs#L114)) and there are no entries for para ids which are not active at the moment. Paras 3359 and 3388 are not active in the current lease period (excerpt from `slots::leases()`: ``` [ 3,359 ] [ null [ 14xQXJdUDC1pzyt8y3z27ANiUBgP7zTSaYutaLELJoyQrdLP 2,010,000,000,000 ] [ 14xQXJdUDC1pzyt8y3z27ANiUBgP7zTSaYutaLELJoyQrdLP 2,010,000,000,000 ] ``` and: ``` [ 3,388 ] [ null [ 1TpMimWf8NvrusAQ36hVdgMpYhhtojg5Nw41CuVxG2zHPDg 31,000,000,000,000 ] [ 1TpMimWf8NvrusAQ36hVdgMpYhhtojg5Nw41CuVxG2zHPDg 31,000,000,000,000 ] ``` And they have got no entries in `paras::parachains()`: ``` [ 1,000 1,001 1,002 1,004 2,000 2,002 2,004 2,006 2,008 2,012 2,013 2,025 2,026 2,030 2,031 2,032 2,034 2,035 2,037 2,040 2,043 2,046 2,048 2,051 2,053 2,056 2,086 2,090 2,091 2,092 2,093 2,094 2,101 2,104 2,106 3,333 3,338 3,340 3,344 3,345 3,346 3,354 3,358 3,366 3,367 3,369 3,370 3,373 3,375 3,377 ] ``` As a result the migration skips them which is wrong. A proper fix for this issue will require a new polkadot-sdk release and a bump in the runtimes repo which requires time and effort. To avoid this the PR moves the coretime migration from polkadot-sdk to the fellowship repo. --------- Co-authored-by: Bastian Köcher Co-authored-by: Dónal Murray Co-authored-by: fellowship-merge-bot[bot] <151052383+fellowship-merge-bot[bot]@users.noreply.github.com> --- CHANGELOG.md | 1 + Cargo.lock | 2 + relay/polkadot/Cargo.toml | 9 + relay/polkadot/src/coretime_migration.rs | 315 +++++++++++++++++++++++ relay/polkadot/src/lib.rs | 13 +- 5 files changed, 338 insertions(+), 2 deletions(-) create mode 100644 relay/polkadot/src/coretime_migration.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 875542ae18..6e47ebae0c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). - Add the Polkadot Coretime Chain runtime ([polkadot-fellows/runtimes#410](https://github.com/polkadot-fellows/runtimes/pull/410)) - Kusama: Add a "Spokesperson" proxy type only allowed to send remarks ([polkadot-fellows/runtimes#430](https://github.com/polkadot-fellows/runtimes/pull/430)) - Add the Polkadot and Kusama Coretime Chain specs ([polkadot-fellows/runtimes#432](https://github.com/polkadot-fellows/runtimes/pull/432)) +- Port Agile Coretime migration from polkadot-sdk in order to fix leases with gaps handling([polkadot-fellows/runtimes#426](https://github.com/polkadot-fellows/runtimes/pull/426)) #### From [#322](https://github.com/polkadot-fellows/runtimes/pull/322): diff --git a/Cargo.lock b/Cargo.lock index 0ccf9de0a4..e18345ee89 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9997,6 +9997,7 @@ dependencies = [ "pallet-beefy", "pallet-beefy-mmr", "pallet-bounties", + "pallet-broker", "pallet-child-bounties", "pallet-conviction-voting", "pallet-election-provider-multi-phase", @@ -10034,6 +10035,7 @@ dependencies = [ "pallet-xcm", "pallet-xcm-benchmarks", "parity-scale-codec", + "polkadot-parachain-primitives", "polkadot-primitives", "polkadot-runtime-common", "polkadot-runtime-constants", diff --git a/relay/polkadot/Cargo.toml b/relay/polkadot/Cargo.toml index c8a5404fac..6a936c2502 100644 --- a/relay/polkadot/Cargo.toml +++ b/relay/polkadot/Cargo.toml @@ -44,6 +44,7 @@ pallet-balances = { workspace = true } pallet-beefy = { workspace = true } pallet-beefy-mmr = { workspace = true } pallet-bounties = { workspace = true } +pallet-broker = { workspace = true } pallet-child-bounties = { workspace = true } pallet-transaction-payment = { workspace = true } pallet-transaction-payment-rpc-runtime-api = { workspace = true } @@ -103,6 +104,9 @@ xcm-runtime-apis = { workspace = true } sp-debug-derive = { workspace = true } +# just for the coretime migration +polkadot-parachain-primitives = { workspace = true } + [dev-dependencies] sp-keyring = { workspace = true } sp-trie = { workspace = true } @@ -208,6 +212,8 @@ std = [ "xcm-executor/std", "xcm-runtime-apis/std", "xcm/std", + "pallet-broker/std", + "polkadot-parachain-primitives/std" ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", @@ -257,6 +263,8 @@ runtime-benchmarks = [ "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", "xcm-runtime-apis/runtime-benchmarks", + "pallet-broker/runtime-benchmarks", + "polkadot-parachain-primitives/runtime-benchmarks" ] try-runtime = [ "frame-election-provider-support/try-runtime", @@ -274,6 +282,7 @@ try-runtime = [ "pallet-beefy-mmr/try-runtime", "pallet-beefy/try-runtime", "pallet-bounties/try-runtime", + "pallet-broker/try-runtime", "pallet-child-bounties/try-runtime", "pallet-conviction-voting/try-runtime", "pallet-election-provider-multi-phase/try-runtime", diff --git a/relay/polkadot/src/coretime_migration.rs b/relay/polkadot/src/coretime_migration.rs new file mode 100644 index 0000000000..54e498e19a --- /dev/null +++ b/relay/polkadot/src/coretime_migration.rs @@ -0,0 +1,315 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! Coretime migration for Polkadot runtime + +use crate::{ + coretime::{Config, WeightInfo}, + parachains_assigner_coretime, + parachains_assigner_coretime::PartsOf57600, + OriginKind, +}; +use codec::{Decode, Encode}; +use core::{iter, result}; +#[cfg(feature = "try-runtime")] +use frame_support::ensure; +use frame_support::{ + traits::{OnRuntimeUpgrade, PalletInfoAccess, StorageVersion}, + weights::Weight, +}; +use frame_system::pallet_prelude::BlockNumberFor; +use pallet_broker::{CoreAssignment, CoreMask, ScheduleItem}; +use polkadot_parachain_primitives::primitives::IsSystem; +use polkadot_primitives::{Balance, BlockNumber, CoreIndex, Id as ParaId}; +use polkadot_runtime_constants::system_parachain::coretime::TIMESLICE_PERIOD; +use runtime_parachains::configuration; +#[cfg(feature = "try-runtime")] +use runtime_parachains::scheduler::common::AssignmentProvider; + +use sp_arithmetic::traits::SaturatedConversion; +use sp_core::Get; +use sp_runtime::BoundedVec; +use sp_std::{vec, vec::Vec}; +use xcm::prelude::{send_xcm, Instruction, Junction, Location, SendError, WeightLimit, Xcm}; + +/// Return information about a legacy lease of a parachain. +pub trait GetLegacyLease { + /// If parachain is a lease holding parachain, return the block at which the lease expires. + fn get_parachain_lease_in_blocks(para: ParaId) -> Option; + // All parachains holding a lease, no matter if there are gaps in the slots or not. + fn get_all_parachains_with_leases() -> Vec; +} + +#[derive(Encode, Decode)] +enum CoretimeCalls { + #[codec(index = 1)] + Reserve(pallet_broker::Schedule), + #[codec(index = 3)] + SetLease(pallet_broker::TaskId, pallet_broker::Timeslice), + #[codec(index = 19)] + NotifyCoreCount(u16), + #[codec(index = 20)] + NotifyRevenue((BlockNumber, Balance)), + #[codec(index = 99)] + SwapLeases(ParaId, ParaId), +} + +#[derive(Encode, Decode)] +enum BrokerRuntimePallets { + #[codec(index = 50)] + Broker(CoretimeCalls), +} + +/// Migrate a chain to use coretime. +/// +/// This assumes that the `Coretime` and the `AssignerCoretime` pallets are added at the same +/// time to a runtime. +pub struct MigrateToCoretime( + core::marker::PhantomData<(T, SendXcm, LegacyLease)>, +); + +impl>> + MigrateToCoretime +{ + fn already_migrated() -> bool { + // We are using the assigner coretime because the coretime pallet doesn't has any + // storage data. But both pallets are introduced at the same time, so this is fine. + let name_hash = parachains_assigner_coretime::Pallet::::name_hash(); + let mut next_key = name_hash.to_vec(); + let storage_version_key = + StorageVersion::storage_key::>(); + + loop { + match sp_io::storage::next_key(&next_key) { + // StorageVersion is initialized before, so we need to ignore it. + Some(key) if key == storage_version_key => { + next_key = key; + }, + // If there is any other key with the prefix of the pallet, + // we already have executed the migration. + Some(key) if key.starts_with(&name_hash) => { + log::info!("`MigrateToCoretime` already executed!"); + return true + }, + // Any other key/no key means that we did not yet have migrated. + None | Some(_) => return false, + } + } + } +} + +impl< + T: Config + runtime_parachains::dmp::Config, + SendXcm: xcm::v4::SendXcm, + LegacyLease: GetLegacyLease>, + > OnRuntimeUpgrade for MigrateToCoretime +{ + fn on_runtime_upgrade() -> Weight { + if Self::already_migrated() { + return Weight::zero() + } + + log::info!("Migrating existing parachains to coretime."); + migrate_to_coretime::() + } + + #[cfg(feature = "try-runtime")] + fn pre_upgrade() -> Result, sp_runtime::DispatchError> { + if Self::already_migrated() { + return Ok(Vec::new()) + } + + let legacy_paras = LegacyLease::get_all_parachains_with_leases(); + let config = configuration::ActiveConfig::::get(); + let total_core_count = config.scheduler_params.num_cores + legacy_paras.len() as u32; + + Ok(total_core_count.encode()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(state: Vec) -> Result<(), sp_runtime::DispatchError> { + if state.is_empty() { + return Ok(()) + } + + log::trace!("Running post_upgrade()"); + + let prev_core_count = ::decode(&mut &state[..]).unwrap(); + let new_core_count = parachains_assigner_coretime::Pallet::::session_core_count(); + ensure!(new_core_count == prev_core_count, "Total number of cores need to not change."); + + Ok(()) + } +} + +// Migrate to Coretime. +// +// NOTE: Also migrates `num_cores` config value in configuration::ActiveConfig. +fn migrate_to_coretime< + T: Config, + SendXcm: xcm::v4::SendXcm, + LegacyLease: GetLegacyLease>, +>() -> Weight { + let legacy_paras = LegacyLease::get_all_parachains_with_leases(); + let legacy_count = legacy_paras.len() as u32; + let now = frame_system::Pallet::::block_number(); + for (core, para_id) in legacy_paras.into_iter().enumerate() { + let r = parachains_assigner_coretime::Pallet::::assign_core( + CoreIndex(core as u32), + now, + vec![(CoreAssignment::Task(para_id.into()), PartsOf57600::FULL)], + None, + ); + if let Err(err) = r { + log::error!( + "Creating assignment for existing para failed: {:?}, error: {:?}", + para_id, + err + ); + } + } + + let config = configuration::ActiveConfig::::get(); + for on_demand in 0..config.scheduler_params.num_cores { + let core = CoreIndex(legacy_count.saturating_add(on_demand as _)); + let r = parachains_assigner_coretime::Pallet::::assign_core( + core, + now, + vec![(CoreAssignment::Pool, PartsOf57600::FULL)], + None, + ); + if let Err(err) = r { + log::error!("Creating assignment for existing on-demand core, failed: {:?}", err); + } + } + let total_cores = config.scheduler_params.num_cores + legacy_count; + configuration::ActiveConfig::::mutate(|c| { + c.scheduler_params.num_cores = total_cores; + }); + + if let Err(err) = migrate_send_assignments_to_coretime_chain::() { + log::error!("Sending legacy chain data to coretime chain failed: {:?}", err); + } + + let single_weight = ::WeightInfo::assign_core(1); + single_weight + .saturating_mul(u64::from(legacy_count.saturating_add(config.scheduler_params.num_cores))) + // Second read from sending assignments to the coretime chain. + .saturating_add(T::DbWeight::get().reads_writes(2, 1)) +} + +fn migrate_send_assignments_to_coretime_chain< + T: Config, + SendXcm: xcm::v4::SendXcm, + LegacyLease: GetLegacyLease>, +>() -> result::Result<(), SendError> { + let legacy_paras = LegacyLease::get_all_parachains_with_leases(); + let legacy_paras_count = legacy_paras.len(); + let (system_chains, lease_holding): (Vec<_>, Vec<_>) = + legacy_paras.into_iter().partition(IsSystem::is_system); + + let reservations = system_chains.into_iter().map(|p| { + let schedule = BoundedVec::truncate_from(vec![ScheduleItem { + mask: CoreMask::complete(), + assignment: CoreAssignment::Task(p.into()), + }]); + mk_coretime_call::(CoretimeCalls::Reserve(schedule)) + }); + + let mut leases = lease_holding.into_iter().filter_map(|p| { + log::trace!(target: "coretime-migration", "Preparing sending of lease holding para {:?}", p); + let Some(valid_until) = LegacyLease::get_parachain_lease_in_blocks(p) else { + log::error!("Lease holding chain with no lease information?!"); + return None + }; + + let valid_until: u32 = match valid_until.try_into() { + Ok(val) => val, + Err(_) => { + log::error!("Converting block number to u32 failed!"); + return None + }, + }; + + let time_slice = (valid_until + TIMESLICE_PERIOD - 1) / TIMESLICE_PERIOD; + log::trace!(target: "coretime-migration", "Sending of lease holding para {:?}, valid_until: {:?}, time_slice: {:?}", p, valid_until, time_slice); + Some(mk_coretime_call::(CoretimeCalls::SetLease(p.into(), time_slice))) + }); + + let core_count: u16 = configuration::ActiveConfig::::get() + .scheduler_params + .num_cores + .saturated_into(); + let set_core_count = + iter::once(mk_coretime_call::(CoretimeCalls::NotifyCoreCount(core_count))); + log::trace!(target: "coretime-migration", "Set core count to {:?}. legacy paras count is {:?}",core_count, legacy_paras_count); + + let pool = (legacy_paras_count..core_count.into()).map(|_| { + let schedule = BoundedVec::truncate_from(vec![ScheduleItem { + mask: CoreMask::complete(), + assignment: CoreAssignment::Pool, + }]); + // Reserved cores will come before lease cores, so cores will change their assignments + // when coretime chain sends us their assign_core calls -> Good test. + mk_coretime_call::(CoretimeCalls::Reserve(schedule)) + }); + + let message_content = iter::once(Instruction::UnpaidExecution { + weight_limit: WeightLimit::Unlimited, + check_origin: None, + }); + + let reservation_content = message_content.clone().chain(reservations).collect(); + let leases_content_1 = message_content + .clone() + .chain(leases.by_ref().take(legacy_paras_count / 2)) // split in two messages to avoid overweighted XCM + .collect(); + let leases_content_2 = message_content.clone().chain(leases).collect(); + let set_core_count_content = message_content.clone().chain(set_core_count).collect(); + + // If `pool_content` is empty don't send a blank XCM message + let messages = if core_count as usize > legacy_paras_count { + let pool_content = message_content.clone().chain(pool).collect(); + vec![ + Xcm(reservation_content), + Xcm(pool_content), + Xcm(leases_content_1), + Xcm(leases_content_2), + Xcm(set_core_count_content), + ] + } else { + vec![ + Xcm(reservation_content), + Xcm(leases_content_1), + Xcm(leases_content_2), + Xcm(set_core_count_content), + ] + }; + + for message in messages { + send_xcm::(Location::new(0, Junction::Parachain(T::BrokerId::get())), message)?; + } + + Ok(()) +} + +fn mk_coretime_call(call: CoretimeCalls) -> Instruction<()> { + Instruction::Transact { + origin_kind: OriginKind::Superuser, + require_weight_at_most: T::MaxXcmTransactWeight::get(), + call: BrokerRuntimePallets::Broker(call).encode().into(), + } +} diff --git a/relay/polkadot/src/lib.rs b/relay/polkadot/src/lib.rs index 1e44c81fc7..52c7a33280 100644 --- a/relay/polkadot/src/lib.rs +++ b/relay/polkadot/src/lib.rs @@ -141,6 +141,8 @@ use governance::{ pub mod impls; pub mod xcm_config; +mod coretime_migration; + pub const LOG_TARGET: &str = "runtime::polkadot"; impl_runtime_weights!(polkadot_runtime_constants); @@ -1936,7 +1938,7 @@ pub mod migrations { use super::*; pub struct GetLegacyLeaseImpl; - impl coretime::migration::GetLegacyLease for GetLegacyLeaseImpl { + impl coretime_migration::GetLegacyLease for GetLegacyLeaseImpl { fn get_parachain_lease_in_blocks(para: ParaId) -> Option { let now = frame_system::Pallet::::block_number(); let lease = slots::Leases::::get(para); @@ -1947,6 +1949,13 @@ pub mod migrations { as Leaser>::lease_period_index(now)?; Some(index.saturating_add(lease.len() as u32).saturating_mul(LeasePeriod::get())) } + + fn get_all_parachains_with_leases() -> Vec { + slots::Leases::::iter() + .filter(|(_, lease)| !lease.is_empty()) + .map(|(para, _)| para) + .collect::>() + } } /// Cancel all ongoing auctions. @@ -2001,7 +2010,7 @@ pub mod migrations { >, clear_judgement_proxies::Migration, // Migrate from legacy lease to coretime. Needs to run after configuration v11 - coretime::migration::MigrateToCoretime< + coretime_migration::MigrateToCoretime< Runtime, crate::xcm_config::XcmRouter, GetLegacyLeaseImpl,