ic-timers 0.30.12

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
//! Bounded command interleavings against the real runtime and native provider.
//! This checks authority/handle ownership, not IC message rollback or recovery.

use super::*;

fn declaration(
    policy: u8,
    timer: &TimerIdentity,
    lifetime: DeclarationLifetime,
) -> RegistrationClaim {
    let start = scheduled_start(lifetime, TimerSchedule::After(Duration::from_nanos(5)));
    let cadence = TimerCadence::from_nanos(5).unwrap();
    match policy {
        0 => {
            register_once(timer.clone(), start, |_| async {
                OnceRunResult::new(TimerCompletion::no_work(), OnceDecision::Stop)
            })
            .unwrap()
            .claim
        }
        1 => {
            register_after_completion(timer.clone(), cadence, start, |_| async {
                AfterCompletionRunResult::new(
                    TimerCompletion::no_work(),
                    AfterCompletionDecision::RecurAfterCompletion,
                )
            })
            .unwrap()
            .claim
        }
        2 => {
            register_watchdog(timer.clone(), cadence, start, |_| {
                WatchdogRunResult::new(TimerCompletion::no_work(), WatchdogDecision::Continue)
            })
            .unwrap()
            .claim
        }
        _ => unreachable!(),
    }
}

#[test]
#[expect(
    clippy::too_many_lines,
    reason = "Keep the bounded trace driver and its invariant checks together."
)]
fn generated_command_sequences_preserve_authority_and_handle_ownership() {
    // Exhaust every four-command word over six operations, for all three
    // policies and both lifetimes: 7,776 traces. Include each command prefix.
    for policy in 0..3 {
        for lifetime in [
            DeclarationLifetime::Retained,
            DeclarationLifetime::RemoveWhenStopped,
        ] {
            for word in 0..6_u32.pow(4) {
                let _fixture = setup();
                let timer = identity("sequence");
                let sentinel = register_once(
                    identity("untouched"),
                    TimerStart::Retained {
                        initial: Some(TimerSchedule::At(u64::MAX)),
                    },
                    |_| async { panic!("unrelated timer must not run") },
                )
                .unwrap();
                let sentinel_before = timer_snapshot(sentinel.identity()).unwrap();
                let mut claim = declaration(policy, &timer, lifetime);
                let mut retired = Vec::new();
                let mut commands = word;
                for step in 0..4 {
                    let command = commands % 6;
                    commands /= 6;
                    let trace = (policy, lifetime, word, step, command);
                    let exists = timer_snapshot(&timer).unwrap().is_some();
                    // Capture a delivery only when this command invalidates it.
                    let stale = if exists && matches!(command, 2 | 3) {
                        let detached =
                            with_registry_mut(|registry| Ok(registry.take_wakeup_handle(&timer)))
                                .unwrap();
                        detached.map(|handle| {
                            let (token, handle) = handle.into_parts();
                            bind_provider_handle(&token, handle, None).unwrap();
                            token
                        })
                    } else {
                        None
                    };
                    let result = match command {
                        0 if policy == 0 => ensure_once_claim(
                            &claim,
                            None,
                            TimerSchedule::After(Duration::from_nanos(5)),
                        ),
                        0 => ensure_recurring_claim(&claim, None),
                        1 => {
                            let schedule = Some(TimerSchedule::After(Duration::from_nanos(7)));
                            if policy == 2 {
                                reconcile_watchdog_claim(&claim, None, schedule)
                            } else {
                                reconcile_ordinary_claim(&claim, None, schedule)
                            }
                        }
                        2 => cancel_claim(&claim, None),
                        3 => {
                            if exists {
                                unregister_claim(&claim).unwrap();
                            }
                            retired.push(claim);
                            claim = declaration(policy, &timer, lifetime);
                            Ok(())
                        }
                        4 => {
                            set_time(platform::time_ns() + 10);
                            // Leave watchdog work pending in some prefixes;
                            // later commands must honor its lifecycle ownership.
                            let _ran = run_next_due();
                            Ok(())
                        }
                        5 => {
                            let _discarded = discard_next_due();
                            Ok(())
                        }
                        _ => unreachable!(),
                    };
                    assert!(
                        result.is_ok() || matches!(result, Err(TimerError::RegistrationExpired)),
                        "{trace:?}: {result:?}"
                    );
                    for old in &retired {
                        assert!(
                            matches!(
                                cancel_claim(old, None),
                                Err(TimerError::RegistrationExpired)
                            ),
                            "{trace:?}"
                        );
                    }
                    if let Some(token) = stale {
                        // Scheduler cancellation while work is pending can be
                        // deferred. Deliver only after its claim really retires,
                        // or ordinary cancellation has invalidated the generation.
                        if policy != 2
                            || command == 3
                            || timer_snapshot(&timer)
                                .unwrap()
                                .is_none_or(|s| s.next_deadline_ns().is_none())
                        {
                            let before = timer_snapshot(&timer).unwrap();
                            let handles = timer_count();
                            if policy == 2 {
                                dispatch_watchdog_scheduler(&token);
                            } else {
                                let _delivery = platform::set_timer(
                                    Duration::ZERO,
                                    dispatch_wakeup(WakeupToken::Ordinary(token)),
                                );
                                assert!(run_next_due());
                            }
                            let after = timer_snapshot(&timer).unwrap();
                            assert_eq!(
                                after.as_ref().map(|s| (
                                    s.registration_id(),
                                    s.state(),
                                    s.next_deadline_ns(),
                                    s.observability().performance()
                                )),
                                before.as_ref().map(|s| (
                                    s.registration_id(),
                                    s.state(),
                                    s.next_deadline_ns(),
                                    s.observability().performance()
                                )),
                                "stale authority: {trace:?}"
                            );
                            assert_eq!(timer_count(), handles, "stale handles: {trace:?}");
                        }
                    }
                    assert_eq!(
                        timer_snapshot(sentinel.identity()).unwrap(),
                        sentinel_before,
                        "{trace:?}"
                    );
                    assert!(timer_inventory().unwrap().len() <= 2, "{trace:?}");
                    assert!(
                        (1..=3).contains(&timer_count()),
                        "orphan handles: {trace:?}"
                    );
                }
                if timer_snapshot(&timer).unwrap().is_some() {
                    unregister_claim(&claim).unwrap();
                }
                // A pending watchdog invocation can defer removal. Drain it at
                // the same time; no future cadence should survive unregister.
                for _ in 0..3 {
                    if !run_next_due() {
                        break;
                    }
                }
                assert_eq!(
                    timer_count(),
                    1,
                    "cleanup: policy={policy} lifetime={lifetime:?} word={word}"
                );
                sentinel.unregister().unwrap();
                assert_eq!(timer_count(), 0);
            }
        }
    }
}

#[test]
#[expect(
    clippy::too_many_lines,
    reason = "Keep each suspended trace, its independent outcome oracle and cleanup together."
)]
fn suspended_command_sequences_retire_authority_across_completion_and_abandonment() {
    for recurring in [false, true] {
        for lifetime in [
            DeclarationLifetime::Retained,
            DeclarationLifetime::RemoveWhenStopped,
        ] {
            for abandon in [false, true] {
                // Abandonment never installs a successor, so an admission fault
                // cannot distinguish another execution path there.
                for admission_failure in
                    [false, true].into_iter().filter(|fault| !abandon || !fault)
                {
                    for word in 0..4_u32.pow(3) {
                        let _fixture = setup();
                        let timer = identity("suspended-sequence");
                        let gate = SuspendedWork::default();
                        let context = Rc::new(RefCell::new(None));
                        let captured = Rc::new(());
                        let claim = suspended_ordinary_registration(
                            recurring,
                            timer.clone(),
                            lifetime,
                            gate.clone(),
                            Rc::clone(&context),
                            Rc::clone(&captured),
                        );
                        reconcile_ordinary_claim(&claim, None, Some(TimerSchedule::At(10)))
                            .unwrap();
                        set_time(10);
                        assert!(run_next_due());
                        let token = context.borrow().as_ref().unwrap().clone();
                        let mut commands = word;
                        let mut expected_deadline: Option<u64> = None;
                        let mut unregistered = false;
                        for _ in 0..3 {
                            let command = commands % 4;
                            if !unregistered {
                                match command {
                                    0 => expected_deadline = None,
                                    1 => {
                                        let requested = if recurring { 15 } else { 20 };
                                        expected_deadline = Some(
                                            expected_deadline
                                                .map_or(requested, |old| old.min(requested)),
                                        );
                                    }
                                    2 => expected_deadline = Some(30),
                                    3 => {
                                        unregistered = true;
                                        expected_deadline = None;
                                    }
                                    _ => unreachable!(),
                                }
                            }
                            match command {
                                0 => cancel_claim(&claim, None),
                                1 if recurring => ensure_recurring_claim(&claim, None),
                                1 => ensure_once_claim(&claim, None, TimerSchedule::At(20)),
                                2 => reconcile_ordinary_claim(
                                    &claim,
                                    None,
                                    Some(TimerSchedule::At(30)),
                                ),
                                3 => unregister_claim(&claim),
                                _ => unreachable!(),
                            }
                            .unwrap();
                            commands /= 4;
                            assert_eq!(timer_count(), 0, "running work owns no pending wakeup");
                        }
                        if admission_failure {
                            platform::ADMISSION_FAULT
                                .set(Some((0, platform::AdmissionError::Capacity)));
                        }
                        gate.resume();
                        if abandon {
                            assert!(discard_next_due());
                        } else {
                            assert!(run_next_due());
                        }
                        platform::ADMISSION_FAULT.set(None);
                        let binding_failed =
                            !abandon && admission_failure && expected_deadline.is_some();
                        if abandon || binding_failed {
                            expected_deadline = None;
                        }
                        let removed = unregistered
                            || (lifetime == DeclarationLifetime::RemoveWhenStopped
                                && expected_deadline.is_none());
                        let snapshot = timer_snapshot(&timer).unwrap();
                        assert_eq!(
                            snapshot.is_none(),
                            removed,
                            "declaration: {word}/{recurring}/{abandon}/{admission_failure}"
                        );
                        assert_eq!(timer_count(), usize::from(expected_deadline.is_some()));
                        if let Some(snapshot) = snapshot {
                            assert_eq!(snapshot.next_deadline_ns(), expected_deadline);
                            if expected_deadline.is_none() {
                                let reason = if abandon {
                                    InactiveReason::Abandoned
                                } else if binding_failed {
                                    InactiveReason::ControlFailure(
                                        crate::TimerControlFailure::ProviderBindingFailed,
                                    )
                                } else {
                                    InactiveReason::Cancelled
                                };
                                assert_eq!(
                                    snapshot.state(),
                                    TimerRuntimeStateSnapshot::Inactive { reason }
                                );
                            }
                            assert_eq!(
                                snapshot.observability().counters().work_completed().total(),
                                u128::from(!abandon)
                            );
                            assert_eq!(
                                snapshot.observability().counters().unacknowledged().total(),
                                u128::from(abandon)
                            );
                        }

                        assert!(
                            matches!(
                                cancel_claim(&claim, Some(&token)),
                                Err(TimerError::RegistrationExpired)
                            ),
                            "stale context: recurring={recurring} lifetime={lifetime:?} abandon={abandon} fault={admission_failure} word={word}"
                        );
                        if timer_snapshot(&timer).unwrap().is_some() {
                            unregister_claim(&claim).unwrap();
                        }
                        assert_eq!(timer_count(), 0);
                        assert!(timer_inventory().unwrap().is_empty());
                        assert_eq!(Rc::strong_count(&captured), 1);
                    }
                }
            }
        }
    }
}

#[test]
fn dropping_public_claims_does_not_cancel_or_unregister() {
    for policy in 0..3 {
        let _fixture = setup();
        let timer = identity("dropped-claim");
        let start = TimerStart::Retained {
            initial: Some(TimerSchedule::At(10)),
        };
        let cadence = TimerCadence::from_nanos(5).unwrap();
        match policy {
            0 => drop(
                register_once(timer.clone(), start, |_| async {
                    OnceRunResult::new(TimerCompletion::no_work(), OnceDecision::Stop)
                })
                .unwrap(),
            ),
            1 => drop(
                register_after_completion(timer.clone(), cadence, start, |_| async {
                    AfterCompletionRunResult::new(
                        TimerCompletion::no_work(),
                        AfterCompletionDecision::Stop,
                    )
                })
                .unwrap(),
            ),
            _ => drop(
                register_watchdog(timer.clone(), cadence, start, |_| {
                    WatchdogRunResult::new(TimerCompletion::no_work(), WatchdogDecision::Stop)
                })
                .unwrap(),
            ),
        }
        assert_eq!(timer_count(), 1);
        assert_eq!(timer_inventory().unwrap().len(), 1);
        set_time(10);
        assert!(run_next_due());
        if policy == 2 {
            assert!(run_next_due());
        }
        assert_eq!(timer_count(), 0);
        let snapshot = timer_snapshot(&timer).unwrap().unwrap();
        assert_eq!(
            snapshot.observability().counters().work_completed().total(),
            1
        );
        assert_eq!(
            timer_inventory().unwrap().len(),
            1,
            "retained declaration survives its lost claim"
        );
    }
}