Skip to main content

solana_program_runtime/program_cache/
global.rs

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