tellus 0.2.1

A resilient world of actors for Rust: typed messages, supervision trees, death watch, event sourcing.
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
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
#![cfg(feature = "persistence")]

use serde::{Deserialize, Serialize};
use std::{
    collections::HashMap,
    convert::Infallible,
    future::pending,
    num::{NonZeroU32, NonZeroUsize},
    sync::{Arc, Mutex},
    time::Duration,
};
use tellus::{
    Actor, ActorConfig, ActorContext, ActorRef, ActorSystem, AppendError, Backoff, Cbor, Codec,
    Control, Effect, EncodedEvent, EncodedSnapshot, EventSourced, EventStore, Incoming, Nothing,
    Persistence, PersistenceId, ReplyTo, RestartPolicy, SchemaVersion, SeqNo, SnapshotStore,
    StoredEvent, StoredSnapshot, SupervisionStrategy, Versioned,
};
use thiserror::Error;
use tokio::{
    sync::mpsc,
    time::{sleep, timeout},
};

const TIMEOUT: Duration = Duration::from_secs(5);

/// Replay reconstructs the live state: a counter increments across single and atomic multi-event
/// effects, persists a final event while stopping, and a second incarnation over the same store
/// answers with the same count, seeded by `init` and folded by `apply` alone.
#[tokio::test]
async fn replay_reconstructs_the_live_state() {
    let store = TestStore::default();
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let system = ActorSystem::event_sourced(
        Counter::new("1", probe_tx.clone()),
        Persistence::new(store.clone()),
    );
    assert_eq!(recv(&mut probe_rx, "no init probe").await, Probe::Init);
    assert_eq!(
        recv(&mut probe_rx, "no recovered probe").await,
        Probe::Recovered
    );

    system.root().tell(Command::Increment(1));
    system.root().tell(Command::IncrementTwice(2, 3));
    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to first get");
    assert_eq!(count, 6);

    system.root().tell(Command::StopAfter(4));
    assert_terminates(system, "first incarnation did not terminate").await;

    let id = persistence_id("1");
    let events = store.stream(&id);
    assert_eq!(events.len(), 4);
    assert_eq!(
        events.last().map(|stored| stored.seq_no),
        Some(SeqNo::new(3)),
        "the final event must be persisted before stopping"
    );

    let system =
        ActorSystem::event_sourced(Counter::new("1", probe_tx), Persistence::new(store.clone()));
    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to second get");
    assert_eq!(count, 10);

    system.root().tell(Command::Stop);
    assert_terminates(system, "second incarnation did not terminate").await;
}

/// Without a snapshot every recovery seeds via `init`; with a snapshot `init` is skipped and
/// `init_from_snapshot` seeds instead; `recovered` runs on every recovery either way. A snapshot
/// also shortens replay: the second incarnation reads only the events after it.
#[tokio::test]
async fn snapshots_skip_init_and_shorten_replay() {
    let store = TestStore::default();
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let system = ActorSystem::event_sourced(
        Counter::new("2", probe_tx.clone()).with_snapshot_every(3),
        Persistence::new(store.clone()).with_snapshot_store(store.clone()),
    );
    assert_eq!(recv(&mut probe_rx, "no init probe").await, Probe::Init);
    assert_eq!(
        recv(&mut probe_rx, "no recovered probe").await,
        Probe::Recovered
    );

    for _ in 0..3 {
        system.root().tell(Command::Increment(1));
    }
    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to first get");
    assert_eq!(count, 3);

    system.root().tell(Command::Stop);
    assert_terminates(system, "first incarnation did not terminate").await;

    let system = ActorSystem::event_sourced(
        Counter::new("2", probe_tx).with_snapshot_every(3),
        Persistence::new(store.clone()).with_snapshot_store(store.clone()),
    );
    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to second get");
    assert_eq!(count, 3);

    system.root().tell(Command::Stop);
    assert_terminates(system, "second incarnation did not terminate").await;

    let mut probes = Vec::new();
    while let Ok(probe) = probe_rx.try_recv() {
        probes.push(probe);
    }
    let second_recovery = probes
        .iter()
        .skip_while(|probe| !matches!(probe, Probe::InitFromSnapshot))
        .take(2)
        .collect::<Vec<_>>();
    assert_eq!(
        second_recovery,
        [&Probe::InitFromSnapshot, &Probe::Recovered],
        "the second recovery must seed from the snapshot and still run recovered"
    );
    assert!(
        !probes[1..].contains(&Probe::Init),
        "init must be skipped once a snapshot exists"
    );
    assert_eq!(
        store.reads(),
        [SeqNo::ZERO, SeqNo::new(3)],
        "the second recovery must replay only the events after the snapshot"
    );
}

/// A failure to save a snapshot never fails the actor: commands keep settling, and with no
/// snapshot stored the next recovery seeds via `init` and replays in full.
#[tokio::test]
async fn a_failed_snapshot_save_never_fails_the_actor() {
    let store = TestStore::default().with_failing_saves();
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let system = ActorSystem::event_sourced(
        Counter::new("8", probe_tx.clone()).with_snapshot_every(1),
        Persistence::new(store.clone()).with_snapshot_store(store.clone()),
    );
    system.root().tell(Command::Increment(1));
    system.root().tell(Command::Increment(2));
    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to first get");
    assert_eq!(count, 3);

    system.root().tell(Command::Stop);
    assert_terminates(system, "first incarnation did not terminate").await;

    let system = ActorSystem::event_sourced(
        Counter::new("8", probe_tx).with_snapshot_every(1),
        Persistence::new(store.clone()).with_snapshot_store(store.clone()),
    );
    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to second get");
    assert_eq!(count, 3);

    system.root().tell(Command::Stop);
    assert_terminates(system, "second incarnation did not terminate").await;

    let mut probes = Vec::new();
    while let Ok(probe) = probe_rx.try_recv() {
        probes.push(probe);
    }
    assert!(
        !probes.contains(&Probe::InitFromSnapshot),
        "with every save failing, no snapshot must exist to recover from"
    );
    assert_eq!(
        store.reads(),
        [SeqNo::ZERO, SeqNo::ZERO],
        "the second recovery must replay in full"
    );
}

/// A snapshot offered without a configured snapshot store is dropped, not a failure: commands
/// keep settling and every recovery replays in full.
#[tokio::test]
async fn an_offered_snapshot_without_a_store_is_dropped() {
    let store = TestStore::default();
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let system = ActorSystem::event_sourced(
        Counter::new("9", probe_tx.clone()).with_snapshot_every(1),
        Persistence::new(store.clone()),
    );
    system.root().tell(Command::Increment(1));
    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to first get");
    assert_eq!(count, 1);

    system.root().tell(Command::Stop);
    assert_terminates(system, "first incarnation did not terminate").await;

    let system = ActorSystem::event_sourced(
        Counter::new("9", probe_tx).with_snapshot_every(1),
        Persistence::new(store.clone()),
    );
    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to second get");
    assert_eq!(count, 1);

    system.root().tell(Command::Stop);
    assert_terminates(system, "second incarnation did not terminate").await;

    let mut probes = Vec::new();
    while let Ok(probe) = probe_rx.try_recv() {
        probes.push(probe);
    }
    assert!(
        !probes.contains(&Probe::InitFromSnapshot),
        "without a snapshot store, no snapshot must exist to recover from"
    );
    assert_eq!(
        store.reads(),
        [SeqNo::ZERO, SeqNo::ZERO],
        "the second recovery must replay in full"
    );
}

/// A `then` continuation runs once its events are settled and never on replay: across a failure
/// and restart, replaying the events emits no continuation probes.
#[tokio::test]
async fn continuations_never_run_on_replay() {
    let store = TestStore::default();
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let system = ActorSystem::event_sourced_with_config(
        Counter::new("3", probe_tx),
        Persistence::new(store.clone()),
        restart_config(),
    );
    assert_eq!(recv(&mut probe_rx, "no init probe").await, Probe::Init);
    assert_eq!(
        recv(&mut probe_rx, "no recovered probe").await,
        Probe::Recovered
    );

    system.root().tell(Command::Increment(1));
    assert_eq!(
        recv(&mut probe_rx, "no handled probe").await,
        Probe::Handled
    );
    assert_eq!(
        recv(&mut probe_rx, "no settled probe").await,
        Probe::Settled(1)
    );

    system.root().tell(Command::Fail);
    assert_eq!(
        recv(&mut probe_rx, "no handled probe").await,
        Probe::Handled
    );
    assert_eq!(
        recv(&mut probe_rx, "no init probe after restart").await,
        Probe::Init
    );
    assert_eq!(
        recv(&mut probe_rx, "no recovered probe after restart").await,
        Probe::Recovered
    );

    system.root().tell(Command::Increment(2));
    assert_eq!(
        recv(&mut probe_rx, "no handled probe").await,
        Probe::Handled
    );
    assert_eq!(
        recv(&mut probe_rx, "no settled probe").await,
        Probe::Settled(3),
        "replay must restore the count without emitting settled probes"
    );

    system.root().tell(Command::Stop);
    assert_terminates(system, "system did not terminate").await;
}

/// A stale append is fenced: an event appended by another writer makes the actor's next append
/// conflict, the conflict goes through supervision, and the restarted actor replays onto the
/// winner's events instead of overwriting them; the conflicting command is consumed.
#[tokio::test]
async fn append_conflict_restarts_onto_the_winners_events() {
    let store = TestStore::default();
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let system = ActorSystem::event_sourced_with_config(
        Counter::new("4", probe_tx),
        Persistence::new(store.clone()),
        restart_config(),
    );

    system.root().tell(Command::Increment(1));
    loop {
        if recv(&mut probe_rx, "no settled probe").await == Probe::Settled(1) {
            break;
        }
    }

    let id = persistence_id("4");
    store
        .append(&id, SeqNo::new(1), vec![encoded(&Increased(10))])
        .await
        .expect("the interloping append must succeed");

    system.root().tell(Command::Increment(1));
    assert_eq!(
        recv(&mut probe_rx, "no handled probe").await,
        Probe::Handled
    );
    assert_eq!(
        recv(&mut probe_rx, "no init probe after the conflict").await,
        Probe::Init
    );
    assert_eq!(
        recv(&mut probe_rx, "no recovered probe after the conflict").await,
        Probe::Recovered
    );

    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to get");
    assert_eq!(count, 11);

    system.root().tell(Command::Stop);
    assert_terminates(system, "system did not terminate").await;
}

/// A store failure on append, unlike a conflict, has no second writer, but takes the same path:
/// supervision restarts the actor, replay reconciles with the store, and the command whose
/// append failed is consumed, its event never appended.
#[tokio::test]
async fn an_append_store_failure_restarts_and_consumes_the_command() {
    let store = TestStore::default().with_append_failures(1);
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let system = ActorSystem::event_sourced_with_config(
        Counter::new("10", probe_tx),
        Persistence::new(store.clone()),
        restart_config(),
    );
    assert_eq!(recv(&mut probe_rx, "no init probe").await, Probe::Init);
    assert_eq!(
        recv(&mut probe_rx, "no recovered probe").await,
        Probe::Recovered
    );

    system.root().tell(Command::Increment(1));
    assert_eq!(
        recv(&mut probe_rx, "no handled probe").await,
        Probe::Handled
    );
    assert_eq!(
        recv(&mut probe_rx, "no init probe after the failed append").await,
        Probe::Init
    );
    assert_eq!(
        recv(&mut probe_rx, "no recovered probe after the failed append").await,
        Probe::Recovered
    );

    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to first get");
    assert_eq!(count, 0, "the failed command's event must not be appended");

    system.root().tell(Command::Increment(2));
    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to second get");
    assert_eq!(count, 2);

    system.root().tell(Command::Stop);
    assert_terminates(system, "system did not terminate").await;
}

/// A store panic on append, like a store error, is an actor failure: supervision restarts the
/// actor instead of the panic unwinding its task, replay reconciles with the store, and the
/// command whose append panicked is consumed.
#[tokio::test]
async fn an_append_store_panic_restarts_and_consumes_the_command() {
    let store = TestStore::default().with_append_panics(1);
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let system = ActorSystem::event_sourced_with_config(
        Counter::new("12", probe_tx),
        Persistence::new(store.clone()),
        restart_config(),
    );
    assert_eq!(recv(&mut probe_rx, "no init probe").await, Probe::Init);
    assert_eq!(
        recv(&mut probe_rx, "no recovered probe").await,
        Probe::Recovered
    );

    system.root().tell(Command::Increment(1));
    assert_eq!(
        recv(&mut probe_rx, "no handled probe").await,
        Probe::Handled
    );
    assert_eq!(
        recv(&mut probe_rx, "no init probe after the panicked append").await,
        Probe::Init
    );
    assert_eq!(
        recv(
            &mut probe_rx,
            "no recovered probe after the panicked append"
        )
        .await,
        Probe::Recovered
    );

    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to first get");
    assert_eq!(
        count, 0,
        "the panicked command's event must not be appended"
    );

    system.root().tell(Command::Increment(2));
    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to second get");
    assert_eq!(count, 2);

    system.root().tell(Command::Stop);
    assert_terminates(system, "system did not terminate").await;
}

/// A parent's stop is honored during recovery: stopping the parent of an event-sourced child
/// whose store read hangs forever aborts the replay instead of stalling termination.
#[tokio::test]
async fn a_parent_stop_aborts_a_hung_recovery() {
    let store = TestStore::default().with_hanging_reads();
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let system = ActorSystem::new(Parent {
        store,
        probe_tx: probe_tx.clone(),
    });
    assert_eq!(recv(&mut probe_rx, "no init probe").await, Probe::Init);

    sleep(Duration::from_millis(50)).await;
    system.root().tell(());
    assert_terminates(system, "termination must not wait for the hung recovery").await;
}

/// A failure of `recovered` is an ordinary startup failure: under `Restart` the next attempt
/// runs recovery again, and once `recovered` succeeds the actor handles commands normally.
#[tokio::test]
async fn a_recovered_failure_restarts_into_a_working_actor() {
    let store = TestStore::default();
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let system = ActorSystem::event_sourced_with_config(
        Counter::new("11", probe_tx).with_recovered_failures(1),
        Persistence::new(store.clone()),
        restart_config(),
    );
    assert_eq!(recv(&mut probe_rx, "no init probe").await, Probe::Init);
    assert_eq!(
        recv(&mut probe_rx, "no init probe after restart").await,
        Probe::Init
    );
    assert_eq!(
        recv(&mut probe_rx, "no recovered probe").await,
        Probe::Recovered
    );

    system.root().tell(Command::Increment(1));
    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to get");
    assert_eq!(count, 1);

    system.root().tell(Command::Stop);
    assert_terminates(system, "system did not terminate").await;
}

/// Writes are strict: a command is fully settled, its continuations included, before the next one
/// is handled, even while the append itself is slow.
#[tokio::test]
async fn a_command_settles_before_the_next_is_handled() {
    let store = TestStore::default().with_append_delay(Duration::from_millis(20));
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let system =
        ActorSystem::event_sourced(Counter::new("5", probe_tx), Persistence::new(store.clone()));
    assert_eq!(recv(&mut probe_rx, "no init probe").await, Probe::Init);
    assert_eq!(
        recv(&mut probe_rx, "no recovered probe").await,
        Probe::Recovered
    );

    system.root().tell(Command::Increment(1));
    system.root().tell(Command::Increment(2));

    let probes = [
        recv(&mut probe_rx, "no first probe").await,
        recv(&mut probe_rx, "no second probe").await,
        recv(&mut probe_rx, "no third probe").await,
        recv(&mut probe_rx, "no fourth probe").await,
    ];
    assert_eq!(
        probes,
        [
            Probe::Handled,
            Probe::Settled(1),
            Probe::Handled,
            Probe::Settled(3)
        ]
    );

    system.root().tell(Command::Stop);
    assert_terminates(system, "system did not terminate").await;
}

/// A watched actor's termination is delivered to `handle` as an ordinary incoming signal.
#[tokio::test]
async fn terminated_signals_reach_handle() {
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let system = ActorSystem::event_sourced(
        Watcher {
            probe_tx,
            bye_before_stopping: false,
        },
        Persistence::new(TestStore::default()),
    );

    system.root().tell(WatcherCommand::StopChild);
    assert_eq!(
        recv(&mut probe_rx, "no terminated probe").await,
        Probe::Terminated
    );

    assert_terminates(system, "system did not terminate").await;
}

/// After `unwatch` no terminated signal is received, even if it is already enqueued: the child
/// says bye through the shared FIFO right before stopping, the watcher unwatches on the bye, and
/// the signal queued behind it is dropped before `handle` ever sees it.
#[tokio::test]
async fn unwatch_drops_an_enqueued_terminated_signal() {
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let system = ActorSystem::event_sourced(
        Watcher {
            probe_tx,
            bye_before_stopping: true,
        },
        Persistence::new(TestStore::default()),
    );

    system.root().tell(WatcherCommand::StopChild);
    assert_eq!(recv(&mut probe_rx, "no bye probe").await, Probe::Bye);

    sleep(Duration::from_millis(100)).await;
    system.root().tell(WatcherCommand::Stop);
    assert_terminates(system, "system did not terminate").await;

    let mut probes = Vec::new();
    while let Ok(probe) = probe_rx.try_recv() {
        probes.push(probe);
    }
    assert!(
        !probes.contains(&Probe::Terminated),
        "no terminated signal must be received after unwatch"
    );
}

/// An undecodable snapshot is not a failure: it is discarded, recovery falls back to full
/// replay seeded by `init`, and the state still comes out right.
#[tokio::test]
async fn undecodable_snapshot_falls_back_to_full_replay() {
    let store = TestStore::default();
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let id = persistence_id("7");
    for (seq_no, increment) in [(0, 1), (1, 2)] {
        store.seed(
            &id,
            StoredEvent {
                seq_no: SeqNo::new(seq_no),
                event: encoded(&Increased(increment)),
            },
        );
    }
    store.seed_snapshot(
        &id,
        StoredSnapshot {
            next_seq_no: SeqNo::new(2),
            snapshot: EncodedSnapshot {
                manifest: Count::MANIFEST.to_string(),
                schema_version: SchemaVersion::new(99),
                payload: Vec::new(),
            },
        },
    );

    let system = ActorSystem::event_sourced(
        Counter::new("7", probe_tx),
        Persistence::new(store.clone()).with_snapshot_store(store.clone()),
    );
    assert_eq!(recv(&mut probe_rx, "no init probe").await, Probe::Init);
    assert_eq!(
        recv(&mut probe_rx, "no recovered probe").await,
        Probe::Recovered
    );

    let count = system
        .root()
        .ask(TIMEOUT, Command::Get)
        .await
        .expect("no reply to get");
    assert_eq!(count, 3);

    system.root().tell(Command::Stop);
    assert_terminates(system, "system did not terminate").await;
}

/// A history the current code cannot decode is a recovery failure: under the default `Stop`
/// strategy the actor stops without ever running `recovered`, and its watchers learn about it.
#[tokio::test]
async fn undecodable_history_stops_the_actor() {
    let store = TestStore::default();
    let (probe_tx, mut probe_rx) = mpsc::unbounded_channel();

    let id = persistence_id("6");
    store.seed(
        &id,
        StoredEvent {
            seq_no: SeqNo::ZERO,
            event: EncodedEvent {
                manifest: Increased::MANIFEST.to_string(),
                schema_version: SchemaVersion::new(99),
                payload: Vec::new(),
            },
        },
    );

    let system =
        ActorSystem::event_sourced(Counter::new("6", probe_tx), Persistence::new(store.clone()));
    assert_terminates(system, "the actor must stop on an undecodable history").await;

    let mut probes = Vec::new();
    while let Ok(probe) = probe_rx.try_recv() {
        probes.push(probe);
    }
    assert_eq!(
        probes,
        [Probe::Init],
        "recovery must fail after init and before recovered"
    );
}

fn persistence_id(entity_id: &str) -> PersistenceId {
    PersistenceId::new("counter", entity_id).expect("the segments are valid")
}

fn encoded(event: &Increased) -> EncodedEvent {
    EncodedEvent {
        manifest: Increased::MANIFEST.to_string(),
        schema_version: Increased::VERSION,
        payload: Cbor.encode(event).expect("the event is encodable"),
    }
}

async fn recv<T>(probe_rx: &mut mpsc::UnboundedReceiver<T>, not_received: &str) -> T {
    timeout(TIMEOUT, probe_rx.recv())
        .await
        .expect(not_received)
        .expect("probe channel closed")
}

async fn assert_terminates<M>(system: ActorSystem<M>, not_terminated: &str)
where
    M: Send + 'static,
{
    timeout(TIMEOUT, system.terminated())
        .await
        .expect(not_terminated)
        .expect("watching the root actor failed");
}

fn restart_config() -> ActorConfig {
    ActorConfig::default().with_supervision_strategy(SupervisionStrategy::Restart(
        RestartPolicy::new(NonZeroU32::new(5).expect("5 is not zero")).with_backoff(
            Backoff::new(Duration::from_millis(1), Duration::from_millis(10))
                .expect("the bounds are ordered"),
        ),
    ))
}

struct Counter {
    entity_id: &'static str,
    probe_tx: mpsc::UnboundedSender<Probe>,
    snapshot_every: Option<u64>,
    recovered_failures: Mutex<u32>,
}

impl Counter {
    fn new(entity_id: &'static str, probe_tx: mpsc::UnboundedSender<Probe>) -> Self {
        Self {
            entity_id,
            probe_tx,
            snapshot_every: None,
            recovered_failures: Mutex::new(0),
        }
    }

    fn with_snapshot_every(mut self, snapshot_every: u64) -> Self {
        self.snapshot_every = Some(snapshot_every);
        self
    }

    fn with_recovered_failures(mut self, failures: u32) -> Self {
        self.recovered_failures = Mutex::new(failures);
        self
    }
}

impl EventSourced for Counter {
    type Command = Command;
    type Event = Increased;
    type State = u64;
    type Snapshot = Count;
    type Error = Boom;

    fn persistence_id(&self) -> PersistenceId {
        persistence_id(self.entity_id)
    }

    fn init(&self) -> Result<Self::State, Self::Error> {
        let _ = self.probe_tx.send(Probe::Init);
        Ok(0)
    }

    fn init_from_snapshot(&self, Count(count): Self::Snapshot) -> Result<Self::State, Self::Error> {
        let _ = self.probe_tx.send(Probe::InitFromSnapshot);
        Ok(count)
    }

    fn recovered(
        &self,
        _: &ActorContext<Self::Command>,
        state: Self::State,
    ) -> Result<Self::State, Self::Error> {
        {
            let mut failures = self
                .recovered_failures
                .lock()
                .expect("recovered failures lock poisoned");
            if *failures > 0 {
                *failures -= 1;
                return Err(Boom);
            }
        }

        let _ = self.probe_tx.send(Probe::Recovered);
        Ok(state)
    }

    fn handle(
        &self,
        _: &ActorContext<Self::Command>,
        incoming: Incoming<Self::Command>,
        _: &Self::State,
    ) -> Result<Effect<Self>, Self::Error> {
        let Incoming::Message(command) = incoming else {
            return Ok(Effect::none());
        };
        let _ = self.probe_tx.send(Probe::Handled);

        match command {
            Command::Increment(n) => {
                let probe_tx = self.probe_tx.clone();
                Ok(Effect::persist(Increased(n)).then(move |count| {
                    let _ = probe_tx.send(Probe::Settled(*count));
                }))
            }

            Command::IncrementTwice(n, m) => Ok(Effect::persist_all([Increased(n), Increased(m)])),

            Command::Get(reply_to) => Ok(Effect::none().then(move |count| reply_to.reply(*count))),

            Command::Fail => Err(Boom),

            Command::Stop => Ok(Effect::stop()),

            Command::StopAfter(n) => Ok(Effect::persist(Increased(n)).and_stop()),
        }
    }

    fn apply(&self, state: Self::State, Increased(n): Self::Event) -> Self::State {
        state + n
    }

    fn snapshot(&self, state: &Self::State) -> Result<Option<Self::Snapshot>, Self::Error> {
        match self.snapshot_every {
            Some(every) if state % every == 0 => Ok(Some(Count(*state))),
            _ => Ok(None),
        }
    }
}

#[derive(Debug)]
enum Command {
    Increment(u64),
    IncrementTwice(u64, u64),
    Get(ReplyTo<u64>),
    Fail,
    Stop,
    StopAfter(u64),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
struct Increased(u64);

impl Versioned for Increased {
    const MANIFEST: &'static str = "increased";
    const VERSION: SchemaVersion = SchemaVersion::new(1);
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
struct Count(u64);

impl Versioned for Count {
    const MANIFEST: &'static str = "count";
    const VERSION: SchemaVersion = SchemaVersion::new(1);
}

#[derive(Debug, Error)]
#[error("boom")]
struct Boom;

#[derive(Debug, PartialEq, Eq)]
enum Probe {
    Init,
    InitFromSnapshot,
    Recovered,
    Handled,
    Settled(u64),
    Bye,
    Terminated,
}

struct Watcher {
    probe_tx: mpsc::UnboundedSender<Probe>,
    bye_before_stopping: bool,
}

impl EventSourced for Watcher {
    type Command = WatcherCommand;
    type Event = Nothing;
    type State = Option<ActorRef<()>>;
    type Snapshot = Nothing;
    type Error = Infallible;

    fn persistence_id(&self) -> PersistenceId {
        persistence_id("watcher")
    }

    fn init(&self) -> Result<Self::State, Self::Error> {
        Ok(None)
    }

    fn init_from_snapshot(&self, snapshot: Self::Snapshot) -> Result<Self::State, Self::Error> {
        match snapshot {}
    }

    fn recovered(
        &self,
        context: &ActorContext<Self::Command>,
        _: Self::State,
    ) -> Result<Self::State, Self::Error> {
        let child = context.spawn(Child {
            parent: self.bye_before_stopping.then(|| context.self_ref().clone()),
        });
        context.watch(&child);

        Ok(Some(child))
    }

    fn handle(
        &self,
        context: &ActorContext<Self::Command>,
        incoming: Incoming<Self::Command>,
        state: &Self::State,
    ) -> Result<Effect<Self>, Self::Error> {
        match incoming {
            Incoming::Message(WatcherCommand::StopChild) => {
                if let Some(child) = state {
                    child.tell(());
                }
                Ok(Effect::none())
            }

            Incoming::Message(WatcherCommand::Bye) => {
                let _ = self.probe_tx.send(Probe::Bye);
                if let Some(child) = state {
                    context.unwatch(child);
                }
                Ok(Effect::none())
            }

            Incoming::Message(WatcherCommand::Stop) => Ok(Effect::stop()),

            Incoming::Terminated(_) => {
                let _ = self.probe_tx.send(Probe::Terminated);
                Ok(Effect::stop())
            }
        }
    }

    fn apply(&self, _: Self::State, event: Self::Event) -> Self::State {
        match event {}
    }
}

#[derive(Debug)]
enum WatcherCommand {
    StopChild,
    Bye,
    Stop,
}

struct Child {
    parent: Option<ActorRef<WatcherCommand>>,
}

impl Actor for Child {
    type Message = ();
    type State = ();
    type Error = Infallible;

    fn init(&self, _: &ActorContext<Self::Message>) -> Result<Self::State, Self::Error> {
        Ok(())
    }

    fn receive(
        &self,
        _: &ActorContext<Self::Message>,
        incoming: Incoming<Self::Message>,
        state: Self::State,
    ) -> Result<Control<Self::State>, Self::Error> {
        match incoming {
            Incoming::Message(()) => {
                if let Some(parent) = &self.parent {
                    parent.tell(WatcherCommand::Bye);
                }
                Ok(Control::Stop)
            }

            Incoming::Terminated(_) => Ok(Control::Continue(state)),
        }
    }
}

struct Parent {
    store: TestStore,
    probe_tx: mpsc::UnboundedSender<Probe>,
}

impl Actor for Parent {
    type Message = ();
    type State = ();
    type Error = Infallible;

    fn init(&self, context: &ActorContext<Self::Message>) -> Result<Self::State, Self::Error> {
        context.spawn_event_sourced(
            Counter::new("13", self.probe_tx.clone()),
            Persistence::new(self.store.clone()),
        );

        Ok(())
    }

    fn receive(
        &self,
        _: &ActorContext<Self::Message>,
        incoming: Incoming<Self::Message>,
        state: Self::State,
    ) -> Result<Control<Self::State>, Self::Error> {
        match incoming {
            Incoming::Message(()) => Ok(Control::Stop),
            Incoming::Terminated(_) => Ok(Control::Continue(state)),
        }
    }
}

#[derive(Debug, Clone, Default)]
struct TestStore {
    streams: Arc<Mutex<HashMap<PersistenceId, Vec<StoredEvent>>>>,
    snapshots: Arc<Mutex<HashMap<PersistenceId, StoredSnapshot>>>,
    reads: Arc<Mutex<Vec<SeqNo>>>,
    append_delay: Option<Duration>,
    append_failures: Arc<Mutex<u32>>,
    append_panics: Arc<Mutex<u32>>,
    hang_reads: bool,
    fail_saves: bool,
}

impl TestStore {
    fn with_append_delay(mut self, append_delay: Duration) -> Self {
        self.append_delay = Some(append_delay);
        self
    }

    fn with_append_failures(mut self, failures: u32) -> Self {
        self.append_failures = Arc::new(Mutex::new(failures));
        self
    }

    fn with_append_panics(mut self, panics: u32) -> Self {
        self.append_panics = Arc::new(Mutex::new(panics));
        self
    }

    fn with_hanging_reads(mut self) -> Self {
        self.hang_reads = true;
        self
    }

    fn with_failing_saves(mut self) -> Self {
        self.fail_saves = true;
        self
    }

    fn seed(&self, id: &PersistenceId, stored: StoredEvent) {
        self.streams
            .lock()
            .expect("streams lock poisoned")
            .entry(id.clone())
            .or_default()
            .push(stored);
    }

    fn seed_snapshot(&self, id: &PersistenceId, stored: StoredSnapshot) {
        self.snapshots
            .lock()
            .expect("snapshots lock poisoned")
            .insert(id.clone(), stored);
    }

    fn stream(&self, id: &PersistenceId) -> Vec<StoredEvent> {
        self.streams
            .lock()
            .expect("streams lock poisoned")
            .get(id)
            .cloned()
            .unwrap_or_default()
    }

    fn reads(&self) -> Vec<SeqNo> {
        self.reads.lock().expect("reads lock poisoned").clone()
    }
}

impl EventStore for TestStore {
    type Error = TestStoreError;

    async fn append(
        &self,
        id: &PersistenceId,
        next_seq_no: SeqNo,
        events: Vec<EncodedEvent>,
    ) -> Result<(), AppendError<Self::Error>> {
        if let Some(append_delay) = self.append_delay {
            sleep(append_delay).await;
        }

        {
            let mut failures = self
                .append_failures
                .lock()
                .expect("append failures lock poisoned");
            if *failures > 0 {
                *failures -= 1;
                return Err(AppendError::Store(TestStoreError));
            }
        }

        // Panic outside the lock scope, else the poisoned lock fails every later append.
        let panic = {
            let mut panics = self
                .append_panics
                .lock()
                .expect("append panics lock poisoned");
            if *panics > 0 {
                *panics -= 1;
                true
            } else {
                false
            }
        };
        if panic {
            panic!("append panicked");
        }

        let mut streams = self.streams.lock().expect("streams lock poisoned");
        let stream = streams.entry(id.clone()).or_default();
        if SeqNo::new(stream.len() as u64) != next_seq_no {
            return Err(AppendError::Conflict);
        }

        for (n, event) in events.into_iter().enumerate() {
            stream.push(StoredEvent {
                seq_no: next_seq_no.advanced_by(n),
                event,
            });
        }

        Ok(())
    }

    async fn read(
        &self,
        id: &PersistenceId,
        from_seq_no: SeqNo,
        limit: NonZeroUsize,
    ) -> Result<Vec<StoredEvent>, Self::Error> {
        if self.hang_reads {
            pending::<()>().await;
        }

        self.reads
            .lock()
            .expect("reads lock poisoned")
            .push(from_seq_no);

        let streams = self.streams.lock().expect("streams lock poisoned");
        let events = streams
            .get(id)
            .map(|stream| {
                stream
                    .iter()
                    .filter(|stored| stored.seq_no >= from_seq_no)
                    .take(limit.get())
                    .cloned()
                    .collect()
            })
            .unwrap_or_default();

        Ok(events)
    }
}

impl SnapshotStore for TestStore {
    type Error = TestStoreError;

    async fn save(
        &self,
        id: &PersistenceId,
        next_seq_no: SeqNo,
        snapshot: EncodedSnapshot,
    ) -> Result<(), Self::Error> {
        if self.fail_saves {
            return Err(TestStoreError);
        }

        self.snapshots
            .lock()
            .expect("snapshots lock poisoned")
            .insert(
                id.clone(),
                StoredSnapshot {
                    next_seq_no,
                    snapshot,
                },
            );

        Ok(())
    }

    async fn load(&self, id: &PersistenceId) -> Result<Option<StoredSnapshot>, Self::Error> {
        let snapshot = self
            .snapshots
            .lock()
            .expect("snapshots lock poisoned")
            .get(id)
            .cloned();

        Ok(snapshot)
    }
}

#[derive(Debug, Error)]
#[error("test store failure")]
struct TestStoreError;