statifier 0.0.0

An SCXML statechart interpreter core, a conformant sibling of the Elixir statifier package.
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
use super::*;
use crate::Key;

const OPEN: &str = r#"<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0""#;

fn machine(attributes: &str, body: &str) -> Machine {
    let text = format!("{OPEN}{attributes}>{body}</scxml>");
    match crate::compile(&text) {
        Ok(machine) => machine,
        Err(refusals) => panic!("{text}: {refusals:#?}"),
    }
}

fn start(attributes: &str, body: &str) -> Moved {
    machine(attributes, body)
        .start(Options::new("s-1"))
        .expect("a start")
}

fn budget(rounds: u64) -> RoundBudget {
    RoundBudget::Rounds(NonZeroU64::new(rounds).expect("a budget above zero"))
}

// Every `<log>`'s label and value, in order.
fn logs(effects: &[Effect]) -> Vec<(String, Value)> {
    effects
        .iter()
        .filter_map(|effect| match effect {
            Effect::Log { label, value, .. } => Some((
                label.clone().unwrap_or_default(),
                value.clone().unwrap_or(Value::Undefined),
            )),
            _ => None,
        })
        .collect()
}

fn labels(effects: &[Effect]) -> Vec<String> {
    logs(effects).into_iter().map(|(label, _)| label).collect()
}

fn text(value: &str) -> Value {
    Value::from(value)
}

// Sabotage: with `ids` leaving the ids in document order, this goes red.
#[test]
fn start_answers_the_active_state_ids_sorted_root_and_unnamed_left_out() {
    let started = start(
        r#" initial="p""#,
        r#"<parallel id="p"><state id="z"/><state id="b"/><state><state id="m"/></state></parallel>"#,
    );
    assert_eq!(started.state.configuration(), ["b", "m", "p", "z"]);
    assert!(started.state.done().is_none());
}

// Sabotage: with `step` moving the state it was given in place (a field
// written through a shared value), the first assertion goes red.
#[test]
fn step_answers_a_new_state_and_leaves_the_one_it_was_given() {
    let started = start(
        r#" initial="a""#,
        r#"<state id="a"><transition event="e.go" target="b"/></state><state id="b"/>"#,
    );
    let moved = started.state.step("e.go", Value::Undefined).unwrap();
    assert_eq!(started.state.configuration(), ["a"]);
    assert_eq!(moved.state.configuration(), ["b"]);
    let again = started.state.step("e.go", Value::Undefined).unwrap();
    assert_eq!(again.state.configuration(), ["b"]);
}

// Sabotage: with `perform_one` not recording the `Done` effect, `done` stays
// `None` and the step after it is not refused.
#[test]
fn a_stopped_chart_answers_its_donedata_and_refuses_another_event() {
    let started = start(
        r#" initial="a""#,
        r#"<state id="a"><transition event="e.go" target="f"/></state>
           <final id="f"><donedata><content expr="'x' + 'y'"/></donedata></final>"#,
    );
    let moved = started.state.step("e.go", Value::Undefined).unwrap();
    let done = moved.state.done().expect("a stopped chart");
    assert_eq!(done.donedata, text("xy"));
    assert_eq!(done.configuration, ["f"]);
    assert!(moved.state.configuration().is_empty());
    assert_eq!(
        moved.state.step("e.go", Value::Undefined).unwrap_err(),
        Error::NotRunning
    );
}

// Sabotage: with `is_built_in` answering false, start is not refused.
#[test]
fn start_refuses_a_built_in_send_type() {
    let mut options = Options::new("s-1");
    options.send_types = [SCXML_EVENT_PROCESSOR, "x-a", "scxml"]
        .into_iter()
        .map(String::from)
        .collect();
    let refused = Error::BuiltInSendTypes {
        types: vec![SCXML_EVENT_PROCESSOR.to_owned(), "scxml".to_owned()],
    };
    assert_eq!(
        machine("", r#"<state id="a"/>"#).start(options).err(),
        Some(refused.clone())
    );
    assert!(refused.to_string().contains("scxml"));
    let error: &dyn std::error::Error = &refused;
    assert!(error.source().is_none());
}

// Sabotage: with `start` dropping the host's datamodel, or `step` dropping
// the event's data, the values read back differ.
#[test]
fn host_values_pass_through_unchanged() {
    let machine = machine(
        r#" initial="a""#,
        r#"<datamodel><data id="x" expr="1"/></datamodel>
           <state id="a"><transition event="e.go" target="a">
             <log label="data" expr="_event.data"/><log label="x" expr="x"/>
           </transition></state>"#,
    );
    let mut options = Options::new("s-1");
    let mut datamodel = Map::new();
    let mut inner = Map::new();
    inner.insert("k", Value::List(vec![Value::from(1.5), Value::Null]));
    datamodel.insert("x", Value::Map(inner.clone()));
    options.datamodel = datamodel;
    let started = machine.start(options).unwrap();
    let Some(Effect::DatamodelInit { datamodel, .. }) = started.effects.first() else {
        panic!("{:#?}", started.effects);
    };
    assert_eq!(
        datamodel.get(&Key::from("x")),
        Some(&Value::Map(inner.clone()))
    );
    let data = Value::List(vec![text("p"), Value::Map(inner.clone())]);
    let moved = started.state.step("e.go", data.clone()).unwrap();
    assert_eq!(
        logs(&moved.effects),
        [
            (String::from("data"), data),
            (String::from("x"), Value::Map(inner))
        ]
    );
}

// Sabotage: with `route` dropping a send with no target, or one to the
// session's own address, the second state is never entered.
#[test]
fn a_send_to_the_session_itself_is_taken_as_an_external_event() {
    for target in ["", r##" target="#_scxml_s-1""##] {
        let started = start(
            r#" initial="a""#,
            &format!(
                r#"<state id="a"><onentry><send event="e.self" id="k"{target}/></onentry>
                   <transition event="e.self" target="b">
                     <log label="origin" expr="_event.origin"/>
                     <log label="type" expr="_event.origintype"/>
                     <log label="sendid" expr="_event.sendid"/>
                     <log label="eventtype" expr="_event.type"/>
                   </transition></state><state id="b"/>"#
            ),
        );
        assert_eq!(started.state.configuration(), ["b"], "{target}");
        assert_eq!(
            logs(&started.effects),
            [
                (String::from("origin"), text("#_scxml_s-1")),
                (String::from("type"), text(SCXML_EVENT_PROCESSOR)),
                (String::from("sendid"), text("k")),
                (String::from("eventtype"), text("external")),
            ]
        );
    }
}

// Sabotage: with `deliver_internal`'s effects acted on at once rather than
// after the batch, the log order changes.
#[test]
fn an_internal_send_runs_the_chart_after_the_batch_that_sent_it() {
    let started = start(
        r#" initial="a""#,
        r##"<state id="a"><onentry><send event="e.in" target="#_internal"/><log label="after"/></onentry>
           <transition event="e.in" target="b"><log label="taken"/>
             <log label="type" expr="_event.type"/></transition></state><state id="b"/>"##,
    );
    assert_eq!(started.state.configuration(), ["b"]);
    assert_eq!(
        logs(&started.effects),
        [
            (String::from("after"), Value::Undefined),
            (String::from("taken"), Value::Undefined),
            (String::from("type"), text("internal")),
        ]
    );
}

// Sabotage: with `next_due` ignoring the sequence among equal due times, or
// `advance` firing a timer not yet due, the order or the count changes.
#[test]
fn advance_fires_due_timers_earliest_first_then_in_scheduled_order() {
    let started = start(
        r#" initial="a""#,
        r#"<state id="a"><onentry>
             <send event="e.two" delay="20ms"/><send event="e.one" delay="10ms"/>
             <send event="e.three" delay="20ms"/><send event="e.four" delay="30ms"/>
           </onentry>
           <transition event="*"><log label="got" expr="_event.name"/></transition></state>"#,
    );
    assert_eq!(started.state.next_due_ms(), Some(10));
    let first = started.state.advance(20).unwrap();
    assert_eq!(first.state.now_ms(), 20);
    assert_eq!(
        logs(&first.effects),
        [
            (String::from("got"), text("e.one")),
            (String::from("got"), text("e.two")),
            (String::from("got"), text("e.three")),
        ]
    );
    assert_eq!(first.state.next_due_ms(), Some(30));
    assert_eq!(started.state.next_due_ms(), Some(10));
    let second = first.state.advance(9).unwrap();
    assert!(second.effects.is_empty());
    let third = second.state.advance(1).unwrap();
    assert_eq!(labels(&third.effects), ["got"]);
    assert_eq!(third.state.next_due_ms(), None);
}

// Sabotage: with the `Cancel` arm keeping every timer, the cancelled send
// fires.
#[test]
fn a_cancel_removes_the_pending_timer_it_names() {
    let started = start(
        r#" initial="a""#,
        r#"<state id="a"><onentry><send event="e.late" id="t" delay="1s"/>
           <send event="e.stop" delay="5ms"/></onentry>
           <transition event="e.stop"><cancel sendid="t"/></transition>
           <transition event="e.late" target="b"/></state><state id="b"/>"#,
    );
    let moved = started.state.advance(5).unwrap();
    assert_eq!(moved.state.next_due_ms(), None);
    let later = moved.state.advance(5_000).unwrap();
    assert_eq!(later.state.configuration(), ["a"]);
}

// Sabotage: with `registered` answering false, the registered send is
// routed to the session itself and the chart moves to `b`.
#[test]
fn a_send_of_a_registered_type_is_answered_as_an_effect_and_never_routed() {
    let machine = machine(
        r#" initial="a""#,
        r#"<state id="a"><onentry>
             <send event="e.out" type="x-host"/><send event="e.out" type="x-host" delay="1s"/>
             <log label="entry" expr="_ioprocessors['x-host']"/>
           </onentry><transition event="e.out" target="b"/></state><state id="b"/>"#,
    );
    let mut options = Options::new("s-1");
    options.send_types = BTreeSet::from([String::from("x-host")]);
    let started = machine.start(options).unwrap();
    assert_eq!(started.state.configuration(), ["a"]);
    assert_eq!(started.state.next_due_ms(), None);
    let sends = started
        .effects
        .iter()
        .filter(|effect| {
            matches!(effect, Effect::Send { send_type: Some(t), .. } | Effect::SendDelayed { send_type: Some(t), .. } if *t == text("x-host"))
        })
        .count();
    assert_eq!(sends, 2);
    assert_eq!(
        logs(&started.effects),
        [(String::from("entry"), Value::Map(Map::new()))]
    );
}

// Sabotage: with an unreachable fired send dropped rather than raising
// `error.communication`, the chart stays in `a`.
#[test]
fn a_delayed_send_to_an_unreachable_target_raises_error_communication_when_it_fires() {
    let started = start(
        r#" initial="a""#,
        r##"<state id="a"><onentry><send event="e.up" id="k" target="#_parent" delay="1ms"/></onentry>
           <transition event="error.communication" target="b">
             <log label="sendid" expr="_event.sendid"/></transition></state><state id="b"/>"##,
    );
    assert_eq!(started.state.configuration(), ["a"]);
    let moved = started.state.advance(1).unwrap();
    assert_eq!(moved.state.configuration(), ["b"]);
    assert_eq!(logs(&moved.effects), [(String::from("sendid"), text("k"))]);
}

// Sabotage: with the fired `#_internal` arm queuing on the external queue,
// the event's type reads `external`.
#[test]
fn a_fired_internal_send_is_delivered_onto_the_internal_queue() {
    let started = start(
        r#" initial="a""#,
        r##"<state id="a"><onentry><send event="e.in" targetexpr="'#_internal'" delay="1ms"/></onentry>
           <transition event="e.in" target="b"><log label="type" expr="_event.type"/></transition>
           </state><state id="b"/>"##,
    );
    let moved = started.state.advance(1).unwrap();
    assert_eq!(moved.state.configuration(), ["b"]);
    assert_eq!(
        logs(&moved.effects),
        [(String::from("type"), text("internal"))]
    );
}

// Sabotage: with `admits` allowing more counted events than the budget, the
// halt comes at a later macrostep.
#[test]
fn a_call_halts_when_the_events_it_sends_itself_spend_the_budget() {
    let machine = machine(
        r#" initial="a""#,
        r#"<state id="a"><onentry><send event="e.loop"/></onentry>
           <transition event="e.loop" target="a"/>
           <transition event="e.host" target="b"/></state><state id="b"/>"#,
    );
    let mut options = Options::new("s-1");
    options.round_budget = budget(3);
    let started = machine.start(options).unwrap();
    let Some(Effect::BudgetExhausted {
        budget, macrostep, ..
    }) = started.effects.last()
    else {
        panic!("{:#?}", started.effects);
    };
    assert_eq!(*budget, 3);
    // The start is macrostep 1, and each of the three events taken one more.
    assert_eq!(*macrostep, 4);
    // Halted: a host event is queued, not taken.
    let moved = started.state.step("e.host", Value::Undefined).unwrap();
    assert!(moved.effects.is_empty());
    assert_eq!(moved.state.configuration(), ["a"]);
}

// Sabotage: with `admits` always true for an internal send, the start never
// returns.
#[test]
fn a_call_halts_when_its_internal_sends_spend_the_budget() {
    let machine = machine(
        r#" initial="a""#,
        r##"<state id="a"><onentry><send event="e.loop" target="#_internal"/></onentry>
           <transition event="e.loop" target="a"/></state>"##,
    );
    let mut options = Options::new("s-1");
    options.round_budget = budget(2);
    let started = machine.start(options).unwrap();
    let exhausted: Vec<&Effect> = started
        .effects
        .iter()
        .filter(|effect| matches!(effect, Effect::BudgetExhausted { .. }))
        .collect();
    assert_eq!(exhausted.len(), 1);
    let Effect::BudgetExhausted {
        pending_internal_events,
        ..
    } = exhausted[0]
    else {
        unreachable!()
    };
    assert_eq!(pending_internal_events.len(), 1);
}

// Sabotage: with a macrostep's `BudgetExhausted` not halting the driver, the
// host event is taken and the chart moves to `b`.
#[test]
fn a_macrostep_that_spends_its_budget_halts_the_driver_and_timers_still_fire() {
    let machine = machine(
        r#" initial="a""#,
        r#"<state id="a"><onentry><raise event="e.r"/><send event="e.t" delay="1ms"/></onentry>
           <transition event="e.r" target="a"/>
           <transition event="e.host" target="b"/>
           <transition event="e.t"><log label="fired"/></transition></state><state id="b"/>"#,
    );
    let mut options = Options::new("s-1");
    options.round_budget = budget(4);
    let started = machine.start(options).unwrap();
    assert!(matches!(
        started.effects.last(),
        Some(Effect::BudgetExhausted { .. })
    ));
    let moved = started.state.step("e.host", Value::Undefined).unwrap();
    assert_eq!(moved.state.configuration(), ["a"]);
    assert!(moved.state.next_due_ms().is_some());
    let fired = moved.state.advance(1).unwrap();
    assert_eq!(fired.state.next_due_ms(), None);
    // The fired event is queued, as the host event is: a halted driver takes
    // none.
    assert!(logs(&fired.effects).is_empty());
}

// Sabotage: with `checked_add` replaced by a saturating add, no refusal.
#[test]
fn advance_refuses_a_duration_past_the_clock_and_moves_a_stopped_chart_only_in_time() {
    let started = start(r#" initial="a""#, r#"<state id="a"/>"#);
    let later = started.state.advance(10).unwrap();
    assert_eq!(
        later.state.advance(u64::MAX).unwrap_err(),
        Error::InvalidDuration { ms: u64::MAX }
    );
    assert!(
        Error::InvalidDuration { ms: 1 }
            .to_string()
            .contains("1 ms")
    );

    let stopped = start(r#" initial="f""#, r#"<final id="f"/>"#);
    assert!(stopped.state.done().is_some());
    let moved = stopped.state.advance(7).unwrap();
    assert_eq!(moved.state.now_ms(), 7);
    assert!(moved.effects.is_empty());
}

// Sabotage: with `Done` not clearing the timers, a timer stays pending after
// the chart stopped.
#[test]
fn a_chart_that_stops_discards_its_timers_and_its_queued_events() {
    let started = start(
        r#" initial="a""#,
        r#"<state id="a"><onentry><send event="e.late" delay="1s"/><send event="e.now"/>
           <send event="e.now"/></onentry>
           <transition event="e.now" target="f"/></state><final id="f"/>"#,
    );
    let done = started.state.done().expect("stopped");
    assert_eq!(done.configuration, ["f"]);
    assert_eq!(done.donedata, Value::Undefined);
    assert_eq!(started.state.next_due_ms(), None);
    assert!(started.state.external_queue.is_empty());
}

// Sabotage: with `present` keeping a null, the send's target is
// `Some(Value::Null)`.
#[test]
fn a_null_target_is_carried_as_no_target() {
    let machine = machine(
        r#" initial="a""#,
        r#"<state id="a"><onentry><send event="e.out" typeexpr="'x-host'" targetexpr="null"/></onentry></state>"#,
    );
    let mut options = Options::new("s-1");
    options.send_types = BTreeSet::from([String::from("x-host")]);
    let started = machine.start(options).unwrap();
    let target = started.effects.iter().find_map(|effect| match effect {
        Effect::Send { target, .. } => Some(target.clone()),
        _ => None,
    });
    assert_eq!(target, Some(None));
}

#[test]
fn the_round_budget_defaults_to_the_reference_and_converts() {
    assert_eq!(RoundBudget::default(), budget(DEFAULT_ROUNDS));
    assert_eq!(
        RoundBudget::Unbounded.interpreter(),
        interpreter::RoundBudget::Unbounded
    );
    assert!(RoundBudget::Unbounded.admits(u64::MAX));
    assert_eq!(RoundBudget::Unbounded.spent(), u64::MAX);
    let options = Options::new("s-1");
    assert_eq!(options.round_budget, RoundBudget::default());
    assert!(!options.trace);
    assert!(Error::NotRunning.to_string().contains("stopped"));
}

// Sabotage: with `start` ignoring an unbounded budget (a bound of 1), the
// eventless chain stops early and `c` is not reached.
#[test]
fn an_unbounded_budget_lets_a_long_macrostep_finish() {
    let machine = machine(
        r#" initial="a""#,
        r#"<state id="a"><transition target="b"/></state><state id="b"><transition target="c"/></state><state id="c"/>"#,
    );
    let mut options = Options::new("s-1");
    options.round_budget = RoundBudget::Unbounded;
    assert_eq!(machine.start(options).unwrap().state.configuration(), ["c"]);
}

// No driver call panics on a chart the corpus holds: each is started,
// sent an event and advanced past its timers, and each answer is a value.
// Sabotage: with `next_due` answering a position past the end, `remove`
// panics and this goes red.
#[test]
fn every_corpus_chart_starts_steps_and_advances_without_a_panic() {
    for (name, bytes) in crate::testing::corpus_documents() {
        let Ok(source) = String::from_utf8(bytes) else {
            continue;
        };
        let Ok(machine) = crate::compile(&source) else {
            continue;
        };
        let mut options = Options::new("s-1");
        options.round_budget = budget(100);
        let started = machine
            .start(options)
            .unwrap_or_else(|error| panic!("{name}: {error}"));
        let stepped = match started.state.step("e.go", Value::Undefined) {
            Ok(moved) => moved.state,
            Err(Error::NotRunning) => started.state,
            Err(error) => panic!("{name}: {error}"),
        };
        let advanced = stepped
            .advance(10_000)
            .unwrap_or_else(|error| panic!("{name}: {error}"));
        assert!(
            advanced.state.next_due_ms().is_none_or(|due| due > 10_000),
            "{name}"
        );
    }
}

// A halted driver drops a fired send to the internal queue or to a target it
// cannot reach: the chart is not run again, and no second budget effect.
// Sabotage: with `fired_internal` delivering whatever the halt, the advance
// runs the chart with a fresh budget and answers a second BudgetExhausted.
#[test]
fn a_halted_driver_drops_a_fired_internal_or_unreachable_send() {
    let machine = machine(
        r#" initial="idle""#,
        r##"<state id="idle"><onentry>
             <send event="e.up" target="#_parent" delay="10ms"/>
             <send event="e.in" targetexpr="'#_internal'" delay="10ms"/>
           </onentry><transition event="go" target="loop"/></state>
           <state id="loop"><transition target="loop2"/></state>
           <state id="loop2"><transition target="loop"/></state>"##,
    );
    let mut options = Options::new("s-1");
    options.round_budget = budget(5);
    let started = machine.start(options).unwrap();
    let stepped = started.state.step("go", Value::Undefined).unwrap();
    let halted = stepped.state.configuration();
    assert!(matches!(
        stepped.effects.last(),
        Some(Effect::BudgetExhausted { .. })
    ));
    let advanced = stepped.state.advance(20).unwrap();
    assert!(advanced.effects.is_empty(), "{:#?}", advanced.effects);
    assert_eq!(advanced.state.configuration(), halted);
    assert_eq!(advanced.state.next_due_ms(), None);
}

// A timer that reschedules itself due at once would fire forever; the call
// counts the timers it scheduled and fired, and halts past the budget.
// Sabotage: with `count_fire` counting nothing, advance(0) never returns.
#[test]
fn a_timer_rescheduled_due_at_once_spends_the_call_s_budget() {
    let machine = machine(
        r#" initial="a""#,
        r#"<state id="a"><onentry><send event="tick" delay="0ms"/></onentry>
           <transition event="tick"><send event="tick" delay="0ms"/></transition></state>"#,
    );
    let mut options = Options::new("s-1");
    options.round_budget = budget(3);
    let started = machine.start(options).unwrap();
    let advanced = started.state.advance(0).unwrap();
    let exhausted = advanced
        .effects
        .iter()
        .filter(|effect| matches!(effect, Effect::BudgetExhausted { .. }))
        .count();
    assert_eq!(exhausted, 1);
    // The start's timer and three it scheduled fire, then the fourth is
    // fired into the queue of a halted driver.
    let sent = advanced
        .effects
        .iter()
        .filter(|effect| matches!(effect, Effect::SendDelayed { .. }))
        .count();
    assert_eq!(sent, 4);
    assert_eq!(advanced.state.next_due_ms(), None);
    assert_eq!(advanced.state.now_ms(), 0);
}

// A heartbeat that reschedules itself a second later is bounded by the
// duration advanced, never by the budget: one long advance answers what ten
// short ones do.
// Sabotage: with `next_instant` keeping the count of fired timers when the
// clock moves on, the long advance halts with BudgetExhausted and leaves no timer.
#[test]
fn a_timer_rescheduled_with_a_delay_is_not_halted_however_time_is_split() {
    let machine = machine(
        r#" initial="a""#,
        r#"<state id="a"><onentry><send event="tick" delay="1000ms"/></onentry>
           <transition event="tick"><log label="tick"/><send event="tick" delay="1000ms"/></transition></state>"#,
    );
    let mut options = Options::new("s-1");
    options.round_budget = budget(3);
    let started = machine.start(options).unwrap();
    let long = started.state.advance(10_000).unwrap();
    assert!(
        !long
            .effects
            .iter()
            .any(|effect| matches!(effect, Effect::BudgetExhausted { .. })),
        "{:#?}",
        long.effects
    );
    assert_eq!(long.state.next_due_ms(), Some(11_000));
    let mut state = started.state;
    let mut effects = Vec::new();
    for _ in 0..10 {
        let moved = state.advance(1_000).unwrap();
        effects.extend(moved.effects);
        state = moved.state;
    }
    assert_eq!(effects, long.effects);
    assert_eq!(labels(&long.effects).len(), 10);
    assert_eq!(state.next_due_ms(), Some(11_000));
}

// A heartbeat whose tick also sends itself an event and sends one onto the
// internal queue at once: each count is kept at one virtual time, so one
// long advance answers what ten short ones do, and nothing halts.
// Sabotage: with `next_instant` keeping the count of events taken (or of
// internal sends), the long advance halts with BudgetExhausted.
#[test]
fn immediate_sends_of_a_heartbeat_are_counted_at_one_virtual_time() {
    let machine = machine(
        r#" initial="a""#,
        r##"<state id="a"><onentry><send event="tick" delay="1000ms"/></onentry>
           <transition event="tick"><send event="echo"/><send event="inner" target="#_internal"/>
             <send event="tick" delay="1000ms"/></transition>
           <transition event="echo"><log label="echo"/></transition>
           <transition event="inner"><log label="inner"/></transition></state>"##,
    );
    let mut options = Options::new("s-1");
    options.round_budget = budget(3);
    let started = machine.start(options).unwrap();
    let long = started.state.advance(10_000).unwrap();
    assert!(
        !long
            .effects
            .iter()
            .any(|effect| matches!(effect, Effect::BudgetExhausted { .. })),
        "{:#?}",
        long.effects
    );
    assert_eq!(labels(&long.effects).len(), 20);
    assert_eq!(long.state.next_due_ms(), Some(11_000));
    let mut state = started.state;
    let mut effects = Vec::new();
    for _ in 0..10 {
        let moved = state.advance(1_000).unwrap();
        effects.extend(moved.effects);
        state = moved.state;
    }
    assert_eq!(effects, long.effects);
    assert_eq!(state.next_due_ms(), Some(11_000));
}

// A fan-out of delayed timers that land on one later time: each was
// scheduled at an earlier time, so none is counted when it fires, and one
// long advance answers what the same time in two short ones does.
// Sabotage: with `next_instant` keeping the call's first sequence, the long
// advance counts the four fires and halts with BudgetExhausted.
#[test]
fn a_fan_out_of_delayed_timers_is_not_halted_however_time_is_split() {
    let machine = machine(
        r#" initial="a""#,
        r#"<state id="a"><onentry><send event="tick" delay="1000ms"/></onentry>
           <transition event="tick"><send event="x" delay="1000ms"/><send event="x" delay="1000ms"/>
             <send event="x" delay="1000ms"/><send event="x" delay="1000ms"/></transition>
           <transition event="x"><log label="x"/></transition></state>"#,
    );
    let mut options = Options::new("s-1");
    options.round_budget = budget(3);
    let started = machine.start(options).unwrap();
    let long = started.state.advance(2_000).unwrap();
    assert!(
        !long
            .effects
            .iter()
            .any(|effect| matches!(effect, Effect::BudgetExhausted { .. })),
        "{:#?}",
        long.effects
    );
    assert_eq!(labels(&long.effects).len(), 4);
    let first = started.state.advance(1_000).unwrap();
    let second = first.state.advance(1_000).unwrap();
    let mut effects = first.effects;
    effects.extend(second.effects);
    assert_eq!(effects, long.effects);
}

// Sabotage: with `leaf_ids` keeping every active state, the first
// assert_eq goes red (the parallel and the compound state are answered).
#[test]
fn the_leaf_read_answers_the_active_atomic_states_sorted_unnamed_left_out() {
    let started = start(
        r#" initial="p""#,
        r#"<parallel id="p"><state id="z"/><state id="s"><state id="m"/></state>
             <state><state id="b"/></state></parallel>"#,
    );
    assert_eq!(started.state.active_leaf_states(), ["b", "m", "z"]);
    assert_eq!(started.state.configuration(), ["b", "m", "p", "s", "z"]);
}

// A stopped chart has no active state, so the leaf read answers none, as
// the reference's does; the leaves it stopped in are on `Done`.
// Sabotage: with `Done::active_leaf_states` built empty in `perform_one`,
// the last assert_eq goes red; with `active_leaf_states` answering the
// done leaves on a stopped chart, the assertion that it is empty goes red.
#[test]
fn a_stopped_chart_answers_no_leaf_and_its_done_the_leaves_it_stopped_in() {
    let started = start(
        r#" initial="a""#,
        r#"<state id="a"><transition event="e.go" target="f"/></state><final id="f"/>"#,
    );
    assert_eq!(started.state.active_leaf_states(), ["a"]);
    let moved = started.state.step("e.go", Value::Undefined).unwrap();
    assert!(moved.state.active_leaf_states().is_empty());
    assert!(moved.state.configuration().is_empty());
    let done = moved.state.done().expect("a stopped chart");
    assert_eq!(done.configuration, ["f"]);
    assert_eq!(done.active_leaf_states, ["f"]);
}

// A nested final ends its parent's region, not the chart: the leaf read is
// the live configuration's.
// Sabotage: with `active_leaf_states` answering the done leaves (none while
// the chart runs) in place of the live read, the first assert_eq goes red.
#[test]
fn the_leaf_read_of_a_running_chart_holds_a_nested_final() {
    let started = start(
        r#" initial="s""#,
        r#"<state id="s"><transition event="done.state.s" target="t"/>
             <state id="a"><transition event="e.go" target="f"/></state><final id="f"/></state>
           <state id="t"/>"#,
    );
    assert_eq!(started.state.active_leaf_states(), ["a"]);
    let moved = started.state.step("e.go", Value::Undefined).unwrap();
    assert_eq!(moved.state.active_leaf_states(), ["t"]);
}

// The leaf count counts a leaf with no id, which the leaf read leaves out,
// running and once stopped, and a stopped chart counts no live leaf.
// Sabotage: with `leaf_count` counting only the states with an id, the
// assert_eq on 3 goes red; with `Done::active_leaf_count` built from the
// leaf read's length in `perform_one`, the assert_eq on 1 goes red.
#[test]
fn the_leaf_count_counts_a_leaf_with_no_id_running_and_stopped() {
    let started = start(
        r#" initial="p""#,
        r#"<parallel id="p"><state id="z"/><state/><state><state id="b"/></state></parallel>"#,
    );
    assert_eq!(started.state.active_leaf_states(), ["b", "z"]);
    assert_eq!(started.state.active_leaf_count(), 3);
    let stopped = start("", "<final/>");
    let done = stopped.state.done().expect("a stopped chart");
    assert!(done.active_leaf_states.is_empty());
    assert_eq!(done.active_leaf_count, 1);
    assert_eq!(stopped.state.active_leaf_count(), 0);
}