Repository navigation
SIMD-0599: remove inactive stakes, only cache effective/activating delegations - #14394
Conversation
|
core logic all looks sound to me. btw that failing test you can just change the array to its current output, see #14265 for more context my only other concern would be if the initial purge is heavy enough to pause block production, ill see what i can see |
db9cf31 to
1034561
Compare
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #14394 +/- ##
========================================
Coverage 82.4% 82.4%
========================================
Files 920 920
Lines 362527 362721 +194
========================================
+ Hits 298787 299044 +257
+ Misses 63740 63677 -63 🚀 New features to boost your workflow:
|
perf seems like itd be fine. we only have 1/5 as many inactives as actives on mainnet, the new work isnt that expensive compared to what we already do, and there arent any time complexity landmines in will wait on a second review from @joncinque as the change is fairly simple but its ramifications are many |
joncinque
left a comment
There was a problem hiding this comment.
Logic looks great to me! Just a few small things to get this into shape
| pub mod remove_inactive_stakes { | ||
| solana_pubkey::declare_id!("ris3UX1af9F46fZdQ5Dx3CzrwGT3e6J4YH3iHqzT5YL"); | ||
| } |
There was a problem hiding this comment.
@ibhatt-jumptrading are you the key holder?
There was a problem hiding this comment.
no, it's a junk key. I was hoping someone on the anza team would create + hold a key for this
| 39, 34, 123, 219, 250, 198, 218, 222, 15, 184, 165, 5, 177, 150, 99, 169, 179, 59, 145, | ||
| 212, 155, 243, 105, 143, 195, 55, 129, 38, 31, 188, 170, 152 |
There was a problem hiding this comment.
Sorry this will need a rebase and probably a redo for this bank hash, I updated this test recently
| delegated_stakes: DelegatedStakes, | ||
| /// Delegations with neither effective nor activating stake, which are | ||
| /// evicted from the stakes cache when `remove_inactive_stakes` is active. | ||
| inert_stake_delegations: HashSet<Pubkey>, |
There was a problem hiding this comment.
I had initially put in a nit saying to rename inert to inactive everywhere, but after reading through the rest of the PR, it's probably useful to define inert as more than just inactive, since the inert set contains stake delegations that deactivated one epoch earlier.
All that to say, can you clarify in the comment that these should be stake delegations that were inactive in the rewarded epoch, and still are?
| // These delegations contribute no stake to `delegated_stakes` nor to | ||
| // `vote_accounts`, so no stake bookkeeping is needed here. | ||
| for stake_pubkey in inert_stake_delegations { | ||
| self.stake_delegations.remove(stake_pubkey); | ||
| } |
There was a problem hiding this comment.
nit: can this comment further elaborate that inert stake delegations were inactive before next_epoch, so their 0 contributions were already recorded in that epoch
|
@claude review once |
| can_safely_remove_inactive_stakes: bool, | ||
| ) { | ||
| debug_assert_ne!(stake_account.lamports(), 0u64); | ||
| let delegation = stake_account.delegation(); | ||
| let voter_pubkey = delegation.voter_pubkey; | ||
| let stake = delegation_effective_stake( | ||
| let activation_status = delegation_activation_status( | ||
| delegation, | ||
| self.epoch, | ||
| &self.stake_history, | ||
| new_rate_activation_epoch, | ||
| use_fixed_point_stake_math, | ||
| ); | ||
| // A delegation with neither effective nor activating stake cannot | ||
| // contribute stake, so there is no reason to keep tracking it. | ||
| if can_safely_remove_inactive_stakes | ||
| && activation_status.effective == 0 | ||
| && activation_status.activating == 0 | ||
| { | ||
| self.remove_stake_delegation( | ||
| &stake_pubkey, | ||
| new_rate_activation_epoch, | ||
| use_fixed_point_stake_math, | ||
| ); | ||
| return; | ||
| } | ||
| let stake = activation_status.effective; | ||
| match self.stake_delegations.insert(stake_pubkey, stake_account) { | ||
| None => { | ||
| self.add_delegated_stake(voter_pubkey, stake); |
There was a problem hiding this comment.
🟡 The inert-delegation predicate activation_status.effective == 0 && activation_status.activating == 0 is duplicated verbatim in Stakes::calculate_activated_stake (the epoch-boundary sweep) and Stakes::upsert_stake_delegation (the per-store eviction path). Consider extracting a small helper, e.g. fn is_inert(status: &StakeActivationStatus) -> bool, so the definition of 'inert' lives in one place and the two eviction paths can't silently diverge.
Extended reasoning...
This PR introduces two independent code paths that decide whether a stake delegation should be evicted from the stakes cache: the epoch-boundary sweep in Stakes::calculate_activated_stake (which populates inert_stake_delegations inside the rayon fold closure), and the per-transaction path in Stakes::upsert_stake_delegation (invoked from check_and_store). Both paths encode exactly the same semantic condition — activation_status.effective == 0 && activation_status.activating == 0 — to decide that a delegation can never contribute stake again and should be dropped.
The duplication is easy to verify by diffing the two call sites in runtime/src/stakes.rs: in calculate_activated_stake the check appears inside the .fold() closure gated on the remove_inactive_stakes boolean, and in upsert_stake_delegation the identical boolean expression appears gated on can_safely_remove_inactive_stakes. Nothing in the type system or a shared function currently ties these two conditions together — they just happen to have been written the same way at the same time by the same PR.
The risk this creates is purely maintenance-related: because "inert" is defined twice, any future change to the definition (e.g. adding a grace-period epoch, tweaking how activating is computed, or handling a new stake state) must be applied in both places, or the two eviction paths will silently diverge. If a maintainer months from now finds and fixes the predicate in upsert_stake_delegation without noticing the equivalent code in calculate_activated_stake, the epoch-boundary sweep and per-transaction store would disagree about which delegations are inert, leading to inconsistent behavior (e.g., a delegation being evicted immediately on store but not by the boundary sweep, or vice versa) without any compiler or test signal pointing at the second copy.
Concretely: imagine a future SIMD wants to also treat a delegation as inert when deactivating stake has fully drained over N epochs. A developer adds || activation_status.some_new_field == 0 to the check in upsert_stake_delegation (since that's the code path they're debugging) but doesn't know to make the same edit in the .fold() closure of calculate_activated_stake. The two eviction paths now disagree on the definition of "inert," and stale delegations that should be swept at the epoch boundary linger in the cache indefinitely, only being caught on the next store to that account (which may never happen for a truly abandoned account).
The fix is straightforward and low-risk: extract fn is_inert(status: &StakeActivationStatus) -> bool { status.effective == 0 && status.activating == 0 } (or similar) as a free function or method, and call it from both sites. This is purely a refactor — it does not change any observed behavior — so it carries no correctness risk, but it does close off the future-divergence risk described above.
This is a code-quality/maintainability observation, not a correctness bug in the current PR: both copies are currently identical and both are exercised by the new tests (test_activate_epoch, test_inert_delegation_is_not_partitioned_for_rewards), so today's behavior is correct. Severity is therefore nit.
1034561 to
665aeba
Compare
cbae4dc to
7ccae06
Compare
|
i was re-reviewing and realized we have to recalculate the PER set if we come up from a mid-rewards snapshot, i believe we should add this to the pr: diff --git a/runtime/src/bank/partitioned_epoch_rewards/calculation.rs b/runtime/src/bank/partitioned_epoch_rewards/calculation.rs
index d432a757d6..f54143a170 100644
--- a/runtime/src/bank/partitioned_epoch_rewards/calculation.rs
+++ b/runtime/src/bank/partitioned_epoch_rewards/calculation.rs
@@ -586,7 +586,24 @@ impl Bank {
) -> EpochRewardCalculateParamInfo<'a> {
// Use `stakes` for stake-related info
let stake_history = stakes.history().clone();
- let stake_delegations = stakes.stake_delegations_vec();
+ let mut stake_delegations = stakes.stake_delegations_vec();
+
+ // Drop inert delegations, mirroring the filter applied to the
+ // candidate set at the prior epoch boundary.
+ if self.feature_set.snapshot().remove_inactive_stakes {
+ let new_rate_activation_epoch = self.new_warmup_cooldown_rate_epoch();
+ let use_fixed_point_stake_math = self.use_fixed_point_stake_math();
+ stake_delegations.retain(|(_stake_pubkey, stake_account)| {
+ let activation_status = delegation_activation_status(
+ stake_account.delegation(),
+ rewarded_epoch,
+ &stake_history,
+ new_rate_activation_epoch,
+ use_fixed_point_stake_math,
+ );
+ activation_status.effective != 0 || activation_status.activating != 0
+ });
+ }
// Use the VAT-filtered vote-account snapshot from epoch_stakes.
// Recalculation should match the vote-account admission policy used forthis filters the delegations in |
|
Surprisingly, I don't think we need that additional change. Please double-check my logic though.
If we're restarting from a snapshot during PER distribution, that means we're restarting with a stakes cache that doesn't have the inert entries, so we don't need to filter them again. Does that make sense? |
b4c68f0 to
1a77b45
Compare
Co-authored-by: Cursor <cursoragent@cursor.com>
1a77b45 to
ca39ad8
Compare
|
Backports to release branches are to be avoided unless absolutely necessary for fixing bugs, security issues, and perf regressions. Changes intended for backport should be structured such that a minimum effective diff can be committed separately from any refactoring, plumbing, cleanup, etc that are not strictly necessary to achieve the goal. Any of the latter should go only into master and ride the normal stabilization schedule. Exceptions include CI/metrics changes, CLI improvements and documentation updates on a case by case basis. |
diff --git a/runtime/src/stakes.rs b/runtime/src/stakes.rs
index 1dac3cb846..a0474294e7 100644
--- a/runtime/src/stakes.rs
+++ b/runtime/src/stakes.rs
@@ -899,6 +899,7 @@ pub(crate) mod tests {
solana_stake_interface::{self as stake, state::StakeStateV2},
solana_vote_interface::state::{BLS_PUBLIC_KEY_COMPRESSED_SIZE, VoteStateV4},
solana_vote_program::vote_state,
+ test_case::test_case,
};
impl Stakes<Delegation> {
@@ -1341,4 +1342,43 @@ pub(crate) mod tests {
assert_eq!(vote_accounts.get_delegated_stake(&vote_pubkey), 0);
}
}
+
+ #[test_case(4, u64::MAX, true; "activating")]
+ #[test_case(0, u64::MAX, true; "active")]
+ #[test_case(0, 4, true; "deactivating")]
+ #[test_case(0, 3, true; "new_deactivated")]
+ #[test_case(0, 2, false; "old_deactivated")]
+ #[test_case(4, 4, false; "active/deactive")]
+ fn test_inert_delegation_is_removed_from_cache(
+ activation_epoch: Epoch,
+ deactivation_epoch: Epoch,
+ expect_cached: bool,
+ ) {
+ let stakes_cache = StakesCache::new(Stakes {
+ epoch: 4,
+ ..Stakes::default()
+ });
+ let rent = Rent::default();
+
+ let ((vote_pubkey, vote_account), (stake_pubkey, mut stake_account)) =
+ create_staked_node_accounts(10, &rent);
+ let StakeStateV2::Stake(meta, mut stake, flags) = stake_account.state().unwrap() else {
+ panic!("expected a delegated stake account");
+ };
+ stake.delegation.activation_epoch = activation_epoch;
+ stake.delegation.deactivation_epoch = deactivation_epoch;
+ stake_account
+ .set_state(&StakeStateV2::Stake(meta, stake, flags))
+ .unwrap();
+
+ stakes_cache.check_and_store(&vote_pubkey, &vote_account, None, true, false);
+ stakes_cache.check_and_store(&stake_pubkey, &stake_account, None, true, false);
+ stakes_cache.check_and_store(&stake_pubkey, &stake_account, None, true, true);
+
+ let stakes = stakes_cache.stakes();
+ assert_eq!(
+ stakes.stake_delegations().contains_key(&stake_pubkey),
+ expect_cached
+ );
+ }
}can we add this? nothing actually tests the new CAS logic. i will refrain from pushing myself and turning this into even more of a party pr |
|
@2501babe done! The only change I made was to remove the first it's Let me know if that's ok |
|
|
e40a50c to
a1f8b94
Compare
Ah right, gotcha, I added it back in |
|
@claude review once |
| let activation_status = delegation_activation_status( | ||
| delegation, | ||
| self.epoch, | ||
| &self.stake_history, | ||
| new_rate_activation_epoch, | ||
| use_fixed_point_stake_math, | ||
| ); | ||
| let previous_activation_status = delegation_activation_status( | ||
| delegation, | ||
| self.epoch.saturating_sub(1), | ||
| &self.stake_history, | ||
| new_rate_activation_epoch, | ||
| use_fixed_point_stake_math, | ||
| ); |
There was a problem hiding this comment.
🟡 nit (optional): upsert_stake_delegation now always computes previous_activation_status (a second delegation_activation_status call) on every stake account store, even when remove_inactive_stakes is false (i.e. before the feature activates), adding unconditional per-store overhead that the base branch does not pay. Fix: only compute previous_activation_status when remove_inactive_stakes is true, e.g. guard it behind the same if remove_inactive_stakes { ... } used for the eviction check.
Extended reasoning...
check_and_store -> upsert_stake_delegation runs on essentially every stake account write during transaction/vote processing. Before this change only one delegation_activation_status call was made per store; now two are made unconditionally (lines 675 and 682), even when remove_inactive_stakes is false and the result (previous_activation_status) is discarded except for the eviction check that never triggers. This is a small but real per-call regression on a hot validator path that persists for every cluster until the feature activates, and forever afterward for the feature-off branch condition evaluation itself.
Verification: Severity: nit. In runtime/src/stakes.rs upsert_stake_delegation, the diff computes previous_activation_status = delegation_activation_status(delegation, self.epoch.saturating_sub(1), ...) unconditionally (right after the current-epoch activation_status call), but its only consumer is the `if remove_inactive_stakes && previous_activation_status.effective == 0 &&… | Severity: nit. Base branch…
Problem
The stakes cache contains inactive stakes, which do not contribute to the stake weight of validators.
Summary of Changes
Remove "inert" stakes (stakes that have been inactive for at least a full epoch) during epoch boundary calculation, and update the stakes cache to remove inactive stakes outside of the reward period.
Testing
New unit test.