solana_program_runtime/program_cache/
entry.rs1#[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#[derive(Default)]
56pub enum ProgramCacheEntryType {
57 FailedVerification(ProgramRuntimeEnvironment),
59 #[default]
63 Closed,
64 DelayVisibility,
66 Unloaded(ProgramRuntimeEnvironment),
70 Loaded(Executable<InvokeContext<'static, 'static>>),
74 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 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#[derive(Default)]
112pub struct ProgramCacheEntry {
113 pub program: ProgramCacheEntryType,
115 pub account_owner: ProgramCacheEntryOwner,
117 pub deployment_slot: Slot,
119 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 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 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, 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 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
324pub(crate) const fn retention_score(last_access: u64, recovery_cost: u64, frequency: u64) -> u64 {
326 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 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}