Skip to content

SIMD-0599: remove inactive stakes, only cache effective/activating delegations - #14394

Merged
joncinque merged 5 commits into
anza-xyz:masterfrom
ibhatt-jumptrading:remove-inactive-stakes
Aug 31, 2026
Merged

joncinque merged 5 commits into
anza-xyz:masterfrom
ibhatt-jumptrading:remove-inactive-stakes

Conversation

@ibhatt-jumptrading

@ibhatt-jumptrading ibhatt-jumptrading commented Aug 6, 2026 •

Copy link
Copy Markdown

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.

Comment thread runtime/src/bank.rs Resolved
Comment thread runtime/src/bank.rs Resolved
@2501babe

2501babe commented Aug 7, 2026 •

Copy link
Copy Markdown
Member

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

@codecov-commenter

codecov-commenter commented Aug 7, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.81890% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.4%. Comparing base (ca54c4e) to head (a1f8b94).
⚠️ Report is 21 commits behind head on master.

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:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@2501babe

2501babe commented Aug 8, 2026

Copy link
Copy Markdown
Member

my only other concern would be if the initial purge is heavy enough to pause block production, ill see what i can see

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 retain() or remove()

will wait on a second review from @joncinque as the change is fairly simple but its ramifications are many

2501babe
2501babe previously approved these changes Aug 8, 2026

@joncinque joncinque left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Logic looks great to me! Just a few small things to get this into shape

Comment thread feature-set/src/lib.rs
Comment on lines +1545 to +1547
pub mod remove_inactive_stakes {
solana_pubkey::declare_id!("ris3UX1af9F46fZdQ5Dx3CzrwGT3e6J4YH3iHqzT5YL");
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

@ibhatt-jumptrading are you the key holder?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

no, it's a junk key. I was hoping someone on the anza team would create + hold a key for this

Comment thread runtime/src/bank/tests.rs Outdated
Comment on lines +5767 to +5768
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Sorry this will need a rebase and probably a redo for this bank hash, I updated this test recently

Comment thread runtime/src/bank.rs
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>,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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?

Comment thread runtime/src/stakes.rs Outdated
Comment on lines +552 to +556
// 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);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

@joncinque

Copy link
Copy Markdown

@claude review once

Comment thread runtime/src/stakes.rs Outdated
Comment on lines 668 to 696
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 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.

@2501babe

2501babe commented Aug 13, 2026 •

Copy link
Copy Markdown
Member

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 for

this filters the delegations in get_epoch_params_for_recalculation() called in recalculate_stake_rewards() similar to how they actually are at epoch boundary

@joncinque

Copy link
Copy Markdown

Surprisingly, I don't think we need that additional change. Please double-check my logic though.

stake_delegations_vec() comes directly from the stake_delegations field in Stakes. During Stakes::activate_epoch, with this PR, we remove all of the inert stake accounts from stake_delegations.

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?

@joncinque
joncinque force-pushed the remove-inactive-stakes branch from b4c68f0 to 1a77b45 Compare August 24, 2026 20:46
@joncinque joncinque added the CI Pull Request is ready to enter CI label Aug 24, 2026
@anza-team anza-team removed the CI Pull Request is ready to enter CI label Aug 24, 2026
@joncinque
joncinque force-pushed the remove-inactive-stakes branch from 1a77b45 to ca39ad8 Compare August 27, 2026 19:03
@joncinque joncinque changed the title remove inactive stakes: only cache effective/activating delegations SIMD-0599: remove inactive stakes, only cache effective/activating delegations Aug 27, 2026
@joncinque joncinque added the v4.3 Backport to v4.3 branch label Aug 27, 2026
@mergify

mergify Bot commented Aug 27, 2026

Copy link
Copy Markdown

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.

@2501babe
2501babe self-requested a review August 28, 2026 11:40
@2501babe

Copy link
Copy Markdown
Member
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

@joncinque

Copy link
Copy Markdown

@2501babe done!

The only change I made was to remove the first check_and_store for the stake account and to always enable remove_inactive_stakes, so instead of:

+        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);

it's

+        stakes_cache.check_and_store(&vote_pubkey, &vote_account, None, true, true);
+        stakes_cache.check_and_store(&stake_pubkey, &stake_account, None, true, true);

Let me know if that's ok

@2501babe

Copy link
Copy Markdown
Member

true for the vote account is fine for style but the point of calling stake with false is insert it, so when we call with true, it tests evict/retain behavior rather than just allowing/refusing new admissions. the most important consensus property for inactives is that we dont evict last-epoch-actives before they get rewards

@joncinque
joncinque force-pushed the remove-inactive-stakes branch from e40a50c to a1f8b94 Compare August 31, 2026 09:46
@joncinque

Copy link
Copy Markdown

true for the vote account is fine for style but the point of calling stake with false is insert it, so when we call with true, it tests evict/retain behavior rather than just allowing/refusing new admissions. the most important consensus property for inactives is that we dont evict last-epoch-actives before they get rewards

Ah right, gotcha, I added it back in

@joncinque

Copy link
Copy Markdown

@claude review once

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Comment thread runtime/src/stakes.rs
Comment on lines +675 to +688
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,
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 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…

@joncinque
joncinque added this pull request to the merge queue Aug 31, 2026
Merged via the queue into anza-xyz:master with commit f339058 Aug 31, 2026
49 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants