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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
use super::*;
use crate::{Effect, Error, Options};
use std::num::NonZeroU64;

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 set(ids: &[&str]) -> BTreeSet<String> {
    ids.iter().map(|id| (*id).to_owned()).collect()
}

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

// A chart with a deep history inside `p`, left from `a2` so the history has
// recorded it.
fn with_history() -> (Machine, State) {
    let machine = machine(
        r#" initial="p""#,
        r#"<state id="p" initial="a"><history id="h" type="deep"><transition target="a"/></history>
             <state id="a" initial="a1"><state id="a1"><transition event="e.next" target="a2"/></state><state id="a2"/></state>
             <transition event="e.out" target="q"/></state>
           <state id="q"><transition event="e.back" target="h"/></state>"#,
    );
    let started = machine.start(Options::new("s-1")).unwrap();
    let next = started.state.step("e.next", Value::Undefined).unwrap();
    let out = next.state.step("e.out", Value::Undefined).unwrap();
    (machine, out.state)
}

// The chart [`with_history`] runs, its `q` holding two `<invoke>` elements,
// which a position imported into it may name as live.
fn with_invokes() -> Machine {
    machine(
        r#" initial="p""#,
        r#"<state id="p" initial="a"><history id="h" type="deep"><transition target="a"/></history>
             <state id="a" initial="a1"><state id="a1"><transition event="e.next" target="a2"/></state><state id="a2"/></state>
             <transition event="e.out" target="q"/></state>
           <state id="q"><invoke id="i1" type="x-none"/><invoke id="i2" type="x-none"/>
             <transition event="e.back" target="h"/></state>"#,
    )
}

// Sabotage: with the export naming the configuration as the entered
// states, this goes red.
#[test]
fn the_export_names_every_state_by_id_and_leaves_the_root_out() {
    let (_, state) = with_history();
    let position = state.export_position().unwrap();
    assert_eq!(position.configuration, set(&["q"]));
    assert_eq!(position.entered_states, set(&["a", "a1", "a2", "p", "q"]));
    assert_eq!(
        position.history_values,
        BTreeMap::from([("h".to_owned(), set(&["a2"]))])
    );
    assert!(position.states_to_invoke.is_empty());
    assert!(position.active_invocations.is_empty());
    assert_eq!(position.identity, Value::Null);
    assert_eq!(position.status, Status::Running);
    assert!(position.running);
    assert_eq!(
        (position.macrostep, position.microstep, position.round),
        (3, 1, 1)
    );
    assert_eq!(
        position.datamodel.get(&Key::from("_sessionid")),
        Some(&Value::from("s-1"))
    );
    assert_eq!(position.max_macrostep_rounds, RoundBudget::default());
    assert!(!position.trace);
}

// Sabotage: with the import leaving `history` empty, the restore enters
// `a1` (the default) and this goes red.
#[test]
fn an_imported_position_restores_its_history_and_moves_on_as_the_original_does() {
    let (machine, state) = with_history();
    let imported = machine
        .import_position(&state.export_position().unwrap())
        .unwrap();
    assert_eq!(imported.configuration(), ["q"]);
    assert_eq!(imported.export_position(), state.export_position());
    let back = imported.step("e.back", Value::Undefined).unwrap();
    assert_eq!(back.state.active_leaf_states(), ["a2"]);
    assert_eq!(
        back.state.export_position(),
        state
            .step("e.back", Value::Undefined)
            .unwrap()
            .state
            .export_position()
    );
}

// Sabotage: with the import re-adding nothing to `entered_states`, the late
// `<data>` of `b` binds again and resets `x`, and this goes red.
#[test]
fn an_imported_position_keeps_late_binding_on_the_states_already_entered() {
    let machine = machine(
        r#" binding="late" initial="a""#,
        r#"<state id="a"><transition event="e.go" target="b"/></state>
           <state id="b"><datamodel><data id="x" expr="1"/></datamodel>
             <onentry><assign location="x" expr="x + 1"/></onentry>
             <transition event="e.go" target="a"/></state>"#,
    );
    let started = machine.start(Options::new("s-1")).unwrap();
    let there = started.state.step("e.go", Value::Undefined).unwrap();
    let back = there.state.step("e.go", Value::Undefined).unwrap();
    let imported = machine
        .import_position(&back.state.export_position().unwrap())
        .unwrap();
    let again = imported.step("e.go", Value::Undefined).unwrap();
    let position = again.state.export_position().unwrap();
    assert_eq!(
        position.datamodel.get(&Key::from("x")),
        Some(&Value::from(3))
    );
}

// Sabotage: with the internal-queue check removed, the export answers a
// position and this goes red.
#[test]
fn the_export_refuses_a_state_whose_internal_queue_holds_an_event() {
    let machine = machine(
        r#" initial="a""#,
        r#"<state id="a"><onentry><raise event="e.again"/></onentry><transition event="e.again" target="a"/></state>"#,
    );
    let mut options = Options::new("s-1");
    options.round_budget = budget(5);
    let started = machine.start(options).unwrap();
    assert_eq!(
        started.state.export_position(),
        Err(ExportError::InternalQueueNotEmpty)
    );
    assert_eq!(
        ExportError::InternalQueueNotEmpty.to_string(),
        "the internal queue holds an event"
    );
}

// Sabotage: with the unnameable check letting a nameless state through, the
// export answers a position missing it and this goes red.
#[test]
fn the_export_refuses_a_state_with_no_id_naming_every_one() {
    let machine = machine(
        r#" initial="m""#,
        r#"<state><state><state id="m"/></state></state>"#,
    );
    let started = machine.start(Options::new("s-1")).unwrap();
    let refused = started.state.export_position().unwrap_err();
    assert_eq!(
        refused,
        ExportError::UnnameableStates {
            indexes: vec![1, 2]
        }
    );
    assert_eq!(
        refused.to_string(),
        "states with no id are in the position: 1, 2"
    );
}

// Sabotage: with the unknown-id check answering the first id only, the list
// is one long and this goes red.
#[test]
fn the_import_refuses_every_unknown_id_at_once_sorted() {
    let (machine, state) = with_history();
    let mut position = state.export_position().unwrap();
    position.configuration.insert("zz".to_owned());
    position
        .history_values
        .insert("hh".to_owned(), set(&["a2", "yy"]));
    position.active_invocations.push(ActiveInvocation {
        state: "ww".to_owned(),
        invoke_index: 0,
        invoke_id: "i".to_owned(),
    });
    let refused = machine.import_position(&position).unwrap_err();
    assert_eq!(
        refused,
        ImportError::UnknownStateIds {
            ids: vec!["hh".into(), "ww".into(), "yy".into(), "zz".into()]
        }
    );
    assert_eq!(
        refused.to_string(),
        "the chart holds no state with these ids: hh, ww, yy, zz"
    );
}

// Sabotage: with the session id read whatever its type, the import answers
// a state and this goes red.
#[test]
fn the_import_refuses_a_datamodel_with_no_session_id() {
    let (machine, state) = with_history();
    let mut position = state.export_position().unwrap();
    position.datamodel.insert("_sessionid", Value::from(1));
    let refused = machine.import_position(&position).unwrap_err();
    assert_eq!(refused, ImportError::NoSessionId);
    assert_eq!(
        refused.to_string(),
        "the datamodel's _sessionid is not a string"
    );
    position.datamodel.remove(&Key::from("_sessionid"));
    assert_eq!(
        machine.import_position(&position).unwrap_err(),
        ImportError::NoSessionId
    );
}

// A history value the chart cannot restore is refused as a value, before
// it can send the entry walk round in a circle: a key that is not a
// history, a recorded history (itself among them), and a recorded state
// outside the history's parent.
// Sabotage: with `restorable` answering true, the import of a key that is
// not a history answers a state and this goes red.
#[test]
fn the_import_refuses_a_history_value_the_chart_cannot_restore() {
    let (machine, state) = with_history();
    let refused = |key: &str, recorded: &[&str]| {
        let mut position = state.export_position().unwrap();
        position.history_values = BTreeMap::from([(key.to_owned(), set(recorded))]);
        machine.import_position(&position).unwrap_err()
    };
    for (key, recorded) in [
        ("a", &["a1"][..]),
        ("h", &["h"][..]),
        ("h", &["a2", "q"][..]),
        ("h", &["p"][..]),
    ] {
        assert_eq!(
            refused(key, recorded),
            ImportError::InvalidHistoryValue {
                history: key.to_owned()
            },
            "{key} {recorded:?}"
        );
    }
    assert_eq!(
        refused("h", &["h"]).to_string(),
        "the history value recorded for \"h\" cannot be restored"
    );
}

// Sabotage: with the duplicate check removed, the second invocation
// replaces the first and this goes red.
#[test]
fn the_import_refuses_two_invocations_of_one_invoke_and_carries_the_rest() {
    let (_, state) = with_history();
    let machine = with_invokes();
    let mut position = state.export_position().unwrap();
    position.states_to_invoke = set(&["q"]);
    position.invoke_counter = 2;
    position.active_invocations = vec![
        ActiveInvocation {
            state: "q".to_owned(),
            invoke_index: 0,
            invoke_id: "i1".to_owned(),
        },
        ActiveInvocation {
            state: "q".to_owned(),
            invoke_index: 1,
            invoke_id: "i2".to_owned(),
        },
    ];
    let carried = machine.import_position(&position).unwrap();
    assert_eq!(carried.export_position(), Ok(position.clone()));

    position.active_invocations[1].invoke_index = 0;
    let refused = machine.import_position(&position).unwrap_err();
    assert_eq!(
        refused,
        ImportError::DuplicateInvocation {
            state: "q".to_owned(),
            invoke_index: 0
        }
    );
    assert_eq!(
        refused.to_string(),
        "two invocations name invoke 0 of \"q\""
    );
}

// An imported live invocation must name an `<invoke>` its state holds.
// Sabotage: with the bound check removed, the invocation of q's third
// `<invoke>` and the one of a state with none import, and this goes red.
#[test]
fn the_import_refuses_an_invocation_of_an_invoke_its_state_does_not_hold() {
    let (_, state) = with_history();
    let machine = with_invokes();
    let mut position = state.export_position().unwrap();
    position.active_invocations = vec![ActiveInvocation {
        state: "q".to_owned(),
        invoke_index: 2,
        invoke_id: "i3".to_owned(),
    }];
    let refused = machine.import_position(&position).err();
    assert_eq!(
        refused,
        Some(ImportError::UnknownInvoke {
            state: "q".to_owned(),
            invoke_index: 2
        })
    );
    assert_eq!(
        refused.map(|error| error.to_string()).as_deref(),
        Some("\"q\" holds no invoke 2")
    );
    position.active_invocations[0].state = "a".to_owned();
    position.active_invocations[0].invoke_index = 0;
    assert_eq!(
        machine.import_position(&position).unwrap_err(),
        ImportError::UnknownInvoke {
            state: "a".to_owned(),
            invoke_index: 0
        }
    );
    position.active_invocations[0].invoke_index = u64::MAX;
    assert!(machine.import_position(&position).is_err());
}

// An imported live invocation has no child: its state's exit cancels it,
// answering the cancel and nothing more, and the export after names none.
// Sabotage: with step.rs's depart not cancelling a state's invocations, no
// CancelInvoke is answered and the invocation is still exported; red.
#[test]
fn an_imported_invocation_is_cancelled_when_its_state_exits() {
    let (_, state) = with_history();
    let machine = with_invokes();
    let mut position = state.export_position().unwrap();
    position.active_invocations = vec![ActiveInvocation {
        state: "q".to_owned(),
        invoke_index: 1,
        invoke_id: "i2".to_owned(),
    }];
    let imported = machine.import_position(&position).unwrap();
    let back = imported.step("e.back", Value::Undefined).unwrap();
    let cancels: Vec<&str> = back
        .effects
        .iter()
        .filter_map(|effect| match effect {
            Effect::CancelInvoke { invoke_id, .. } => Some(invoke_id.as_str()),
            _ => None,
        })
        .collect();
    assert_eq!(cancels, ["i2"]);
    assert!(
        back.state
            .export_position()
            .unwrap()
            .active_invocations
            .is_empty()
    );
}

// Sabotage: with the import's done left `None` for a stopped position, the
// first assertion goes red.
#[test]
fn a_stopped_position_imports_stopped() {
    let machine = machine(
        r#" initial="a""#,
        r#"<state id="a"><transition event="e.go" target="f"/></state>
           <final id="f"><donedata><param name="n" expr="1"/></donedata></final>"#,
    );
    let started = machine.start(Options::new("s-1")).unwrap();
    let stopped = started.state.step("e.go", Value::Undefined).unwrap().state;
    let position = stopped.export_position().unwrap();
    assert_eq!(position.status, Status::Done);
    assert!(!position.running);
    let imported = machine.import_position(&position).unwrap();
    let done = imported.done().expect("a stopped chart");
    assert_eq!(done.donedata, Value::Undefined);
    assert!(done.configuration.is_empty());
    assert_eq!(done.active_leaf_count, 0);
    assert_eq!(
        imported.step("e.go", Value::Undefined).unwrap_err(),
        Error::NotRunning
    );
    assert_eq!(imported.export_position(), Ok(position));
}

// The import reads the registered send types from `_ioprocessors`, so a
// send of one is still answered as an effect for the host, and keeps the
// trace flag, the budget and the session id.
// Sabotage: with `send_types` answering none, the send is refused with
// error.execution and no Send effect is answered.
#[test]
fn the_import_keeps_the_send_types_the_trace_flag_the_budget_and_the_session() {
    let machine = machine(
        r#" initial="a""#,
        r#"<state id="a"><transition event="e.go" target="b"/></state>
           <state id="b"><onentry><send type="x-example" event="e.out" target="somewhere"/></onentry></state>"#,
    );
    let mut options = Options::new("s-7");
    options.send_types = set(&["x-example"]);
    options.trace = true;
    options.round_budget = RoundBudget::Unbounded;
    let started = machine.start(options).unwrap();
    let position = started.state.export_position().unwrap();
    assert!(position.trace);
    assert_eq!(position.max_macrostep_rounds, RoundBudget::Unbounded);
    let imported = machine.import_position(&position).unwrap();
    assert_eq!(imported.session_id, "s-7");
    assert_eq!(imported.core.send_types, set(&["x-example"]));
    let moved = imported.step("e.go", Value::Undefined).unwrap();
    assert!(moved.effects.iter().any(|effect| matches!(
        effect,
        Effect::Send { send_type: Some(Value::String(send_type)), .. } if send_type == "x-example"
    )));
    assert_eq!(imported.export_position(), Ok(position));
}

// Sabotage: with `send_types` keeping a built-in spelling, the set holds
// "scxml" and this goes red.
#[test]
fn the_send_types_leave_out_every_built_in_spelling_and_a_missing_entry() {
    let mut ioprocessors = Map::new();
    ioprocessors.insert("scxml", Value::Map(Map::new()));
    ioprocessors.insert(
        "http://www.w3.org/TR/scxml/#SCXMLEventProcessor",
        Value::Map(Map::new()),
    );
    ioprocessors.insert("x-one", Value::Map(Map::new()));
    ioprocessors.insert(1, Value::Map(Map::new()));
    let mut datamodel = Map::new();
    datamodel.insert("_ioprocessors", Value::Map(ioprocessors));
    assert_eq!(send_types(&datamodel), set(&["x-one"]));
    assert!(send_types(&Map::new()).is_empty());
}

// A tiny deterministic generator, so the arbitrary positions below are the
// same on every run.
struct Draw(u64);

impl Draw {
    fn next(&mut self) -> u64 {
        self.0 ^= self.0 << 13;
        self.0 ^= self.0 >> 7;
        self.0 ^= self.0 << 17;
        self.0
    }

    fn pick(&mut self, ids: &[String]) -> BTreeSet<String> {
        ids.iter()
            .filter(|_| self.next() % 3 == 0)
            .cloned()
            .collect()
    }
}

// No import panics, and no imported state panics when it is stepped and
// advanced: every corpus chart takes positions whose fields name arbitrary
// subsets of its states, unknown ids among them, with arbitrary counters and
// either status; each import answers a state or a refusal.
// Sabotage: with the unknown-id check removed and an unknown id read as an
// index past the chart's last state, a step indexes past the states, panics,
// and this goes red.
#[test]
fn no_arbitrary_position_panics_on_import_or_after_it() {
    let mut draw = Draw(0x9e37_79b9_7f4a_7c15);
    let mut imported = 0;
    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(50);
        let Ok(started) = machine.start(options) else {
            continue;
        };
        let Ok(base) = started.state.export_position() else {
            continue;
        };
        let mut ids: Vec<String> = machine.chart().id_to_index.keys().cloned().collect();
        ids.push("unknown".to_owned());
        for _ in 0..8 {
            let mut position = base.clone();
            position.configuration = draw.pick(&ids);
            position.entered_states = draw.pick(&ids);
            position.states_to_invoke = draw.pick(&ids);
            position.history_values = draw
                .pick(&ids)
                .into_iter()
                .map(|key| (key, draw.pick(&ids)))
                .collect();
            position.running = draw.next() % 4 != 0;
            position.status = if draw.next() % 4 == 0 {
                Status::Done
            } else {
                Status::Running
            };
            position.macrostep = draw.next();
            position.microstep = draw.next();
            position.round = draw.next();
            position.send_counter = draw.next();
            position.timer_counter = draw.next();
            let Ok(state) = machine.import_position(&position) else {
                continue;
            };
            imported += 1;
            for event in ["e.go", "e.next", "done.state.s", "error.execution"] {
                let _ = state.step(event, Value::Undefined);
            }
            let _ = state
                .advance(10_000)
                .and_then(|moved| moved.state.step("e.go", Value::Undefined));
            let _ = state.export_position();
            let _ = name;
        }
    }
    assert!(
        imported > 100,
        "only {imported} arbitrary positions imported"
    );
}

#[cfg(feature = "serde")]
mod serde {
    use super::*;
    use crate::{BlockOwner, PathSegment};
    use serde_json::{Value as Json, json};

    // The keys of an exported position in the TypeScript sibling,
    // statifier-ts v0.4.0: `ExportedPosition` in `src/position.ts`, the
    // identity beside the reference's required keys (`POSITION_FIELDS` in
    // `src/driver-shape.ts`).
    const SIBLING_KEYS: [&str; 17] = [
        "identity",
        "configuration",
        "enteredStates",
        "statesToInvoke",
        "historyValues",
        "activeInvocations",
        "invokeCounter",
        "sendCounter",
        "timerCounter",
        "datamodel",
        "running",
        "status",
        "macrostep",
        "microstep",
        "round",
        "trace",
        "maxMacrostepRounds",
    ];

    // Sabotage: with `Position`'s writer naming `entered_states` in snake
    // case, the keys differ and this goes red.
    #[test]
    fn the_json_form_has_the_typescript_siblings_keys() {
        let (_, state) = with_history();
        let json = serde_json::to_value(state.export_position().unwrap()).unwrap();
        let mut keys: Vec<&str> = json
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        keys.sort_unstable();
        let mut sibling: Vec<&str> = SIBLING_KEYS.to_vec();
        sibling.sort_unstable();
        assert_eq!(keys, sibling);
    }

    // A position in the TypeScript sibling's JSON form, its identity an
    // object and every datamodel root tagged text, reads and imports here.
    // Sabotage: with `datamodel_of` keeping each root's text as a string,
    // `x` is the string "1" and this goes red.
    #[test]
    fn a_position_in_the_siblings_form_reads_and_imports() {
        let machine = with_invokes();
        let sibling = json!({
            "identity": {"contentHash": "abc", "name": null, "version": "3"},
            "configuration": ["q"],
            "enteredStates": ["a", "a1", "a2", "p", "q"],
            "statesToInvoke": [],
            "historyValues": {"h": ["a2"]},
            "activeInvocations": [{"state": "q", "invokeIndex": 0, "invokeId": "q.i"}],
            "invokeCounter": 1,
            "sendCounter": 0,
            "timerCounter": 0,
            "datamodel": {
                "_sessionid": "\"s-9\"",
                "_name": "{\"$type\":\"undefined\"}",
                "_event": "{\"$type\":\"undefined\"}",
                "_ioprocessors": "{}",
                "x": "1"
            },
            "running": true,
            "status": "running",
            "macrostep": 3,
            "microstep": 1,
            "round": 2,
            "trace": false,
            "maxMacrostepRounds": "infinity",
            "extra": "a key that is not required is not read"
        });
        let position: Position = serde_json::from_value(sibling).unwrap();
        assert_eq!(
            position.datamodel.get(&Key::from("x")),
            Some(&Value::from(1))
        );
        assert_eq!(position.max_macrostep_rounds, RoundBudget::Unbounded);
        let state = machine.import_position(&position).unwrap();
        assert_eq!(state.configuration(), ["q"]);
        assert_eq!(state.session_id, "s-9");
        let back = state.step("e.back", Value::Undefined).unwrap();
        assert_eq!(back.state.active_leaf_states(), ["a2"]);
    }

    // Sabotage: with `position_of` taking `identity` as a required field, the
    // position without one is refused and this goes red.
    #[test]
    fn a_position_round_trips_through_json_text_and_needs_no_identity() {
        let (_, state) = with_history();
        let position = state.export_position().unwrap();
        let text = serde_json::to_string(&position).unwrap();
        assert_eq!(serde_json::from_str::<Position>(&text).unwrap(), position);
        let mut json: Json = serde_json::from_str(&text).unwrap();
        assert_eq!(
            json["datamodel"]["_name"],
            json!("{\"$type\":\"undefined\"}")
        );
        assert_eq!(json["maxMacrostepRounds"], json!(10_000));
        assert_eq!(json["status"], json!("running"));
        json.as_object_mut().unwrap().remove("identity");
        assert_eq!(
            serde_json::from_value::<Position>(json).unwrap().identity,
            Value::Null
        );
    }

    // Sabotage: with `budget_of` reading any string as no bound, "forever"
    // reads and this goes red.
    #[test]
    fn a_round_budget_is_a_count_above_zero_or_infinity() {
        assert_eq!(serde_json::to_string(&budget(7)).unwrap(), "7");
        assert_eq!(
            serde_json::to_string(&RoundBudget::Unbounded).unwrap(),
            "\"infinity\""
        );
        assert_eq!(serde_json::from_str::<RoundBudget>("7").unwrap(), budget(7));
        assert_eq!(
            serde_json::from_str::<RoundBudget>("\"infinity\"").unwrap(),
            RoundBudget::Unbounded
        );
        for refused in ["0", "-1", "\"forever\"", "1.5", "null"] {
            assert!(
                serde_json::from_str::<RoundBudget>(refused).is_err(),
                "{refused}"
            );
        }
    }

    // Sabotage: with `AsText` writing an empty text for a value it cannot
    // encode, the NaN serializes and this goes red.
    #[test]
    fn a_datamodel_the_tagged_text_cannot_hold_is_refused_as_an_error() {
        let (_, state) = with_history();
        let mut position = state.export_position().unwrap();
        position.datamodel.insert("x", Value::Float(f64::NAN));
        assert!(serde_json::to_string(&position).is_err());
        let mut position = state.export_position().unwrap();
        position.datamodel.insert(1, Value::from(1));
        assert!(serde_json::to_string(&position).is_err());
        let text = serde_json::to_string(&state.export_position().unwrap()).unwrap();
        let bad = text.replacen("\"_sessionid\":\"\\\"s-1\\\"\"", "\"_sessionid\":\"[\"", 1);
        assert_ne!(bad, text);
        assert!(serde_json::from_str::<Position>(&bad).is_err());
    }

    // No byte prefix of a position's JSON text, and no text with one byte
    // changed, panics on the way in: each answers a position or an error.
    // Sabotage: with `datamodel_of` unwrapping the decode it makes, an
    // altered datamodel text panics and this goes red.
    #[test]
    fn no_truncated_or_altered_json_text_panics() {
        let (machine, state) = with_history();
        let text = serde_json::to_string(&state.export_position().unwrap()).unwrap();
        for end in 0..text.len() {
            if let Some(prefix) = text.get(..end) {
                let _ = serde_json::from_str::<Position>(prefix);
            }
        }
        let bytes = text.as_bytes();
        for at in 0..bytes.len() {
            for replacement in *b"0\"{]x" {
                let mut altered = bytes.to_vec();
                altered[at] = replacement;
                if let Ok(position) = serde_json::from_slice::<Position>(&altered) {
                    if let Ok(state) = machine.import_position(&position) {
                        let _ = state.step("e.back", Value::Undefined);
                    }
                }
            }
        }
    }

    // Every effect a chart answers, the done answer among them, goes
    // through JSON text and back unchanged, a present null apart from an
    // absent value.
    // Sabotage: with the `Log` writer writing a `None` value as null, it is
    // read back as `Some(Null)`, and this goes red.
    #[test]
    fn effects_and_done_round_trip_through_json_text() {
        let machine = machine(
            r#" initial="a""#,
            r#"<datamodel><data id="n" expr="null"/></datamodel>
               <state id="a"><onentry><log label="none"/><log label="null" expr="n"/>
                 <assign location="n" expr="[1]"/><assign location="n[0]" expr="2"/>
                 <send event="e.later" delay="5ms" id="t"/><cancel sendid="t"/>
                 <send type="x-example" event="e.out"/></onentry>
                 <transition event="e.go" target="f"/></state>
               <final id="f"><donedata><param name="k" expr="n"/></donedata></final>"#,
        );
        let mut options = Options::new("s-1");
        options.send_types = set(&["x-example"]);
        let started = machine.start(options).unwrap();
        let stopped = started.state.step("e.go", Value::Undefined).unwrap();
        let effects: Vec<Effect> = started.effects.into_iter().chain(stopped.effects).collect();
        for kind in [
            "log",
            "datamodel_change",
            "send",
            "send_delayed",
            "datamodel_init",
            "done",
            "cancel",
        ] {
            let found = effects
                .iter()
                .any(|effect| serde_json::to_value(effect).unwrap()["kind"] == json!(kind));
            assert!(found, "{kind}");
        }
        let text = serde_json::to_string(&effects).unwrap();
        assert_eq!(serde_json::from_str::<Vec<Effect>>(&text).unwrap(), effects);
        let logs: Vec<&Effect> = effects
            .iter()
            .filter(|effect| matches!(effect, Effect::Log { .. }))
            .collect();
        assert_eq!(serde_json::to_value(logs[1]).unwrap()["value"], Json::Null);
        assert!(
            serde_json::to_value(logs[0])
                .unwrap()
                .get("value")
                .is_none()
        );
        let done = stopped.state.done().unwrap();
        let text = serde_json::to_string(done).unwrap();
        assert!(text.contains("activeLeafStates"));
        assert!(text.contains("\"activeLeafCount\":1"));
        assert_eq!(&serde_json::from_str::<Done>(&text).unwrap(), done);
        assert!(
            serde_json::from_str::<Effect>(
                r#"{"kind":"datamodel_init","datamodel":1,"macrostep":0,"microstep":0,"round":0}"#
            )
            .is_err()
        );
    }

    // Every effect variant and block owner kind goes through JSON text and
    // back, and what the reader refuses it answers as an error naming why.
    // Sabotage: with `owner_of` reading `on_exit` as `OnEntry`, the round
    // trip of the second effect goes red.
    #[test]
    fn every_effect_and_owner_kind_round_trips_and_a_bad_one_is_refused() {
        let owners = [
            BlockOwner::OnEntry {
                state: 1,
                ordinal: 0,
            },
            BlockOwner::OnExit {
                state: 2,
                ordinal: 1,
            },
            BlockOwner::Transition { transition: 3 },
            BlockOwner::Finalize {
                state: 4,
                invoke: 0,
            },
            BlockOwner::Invoke {
                state: 5,
                invoke: 1,
            },
        ];
        let mut effects: Vec<Effect> = owners
            .iter()
            .map(|owner| Effect::Cancel {
                send_id: Value::from("t"),
                ordinal: 1,
                content_index: 0,
                owner: *owner,
                macrostep: 1,
                microstep: 2,
                round: 3,
            })
            .collect();
        effects.push(Effect::BudgetExhausted {
            configuration: vec![0, 1],
            budget: 5,
            pending_internal_events: vec![Value::from("e")],
            macrostep: 1,
            microstep: 1,
            round: 5,
        });
        effects.push(Effect::DatamodelChange {
            location_path: vec![PathSegment::Key("a".into()), PathSegment::Index(-1)],
            location_source: "a[-1]".into(),
            new_value: Value::Undefined,
            prior_value: Value::Null,
            data_index: Some(0),
            content_index: None,
            owner: None,
            macrostep: 1,
            microstep: 1,
            round: 1,
        });
        let mut data = Map::new();
        data.insert("p", Value::from(1));
        effects.push(Effect::Invoke {
            invoke_id: "a.inv_1".into(),
            invoke_type: Some(Value::from("scxml")),
            src: None,
            params: Value::Map(data),
            content: Some(Value::from("<scxml/>")),
            autoforward: true,
            state_index: 1,
            invoke_index: 0,
            macrostep: 1,
            microstep: 1,
            round: 1,
        });
        effects.push(Effect::CancelInvoke {
            invoke_id: "a.inv_1".into(),
            state_index: 1,
            macrostep: 2,
            microstep: 1,
            round: 1,
        });
        effects.push(Effect::Autoforward {
            invoke_id: "a.inv_1".into(),
            state_index: 1,
            event: Value::from("e"),
            macrostep: 2,
            microstep: 0,
            round: 0,
        });
        let wrapped = Effect::Child {
            session_id: "s-1.a.inv_1".into(),
            effect: Box::new(effects[0].clone()),
        };
        effects.push(Effect::Child {
            session_id: "s-1.a.inv_1.b".into(),
            effect: Box::new(wrapped),
        });
        let text = serde_json::to_string(&effects).unwrap();
        for kind in ["invoke", "cancel_invoke", "autoforward", "child"] {
            assert!(text.contains(&format!(r#""kind":"{kind}""#)), "{kind}");
        }
        assert_eq!(serde_json::from_str::<Vec<Effect>>(&text).unwrap(), effects);
        let refused = |text: &str| {
            serde_json::from_str::<Effect>(text)
                .unwrap_err()
                .to_string()
        };
        assert!(refused(r#"{"kind":"other"}"#).contains("unknown"));
        assert!(
            refused(r#"{"kind":"budget_exhausted"}"#).contains("missing field `configuration`")
        );
        assert!(refused(r#"[]"#).contains("not a map"));
        assert!(
            refused(r#"{"kind":"cancel","sendId":"t","ordinal":-1}"#)
                .contains("`ordinal` is not a count")
        );
        assert!(
            serde_json::from_str::<BlockOwner>(r#"{"kind":"elsewhere"}"#)
                .unwrap_err()
                .to_string()
                .contains("unknown")
        );
        for bad in [r#"{"key":1}"#, r#"{"key":"a","index":0}"#, r#""a""#] {
            assert!(serde_json::from_str::<PathSegment>(bad).is_err(), "{bad}");
        }
        assert!(serde_json::from_str::<Status>(r#""stopped""#).is_err());
        assert_eq!(
            serde_json::from_str::<Status>(r#""done""#).unwrap(),
            Status::Done
        );
        let invocation = ActiveInvocation {
            state: "a".into(),
            invoke_index: 2,
            invoke_id: "a.i".into(),
        };
        let text = serde_json::to_string(&invocation).unwrap();
        assert_eq!(text, r#"{"state":"a","invokeIndex":2,"invokeId":"a.i"}"#);
        assert_eq!(
            serde_json::from_str::<ActiveInvocation>(&text).unwrap(),
            invocation
        );
    }

    // A position whose fields have the wrong shape is refused naming the
    // field.
    // Sabotage: with `history_of` keeping a value that is not a list as an
    // empty set, the second refusal reads and this goes red.
    #[test]
    fn a_position_of_the_wrong_shape_is_refused_naming_the_field() {
        let (_, state) = with_history();
        let json = serde_json::to_value(state.export_position().unwrap()).unwrap();
        let refused = |field: &str, value: Json| {
            let mut json = json.clone();
            json[field] = value;
            serde_json::from_value::<Position>(json)
                .unwrap_err()
                .to_string()
        };
        assert!(
            refused("activeInvocations", json!({})).contains("`activeInvocations` is not a list")
        );
        assert!(refused("historyValues", json!({"h": 1})).contains("`historyValues.h`"));
        assert!(refused("datamodel", json!({"x": 1})).contains("`datamodel.x` is not tagged text"));
        assert!(refused("status", json!("halted")).contains("`status`"));
        assert!(refused("running", json!(1)).contains("`running` is not a boolean"));
        assert!(refused("configuration", json!("a")).contains("`configuration`"));
        assert!(refused("maxMacrostepRounds", json!(0)).contains("`maxMacrostepRounds`"));
        let mut missing = json.clone();
        missing.as_object_mut().unwrap().remove("round");
        assert!(
            serde_json::from_value::<Position>(missing)
                .unwrap_err()
                .to_string()
                .contains("missing field `round`")
        );
    }
}