Skip to main content

solana_program_runtime/program_cache/
entry.rs

1#[cfg(feature = "metrics")]
2use crate::program_cache::metrics::LoadProgramMetrics;
3use {
4    crate::{
5        invoke_context::{BuiltinFunctionRegisterer, InvokeContext},
6        program_cache::{
7            DELAY_VISIBILITY_SLOT_OFFSET, env::ProgramRuntimeEnvironment,
8            metrics::ProgramStatistics, owner::ProgramCacheEntryOwner,
9        },
10    },
11    solana_clock::Slot,
12    solana_pubkey::Pubkey,
13    solana_sbpf::{elf::Executable, program::BuiltinProgram, verifier::RequisiteVerifier},
14    solana_svm_type_overrides::sync::{
15        Arc,
16        atomic::{AtomicU64, Ordering},
17    },
18};
19
20/*
21    The possible ProgramCacheEntryType transitions:
22
23    DelayVisibility is special in that it is never stored in the cache.
24    It is only returned by ProgramCacheForTxBatch::find() when a Loaded entry
25    is encountered which is not effective yet.
26
27    Builtin re/deployment:
28    - Empty => Builtin in TransactionBatchProcessor::add_builtin
29    - Builtin => Builtin in TransactionBatchProcessor::add_builtin
30
31    Un/re/deployment (with delay and cooldown):
32    - Empty / Closed => Unloaded in UpgradeableLoaderInstruction::DeployWithMaxDataLen
33    - Loaded / FailedVerification => Loaded in UpgradeableLoaderInstruction::Upgrade
34    - Loaded / FailedVerification => Closed in UpgradeableLoaderInstruction::Close
35
36    Loader migration:
37    - Closed => Closed (in the same slot)
38    - FailedVerification => FailedVerification (with different account_owner)
39    - Loaded => Loaded (with different account_owner)
40
41    Eviction and unloading (in the same slot):
42    - Unloaded => Loaded / FailedVerification in ProgramCache::assign_program
43    - Loaded => Unloaded in ProgramCache::unload_program_entry
44
45    At epoch boundary (when feature set and environment changes):
46    - Loaded => FailedVerification in Bank::_new_from_parent
47    - FailedVerification => Loaded in Bank::_new_from_parent
48
49    Through pruning:
50    - Closed / Unloaded / Loaded / Builtin => Empty in ProgramCache::prune (when on orphan fork or overshadowed on the rooted fork)
51    - FailedVerification / Unloaded / Loaded => Unloaded in ProgramCache::prune (when on outdated program runtime environment)
52*/
53
54/// Actual payload of [ProgramCacheEntry].
55#[derive(Default)]
56pub enum ProgramCacheEntryType {
57    /// Tombstone for programs which currently do not pass the verifier but could if the feature set changed.
58    FailedVerification(ProgramRuntimeEnvironment),
59    /// Tombstone for programs that were either explicitly closed or never deployed.
60    ///
61    /// It's also used for accounts belonging to program loaders, that don't actually contain program code (e.g. buffer accounts for LoaderV3 programs).
62    #[default]
63    Closed,
64    /// Tombstone for programs which have recently been modified but the new version is not visible yet.
65    DelayVisibility,
66    /// Valid program account, but not relocated, verified or compiled.
67    ///
68    /// It continues to track usage statistics even when the executable of the program is evicted from memory.
69    Unloaded(ProgramRuntimeEnvironment),
70    /// Verified program.
71    ///
72    /// It may or may not be JIT compiled.
73    Loaded(Executable<InvokeContext<'static, 'static>>),
74    /// A built-in program which is not stored on-chain but backed into and distributed with the validator
75    Builtin(BuiltinProgram<InvokeContext<'static, 'static>>),
76}
77
78impl std::fmt::Debug for ProgramCacheEntryType {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        f.debug_struct(match self {
81            ProgramCacheEntryType::FailedVerification(_) => {
82                "ProgramCacheEntryType::FailedVerification"
83            }
84            ProgramCacheEntryType::Closed => "ProgramCacheEntryType::Closed",
85            ProgramCacheEntryType::DelayVisibility => "ProgramCacheEntryType::DelayVisibility",
86            ProgramCacheEntryType::Unloaded(_) => "ProgramCacheEntryType::Unloaded",
87            ProgramCacheEntryType::Loaded(_) => "ProgramCacheEntryType::Loaded",
88            ProgramCacheEntryType::Builtin(_) => "ProgramCacheEntryType::Builtin",
89        })
90        .finish()
91    }
92}
93
94impl ProgramCacheEntryType {
95    /// Returns a reference to its environment if it has one
96    pub fn get_environment(&self) -> Option<&ProgramRuntimeEnvironment> {
97        match self {
98            ProgramCacheEntryType::Loaded(program) => {
99                Some(ProgramRuntimeEnvironment::from_ref(program.get_loader()))
100            }
101            ProgramCacheEntryType::FailedVerification(env)
102            | ProgramCacheEntryType::Unloaded(env) => Some(env),
103            _ => None,
104        }
105    }
106}
107
108/// Holds a program version at a specific address and on a specific slot / fork.
109///
110/// It contains the actual program in [ProgramCacheEntryType] and a bunch of meta-data.
111#[derive(Default)]
112pub struct ProgramCacheEntry {
113    /// The program of this entry
114    pub program: ProgramCacheEntryType,
115    /// The loader of this entry
116    pub account_owner: ProgramCacheEntryOwner,
117    /// Slot in which the program was (re)deployed
118    pub deployment_slot: Slot,
119    /// How often this entry was used by a transaction
120    pub stats: Arc<ProgramStatistics>,
121    pub latest_access_slot: AtomicU64,
122}
123
124impl std::fmt::Debug for ProgramCacheEntry {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        f.debug_struct("ProgramCacheEntry")
127            .field("slot", &self.deployment_slot)
128            .field(
129                "env",
130                &self
131                    .program
132                    .get_environment()
133                    .map(|env| Arc::as_ptr(env))
134                    .unwrap_or(std::ptr::null()),
135            )
136            .field("type", &self.program)
137            .finish()
138    }
139}
140
141#[cfg(feature = "dev-context-only-utils")]
142impl PartialEq for ProgramCacheEntry {
143    fn eq(&self, other: &Self) -> bool {
144        self.deployment_slot == other.deployment_slot
145            && self.account_owner == other.account_owner
146            && std::mem::discriminant(&self.program) == std::mem::discriminant(&other.program)
147    }
148}
149
150impl ProgramCacheEntry {
151    /// Creates a loaded user program
152    pub fn load(
153        loader_key: &Pubkey,
154        program_runtime_environment: ProgramRuntimeEnvironment,
155        deployment_slot: Slot,
156        elf_bytes: &[u8],
157        #[cfg(feature = "metrics")] metrics: &mut LoadProgramMetrics,
158    ) -> Result<Self, Box<dyn std::error::Error>> {
159        let entry_stats = ProgramStatistics::default();
160        #[cfg(feature = "metrics")]
161        let load_elf_time = solana_svm_measure::measure::Measure::start("load_elf_time");
162        let executable = Executable::load(elf_bytes, Arc::clone(&*program_runtime_environment))?;
163
164        #[cfg(feature = "metrics")]
165        {
166            metrics.load_elf_us = load_elf_time.end_as_us();
167        }
168
169        #[cfg(feature = "metrics")]
170        let verify_code_time = solana_svm_measure::measure::Measure::start("verify_code_time");
171        executable.verify::<RequisiteVerifier>()?;
172        #[cfg(feature = "metrics")]
173        {
174            metrics.verify_code_us = verify_code_time.end_as_us();
175        }
176
177        #[cfg(all(not(target_os = "windows"), target_arch = "x86_64"))]
178        {
179            let jit_compile_time = solana_svm_measure::measure::Measure::start("jit_compile_time");
180            executable.jit_compile()?;
181            let jit_compile_time = jit_compile_time.end_as_us();
182            entry_stats.jit_compiled(jit_compile_time);
183            #[cfg(feature = "metrics")]
184            {
185                metrics.jit_compile_us = jit_compile_time;
186            }
187        }
188
189        Ok(Self {
190            deployment_slot,
191            account_owner: ProgramCacheEntryOwner::try_from(loader_key).unwrap(),
192            program: ProgramCacheEntryType::Loaded(executable),
193            stats: entry_stats.into(),
194            latest_access_slot: AtomicU64::new(0),
195        })
196    }
197
198    pub fn new_unloaded(
199        deployment_slot: Slot,
200        account_owner: ProgramCacheEntryOwner,
201        program_runtime_environment: ProgramRuntimeEnvironment,
202    ) -> Self {
203        Self {
204            program: ProgramCacheEntryType::Unloaded(program_runtime_environment),
205            account_owner,
206            deployment_slot,
207            stats: Arc::default(),
208            latest_access_slot: AtomicU64::new(deployment_slot),
209        }
210    }
211
212    pub fn to_unloaded(&self) -> Option<Self> {
213        let environment = ProgramRuntimeEnvironment::clone(self.program.get_environment()?);
214        Some(Self {
215            program: ProgramCacheEntryType::Unloaded(environment),
216            account_owner: self.account_owner,
217            deployment_slot: self.deployment_slot,
218            stats: Arc::clone(&self.stats),
219            latest_access_slot: AtomicU64::new(self.latest_access_slot.load(Ordering::Relaxed)),
220        })
221    }
222
223    /// Creates a new built-in program
224    pub fn new_builtin(register_fn: BuiltinFunctionRegisterer) -> Self {
225        let mut program = BuiltinProgram::new_builtin();
226        register_fn(&mut program, "entrypoint").unwrap();
227        Self {
228            deployment_slot: 0, // Deployment slot is always zero
229            account_owner: ProgramCacheEntryOwner::NativeLoader,
230            program: ProgramCacheEntryType::Builtin(program),
231            stats: Arc::default(),
232            latest_access_slot: AtomicU64::new(0),
233        }
234    }
235
236    pub fn new_failed_verification_tombstone(
237        deployment_slot: Slot,
238        account_owner: ProgramCacheEntryOwner,
239        program_runtime_environment: ProgramRuntimeEnvironment,
240    ) -> Self {
241        Self {
242            program: ProgramCacheEntryType::FailedVerification(program_runtime_environment),
243            account_owner,
244            deployment_slot,
245            stats: Arc::default(),
246            latest_access_slot: AtomicU64::new(0),
247        }
248    }
249
250    pub fn new_closed_tombstone(
251        deployment_slot: Slot,
252        account_owner: ProgramCacheEntryOwner,
253    ) -> Self {
254        Self {
255            program: ProgramCacheEntryType::Closed,
256            account_owner,
257            deployment_slot,
258            stats: Arc::default(),
259            latest_access_slot: AtomicU64::new(0),
260        }
261    }
262
263    pub fn new_delay_visibility_tombstone(
264        deployment_slot: Slot,
265        account_owner: ProgramCacheEntryOwner,
266        stats: Arc<ProgramStatistics>,
267    ) -> Self {
268        Self {
269            program: ProgramCacheEntryType::DelayVisibility,
270            account_owner,
271            deployment_slot,
272            stats,
273            latest_access_slot: AtomicU64::new(0),
274        }
275    }
276
277    pub fn is_tombstone(&self) -> bool {
278        matches!(
279            self.program,
280            ProgramCacheEntryType::FailedVerification(_)
281                | ProgramCacheEntryType::Closed
282                | ProgramCacheEntryType::DelayVisibility
283        )
284    }
285
286    pub(crate) fn is_implicit_delay_visibility_tombstone(&self, slot: Slot) -> bool {
287        slot >= self.deployment_slot && slot < self.effective_slot()
288    }
289
290    pub fn is_unloaded(&self) -> bool {
291        matches!(self.program, ProgramCacheEntryType::Unloaded(_))
292    }
293
294    pub fn effective_slot(&self) -> Slot {
295        match self.program {
296            ProgramCacheEntryType::Closed
297            | ProgramCacheEntryType::DelayVisibility
298            | ProgramCacheEntryType::FailedVerification(_)
299            | ProgramCacheEntryType::Builtin(_) => self.deployment_slot,
300            ProgramCacheEntryType::Unloaded(_) | ProgramCacheEntryType::Loaded(_) => self
301                .deployment_slot
302                .saturating_add(DELAY_VISIBILITY_SLOT_OFFSET),
303        }
304    }
305
306    pub fn update_access_slot(&self, slot: Slot) {
307        let _ = self.latest_access_slot.fetch_max(slot, Ordering::Relaxed);
308    }
309
310    /// Compute a retention score.
311    ///
312    /// Eviction uses an adapted GDSF scheme which incorporates frequency, recovery cost
313    /// (recompilation) and time-based decay.
314    ///
315    /// How hard should we try to retain this entry. Higher number -> retention more likely.
316    pub fn retention_score(&self) -> u64 {
317        let last_access = self.latest_access_slot.load(Ordering::Relaxed);
318        let recovery_cost = self.stats.compilation_time_ema.load(Ordering::Relaxed);
319        let frequency = self.stats.uses.load(Ordering::Relaxed);
320        retention_score(last_access, recovery_cost, frequency)
321    }
322}
323
324/// See [`ProgramCacheEntry::retention_score`].
325pub(crate) const fn retention_score(last_access: u64, recovery_cost: u64, frequency: u64) -> u64 {
326    // Traditionally GDSF uses the following logic:
327    //
328    // on_access:
329    //   entry.frequency += 1
330    //   entry.H := cache.L + (entry.cost * entry.frequency) / entry.size
331    //
332    // on_eviction:
333    //   victim = pick_victim_minimizing_H()
334    //   cache.L := victim.H
335    //
336    // It achieves decay by virtue of L increasing over time (and therefore the “value” of
337    // stored score of each entry decreasing over time.) Entry recovery and frequency, as well
338    // as size are otherwise also accounted for by them inflating the overall score by a bit.
339    //
340    // We adapt this algorithm slightly: we already have a kind of `L` – access slot. It does
341    // not include the weight of the evicted entry as the original algorithm does, that is
342    // *probably* fine (the author has not done any empirical experiments to verify it it
343    // actually matters.)
344    //
345    // Additionally we ignore the size component altogether as irrelevant and instead of
346    // applying entry weight linearly, we use a `log_2`. We can't use plain `weight*frequency`
347    // as the most heavily used entries would never ever get evicted after just some runtime,
348    // even if they're no longer used. With `log_2` weight and frequency can contribute to
349    // up-to 128 slots of "bonus" towards their retention compared to rarely used peers.
350    //
351    // Feel free to adjust the specific formulae used.
352    let weight = (recovery_cost as u128).wrapping_mul(frequency as u128);
353    let weight_log = u128::BITS.wrapping_sub(weight.leading_zeros());
354    last_access.saturating_add(weight_log as u64)
355}
356
357#[cfg(test)]
358pub(crate) fn new_loaded_entry(env: ProgramRuntimeEnvironment) -> ProgramCacheEntryType {
359    use std::{fs::File, io::Read};
360
361    let mut elf = Vec::new();
362    File::open("../programs/bpf_loader/test_elfs/out/noop_aligned.so")
363        .unwrap()
364        .read_to_end(&mut elf)
365        .unwrap();
366    let executable = Executable::load(&elf, Arc::clone(&*env)).unwrap();
367    ProgramCacheEntryType::Loaded(executable)
368}
369
370#[cfg(test)]
371pub(crate) fn new_test_entry_with_usage(
372    deployment_slot: Slot,
373    stats: ProgramStatistics,
374) -> Arc<ProgramCacheEntry> {
375    use crate::program_cache::env::get_mock_program_runtime_environment;
376
377    Arc::new(ProgramCacheEntry {
378        program: new_loaded_entry(get_mock_program_runtime_environment()),
379        account_owner: ProgramCacheEntryOwner::LoaderV2,
380        deployment_slot,
381        stats: Arc::new(stats),
382        latest_access_slot: AtomicU64::new(deployment_slot),
383    })
384}
385
386#[cfg(test)]
387mod tests {
388    use {
389        super::new_test_entry_with_usage,
390        crate::program_cache::metrics::ProgramStatistics,
391        std::sync::atomic::{AtomicU64, Ordering},
392    };
393
394    #[test]
395    fn test_retention_score_decay_horizon() {
396        let stats = ProgramStatistics {
397            uses: AtomicU64::new(u64::MAX),
398            compilation_time_ema: AtomicU64::new(u64::MAX),
399            ..Default::default()
400        };
401        let program = new_test_entry_with_usage(0, stats);
402        program.update_access_slot(1);
403        assert!(
404            dbg!(program.retention_score()) <= 129,
405            "retention score should remain within sensible boundaries even for very frequently \
406             used entries."
407        );
408    }
409
410    #[test]
411    fn test_retention_score_frequency_preference() {
412        let stats = ProgramStatistics {
413            uses: AtomicU64::new(16),
414            compilation_time_ema: AtomicU64::new(1),
415            ..Default::default()
416        };
417        let program = new_test_entry_with_usage(10, stats);
418        program.update_access_slot(15);
419        let less_used_retention_score = program.retention_score();
420        program.stats.uses.fetch_max(1024, Ordering::Relaxed);
421        let more_used_retention_score = program.retention_score();
422        assert!(
423            less_used_retention_score > 15,
424            "frequency should count for entry retention score"
425        );
426        assert!(
427            dbg!(more_used_retention_score) > dbg!(less_used_retention_score),
428            "retention score should prefer evicting less used entry over the more used one if \
429             possible"
430        );
431    }
432
433    #[test]
434    fn test_retention_score_recovery_time_preference() {
435        let stats = ProgramStatistics {
436            uses: AtomicU64::new(1),
437            compilation_time_ema: AtomicU64::new(1000),
438            ..Default::default()
439        };
440        let program = new_test_entry_with_usage(10, stats);
441        program.update_access_slot(15);
442        let cheaper_to_compile_score = program.retention_score();
443        program
444            .stats
445            .compilation_time_ema
446            .fetch_max(2000, Ordering::Relaxed);
447        let more_expensive_to_compile_score = program.retention_score();
448        assert!(
449            cheaper_to_compile_score > 15,
450            "compile time should count for entry retention score"
451        );
452        assert!(
453            dbg!(more_expensive_to_compile_score) > dbg!(cheaper_to_compile_score),
454            "retention score should prefer evicting cheaper-to-compile entries"
455        );
456    }
457
458    #[test]
459    fn test_retention_weight_metric_does_not_outweight_smaller_metric() {
460        // Compilation time generally stays in the scale of 4 digits, while the uses counter can
461        // become many millions. Neither should overshadow other too much.
462        let stats = ProgramStatistics {
463            uses: AtomicU64::new(100_000_000),
464            compilation_time_ema: AtomicU64::new(1000),
465            ..Default::default()
466        };
467        let program = new_test_entry_with_usage(10, stats);
468        program.update_access_slot(15);
469        let previous_score = program.retention_score();
470        program
471            .stats
472            .compilation_time_ema
473            .fetch_max(2000, Ordering::Relaxed);
474        let new_score = program.retention_score();
475        assert!(
476            dbg!(previous_score) != dbg!(new_score),
477            "retention weight components shouldn't overshadow the other due to scale differences"
478        );
479    }
480}