Skip to main content

solana_program_runtime/program_cache/
tx_batch.rs

1use {
2    crate::program_cache::entry::ProgramCacheEntry, solana_clock::Slot, solana_pubkey::Pubkey,
3    solana_svm_type_overrides::sync::Arc, std::collections::HashMap,
4};
5
6/// Local view into [ProgramCache] which was extracted for a specific TX batch.
7///
8/// This isolation enables the global [ProgramCache] to continue to evolve (e.g. evictions),
9/// while the TX batch is guaranteed it will continue to find all the programs it requires.
10/// For program management instructions this also buffers them until their transaction succeeds,
11/// at which point they are merged into the batch's own entries.
12///
13/// [ProgramCache]: crate::program_cache::global::ProgramCache
14#[derive(Clone, Debug, Default)]
15pub struct ProgramCacheForTxBatch {
16    /// K: The program ID
17    /// V: A cached program entry valid only for the batch
18    entries: HashMap<Pubkey, Arc<ProgramCacheEntry>>,
19    /// Program entries modified during the transaction batch.
20    ///
21    /// These are buffered separately in case a transaction fails, but one of
22    /// its earlier instructions has modified a program.
23    ///
24    /// It is folded into the primary index after the transaction is confirmed
25    /// to succeed.
26    modified_entries: HashMap<Pubkey, Arc<ProgramCacheEntry>>,
27    /// The slot of this cache's corresponding transaction batch.
28    slot: Slot,
29    /// Whether any programs were merged into the primary index.
30    merged_modified: bool,
31}
32
33impl ProgramCacheForTxBatch {
34    pub fn new(slot: Slot) -> Self {
35        Self {
36            entries: HashMap::new(),
37            modified_entries: HashMap::new(),
38            slot,
39            merged_modified: false,
40        }
41    }
42
43    pub(super) fn len(&self) -> usize {
44        self.entries.len()
45    }
46
47    pub fn slot(&self) -> Slot {
48        self.slot
49    }
50
51    pub fn merged_modified(&self) -> bool {
52        self.merged_modified
53    }
54
55    /// Refill the cache with a single entry. It's typically called during transaction loading, and
56    /// transaction processing (for program management instructions).
57    /// It replaces the existing entry (if any) with the provided entry.
58    pub fn replenish(&mut self, key: Pubkey, entry: Arc<ProgramCacheEntry>) {
59        self.entries.insert(key, entry);
60    }
61
62    /// Store an entry in `modified_entries` for a program modified during the
63    /// transaction batch.
64    pub fn store_modified_entry(&mut self, key: Pubkey, entry: Arc<ProgramCacheEntry>) {
65        self.modified_entries.insert(key, entry);
66    }
67
68    /// Drain the program cache's modified entries, returning the owned
69    /// collection.
70    pub fn drain_modified_entries(&mut self) -> HashMap<Pubkey, Arc<ProgramCacheEntry>> {
71        std::mem::take(&mut self.modified_entries)
72    }
73
74    pub fn find(&self, key: &Pubkey) -> Option<Arc<ProgramCacheEntry>> {
75        // First lookup the cache of the programs modified by the current
76        // transaction. If not found, lookup the cache of the cache of the
77        // programs that are loaded for the transaction batch.
78        self.modified_entries
79            .get(key)
80            .or_else(|| self.entries.get(key))
81            .map(|entry| {
82                if entry.is_implicit_delay_visibility_tombstone(self.slot) {
83                    // Found a program entry on the current fork, but it's not effective
84                    // yet. It indicates that the program has delayed visibility. Return
85                    // the tombstone to reflect that.
86                    Arc::new(ProgramCacheEntry::new_delay_visibility_tombstone(
87                        entry.deployment_slot,
88                        entry.account_owner,
89                        Arc::clone(&entry.stats),
90                    ))
91                } else {
92                    entry.clone()
93                }
94            })
95    }
96
97    /// Merge the provided entries into the primary index.
98    pub fn merge(&mut self, entries: &HashMap<Pubkey, Arc<ProgramCacheEntry>>) {
99        entries.iter().for_each(|(key, entry)| {
100            self.merged_modified = true;
101            self.replenish(*key, entry.clone());
102        })
103    }
104
105    /// Remove an entry from the `entries` list.
106    /// Note: DOES NOT remove modified entries!
107    pub fn remove_entry(&mut self, key: &Pubkey) {
108        self.entries.remove(key);
109    }
110}
111
112#[cfg(any(test, feature = "dev-context-only-utils"))]
113impl ProgramCacheForTxBatch {
114    pub fn is_empty(&self) -> bool {
115        self.entries.is_empty()
116    }
117
118    /// Look up `entries` directly, without the delay visibility rewrite
119    /// `find` performs, so a test can see the entry as it was stored.
120    pub fn get_entry_for_tests(&self, key: &Pubkey) -> Option<&Arc<ProgramCacheEntry>> {
121        self.entries.get(key)
122    }
123
124    pub fn set_slot_for_tests(&mut self, slot: Slot) {
125        self.slot = slot;
126    }
127}