ic-timers 0.3.3

Observable and recovery-aware timers for Internet Computer canisters
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//! Saturating epoch-local counters and instruction aggregates.

use super::{TimerCompletion, TimerCompletionOutcome, TimerEpoch, TimerOutcomeSnapshot};

/// Epoch-local timer event counters.
///
/// Fields are private so mutation preserves saturation and the completion
/// partition. The registry is the sole writer.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct TimerCounters {
    schedule_requests: u64,
    wakeups_armed: u64,
    work_dispatched: u64,
    scheduler_started: u64,
    work_started: u64,
    work_completed: u64,
    succeeded: u64,
    no_work: u64,
    retryable_failure: u64,
    invariant_failure: u64,
    cancelled: u64,
    stale_wakeups: u64,
    stale_work: u64,
    coalesced: u64,
    unacknowledged: u64,
}

impl TimerCounters {
    pub(crate) const fn record_schedule_request(&mut self) {
        self.schedule_requests = self.schedule_requests.saturating_add(1);
    }

    pub(crate) const fn record_wakeup_armed(&mut self) {
        self.wakeups_armed = self.wakeups_armed.saturating_add(1);
    }

    pub(crate) const fn record_work_dispatched(&mut self) {
        self.work_dispatched = self.work_dispatched.saturating_add(1);
    }

    pub(crate) const fn record_scheduler_started(&mut self) {
        self.scheduler_started = self.scheduler_started.saturating_add(1);
    }

    pub(crate) const fn record_work_started(&mut self) {
        self.work_started = self.work_started.saturating_add(1);
    }

    pub(crate) const fn record_completion(&mut self, outcome: TimerCompletionOutcome) {
        self.work_completed = self.work_completed.saturating_add(1);
        match outcome {
            TimerCompletionOutcome::Success => {
                self.succeeded = self.succeeded.saturating_add(1);
            }
            TimerCompletionOutcome::NoWork => {
                self.no_work = self.no_work.saturating_add(1);
            }
            TimerCompletionOutcome::RetryableFailure => {
                self.retryable_failure = self.retryable_failure.saturating_add(1);
            }
            TimerCompletionOutcome::InvariantFailure => {
                self.invariant_failure = self.invariant_failure.saturating_add(1);
            }
        }
    }

    pub(crate) const fn record_cancellation(&mut self) {
        self.cancelled = self.cancelled.saturating_add(1);
    }

    pub(crate) const fn record_stale_wakeup(&mut self) {
        self.stale_wakeups = self.stale_wakeups.saturating_add(1);
    }

    pub(crate) const fn record_stale_work(&mut self) {
        self.stale_work = self.stale_work.saturating_add(1);
    }

    pub(crate) const fn record_coalesced(&mut self) {
        self.coalesced = self.coalesced.saturating_add(1);
    }

    pub(crate) const fn record_unacknowledged(&mut self) {
        self.unacknowledged = self.unacknowledged.saturating_add(1);
    }

    /// Return validated activation and reconciliation requests.
    #[must_use]
    pub const fn schedule_requests(self) -> u64 {
        self.schedule_requests
    }

    /// Return ordinary or scheduler provider one-shots armed.
    #[must_use]
    pub const fn wakeups_armed(self) -> u64 {
        self.wakeups_armed
    }

    /// Return immediate watchdog work one-shots dispatched.
    #[must_use]
    pub const fn work_dispatched(self) -> u64 {
        self.work_dispatched
    }

    /// Return actual provider arms across both callback roles.
    #[must_use]
    pub const fn provider_arms(self) -> u64 {
        self.wakeups_armed.saturating_add(self.work_dispatched)
    }

    /// Return accepted watchdog scheduler callbacks.
    #[must_use]
    pub const fn scheduler_started(self) -> u64 {
        self.scheduler_started
    }

    /// Return accepted consumer-work callbacks.
    #[must_use]
    pub const fn work_started(self) -> u64 {
        self.work_started
    }

    /// Return consumer work whose completion accounting committed.
    #[must_use]
    pub const fn work_completed(self) -> u64 {
        self.work_completed
    }

    /// Return successful-work completions.
    #[must_use]
    pub const fn succeeded(self) -> u64 {
        self.succeeded
    }

    /// Return valid no-work completions.
    #[must_use]
    pub const fn no_work(self) -> u64 {
        self.no_work
    }

    /// Return retryable expected-failure completions.
    #[must_use]
    pub const fn retryable_failure(self) -> u64 {
        self.retryable_failure
    }

    /// Return invariant or terminal-failure completions.
    #[must_use]
    pub const fn invariant_failure(self) -> u64 {
        self.invariant_failure
    }

    /// Return logical cancellations that changed authoritative state.
    #[must_use]
    pub const fn cancelled(self) -> u64 {
        self.cancelled
    }

    /// Return rejected ordinary or scheduler callback generations.
    #[must_use]
    pub const fn stale_wakeups(self) -> u64 {
        self.stale_wakeups
    }

    /// Return rejected watchdog work generations.
    #[must_use]
    pub const fn stale_work(self) -> u64 {
        self.stale_work
    }

    /// Return scheduling demand satisfied without another logical arm.
    #[must_use]
    pub const fn coalesced(self) -> u64 {
        self.coalesced
    }

    /// Return committed watchdog dispatches retired without completion.
    #[must_use]
    pub const fn unacknowledged(self) -> u64 {
        self.unacknowledged
    }

    /// Check that every completion belongs to exactly one outcome class.
    #[must_use]
    pub const fn completion_partition_is_valid(self) -> bool {
        self.work_completed
            == self
                .succeeded
                .saturating_add(self.no_work)
                .saturating_add(self.retryable_failure)
                .saturating_add(self.invariant_failure)
    }
}

/// Saturating aggregate for one instruction measurement role.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct MeasurementSummary {
    samples: u64,
    total: u64,
    latest: Option<u64>,
    maximum: Option<u64>,
}

impl MeasurementSummary {
    pub(crate) const fn record(&mut self, value: u64) {
        self.samples = self.samples.saturating_add(1);
        self.total = self.total.saturating_add(value);
        self.latest = Some(value);
        self.maximum = Some(match self.maximum {
            Some(current) if current > value => current,
            Some(_) | None => value,
        });
    }

    /// Return the number of completed samples.
    #[must_use]
    pub const fn samples(self) -> u64 {
        self.samples
    }

    /// Return the saturating sum of all samples.
    #[must_use]
    pub const fn total(self) -> u64 {
        self.total
    }

    /// Return the latest sample, if one exists.
    #[must_use]
    pub const fn latest(self) -> Option<u64> {
        self.latest
    }

    /// Return the largest sample, if one exists.
    #[must_use]
    pub const fn maximum(self) -> Option<u64> {
        self.maximum
    }
}

/// Completed instruction aggregates split by callback role.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct TimerPerformance {
    scheduler_instructions: MeasurementSummary,
    work_instructions: MeasurementSummary,
}

impl TimerPerformance {
    pub(crate) const fn record_scheduler(&mut self, instructions: u64) {
        self.scheduler_instructions.record(instructions);
    }

    pub(crate) const fn record_work(&mut self, instructions: u64) {
        self.work_instructions.record(instructions);
    }

    /// Return normally completed scheduler instruction measurements.
    #[must_use]
    pub const fn scheduler_instructions(self) -> MeasurementSummary {
        self.scheduler_instructions
    }

    /// Return normally completed consumer-work instruction measurements.
    #[must_use]
    pub const fn work_instructions(self) -> MeasurementSummary {
        self.work_instructions
    }
}

/// Epoch-scoped outcomes, counters, and performance for one timer.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct TimerObservabilitySnapshot {
    epoch: TimerEpoch,
    outcomes: TimerOutcomeSnapshot,
    counters: TimerCounters,
    performance: TimerPerformance,
}

impl TimerObservabilitySnapshot {
    pub(crate) const fn new(epoch: TimerEpoch) -> Self {
        Self {
            epoch,
            outcomes: TimerOutcomeSnapshot::new(),
            counters: TimerCounters {
                schedule_requests: 0,
                wakeups_armed: 0,
                work_dispatched: 0,
                scheduler_started: 0,
                work_started: 0,
                work_completed: 0,
                succeeded: 0,
                no_work: 0,
                retryable_failure: 0,
                invariant_failure: 0,
                cancelled: 0,
                stale_wakeups: 0,
                stale_work: 0,
                coalesced: 0,
                unacknowledged: 0,
            },
            performance: TimerPerformance {
                scheduler_instructions: MeasurementSummary {
                    samples: 0,
                    total: 0,
                    latest: None,
                    maximum: None,
                },
                work_instructions: MeasurementSummary {
                    samples: 0,
                    total: 0,
                    latest: None,
                    maximum: None,
                },
            },
        }
    }

    pub(crate) const fn record_completion(
        &mut self,
        completion: TimerCompletion,
        completed_at_ns: u64,
    ) {
        self.outcomes.record_completion(completion, completed_at_ns);
        self.counters.record_completion(completion.outcome());
    }

    pub(crate) const fn record_unacknowledged(&mut self, observed_at_ns: u64) {
        self.outcomes.record_unacknowledged(observed_at_ns);
        self.counters.record_unacknowledged();
    }

    pub(crate) const fn counters_mut(&mut self) -> &mut TimerCounters {
        &mut self.counters
    }

    pub(crate) const fn record_scheduler_instructions(&mut self, instructions: u64) {
        self.performance.record_scheduler(instructions);
    }

    pub(crate) const fn record_work_instructions(&mut self, instructions: u64) {
        self.performance.record_work(instructions);
    }

    /// Return the observation epoch.
    #[must_use]
    pub const fn epoch(self) -> TimerEpoch {
        self.epoch
    }

    /// Return latest outcomes and functional failure state.
    #[must_use]
    pub const fn outcomes(self) -> TimerOutcomeSnapshot {
        self.outcomes
    }

    /// Return epoch-local event counters.
    #[must_use]
    pub const fn counters(self) -> TimerCounters {
        self.counters
    }

    /// Return completed instruction aggregates.
    #[must_use]
    pub const fn performance(self) -> TimerPerformance {
        self.performance
    }

    /// Return functional expected-failure state without rebuilding a snapshot.
    #[must_use]
    pub const fn consecutive_expected_failures(self) -> u64 {
        self.outcomes.consecutive_expected_failures()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn all_counters_saturate() {
        let mut counters = TimerCounters {
            schedule_requests: u64::MAX,
            wakeups_armed: u64::MAX,
            work_dispatched: u64::MAX,
            scheduler_started: u64::MAX,
            work_started: u64::MAX,
            work_completed: u64::MAX,
            succeeded: u64::MAX,
            no_work: u64::MAX,
            retryable_failure: u64::MAX,
            invariant_failure: u64::MAX,
            cancelled: u64::MAX,
            stale_wakeups: u64::MAX,
            stale_work: u64::MAX,
            coalesced: u64::MAX,
            unacknowledged: u64::MAX,
        };

        counters.record_schedule_request();
        counters.record_wakeup_armed();
        counters.record_work_dispatched();
        counters.record_scheduler_started();
        counters.record_work_started();
        counters.record_completion(TimerCompletionOutcome::Success);
        counters.record_cancellation();
        counters.record_stale_wakeup();
        counters.record_stale_work();
        counters.record_coalesced();
        counters.record_unacknowledged();

        assert_eq!(counters.schedule_requests(), u64::MAX);
        assert_eq!(counters.provider_arms(), u64::MAX);
        assert_eq!(counters.work_completed(), u64::MAX);
        assert_eq!(counters.cancelled(), u64::MAX);
        assert_eq!(counters.stale_wakeups(), u64::MAX);
        assert_eq!(counters.stale_work(), u64::MAX);
        assert_eq!(counters.coalesced(), u64::MAX);
        assert_eq!(counters.unacknowledged(), u64::MAX);
        assert!(counters.completion_partition_is_valid());
    }

    #[test]
    fn instruction_roles_are_separate_and_saturating() {
        let mut performance = TimerPerformance::default();
        performance.record_scheduler(20);
        performance.record_work(30);
        performance.record_work(10);

        assert_eq!(performance.scheduler_instructions().total(), 20);
        assert_eq!(performance.work_instructions().samples(), 2);
        assert_eq!(performance.work_instructions().total(), 40);
        assert_eq!(performance.work_instructions().latest(), Some(10));
        assert_eq!(performance.work_instructions().maximum(), Some(30));
    }
}