Skip to main content

solana_program_runtime/
program_metrics.rs

1#[cfg(feature = "metrics")]
2use solana_svm_timings::ExecuteDetailsTimings;
3use {
4    crate::loaded_programs::ForkGraph,
5    log::{debug, log_enabled, trace},
6    solana_pubkey::Pubkey,
7    std::{
8        collections::HashMap,
9        sync::atomic::{AtomicU64, Ordering},
10    },
11};
12
13#[derive(Debug, Default)]
14pub struct ProgramStatistics {
15    pub uses: AtomicU64,
16
17    pub compilations: AtomicU64,
18    pub total_compilation_time_us: AtomicU64,
19    /// Exponential moving average of the compilation time.
20    pub compilation_time_ema: AtomicU64,
21
22    pub jit_invocations: AtomicU64,
23    pub total_jit_execution_time_us: AtomicU64,
24    /// Exponential moving average of the JIT execution time.
25    pub jit_execution_time_ema: AtomicU64,
26
27    pub interpreted_invocations: AtomicU64,
28    pub total_interpretation_time_us: AtomicU64,
29    /// Exponential moving average of the interpreted execution time.
30    pub interpretation_time_ema: AtomicU64,
31}
32
33/// Number of compilation observations contributing to the the [`Self::compilation_time_ema`].
34const COMPILATION_EMA_WINDOW_SIZE: u64 = 10;
35/// Number of execution observations contributing to the execution EMA stats.
36const EXECUTION_EMA_WINDOW_SIZE: u64 = 500;
37/// Track exponential moving average in scaled-up units.
38///
39/// Doing so allows to mitigate error from rounding-towards-zero we get when using integer math.
40pub(crate) const EMA_SCALE: u64 = 1_000;
41
42impl ProgramStatistics {
43    fn observe_ema<const WINDOW_SIZE: u64>(counter: &AtomicU64, duration_us: u64) {
44        let duration_ema = duration_us.saturating_mul(EMA_SCALE);
45        counter.update(Ordering::Relaxed, Ordering::Relaxed, |ema| {
46            // Exponential moving average iteratively is computed as $ema' = alpha *
47            // observation + (1 - alpha) * ema$. This works great for floating point, but we
48            // want integers. For purposes of convenience we also want to really think in terms
49            // of simple moving average window sizes as that is easier to reason about.
50            //
51            // Exponential moving average and simple moving average of window N has a rough
52            // equivalence of `alpha ≈ 2 / (N + 1)`. Slotting this into our original iterative
53            // formula:
54            //
55            // $$ ema' = 2 / (N+1) * observation + (1 - 2/(N+1)) * ema $$
56            //
57            // we get
58            //
59            // $$ ema' = (2*observation)/(N+1) + (N+1-2)*ema/(N+1) $$
60            let (numer, denom) = const { (2, 1 + WINDOW_SIZE) };
61            if ema == 0 {
62                duration_ema
63            } else {
64                let weighted_observation = duration_ema.saturating_mul(numer);
65                let previous_observations = ema.saturating_mul(denom.saturating_sub(numer));
66                weighted_observation
67                    .saturating_add(previous_observations)
68                    .checked_div(denom)
69                    .expect("unreachable: denom is >= 1")
70            }
71        });
72    }
73
74    /// Record information about JIT compilation.
75    pub fn jit_compiled(&self, duration_us: u64) {
76        let ord = Ordering::Relaxed;
77        self.compilations.fetch_add(1, ord);
78        self.total_compilation_time_us.fetch_add(duration_us, ord);
79        Self::observe_ema::<COMPILATION_EMA_WINDOW_SIZE>(&self.compilation_time_ema, duration_us);
80    }
81
82    /// Record information about JIT-compiled program having been executed.
83    pub fn jit_executed(&self, duration_us: u64) {
84        let ord = Ordering::Relaxed;
85        self.jit_invocations.fetch_add(1, ord);
86        self.total_jit_execution_time_us.fetch_add(duration_us, ord);
87        Self::observe_ema::<EXECUTION_EMA_WINDOW_SIZE>(&self.jit_execution_time_ema, duration_us);
88    }
89
90    /// Record information about program executed with the interpreter.
91    pub fn interpreter_executed(&self, duration_us: u64) {
92        let ord = Ordering::Relaxed;
93        self.interpreted_invocations.fetch_add(1, ord);
94        self.total_interpretation_time_us
95            .fetch_add(duration_us, ord);
96        Self::observe_ema::<EXECUTION_EMA_WINDOW_SIZE>(&self.interpretation_time_ema, duration_us);
97    }
98
99    pub fn merge_from(&self, other: &ProgramStatistics) {
100        let ord = Ordering::Relaxed;
101        self.uses.fetch_add(other.uses.load(ord), ord);
102        let other_compilations = other.compilations.load(ord);
103        let this_compilations = self.compilations.fetch_add(other_compilations, ord);
104        self.total_compilation_time_us
105            .fetch_add(other.total_compilation_time_us.load(ord), ord);
106        let other_jit_invocations = other.jit_invocations.load(ord);
107        let this_jit_invocations = self.jit_invocations.fetch_add(other_jit_invocations, ord);
108        self.total_jit_execution_time_us
109            .fetch_add(other.total_jit_execution_time_us.load(ord), ord);
110        let other_interpretations = other.interpreted_invocations.load(ord);
111        let this_interpretations = self
112            .interpreted_invocations
113            .fetch_add(other_interpretations, ord);
114        self.total_interpretation_time_us
115            .fetch_add(other.total_interpretation_time_us.load(ord), ord);
116        if let Some(comp_ema) = ProgramCacheStats::combined_ema::<
117            COMPILATION_EMA_WINDOW_SIZE,
118            COMPILATION_EMA_WINDOW_SIZE,
119        >(
120            &self.compilation_time_ema,
121            &other.compilation_time_ema,
122            this_compilations,
123            other_compilations,
124        ) {
125            self.compilation_time_ema.store(comp_ema, ord);
126        }
127        if let Some(exec_ema) =
128            ProgramCacheStats::combined_ema::<EXECUTION_EMA_WINDOW_SIZE, EXECUTION_EMA_WINDOW_SIZE>(
129                &self.jit_execution_time_ema,
130                &other.jit_execution_time_ema,
131                this_jit_invocations,
132                other_jit_invocations,
133            )
134        {
135            self.jit_execution_time_ema.store(exec_ema, ord);
136        }
137        if let Some(interp_ema) =
138            ProgramCacheStats::combined_ema::<EXECUTION_EMA_WINDOW_SIZE, EXECUTION_EMA_WINDOW_SIZE>(
139                &self.interpretation_time_ema,
140                &other.interpretation_time_ema,
141                this_interpretations,
142                other_interpretations,
143            )
144        {
145            self.interpretation_time_ema.store(interp_ema, ord);
146        }
147    }
148}
149
150/// Global cache statistics for [ProgramCache].
151#[derive(Debug, Default)]
152pub struct ProgramCacheStats {
153    /// a program was already in the cache
154    pub hits: AtomicU64,
155    /// a program was not found and loaded instead
156    pub misses: AtomicU64,
157    /// a compiled executable was unloaded
158    pub evictions: HashMap<Pubkey, u64>,
159    /// an unloaded program was loaded again (opposite of eviction)
160    pub reloads: AtomicU64,
161    /// a program was loaded or un/re/deployed
162    pub insertions: AtomicU64,
163    /// a program was loaded but can not be extracted on its own fork anymore
164    pub lost_insertions: AtomicU64,
165    /// a program which was already in the cache was reloaded by mistake
166    pub replacements: AtomicU64,
167    /// a program was only used once before being unloaded
168    pub one_hit_wonders: AtomicU64,
169    /// a program got pruned because it was unloaded for too long or a tombstone
170    pub prunes_stale: AtomicU64,
171    /// a program became unreachable in the fork graph because of rerooting
172    pub prunes_orphan: AtomicU64,
173    /// a program got pruned because it was not recompiled for the next epoch
174    pub prunes_environment: AtomicU64,
175    /// a program had no entries because all slot versions got pruned
176    pub empty_entries: AtomicU64,
177    /// water level of loaded entries currently cached
178    pub water_level: AtomicU64,
179}
180
181impl ProgramCacheStats {
182    pub fn reset(&mut self) {
183        *self = ProgramCacheStats::default();
184    }
185    pub fn log(&self) {
186        let hits = self.hits.load(Ordering::Relaxed);
187        let misses = self.misses.load(Ordering::Relaxed);
188        let evictions: u64 = self.evictions.values().sum();
189        let reloads = self.reloads.load(Ordering::Relaxed);
190        let insertions = self.insertions.load(Ordering::Relaxed);
191        let lost_insertions = self.lost_insertions.load(Ordering::Relaxed);
192        let replacements = self.replacements.load(Ordering::Relaxed);
193        let one_hit_wonders = self.one_hit_wonders.load(Ordering::Relaxed);
194        let prunes_stale = self.prunes_stale.load(Ordering::Relaxed);
195        let prunes_orphan = self.prunes_orphan.load(Ordering::Relaxed);
196        let prunes_environment = self.prunes_environment.load(Ordering::Relaxed);
197        let empty_entries = self.empty_entries.load(Ordering::Relaxed);
198        let water_level = self.water_level.load(Ordering::Relaxed);
199        debug!(
200            "Loaded Programs Cache Stats -- Hits: {hits}, Misses: {misses}, Evictions: \
201             {evictions}, Reloads: {reloads}, Insertions: {insertions}, Lost-Insertions: \
202             {lost_insertions}, Replacements: {replacements}, One-Hit-Wonders: {one_hit_wonders}, \
203             Prunes-Stale: {prunes_stale}, Prunes-Orphan: {prunes_orphan}, Prunes-Environment: \
204             {prunes_environment}, Empty: {empty_entries}, Water-Level: {water_level}"
205        );
206
207        if log_enabled!(log::Level::Trace) && !self.evictions.is_empty() {
208            let mut evictions = self.evictions.iter().collect::<Vec<_>>();
209            evictions.sort_by_key(|e| e.1);
210            let evictions = evictions
211                .into_iter()
212                .rev()
213                .map(|(program_id, evictions)| {
214                    format!("  {:<44}  {}", program_id.to_string(), evictions)
215                })
216                .collect::<Vec<_>>();
217            let evictions = evictions.join("\n");
218            trace!(
219                "Eviction Details:\n  {:<44}  {}\n{}",
220                "Program", "Count", evictions
221            );
222        }
223    }
224
225    fn combined_ema<const WINDOW1: u64, const WINDOW2: u64>(
226        into_ema: &AtomicU64,
227        from_ema: &AtomicU64,
228        into_observations: u64,
229        from_observations: u64,
230    ) -> Option<u64> {
231        // This is a mild non-sense, but there is no good mathematically rigorous way to merge
232        // two independent EMA trackers AFAICT and this is the best I (nagisa) could come up
233        // with…
234        let other_ema_val = from_ema.load(Ordering::Relaxed);
235        let other_ema_weight = std::cmp::max(WINDOW1, from_observations);
236        let this_ema_val = into_ema.load(Ordering::Relaxed);
237        let this_ema_weight = std::cmp::max(WINDOW2, into_observations);
238        other_ema_val
239            .wrapping_mul(other_ema_weight)
240            .wrapping_add(this_ema_val.wrapping_mul(this_ema_weight))
241            .checked_div(other_ema_weight.wrapping_add(this_ema_weight))
242    }
243}
244
245#[cfg(feature = "metrics")]
246/// Time measurements for loading a single [ProgramCacheEntry].
247#[derive(Debug, Default)]
248pub struct LoadProgramMetrics {
249    /// Program address, but as text
250    pub program_id: String,
251    /// Microseconds it took to `create_program_runtime_environment`
252    pub register_syscalls_us: u64,
253    /// Microseconds it took to `Executable::<InvokeContext>::load`
254    pub load_elf_us: u64,
255    /// Microseconds it took to `executable.verify::<RequisiteVerifier>`
256    pub verify_code_us: u64,
257    /// Microseconds it took to `executable.jit_compile`
258    pub jit_compile_us: u64,
259}
260
261#[cfg(feature = "metrics")]
262impl LoadProgramMetrics {
263    pub fn submit_datapoint(&self, timings: &mut ExecuteDetailsTimings) {
264        timings.create_executor_register_syscalls_us += self.register_syscalls_us;
265        timings.create_executor_load_elf_us += self.load_elf_us;
266        timings.create_executor_verify_code_us += self.verify_code_us;
267        timings.create_executor_jit_compile_us += self.jit_compile_us;
268    }
269}
270
271impl<FG: ForkGraph> crate::loaded_programs::ProgramCache<FG> {
272    /// Log per-entry statistics for each entry in the global cache.
273    #[cfg(feature = "dev-context-only-utils")]
274    pub fn output_entry_stats(&self) {
275        use {crate::program_cache_entry::ProgramCacheEntryType, std::fmt::Write};
276        // The entry stats can become very verbose after some runtime. Rather than dumping them
277        // to the log, we'd rather maintain a continuously updated file instead...
278        static ENTRY_STAT_PATH: std::sync::LazyLock<Option<std::ffi::OsString>> =
279            std::sync::LazyLock::new(|| std::env::var_os("AGAVE_PROGRAM_CACHE_ENTRY_STATS_PATH"));
280        let Some(stat_path) = &*ENTRY_STAT_PATH else {
281            log::trace!("Set AGAVE_PROGRAM_CACHE_ENTRY_STATS_PATH to write per-entry stats");
282            return;
283        };
284        let mut output = String::new();
285        let entries = self.get_flattened_entries_for_tests();
286        for (addr, entry) in entries {
287            let entry_ty = match &entry.program {
288                ProgramCacheEntryType::FailedVerification(_) => "FailedVerification",
289                ProgramCacheEntryType::Closed => "Closed",
290                ProgramCacheEntryType::DelayVisibility => "DelayVisibility",
291                ProgramCacheEntryType::Unloaded(_) => "Unloaded",
292                ProgramCacheEntryType::Builtin(_) => "Builtin",
293                #[cfg(not(all(not(target_os = "windows"), target_arch = "x86_64")))]
294                ProgramCacheEntryType::Loaded(_) => "Loaded",
295                #[cfg(all(not(target_os = "windows"), target_arch = "x86_64"))]
296                ProgramCacheEntryType::Loaded(executable) => {
297                    if executable.get_compiled_program().is_some() {
298                        "JitCompiled"
299                    } else {
300                        "Loaded"
301                    }
302                }
303            };
304            let stats = &entry.stats;
305            let uses = stats.uses.load(Ordering::Relaxed);
306            let compiles = stats.compilations.load(Ordering::Relaxed);
307            let comptime = stats.total_compilation_time_us.load(Ordering::Relaxed);
308            let comptime_ema = stats.compilation_time_ema.load(Ordering::Relaxed) / EMA_SCALE;
309            let invokes = stats.jit_invocations.load(Ordering::Relaxed);
310            let jittime = stats.total_jit_execution_time_us.load(Ordering::Relaxed);
311            let jittime_ema = stats.jit_execution_time_ema.load(Ordering::Relaxed) / EMA_SCALE;
312            let interps = stats.interpreted_invocations.load(Ordering::Relaxed);
313            let interptime = stats.total_interpretation_time_us.load(Ordering::Relaxed);
314            let interpema = stats.interpretation_time_ema.load(Ordering::Relaxed) / EMA_SCALE;
315            let _ = writeln!(
316                &mut output,
317                "{addr},{entry_ty},{uses},{compiles},{comptime},{comptime_ema},{invokes},\
318                 {jittime},{jittime_ema},{interps},{interptime},{interpema}"
319            );
320        }
321        if let Err(e) = std::fs::write(stat_path, output) {
322            log::info!("Writing entry stats to {stat_path:?} failed: {e:?}");
323        } else {
324            log::debug!("Entry stats written to {stat_path:?}");
325        }
326    }
327}