Skip to main content

icydb_core/obs/metrics/
mod.rs

1//! Runtime metrics are update-only by contract.
2//! Query-side instrumentation is intentionally not surfaced by `report`, so
3//! query metrics are non-existent by design under IC query semantics.
4
5use candid::CandidType;
6use canic_cdk::utils::time::now_millis;
7use serde::{Deserialize, Serialize};
8use std::{cell::RefCell, cmp::Ordering, collections::BTreeMap};
9
10///
11/// EventState
12///
13
14#[derive(CandidType, Clone, Debug, Deserialize, Serialize)]
15pub struct EventState {
16    pub ops: EventOps,
17    pub perf: EventPerf,
18    pub entities: BTreeMap<String, EntityCounters>,
19    pub window_start_ms: u64,
20}
21
22impl Default for EventState {
23    fn default() -> Self {
24        Self {
25            ops: EventOps::default(),
26            perf: EventPerf::default(),
27            entities: BTreeMap::new(),
28            window_start_ms: now_millis(),
29        }
30    }
31}
32
33///
34/// EventOps
35///
36
37/// Call counters are execution attempts; errors still increment them.
38/// Row counters reflect rows touched after execution, not requested rows.
39#[derive(CandidType, Clone, Debug, Default, Deserialize, Serialize)]
40pub struct EventOps {
41    // Executor entrypoints
42    pub load_calls: u64,
43    pub save_calls: u64,
44    pub delete_calls: u64,
45
46    // Planner kinds
47    pub plan_index: u64,
48    pub plan_keys: u64,
49    pub plan_range: u64,
50    pub plan_full_scan: u64,
51
52    // Rows touched
53    pub rows_loaded: u64,
54    pub rows_scanned: u64,
55    pub rows_deleted: u64,
56
57    // Index maintenance
58    pub index_inserts: u64,
59    pub index_removes: u64,
60    pub reverse_index_inserts: u64,
61    pub reverse_index_removes: u64,
62    pub relation_reverse_lookups: u64,
63    pub relation_delete_blocks: u64,
64    pub unique_violations: u64,
65}
66
67///
68/// EntityCounters
69///
70
71#[derive(CandidType, Clone, Debug, Default, Deserialize, Serialize)]
72pub struct EntityCounters {
73    pub load_calls: u64,
74    pub save_calls: u64,
75    pub delete_calls: u64,
76    pub rows_loaded: u64,
77    pub rows_scanned: u64,
78    pub rows_deleted: u64,
79    pub index_inserts: u64,
80    pub index_removes: u64,
81    pub reverse_index_inserts: u64,
82    pub reverse_index_removes: u64,
83    pub relation_reverse_lookups: u64,
84    pub relation_delete_blocks: u64,
85    pub unique_violations: u64,
86}
87
88///
89/// EventPerf
90///
91
92/// Instruction deltas are pressure indicators (validation + planning + execution),
93/// not latency measurements.
94#[derive(CandidType, Clone, Debug, Default, Deserialize, Serialize)]
95pub struct EventPerf {
96    // Instruction totals per executor (ic_cdk::api::performance_counter(1))
97    pub load_inst_total: u128,
98    pub save_inst_total: u128,
99    pub delete_inst_total: u128,
100
101    // Maximum observed instruction deltas
102    pub load_inst_max: u64,
103    pub save_inst_max: u64,
104    pub delete_inst_max: u64,
105}
106
107thread_local! {
108    static EVENT_STATE: RefCell<EventState> = RefCell::new(EventState::default());
109}
110
111/// Borrow metrics immutably.
112pub(crate) fn with_state<R>(f: impl FnOnce(&EventState) -> R) -> R {
113    EVENT_STATE.with(|m| f(&m.borrow()))
114}
115
116/// Borrow metrics mutably.
117pub(crate) fn with_state_mut<R>(f: impl FnOnce(&mut EventState) -> R) -> R {
118    EVENT_STATE.with(|m| f(&mut m.borrow_mut()))
119}
120
121/// Reset all counters (useful in tests).
122pub fn reset() {
123    with_state_mut(|m| *m = EventState::default());
124}
125
126/// Reset all event state: counters, perf, and serialize counters.
127pub fn reset_all() {
128    reset();
129}
130
131/// Accumulate instruction counts and track a max.
132#[allow(clippy::missing_const_for_fn)]
133pub fn add_instructions(total: &mut u128, max: &mut u64, delta_inst: u64) {
134    *total = total.saturating_add(u128::from(delta_inst));
135    if delta_inst > *max {
136        *max = delta_inst;
137    }
138}
139
140///
141/// EventReport
142/// Event/counter report; storage snapshot types live in snapshot/storage modules.
143///
144
145#[derive(CandidType, Clone, Debug, Default, Deserialize, Serialize)]
146pub struct EventReport {
147    /// Ephemeral runtime counters since `window_start_ms`.
148    pub counters: Option<EventState>,
149    /// Per-entity ephemeral counters and averages.
150    pub entity_counters: Vec<EntitySummary>,
151}
152
153///
154/// EntitySummary
155///
156
157#[derive(CandidType, Clone, Debug, Default, Deserialize, Serialize)]
158pub struct EntitySummary {
159    pub path: String,
160    pub load_calls: u64,
161    pub delete_calls: u64,
162    pub rows_loaded: u64,
163    pub rows_scanned: u64,
164    pub rows_deleted: u64,
165    pub avg_rows_per_load: f64,
166    pub avg_rows_scanned_per_load: f64,
167    pub avg_rows_per_delete: f64,
168    pub index_inserts: u64,
169    pub index_removes: u64,
170    pub reverse_index_inserts: u64,
171    pub reverse_index_removes: u64,
172    pub relation_reverse_lookups: u64,
173    pub relation_delete_blocks: u64,
174    pub unique_violations: u64,
175}
176
177/// Build a metrics report by inspecting in-memory counters only.
178#[must_use]
179#[allow(clippy::cast_precision_loss)]
180pub fn report() -> EventReport {
181    report_window_start(None)
182}
183
184/// Build a metrics report gated by `window_start_ms`.
185///
186/// This is a window-start filter:
187/// - If `window_start_ms` is `None`, return the current window.
188/// - If `window_start_ms <= state.window_start_ms`, return the current window.
189/// - If `window_start_ms > state.window_start_ms`, return an empty report.
190///
191/// IcyDB stores aggregate counters only, so it cannot produce a precise
192/// sub-window report after `state.window_start_ms`.
193#[must_use]
194#[allow(clippy::cast_precision_loss)]
195pub fn report_window_start(window_start_ms: Option<u64>) -> EventReport {
196    let snap = with_state(Clone::clone);
197    if let Some(requested_window_start_ms) = window_start_ms
198        && requested_window_start_ms > snap.window_start_ms
199    {
200        return EventReport::default();
201    }
202
203    let mut entity_counters: Vec<EntitySummary> = Vec::new();
204    for (path, ops) in &snap.entities {
205        let avg_load = if ops.load_calls > 0 {
206            ops.rows_loaded as f64 / ops.load_calls as f64
207        } else {
208            0.0
209        };
210        let avg_scanned = if ops.load_calls > 0 {
211            ops.rows_scanned as f64 / ops.load_calls as f64
212        } else {
213            0.0
214        };
215        let avg_delete = if ops.delete_calls > 0 {
216            ops.rows_deleted as f64 / ops.delete_calls as f64
217        } else {
218            0.0
219        };
220
221        entity_counters.push(EntitySummary {
222            path: path.clone(),
223            load_calls: ops.load_calls,
224            delete_calls: ops.delete_calls,
225            rows_loaded: ops.rows_loaded,
226            rows_scanned: ops.rows_scanned,
227            rows_deleted: ops.rows_deleted,
228            avg_rows_per_load: avg_load,
229            avg_rows_scanned_per_load: avg_scanned,
230            avg_rows_per_delete: avg_delete,
231            index_inserts: ops.index_inserts,
232            index_removes: ops.index_removes,
233            reverse_index_inserts: ops.reverse_index_inserts,
234            reverse_index_removes: ops.reverse_index_removes,
235            relation_reverse_lookups: ops.relation_reverse_lookups,
236            relation_delete_blocks: ops.relation_delete_blocks,
237            unique_violations: ops.unique_violations,
238        });
239    }
240
241    entity_counters.sort_by(|a, b| {
242        match b
243            .avg_rows_per_load
244            .partial_cmp(&a.avg_rows_per_load)
245            .unwrap_or(Ordering::Equal)
246        {
247            Ordering::Equal => match b.rows_loaded.cmp(&a.rows_loaded) {
248                Ordering::Equal => a.path.cmp(&b.path),
249                other => other,
250            },
251            other => other,
252        }
253    });
254
255    EventReport {
256        counters: Some(snap),
257        entity_counters,
258    }
259}
260
261///
262/// TESTS
263///
264
265#[cfg(test)]
266#[allow(clippy::float_cmp)]
267mod tests {
268    use crate::obs::metrics::{EntityCounters, report, reset_all, with_state, with_state_mut};
269
270    #[test]
271    fn reset_all_clears_state() {
272        with_state_mut(|m| {
273            m.ops.load_calls = 3;
274            m.ops.index_inserts = 2;
275            m.perf.save_inst_max = 9;
276            m.entities.insert(
277                "alpha".to_string(),
278                EntityCounters {
279                    load_calls: 1,
280                    ..Default::default()
281                },
282            );
283        });
284
285        reset_all();
286
287        with_state(|m| {
288            assert_eq!(m.ops.load_calls, 0);
289            assert_eq!(m.ops.index_inserts, 0);
290            assert_eq!(m.perf.save_inst_max, 0);
291            assert!(m.entities.is_empty());
292        });
293    }
294
295    #[test]
296    fn report_sorts_entities_by_average_rows() {
297        reset_all();
298        with_state_mut(|m| {
299            m.entities.insert(
300                "alpha".to_string(),
301                EntityCounters {
302                    load_calls: 2,
303                    rows_loaded: 6,
304                    ..Default::default()
305                },
306            );
307            m.entities.insert(
308                "beta".to_string(),
309                EntityCounters {
310                    load_calls: 1,
311                    rows_loaded: 5,
312                    ..Default::default()
313                },
314            );
315            m.entities.insert(
316                "gamma".to_string(),
317                EntityCounters {
318                    load_calls: 2,
319                    rows_loaded: 6,
320                    ..Default::default()
321                },
322            );
323        });
324
325        let report = report();
326        let paths: Vec<_> = report
327            .entity_counters
328            .iter()
329            .map(|e| e.path.as_str())
330            .collect();
331
332        // Order by avg rows per load desc, then rows_loaded desc, then path asc.
333        assert_eq!(paths, ["beta", "alpha", "gamma"]);
334        assert_eq!(report.entity_counters[0].avg_rows_per_load, 5.0);
335        assert_eq!(report.entity_counters[1].avg_rows_per_load, 3.0);
336        assert_eq!(report.entity_counters[2].avg_rows_per_load, 3.0);
337    }
338}