Skip to main content

solana_program_runtime/
loaded_programs.rs

1use {
2    crate::{
3        invoke_context::InvokeContext,
4        loading_task::LoadingTaskWaiter,
5        program_cache_entry::{
6            ProgramCacheEntry, ProgramCacheEntryOwner, ProgramCacheEntryType, retention_score,
7        },
8        program_metrics::{EMA_SCALE, ProgramCacheStats},
9    },
10    log::error,
11    solana_clock::{Epoch, Slot},
12    solana_pubkey::Pubkey,
13    solana_sbpf::program::BuiltinProgram,
14    solana_svm_type_overrides::{
15        rand::{Rng, rng},
16        sync::{Arc, Mutex, RwLock, atomic::Ordering},
17        thread,
18    },
19    std::{
20        collections::{HashMap, hash_map::Entry},
21        sync::Weak,
22    },
23};
24
25#[repr(transparent)]
26#[derive(Clone, Debug)]
27pub struct ProgramRuntimeEnvironment(Arc<BuiltinProgram<InvokeContext<'static, 'static>>>);
28impl std::hash::Hash for ProgramRuntimeEnvironment {
29    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
30        Arc::<BuiltinProgram<InvokeContext<'static, 'static>>>::as_ptr(&self.0).hash(state);
31    }
32}
33impl PartialEq for ProgramRuntimeEnvironment {
34    fn eq(&self, other: &Self) -> bool {
35        Arc::ptr_eq(&self.0, &other.0)
36    }
37}
38impl Eq for ProgramRuntimeEnvironment {}
39impl std::ops::Deref for ProgramRuntimeEnvironment {
40    type Target = Arc<BuiltinProgram<InvokeContext<'static, 'static>>>;
41
42    fn deref(&self) -> &Self::Target {
43        &self.0
44    }
45}
46impl ProgramRuntimeEnvironment {
47    pub fn from(inner: BuiltinProgram<InvokeContext<'static, 'static>>) -> Self {
48        Self(Arc::new(inner))
49    }
50
51    pub const fn from_ref<'a>(
52        inner: &'a Arc<BuiltinProgram<InvokeContext<'static, 'static>>>,
53    ) -> &'a Self {
54        // Safety: This wrapper type is transparent and shares the same representation as the underlying type
55        unsafe { std::mem::transmute(inner) }
56    }
57}
58
59/// Paired execution and deployment environments.
60///
61/// Registered functions within each program runtime environment (syscalls)
62/// depend on per-epoch feature gate statuses. In most cases, the list of
63/// registered functions in the two environments will be the same. However,
64/// it's possible that the effective epoch of deployment could be in the
65/// *next epoch*.
66pub struct ProgramRuntimeEnvironments {
67    /// Environment compiled for the current epoch in which programs are
68    /// executing.
69    execution: ProgramRuntimeEnvironment,
70    /// Environment compiled for the epoch of the next slot at which a program
71    /// deployed in the current slot will execute.
72    deployment: ProgramRuntimeEnvironment,
73}
74
75impl ProgramRuntimeEnvironments {
76    /// Create a new ProgramRuntimeEnvironments from an `execution` and
77    /// `deployment` environment.
78    pub fn new(
79        execution: ProgramRuntimeEnvironment,
80        deployment: ProgramRuntimeEnvironment,
81    ) -> Self {
82        Self {
83            execution,
84            deployment,
85        }
86    }
87
88    /// Get the program runtime environment for execution.
89    pub fn get_env_for_execution(&self) -> &ProgramRuntimeEnvironment {
90        &self.execution
91    }
92
93    /// Get the program runtime environment for deployment.
94    pub fn get_env_for_deployment(&self) -> &ProgramRuntimeEnvironment {
95        &self.deployment
96    }
97
98    #[cfg(feature = "dev-context-only-utils")]
99    pub fn mock() -> Self {
100        Self {
101            execution: get_mock_program_runtime_environment(),
102            deployment: get_mock_program_runtime_environment(),
103        }
104    }
105}
106
107#[cfg(feature = "dev-context-only-utils")]
108pub fn get_mock_program_runtime_environment() -> ProgramRuntimeEnvironment {
109    static MOCK_ENVIRONMENT: std::sync::OnceLock<ProgramRuntimeEnvironment> =
110        std::sync::OnceLock::<ProgramRuntimeEnvironment>::new();
111    MOCK_ENVIRONMENT
112        .get_or_init(|| ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock()))
113        .clone()
114}
115
116pub const MAX_LOADED_ENTRY_COUNT: usize = 1024;
117pub const MAX_TOMBSTONE_AGE_IN_SLOTS: u64 = 2250; // 15 Minutes at 400ms slot time
118
119/// A percentage, expected to be in the range `0..=100`.
120pub type Percent = u8;
121
122/// The given percentage of [`MAX_LOADED_ENTRY_COUNT`], as an entry count.
123/// Equivalent to the former `percentage` crate's
124/// `Percentage::from(percent).apply_to(MAX_LOADED_ENTRY_COUNT)`,
125/// i.e. floor(MAX_LOADED_ENTRY_COUNT * percent / 100).
126fn percent_of_max_entries(percent: Percent) -> usize {
127    debug_assert!(percent <= 100, "percent must be <= 100");
128    MAX_LOADED_ENTRY_COUNT.saturating_mul(percent as usize) / 100
129}
130
131/// Relationship between two fork IDs
132#[derive(Copy, Clone, Debug, PartialEq)]
133pub enum BlockRelation {
134    /// The slot is on the same fork and is an ancestor of the other slot
135    Ancestor,
136    /// The two slots are equal and are on the same fork
137    Equal,
138    /// The slot is on the same fork and is a descendant of the other slot
139    Descendant,
140    /// The slots are on two different forks and may have had a common ancestor at some point
141    Unrelated,
142    /// Either one or both of the slots are either older than the latest root, or are in future
143    Unknown,
144}
145
146/// Maps relationship between two slots.
147pub trait ForkGraph {
148    /// Returns the BlockRelation of A to B
149    fn relationship(&self, a: Slot, b: Slot) -> BlockRelation;
150}
151
152/// Globally manages the transition between environments at the epoch boundary
153#[derive(Debug, Default)]
154pub struct EpochBoundaryPreparation {
155    /// The epoch of the upcoming_environment
156    pub upcoming_epoch: Epoch,
157    /// Anticipated replacement for `environments` at the next epoch
158    ///
159    /// This is only `Some` around the boundaries when a changed environment is
160    /// actually coming. It starts with the cache preparation phase a few
161    /// hundred slots before the epoch boundary, and it ends with the first
162    /// rerooting after the epoch boundary.
163    pub upcoming_environment: Option<ProgramRuntimeEnvironment>,
164    /// List of loaded programs which should be recompiled before the next epoch (but don't have to).
165    pub programs_to_recompile: Vec<(Pubkey, Arc<ProgramCacheEntry>)>,
166}
167
168impl EpochBoundaryPreparation {
169    pub fn new(epoch: Epoch) -> Self {
170        Self {
171            upcoming_epoch: epoch,
172            upcoming_environment: None,
173            programs_to_recompile: Vec::default(),
174        }
175    }
176
177    /// Returns the upcoming environments depending on the given epoch
178    pub fn get_upcoming_environment_for_epoch(
179        &self,
180        epoch: Epoch,
181    ) -> Option<ProgramRuntimeEnvironment> {
182        if epoch == self.upcoming_epoch {
183            return self.upcoming_environment.clone();
184        }
185        None
186    }
187
188    /// Before rerooting the blockstore this concludes the epoch boundary
189    /// preparation. Returns whether there was one to conclude.
190    pub fn reroot(&mut self, epoch: Epoch) -> bool {
191        if epoch == self.upcoming_epoch && self.upcoming_environment.take().is_some() {
192            self.programs_to_recompile.clear();
193            return true;
194        }
195
196        false
197    }
198}
199
200/// Input of ProgramCache::extract()
201#[derive(Clone, PartialEq, Debug)]
202pub struct ProgramToLoad<'a> {
203    /// The program address
204    pub program_id: &'a Pubkey,
205    /// The program loader
206    pub loader: ProgramCacheEntryOwner,
207    /// The slot the program was (re)deployed in, as reported by the program
208    /// account on the caller's own fork.
209    ///
210    /// For Loader V1/V2 and builtin programs, this is 0.
211    pub deployment_slot: Slot,
212}
213
214#[derive(Debug)]
215pub(crate) enum IndexImplementation {
216    /// Fork-graph aware index implementation
217    V1 {
218        /// A two level index:
219        ///
220        /// - the first level is for the address at which programs are deployed
221        /// - the second level for the slot (and thus also fork), sorted by slot
222        ///   number from smallest to largest.
223        entries: HashMap<Pubkey, Vec<Arc<ProgramCacheEntry>>>,
224        /// The entries that are getting loaded and have not yet finished loading.
225        ///
226        /// The key is the program address, the value is a tuple of the slot in which the program is
227        /// being loaded and the thread ID doing the load.
228        ///
229        /// It is possible that multiple TX batches from different slots need different versions of a
230        /// program. The deployment slot of a program is only known after load tho,
231        /// so all loads for a given program key are serialized.
232        loading_entries: Mutex<HashMap<Pubkey, (Slot, thread::ThreadId)>>,
233    },
234}
235
236/// This structure is the global cache of loaded, verified and compiled programs.
237///
238/// It ...
239/// - is validator global and fork graph aware, so it can optimize the commonalities across banks.
240/// - handles the visibility rules of un/re/deployments.
241/// - stores the usage statistics and verification status of each program.
242/// - is elastic and uses a probabilistic eviction strategy based on the usage statistics.
243/// - also keeps the compiled executables around, but only for the most used programs.
244/// - supports various kinds of tombstones to avoid loading programs which can not be loaded.
245/// - cleans up entries on orphan branches when the block store is rerooted.
246/// - supports the cache preparation phase before feature activations which can change cached programs.
247/// - manages the environments of the programs and upcoming environments for the next epoch.
248/// - allows for cooperative loading of TX batches which hit the same missing programs simultaneously.
249/// - enforces that all programs used in a batch are eagerly loaded ahead of execution.
250/// - is not persisted to disk or a snapshot, so it needs to cold start and warm up first.
251pub struct ProgramCache<FG: ForkGraph> {
252    /// Index of the cached entries and cooperative loading tasks
253    pub(crate) index: IndexImplementation,
254    /// The slot of the last rerooting
255    pub latest_root_slot: Slot,
256    /// Statistics counters
257    pub stats: ProgramCacheStats,
258    /// Reference to the block store
259    pub fork_graph: Option<Weak<RwLock<FG>>>,
260    /// Coordinates TX batches waiting for others to complete their task during cooperative loading
261    pub loading_task_waiter: Arc<LoadingTaskWaiter>,
262}
263
264impl<FG: ForkGraph> std::fmt::Debug for ProgramCache<FG> {
265    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
266        f.debug_struct("ProgramCache")
267            .field("root slot", &self.latest_root_slot)
268            .field("stats", &self.stats)
269            .field("index", &self.index)
270            .finish()
271    }
272}
273
274/// Local view into [ProgramCache] which was extracted for a specific TX batch.
275///
276/// This isolation enables the global [ProgramCache] to continue to evolve (e.g. evictions),
277/// while the TX batch is guaranteed it will continue to find all the programs it requires.
278/// For program management instructions this also buffers them before they are merged back into the global [ProgramCache].
279#[derive(Clone, Debug, Default)]
280pub struct ProgramCacheForTxBatch {
281    /// Pubkey is the address of a program.
282    /// ProgramCacheEntry is the corresponding program entry valid for the slot in which a transaction is being executed.
283    entries: HashMap<Pubkey, Arc<ProgramCacheEntry>>,
284    /// Program entries modified during the transaction batch.
285    modified_entries: HashMap<Pubkey, Arc<ProgramCacheEntry>>,
286    slot: Slot,
287    pub hit_max_limit: bool,
288    pub loaded_missing: bool,
289    pub merged_modified: bool,
290}
291
292impl ProgramCacheForTxBatch {
293    pub fn new(slot: Slot) -> Self {
294        Self {
295            entries: HashMap::new(),
296            modified_entries: HashMap::new(),
297            slot,
298            hit_max_limit: false,
299            loaded_missing: false,
300            merged_modified: false,
301        }
302    }
303
304    /// Refill the cache with a single entry. It's typically called during transaction loading, and
305    /// transaction processing (for program management instructions).
306    /// It replaces the existing entry (if any) with the provided entry. The return value contains
307    /// `true` if an entry existed.
308    /// The function also returns the newly inserted value.
309    pub fn replenish(
310        &mut self,
311        key: Pubkey,
312        entry: Arc<ProgramCacheEntry>,
313    ) -> (bool, Arc<ProgramCacheEntry>) {
314        (self.entries.insert(key, entry.clone()).is_some(), entry)
315    }
316
317    /// Store an entry in `modified_entries` for a program modified during the
318    /// transaction batch.
319    pub fn store_modified_entry(&mut self, key: Pubkey, entry: Arc<ProgramCacheEntry>) {
320        self.modified_entries.insert(key, entry);
321    }
322
323    /// Drain the program cache's modified entries, returning the owned
324    /// collection.
325    pub fn drain_modified_entries(&mut self) -> HashMap<Pubkey, Arc<ProgramCacheEntry>> {
326        std::mem::take(&mut self.modified_entries)
327    }
328
329    pub fn find(&self, key: &Pubkey) -> Option<Arc<ProgramCacheEntry>> {
330        // First lookup the cache of the programs modified by the current
331        // transaction. If not found, lookup the cache of the cache of the
332        // programs that are loaded for the transaction batch.
333        self.modified_entries
334            .get(key)
335            .or_else(|| self.entries.get(key))
336            .map(|entry| {
337                if entry.is_implicit_delay_visibility_tombstone(self.slot) {
338                    // Found a program entry on the current fork, but it's not effective
339                    // yet. It indicates that the program has delayed visibility. Return
340                    // the tombstone to reflect that.
341                    Arc::new(ProgramCacheEntry::new_delay_visibility_tombstone(
342                        entry.deployment_slot,
343                        entry.account_owner,
344                        Arc::clone(&entry.stats),
345                    ))
346                } else {
347                    entry.clone()
348                }
349            })
350    }
351
352    pub fn slot(&self) -> Slot {
353        self.slot
354    }
355
356    /// Look up `entries` directly, without the delay visibility rewrite
357    /// `find` performs, so a test can see the entry as it was stored.
358    pub fn get_entry_for_tests(&self, key: &Pubkey) -> Option<&Arc<ProgramCacheEntry>> {
359        self.entries.get(key)
360    }
361
362    pub fn set_slot_for_tests(&mut self, slot: Slot) {
363        self.slot = slot;
364    }
365
366    pub fn merge(&mut self, modified_entries: &HashMap<Pubkey, Arc<ProgramCacheEntry>>) {
367        modified_entries.iter().for_each(|(key, entry)| {
368            self.merged_modified = true;
369            self.replenish(*key, entry.clone());
370        })
371    }
372
373    /// Remove an entry from the `entries` list.
374    /// Note: DOES NOT remove modified entries!
375    pub fn remove_entry(&mut self, key: &Pubkey) {
376        self.entries.remove(key);
377    }
378
379    pub fn is_empty(&self) -> bool {
380        self.entries.is_empty()
381    }
382}
383
384impl<FG: ForkGraph> ProgramCache<FG> {
385    pub fn new(root_slot: Slot) -> Self {
386        Self {
387            index: IndexImplementation::V1 {
388                entries: HashMap::new(),
389                loading_entries: Mutex::new(HashMap::new()),
390            },
391            latest_root_slot: root_slot,
392            stats: ProgramCacheStats::default(),
393            fork_graph: None,
394            loading_task_waiter: Arc::new(LoadingTaskWaiter::default()),
395        }
396    }
397
398    pub fn set_fork_graph(&mut self, fork_graph: Weak<RwLock<FG>>) {
399        self.fork_graph = Some(fork_graph);
400    }
401
402    /// Insert a single entry. It's typically called during transaction loading,
403    /// when the cache doesn't contain the entry corresponding to program `key`.
404    pub fn assign_program(
405        &mut self,
406        program_runtime_environment: &ProgramRuntimeEnvironment,
407        key: Pubkey,
408        _current_slot: Slot,
409        entry: Arc<ProgramCacheEntry>,
410    ) -> bool {
411        debug_assert!(
412            !matches!(&entry.program, ProgramCacheEntryType::DelayVisibility),
413            "Unexpected assignment of a DelayVisibility tombstone"
414        );
415        // This function always returns `true` during normal operation.
416        // Only during the cache preparation phase this can return `false`
417        // for entries with `upcoming_environment`.
418        fn is_current_env(
419            program_runtime_environment: &ProgramRuntimeEnvironment,
420            env_opt: Option<&ProgramRuntimeEnvironment>,
421        ) -> bool {
422            env_opt
423                .map(|env| env == program_runtime_environment)
424                .unwrap_or(true)
425        }
426        match &mut self.index {
427            IndexImplementation::V1 { entries, .. } => {
428                let slot_versions = &mut entries.entry(key).or_default();
429                let insertion_point = slot_versions.binary_search_by(|at| {
430                    at.deployment_slot
431                        .cmp(&entry.deployment_slot)
432                        .then(at.account_owner.cmp(&entry.account_owner))
433                        .then(
434                            // This `.then()` has no effect during normal operation.
435                            // Only during the cache preparation phase this does allow entries
436                            // which only differ in their environment to be interleaved in `slot_versions`.
437                            is_current_env(
438                                program_runtime_environment,
439                                at.program.get_environment(),
440                            )
441                            .cmp(&is_current_env(
442                                program_runtime_environment,
443                                entry.program.get_environment(),
444                            )),
445                        )
446                });
447                match insertion_point {
448                    Ok(index) => {
449                        let existing = slot_versions.get_mut(index).unwrap();
450                        match (&existing.program, &entry.program) {
451                            (
452                                ProgramCacheEntryType::Builtin(_),
453                                ProgramCacheEntryType::Builtin(_),
454                            )
455                            | (ProgramCacheEntryType::Closed, ProgramCacheEntryType::Unloaded(_))
456                            | (
457                                ProgramCacheEntryType::Unloaded(_),
458                                ProgramCacheEntryType::Loaded(_),
459                            )
460                            | (
461                                ProgramCacheEntryType::Unloaded(_),
462                                ProgramCacheEntryType::FailedVerification(_),
463                            ) => {}
464                            _ => {
465                                // Something is wrong, I can feel it ...
466                                error!(
467                                    "ProgramCache::assign_program() failed key={key:?} \
468                                     existing={slot_versions:?} entry={entry:?}"
469                                );
470                                debug_assert!(false, "Unexpected replacement of an entry");
471                                self.stats.replacements.fetch_add(1, Ordering::Relaxed);
472                                return true;
473                            }
474                        }
475                        entry.stats.merge_from(&existing.stats);
476                        *existing = Arc::clone(&entry);
477                        self.stats.reloads.fetch_add(1, Ordering::Relaxed);
478                    }
479                    Err(index) => {
480                        self.stats.insertions.fetch_add(1, Ordering::Relaxed);
481                        slot_versions.insert(index, Arc::clone(&entry));
482                    }
483                }
484                // Remove existing entries in the same deployment slot unless they are for a different
485                // environment.
486                // This overwrites the current status of a program in program management instructions.
487                slot_versions.retain(|existing| {
488                    existing.deployment_slot != entry.deployment_slot
489                        || existing
490                            .program
491                            .get_environment()
492                            .zip(entry.program.get_environment())
493                            .map(|(a, b)| a != b)
494                            .unwrap_or(false)
495                        || Arc::ptr_eq(existing, &entry)
496                });
497            }
498        }
499        false
500    }
501
502    pub fn prune_by_deployment_slot(&mut self, slot: Slot) {
503        match &mut self.index {
504            IndexImplementation::V1 { entries, .. } => {
505                for second_level in entries.values_mut() {
506                    second_level.retain(|entry| entry.deployment_slot != slot);
507                }
508                self.remove_programs_with_no_entries();
509            }
510        }
511    }
512
513    /// Before rerooting the blockstore this removes all superfluous entries
514    pub fn prune(
515        &mut self,
516        new_root_slot: Slot,
517        new_environment: Option<ProgramRuntimeEnvironment>,
518        fork_graph: &FG,
519    ) {
520        match &mut self.index {
521            IndexImplementation::V1 { entries, .. } => {
522                let tombstone_slot_cutoff =
523                    new_root_slot.saturating_sub(MAX_TOMBSTONE_AGE_IN_SLOTS);
524                entries.retain(|_id, second_level| {
525                    // Clean up tombstones and unloaded entries
526                    if let [candidate] = &second_level[..]
527                        && (candidate.is_unloaded() || candidate.is_tombstone())
528                        && candidate.deployment_slot <= self.latest_root_slot
529                        && candidate.latest_access_slot.load(Ordering::Relaxed)
530                            < tombstone_slot_cutoff
531                    {
532                        self.stats.prunes_stale.fetch_add(1, Ordering::Relaxed);
533                        return false;
534                    }
535                    // Remove entries un/re/deployed on orphan forks
536                    let mut first_ancestor_found = false;
537                    let mut first_ancestor_env = None;
538                    *second_level = second_level
539                        .iter()
540                        .rev()
541                        .filter(|entry| {
542                            let relation =
543                                fork_graph.relationship(entry.deployment_slot, new_root_slot);
544                            if entry.deployment_slot >= new_root_slot {
545                                let keep = matches!(
546                                    relation,
547                                    BlockRelation::Equal | BlockRelation::Descendant
548                                );
549                                if !keep {
550                                    self.stats.prunes_orphan.fetch_add(1, Ordering::Relaxed);
551                                }
552                                keep
553                            } else if matches!(relation, BlockRelation::Ancestor)
554                                || entry.deployment_slot <= self.latest_root_slot
555                            {
556                                if !first_ancestor_found {
557                                    first_ancestor_found = true;
558                                    first_ancestor_env = entry.program.get_environment();
559                                    return true;
560                                }
561                                // Do not prune the entry if the runtime environment of the entry is
562                                // different than the entry that was previously found (stored in
563                                // first_ancestor_env). Different environment indicates that this entry
564                                // might belong to an older epoch that had a different environment (e.g.
565                                // different feature set). Once the root moves to the new/current epoch,
566                                // the entry will get pruned. But, until then the entry might still be
567                                // getting used by an older slot.
568                                if let Some(entry_env) = entry.program.get_environment()
569                                    && let Some(env) = first_ancestor_env
570                                    && entry_env != env
571                                {
572                                    return true;
573                                }
574                                self.stats.prunes_orphan.fetch_add(1, Ordering::Relaxed);
575                                false
576                            } else {
577                                self.stats.prunes_orphan.fetch_add(1, Ordering::Relaxed);
578                                false
579                            }
580                        })
581                        .filter(|entry| {
582                            // Remove outdated environment of previous feature set
583                            if let Some(new_environment) = new_environment.as_ref()
584                                && !Self::matches_environment(entry, new_environment)
585                            {
586                                self.stats
587                                    .prunes_environment
588                                    .fetch_add(1, Ordering::Relaxed);
589                                return false;
590                            }
591                            true
592                        })
593                        .cloned()
594                        .collect();
595                    second_level.reverse();
596                    true
597                });
598            }
599        }
600        self.remove_programs_with_no_entries();
601        debug_assert!(self.latest_root_slot <= new_root_slot);
602        self.latest_root_slot = new_root_slot;
603    }
604
605    fn matches_environment(
606        entry: &Arc<ProgramCacheEntry>,
607        program_runtime_environment: &ProgramRuntimeEnvironment,
608    ) -> bool {
609        let Some(environment) = entry.program.get_environment() else {
610            return true;
611        };
612        environment == program_runtime_environment
613    }
614
615    /// Extracts a subset of the programs relevant to a transaction batch
616    /// and returns which program accounts the accounts DB needs to load.
617    pub fn extract(
618        &self,
619        search_for: &mut Vec<ProgramToLoad>,
620        loaded_programs_for_tx_batch: &mut ProgramCacheForTxBatch,
621        program_runtime_environment_for_execution: &ProgramRuntimeEnvironment,
622        increment_usage_counter: bool,
623        count_hits_and_misses: bool,
624    ) -> Option<Pubkey> {
625        let entries_in_batch = loaded_programs_for_tx_batch.entries.len();
626        let batch_slot = loaded_programs_for_tx_batch.slot;
627        let mut cooperative_loading_task = None;
628        match &self.index {
629            IndexImplementation::V1 {
630                entries,
631                loading_entries,
632            } => {
633                search_for.retain(|program_to_load| {
634                    if let Some(second_level) = entries.get(program_to_load.program_id) {
635                        for entry in second_level.iter().rev() {
636                            // The entry must have been deployed in the slot reported by
637                            // the caller's own program account, and by the same loader.
638                            if program_to_load.deployment_slot != entry.deployment_slot
639                                || program_to_load.loader != entry.account_owner
640                            {
641                                continue;
642                            }
643
644                            // At this point we're sitting on an entry with a matching
645                            // deployment slot and owner.
646                            let entry_is_effective = batch_slot >= entry.effective_slot();
647                            let entry_to_return = if entry_is_effective {
648                                if !Self::matches_environment(
649                                    entry,
650                                    program_runtime_environment_for_execution,
651                                ) {
652                                    // We found an entry that would work, had its environment
653                                    // matched the one we're planning to use for this slot. A
654                                    // sibling compiled against that environment may follow.
655                                    continue;
656                                }
657                                if entry.is_unloaded() {
658                                    break;
659                                }
660                                entry.clone()
661                            } else if entry.is_implicit_delay_visibility_tombstone(batch_slot) {
662                                // Found a program entry on the current fork, but it's not effective
663                                // yet. It indicates that the program has delayed visibility. Return
664                                // the tombstone to reflect that.
665                                Arc::new(ProgramCacheEntry::new_delay_visibility_tombstone(
666                                    entry.deployment_slot,
667                                    entry.account_owner,
668                                    Arc::clone(&entry.stats),
669                                ))
670                            } else {
671                                continue;
672                            };
673                            entry.update_access_slot(batch_slot.min(self.latest_root_slot));
674                            if increment_usage_counter {
675                                entry_to_return.stats.uses.fetch_add(1, Ordering::Relaxed);
676                            }
677                            loaded_programs_for_tx_batch
678                                .entries
679                                .insert(*program_to_load.program_id, entry_to_return);
680                            return false;
681                        }
682                    }
683                    if cooperative_loading_task.is_none() {
684                        let mut loading_entries = loading_entries.lock().unwrap();
685                        let entry = loading_entries.entry(*program_to_load.program_id);
686                        if let Entry::Vacant(entry) = entry {
687                            entry.insert((batch_slot, thread::current().id()));
688                            cooperative_loading_task = Some(*program_to_load.program_id);
689                        }
690                    }
691                    true
692                });
693            }
694        }
695        if count_hits_and_misses {
696            let misses = search_for.len() as u64;
697            let hits = loaded_programs_for_tx_batch
698                .entries
699                .len()
700                .saturating_sub(entries_in_batch) as u64;
701            self.stats.misses.fetch_add(misses, Ordering::Relaxed);
702            self.stats.hits.fetch_add(hits, Ordering::Relaxed);
703        }
704        cooperative_loading_task
705    }
706
707    /// Called by Bank::replenish_program_cache() for each program that is done loading.
708    pub fn finish_cooperative_loading_task(
709        &mut self,
710        program_runtime_environment: &ProgramRuntimeEnvironment,
711        current_slot: Slot,
712        key: Pubkey,
713        loaded_program: Arc<ProgramCacheEntry>,
714    ) -> bool {
715        match &mut self.index {
716            IndexImplementation::V1 {
717                loading_entries, ..
718            } => {
719                let loading_thread = loading_entries.get_mut().unwrap().remove(&key);
720                debug_assert_eq!(loading_thread, Some((current_slot, thread::current().id())));
721                // Check that it will be visible to our own fork once inserted
722                if loaded_program.deployment_slot > self.latest_root_slot
723                    && !matches!(
724                        self.fork_graph
725                            .as_ref()
726                            .unwrap()
727                            .upgrade()
728                            .unwrap()
729                            .read()
730                            .unwrap()
731                            .relationship(loaded_program.deployment_slot, current_slot),
732                        BlockRelation::Equal | BlockRelation::Ancestor
733                    )
734                {
735                    self.stats.lost_insertions.fetch_add(1, Ordering::Relaxed);
736                }
737                let was_occupied = self.assign_program(
738                    program_runtime_environment,
739                    key,
740                    current_slot,
741                    loaded_program,
742                );
743                self.loading_task_waiter.notify();
744                was_occupied
745            }
746        }
747    }
748
749    /// Returns the list of entries which are verified and compiled.
750    pub fn get_flattened_entries(&self) -> Vec<(Pubkey, Arc<ProgramCacheEntry>)> {
751        match &self.index {
752            IndexImplementation::V1 { entries, .. } => entries
753                .iter()
754                .flat_map(|(id, second_level)| {
755                    second_level
756                        .iter()
757                        .filter_map(move |program| match program.program {
758                            ProgramCacheEntryType::Loaded(_) => Some((*id, program.clone())),
759                            _ => None,
760                        })
761                })
762                .collect(),
763        }
764    }
765
766    /// Returns the list of all entries in the cache.
767    #[cfg(feature = "dev-context-only-utils")]
768    pub fn get_flattened_entries_for_tests(&self) -> Vec<(Pubkey, Arc<ProgramCacheEntry>)> {
769        match &self.index {
770            IndexImplementation::V1 { entries, .. } => entries
771                .iter()
772                .flat_map(|(id, second_level)| {
773                    second_level.iter().map(|program| (*id, program.clone()))
774                })
775                .collect(),
776        }
777    }
778
779    /// Returns the slot versions for the given program id.
780    pub fn get_slot_versions_for_tests(&self, key: &Pubkey) -> &[Arc<ProgramCacheEntry>] {
781        match &self.index {
782            IndexImplementation::V1 { entries, .. } => entries
783                .get(key)
784                .map(|second_level| second_level.as_ref())
785                .unwrap_or(&[]),
786        }
787    }
788
789    /// Unloads programs which were used infrequently
790    pub fn sort_and_unload(&mut self, shrink_to_percent: Percent) {
791        let mut sorted_candidates = self.get_flattened_entries();
792        sorted_candidates
793            .sort_by_cached_key(|(_id, program)| program.stats.uses.load(Ordering::Relaxed));
794        let num_to_unload = sorted_candidates
795            .len()
796            .saturating_sub(percent_of_max_entries(shrink_to_percent));
797        for (program, entry) in sorted_candidates.iter().take(num_to_unload) {
798            self.unload_program_entry(*program, entry);
799        }
800    }
801
802    /// Evicts programs using random selection, choosing the worst scoring program out of the
803    /// entries sampled.
804    ///
805    /// The eviction is performed enough number of times to reduce the cache usage to the given
806    /// percentage.
807    pub fn evict_using_random_selection(&mut self, shrink_to_percent: Percent, now: Slot) {
808        let mut candidates = self.get_flattened_entries();
809        let mut rng = rng();
810        self.stats
811            .water_level
812            .store(candidates.len() as u64, Ordering::Relaxed);
813        let num_to_unload = candidates
814            .len()
815            .saturating_sub(percent_of_max_entries(shrink_to_percent));
816        let mut sample_entry = |candidates: &Vec<(Pubkey, Arc<ProgramCacheEntry>)>| {
817            // gen_range is deprecated in favor of random_range in rand>=0.9, but we also get
818            // rnd() from shuttle, which doesn't yet support rand 0.9 APIs
819            #[cfg(feature = "shuttle-test")]
820            let index = rng.gen_range(0..candidates.len());
821            #[cfg(not(feature = "shuttle-test"))]
822            let index = rng.random_range(0..candidates.len());
823            let usage_counter = candidates
824                .get(index)
825                .expect("Failed to get cached entry")
826                .1
827                .retention_score();
828            (index, usage_counter)
829        };
830
831        // Random sampling with just 2 choices can frequently lead to a situation where both
832        // entries chosen have relatively high retention scores, having us to pick one out of two
833        // poor options. We can tell what a relatively high retention score is, so we can make a
834        // few additional samples until we hit some other entry that isn't as highly scoring.
835        //
836        // Note that the "high enough" compilation time and use count numbers used here are
837        // relatively arbitrary.
838        const MAX_ADDITIONAL_SAMPLES: usize = 3;
839        let avoid_evicting_above_score = retention_score(now, 500 * EMA_SCALE, 500);
840        for _ in 0..num_to_unload {
841            let (mut index, mut score) = sample_entry(&candidates);
842            for _ in 0..MAX_ADDITIONAL_SAMPLES {
843                let (sample_index, sample_score) = sample_entry(&candidates);
844                if score > sample_score {
845                    index = sample_index;
846                    score = sample_score;
847                }
848                if score < avoid_evicting_above_score {
849                    break;
850                }
851            }
852            let (id, entry) = candidates.swap_remove(index);
853            self.unload_program_entry(id, &entry);
854        }
855    }
856
857    /// Removes all the entries at the given keys, if they exist
858    pub fn remove_programs(&mut self, keys: impl Iterator<Item = Pubkey>) {
859        match &mut self.index {
860            IndexImplementation::V1 { entries, .. } => {
861                for k in keys {
862                    entries.remove(&k);
863                }
864            }
865        }
866    }
867
868    /// This function removes the given entry for the given program from the cache.
869    /// The function expects that the program and entry exists in the cache. Otherwise it'll panic.
870    fn unload_program_entry(&mut self, id: Pubkey, remove_entry: &Arc<ProgramCacheEntry>) {
871        match &mut self.index {
872            IndexImplementation::V1 { entries, .. } => {
873                let second_level = entries.get_mut(&id).expect("Cache lookup failed");
874                let candidate = second_level
875                    .iter_mut()
876                    .find(|entry| Arc::ptr_eq(entry, remove_entry))
877                    .expect("Program entry not found");
878
879                // Only loaded entries shall be unloaded by eviction.
880                if let ProgramCacheEntryType::Loaded(_) = candidate.program
881                    && let Some(unloaded) = candidate.to_unloaded()
882                {
883                    if candidate.stats.uses.load(Ordering::Relaxed) == 1 {
884                        self.stats.one_hit_wonders.fetch_add(1, Ordering::Relaxed);
885                    }
886                    self.stats
887                        .evictions
888                        .entry(id)
889                        .and_modify(|c| *c = c.saturating_add(1))
890                        .or_insert(1);
891                    *candidate = Arc::new(unloaded);
892                }
893            }
894        }
895    }
896
897    fn remove_programs_with_no_entries(&mut self) {
898        match &mut self.index {
899            IndexImplementation::V1 { entries, .. } => {
900                let num_programs_before_removal = entries.len();
901                entries.retain(|_key, second_level| !second_level.is_empty());
902                if entries.len() < num_programs_before_removal {
903                    self.stats.empty_entries.fetch_add(
904                        num_programs_before_removal.saturating_sub(entries.len()) as u64,
905                        Ordering::Relaxed,
906                    );
907                }
908            }
909        }
910    }
911}
912
913#[cfg(test)]
914pub(crate) mod tests {
915    use {
916        crate::{
917            loaded_programs::{
918                BlockRelation, ForkGraph, IndexImplementation, MAX_TOMBSTONE_AGE_IN_SLOTS, Percent,
919                ProgramCache, ProgramCacheForTxBatch, ProgramRuntimeEnvironment, ProgramToLoad,
920                get_mock_program_runtime_environment,
921            },
922            program_cache_entry::{
923                ProgramCacheEntry, ProgramCacheEntryOwner, ProgramCacheEntryType,
924            },
925            program_metrics::ProgramStatistics,
926        },
927        solana_clock::Slot,
928        solana_pubkey::Pubkey,
929        solana_sbpf::{elf::Executable, program::BuiltinProgram},
930        solana_svm_type_overrides::{
931            sync::{
932                Arc, RwLock,
933                atomic::{AtomicU64, Ordering},
934            },
935            thread,
936        },
937        std::{assert_matches, fs::File, io::Read, ops::ControlFlow},
938        test_case::{test_case, test_matrix},
939    };
940
941    fn new_test_entry(deployment_slot: Slot) -> Arc<ProgramCacheEntry> {
942        new_test_entry_with_usage(deployment_slot, ProgramStatistics::default())
943    }
944
945    fn new_closed_entry(_env: ProgramRuntimeEnvironment) -> ProgramCacheEntryType {
946        ProgramCacheEntryType::Closed
947    }
948
949    fn new_builtin_entry(_env: ProgramRuntimeEnvironment) -> ProgramCacheEntryType {
950        ProgramCacheEntryType::Builtin(BuiltinProgram::new_mock())
951    }
952
953    fn new_failed_verification_entry(env: ProgramRuntimeEnvironment) -> ProgramCacheEntryType {
954        ProgramCacheEntryType::FailedVerification(env)
955    }
956
957    fn new_unloaded_entry(env: ProgramRuntimeEnvironment) -> ProgramCacheEntryType {
958        ProgramCacheEntryType::Unloaded(env)
959    }
960
961    fn new_loaded_entry(env: ProgramRuntimeEnvironment) -> ProgramCacheEntryType {
962        let mut elf = Vec::new();
963        File::open("../programs/bpf_loader/test_elfs/out/noop_aligned.so")
964            .unwrap()
965            .read_to_end(&mut elf)
966            .unwrap();
967        let executable = Executable::load(&elf, Arc::clone(&*env)).unwrap();
968        ProgramCacheEntryType::Loaded(executable)
969    }
970
971    fn new_test_entry_with_owner(
972        deployment_slot: Slot,
973        account_owner: ProgramCacheEntryOwner,
974        program: ProgramCacheEntryType,
975    ) -> Arc<ProgramCacheEntry> {
976        Arc::new(ProgramCacheEntry {
977            program,
978            account_owner,
979            deployment_slot,
980            stats: Arc::default(),
981            latest_access_slot: AtomicU64::default(),
982        })
983    }
984
985    fn new_test_cache_with_fork_graph(
986        relation: BlockRelation,
987    ) -> (ProgramCache<TestForkGraph>, Arc<RwLock<TestForkGraph>>) {
988        let mut cache = ProgramCache::<TestForkGraph>::new(0);
989        let fork_graph = Arc::new(RwLock::new(TestForkGraph { relation }));
990        cache.set_fork_graph(Arc::downgrade(&fork_graph));
991        (cache, fork_graph)
992    }
993
994    pub(crate) fn new_test_entry_with_usage(
995        deployment_slot: Slot,
996        stats: ProgramStatistics,
997    ) -> Arc<ProgramCacheEntry> {
998        Arc::new(ProgramCacheEntry {
999            program: new_loaded_entry(get_mock_program_runtime_environment()),
1000            account_owner: ProgramCacheEntryOwner::LoaderV2,
1001            deployment_slot,
1002            stats: Arc::new(stats),
1003            latest_access_slot: AtomicU64::new(deployment_slot),
1004        })
1005    }
1006
1007    fn new_test_builtin_entry(deployment_slot: Slot) -> Arc<ProgramCacheEntry> {
1008        Arc::new(ProgramCacheEntry {
1009            program: ProgramCacheEntryType::Builtin(BuiltinProgram::new_mock()),
1010            account_owner: ProgramCacheEntryOwner::NativeLoader,
1011            deployment_slot,
1012            stats: Arc::default(),
1013            latest_access_slot: AtomicU64::default(),
1014        })
1015    }
1016
1017    fn set_failed_verification_tombstone<FG: ForkGraph>(
1018        cache: &mut ProgramCache<FG>,
1019        key: Pubkey,
1020        current_slot: Slot,
1021        env: ProgramRuntimeEnvironment,
1022    ) -> Arc<ProgramCacheEntry> {
1023        let program = Arc::new(ProgramCacheEntry::new_failed_verification_tombstone(
1024            current_slot,
1025            ProgramCacheEntryOwner::LoaderV2,
1026            ProgramRuntimeEnvironment::clone(&env),
1027        ));
1028        cache.assign_program(&env, key, current_slot, program.clone());
1029        program
1030    }
1031
1032    fn insert_unloaded_entry<FG: ForkGraph>(
1033        cache: &mut ProgramCache<FG>,
1034        key: Pubkey,
1035        current_slot: Slot,
1036    ) -> Arc<ProgramCacheEntry> {
1037        let env = get_mock_program_runtime_environment();
1038        let loaded = new_test_entry_with_usage(current_slot, ProgramStatistics::default());
1039        let unloaded = Arc::new(loaded.to_unloaded().expect("Failed to unload the program"));
1040        cache.assign_program(&env, key, current_slot, unloaded.clone());
1041        unloaded
1042    }
1043
1044    fn num_matching_entries<P, FG>(cache: &ProgramCache<FG>, predicate: P) -> usize
1045    where
1046        P: Fn(&ProgramCacheEntryType) -> bool,
1047        FG: ForkGraph,
1048    {
1049        cache
1050            .get_flattened_entries_for_tests()
1051            .iter()
1052            .filter(|(_key, program)| predicate(&program.program))
1053            .count()
1054    }
1055
1056    #[expect(clippy::arithmetic_side_effects)]
1057    fn program_deploy_test_helper(
1058        cache: &mut ProgramCache<TestForkGraph>,
1059        program: Pubkey,
1060        deployment_slots: Vec<Slot>,
1061        usage_counters: Vec<u64>,
1062        programs: &mut Vec<(Pubkey, Slot, u64)>,
1063    ) {
1064        let env = get_mock_program_runtime_environment();
1065        // Add multiple entries for program
1066        deployment_slots
1067            .iter()
1068            .enumerate()
1069            .for_each(|(i, deployment_slot)| {
1070                let usage_counter = *usage_counters.get(i).unwrap_or(&0);
1071                let stats = ProgramStatistics {
1072                    uses: usage_counter.into(),
1073                    ..Default::default()
1074                };
1075                cache.assign_program(
1076                    &env,
1077                    program,
1078                    *deployment_slot,
1079                    new_test_entry_with_usage(*deployment_slot, stats),
1080                );
1081                programs.push((program, *deployment_slot, usage_counter));
1082            });
1083
1084        let next_slot = deployment_slots.iter().max().map_or(0, |slot| slot + 1);
1085
1086        // Add tombstones entries for program
1087        let env = ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock());
1088        for slot in next_slot..next_slot + 10 {
1089            set_failed_verification_tombstone(
1090                cache,
1091                program,
1092                slot,
1093                ProgramRuntimeEnvironment::clone(&env),
1094            );
1095        }
1096
1097        // Add unloaded entries for program
1098        for slot in next_slot + 10..next_slot + 20 {
1099            insert_unloaded_entry(cache, program, slot);
1100        }
1101    }
1102
1103    #[test]
1104    fn test_random_eviction() {
1105        let mut programs = vec![];
1106        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1107
1108        // This test adds different kind of entries to the cache.
1109        // Tombstones and unloaded entries are expected to not be evicted.
1110        // It also adds multiple entries for three programs as it tries to create a typical cache instance.
1111
1112        // Program 1
1113        program_deploy_test_helper(
1114            &mut cache,
1115            Pubkey::new_unique(),
1116            vec![0, 10, 20, 30, 40],
1117            vec![4, 5, 25, 35, 12],
1118            &mut programs,
1119        );
1120
1121        // Program 2
1122        program_deploy_test_helper(
1123            &mut cache,
1124            Pubkey::new_unique(),
1125            vec![5, 11, 21, 24],
1126            vec![0, 2, 30, 45],
1127            &mut programs,
1128        );
1129
1130        // Program 3
1131        program_deploy_test_helper(
1132            &mut cache,
1133            Pubkey::new_unique(),
1134            vec![0, 5, 15, 25],
1135            vec![100, 3, 20, 40],
1136            &mut programs,
1137        );
1138
1139        // 1 for each deployment slot
1140        let num_loaded_expected = 13;
1141        // 10 for each program
1142        let num_unloaded_expected = 30;
1143        // 10 for each program
1144        let num_tombstones_expected = 30;
1145
1146        // Count the number of loaded, unloaded and tombstone entries.
1147        programs.sort_by_key(|(_id, _slot, usage_count)| *usage_count);
1148        let num_loaded = num_matching_entries(&cache, |program_type| {
1149            matches!(program_type, ProgramCacheEntryType::Loaded(_))
1150        });
1151        let num_unloaded = num_matching_entries(&cache, |program_type| {
1152            matches!(program_type, ProgramCacheEntryType::Unloaded(_))
1153        });
1154        let num_tombstones = num_matching_entries(&cache, |program_type| {
1155            matches!(
1156                program_type,
1157                ProgramCacheEntryType::DelayVisibility
1158                    | ProgramCacheEntryType::FailedVerification(_)
1159                    | ProgramCacheEntryType::Closed
1160            )
1161        });
1162
1163        // Test that the cache is constructed with the expected number of entries.
1164        assert_eq!(num_loaded, num_loaded_expected);
1165        assert_eq!(num_unloaded, num_unloaded_expected);
1166        assert_eq!(num_tombstones, num_tombstones_expected);
1167
1168        // Evict entries from the cache
1169        let eviction_pct: Percent = 1;
1170
1171        let num_loaded_expected = crate::loaded_programs::percent_of_max_entries(eviction_pct);
1172        let num_unloaded_expected = num_unloaded_expected + num_loaded - num_loaded_expected;
1173        cache.evict_using_random_selection(eviction_pct, 21);
1174
1175        // Count the number of loaded, unloaded and tombstone entries.
1176        let num_loaded = num_matching_entries(&cache, |program_type| {
1177            matches!(program_type, ProgramCacheEntryType::Loaded(_))
1178        });
1179        let num_unloaded = num_matching_entries(&cache, |program_type| {
1180            matches!(program_type, ProgramCacheEntryType::Unloaded(_))
1181        });
1182        let num_tombstones = num_matching_entries(&cache, |program_type| {
1183            matches!(program_type, ProgramCacheEntryType::FailedVerification(_))
1184        });
1185
1186        // However many entries are left after the shrink
1187        assert_eq!(num_loaded, num_loaded_expected);
1188        // The original unloaded entries + the evicted loaded entries
1189        assert_eq!(num_unloaded, num_unloaded_expected);
1190        // The original tombstones are not evicted
1191        assert_eq!(num_tombstones, num_tombstones_expected);
1192    }
1193
1194    #[test]
1195    fn test_eviction() {
1196        let mut programs = vec![];
1197        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1198
1199        // Program 1
1200        program_deploy_test_helper(
1201            &mut cache,
1202            Pubkey::new_unique(),
1203            vec![0, 10, 20, 30, 40],
1204            vec![4, 5, 25, 35, 12],
1205            &mut programs,
1206        );
1207
1208        // Program 2
1209        program_deploy_test_helper(
1210            &mut cache,
1211            Pubkey::new_unique(),
1212            vec![5, 11, 21, 24],
1213            vec![0, 2, 30, 45],
1214            &mut programs,
1215        );
1216
1217        // Program 3
1218        program_deploy_test_helper(
1219            &mut cache,
1220            Pubkey::new_unique(),
1221            vec![0, 5, 15, 25],
1222            vec![100, 3, 20, 40],
1223            &mut programs,
1224        );
1225
1226        // 1 for each deployment slot
1227        let num_loaded_expected = 13;
1228        // 10 for each program
1229        let num_unloaded_expected = 30;
1230        // 10 for each program
1231        let num_tombstones_expected = 30;
1232
1233        // Count the number of loaded, unloaded and tombstone entries.
1234        programs.sort_by_key(|(_id, _slot, usage_count)| *usage_count);
1235        let num_loaded = num_matching_entries(&cache, |program_type| {
1236            matches!(program_type, ProgramCacheEntryType::Loaded(_))
1237        });
1238        let num_unloaded = num_matching_entries(&cache, |program_type| {
1239            matches!(program_type, ProgramCacheEntryType::Unloaded(_))
1240        });
1241        let num_tombstones = num_matching_entries(&cache, |program_type| {
1242            matches!(program_type, ProgramCacheEntryType::FailedVerification(_))
1243        });
1244
1245        // Test that the cache is constructed with the expected number of entries.
1246        assert_eq!(num_loaded, num_loaded_expected);
1247        assert_eq!(num_unloaded, num_unloaded_expected);
1248        assert_eq!(num_tombstones, num_tombstones_expected);
1249
1250        // Evict entries from the cache
1251        let eviction_pct: Percent = 1;
1252
1253        let num_loaded_expected = crate::loaded_programs::percent_of_max_entries(eviction_pct);
1254        let num_unloaded_expected = num_unloaded_expected + num_loaded - num_loaded_expected;
1255
1256        cache.sort_and_unload(eviction_pct);
1257
1258        // Check that every program is still in the cache.
1259        let entries = cache.get_flattened_entries_for_tests();
1260        programs.iter().for_each(|entry| {
1261            assert!(entries.iter().any(|(key, _entry)| key == &entry.0));
1262        });
1263
1264        let unloaded = entries
1265            .iter()
1266            .filter_map(|(key, program)| {
1267                program
1268                    .is_unloaded()
1269                    .then_some((*key, program.stats.uses.load(Ordering::Relaxed)))
1270            })
1271            .collect::<Vec<(Pubkey, u64)>>();
1272
1273        for index in 0..3 {
1274            let expected = programs.get(index).expect("Missing program");
1275            assert!(unloaded.contains(&(expected.0, expected.2)));
1276        }
1277
1278        // Count the number of loaded, unloaded and tombstone entries.
1279        let num_loaded = num_matching_entries(&cache, |program_type| {
1280            matches!(program_type, ProgramCacheEntryType::Loaded(_))
1281        });
1282        let num_unloaded = num_matching_entries(&cache, |program_type| {
1283            matches!(program_type, ProgramCacheEntryType::Unloaded(_))
1284        });
1285        let num_tombstones = num_matching_entries(&cache, |program_type| {
1286            matches!(
1287                program_type,
1288                ProgramCacheEntryType::DelayVisibility
1289                    | ProgramCacheEntryType::FailedVerification(_)
1290                    | ProgramCacheEntryType::Closed
1291            )
1292        });
1293
1294        // However many entries are left after the shrink
1295        assert_eq!(num_loaded, num_loaded_expected);
1296        // The original unloaded entries + the evicted loaded entries
1297        assert_eq!(num_unloaded, num_unloaded_expected);
1298        // The original tombstones are not evicted
1299        assert_eq!(num_tombstones, num_tombstones_expected);
1300    }
1301
1302    #[test]
1303    fn test_usage_count_of_unloaded_program() {
1304        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1305        let env = get_mock_program_runtime_environment();
1306
1307        let program = Pubkey::new_unique();
1308        let evict_to_pct: Percent = 2;
1309        let cache_capacity_after_shrink =
1310            crate::loaded_programs::percent_of_max_entries(evict_to_pct);
1311        // Add enough programs to the cache to trigger 1 eviction after shrinking.
1312        let num_total_programs = (cache_capacity_after_shrink + 1) as u64;
1313        (0..num_total_programs).for_each(|i| {
1314            let stats = ProgramStatistics {
1315                uses: (i + 10).into(),
1316                ..Default::default()
1317            };
1318            let entry = new_test_entry_with_usage(i, stats);
1319            cache.assign_program(&env, program, i, entry);
1320        });
1321
1322        cache.sort_and_unload(evict_to_pct);
1323
1324        let num_unloaded = num_matching_entries(&cache, |program_type| {
1325            matches!(program_type, ProgramCacheEntryType::Unloaded(_))
1326        });
1327        assert_eq!(num_unloaded, 1);
1328
1329        cache
1330            .get_flattened_entries_for_tests()
1331            .iter()
1332            .for_each(|(_key, program)| {
1333                if program.is_unloaded() {
1334                    // Test that the usage counter is retained for the unloaded program
1335                    assert_eq!(program.stats.uses.load(Ordering::Relaxed), 10);
1336                    assert_eq!(program.deployment_slot, 0);
1337                    assert_eq!(program.effective_slot(), 1);
1338                }
1339            });
1340
1341        // Replenish the program that was just unloaded. Use 0 as the usage counter. This should be
1342        // updated with the usage counter from the unloaded program.
1343        cache.assign_program(
1344            &env,
1345            program,
1346            0,
1347            new_test_entry_with_usage(0, ProgramStatistics::default()),
1348        );
1349
1350        cache
1351            .get_flattened_entries_for_tests()
1352            .iter()
1353            .for_each(|(_key, program)| {
1354                if program.is_unloaded()
1355                    && program.deployment_slot == 0
1356                    && program.effective_slot() == 1
1357                {
1358                    // Test that the usage counter was correctly updated.
1359                    assert_eq!(program.stats.uses.load(Ordering::Relaxed), 10);
1360                }
1361            });
1362    }
1363
1364    #[test_matrix(
1365        (
1366            ProgramCacheEntryType::FailedVerification(get_mock_program_runtime_environment()),
1367            ProgramCacheEntryType::Closed,
1368            ProgramCacheEntryType::Unloaded(get_mock_program_runtime_environment()),
1369            new_loaded_entry(get_mock_program_runtime_environment()),
1370            ProgramCacheEntryType::Builtin(BuiltinProgram::new_mock()),
1371        ),
1372        (false, true)
1373    )]
1374    fn test_assign_program_no_second_level(
1375        program: ProgramCacheEntryType,
1376        empty_second_level: bool,
1377    ) {
1378        // Here we test the scenario where no second_level entry exists for the
1379        // program. We expect the `second_level.binary_search_by` to return
1380        // `Err(0)` and we expect the single entry to land in the cache.
1381        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1382        let env = get_mock_program_runtime_environment();
1383        let program_id = Pubkey::new_unique();
1384
1385        if empty_second_level {
1386            // Make the entry already exist, but with an empty second level.
1387            match &mut cache.index {
1388                IndexImplementation::V1 { entries, .. } => {
1389                    entries.insert(program_id, Vec::new());
1390                }
1391            }
1392        }
1393
1394        let entry = Arc::new(ProgramCacheEntry {
1395            program,
1396            account_owner: ProgramCacheEntryOwner::LoaderV3,
1397            deployment_slot: 10,
1398            stats: Arc::default(),
1399            latest_access_slot: AtomicU64::default(),
1400        });
1401
1402        cache.assign_program(&env, program_id, 10, Arc::clone(&entry));
1403
1404        // We should have just the one single entry we just inserted.
1405        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
1406        assert_eq!(slot_versions.len(), 1);
1407        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &entry));
1408
1409        // Stats should be incremented by 1 to exactly 1.
1410        assert_eq!(cache.stats.insertions.load(Ordering::Relaxed), 1);
1411    }
1412
1413    #[test_matrix(
1414        (
1415            new_closed_entry,
1416            new_builtin_entry,
1417            new_failed_verification_entry,
1418            new_unloaded_entry,
1419            new_loaded_entry,
1420        ),
1421        ((50, 0), (150, 1), (250, 2), (350, 3))
1422    )]
1423    fn test_assign_program_new_insertion_deployment_slot(
1424        new_program: fn(ProgramRuntimeEnvironment) -> ProgramCacheEntryType,
1425        case: (Slot, usize),
1426    ) {
1427        let (deployment_slot, expected_index) = case;
1428        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1429        let env = get_mock_program_runtime_environment();
1430        let program_id = Pubkey::new_unique();
1431
1432        // Entries at distinct deployment slots always coexist.
1433        for slot in [100, 200, 300] {
1434            cache.assign_program(
1435                &env,
1436                program_id,
1437                slot,
1438                new_test_entry_with_owner(
1439                    slot,
1440                    ProgramCacheEntryOwner::LoaderV3,
1441                    new_program(env.clone()),
1442                ),
1443            );
1444        }
1445
1446        // Only the deployment slot differs, so it alone decides the index.
1447        let entry = new_test_entry_with_owner(
1448            deployment_slot,
1449            ProgramCacheEntryOwner::LoaderV3,
1450            new_program(env.clone()),
1451        );
1452        cache.assign_program(&env, program_id, deployment_slot, Arc::clone(&entry));
1453
1454        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
1455        assert_eq!(slot_versions.len(), 4);
1456        assert!(Arc::ptr_eq(
1457            slot_versions.get(expected_index).unwrap(),
1458            &entry
1459        ));
1460        assert_eq!(cache.stats.insertions.load(Ordering::Relaxed), 4);
1461    }
1462
1463    #[test_matrix(
1464        (new_failed_verification_entry, new_unloaded_entry, new_loaded_entry),
1465        (
1466            (ProgramCacheEntryOwner::NativeLoader, 0),
1467            (ProgramCacheEntryOwner::LoaderV2, 1),
1468            (ProgramCacheEntryOwner::LoaderV4, 2),
1469        )
1470    )]
1471    fn test_assign_program_new_insertion_account_owner(
1472        new_program: fn(ProgramRuntimeEnvironment) -> ProgramCacheEntryType,
1473        case: (ProgramCacheEntryOwner, usize),
1474    ) {
1475        let (account_owner, expected_index) = case;
1476        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1477        let env = get_mock_program_runtime_environment();
1478        let program_id = Pubkey::new_unique();
1479
1480        // Entries at the same deployment slot only coexist when their
1481        // environments differ, so give each one its own.
1482        for owner in [
1483            ProgramCacheEntryOwner::LoaderV1,
1484            ProgramCacheEntryOwner::LoaderV3,
1485        ] {
1486            cache.assign_program(
1487                &env,
1488                program_id,
1489                100,
1490                new_test_entry_with_owner(
1491                    100,
1492                    owner,
1493                    new_program(ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock())),
1494                ),
1495            );
1496        }
1497
1498        // None of the environments are the current one, so the account owner
1499        // alone decides the index.
1500        let entry = new_test_entry_with_owner(
1501            100,
1502            account_owner,
1503            new_program(ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock())),
1504        );
1505        cache.assign_program(&env, program_id, 100, Arc::clone(&entry));
1506
1507        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
1508        assert_eq!(slot_versions.len(), 3);
1509        assert!(Arc::ptr_eq(
1510            slot_versions.get(expected_index).unwrap(),
1511            &entry
1512        ));
1513        assert_eq!(cache.stats.insertions.load(Ordering::Relaxed), 3);
1514    }
1515
1516    #[test_matrix(
1517        (new_failed_verification_entry, new_unloaded_entry, new_loaded_entry),
1518        (false, true)
1519    )]
1520    fn test_assign_program_new_insertion_environment(
1521        new_program: fn(ProgramRuntimeEnvironment) -> ProgramCacheEntryType,
1522        entry_uses_current_env: bool,
1523    ) {
1524        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1525        let env = get_mock_program_runtime_environment();
1526        let other_env = ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock());
1527        let program_id = Pubkey::new_unique();
1528
1529        // Deployment slot and account owner are equal, so entries for the
1530        // current environment sort after those which are not.
1531        let (existing_env, entry_env, expected_index) = if entry_uses_current_env {
1532            (other_env, env.clone(), 1)
1533        } else {
1534            (env.clone(), other_env, 0)
1535        };
1536        cache.assign_program(
1537            &env,
1538            program_id,
1539            100,
1540            new_test_entry_with_owner(
1541                100,
1542                ProgramCacheEntryOwner::LoaderV3,
1543                new_program(existing_env),
1544            ),
1545        );
1546
1547        let entry = new_test_entry_with_owner(
1548            100,
1549            ProgramCacheEntryOwner::LoaderV3,
1550            new_program(entry_env),
1551        );
1552        cache.assign_program(&env, program_id, 100, Arc::clone(&entry));
1553
1554        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
1555        assert_eq!(slot_versions.len(), 2);
1556        assert!(Arc::ptr_eq(
1557            slot_versions.get(expected_index).unwrap(),
1558            &entry
1559        ));
1560        assert_eq!(cache.stats.insertions.load(Ordering::Relaxed), 2);
1561    }
1562
1563    #[test]
1564    #[should_panic(expected = "Unexpected assignment of a DelayVisibility tombstone")]
1565    fn test_assign_program_delay_visibility_tombstone_panics() {
1566        // A tombstone minted by `extract` only ever lives in the batch cache.
1567        // Assigning one into the global cache is a caller error.
1568        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1569        let env = get_mock_program_runtime_environment();
1570        cache.assign_program(
1571            &env,
1572            Pubkey::new_unique(),
1573            100,
1574            Arc::new(ProgramCacheEntry::new_delay_visibility_tombstone(
1575                100,
1576                ProgramCacheEntryOwner::LoaderV3,
1577                Arc::default(),
1578            )),
1579        );
1580    }
1581
1582    #[test]
1583    fn test_fuzz_assign_program_order() {
1584        use rand::prelude::SliceRandom;
1585        const EXPECTED_ENTRIES: [(u64, bool); 5] =
1586            [(1, true), (3, false), (5, true), (9, true), (10, false)];
1587        let mut rng = rand::rng();
1588        let program_id = Pubkey::new_unique();
1589        let env = get_mock_program_runtime_environment();
1590        for _ in 0..1000 {
1591            let mut entries = EXPECTED_ENTRIES.to_vec();
1592            entries.shuffle(&mut rng);
1593            let mut cache = ProgramCache::<TestForkGraph>::new(0);
1594            for (deployment_slot, delay_visibility) in entries {
1595                let entry = Arc::new(if delay_visibility {
1596                    ProgramCacheEntry {
1597                        program: new_loaded_entry(ProgramRuntimeEnvironment::from(
1598                            BuiltinProgram::new_mock(),
1599                        )), // Assign them different environments
1600                        account_owner: ProgramCacheEntryOwner::LoaderV2,
1601                        deployment_slot,
1602                        stats: Arc::default(),
1603                        latest_access_slot: AtomicU64::new(deployment_slot),
1604                    }
1605                } else {
1606                    ProgramCacheEntry::new_failed_verification_tombstone(
1607                        deployment_slot,
1608                        ProgramCacheEntryOwner::LoaderV2,
1609                        ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock()), // Assign them different environments
1610                    )
1611                });
1612                assert!(!cache.assign_program(&env, program_id, deployment_slot, entry));
1613            }
1614            for ((deployment_slot, delay_visibility), entry) in EXPECTED_ENTRIES
1615                .iter()
1616                .zip(cache.get_slot_versions_for_tests(&program_id).iter())
1617            {
1618                assert_eq!(entry.deployment_slot, *deployment_slot);
1619                assert_eq!(
1620                    entry.effective_slot(),
1621                    deployment_slot.saturating_add(*delay_visibility as u64)
1622                );
1623            }
1624        }
1625    }
1626
1627    #[test_matrix(
1628        (
1629            ProgramCacheEntryType::FailedVerification(get_mock_program_runtime_environment()),
1630            new_loaded_entry(get_mock_program_runtime_environment()),
1631        ),
1632        (
1633            ProgramCacheEntryType::FailedVerification(get_mock_program_runtime_environment()),
1634            ProgramCacheEntryType::Closed,
1635            ProgramCacheEntryType::Unloaded(get_mock_program_runtime_environment()),
1636            new_loaded_entry(get_mock_program_runtime_environment()),
1637            ProgramCacheEntryType::Builtin(BuiltinProgram::new_mock()),
1638        )
1639    )]
1640    #[test_matrix(
1641        ProgramCacheEntryType::Closed,
1642        (
1643            ProgramCacheEntryType::FailedVerification(get_mock_program_runtime_environment()),
1644            ProgramCacheEntryType::Closed,
1645            new_loaded_entry(get_mock_program_runtime_environment()),
1646            ProgramCacheEntryType::Builtin(BuiltinProgram::new_mock()),
1647        )
1648    )]
1649    #[test_matrix(
1650        ProgramCacheEntryType::Unloaded(get_mock_program_runtime_environment()),
1651        (
1652            ProgramCacheEntryType::Closed,
1653            ProgramCacheEntryType::Unloaded(get_mock_program_runtime_environment()),
1654            ProgramCacheEntryType::Builtin(BuiltinProgram::new_mock()),
1655        )
1656    )]
1657    #[test_matrix(
1658        (ProgramCacheEntryType::Builtin(BuiltinProgram::new_mock()),),
1659        (
1660            ProgramCacheEntryType::FailedVerification(get_mock_program_runtime_environment()),
1661            ProgramCacheEntryType::Closed,
1662            ProgramCacheEntryType::Unloaded(get_mock_program_runtime_environment()),
1663            new_loaded_entry(get_mock_program_runtime_environment()),
1664        )
1665    )]
1666    #[should_panic(expected = "Unexpected replacement of an entry")]
1667    fn test_assign_program_failure(old: ProgramCacheEntryType, new: ProgramCacheEntryType) {
1668        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1669        let env = get_mock_program_runtime_environment();
1670        let program_id = Pubkey::new_unique();
1671        assert!(!cache.assign_program(
1672            &env,
1673            program_id,
1674            10,
1675            Arc::new(ProgramCacheEntry {
1676                program: old,
1677                account_owner: ProgramCacheEntryOwner::LoaderV2,
1678                deployment_slot: 10,
1679                stats: Arc::default(),
1680                latest_access_slot: AtomicU64::default(),
1681            }),
1682        ));
1683        cache.assign_program(
1684            &env,
1685            program_id,
1686            10,
1687            Arc::new(ProgramCacheEntry {
1688                program: new,
1689                account_owner: ProgramCacheEntryOwner::LoaderV2,
1690                deployment_slot: 10,
1691                stats: Arc::default(),
1692                latest_access_slot: AtomicU64::default(),
1693            }),
1694        );
1695    }
1696
1697    #[test_matrix(
1698        ProgramCacheEntryType::Unloaded(get_mock_program_runtime_environment()),
1699        (
1700            new_loaded_entry(get_mock_program_runtime_environment()),
1701            ProgramCacheEntryType::FailedVerification(get_mock_program_runtime_environment()),
1702        )
1703    )]
1704    #[test_case(
1705        ProgramCacheEntryType::Closed,
1706        ProgramCacheEntryType::Unloaded(get_mock_program_runtime_environment())
1707    )]
1708    #[test_case(
1709        ProgramCacheEntryType::Builtin(BuiltinProgram::new_mock()),
1710        ProgramCacheEntryType::Builtin(BuiltinProgram::new_mock())
1711    )]
1712    fn test_assign_program_success(old: ProgramCacheEntryType, new: ProgramCacheEntryType) {
1713        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1714        let env = get_mock_program_runtime_environment();
1715        let program_id = Pubkey::new_unique();
1716        assert!(!cache.assign_program(
1717            &env,
1718            program_id,
1719            10,
1720            Arc::new(ProgramCacheEntry {
1721                program: old,
1722                account_owner: ProgramCacheEntryOwner::LoaderV2,
1723                deployment_slot: 10,
1724                stats: Arc::default(),
1725                latest_access_slot: AtomicU64::default(),
1726            }),
1727        ));
1728        assert!(!cache.assign_program(
1729            &env,
1730            program_id,
1731            10,
1732            Arc::new(ProgramCacheEntry {
1733                program: new,
1734                account_owner: ProgramCacheEntryOwner::LoaderV2,
1735                deployment_slot: 10,
1736                stats: Arc::default(),
1737                latest_access_slot: AtomicU64::default(),
1738            }),
1739        ));
1740    }
1741
1742    #[test]
1743    fn test_assign_program_removes_entries_in_same_slot() {
1744        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1745        let env = get_mock_program_runtime_environment();
1746        let program_id = Pubkey::new_unique();
1747        let closed_other_slot = new_test_entry_with_owner(
1748            9,
1749            ProgramCacheEntryOwner::LoaderV2,
1750            new_closed_entry(env.clone()),
1751        );
1752        let closed_current_slot = new_test_entry_with_owner(
1753            10,
1754            ProgramCacheEntryOwner::LoaderV2,
1755            new_closed_entry(env.clone()),
1756        );
1757        let unloaded_current_env = new_test_entry_with_owner(
1758            10,
1759            ProgramCacheEntryOwner::LoaderV2,
1760            new_unloaded_entry(get_mock_program_runtime_environment()),
1761        );
1762        let unloaded_upcoming_env = new_test_entry_with_owner(
1763            10,
1764            ProgramCacheEntryOwner::LoaderV2,
1765            new_unloaded_entry(ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock())),
1766        );
1767
1768        // Here the ordering is important.
1769        // We have an older `Closed` tombstone for a different slot, so when we
1770        // go to insert `Closed` for slot 10, they are allowed to coexist.
1771        assert!(!cache.assign_program(&env, program_id, 9, closed_other_slot.clone()));
1772        assert!(!cache.assign_program(&env, program_id, 10, closed_current_slot.clone()));
1773        assert_eq!(
1774            cache.get_slot_versions_for_tests(&program_id),
1775            &[closed_other_slot.clone(), closed_current_slot.clone()]
1776        );
1777
1778        // However, if we then insert an `Unloaded` entry for slot 10, it will
1779        // nuke the `Closed` tombstone that was there.
1780        //
1781        // This is because a closed tombstone has no environment, so the
1782        // env-based sweep criteria unwraps to `keep=false`.
1783        //
1784        // Inserting an `env=None` entry here would also cause `keep=false`,
1785        // but none such transitions are allowed.
1786        assert!(!cache.assign_program(&env, program_id, 10, unloaded_current_env.clone()));
1787        assert_eq!(
1788            cache.get_slot_versions_for_tests(&program_id),
1789            &[
1790                closed_other_slot.clone(),
1791                unloaded_current_env.clone() // <-- Closed is gone for slot 10
1792            ]
1793        );
1794
1795        // Now insert another unloaded entry for the same slot 10, but on a
1796        // different environment. When both entries have `env=Some`, they are
1797        // actually compared, and if they differ, we get `keep=true`.
1798        assert!(!cache.assign_program(&env, program_id, 10, unloaded_upcoming_env.clone()));
1799        assert_eq!(
1800            cache.get_slot_versions_for_tests(&program_id),
1801            &[
1802                closed_other_slot,
1803                unloaded_current_env,
1804                unloaded_upcoming_env
1805            ]
1806        );
1807    }
1808
1809    #[test]
1810    fn test_assign_program_reload_merges_statistics() {
1811        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1812        let env = get_mock_program_runtime_environment();
1813        let program_id = Pubkey::new_unique();
1814
1815        let stats = Arc::new(ProgramStatistics {
1816            uses: 1.into(),
1817            compilations: 2.into(),
1818            total_compilation_time_us: 3.into(),
1819            compilation_time_ema: 100.into(),
1820            jit_invocations: 4.into(),
1821            total_jit_execution_time_us: 5.into(),
1822            jit_execution_time_ema: 200.into(),
1823            interpreted_invocations: 6.into(),
1824            total_interpretation_time_us: 7.into(),
1825            interpretation_time_ema: 300.into(),
1826        });
1827        let unloaded = Arc::new(ProgramCacheEntry {
1828            program: ProgramCacheEntryType::Unloaded(env.clone()),
1829            account_owner: ProgramCacheEntryOwner::LoaderV3,
1830            deployment_slot: 100,
1831            stats: Arc::clone(&stats),
1832            latest_access_slot: AtomicU64::default(),
1833        });
1834        cache.assign_program(&env, program_id, 100, unloaded);
1835
1836        // `Unloaded` -> `Loaded` matches the existing entry, so it is a reload.
1837        let loaded = Arc::new(ProgramCacheEntry {
1838            program: new_loaded_entry(env.clone()),
1839            account_owner: ProgramCacheEntryOwner::LoaderV3,
1840            deployment_slot: 100,
1841            stats: Arc::default(), // <-- Empty stats
1842            latest_access_slot: AtomicU64::default(),
1843        });
1844        cache.assign_program(&env, program_id, 100, Arc::clone(&loaded));
1845
1846        assert_eq!(cache.stats.insertions.load(Ordering::Relaxed), 1);
1847        assert_eq!(cache.stats.reloads.load(Ordering::Relaxed), 1);
1848
1849        let merged = &loaded.stats;
1850        let ord = Ordering::Relaxed;
1851        assert_eq!(merged.uses.load(ord), stats.uses.load(ord));
1852        assert_eq!(merged.compilations.load(ord), stats.compilations.load(ord));
1853        assert_eq!(
1854            merged.total_compilation_time_us.load(ord),
1855            stats.total_compilation_time_us.load(ord)
1856        );
1857        assert_eq!(
1858            merged.jit_invocations.load(ord),
1859            stats.jit_invocations.load(ord)
1860        );
1861        assert_eq!(
1862            merged.total_jit_execution_time_us.load(ord),
1863            stats.total_jit_execution_time_us.load(ord)
1864        );
1865        assert_eq!(
1866            merged.interpreted_invocations.load(ord),
1867            stats.interpreted_invocations.load(ord)
1868        );
1869        assert_eq!(
1870            merged.total_interpretation_time_us.load(ord),
1871            stats.total_interpretation_time_us.load(ord)
1872        );
1873
1874        // The moving averages are weighted against the empty ones of the new
1875        // entry, which halves them.
1876        const EMA_DIVISOR: u64 = 2;
1877        assert_eq!(
1878            merged.compilation_time_ema.load(ord),
1879            stats
1880                .compilation_time_ema
1881                .load(ord)
1882                .wrapping_div(EMA_DIVISOR)
1883        );
1884        assert_eq!(
1885            merged.jit_execution_time_ema.load(ord),
1886            stats
1887                .jit_execution_time_ema
1888                .load(ord)
1889                .wrapping_div(EMA_DIVISOR)
1890        );
1891        assert_eq!(
1892            merged.interpretation_time_ema.load(ord),
1893            stats
1894                .interpretation_time_ema
1895                .load(ord)
1896                .wrapping_div(EMA_DIVISOR)
1897        );
1898    }
1899
1900    #[test]
1901    fn test_tombstone() {
1902        let env = get_mock_program_runtime_environment();
1903        let tombstone = ProgramCacheEntry::new_failed_verification_tombstone(
1904            0,
1905            ProgramCacheEntryOwner::LoaderV2,
1906            env.clone(),
1907        );
1908        assert_matches!(
1909            tombstone.program,
1910            ProgramCacheEntryType::FailedVerification(_)
1911        );
1912        assert!(tombstone.is_tombstone());
1913        assert_eq!(tombstone.deployment_slot, 0);
1914        assert_eq!(tombstone.effective_slot(), 0);
1915
1916        let tombstone =
1917            ProgramCacheEntry::new_closed_tombstone(100, ProgramCacheEntryOwner::LoaderV2);
1918        assert_matches!(tombstone.program, ProgramCacheEntryType::Closed);
1919        assert!(tombstone.is_tombstone());
1920        assert_eq!(tombstone.deployment_slot, 100);
1921        assert_eq!(tombstone.effective_slot(), 100);
1922
1923        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1924        let program1 = Pubkey::new_unique();
1925        let tombstone = set_failed_verification_tombstone(&mut cache, program1, 10, env.clone());
1926        let slot_versions = cache.get_slot_versions_for_tests(&program1);
1927        assert_eq!(slot_versions.len(), 1);
1928        assert!(slot_versions.first().unwrap().is_tombstone());
1929        assert_eq!(tombstone.deployment_slot, 10);
1930        assert_eq!(tombstone.effective_slot(), 10);
1931
1932        // Add a program at slot 50, and a tombstone for the program at slot 60
1933        let program2 = Pubkey::new_unique();
1934        cache.assign_program(&env, program2, 50, new_test_builtin_entry(50));
1935        let slot_versions = cache.get_slot_versions_for_tests(&program2);
1936        assert_eq!(slot_versions.len(), 1);
1937        assert!(!slot_versions.first().unwrap().is_tombstone());
1938
1939        let tombstone = set_failed_verification_tombstone(&mut cache, program2, 60, env);
1940        let slot_versions = cache.get_slot_versions_for_tests(&program2);
1941        assert_eq!(slot_versions.len(), 2);
1942        assert!(!slot_versions.first().unwrap().is_tombstone());
1943        assert!(slot_versions.get(1).unwrap().is_tombstone());
1944        assert!(tombstone.is_tombstone());
1945        assert_eq!(tombstone.deployment_slot, 60);
1946        assert_eq!(tombstone.effective_slot(), 60);
1947    }
1948
1949    struct TestForkGraph {
1950        relation: BlockRelation,
1951    }
1952    impl ForkGraph for TestForkGraph {
1953        fn relationship(&self, _a: Slot, _b: Slot) -> BlockRelation {
1954            self.relation
1955        }
1956    }
1957
1958    #[test]
1959    fn test_prune_empty() {
1960        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1961        let fork_graph = Arc::new(RwLock::new(TestForkGraph {
1962            relation: BlockRelation::Unrelated,
1963        }));
1964
1965        cache.set_fork_graph(Arc::downgrade(&fork_graph));
1966
1967        cache.prune(0, None, &fork_graph.read().unwrap());
1968        assert!(cache.get_flattened_entries_for_tests().is_empty());
1969
1970        cache.prune(10, None, &fork_graph.read().unwrap());
1971        assert!(cache.get_flattened_entries_for_tests().is_empty());
1972
1973        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1974        let fork_graph = Arc::new(RwLock::new(TestForkGraph {
1975            relation: BlockRelation::Ancestor,
1976        }));
1977
1978        cache.set_fork_graph(Arc::downgrade(&fork_graph));
1979
1980        cache.prune(0, None, &fork_graph.read().unwrap());
1981        assert!(cache.get_flattened_entries_for_tests().is_empty());
1982
1983        cache.prune(10, None, &fork_graph.read().unwrap());
1984        assert!(cache.get_flattened_entries_for_tests().is_empty());
1985
1986        let mut cache = ProgramCache::<TestForkGraph>::new(0);
1987        let fork_graph = Arc::new(RwLock::new(TestForkGraph {
1988            relation: BlockRelation::Descendant,
1989        }));
1990
1991        cache.set_fork_graph(Arc::downgrade(&fork_graph));
1992
1993        cache.prune(0, None, &fork_graph.read().unwrap());
1994        assert!(cache.get_flattened_entries_for_tests().is_empty());
1995
1996        cache.prune(10, None, &fork_graph.read().unwrap());
1997        assert!(cache.get_flattened_entries_for_tests().is_empty());
1998
1999        let mut cache = ProgramCache::<TestForkGraph>::new(0);
2000        let fork_graph = Arc::new(RwLock::new(TestForkGraph {
2001            relation: BlockRelation::Unknown,
2002        }));
2003        cache.set_fork_graph(Arc::downgrade(&fork_graph));
2004
2005        cache.prune(0, None, &fork_graph.read().unwrap());
2006        assert!(cache.get_flattened_entries_for_tests().is_empty());
2007
2008        cache.prune(10, None, &fork_graph.read().unwrap());
2009        assert!(cache.get_flattened_entries_for_tests().is_empty());
2010    }
2011
2012    #[test]
2013    fn test_prune_removes_programs_with_no_entries() {
2014        let (mut cache, fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Unknown);
2015        let env = get_mock_program_runtime_environment();
2016        let emptied = Pubkey::new_unique();
2017        cache.assign_program(
2018            &env,
2019            emptied,
2020            100,
2021            new_test_entry_with_owner(
2022                100,
2023                ProgramCacheEntryOwner::LoaderV3,
2024                new_loaded_entry(env.clone()),
2025            ),
2026        );
2027
2028        // The entry is dropped, and the key goes with it.
2029        cache.prune(50, None, &fork_graph.read().unwrap());
2030        match &cache.index {
2031            IndexImplementation::V1 { entries, .. } => assert!(!entries.contains_key(&emptied)),
2032        }
2033        assert_eq!(cache.stats.empty_entries.load(Ordering::Relaxed), 1);
2034        assert_eq!(cache.stats.prunes_orphan.load(Ordering::Relaxed), 1);
2035    }
2036
2037    #[test]
2038    fn test_prune_across_the_root() {
2039        // Fork graph created for the test
2040        //                30 - 50 - 70
2041        //
2042        // One program with entries on both sides of the new root.
2043        // Both the ancestor and the descendant are kept.
2044        let mut cache = ProgramCache::<TestForkGraphSpecific>::new(0);
2045        let mut fork_graph = TestForkGraphSpecific::default();
2046        fork_graph.insert_fork(&[30, 50, 70]);
2047        let fork_graph = Arc::new(RwLock::new(fork_graph));
2048        cache.set_fork_graph(Arc::downgrade(&fork_graph));
2049
2050        let env = get_mock_program_runtime_environment();
2051        let program_id = Pubkey::new_unique();
2052        let below = new_test_entry_with_owner(
2053            30,
2054            ProgramCacheEntryOwner::LoaderV3,
2055            new_loaded_entry(env.clone()),
2056        );
2057        let above = new_test_entry_with_owner(
2058            70,
2059            ProgramCacheEntryOwner::LoaderV3,
2060            new_loaded_entry(env.clone()),
2061        );
2062        cache.assign_program(&env, program_id, 30, Arc::clone(&below));
2063        cache.assign_program(&env, program_id, 70, Arc::clone(&above));
2064
2065        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2066        assert_eq!(slot_versions.len(), 2);
2067        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &below));
2068        assert!(Arc::ptr_eq(slot_versions.get(1).unwrap(), &above));
2069
2070        cache.prune(50, None, &fork_graph.read().unwrap());
2071
2072        // Both survive, and in the order they were in.
2073        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2074        assert_eq!(slot_versions.len(), 2);
2075        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &below));
2076        assert!(Arc::ptr_eq(slot_versions.get(1).unwrap(), &above));
2077    }
2078
2079    #[test]
2080    fn test_prune_across_the_root_ancestors() {
2081        // Fork graph created for the test
2082        //                10 - 20 - 30 - 50 - 70
2083        //
2084        // Same as above, with more entries deployed before the new root.
2085        // Only the newest of those is the first ancestor.
2086        let mut cache = ProgramCache::<TestForkGraphSpecific>::new(0);
2087        let mut fork_graph = TestForkGraphSpecific::default();
2088        fork_graph.insert_fork(&[10, 20, 30, 50, 70]);
2089        let fork_graph = Arc::new(RwLock::new(fork_graph));
2090        cache.set_fork_graph(Arc::downgrade(&fork_graph));
2091
2092        let env = get_mock_program_runtime_environment();
2093        let program_id = Pubkey::new_unique();
2094        let oldest = new_test_entry_with_owner(
2095            10,
2096            ProgramCacheEntryOwner::LoaderV3,
2097            new_loaded_entry(env.clone()),
2098        );
2099        let older = new_test_entry_with_owner(
2100            20,
2101            ProgramCacheEntryOwner::LoaderV3,
2102            new_loaded_entry(env.clone()),
2103        );
2104        let below = new_test_entry_with_owner(
2105            30,
2106            ProgramCacheEntryOwner::LoaderV3,
2107            new_loaded_entry(env.clone()),
2108        );
2109        let above = new_test_entry_with_owner(
2110            70,
2111            ProgramCacheEntryOwner::LoaderV3,
2112            new_loaded_entry(env.clone()),
2113        );
2114        cache.assign_program(&env, program_id, 10, Arc::clone(&oldest));
2115        cache.assign_program(&env, program_id, 20, Arc::clone(&older));
2116        cache.assign_program(&env, program_id, 30, Arc::clone(&below));
2117        cache.assign_program(&env, program_id, 70, Arc::clone(&above));
2118
2119        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2120        assert_eq!(slot_versions.len(), 4);
2121        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &oldest));
2122        assert!(Arc::ptr_eq(slot_versions.get(1).unwrap(), &older));
2123        assert!(Arc::ptr_eq(slot_versions.get(2).unwrap(), &below));
2124        assert!(Arc::ptr_eq(slot_versions.get(3).unwrap(), &above));
2125
2126        cache.prune(50, None, &fork_graph.read().unwrap());
2127
2128        // The entries at 10 and 20 have been redeployed over by the one at 30,
2129        // so they go, and nothing was on another environment to exempt them.
2130        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2131        assert_eq!(slot_versions.len(), 2);
2132        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &below));
2133        assert!(Arc::ptr_eq(slot_versions.get(1).unwrap(), &above));
2134        assert_eq!(cache.stats.prunes_orphan.load(Ordering::Relaxed), 2);
2135    }
2136
2137    #[test]
2138    fn test_prune_entry_older_than_root() {
2139        // Fork graph created for the test
2140        //                5  ?  10  ?  20
2141        //                ^     ^^     ^^
2142        //                |     |      the new root
2143        //                |     the old root
2144        //                the entry is deployed here
2145        //
2146        // The graph answers `BlockRelation::Unknown` for every pair, so
2147        // nothing here is related to anything else.
2148        //
2149        // Here we want to test that an entry the graph cannot place on the
2150        // querying fork is kept anyway, purely because it was deployed before
2151        // the root. Therefore, nothing is pruned and no orphan is counted.
2152        let (mut cache, fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Unknown);
2153        let env = get_mock_program_runtime_environment();
2154        let program_id = Pubkey::new_unique();
2155        let entry = new_test_entry_with_owner(
2156            5,
2157            ProgramCacheEntryOwner::LoaderV3,
2158            new_loaded_entry(env.clone()),
2159        );
2160        cache.assign_program(&env, program_id, 5, Arc::clone(&entry));
2161        cache.latest_root_slot = 10;
2162
2163        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2164        assert_eq!(slot_versions.len(), 1);
2165        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &entry));
2166
2167        cache.prune(20, None, &fork_graph.read().unwrap());
2168
2169        // `Unknown` means the graph cannot say the entry belongs to this fork,
2170        // but the `deployment_slot <= latest_root_slot` fallback keeps it
2171        // regardless.
2172        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2173        assert_eq!(slot_versions.len(), 1);
2174        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &entry));
2175        assert_eq!(cache.stats.prunes_orphan.load(Ordering::Relaxed), 0);
2176    }
2177
2178    #[test]
2179    fn test_prune_orphan_newer_than_root() {
2180        // Fork graph created for the test
2181        //                50  ?  100
2182        //                ^^     ^^^
2183        //                |      the entry is deployed here
2184        //                the new root
2185        //
2186        // Here we want to test the other side of the root from the test above:
2187        // an entry deployed past it, which the graph cannot place either.
2188        // Therefore it is pruned, where the one behind the root was kept.
2189        let (mut cache, fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Unknown);
2190        let env = get_mock_program_runtime_environment();
2191        let program_id = Pubkey::new_unique();
2192        let orphan = new_test_entry_with_owner(
2193            100,
2194            ProgramCacheEntryOwner::LoaderV3,
2195            new_loaded_entry(env.clone()),
2196        );
2197        cache.assign_program(&env, program_id, 100, Arc::clone(&orphan));
2198
2199        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2200        assert_eq!(slot_versions.len(), 1);
2201        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &orphan));
2202
2203        cache.prune(50, None, &fork_graph.read().unwrap());
2204
2205        // Past the root there is no `deployment_slot <= latest_root_slot`
2206        // fallback to keep it, so the entry the graph cannot place goes.
2207        assert!(cache.get_slot_versions_for_tests(&program_id).is_empty());
2208        assert_eq!(cache.stats.prunes_orphan.load(Ordering::Relaxed), 1);
2209    }
2210
2211    #[test]
2212    fn test_prune_tombstones() {
2213        let env = get_mock_program_runtime_environment();
2214        let fork_graph = Arc::new(RwLock::new(TestForkGraph {
2215            relation: BlockRelation::Ancestor,
2216        }));
2217
2218        let program1 = Pubkey::new_unique();
2219        let entries = [
2220            Arc::new(ProgramCacheEntry::new_unloaded(
2221                20,
2222                ProgramCacheEntryOwner::LoaderV3,
2223                ProgramRuntimeEnvironment::clone(&env),
2224            )),
2225            Arc::new(ProgramCacheEntry::new_closed_tombstone(
2226                20,
2227                ProgramCacheEntryOwner::LoaderV3,
2228            )),
2229            Arc::new(ProgramCacheEntry::new_failed_verification_tombstone(
2230                20,
2231                ProgramCacheEntryOwner::LoaderV3,
2232                ProgramRuntimeEnvironment::clone(&env),
2233            )),
2234        ];
2235        for entry in &entries {
2236            let mut cache = ProgramCache::<TestForkGraph>::new(0);
2237            cache.set_fork_graph(Arc::downgrade(&fork_graph));
2238            // Test that multiple entries prevent pruning
2239            cache.assign_program(&env, program1, 10, new_test_entry(10));
2240            cache.assign_program(&env, program1, entry.deployment_slot, Arc::clone(entry));
2241            cache.prune(
2242                MAX_TOMBSTONE_AGE_IN_SLOTS,
2243                None,
2244                &fork_graph.read().unwrap(),
2245            );
2246            let slot_versions = cache.get_slot_versions_for_tests(&program1);
2247            assert_eq!(slot_versions, std::slice::from_ref(entry));
2248            // Test that latest_access_slot prevents pruning
2249            cache.prune(
2250                MAX_TOMBSTONE_AGE_IN_SLOTS
2251                    .saturating_add(entry.latest_access_slot.load(Ordering::Relaxed)),
2252                None,
2253                &fork_graph.read().unwrap(),
2254            );
2255            let slot_versions = cache.get_slot_versions_for_tests(&program1);
2256            assert_eq!(slot_versions, std::slice::from_ref(entry));
2257            // Test that exeeding latest_access_slot + MAX_TOMBSTONE_AGE_IN_SLOTS prunes
2258            cache.prune(
2259                MAX_TOMBSTONE_AGE_IN_SLOTS
2260                    .saturating_add(entry.latest_access_slot.load(Ordering::Relaxed))
2261                    .saturating_add(1),
2262                None,
2263                &fork_graph.read().unwrap(),
2264            );
2265            assert!(cache.get_flattened_entries_for_tests().is_empty());
2266        }
2267    }
2268
2269    #[test]
2270    fn test_prune_tombstone_first_ancestor_takes_the_rest() {
2271        // Fork graph created for the test
2272        //                50 - 60 - 100 - 200
2273        //                          ^^^
2274        //                          the program is closed here
2275        //
2276        // Here we want to test that the pruning step correctly sees that a
2277        // closure - a `Closed` tombstone - is being rooted. Therefore, nothing
2278        // else should be retained in the cache for this entry.
2279        let (mut cache, fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
2280        let env = get_mock_program_runtime_environment();
2281        let other_env = ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock());
2282        let program_id = Pubkey::new_unique();
2283        let on_other_env = new_test_entry_with_owner(
2284            50,
2285            ProgramCacheEntryOwner::LoaderV3,
2286            new_loaded_entry(other_env.clone()),
2287        );
2288        let on_env = new_test_entry_with_owner(
2289            60,
2290            ProgramCacheEntryOwner::LoaderV3,
2291            new_loaded_entry(env.clone()),
2292        );
2293        let closed = new_test_entry_with_owner(
2294            100,
2295            ProgramCacheEntryOwner::LoaderV3,
2296            new_closed_entry(env.clone()),
2297        );
2298        cache.assign_program(&other_env, program_id, 50, Arc::clone(&on_other_env));
2299        cache.assign_program(&env, program_id, 60, Arc::clone(&on_env));
2300        cache.assign_program(&env, program_id, 100, Arc::clone(&closed));
2301
2302        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2303        assert_eq!(slot_versions.len(), 3);
2304        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &on_other_env));
2305        assert!(Arc::ptr_eq(slot_versions.get(1).unwrap(), &on_env));
2306        assert!(Arc::ptr_eq(slot_versions.get(2).unwrap(), &closed));
2307
2308        cache.prune(200, None, &fork_graph.read().unwrap());
2309
2310        // The newest entry deployed before the root is the tombstone, so
2311        // `first_ancestor_env` is `None`. The env-based exemption for entries
2312        // behind the tombstone is unreachable, so they all get pruned.
2313        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2314        assert_eq!(slot_versions.len(), 1);
2315        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &closed));
2316        assert_eq!(cache.stats.prunes_orphan.load(Ordering::Relaxed), 2);
2317    }
2318
2319    #[test]
2320    fn test_prune_tombstone_newer_than_root_keeps_the_rest() {
2321        // Fork graph created for the test
2322        //                50 - 60 - 100 - 101
2323        //                                ^^^
2324        //                                the program is closed here
2325        //
2326        // Here we want to test that the pruning step does not see a closure -
2327        // a `Closed` tombstone - being rooted, since it lands after the new
2328        // root. Therefore, everything else should be retained in the cache
2329        // for this program.
2330        let mut cache = ProgramCache::<TestForkGraphSpecific>::new(0);
2331        let mut fork_graph = TestForkGraphSpecific::default();
2332        fork_graph.insert_fork(&[50, 60, 100, 101]);
2333        let fork_graph = Arc::new(RwLock::new(fork_graph));
2334        cache.set_fork_graph(Arc::downgrade(&fork_graph));
2335
2336        let env = get_mock_program_runtime_environment();
2337        let other_env = ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock());
2338        let program_id = Pubkey::new_unique();
2339        let on_other_env = new_test_entry_with_owner(
2340            50,
2341            ProgramCacheEntryOwner::LoaderV3,
2342            new_loaded_entry(other_env.clone()),
2343        );
2344        let on_env = new_test_entry_with_owner(
2345            60,
2346            ProgramCacheEntryOwner::LoaderV3,
2347            new_loaded_entry(env.clone()),
2348        );
2349        let closed = new_test_entry_with_owner(
2350            101,
2351            ProgramCacheEntryOwner::LoaderV3,
2352            new_closed_entry(env.clone()),
2353        );
2354        cache.assign_program(&other_env, program_id, 50, Arc::clone(&on_other_env));
2355        cache.assign_program(&env, program_id, 60, Arc::clone(&on_env));
2356        cache.assign_program(&env, program_id, 101, Arc::clone(&closed));
2357
2358        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2359        assert_eq!(slot_versions.len(), 3);
2360        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &on_other_env));
2361        assert!(Arc::ptr_eq(slot_versions.get(1).unwrap(), &on_env));
2362        assert!(Arc::ptr_eq(slot_versions.get(2).unwrap(), &closed));
2363
2364        cache.prune(100, None, &fork_graph.read().unwrap());
2365
2366        // The tombstone is kept as a descendant of the root, and never reaches
2367        // the arm which sets `first_ancestor_env`. So the entry at 60 is the
2368        // first ancestor, the one at 50 is exempt for being on another
2369        // environment, and nothing is pruned.
2370        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2371        assert_eq!(slot_versions.len(), 3);
2372        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &on_other_env));
2373        assert!(Arc::ptr_eq(slot_versions.get(1).unwrap(), &on_env));
2374        assert!(Arc::ptr_eq(slot_versions.get(2).unwrap(), &closed));
2375        assert_eq!(cache.stats.prunes_orphan.load(Ordering::Relaxed), 0);
2376    }
2377
2378    #[test]
2379    fn test_prune_with_two_environments_before_epoch_boundary() {
2380        let mut cache = ProgramCache::<TestForkGraph>::new(0);
2381        let env = get_mock_program_runtime_environment();
2382        let new_env = ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock());
2383        let fork_graph = Arc::new(RwLock::new(TestForkGraph {
2384            relation: BlockRelation::Ancestor,
2385        }));
2386        cache.set_fork_graph(Arc::downgrade(&fork_graph));
2387
2388        let program1 = Pubkey::new_unique();
2389        cache.assign_program(&env, program1, 10, new_test_entry(10));
2390        let updated_program = Arc::new(ProgramCacheEntry {
2391            program: new_loaded_entry(new_env.clone()),
2392            deployment_slot: 20,
2393            ..Default::default()
2394        });
2395        cache.assign_program(&env, program1, 20, updated_program.clone());
2396
2397        // Test that there are 2 entries for the program
2398        assert_eq!(cache.get_slot_versions_for_tests(&program1).len(), 2);
2399
2400        cache.prune(21, None, &fork_graph.read().unwrap());
2401
2402        // Test that prune didn't remove the entry, since environments are different.
2403        assert_eq!(cache.get_slot_versions_for_tests(&program1).len(), 2);
2404    }
2405
2406    #[test]
2407    fn test_prune_with_two_environments_after_epoch_boundary() {
2408        let mut cache = ProgramCache::<TestForkGraph>::new(0);
2409        let env = get_mock_program_runtime_environment();
2410        let new_env = ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock());
2411        let fork_graph = Arc::new(RwLock::new(TestForkGraph {
2412            relation: BlockRelation::Ancestor,
2413        }));
2414        cache.set_fork_graph(Arc::downgrade(&fork_graph));
2415        let program1 = Pubkey::new_unique();
2416
2417        let old_program_old_env = Arc::new(ProgramCacheEntry {
2418            program: new_loaded_entry(env.clone()),
2419            deployment_slot: 10,
2420            ..Default::default()
2421        });
2422        let old_program_new_env = Arc::new(ProgramCacheEntry {
2423            program: new_loaded_entry(new_env.clone()),
2424            deployment_slot: 10,
2425            ..Default::default()
2426        });
2427        let new_program_old_env = Arc::new(ProgramCacheEntry {
2428            program: new_loaded_entry(env.clone()),
2429            deployment_slot: 20,
2430            ..Default::default()
2431        });
2432        cache.assign_program(&env, program1, 10, old_program_old_env.clone());
2433        cache.assign_program(&env, program1, 10, old_program_new_env.clone());
2434        cache.assign_program(&env, program1, 20, new_program_old_env.clone());
2435        let slot_versions = cache.get_slot_versions_for_tests(&program1);
2436        assert_eq!(
2437            &slot_versions,
2438            &[
2439                old_program_new_env.clone(),
2440                old_program_old_env.clone(),
2441                new_program_old_env.clone(),
2442            ]
2443        );
2444
2445        cache.prune(21, Some(new_env.clone()), &fork_graph.read().unwrap());
2446        let slot_versions = cache.get_slot_versions_for_tests(&program1);
2447        assert_eq!(&slot_versions, &[old_program_new_env]);
2448        assert!(matches!(
2449            &slot_versions.first().unwrap().program,
2450            ProgramCacheEntryType::Loaded(_)
2451        ));
2452    }
2453
2454    #[test_matrix(
2455        (
2456            new_closed_entry,
2457            new_builtin_entry,
2458            new_failed_verification_entry,
2459            new_unloaded_entry,
2460            new_loaded_entry,
2461        ),
2462        (false, true)
2463    )]
2464    fn test_prune_environment_sweep_by_entry_type(
2465        new_program: fn(ProgramRuntimeEnvironment) -> ProgramCacheEntryType,
2466        on_new_environment: bool,
2467    ) {
2468        // Fork graph created for the test
2469        //                40 - 50
2470        //
2471        // The entry is deployed after the root the sweep runs at, so the fork
2472        // graph keeps it and the environment decides the rest.
2473        //
2474        // Here we want to test which entry types the sweep can reach.
2475        // Therefore only one which carries an environment, and not the
2476        // incoming one, is taken - and taken outright, rather than unloaded.
2477        let mut cache = ProgramCache::<TestForkGraphSpecific>::new(0);
2478        let mut fork_graph = TestForkGraphSpecific::default();
2479        fork_graph.insert_fork(&[40, 50]);
2480        let fork_graph = Arc::new(RwLock::new(fork_graph));
2481        cache.set_fork_graph(Arc::downgrade(&fork_graph));
2482
2483        let env = get_mock_program_runtime_environment();
2484        let new_env = ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock());
2485        let entry_env = if on_new_environment {
2486            new_env.clone()
2487        } else {
2488            env.clone()
2489        };
2490        let program_id = Pubkey::new_unique();
2491        let entry = new_test_entry_with_owner(
2492            50,
2493            ProgramCacheEntryOwner::LoaderV3,
2494            new_program(entry_env.clone()),
2495        );
2496        let carries_an_environment = entry.program.get_environment().is_some();
2497        cache.assign_program(&entry_env, program_id, 50, Arc::clone(&entry));
2498
2499        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2500        assert_eq!(slot_versions.len(), 1);
2501        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &entry));
2502
2503        cache.prune(40, Some(new_env.clone()), &fork_graph.read().unwrap());
2504
2505        // Only an entry which carries an environment, and one which is not
2506        // the incoming one, is swept - and it is removed, not unloaded.
2507        let swept = carries_an_environment && !on_new_environment;
2508        assert_eq!(
2509            cache.stats.prunes_environment.load(Ordering::Relaxed),
2510            u64::from(swept)
2511        );
2512        if swept {
2513            assert!(cache.get_slot_versions_for_tests(&program_id).is_empty());
2514        } else {
2515            let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2516            assert_eq!(slot_versions.len(), 1);
2517            assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &entry));
2518        }
2519    }
2520
2521    #[test]
2522    fn test_prune_environment_sweep_keeps_tombstones() {
2523        // Fork graph created for the test
2524        //                0 - 40 - 50 - 60 - 70 - 100
2525        //
2526        // Every entry is deployed after the root the sweep runs at, so `prune`
2527        // keeps all of them on the fork graph alone and the environment is the
2528        // only thing which takes any of them out.
2529        //
2530        // Here we want to test that the sweep can only take an entry which
2531        // carries an environment. Therefore the two built for the outgoing one
2532        // go, and the tombstone survives because it has none to compare
2533        // against.
2534        let mut cache = ProgramCache::<TestForkGraphSpecific>::new(0);
2535        let mut fork_graph = TestForkGraphSpecific::default();
2536        fork_graph.insert_fork(&[0, 40, 50, 60, 70, 100]);
2537        let fork_graph = Arc::new(RwLock::new(fork_graph));
2538        cache.set_fork_graph(Arc::downgrade(&fork_graph));
2539        let env = get_mock_program_runtime_environment();
2540        let new_env = ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock());
2541        let program_id = Pubkey::new_unique();
2542        let closed = new_test_entry_with_owner(
2543            50,
2544            ProgramCacheEntryOwner::LoaderV3,
2545            new_closed_entry(env.clone()),
2546        );
2547        let failed_verification = new_test_entry_with_owner(
2548            60,
2549            ProgramCacheEntryOwner::LoaderV3,
2550            // `FailedVerification` carries an environment, so it gets pruned.
2551            new_failed_verification_entry(env.clone()),
2552        );
2553        let loaded = new_test_entry_with_owner(
2554            70,
2555            ProgramCacheEntryOwner::LoaderV3,
2556            new_loaded_entry(env.clone()),
2557        );
2558        cache.assign_program(&env, program_id, 50, Arc::clone(&closed));
2559        cache.assign_program(&env, program_id, 60, Arc::clone(&failed_verification));
2560        cache.assign_program(&env, program_id, 70, Arc::clone(&loaded));
2561
2562        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2563        assert_eq!(slot_versions.len(), 3);
2564        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &closed));
2565        assert!(Arc::ptr_eq(
2566            slot_versions.get(1).unwrap(),
2567            &failed_verification
2568        ));
2569        assert!(Arc::ptr_eq(slot_versions.get(2).unwrap(), &loaded));
2570
2571        // The epoch boundary. Both entries which carry an environment are on
2572        // the outgoing one and are swept away.
2573        cache.prune(40, Some(new_env.clone()), &fork_graph.read().unwrap());
2574        assert_eq!(cache.stats.prunes_environment.load(Ordering::Relaxed), 2);
2575        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
2576        assert_eq!(slot_versions.len(), 1);
2577        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &closed));
2578
2579        // The `Closed` tombstone survives because it carries no environment.
2580        let mut search_for = vec![ProgramToLoad {
2581            program_id: &program_id,
2582            loader: ProgramCacheEntryOwner::LoaderV3,
2583            deployment_slot: 50,
2584        }];
2585        let mut extracted = ProgramCacheForTxBatch::new(100);
2586        cache.extract(&mut search_for, &mut extracted, &new_env, true, true);
2587        assert!(search_for.is_empty());
2588        assert!(Arc::ptr_eq(
2589            extracted.entries.get(&program_id).unwrap(),
2590            &closed
2591        ));
2592
2593        // Try the same search again with the outgoing environment. That would
2594        // not happen in production, since the sweep has just rooted the new
2595        // one, but exercise it anyway.
2596        let mut search_for = vec![ProgramToLoad {
2597            program_id: &program_id,
2598            loader: ProgramCacheEntryOwner::LoaderV3,
2599            deployment_slot: 50,
2600        }];
2601        let mut extracted = ProgramCacheForTxBatch::new(100);
2602        cache.extract(&mut search_for, &mut extracted, &env, true, true);
2603        assert!(search_for.is_empty());
2604        assert!(Arc::ptr_eq(
2605            extracted.entries.get(&program_id).unwrap(),
2606            &closed
2607        ));
2608    }
2609
2610    #[test]
2611    #[should_panic(expected = "self.latest_root_slot <= new_root_slot")]
2612    fn test_prune_backwards_panics() {
2613        let (mut cache, fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
2614        cache.latest_root_slot = 100;
2615
2616        // The `debug_assert!` guarding this runs after the pruning logic,
2617        // not before it.
2618        cache.prune(50, None, &fork_graph.read().unwrap());
2619    }
2620
2621    #[derive(Default)]
2622    struct TestForkGraphSpecific {
2623        forks: Vec<Vec<Slot>>,
2624    }
2625
2626    impl TestForkGraphSpecific {
2627        fn insert_fork(&mut self, fork: &[Slot]) {
2628            let mut fork = fork.to_vec();
2629            fork.sort();
2630            self.forks.push(fork)
2631        }
2632    }
2633
2634    impl ForkGraph for TestForkGraphSpecific {
2635        fn relationship(&self, a: Slot, b: Slot) -> BlockRelation {
2636            match self.forks.iter().try_for_each(|fork| {
2637                let relation = fork
2638                    .iter()
2639                    .position(|x| *x == a)
2640                    .and_then(|a_pos| {
2641                        fork.iter().position(|x| *x == b).and_then(|b_pos| {
2642                            (a_pos == b_pos)
2643                                .then_some(BlockRelation::Equal)
2644                                .or_else(|| (a_pos < b_pos).then_some(BlockRelation::Ancestor))
2645                                .or(Some(BlockRelation::Descendant))
2646                        })
2647                    })
2648                    .unwrap_or(BlockRelation::Unrelated);
2649
2650                if relation != BlockRelation::Unrelated {
2651                    return ControlFlow::Break(relation);
2652                }
2653
2654                ControlFlow::Continue(())
2655            }) {
2656                ControlFlow::Break(relation) => relation,
2657                _ => BlockRelation::Unrelated,
2658            }
2659        }
2660    }
2661
2662    fn get_entries_to_load<'a>(
2663        cache: &ProgramCache<TestForkGraphSpecific>,
2664        loading_slot: Slot,
2665        keys: &'a [Pubkey],
2666    ) -> Vec<ProgramToLoad<'a>> {
2667        let fork_graph = cache.fork_graph.as_ref().unwrap().upgrade().unwrap();
2668        let locked_fork_graph = fork_graph.read().unwrap();
2669        let entries = cache.get_flattened_entries_for_tests();
2670        keys.iter()
2671            .filter_map(|key| {
2672                entries
2673                    .iter()
2674                    .rev()
2675                    .find(|(program_id, entry)| {
2676                        program_id == key
2677                            && matches!(
2678                                locked_fork_graph.relationship(entry.deployment_slot, loading_slot),
2679                                BlockRelation::Equal | BlockRelation::Ancestor,
2680                            )
2681                    })
2682                    .map(|(_program_id, entry)| ProgramToLoad {
2683                        program_id: key,
2684                        loader: entry.account_owner,
2685                        deployment_slot: entry.deployment_slot,
2686                    })
2687            })
2688            .collect()
2689    }
2690
2691    fn match_slot(
2692        extracted: &ProgramCacheForTxBatch,
2693        program: &Pubkey,
2694        deployment_slot: Slot,
2695        working_slot: Slot,
2696    ) -> bool {
2697        assert_eq!(extracted.slot, working_slot);
2698        extracted
2699            .entries
2700            .get(program)
2701            .map(|entry| entry.deployment_slot == deployment_slot)
2702            .unwrap_or(false)
2703    }
2704
2705    fn match_missing(
2706        missing: &[ProgramToLoad],
2707        program_id: &Pubkey,
2708        expected_result: bool,
2709    ) -> bool {
2710        missing.iter().any(|entry| entry.program_id == program_id) == expected_result
2711    }
2712
2713    #[test]
2714    fn test_fork_extract_and_prune() {
2715        let mut cache = ProgramCache::<TestForkGraphSpecific>::new(0);
2716        let env = get_mock_program_runtime_environment();
2717
2718        // Fork graph created for the test
2719        //                   0
2720        //                 /   \
2721        //                10    5
2722        //                |     |
2723        //                20    11
2724        //                |     | \
2725        //                22   15  25
2726        //                      |   |
2727        //                     16  27
2728        //                      |
2729        //                     19
2730        //                      |
2731        //                     23
2732
2733        let mut fork_graph = TestForkGraphSpecific::default();
2734        fork_graph.insert_fork(&[0, 10, 20, 22]);
2735        fork_graph.insert_fork(&[0, 5, 11, 15, 16, 18, 19, 21, 23]);
2736        fork_graph.insert_fork(&[0, 5, 11, 25, 27]);
2737
2738        let fork_graph = Arc::new(RwLock::new(fork_graph));
2739        cache.set_fork_graph(Arc::downgrade(&fork_graph));
2740
2741        let program1 = Pubkey::new_unique();
2742        cache.assign_program(&env, program1, 0, new_test_entry(0));
2743        cache.assign_program(&env, program1, 10, new_test_entry(10));
2744        cache.assign_program(&env, program1, 20, new_test_entry(20));
2745
2746        let program2 = Pubkey::new_unique();
2747        cache.assign_program(&env, program2, 5, new_test_entry(5));
2748        cache.assign_program(&env, program2, 11, new_test_entry(11));
2749
2750        let program3 = Pubkey::new_unique();
2751        cache.assign_program(&env, program3, 25, new_test_entry(25));
2752
2753        let program4 = Pubkey::new_unique();
2754        cache.assign_program(&env, program4, 0, new_test_entry(0));
2755        cache.assign_program(&env, program4, 5, new_test_entry(5));
2756        // The following is a special case, where effective slot is 3 slots in the future
2757        cache.assign_program(&env, program4, 15, new_test_entry(15));
2758
2759        // Current fork graph
2760        //                   0
2761        //                 /   \
2762        //                10    5
2763        //                |     |
2764        //                20    11
2765        //                |     | \
2766        //                22   15  25
2767        //                      |   |
2768        //                     16  27
2769        //                      |
2770        //                     19
2771        //                      |
2772        //                     23
2773
2774        // Testing fork 0 - 10 - 20 - 22 with current slot at 22
2775        let keys = &[program1, program2, program3, program4];
2776        let mut missing = get_entries_to_load(&cache, 22, keys);
2777        assert!(match_missing(&missing, &program2, false));
2778        assert!(match_missing(&missing, &program3, false));
2779        let mut extracted = ProgramCacheForTxBatch::new(22);
2780        cache.extract(&mut missing, &mut extracted, &env, true, true);
2781        assert!(match_slot(&extracted, &program1, 20, 22));
2782        assert!(match_slot(&extracted, &program4, 0, 22));
2783
2784        // Testing fork 0 - 5 - 11 - 15 - 16 with current slot at 15
2785        let mut missing = get_entries_to_load(&cache, 15, keys);
2786        assert!(match_missing(&missing, &program3, false));
2787        let mut extracted = ProgramCacheForTxBatch::new(15);
2788        cache.extract(&mut missing, &mut extracted, &env, true, true);
2789        assert!(match_slot(&extracted, &program1, 0, 15));
2790        assert!(match_slot(&extracted, &program2, 11, 15));
2791        // The effective slot of program4 deployed in slot 15 is 19. So it should not be usable in slot 16.
2792        // A delay visibility tombstone should be returned here.
2793        let tombstone = extracted
2794            .find(&program4)
2795            .expect("Failed to find the tombstone");
2796        assert_matches!(tombstone.program, ProgramCacheEntryType::DelayVisibility);
2797        assert_eq!(tombstone.deployment_slot, 15);
2798
2799        // Testing the same fork above, but current slot is now 18 (equal to effective slot of program4).
2800        let mut missing = get_entries_to_load(&cache, 18, keys);
2801        assert!(match_missing(&missing, &program3, false));
2802        let mut extracted = ProgramCacheForTxBatch::new(18);
2803        cache.extract(&mut missing, &mut extracted, &env, true, true);
2804        assert!(match_slot(&extracted, &program1, 0, 18));
2805        assert!(match_slot(&extracted, &program2, 11, 18));
2806        // The effective slot of program4 deployed in slot 15 is 18. So it should be usable in slot 18.
2807        assert!(match_slot(&extracted, &program4, 15, 18));
2808
2809        // Testing the same fork above, but current slot is now 23 (future slot than effective slot of program4).
2810        let mut missing = get_entries_to_load(&cache, 23, keys);
2811        assert!(match_missing(&missing, &program3, false));
2812        let mut extracted = ProgramCacheForTxBatch::new(23);
2813        cache.extract(&mut missing, &mut extracted, &env, true, true);
2814        assert!(match_slot(&extracted, &program1, 0, 23));
2815        assert!(match_slot(&extracted, &program2, 11, 23));
2816        // The effective slot of program4 deployed in slot 15 is 19. So it should be usable in slot 23.
2817        assert!(match_slot(&extracted, &program4, 15, 23));
2818
2819        // Testing fork 0 - 5 - 11 - 15 - 16 with current slot at 11
2820        let mut missing = get_entries_to_load(&cache, 11, keys);
2821        assert!(match_missing(&missing, &program3, false));
2822        let mut extracted = ProgramCacheForTxBatch::new(11);
2823        cache.extract(&mut missing, &mut extracted, &env, true, true);
2824        assert!(match_slot(&extracted, &program1, 0, 11));
2825        // program2 was updated at slot 11, but is not effective till slot 12. The result should contain a tombstone.
2826        let tombstone = extracted
2827            .find(&program2)
2828            .expect("Failed to find the tombstone");
2829        assert_matches!(tombstone.program, ProgramCacheEntryType::DelayVisibility);
2830        assert_eq!(tombstone.deployment_slot, 11);
2831        assert!(match_slot(&extracted, &program4, 5, 11));
2832
2833        cache.prune(5, None, &fork_graph.read().unwrap());
2834
2835        // Fork graph after pruning
2836        //                   0
2837        //                   |
2838        //                   5
2839        //                   |
2840        //                   11
2841        //                   | \
2842        //                  15  25
2843        //                   |   |
2844        //                  16  27
2845        //                   |
2846        //                  19
2847        //                   |
2848        //                  23
2849
2850        // Testing fork 11 - 15 - 16- 19 - 22 with root at 5 and current slot at 22
2851        let mut missing = get_entries_to_load(&cache, 21, keys);
2852        assert!(match_missing(&missing, &program3, false));
2853        let mut extracted = ProgramCacheForTxBatch::new(21);
2854        cache.extract(&mut missing, &mut extracted, &env, true, true);
2855        // Since the fork was pruned, we should not find the entry deployed at slot 20.
2856        assert!(match_slot(&extracted, &program1, 0, 21));
2857        assert!(match_slot(&extracted, &program2, 11, 21));
2858        assert!(match_slot(&extracted, &program4, 15, 21));
2859
2860        // Testing fork 0 - 5 - 11 - 25 - 27 with current slot at 27
2861        let mut missing = get_entries_to_load(&cache, 27, keys);
2862        let mut extracted = ProgramCacheForTxBatch::new(27);
2863        cache.extract(&mut missing, &mut extracted, &env, true, true);
2864        assert!(match_slot(&extracted, &program1, 0, 27));
2865        assert!(match_slot(&extracted, &program2, 11, 27));
2866        assert!(match_slot(&extracted, &program3, 25, 27));
2867        assert!(match_slot(&extracted, &program4, 5, 27));
2868
2869        cache.prune(15, None, &fork_graph.read().unwrap());
2870
2871        // Fork graph after pruning
2872        //                  0
2873        //                  |
2874        //                  5
2875        //                  |
2876        //                  11
2877        //                  |
2878        //                  15
2879        //                  |
2880        //                  16
2881        //                  |
2882        //                  19
2883        //                  |
2884        //                  23
2885
2886        // Testing fork 16, 19, 23, with root at 15, current slot at 23
2887        let mut missing = get_entries_to_load(&cache, 23, keys);
2888        assert!(match_missing(&missing, &program3, false));
2889        let mut extracted = ProgramCacheForTxBatch::new(23);
2890        cache.extract(&mut missing, &mut extracted, &env, true, true);
2891        assert!(match_slot(&extracted, &program1, 0, 23));
2892        assert!(match_slot(&extracted, &program2, 11, 23));
2893        assert!(match_slot(&extracted, &program4, 15, 23));
2894    }
2895
2896    #[test]
2897    fn test_extract_using_deployment_slot() {
2898        let mut cache = ProgramCache::<TestForkGraphSpecific>::new(0);
2899        let env = get_mock_program_runtime_environment();
2900
2901        // Fork graph created for the test
2902        //                   0
2903        //                 /   \
2904        //                10    5
2905        //                |     |
2906        //                20    11
2907        //                |     | \
2908        //                22   15  25
2909        //                      |   |
2910        //                     16  27
2911        //                      |
2912        //                     19
2913        //                      |
2914        //                     23
2915
2916        let mut fork_graph = TestForkGraphSpecific::default();
2917        fork_graph.insert_fork(&[0, 10, 20, 22]);
2918        fork_graph.insert_fork(&[0, 5, 11, 12, 15, 16, 18, 19, 21, 23]);
2919        fork_graph.insert_fork(&[0, 5, 11, 25, 27]);
2920
2921        let fork_graph = Arc::new(RwLock::new(fork_graph));
2922        cache.set_fork_graph(Arc::downgrade(&fork_graph));
2923
2924        let program1 = Pubkey::new_unique();
2925        cache.assign_program(&env, program1, 0, new_test_entry(0));
2926        cache.assign_program(&env, program1, 20, new_test_entry(20));
2927
2928        let program2 = Pubkey::new_unique();
2929        cache.assign_program(&env, program2, 5, new_test_entry(5));
2930        cache.assign_program(&env, program2, 11, new_test_entry(11));
2931
2932        let program3 = Pubkey::new_unique();
2933        cache.assign_program(&env, program3, 25, new_test_entry(25));
2934
2935        // Testing fork 0 - 5 - 11 - 15 - 16 - 19 - 21 - 23 with current slot at 19
2936        let keys = &[program1, program2, program3];
2937        let mut missing = get_entries_to_load(&cache, 12, keys);
2938        assert!(match_missing(&missing, &program3, false));
2939        let mut extracted = ProgramCacheForTxBatch::new(12);
2940        cache.extract(&mut missing, &mut extracted, &env, true, true);
2941        assert!(match_slot(&extracted, &program1, 0, 12));
2942        assert!(match_slot(&extracted, &program2, 11, 12));
2943
2944        // Now try extractions that previously worked under the "deployed on
2945        // or after" criteria, but won't work with exact matching.
2946        let mut missing = get_entries_to_load(&cache, 12, keys);
2947        // Program 2's newest entry is at slot 11. Asking for 5 doesn't extract
2948        // the latest (11) anymore. You get 5.
2949        missing.get_mut(1).unwrap().deployment_slot = 5;
2950        assert!(match_missing(&missing, &program3, false));
2951        let mut extracted = ProgramCacheForTxBatch::new(12);
2952        cache.extract(&mut missing, &mut extracted, &env, true, true);
2953        assert!(match_slot(&extracted, &program1, 0, 12));
2954        assert!(match_slot(&extracted, &program2, 5, 12));
2955    }
2956
2957    #[test]
2958    fn test_extract_rejects_entry_deployed_after_the_requested_slot() {
2959        let mut cache = ProgramCache::<TestForkGraphSpecific>::new(0);
2960        let env = get_mock_program_runtime_environment();
2961
2962        let mut fork_graph = TestForkGraphSpecific::default();
2963        fork_graph.insert_fork(&[0, 5, 11, 12]);
2964        let fork_graph = Arc::new(RwLock::new(fork_graph));
2965        cache.set_fork_graph(Arc::downgrade(&fork_graph));
2966
2967        // The only cached entry was deployed in slot 11.
2968        let program = Pubkey::new_unique();
2969        cache.assign_program(&env, program, 11, new_test_entry(11));
2970
2971        // A caller whose account state holds slot 5 must not be handed it.
2972        let mut missing = vec![ProgramToLoad {
2973            program_id: &program,
2974            loader: ProgramCacheEntryOwner::LoaderV2,
2975            deployment_slot: 5,
2976        }];
2977        let mut extracted = ProgramCacheForTxBatch::new(12);
2978        cache.extract(&mut missing, &mut extracted, &env, true, true);
2979        assert!(match_missing(&missing, &program, true));
2980        assert!(extracted.find(&program).is_none());
2981
2982        // The same caller requesting slot 11 gets it.
2983        let mut missing = vec![ProgramToLoad {
2984            program_id: &program,
2985            loader: ProgramCacheEntryOwner::LoaderV2,
2986            deployment_slot: 11,
2987        }];
2988        let mut extracted = ProgramCacheForTxBatch::new(12);
2989        cache.extract(&mut missing, &mut extracted, &env, true, true);
2990        assert!(match_missing(&missing, &program, false));
2991        assert!(match_slot(&extracted, &program, 11, 12));
2992    }
2993
2994    #[test]
2995    fn test_extract_unloaded() {
2996        let mut cache = ProgramCache::<TestForkGraphSpecific>::new(0);
2997        let env = get_mock_program_runtime_environment();
2998
2999        // Fork graph created for the test
3000        //                   0
3001        //                 /   \
3002        //                10    5
3003        //                |     |
3004        //                20    11
3005        //                |     | \
3006        //                22   15  25
3007        //                      |   |
3008        //                     16  27
3009        //                      |
3010        //                     19
3011        //                      |
3012        //                     23
3013
3014        let mut fork_graph = TestForkGraphSpecific::default();
3015        fork_graph.insert_fork(&[0, 10, 20, 22]);
3016        fork_graph.insert_fork(&[0, 5, 11, 15, 16, 19, 21, 23]);
3017        fork_graph.insert_fork(&[0, 5, 11, 25, 27]);
3018
3019        let fork_graph = Arc::new(RwLock::new(fork_graph));
3020        cache.set_fork_graph(Arc::downgrade(&fork_graph));
3021
3022        let program1 = Pubkey::new_unique();
3023        cache.assign_program(&env, program1, 0, new_test_entry(0));
3024        cache.assign_program(&env, program1, 20, new_test_entry(20));
3025
3026        let program2 = Pubkey::new_unique();
3027        cache.assign_program(&env, program2, 5, new_test_entry(5));
3028        cache.assign_program(&env, program2, 11, new_test_entry(11));
3029
3030        let program3 = Pubkey::new_unique();
3031        // Insert an unloaded program with correct/cache's environment at slot 25
3032        let _ = insert_unloaded_entry(&mut cache, program3, 25);
3033
3034        // Insert another unloaded program with a different environment at slot 20
3035        // Since this entry's environment won't match cache's environment, looking up this
3036        // entry should return missing instead of unloaded entry.
3037        cache.assign_program(
3038            &env,
3039            program3,
3040            20,
3041            Arc::new(
3042                new_test_entry(20)
3043                    .to_unloaded()
3044                    .expect("Failed to create unloaded program"),
3045            ),
3046        );
3047
3048        // Testing fork 0 - 5 - 11 - 15 - 16 - 19 - 21 - 23 with current slot at 19
3049        let keys = &[program1, program2, program3];
3050        let mut missing = get_entries_to_load(&cache, 19, keys);
3051        assert!(match_missing(&missing, &program3, false));
3052        let mut extracted = ProgramCacheForTxBatch::new(19);
3053        cache.extract(&mut missing, &mut extracted, &env, true, true);
3054        assert!(match_slot(&extracted, &program1, 0, 19));
3055        assert!(match_slot(&extracted, &program2, 11, 19));
3056
3057        // Testing fork 0 - 5 - 11 - 25 - 27 with current slot at 27
3058        let mut missing = get_entries_to_load(&cache, 27, keys);
3059        let mut extracted = ProgramCacheForTxBatch::new(27);
3060        cache.extract(&mut missing, &mut extracted, &env, true, true);
3061        assert!(match_slot(&extracted, &program1, 0, 27));
3062        assert!(match_slot(&extracted, &program2, 11, 27));
3063        assert!(match_missing(&missing, &program3, true));
3064
3065        // Testing fork 0 - 10 - 20 - 22 with current slot at 22
3066        let mut missing = get_entries_to_load(&cache, 22, keys);
3067        assert!(match_missing(&missing, &program2, false));
3068        let mut extracted = ProgramCacheForTxBatch::new(22);
3069        cache.extract(&mut missing, &mut extracted, &env, true, true);
3070        assert!(match_slot(&extracted, &program1, 20, 22));
3071        assert!(match_missing(&missing, &program3, true));
3072    }
3073
3074    #[test]
3075    fn test_extract_different_environment() {
3076        let mut cache = ProgramCache::<TestForkGraphSpecific>::new(0);
3077        let env = get_mock_program_runtime_environment();
3078        let other_env = ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock());
3079
3080        // Fork graph created for the test
3081        //                0
3082        //                |
3083        //                10
3084        //                |
3085        //                20
3086        //                |
3087        //                22
3088
3089        let mut fork_graph = TestForkGraphSpecific::default();
3090        fork_graph.insert_fork(&[0, 10, 20, 22]);
3091
3092        let fork_graph = Arc::new(RwLock::new(fork_graph));
3093        cache.set_fork_graph(Arc::downgrade(&fork_graph));
3094
3095        let program1 = Pubkey::new_unique();
3096        cache.assign_program(
3097            &env,
3098            program1,
3099            10,
3100            Arc::new(ProgramCacheEntry::new_closed_tombstone(
3101                10,
3102                ProgramCacheEntryOwner::LoaderV3,
3103            )),
3104        );
3105        cache.assign_program(&env, program1, 20, new_test_entry(20));
3106
3107        // Testing fork 0 - 10 - 20 - 22 with current slot at 22
3108        let keys = &[program1];
3109        let mut missing = get_entries_to_load(&cache, 22, keys);
3110        let mut extracted = ProgramCacheForTxBatch::new(22);
3111        cache.extract(&mut missing, &mut extracted, &env, true, true);
3112        assert!(match_slot(&extracted, &program1, 20, 22));
3113
3114        // Looking for a different environment
3115        let mut missing = get_entries_to_load(&cache, 22, keys);
3116        let mut extracted = ProgramCacheForTxBatch::new(22);
3117        cache.extract(&mut missing, &mut extracted, &other_env, true, true);
3118        assert!(match_missing(&missing, &program1, true));
3119    }
3120
3121    #[test_matrix((false, true))]
3122    fn test_extract_no_second_level(empty_second_level: bool) {
3123        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3124        let env = get_mock_program_runtime_environment();
3125        let program_id = Pubkey::new_unique();
3126        if empty_second_level {
3127            // Make the entry already exist, but with an empty second level.
3128            match &mut cache.index {
3129                IndexImplementation::V1 { entries, .. } => {
3130                    entries.insert(program_id, Vec::new());
3131                }
3132            }
3133        }
3134
3135        // There is nothing to iterate either way, so the program is left to be
3136        // loaded.
3137        let mut search_for = vec![ProgramToLoad {
3138            program_id: &program_id,
3139            loader: ProgramCacheEntryOwner::LoaderV3,
3140            deployment_slot: 0,
3141        }];
3142        let mut extracted = ProgramCacheForTxBatch::new(100);
3143        let task = cache.extract(&mut search_for, &mut extracted, &env, true, true);
3144        assert_eq!(search_for.len(), 1);
3145        assert!(extracted.entries.is_empty());
3146        assert_eq!(task, Some(program_id));
3147    }
3148
3149    #[test]
3150    fn test_extract_account_owner_mismatch() {
3151        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3152        let env = get_mock_program_runtime_environment();
3153        let program_id = Pubkey::new_unique();
3154        let owned_by_v2 = new_test_entry_with_owner(
3155            100,
3156            ProgramCacheEntryOwner::LoaderV2,
3157            new_loaded_entry(env.clone()),
3158        );
3159        cache.assign_program(&env, program_id, 100, Arc::clone(&owned_by_v2));
3160
3161        // The only entry has an owner the search does not ask for.
3162        // Nothing is extracted. The caller must reload.
3163        let mut search_for = vec![ProgramToLoad {
3164            program_id: &program_id,
3165            loader: ProgramCacheEntryOwner::LoaderV3,
3166            deployment_slot: 100,
3167        }];
3168        let mut extracted = ProgramCacheForTxBatch::new(200);
3169        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3170        assert_eq!(search_for.len(), 1);
3171        assert!(extracted.entries.is_empty());
3172
3173        // A loader migration, where only the newest entry has the new owner. A
3174        // search for the old one skips it and takes the entry below it.
3175        let owned_by_v3 = new_test_entry_with_owner(
3176            150,
3177            ProgramCacheEntryOwner::LoaderV3,
3178            new_loaded_entry(env.clone()),
3179        );
3180        cache.assign_program(&env, program_id, 150, Arc::clone(&owned_by_v3));
3181
3182        // Here the cache has the original v2 at 100 followed by the v3 at 150.
3183        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
3184        assert_eq!(slot_versions.len(), 2);
3185        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &owned_by_v2));
3186        assert!(Arc::ptr_eq(slot_versions.get(1).unwrap(), &owned_by_v3));
3187
3188        // Try searching for the v2 version, from some fork that did not see
3189        // the migration. Assert the v2 entry is returned.
3190        let mut search_for = vec![ProgramToLoad {
3191            program_id: &program_id,
3192            loader: ProgramCacheEntryOwner::LoaderV2,
3193            deployment_slot: 100,
3194        }];
3195        let mut extracted = ProgramCacheForTxBatch::new(200);
3196        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3197        assert!(search_for.is_empty());
3198        assert!(Arc::ptr_eq(
3199            extracted.entries.get(&program_id).unwrap(),
3200            &owned_by_v2
3201        ));
3202
3203        // And a fork which did see the migration finds the v3 entry, so both
3204        // owners are reachable from the same second level.
3205        let mut search_for = vec![ProgramToLoad {
3206            program_id: &program_id,
3207            loader: ProgramCacheEntryOwner::LoaderV3,
3208            deployment_slot: 150,
3209        }];
3210        let mut extracted = ProgramCacheForTxBatch::new(200);
3211        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3212        assert!(search_for.is_empty());
3213        assert!(Arc::ptr_eq(
3214            extracted.entries.get(&program_id).unwrap(),
3215            &owned_by_v3
3216        ));
3217    }
3218
3219    #[test]
3220    fn test_extract_environment_mismatch() {
3221        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3222        let env = get_mock_program_runtime_environment();
3223        let other_env = ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock());
3224        let program_id = Pubkey::new_unique();
3225        let on_other_env = new_test_entry_with_owner(
3226            100,
3227            ProgramCacheEntryOwner::LoaderV3,
3228            new_loaded_entry(other_env.clone()),
3229        );
3230        cache.assign_program(&other_env, program_id, 100, Arc::clone(&on_other_env));
3231
3232        // The only entry is in the same branch and effective, but it was built
3233        // for another environment.
3234        // Nothing is extracted. The caller must reload.
3235        // This is "reload when in doubt" in its smallest form.
3236        let mut search_for = vec![ProgramToLoad {
3237            program_id: &program_id,
3238            loader: ProgramCacheEntryOwner::LoaderV3,
3239            deployment_slot: 100,
3240        }];
3241        let mut extracted = ProgramCacheForTxBatch::new(200);
3242        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3243        assert_eq!(search_for.len(), 1);
3244        assert!(extracted.entries.is_empty());
3245
3246        // The same deployment, compiled for the environment which is asked
3247        // for. Both are kept, since they differ in env.
3248        let on_execution_env = new_test_entry_with_owner(
3249            100,
3250            ProgramCacheEntryOwner::LoaderV3,
3251            new_loaded_entry(env.clone()),
3252        );
3253        cache.assign_program(&env, program_id, 100, Arc::clone(&on_execution_env));
3254
3255        // Here the cache has the one on the other environment first, since
3256        // entries for the current one sort last.
3257        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
3258        assert_eq!(slot_versions.len(), 2);
3259        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &on_other_env));
3260        assert!(Arc::ptr_eq(
3261            slot_versions.get(1).unwrap(),
3262            &on_execution_env
3263        ));
3264
3265        // Try searching for the entry with the current env. Assert it is
3266        // returned.
3267        let mut search_for = vec![ProgramToLoad {
3268            program_id: &program_id,
3269            loader: ProgramCacheEntryOwner::LoaderV3,
3270            deployment_slot: 100,
3271        }];
3272        let mut extracted = ProgramCacheForTxBatch::new(200);
3273        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3274        assert!(search_for.is_empty());
3275        assert!(Arc::ptr_eq(
3276            extracted.entries.get(&program_id).unwrap(),
3277            &on_execution_env
3278        ));
3279
3280        // And searching under the other environment returns the entry built
3281        // for it, so both are reachable from the same second level.
3282        let mut search_for = vec![ProgramToLoad {
3283            program_id: &program_id,
3284            loader: ProgramCacheEntryOwner::LoaderV3,
3285            deployment_slot: 100,
3286        }];
3287        let mut extracted = ProgramCacheForTxBatch::new(200);
3288        cache.extract(&mut search_for, &mut extracted, &other_env, true, true);
3289        assert!(search_for.is_empty());
3290        assert!(Arc::ptr_eq(
3291            extracted.entries.get(&program_id).unwrap(),
3292            &on_other_env
3293        ));
3294    }
3295
3296    #[test]
3297    fn test_extract_unloaded_entry() {
3298        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3299        let env = get_mock_program_runtime_environment();
3300        let program_id = Pubkey::new_unique();
3301        let unloaded = new_test_entry_with_owner(
3302            100,
3303            ProgramCacheEntryOwner::LoaderV3,
3304            new_unloaded_entry(env.clone()),
3305        );
3306        cache.assign_program(&env, program_id, 100, Arc::clone(&unloaded));
3307
3308        // The only entry clears every check documented in the previous test,
3309        // but its executable has been evicted.
3310        // Nothing is extracted. The caller must reload.
3311        let mut search_for = vec![ProgramToLoad {
3312            program_id: &program_id,
3313            loader: ProgramCacheEntryOwner::LoaderV3,
3314            deployment_slot: 100,
3315        }];
3316        let mut extracted = ProgramCacheForTxBatch::new(200);
3317        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3318        assert_eq!(search_for.len(), 1);
3319        assert!(extracted.entries.is_empty());
3320
3321        // Reloading it is an allowed replacement, so it takes the same place.
3322        let loaded = new_test_entry_with_owner(
3323            100,
3324            ProgramCacheEntryOwner::LoaderV3,
3325            new_loaded_entry(env.clone()),
3326        );
3327        cache.assign_program(&env, program_id, 100, Arc::clone(&loaded));
3328        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
3329        assert_eq!(slot_versions.len(), 1);
3330        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &loaded));
3331
3332        // Extracting now gives the loaded entry. The unloaded is gone.
3333        let mut search_for = vec![ProgramToLoad {
3334            program_id: &program_id,
3335            loader: ProgramCacheEntryOwner::LoaderV3,
3336            deployment_slot: 100,
3337        }];
3338        let mut extracted = ProgramCacheForTxBatch::new(200);
3339        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3340        assert!(search_for.is_empty());
3341        assert!(Arc::ptr_eq(
3342            extracted.entries.get(&program_id).unwrap(),
3343            &loaded
3344        ));
3345    }
3346
3347    #[test_matrix(
3348        (
3349            new_closed_entry,
3350            new_builtin_entry,
3351            new_failed_verification_entry,
3352            new_unloaded_entry,
3353            new_loaded_entry,
3354        ),
3355        (100, 101)
3356    )]
3357    fn test_extract_effective_slot(
3358        new_program: fn(ProgramRuntimeEnvironment) -> ProgramCacheEntryType,
3359        batch_slot: Slot,
3360    ) {
3361        // Fork graph created for the test
3362        //                100 - 101
3363        //                ^^^   ^^^
3364        //                |     `Loaded` and `Unloaded` become effective here
3365        //                the entry is deployed here
3366        //
3367        // Only `Loaded` and `Unloaded` have a delay window. The other three
3368        // are effective in the slot they were deployed in.
3369        //
3370        // Here we want to test that for all entry types, inside their
3371        // designated delay window, we get a tombstone standing in for the
3372        // entry, and outside it we get the entry itself (unless it is
3373        // `Unloaded`).
3374        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3375        let env = get_mock_program_runtime_environment();
3376        let program_id = Pubkey::new_unique();
3377        let entry = new_test_entry_with_owner(
3378            100,
3379            ProgramCacheEntryOwner::LoaderV3,
3380            new_program(env.clone()),
3381        );
3382        cache.assign_program(&env, program_id, 100, Arc::clone(&entry));
3383        cache.latest_root_slot = batch_slot;
3384
3385        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
3386        assert_eq!(slot_versions.len(), 1);
3387        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &entry));
3388
3389        let mut search_for = vec![ProgramToLoad {
3390            program_id: &program_id,
3391            loader: ProgramCacheEntryOwner::LoaderV3,
3392            deployment_slot: 100,
3393        }];
3394        let mut extracted = ProgramCacheForTxBatch::new(batch_slot);
3395        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3396
3397        if batch_slot < entry.effective_slot() {
3398            // The entry wasn't effective, so a tombstone was minted to stand
3399            // in for it. It is built at that moment rather than found, so what
3400            // it carries is copied across from the entry.
3401            assert!(search_for.is_empty());
3402            let tombstone = extracted.entries.get(&program_id).unwrap();
3403            assert_matches!(tombstone.program, ProgramCacheEntryType::DelayVisibility);
3404            assert_eq!(tombstone.account_owner, ProgramCacheEntryOwner::LoaderV3);
3405            assert_eq!(tombstone.deployment_slot, 100);
3406            assert!(Arc::ptr_eq(&tombstone.stats, &entry.stats)); // <-- Shared, not copied.
3407            assert_eq!(entry.stats.uses.load(Ordering::Relaxed), 1);
3408
3409            // The access slot is recorded on the entry the tombstone stands in
3410            // for. The tombstone's own is never touched, and is thrown away
3411            // with the batch.
3412            assert_eq!(entry.latest_access_slot.load(Ordering::Relaxed), batch_slot);
3413            assert_eq!(tombstone.latest_access_slot.load(Ordering::Relaxed), 0);
3414        } else if entry.is_unloaded() {
3415            // The entry was effective, but there is no binary behind it, so
3416            // the search breaks off and the caller is left to reload. Nothing
3417            // is recorded against the entry.
3418            assert!(extracted.entries.is_empty());
3419            assert_eq!(search_for.len(), 1);
3420            assert_eq!(entry.stats.uses.load(Ordering::Relaxed), 0);
3421            assert_eq!(entry.latest_access_slot.load(Ordering::Relaxed), 0);
3422        } else {
3423            // The entry was effective, so it comes back itself, and the use
3424            // and access slot are recorded on it.
3425            assert!(search_for.is_empty());
3426            assert!(Arc::ptr_eq(
3427                extracted.entries.get(&program_id).unwrap(),
3428                &entry
3429            ));
3430            assert_eq!(entry.stats.uses.load(Ordering::Relaxed), 1);
3431            assert_eq!(entry.latest_access_slot.load(Ordering::Relaxed), batch_slot);
3432        }
3433    }
3434
3435    #[test]
3436    fn test_extract_closed_entry_matches_any_env() {
3437        // Fork graph created for the test
3438        //                100
3439        //                ^^^
3440        //                the program is closed here
3441        //
3442        // Here we want to test that a closed entry carries no environment at
3443        // all, and that `matches_environment` reads that as a match for any of
3444        // them. Therefore, the entry is handed out whichever environment is
3445        // asked for.
3446        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3447        let env = get_mock_program_runtime_environment();
3448        let other_env = ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock());
3449        let program_id = Pubkey::new_unique();
3450        let closed = new_test_entry_with_owner(
3451            100,
3452            ProgramCacheEntryOwner::LoaderV3,
3453            new_closed_entry(env.clone()), // <-- Entry is created with `env`.
3454        );
3455        assert_eq!(closed.effective_slot(), closed.deployment_slot);
3456        cache.assign_program(&env, program_id, 100, Arc::clone(&closed));
3457
3458        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
3459        assert_eq!(slot_versions.len(), 1);
3460        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &closed));
3461
3462        // Ask for the entry with `env`, matching the one used to assign it.
3463        let mut search_for = vec![ProgramToLoad {
3464            program_id: &program_id,
3465            loader: ProgramCacheEntryOwner::LoaderV3,
3466            deployment_slot: 100,
3467        }];
3468        let mut extracted = ProgramCacheForTxBatch::new(100);
3469        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3470        assert!(Arc::ptr_eq(
3471            extracted.entries.get(&program_id).unwrap(),
3472            &closed
3473        ));
3474        assert!(search_for.is_empty());
3475
3476        // Now ask for it again with `other_env`. Still successful.
3477        let mut search_for = vec![ProgramToLoad {
3478            program_id: &program_id,
3479            loader: ProgramCacheEntryOwner::LoaderV3,
3480            deployment_slot: 100,
3481        }];
3482        let mut extracted = ProgramCacheForTxBatch::new(100);
3483        cache.extract(&mut search_for, &mut extracted, &other_env, true, true);
3484        assert!(Arc::ptr_eq(
3485            extracted.entries.get(&program_id).unwrap(),
3486            &closed
3487        ));
3488        assert!(search_for.is_empty());
3489    }
3490
3491    #[test]
3492    fn test_extract_delay_visibility_tombstone_interleaved_environments() {
3493        // Fork graph created for the test
3494        //                100 - 101
3495        //                ^^^   ^^^
3496        //                |     both entries become effective here
3497        //                both entries are deployed here
3498        //
3499        // Two entries at one deployment slot, one per environment. Here we
3500        // attempt to extract within the delay window (at the deployment slot).
3501        //
3502        // This test demonstrates that `DelayVisibility` tombstones - like
3503        // `Closed` - are indiscriminant about environments. Inside `extract`,
3504        // the delay visibility arm does not check the environment. Thus, any
3505        // entry provided to `extract` will see a `DelayVisibility` tombstone
3506        // if the batch slot falls within the delay window.
3507        //
3508        // Such a scenario is only possible if a program is deployed, loaded,
3509        // recompiled for the upcoming epoch, and extracted all within the same
3510        // slot. Since deployments insert `Unloaded` entries, this isn't
3511        // reachable in production today.
3512        //
3513        // However, this test serves to document this behavior, since it causes
3514        // a stats bug for now and could one day become a wider footgun.
3515        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3516        let env = get_mock_program_runtime_environment();
3517        let upcoming_env = ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock());
3518        let program_id = Pubkey::new_unique();
3519        let on_execution_env = new_test_entry_with_owner(
3520            100,
3521            ProgramCacheEntryOwner::LoaderV3,
3522            new_loaded_entry(env.clone()),
3523        );
3524        let on_upcoming_env = new_test_entry_with_owner(
3525            100,
3526            ProgramCacheEntryOwner::LoaderV3,
3527            new_loaded_entry(upcoming_env.clone()),
3528        );
3529        cache.assign_program(&env, program_id, 100, Arc::clone(&on_execution_env));
3530        cache.assign_program(&upcoming_env, program_id, 100, Arc::clone(&on_upcoming_env));
3531
3532        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
3533        assert_eq!(slot_versions.len(), 2);
3534        assert!(Arc::ptr_eq(
3535            slot_versions.first().unwrap(),
3536            &on_execution_env
3537        ));
3538        assert!(Arc::ptr_eq(slot_versions.get(1).unwrap(), &on_upcoming_env));
3539
3540        // Try the extraction, with the batch slot within the delay window.
3541        let mut search_for = vec![ProgramToLoad {
3542            program_id: &program_id,
3543            loader: ProgramCacheEntryOwner::LoaderV3,
3544            deployment_slot: 100,
3545        }];
3546        let mut extracted = ProgramCacheForTxBatch::new(100);
3547        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3548        assert!(search_for.is_empty());
3549
3550        // As expected, we get a `DelayVisibility` tombstone.
3551        let tombstone = extracted.entries.get(&program_id).unwrap();
3552        assert_matches!(tombstone.program, ProgramCacheEntryType::DelayVisibility);
3553
3554        // TODO: Here's the stats bug, though. The entry the batch is actually
3555        // using (passed to `extract`) is present and reached second. The first
3556        // one reached is `!is_current_env`. Extraction traverses the second
3557        // level in reverse.
3558        //
3559        // So, in a case like this, we're actually updating the stats on the
3560        // wrong underlying `Loaded` entry.
3561        assert!(Arc::ptr_eq(&tombstone.stats, &on_upcoming_env.stats));
3562        assert_eq!(on_upcoming_env.stats.uses.load(Ordering::Relaxed), 1);
3563        assert_eq!(on_execution_env.stats.uses.load(Ordering::Relaxed), 0);
3564
3565        // Now extract one slot later, when the program becomes effective. As
3566        // we know, here environment *does* matter.
3567        let mut search_for = vec![ProgramToLoad {
3568            program_id: &program_id,
3569            loader: ProgramCacheEntryOwner::LoaderV3,
3570            deployment_slot: 100,
3571        }];
3572        let mut extracted = ProgramCacheForTxBatch::new(101);
3573        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3574        assert!(search_for.is_empty());
3575        assert!(Arc::ptr_eq(
3576            extracted.entries.get(&program_id).unwrap(),
3577            &on_execution_env
3578        ));
3579
3580        // Now we see one use on each, since we just pulled `on_execution_env`.
3581        assert_eq!(on_upcoming_env.stats.uses.load(Ordering::Relaxed), 1);
3582        assert_eq!(on_execution_env.stats.uses.load(Ordering::Relaxed), 1);
3583    }
3584
3585    #[test_case(false)]
3586    #[test_case(true)]
3587    fn test_extract_environment_filter_same_slot(other_env_first: bool) {
3588        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3589        let env = get_mock_program_runtime_environment();
3590        let other_env = ProgramRuntimeEnvironment::from(BuiltinProgram::new_mock());
3591        let program_id = Pubkey::new_unique();
3592
3593        // Two entries at one deployment slot, one per environment.
3594        let on_other_env = new_test_entry_with_owner(
3595            100,
3596            ProgramCacheEntryOwner::LoaderV3,
3597            new_loaded_entry(other_env.clone()),
3598        );
3599        let on_execution_env = new_test_entry_with_owner(
3600            100,
3601            ProgramCacheEntryOwner::LoaderV3,
3602            new_loaded_entry(env.clone()),
3603        );
3604        if other_env_first {
3605            cache.assign_program(&other_env, program_id, 100, Arc::clone(&on_other_env));
3606            cache.assign_program(&env, program_id, 100, Arc::clone(&on_execution_env));
3607        } else {
3608            cache.assign_program(&env, program_id, 100, Arc::clone(&on_execution_env));
3609            cache.assign_program(&other_env, program_id, 100, Arc::clone(&on_other_env));
3610        }
3611
3612        // Each is assigned under its own environment, so whichever came
3613        // first sits first.
3614        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
3615        assert_eq!(slot_versions.len(), 2);
3616        let (first, second) = if other_env_first {
3617            (&on_other_env, &on_execution_env)
3618        } else {
3619            (&on_execution_env, &on_other_env)
3620        };
3621        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), first));
3622        assert!(Arc::ptr_eq(slot_versions.get(1).unwrap(), second));
3623
3624        // No matter the ordering, the one on the environment which is asked
3625        // for is the one returned.
3626        let mut search_for = vec![ProgramToLoad {
3627            program_id: &program_id,
3628            loader: ProgramCacheEntryOwner::LoaderV3,
3629            deployment_slot: 100,
3630        }];
3631        let mut extracted = ProgramCacheForTxBatch::new(200);
3632        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3633        assert!(Arc::ptr_eq(
3634            extracted.entries.get(&program_id).unwrap(),
3635            &on_execution_env
3636        ));
3637
3638        // And asking for the other environment reaches the other entry.
3639        let mut search_for = vec![ProgramToLoad {
3640            program_id: &program_id,
3641            loader: ProgramCacheEntryOwner::LoaderV3,
3642            deployment_slot: 100,
3643        }];
3644        let mut extracted = ProgramCacheForTxBatch::new(200);
3645        cache.extract(&mut search_for, &mut extracted, &other_env, true, true);
3646        assert!(Arc::ptr_eq(
3647            extracted.entries.get(&program_id).unwrap(),
3648            &on_other_env
3649        ));
3650    }
3651
3652    #[test_matrix((false, true))]
3653    fn test_extract_usage_counter(increment_usage_counter: bool) {
3654        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3655        let env = get_mock_program_runtime_environment();
3656        let program_id = Pubkey::new_unique();
3657        let entry = new_test_entry_with_owner(
3658            100,
3659            ProgramCacheEntryOwner::LoaderV3,
3660            new_loaded_entry(env.clone()),
3661        );
3662        cache.assign_program(&env, program_id, 100, Arc::clone(&entry));
3663        cache.latest_root_slot = 200;
3664
3665        let mut search_for = vec![ProgramToLoad {
3666            program_id: &program_id,
3667            loader: ProgramCacheEntryOwner::LoaderV3,
3668            deployment_slot: 100,
3669        }];
3670        let mut extracted = ProgramCacheForTxBatch::new(200);
3671        cache.extract(
3672            &mut search_for,
3673            &mut extracted,
3674            &env,
3675            increment_usage_counter,
3676            true,
3677        );
3678
3679        // The access slot moves either way, the usage counter only when asked.
3680        assert_eq!(entry.latest_access_slot.load(Ordering::Relaxed), 200);
3681        assert_eq!(
3682            entry.stats.uses.load(Ordering::Relaxed),
3683            u64::from(increment_usage_counter)
3684        );
3685    }
3686
3687    #[test]
3688    fn test_extract_usage_counter_delayed_visibility() {
3689        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3690        let env = get_mock_program_runtime_environment();
3691        let program_id = Pubkey::new_unique();
3692        let entry = new_test_entry_with_owner(
3693            100,
3694            ProgramCacheEntryOwner::LoaderV3,
3695            new_loaded_entry(env.clone()),
3696        );
3697        cache.assign_program(&env, program_id, 100, Arc::clone(&entry));
3698        cache.latest_root_slot = 100;
3699
3700        // Extract at the deployment slot itself, which is inside the delay
3701        // visibility window, so a `DelayVisibility` tombstone stands in for
3702        // the entry.
3703        let mut search_for = vec![ProgramToLoad {
3704            program_id: &program_id,
3705            loader: ProgramCacheEntryOwner::LoaderV3,
3706            deployment_slot: 100,
3707        }];
3708        let mut extracted = ProgramCacheForTxBatch::new(100);
3709        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3710
3711        let tombstone = extracted.entries.get(&program_id).unwrap();
3712        assert!(matches!(
3713            tombstone.program,
3714            ProgramCacheEntryType::DelayVisibility
3715        ));
3716        assert!(!Arc::ptr_eq(tombstone, &entry));
3717
3718        // The access slot lands on the entry the tombstone stands in for. The
3719        // tombstone's own is never touched, and is dropped with the batch.
3720        assert_eq!(entry.latest_access_slot.load(Ordering::Relaxed), 100);
3721        assert_eq!(tombstone.latest_access_slot.load(Ordering::Relaxed), 0);
3722
3723        // The usage counter reaches the entry either way, through the
3724        // statistics the two share.
3725        assert!(Arc::ptr_eq(&tombstone.stats, &entry.stats));
3726        assert_eq!(entry.stats.uses.load(Ordering::Relaxed), 1);
3727    }
3728
3729    #[test_matrix((false, true))]
3730    fn test_extract_hits_and_misses(count_hits_and_misses: bool) {
3731        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3732        let env = get_mock_program_runtime_environment();
3733        let found = Pubkey::new_unique();
3734        let missing = Pubkey::new_unique();
3735        cache.assign_program(
3736            &env,
3737            found,
3738            100,
3739            new_test_entry_with_owner(
3740                100,
3741                ProgramCacheEntryOwner::LoaderV3,
3742                new_loaded_entry(env.clone()),
3743            ),
3744        );
3745
3746        let mut search_for = vec![
3747            ProgramToLoad {
3748                program_id: &found,
3749                loader: ProgramCacheEntryOwner::LoaderV3,
3750                deployment_slot: 100,
3751            },
3752            ProgramToLoad {
3753                program_id: &missing,
3754                loader: ProgramCacheEntryOwner::LoaderV3,
3755                deployment_slot: 0,
3756            },
3757        ];
3758        let mut extracted = ProgramCacheForTxBatch::new(200);
3759        cache.extract(
3760            &mut search_for,
3761            &mut extracted,
3762            &env,
3763            true,
3764            count_hits_and_misses,
3765        );
3766
3767        let expected = u64::from(count_hits_and_misses);
3768        assert_eq!(cache.stats.hits.load(Ordering::Relaxed), expected);
3769        assert_eq!(cache.stats.misses.load(Ordering::Relaxed), expected);
3770    }
3771
3772    #[test]
3773    fn test_extract_hits_count_only_this_call() {
3774        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3775        let env = get_mock_program_runtime_environment();
3776        let program_id = Pubkey::new_unique();
3777        cache.assign_program(
3778            &env,
3779            program_id,
3780            100,
3781            new_test_entry_with_owner(
3782                100,
3783                ProgramCacheEntryOwner::LoaderV3,
3784                new_loaded_entry(env.clone()),
3785            ),
3786        );
3787
3788        // Anything already in the batch, such as the builtins it is seeded
3789        // with.
3790        let mut extracted = ProgramCacheForTxBatch::new(200);
3791        extracted.replenish(Pubkey::new_unique(), new_test_builtin_entry(0));
3792
3793        // One entry is found, and only that one is counted. The entry seeded
3794        // above is still in the batch, but it was not found by this call.
3795        let mut search_for = vec![ProgramToLoad {
3796            program_id: &program_id,
3797            loader: ProgramCacheEntryOwner::LoaderV3,
3798            deployment_slot: 100,
3799        }];
3800        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3801        assert_eq!(extracted.entries.len(), 2);
3802        assert_eq!(cache.stats.hits.load(Ordering::Relaxed), 1);
3803    }
3804
3805    #[test]
3806    fn test_extract_cooperative_loading_task() {
3807        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3808        let env = get_mock_program_runtime_environment();
3809        let program_ids = [Pubkey::new_unique(), Pubkey::new_unique()];
3810
3811        // Both are missing, but only the first one becomes a task.
3812        let mut search_for = program_ids
3813            .iter()
3814            .map(|program_id| ProgramToLoad {
3815                program_id,
3816                loader: ProgramCacheEntryOwner::LoaderV3,
3817                deployment_slot: 0,
3818            })
3819            .collect();
3820        let mut extracted = ProgramCacheForTxBatch::new(100);
3821        let task = cache.extract(&mut search_for, &mut extracted, &env, true, true);
3822        assert_eq!(search_for.len(), 2);
3823        assert_eq!(task, program_ids.first().copied());
3824        match &cache.index {
3825            IndexImplementation::V1 {
3826                loading_entries, ..
3827            } => {
3828                let loading_entries = loading_entries.lock().unwrap();
3829                assert_eq!(loading_entries.len(), 1);
3830                assert_eq!(
3831                    loading_entries.get(program_ids.first().unwrap()),
3832                    Some(&(100, thread::current().id()))
3833                );
3834            }
3835        }
3836
3837        // Asking again for the one which is already loading returns nothing.
3838        let mut search_for = vec![ProgramToLoad {
3839            program_id: program_ids.first().unwrap(),
3840            loader: ProgramCacheEntryOwner::LoaderV3,
3841            deployment_slot: 0,
3842        }];
3843        let task = cache.extract(&mut search_for, &mut extracted, &env, true, true);
3844        assert_eq!(search_for.len(), 1);
3845        assert_eq!(task, None);
3846
3847        // Submitting the finished task notifies whoever is waiting on one.
3848        let cookie = cache.loading_task_waiter.cookie();
3849        let loaded = new_test_entry_with_owner(
3850            50,
3851            ProgramCacheEntryOwner::LoaderV3,
3852            new_loaded_entry(env.clone()),
3853        );
3854        cache.finish_cooperative_loading_task(
3855            &env,
3856            100,
3857            *program_ids.first().unwrap(),
3858            Arc::clone(&loaded),
3859        );
3860        assert_ne!(cache.loading_task_waiter.wait(cookie), cookie);
3861
3862        // It is no longer loading, and extracting it now finds it.
3863        match &cache.index {
3864            IndexImplementation::V1 {
3865                loading_entries, ..
3866            } => assert!(loading_entries.lock().unwrap().is_empty()),
3867        }
3868        let mut search_for = vec![ProgramToLoad {
3869            program_id: program_ids.first().unwrap(),
3870            loader: ProgramCacheEntryOwner::LoaderV3,
3871            deployment_slot: 50,
3872        }];
3873        let mut extracted = ProgramCacheForTxBatch::new(100);
3874        let task = cache.extract(&mut search_for, &mut extracted, &env, true, true);
3875        assert!(search_for.is_empty());
3876        assert_eq!(task, None);
3877        assert!(Arc::ptr_eq(
3878            extracted.entries.get(program_ids.first().unwrap()).unwrap(),
3879            &loaded
3880        ));
3881    }
3882
3883    #[test]
3884    fn test_extract_cooperative_loading_task_ordering() {
3885        let (cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3886        let env = get_mock_program_runtime_environment();
3887        let program_ids = [Pubkey::new_unique(), Pubkey::new_unique()];
3888        let mut extracted = ProgramCacheForTxBatch::new(100);
3889
3890        // The first one reached becomes the task.
3891        let mut search_for = program_ids
3892            .iter()
3893            .map(|program_id| ProgramToLoad {
3894                program_id,
3895                loader: ProgramCacheEntryOwner::LoaderV3,
3896                deployment_slot: 0,
3897            })
3898            .collect();
3899        let task = cache.extract(&mut search_for, &mut extracted, &env, true, true);
3900        assert_eq!(task, program_ids.first().copied());
3901
3902        // Asking again in the reverse order reaches the one which is not
3903        // loading yet first, so that one becomes a task of its own.
3904        let mut search_for = program_ids
3905            .iter()
3906            .rev()
3907            .map(|program_id| ProgramToLoad {
3908                program_id,
3909                loader: ProgramCacheEntryOwner::LoaderV3,
3910                deployment_slot: 0,
3911            })
3912            .collect();
3913        let task = cache.extract(&mut search_for, &mut extracted, &env, true, true);
3914        assert_eq!(task, program_ids.get(1).copied());
3915
3916        // Both are loading now, by this thread and for this slot.
3917        match &cache.index {
3918            IndexImplementation::V1 {
3919                loading_entries, ..
3920            } => {
3921                let loading_entries = loading_entries.lock().unwrap();
3922                assert_eq!(loading_entries.len(), 2);
3923                for program_id in &program_ids {
3924                    assert_eq!(
3925                        loading_entries.get(program_id),
3926                        Some(&(100, thread::current().id()))
3927                    );
3928                }
3929            }
3930        }
3931
3932        // Neither of them can become a task again.
3933        let mut search_for = program_ids
3934            .iter()
3935            .map(|program_id| ProgramToLoad {
3936                program_id,
3937                loader: ProgramCacheEntryOwner::LoaderV3,
3938                deployment_slot: 0,
3939            })
3940            .collect();
3941        let task = cache.extract(&mut search_for, &mut extracted, &env, true, true);
3942        assert_eq!(search_for.len(), 2);
3943        assert_eq!(task, None);
3944    }
3945
3946    #[test]
3947    fn test_extract_deployment_slot_mismatch() {
3948        // Unlike the mismatched owner test above, a mismatched deployment slot
3949        // is only a genuine miss when the targeted `deployment_slot`
3950        // is too new.
3951        //
3952        // So, we produce a scenario where `entry_is_effective` and
3953        // `matches_environment` both evaluate to `true`, finally trapping and
3954        // breaking out on
3955        // `entry.deployment_slot < program_to_load.deployment_slot`.
3956        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
3957        assert_eq!(cache.latest_root_slot, 0);
3958        let env = get_mock_program_runtime_environment();
3959        let program_id = Pubkey::new_unique();
3960        let deployed_at_100 = new_test_entry_with_owner(
3961            100,
3962            ProgramCacheEntryOwner::LoaderV3,
3963            new_loaded_entry(env.clone()),
3964        );
3965        cache.assign_program(&env, program_id, 100, Arc::clone(&deployed_at_100));
3966
3967        // The only entry is effective and on the right environment, but it is
3968        // older than the search demands. Nothing is extracted. The caller must
3969        // reload.
3970        let mut search_for = vec![ProgramToLoad {
3971            program_id: &program_id,
3972            loader: ProgramCacheEntryOwner::LoaderV3,
3973            deployment_slot: 150,
3974        }];
3975        let mut extracted = ProgramCacheForTxBatch::new(200);
3976        cache.extract(&mut search_for, &mut extracted, &env, true, true);
3977        assert_eq!(search_for.len(), 1);
3978        assert!(extracted.entries.is_empty());
3979
3980        // A redeployment at the slot the search asks for.
3981        let deployed_at_150 = new_test_entry_with_owner(
3982            150,
3983            ProgramCacheEntryOwner::LoaderV3,
3984            new_loaded_entry(env.clone()),
3985        );
3986        cache.assign_program(&env, program_id, 150, Arc::clone(&deployed_at_150));
3987
3988        // Here the cache has the original entry at 100 followed by the one at
3989        // 150.
3990        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
3991        assert_eq!(slot_versions.len(), 2);
3992        assert!(Arc::ptr_eq(
3993            slot_versions.first().unwrap(),
3994            &deployed_at_100
3995        ));
3996        assert!(Arc::ptr_eq(slot_versions.get(1).unwrap(), &deployed_at_150));
3997
3998        // Now a search at 150 finds it.
3999        let mut search_for = vec![ProgramToLoad {
4000            program_id: &program_id,
4001            loader: ProgramCacheEntryOwner::LoaderV3,
4002            deployment_slot: 150,
4003        }];
4004        let mut extracted = ProgramCacheForTxBatch::new(200);
4005        cache.extract(&mut search_for, &mut extracted, &env, true, true);
4006        assert!(search_for.is_empty());
4007        assert!(Arc::ptr_eq(
4008            extracted.entries.get(&program_id).unwrap(),
4009            &deployed_at_150
4010        ));
4011
4012        // A caller whose own account still names 100 is served the entry at
4013        // 100, not the newer one at 150.
4014        let mut search_for = vec![ProgramToLoad {
4015            program_id: &program_id,
4016            loader: ProgramCacheEntryOwner::LoaderV3,
4017            deployment_slot: 100,
4018        }];
4019        let mut extracted = ProgramCacheForTxBatch::new(200);
4020        cache.extract(&mut search_for, &mut extracted, &env, true, true);
4021        assert!(search_for.is_empty());
4022        assert!(Arc::ptr_eq(
4023            extracted.entries.get(&program_id).unwrap(),
4024            &deployed_at_100
4025        ));
4026    }
4027
4028    #[test]
4029    fn test_extract_below_deployment_slot() {
4030        let (mut cache, fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
4031        let env = get_mock_program_runtime_environment();
4032        let program_id = Pubkey::new_unique();
4033        let entry = new_test_entry_with_owner(
4034            100,
4035            ProgramCacheEntryOwner::LoaderV3,
4036            new_loaded_entry(env.clone()),
4037        );
4038        cache.assign_program(&env, program_id, 100, Arc::clone(&entry));
4039
4040        // Rooting past the entry puts it in the branch without the fork graph
4041        // being consulted.
4042        cache.prune(200, None, &fork_graph.read().unwrap());
4043        assert_eq!(cache.latest_root_slot, 200);
4044
4045        // It survives that, since the fork graph said it was an `Ancestor`.
4046        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
4047        assert_eq!(slot_versions.len(), 1);
4048        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &entry));
4049
4050        // The caller asks for the correct deployment slot (somehow), but since
4051        // the batch slot is below that target slot, the entry is neither
4052        // effective nor a delay visibility tombstone, so it is not served.
4053        let mut search_for = vec![ProgramToLoad {
4054            program_id: &program_id,
4055            loader: ProgramCacheEntryOwner::LoaderV3,
4056            deployment_slot: 100,
4057        }];
4058        let mut extracted = ProgramCacheForTxBatch::new(50);
4059        cache.extract(&mut search_for, &mut extracted, &env, true, true);
4060        assert_eq!(search_for.len(), 1);
4061        assert!(extracted.entries.is_empty());
4062    }
4063
4064    #[test]
4065    fn test_extract_entry_older_than_root() {
4066        // The same setup as above, extracted from a slot above the entry
4067        // rather than below it.
4068        let (mut cache, fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
4069        let env = get_mock_program_runtime_environment();
4070        let program_id = Pubkey::new_unique();
4071        let entry = new_test_entry_with_owner(
4072            100,
4073            ProgramCacheEntryOwner::LoaderV3,
4074            new_loaded_entry(env.clone()),
4075        );
4076        cache.assign_program(&env, program_id, 100, Arc::clone(&entry));
4077
4078        // Rooting past the entry puts it in the branch without the fork graph
4079        // being consulted.
4080        cache.prune(200, None, &fork_graph.read().unwrap());
4081        assert_eq!(cache.latest_root_slot, 200);
4082
4083        // It survives that, since the fork graph said it was an `Ancestor`.
4084        let slot_versions = cache.get_slot_versions_for_tests(&program_id);
4085        assert_eq!(slot_versions.len(), 1);
4086        assert!(Arc::ptr_eq(slot_versions.first().unwrap(), &entry));
4087
4088        // The entry is still served. The search criteria is still a match.
4089        let mut search_for = vec![ProgramToLoad {
4090            program_id: &program_id,
4091            loader: ProgramCacheEntryOwner::LoaderV3,
4092            deployment_slot: 100,
4093        }];
4094        let mut extracted = ProgramCacheForTxBatch::new(300);
4095        cache.extract(&mut search_for, &mut extracted, &env, true, true);
4096        assert!(search_for.is_empty());
4097        assert!(Arc::ptr_eq(
4098            extracted.entries.get(&program_id).unwrap(),
4099            &entry
4100        ));
4101    }
4102
4103    #[test]
4104    fn test_extract_access_slot_clamped_to_root() {
4105        let (mut cache, _fork_graph) = new_test_cache_with_fork_graph(BlockRelation::Ancestor);
4106        let env = get_mock_program_runtime_environment();
4107        let program_id = Pubkey::new_unique();
4108        let entry = new_test_entry_with_owner(
4109            100,
4110            ProgramCacheEntryOwner::LoaderV3,
4111            new_loaded_entry(env.clone()),
4112        );
4113        cache.assign_program(&env, program_id, 100, Arc::clone(&entry));
4114
4115        let batch_slot = 200;
4116        for root_slot in [0, 150, batch_slot] {
4117            cache.latest_root_slot = root_slot;
4118
4119            let mut search_for = vec![ProgramToLoad {
4120                program_id: &program_id,
4121                loader: ProgramCacheEntryOwner::LoaderV3,
4122                deployment_slot: 100,
4123            }];
4124            let mut extracted = ProgramCacheForTxBatch::new(batch_slot);
4125            cache.extract(&mut search_for, &mut extracted, &env, true, true);
4126
4127            assert!(search_for.is_empty());
4128            assert_eq!(entry.latest_access_slot.load(Ordering::Relaxed), root_slot);
4129        }
4130    }
4131
4132    #[test]
4133    fn test_unloaded() {
4134        let mut cache = ProgramCache::<TestForkGraph>::new(0);
4135        let env = get_mock_program_runtime_environment();
4136        for program_cache_entry_type in [
4137            ProgramCacheEntryType::Closed,
4138            ProgramCacheEntryType::Builtin(BuiltinProgram::new_mock()),
4139        ] {
4140            let entry = Arc::new(ProgramCacheEntry {
4141                program: program_cache_entry_type,
4142                account_owner: ProgramCacheEntryOwner::LoaderV2,
4143                deployment_slot: 0,
4144                stats: Arc::default(),
4145                latest_access_slot: AtomicU64::default(),
4146            });
4147            assert!(entry.to_unloaded().is_none());
4148
4149            // Check that unload_program_entry() does nothing for this entry
4150            let program_id = Pubkey::new_unique();
4151            cache.assign_program(&env, program_id, entry.deployment_slot, entry.clone());
4152            cache.unload_program_entry(program_id, &entry);
4153            assert_eq!(cache.get_slot_versions_for_tests(&program_id).len(), 1);
4154            assert!(cache.stats.evictions.is_empty());
4155        }
4156
4157        let stats = ProgramStatistics {
4158            uses: 3.into(),
4159            ..Default::default()
4160        };
4161        let entry = new_test_entry_with_usage(1, stats);
4162        let unloaded_entry = entry.to_unloaded().unwrap();
4163        assert_eq!(unloaded_entry.deployment_slot, 1);
4164        assert_eq!(unloaded_entry.effective_slot(), 2);
4165        assert_eq!(unloaded_entry.latest_access_slot.load(Ordering::Relaxed), 1);
4166        assert_eq!(unloaded_entry.stats.uses.load(Ordering::Relaxed), 3);
4167
4168        // Check that unload_program_entry() does its work
4169        let program_id = Pubkey::new_unique();
4170        cache.assign_program(&env, program_id, entry.deployment_slot, entry.clone());
4171        cache.unload_program_entry(program_id, &entry);
4172        assert!(cache.stats.evictions.contains_key(&program_id));
4173    }
4174
4175    #[test]
4176    fn test_fork_prune_find_first_ancestor() {
4177        let mut cache = ProgramCache::<TestForkGraphSpecific>::new(0);
4178        let env = get_mock_program_runtime_environment();
4179
4180        // Fork graph created for the test
4181        //                   0
4182        //                 /   \
4183        //                10    5
4184        //                |
4185        //                20
4186
4187        // Deploy program on slot 0, and slot 5.
4188        // Prune the fork that has slot 5. The cache should still have the program
4189        // deployed at slot 0.
4190        let mut fork_graph = TestForkGraphSpecific::default();
4191        fork_graph.insert_fork(&[0, 10, 20]);
4192        fork_graph.insert_fork(&[0, 5]);
4193        let fork_graph = Arc::new(RwLock::new(fork_graph));
4194        cache.set_fork_graph(Arc::downgrade(&fork_graph));
4195
4196        let program1 = Pubkey::new_unique();
4197        cache.assign_program(&env, program1, 0, new_test_entry(0));
4198        cache.assign_program(&env, program1, 5, new_test_entry(5));
4199
4200        cache.prune(10, None, &fork_graph.read().unwrap());
4201
4202        let keys = &[program1];
4203        let mut missing = get_entries_to_load(&cache, 20, keys);
4204        let mut extracted = ProgramCacheForTxBatch::new(20);
4205        cache.extract(&mut missing, &mut extracted, &env, true, true);
4206
4207        // The cache should have the program deployed at slot 0
4208        assert_eq!(
4209            extracted
4210                .find(&program1)
4211                .expect("Did not find the program")
4212                .deployment_slot,
4213            0
4214        );
4215    }
4216
4217    #[test]
4218    fn test_prune_by_deployment_slot() {
4219        let mut cache = ProgramCache::<TestForkGraphSpecific>::new(0);
4220        let env = get_mock_program_runtime_environment();
4221
4222        // Fork graph created for the test
4223        //                   0
4224        //                 /   \
4225        //                10    5
4226        //                |
4227        //                20
4228
4229        // Deploy program on slot 0, and slot 5.
4230        // Prune the fork that has slot 5. The cache should still have the program
4231        // deployed at slot 0.
4232        let mut fork_graph = TestForkGraphSpecific::default();
4233        fork_graph.insert_fork(&[0, 10, 20]);
4234        fork_graph.insert_fork(&[0, 5, 6]);
4235        let fork_graph = Arc::new(RwLock::new(fork_graph));
4236        cache.set_fork_graph(Arc::downgrade(&fork_graph));
4237
4238        let program1 = Pubkey::new_unique();
4239        cache.assign_program(&env, program1, 0, new_test_entry(0));
4240        cache.assign_program(&env, program1, 5, new_test_entry(5));
4241
4242        let program2 = Pubkey::new_unique();
4243        cache.assign_program(&env, program2, 10, new_test_entry(10));
4244
4245        let keys = &[program1, program2];
4246        let mut missing = get_entries_to_load(&cache, 20, keys);
4247        let mut extracted = ProgramCacheForTxBatch::new(20);
4248        cache.extract(&mut missing, &mut extracted, &env, true, true);
4249        assert!(match_slot(&extracted, &program1, 0, 20));
4250        assert!(match_slot(&extracted, &program2, 10, 20));
4251
4252        let mut missing = get_entries_to_load(&cache, 6, keys);
4253        assert!(match_missing(&missing, &program2, false));
4254        let mut extracted = ProgramCacheForTxBatch::new(6);
4255        cache.extract(&mut missing, &mut extracted, &env, true, true);
4256        assert!(match_slot(&extracted, &program1, 5, 6));
4257
4258        // Pruning slot 5 will remove program1 entry deployed at slot 5.
4259        // On fork chaining from slot 5, the entry deployed at slot 0 will become visible.
4260        cache.prune_by_deployment_slot(5);
4261
4262        let mut missing = get_entries_to_load(&cache, 20, keys);
4263        let mut extracted = ProgramCacheForTxBatch::new(20);
4264        cache.extract(&mut missing, &mut extracted, &env, true, true);
4265        assert!(match_slot(&extracted, &program1, 0, 20));
4266        assert!(match_slot(&extracted, &program2, 10, 20));
4267
4268        let mut missing = get_entries_to_load(&cache, 6, keys);
4269        assert!(match_missing(&missing, &program2, false));
4270        let mut extracted = ProgramCacheForTxBatch::new(6);
4271        cache.extract(&mut missing, &mut extracted, &env, true, true);
4272        assert!(match_slot(&extracted, &program1, 0, 6));
4273
4274        // Pruning slot 10 will remove program2 entry deployed at slot 10.
4275        // As there is no other entry for program2, extract() will return it as missing.
4276        cache.prune_by_deployment_slot(10);
4277
4278        let mut missing = get_entries_to_load(&cache, 20, keys);
4279        assert!(match_missing(&missing, &program2, false));
4280        let mut extracted = ProgramCacheForTxBatch::new(20);
4281        cache.extract(&mut missing, &mut extracted, &env, true, true);
4282        assert!(match_slot(&extracted, &program1, 0, 20));
4283    }
4284}