forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtests.rs
More file actions
6207 lines (5640 loc) · 217 KB
/
Copy pathtests.rs
File metadata and controls
6207 lines (5640 loc) · 217 KB
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
//! Runtime integration tests.
//!
//! 84 tests total (see AGENTS.md "Testing & QA" for the suite-wide counts).
//! Full history in local commit 1c2cde9.
use super::*;
use crate::runtime::gc::OrcaGc;
use crate::runtime::heap::{ActorHeap, TypeTag};
use crate::vm::Frame;
use std::collections::HashSet;
use std::sync::Arc;
use std::time::{Duration, Instant};
// ========================================================================
// Core Runtime Tests
// ========================================================================
#[test]
fn test_spawn_send_step_sequence() {
let mut rt = Runtime::new();
let actor_id = rt.spawn_actor(Box::new(|| vec![("count".to_string(), Value::int(0))]));
assert!(rt.actors.contains_key(&actor_id));
{
let actor = rt.actors.get_mut(&actor_id).unwrap();
actor.register_behavior("inc", |actor, args| {
if let Some(n) = actor.get_state_field("counter").and_then(|v| v.as_int()) {
if let Some(incr) = args.get(0).and_then(|v| v.as_int()) {
actor.set_state_field("counter", Value::int(n + incr));
}
}
});
}
rt.send_message(actor_id, "inc", &[Value::int(1)]);
rt.step_actor(actor_id);
// Message processed
}
#[test]
fn test_mailbox_push_pop() {
let mut mb = Mailbox::new(4);
let msg = Message {
behavior_id: 0,
payload: Arc::new(vec![Value::int(42)]),
sender: 1,
priority: MessagePriority::Normal,
trace_id: None,
};
assert!(mb.push(msg.clone()).is_ok());
assert_eq!(mb.len(), 1);
let popped = mb.pop().unwrap();
assert_eq!(popped.payload[0].as_int(), Some(42));
assert!(mb.is_empty());
}
#[test]
fn test_send_carries_current_trace_span() {
let mut rt = Runtime::new();
let b = rt.spawn_actor(Box::new(|| vec![]));
let root = TraceContext::root();
rt.current_trace = Some(root);
rt.send_message_by_id(b, 0, &[]);
let actor = rt.actors.get_mut(&b).unwrap();
let msg = actor.receive().expect("message delivered");
let tp = msg
.trace_id
.expect("outgoing message carries a traceparent");
let parsed = TraceContext::from_traceparent(&tp).expect("valid traceparent");
// `traceparent` carries the current span (trace-id + span-id), so the
// outgoing message exposes the handler's span for the receiver to child.
assert_eq!(parsed.trace_id(), root.trace_id());
assert_eq!(parsed.span_id(), root.span_id());
}
#[test]
fn test_delivery_establishes_child_context_and_inherits() {
let mut rt = Runtime::new();
let a = rt.spawn_actor(Box::new(|| vec![]));
// Deliver a message carrying a known W3C traceparent (the W3C spec example).
let incoming = "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01";
{
let actor = rt.actors.get_mut(&a).unwrap();
actor
.mailbox
.push(Message {
behavior_id: 0,
payload: Arc::new(vec![]),
sender: 0,
priority: MessagePriority::Normal,
trace_id: Some(incoming.to_string()),
})
.unwrap();
}
rt.step_actor(a);
let ctx = rt
.current_trace
.expect("delivery establishes a trace context");
assert_eq!(ctx.trace_id(), 0x4bf9_2f35_77b3_4da6_a3ce_929d_0e0e_4736);
assert_eq!(ctx.parent_span_id(), 0x00f0_67aa_0ba9_02b7);
// A send performed after delivery inherits the same trace.
let b = rt.spawn_actor(Box::new(|| vec![]));
rt.send_message_by_id(b, 0, &[]);
let msg = rt.actors.get_mut(&b).unwrap().receive().expect("delivered");
let child = TraceContext::from_traceparent(&msg.trace_id.expect("stamped")).unwrap();
// The send carries `ctx`'s span (traceparent has no parent field); a
// receiver would child off it, continuing the same trace.
assert_eq!(child.trace_id(), ctx.trace_id());
assert_eq!(child.span_id(), ctx.span_id());
}
#[test]
fn test_scheduler_enqueue_steal() {
let sched = Scheduler::new(4);
assert!(sched.steal_one().is_none());
sched.enqueue(100);
sched.enqueue(200);
// Global injector is FIFO: 100 was enqueued first, so it's stolen first
assert_eq!(sched.steal_one(), Some(100));
assert_eq!(sched.steal_one(), Some(200));
assert!(sched.steal_one().is_none());
}
#[test]
fn test_actor_register_behavior() {
let mut actor = Actor::new(1, "test_actor", 0);
actor.register_behavior("hello", |_actor, _args| {});
assert_eq!(actor.behavior_table.len(), 1);
assert_eq!(actor.behavior_table[0].name, "hello");
}
#[test]
fn test_run_scheduler_processes_all_actors() {
let mut rt = Runtime::new();
let a1 = rt.spawn_actor(Box::new(|| vec![("counter".to_string(), Value::int(0))]));
let a2 = rt.spawn_actor(Box::new(|| vec![("counter".to_string(), Value::int(0))]));
rt.send_message(a1, "add", &[Value::int(10)]);
rt.send_message(a2, "add", &[Value::int(20)]);
rt.run_scheduler();
}
// ========================================================================
// Actor Priority Tests
// ========================================================================
#[test]
fn test_actor_priority_default_is_normal() {
let actor = Actor::new(1, "test_actor", 0);
assert_eq!(actor.priority, ActorPriority::Normal);
assert_eq!(ActorPriority::default(), ActorPriority::Normal);
}
#[test]
fn test_scheduler_priority_dequeue_order() {
// Strict per-level preference: every High entry drains before any
// Normal, every Normal before any Low; FIFO within a level.
let sched = Scheduler::new(4);
sched.enqueue_with_priority(1, ActorPriority::Normal);
sched.enqueue_with_priority(2, ActorPriority::Low);
sched.enqueue_with_priority(3, ActorPriority::High);
sched.enqueue_with_priority(4, ActorPriority::Normal);
sched.enqueue_with_priority(5, ActorPriority::High);
sched.enqueue_with_priority(6, ActorPriority::Low);
assert_eq!(sched.steal_one(), Some(3));
assert_eq!(sched.steal_one(), Some(5));
assert_eq!(sched.steal_one(), Some(1));
assert_eq!(sched.steal_one(), Some(4));
assert_eq!(sched.steal_one(), Some(2));
assert_eq!(sched.steal_one(), Some(6));
assert!(sched.steal_one().is_none());
}
#[test]
fn test_scheduler_enqueue_defaults_to_normal() {
// The plain `enqueue` entry point lands in the Normal level.
let sched = Scheduler::new(2);
sched.enqueue(1); // Normal
sched.enqueue_with_priority(2, ActorPriority::High);
sched.enqueue_with_priority(3, ActorPriority::Low);
assert_eq!(sched.steal_one(), Some(2));
assert_eq!(sched.steal_one(), Some(1));
assert_eq!(sched.steal_one(), Some(3));
}
#[test]
fn test_actor_set_priority_effect_maps_levels() {
let mut rt = Runtime::new();
let a = rt.spawn_actor(Box::new(|| vec![]));
let set = |rt: &mut Runtime, who: Option<u64>, level: i64| {
rt.perform_actor_builtin(who, Some("set_priority"), &[], &[Value::int(level)])
};
assert_eq!(set(&mut rt, Some(a), 0), Some(Value::nil()));
assert_eq!(rt.actors.get(&a).unwrap().priority, ActorPriority::High);
assert_eq!(set(&mut rt, Some(a), 2), Some(Value::nil()));
assert_eq!(rt.actors.get(&a).unwrap().priority, ActorPriority::Low);
assert_eq!(set(&mut rt, Some(a), 1), Some(Value::nil()));
assert_eq!(rt.actors.get(&a).unwrap().priority, ActorPriority::Normal);
// Out-of-range levels fall back to Normal.
assert_eq!(set(&mut rt, Some(a), 7), Some(Value::nil()));
assert_eq!(rt.actors.get(&a).unwrap().priority, ActorPriority::Normal);
// Outside an actor context the effect is a nil no-op.
assert_eq!(set(&mut rt, None, 0), Some(Value::nil()));
}
#[test]
fn test_actor_set_priority_changes_scheduling() {
// A High-priority actor is dequeued before a Normal one even when the
// Normal actor's message was sent first.
let mut rt = Runtime::new();
let a = rt.spawn_actor(Box::new(|| vec![]));
let b = rt.spawn_actor(Box::new(|| vec![]));
// Drain the spawn-time queue entries (both enqueued at Normal).
assert_eq!(rt.scheduler.dequeue(), Some(a));
assert_eq!(rt.scheduler.dequeue(), Some(b));
// Boost b via the builtin-effect path, then send to a before b.
assert_eq!(
rt.perform_actor_builtin(Some(b), Some("set_priority"), &[], &[Value::int(0)]),
Some(Value::nil())
);
rt.send_message(a, "noop", &[]);
rt.send_message(b, "noop", &[]);
assert_eq!(rt.scheduler.dequeue(), Some(b));
assert_eq!(rt.scheduler.dequeue(), Some(a));
}
// ========================================================================
// Supervisor Tests
// ========================================================================
#[test]
fn test_one_for_one_restart() {
let mut rt = Runtime::new();
let sup_id = rt.create_supervisor("test_sup", RestartStrategy::OneForOne);
let child_id = rt.spawn_actor(Box::new(|| vec![("x".to_string(), Value::int(0))]));
let spec = ChildSpec::new("child1", RestartPolicy::Permanent);
rt.supervise_child(sup_id, spec, child_id);
assert_eq!(rt.supervisors[&sup_id].child_count(), 1);
rt.exit_actor(child_id, ExitReason::Error("crash".to_string()));
assert!(!rt.actors.contains_key(&child_id));
assert_eq!(rt.supervisors[&sup_id].child_count(), 1);
}
#[test]
fn test_supervisor_restart_rate_limiting() {
let mut rt = Runtime::new();
let sup_id = rt.create_supervisor("rate_sup", RestartStrategy::OneForOne);
let child_id = rt.spawn_actor(Box::new(|| vec![]));
let spec = ChildSpec::new("fragile", RestartPolicy::Permanent).with_limits(2, 60);
rt.supervise_child(sup_id, spec, child_id);
// Crash 1: child should be restarted (restart #1)
rt.exit_actor(child_id, ExitReason::Error("crash1".to_string()));
let child_id_2 = rt.supervisors[&sup_id].children[0].1;
assert_eq!(rt.supervisors[&sup_id].restart_count(child_id_2), 1);
// Crash 2: child should be restarted again (restart #2)
rt.exit_actor(child_id_2, ExitReason::Error("crash2".to_string()));
let child_id_3 = rt.supervisors[&sup_id].children[0].1;
assert_eq!(rt.supervisors[&sup_id].restart_count(child_id_3), 2);
// Crash 3: max_restarts=2 exceeded → supervisor shuts down
rt.exit_actor(child_id_3, ExitReason::Error("crash3".to_string()));
assert!(
!rt.supervisors.contains_key(&sup_id),
"supervisor should shut down after max restarts"
);
}
#[test]
fn test_supervisor_escalate_to_parent() {
let mut rt = Runtime::new();
let parent_sup = rt.create_supervisor("parent", RestartStrategy::OneForOne);
let child_sup = rt.create_supervisor("child", RestartStrategy::OneForOne);
rt.supervisors.get_mut(&child_sup).unwrap().parent = Some(parent_sup);
let grandchild = rt.spawn_actor(Box::new(|| vec![]));
let spec = ChildSpec::new("gc", RestartPolicy::Permanent).with_limits(1, 60);
rt.supervise_child(child_sup, spec, grandchild);
rt.exit_actor(grandchild, ExitReason::Error("boom".to_string()));
assert!(
rt.actors.contains_key(&child_sup),
"child supervisor should still exist after one restart"
);
let gc2 = rt.supervisors[&child_sup].children[0].1;
rt.exit_actor(gc2, ExitReason::Error("boom2".to_string()));
}
/// Regression (Phase 5 deliverable 9): restarting a supervisor actor must
/// recreate its `Supervisor` struct under the new actor id — a supervised
/// supervisor that loses its struct stops supervising its own children.
#[test]
fn test_supervised_supervisor_keeps_supervising_after_restart() {
let mut rt = Runtime::new();
let parent = rt.create_supervisor("parent", RestartStrategy::OneForOne);
let child_sup = rt.create_supervisor("child", RestartStrategy::OneForOne);
rt.supervise_child(
parent,
ChildSpec::new("child_sup", RestartPolicy::Permanent),
child_sup,
);
let grandchild = rt.spawn_actor(Box::new(|| vec![]));
rt.supervise_child(
child_sup,
ChildSpec::new("gc", RestartPolicy::Permanent),
grandchild,
);
rt.supervisors.get_mut(&child_sup).unwrap().parent = Some(parent);
// Crash the child supervisor's actor: the parent restarts it under a
// fresh actor id.
rt.exit_actor(child_sup, ExitReason::Error("sup crashed".to_string()));
let new_sup_id = rt.supervisors[&parent].children[0].1;
assert_ne!(new_sup_id, child_sup, "supervisor actor must be rebuilt");
// The Supervisor struct must follow the actor to its new id, still
// supervising the grandchild.
assert!(
rt.supervisors.contains_key(&new_sup_id),
"restarted supervisor must have a live Supervisor struct"
);
assert!(
!rt.supervisors.contains_key(&child_sup),
"the old supervisor struct must not linger under a dead actor id"
);
let gc_id = rt.supervisors[&new_sup_id].children[0].1;
assert_eq!(
rt.actors.get(&gc_id).unwrap().parent,
Some(new_sup_id),
"grandchild must be re-pointed at the new supervisor id"
);
// Supervision must actually work through the recreated struct: a
// grandchild crash restarts it.
rt.exit_actor(gc_id, ExitReason::Error("boom".to_string()));
let new_gc = rt.supervisors[&new_sup_id].children[0].1;
assert_ne!(
new_gc, gc_id,
"grandchild must be restarted by the recreated supervisor"
);
}
/// Regression (Phase 5 deliverable 10): a OneForAll restart must respect
/// each sibling's own restart intensity. A sibling whose MaxR is exhausted
/// must be dropped, not rebuilt — otherwise the group can restart-loop
/// forever even though every child's limits are individually respected.
#[test]
fn test_one_for_all_respects_sibling_rate_limit() {
let mut rt = Runtime::new();
let sup_id = rt.create_supervisor("sup", RestartStrategy::OneForAll);
let trigger = rt.spawn_actor(Box::new(|| vec![]));
rt.supervise_child(
sup_id,
ChildSpec::new("trigger", RestartPolicy::Permanent),
trigger,
);
let fragile = rt.spawn_actor(Box::new(|| vec![]));
rt.supervise_child(
sup_id,
ChildSpec::new("fragile", RestartPolicy::Permanent).with_limits(1, 60),
fragile,
);
let sibling = rt.spawn_actor(Box::new(|| vec![]));
rt.supervise_child(
sup_id,
ChildSpec::new("sibling", RestartPolicy::Permanent),
sibling,
);
// Crash 1: the OneForAll cascade rebuilds every child, recording
// fragile's first (and only permitted) restart.
rt.exit_actor(trigger, ExitReason::Error("crash1".to_string()));
assert_eq!(rt.supervisors[&sup_id].child_count(), 3);
// Crash 2: the cascade must NOT rebuild fragile again — its MaxR of 1
// is exhausted. It is stopped and dropped from supervision instead.
let trigger2 = rt.supervisors[&sup_id]
.children
.iter()
.find(|(s, _)| s.id == "trigger")
.unwrap()
.1;
rt.exit_actor(trigger2, ExitReason::Error("crash2".to_string()));
assert_eq!(
rt.supervisors[&sup_id].child_count(),
2,
"the rate-limited sibling must be dropped, not rebuilt"
);
assert!(
rt.supervisors[&sup_id]
.children
.iter()
.all(|(s, _)| s.id != "fragile"),
"the rate-limited sibling must be gone from supervision"
);
}
/// Regression (Phase 5 deliverable 10, RestForOne variant): same per-sibling
/// rate-limit discipline in the restart-from cascade.
#[test]
fn test_rest_for_one_respects_sibling_rate_limit() {
let mut rt = Runtime::new();
let sup_id = rt.create_supervisor("sup", RestartStrategy::RestForOne);
let trigger = rt.spawn_actor(Box::new(|| vec![]));
rt.supervise_child(
sup_id,
ChildSpec::new("trigger", RestartPolicy::Permanent),
trigger,
);
let fragile = rt.spawn_actor(Box::new(|| vec![]));
rt.supervise_child(
sup_id,
ChildSpec::new("fragile", RestartPolicy::Permanent).with_limits(1, 60),
fragile,
);
let sibling = rt.spawn_actor(Box::new(|| vec![]));
rt.supervise_child(
sup_id,
ChildSpec::new("sibling", RestartPolicy::Permanent),
sibling,
);
// Crash fragile: RestForOne restarts fragile and everything after it,
// recording fragile's only permitted restart.
rt.exit_actor(fragile, ExitReason::Error("crash1".to_string()));
assert_eq!(rt.supervisors[&sup_id].child_count(), 3);
// Crash trigger: the cascade (trigger, fragile, sibling) must not
// rebuild fragile again.
let trigger2 = rt.supervisors[&sup_id]
.children
.iter()
.find(|(s, _)| s.id == "trigger")
.unwrap()
.1;
rt.exit_actor(trigger2, ExitReason::Error("crash2".to_string()));
assert_eq!(
rt.supervisors[&sup_id].child_count(),
2,
"the rate-limited sibling must be dropped, not rebuilt"
);
assert!(
rt.supervisors[&sup_id]
.children
.iter()
.all(|(s, _)| s.id != "fragile"),
"the rate-limited sibling must be gone from supervision"
);
}
#[test]
fn test_temporary_child_not_restarted() {
let mut rt = Runtime::new();
let sup_id = rt.create_supervisor("sup", RestartStrategy::OneForOne);
let child_id = rt.spawn_actor(Box::new(|| vec![]));
let spec = ChildSpec::new("temp_child", RestartPolicy::Temporary);
rt.supervise_child(sup_id, spec, child_id);
rt.exit_actor(child_id, ExitReason::Error("boom".to_string()));
assert_eq!(rt.supervisors[&sup_id].child_count(), 0);
}
/// Regression test: a restarted child must be rebuilt with its behavior
/// table and initial state, not as a bare actor that silently drops every
/// message it receives.
#[test]
fn test_restarted_child_restores_behavior_and_state() {
let mut rt = Runtime::new();
let sup_id = rt.create_supervisor("test_sup", RestartStrategy::OneForOne);
let child_id = rt.spawn_actor(Box::new(|| vec![("count".to_string(), Value::int(0))]));
{
let actor = rt.actors.get_mut(&child_id).unwrap();
actor.register_behavior("inc", |actor, args| {
let n = actor
.get_state_field("count")
.and_then(|v| v.as_int())
.unwrap_or(0);
let by = args.get(0).and_then(|v| v.as_int()).unwrap_or(1);
actor.set_state_field("count", Value::int(n + by));
});
}
let spec = ChildSpec::new("child1", RestartPolicy::Permanent);
rt.supervise_child(sup_id, spec, child_id);
rt.exit_actor(child_id, ExitReason::Error("crash".to_string()));
let new_id = rt.supervisors[&sup_id].children[0].1;
assert_ne!(new_id, child_id, "restart should create a fresh actor");
// The restarted child must handle messages (before the fix it was a
// bare actor that silently dropped them).
rt.send_message(new_id, "inc", &[Value::int(5)]);
rt.step_actor(new_id);
let count = rt.actors.get(&new_id).unwrap().get_state_field("count");
assert_eq!(count, Some(Value::int(5)));
}
/// Supervisor restart of a persistent child must hydrate state from the
/// persistence store, not from the captured RestartTemplate (which holds
/// the *original* state from registration time).
#[test]
fn test_supervisor_restart_hydrates_from_persistence() {
let mut rt = Runtime::new();
rt.persistence = Box::new(MemoryStore::new());
let sup_id = rt.create_supervisor("sup", RestartStrategy::OneForOne);
let mut models = HashMap::new();
models.insert("count".to_string(), StateModel::Durable);
let child_id = rt.spawn_persistent_actor(
Box::new(|| vec![("count".to_string(), Value::int(0))]),
models,
);
{
let actor = rt.actors.get_mut(&child_id).unwrap();
actor.register_behavior("inc", |actor, args| {
let n = actor
.get_state_field("count")
.and_then(|v| v.as_int())
.unwrap_or(0);
let by = args.get(0).and_then(|v| v.as_int()).unwrap_or(1);
actor.set_state_field("count", Value::int(n + by));
});
}
for _ in 0..3 {
rt.send_message(child_id, "inc", &[Value::int(1)]);
rt.step_actor(child_id);
}
assert_eq!(
rt.actors.get(&child_id).unwrap().get_state_field("count"),
Some(Value::int(3)),
"count should be 3 before crash"
);
assert!(
rt.persistence.load_snapshot(child_id).is_some(),
"snapshot should exist before crash"
);
let spec = ChildSpec::new("counter", RestartPolicy::Permanent);
rt.supervise_child(sup_id, spec, child_id);
rt.exit_actor(child_id, ExitReason::Error("simulated crash".to_string()));
let new_id = rt.supervisors[&sup_id].children[0].1;
assert_ne!(new_id, child_id, "restart should create a fresh actor");
let count = rt.actors.get(&new_id).unwrap().get_state_field("count");
assert_eq!(
count,
Some(Value::int(3)),
"restarted actor must hydrate count=3 from persistence, not template count=0"
);
assert!(
rt.persistence.load_snapshot(new_id).is_some(),
"snapshot must be re-keyed under new actor id"
);
assert!(
rt.persistence.load_snapshot(child_id).is_none(),
"old snapshot must be cleared after re-keying"
);
}
/// Regression test: a restarted bytecode child must keep its bytecode
/// module, behavior offsets, and captured initial state so it still
/// resolves and runs its bytecode behaviors after a restart.
#[test]
fn test_restarted_bytecode_child_handles_messages() {
use crate::bytecode::{BehaviorTableEntry, CodeModule, Constant, Instruction, OpCode};
let mut rt = Runtime::new();
let sup_id = rt.create_supervisor("byte_sup", RestartStrategy::OneForOne);
// Behavior "Counter.inc": count += 1, returning the new count.
let mut module = CodeModule::new("test");
let field_idx = module.add_constant(Constant::String("count".to_string()));
let one_idx = module.add_constant(Constant::Int(1));
module.add_behavior(BehaviorTableEntry {
name: "Counter.inc".to_string(),
param_count: 0,
code_offset: 0,
local_count: 4,
effect_mask: 0,
compensate_offset: None,
content_hash: None,
source_location: None,
parallel_branches: None,
});
module.emit(Instruction::new3(
OpCode::StateGet,
((field_idx >> 8) & 0xFF) as u8,
(field_idx & 0xFF) as u8,
1,
));
module.emit(Instruction::new3(
OpCode::ConstU,
((one_idx >> 8) & 0xFF) as u8,
(one_idx & 0xFF) as u8,
2,
));
module.emit(Instruction::new3(OpCode::IAdd, 1, 2, 3));
module.emit(Instruction::new3(OpCode::StateSet, 0, 0, 3));
module.emit(Instruction::new1(OpCode::RetVal, 3));
let child_id = rt.spawn_actor(Box::new(|| vec![("count".to_string(), Value::int(0))]));
{
let actor = rt.actors.get_mut(&child_id).unwrap();
actor.bytecode_module = Some(module.clone());
actor.bytecode_offsets = vec![0];
actor.compensation_offsets = vec![None];
}
rt.register_recovery_module(child_id, module, vec![0], vec![None]);
let spec = ChildSpec::new("counter", RestartPolicy::Permanent);
rt.supervise_child(sup_id, spec, child_id);
// Sanity: the behavior works before the crash.
let before = rt.ask_actor_sync(child_id, 0, &[]).unwrap();
assert_eq!(before, Value::int(1));
rt.exit_actor(child_id, ExitReason::Error("crash".to_string()));
let new_id = rt.supervisors[&sup_id].children[0].1;
assert_ne!(new_id, child_id);
// After restart the child must still resolve and run its bytecode
// behavior (before the fix the bare actor answered every ask with nil).
assert_eq!(rt.behavior_id_for(new_id, "inc"), Some(0));
let after = rt.ask_actor_sync(new_id, 0, &[]).unwrap();
assert_eq!(
after,
Value::int(1),
"restarted child must restart from its captured initial state"
);
// And the module was re-registered for recovery after a runtime restart.
assert!(rt.recovery_modules.contains_key(&new_id));
}
/// Regression test: OneForAll mass restart removes the LIVING sibling
/// children through the full exit protocol — registry names are
/// unregistered and monitors receive a DOWN message.
#[test]
fn test_restart_all_unregisters_names_and_notifies_monitors() {
let mut rt = Runtime::new();
let sup_id = rt.create_supervisor("all_sup", RestartStrategy::OneForAll);
let trigger = rt.spawn_actor(Box::new(|| vec![]));
let sibling = rt.spawn_actor(Box::new(|| vec![]));
rt.supervise_child(
sup_id,
ChildSpec::new("trigger", RestartPolicy::Permanent),
trigger,
);
rt.supervise_child(
sup_id,
ChildSpec::new("sibling", RestartPolicy::Permanent),
sibling,
);
rt.registry.register("sibling_name", sibling).unwrap();
let watcher = rt.spawn_actor(Box::new(|| vec![]));
rt.monitor(watcher, sibling);
rt.exit_actor(trigger, ExitReason::Error("crash".to_string()));
assert!(
!rt.actors.contains_key(&sibling),
"living sibling must be replaced on a OneForAll restart"
);
assert_eq!(
rt.registry.whereis("sibling_name"),
None,
"removed child's registered name must not linger"
);
let down = rt
.actors
.get_mut(&watcher)
.unwrap()
.mailbox
.pop()
.expect("monitor of the removed sibling must receive a DOWN message");
assert_eq!(down.payload[0].as_int(), Some(sibling as i64));
assert_eq!(rt.supervisors[&sup_id].child_count(), 2);
}
/// Regression test: when a supervisor shuts down (restart intensity
/// exceeded), its remaining living children are removed through the exit
/// protocol too — not via a raw map removal.
#[test]
fn test_supervisor_shutdown_cleans_up_children() {
let mut rt = Runtime::new();
let sup_id = rt.create_supervisor("rate_sup", RestartStrategy::OneForOne);
let fragile = rt.spawn_actor(Box::new(|| vec![]));
rt.supervise_child(
sup_id,
ChildSpec::new("fragile", RestartPolicy::Permanent).with_limits(1, 60),
fragile,
);
let sibling = rt.spawn_actor(Box::new(|| vec![]));
rt.supervise_child(
sup_id,
ChildSpec::new("sibling", RestartPolicy::Permanent),
sibling,
);
rt.registry.register("sibling_name", sibling).unwrap();
let watcher = rt.spawn_actor(Box::new(|| vec![]));
rt.monitor(watcher, sibling);
// Crash 1 restarts the fragile child (within limits); crash 2 exceeds
// the intensity and shuts the supervisor down, which must remove the
// living sibling through the exit protocol.
rt.exit_actor(fragile, ExitReason::Error("crash1".to_string()));
let fragile2 = rt.supervisors[&sup_id]
.children
.iter()
.find(|(s, _)| s.id == "fragile")
.unwrap()
.1;
rt.exit_actor(fragile2, ExitReason::Error("crash2".to_string()));
assert!(!rt.supervisors.contains_key(&sup_id));
assert!(!rt.actors.contains_key(&sibling));
assert_eq!(
rt.registry.whereis("sibling_name"),
None,
"shut-down supervisor must unregister its children's names"
);
let down = rt.actors.get_mut(&watcher).unwrap().mailbox.pop();
assert!(
down.is_some(),
"monitor of a child removed by supervisor shutdown must receive DOWN"
);
}
/// Regression test: a supervised child that exits with an outstanding
/// foreign reference must have its heap retired (not dropped wholesale),
/// exactly like an unsupervised exit via `remove_actor_reaping`.
#[test]
fn test_supervised_child_restart_retires_heap_with_foreign_refs() {
let mut rt = Runtime::new();
let sup_id = rt.create_supervisor("reap_sup", RestartStrategy::OneForOne);
let a = rt.spawn_actor(Box::new(|| vec![]));
rt.supervise_child(sup_id, ChildSpec::new("a", RestartPolicy::Permanent), a);
let b = rt.spawn_actor(Box::new(|| vec![]));
rt.current_actor = Some(a);
let ptr = rt
.actors
.get_mut(&a)
.unwrap()
.heap
.alloc(16, TypeTag::Raw)
.unwrap();
let v = Value::ptr(ptr);
rt.send_message_by_id(b, 0, &[v]);
// A crashes with the in-flight foreign ref still pending.
rt.exit_actor(a, ExitReason::Error("crash".to_string()));
rt.current_actor = None;
assert!(!rt.actors.contains_key(&a));
assert_eq!(
rt.retired_heaps.len(),
1,
"supervised child's heap must be retired while foreign refs are outstanding"
);
let new_id = rt.supervisors[&sup_id].children[0].1;
assert_ne!(new_id, a, "replacement child should have been spawned");
// SAFETY: the retired heap keeps the object alive while refs drain.
unsafe {
let header = &*ActorHeap::header_of(ptr);
assert!(
header.foreign_count >= 1,
"retired heap object must remain readable"
);
}
}
// ========================================================================
// SimpleOneForOne Dynamic Children Tests
// ========================================================================
/// Build a module declaring actor type `DynWorker` with a `count` state
/// field (default `default_count`) and one bytecode behavior
/// `DynWorker.inc` that increments `count` and returns the new value.
fn dyn_worker_module(default_count: i64) -> crate::bytecode::CodeModule {
use crate::bytecode::{
ActorMeta, BehaviorTableEntry, CodeModule, Constant, Instruction, OpCode,
};
let mut module = CodeModule::new("dyn_test");
let field_idx = module.add_constant(Constant::String("count".to_string()));
let one_idx = module.add_constant(Constant::Int(1));
module.add_behavior(BehaviorTableEntry {
name: "DynWorker.inc".to_string(),
param_count: 0,
code_offset: 0,
local_count: 4,
effect_mask: 0,
compensate_offset: None,
content_hash: None,
source_location: None,
parallel_branches: None,
});
module.emit(Instruction::new3(
OpCode::StateGet,
((field_idx >> 8) & 0xFF) as u8,
(field_idx & 0xFF) as u8,
1,
));
module.emit(Instruction::new3(
OpCode::ConstU,
((one_idx >> 8) & 0xFF) as u8,
(one_idx & 0xFF) as u8,
2,
));
module.emit(Instruction::new3(OpCode::IAdd, 1, 2, 3));
module.emit(Instruction::new3(OpCode::StateSet, 0, 0, 3));
module.emit(Instruction::new1(OpCode::RetVal, 3));
module.add_actor_meta(ActorMeta {
name: "DynWorker".to_string(),
persistent: false,
state_models: vec![("count".to_string(), crate::ast::StateModel::Local)],
state_defaults: vec![("count".to_string(), Constant::Int(default_count))],
behavior_indices: vec![0],
type_hash: None,
version: 1,
migrations: String::new(),
is_workflow: false,
is_agent: false,
is_organization: false,
tools: vec![],
semantic_memory_dimensions: None,
procedural_memory_namespace: None,
backend: crate::ast::ActorBackendKind::Native,
fallback_config: String::new(),
retry_config: String::new(),
});
module
}
#[test]
fn test_simple_one_for_one_start_child_spawns_real_children() {
let mut rt = Runtime::new();
let module = dyn_worker_module(0);
let sup_id = rt.create_supervisor("pool", RestartStrategy::SimpleOneForOne);
assert!(rt.set_supervisor_template(sup_id, "DynWorker", &module));
let w1 = rt
.start_supervised_child(sup_id, vec![])
.expect("start_child should spawn from the template");
let w2 = rt
.start_supervised_child(sup_id, vec![])
.expect("start_child should spawn from the template");
assert_ne!(w1, w2);
assert_eq!(rt.supervisors[&sup_id].child_count(), 2);
assert_eq!(rt.actors[&w1].parent, Some(sup_id));
assert_eq!(rt.actors[&w2].parent, Some(sup_id));
// Children are real bytecode actors running the template behavior.
assert_eq!(rt.ask_actor_sync(w1, 0, &[]).unwrap(), Value::int(1));
assert_eq!(rt.ask_actor_sync(w2, 0, &[]).unwrap(), Value::int(1));
// Distinct dynamic spec ids keep restart rate limiting per child.
let specs: Vec<&str> = rt.supervisors[&sup_id]
.children
.iter()
.map(|(s, _)| s.id.as_str())
.collect();
assert_eq!(specs, vec!["DynWorker_0", "DynWorker_1"]);
}
#[test]
fn test_simple_one_for_one_restart_from_template_on_crash() {
let mut rt = Runtime::new();
let module = dyn_worker_module(0);
let sup_id = rt.create_supervisor("pool", RestartStrategy::SimpleOneForOne);
assert!(rt.set_supervisor_template(sup_id, "DynWorker", &module));
let w = rt.start_supervised_child(sup_id, vec![]).unwrap();
// Mutate state away from the template defaults, then crash.
assert_eq!(rt.ask_actor_sync(w, 0, &[]).unwrap(), Value::int(1));
assert_eq!(rt.ask_actor_sync(w, 0, &[]).unwrap(), Value::int(2));
rt.exit_actor(w, ExitReason::Error("crash".to_string()));
assert!(!rt.actors.contains_key(&w));
assert_eq!(rt.supervisors[&sup_id].child_count(), 1);
let restarted = rt.supervisors[&sup_id].children[0].1;
assert_ne!(restarted, w, "restart should create a fresh actor");
assert_eq!(rt.actors[&restarted].parent, Some(sup_id));
// The replacement restarts from the template defaults, not the
// pre-crash state: its first inc returns 1, not 3.
assert_eq!(rt.ask_actor_sync(restarted, 0, &[]).unwrap(), Value::int(1));
}
#[test]
fn test_simple_one_for_one_terminate_child_skips_restart() {
let mut rt = Runtime::new();
let module = dyn_worker_module(0);
let sup_id = rt.create_supervisor("pool", RestartStrategy::SimpleOneForOne);
assert!(rt.set_supervisor_template(sup_id, "DynWorker", &module));
let w = rt.start_supervised_child(sup_id, vec![]).unwrap();
assert_eq!(rt.supervisors[&sup_id].child_count(), 1);
assert!(rt.terminate_supervised_child(sup_id, w));
assert_eq!(
rt.supervisors[&sup_id].child_count(),
0,
"terminated child must leave supervision"
);
assert!(
!rt.actors.contains_key(&w),
"terminated child must exit without a restart replacement"
);
// Unknown child / unknown supervisor are no-ops.
assert!(!rt.terminate_supervised_child(sup_id, w));
assert!(!rt.terminate_supervised_child(999_999, w));
}
#[test]
fn test_simple_one_for_one_normal_exit_not_restarted() {
// Dynamic children are Transient: a Normal exit retires the child
// without a replacement (unlike terminate_child, this routes through
// the restart policy).
let mut rt = Runtime::new();
let module = dyn_worker_module(0);
let sup_id = rt.create_supervisor("pool", RestartStrategy::SimpleOneForOne);
assert!(rt.set_supervisor_template(sup_id, "DynWorker", &module));
let w = rt.start_supervised_child(sup_id, vec![]).unwrap();
rt.exit_actor(w, ExitReason::Normal);
assert!(!rt.actors.contains_key(&w));
assert_eq!(rt.supervisors[&sup_id].child_count(), 0);
}
#[test]
fn test_simple_one_for_one_start_child_guards() {
let mut rt = Runtime::new();
let module = dyn_worker_module(0);
// No template set -> None.
let sup_id = rt.create_supervisor("pool", RestartStrategy::SimpleOneForOne);
assert_eq!(rt.start_supervised_child(sup_id, vec![]), None);
// Non-dynamic strategy -> None even with a template set.
let plain_id = rt.create_supervisor("plain", RestartStrategy::OneForOne);
assert!(rt.set_supervisor_template(plain_id, "DynWorker", &module));
assert_eq!(rt.start_supervised_child(plain_id, vec![]), None);
// Unknown supervisor / unknown actor type -> None / false.
assert_eq!(rt.start_supervised_child(999_999, vec![]), None);
assert!(!rt.set_supervisor_template(sup_id, "NoSuchActor", &module));
assert!(!rt.set_supervisor_template(999_999, "DynWorker", &module));
}
#[test]
fn test_otp_builtin_effect_strategy_mapping_and_noops() {
use crate::bytecode::{CodeModule, Constant};
let mut module = CodeModule::new("otp_test");
let name_idx = module.add_constant(Constant::String("s".to_string())) as u32;
let mut rt = Runtime::new();
for (raw, want) in [
(0i64, RestartStrategy::OneForOne),
(1, RestartStrategy::OneForAll),
(2, RestartStrategy::RestForOne),
(3, RestartStrategy::SimpleOneForOne),
] {
let id = rt
.perform_otp_builtin(
Some("create_supervisor"),
&module,
&[Value::string(name_idx), Value::int(raw)],
)
.and_then(|v| v.as_int())
.expect("create_supervisor should return an Int id") as u64;
assert_eq!(rt.supervisors[&id].strategy, want);
}
// Out-of-range strategy -> nil no-op (no supervisor created).
let before = rt.supervisors.len();
let value = rt.perform_otp_builtin(
Some("create_supervisor"),
&module,
&[Value::string(name_idx), Value::int(9)],
);
assert_eq!(value, Some(Value::nil()));
assert_eq!(rt.supervisors.len(), before);
// Policy mapping via supervise_child (2 = transient).
let sup_id = rt
.perform_otp_builtin(
Some("create_supervisor"),
&module,
&[Value::string(name_idx), Value::int(0)],
)
.and_then(|v| v.as_int())
.unwrap() as u64;
let child = rt.spawn_actor(Box::new(|| vec![]));
let value = rt.perform_otp_builtin(
Some("supervise_child"),
&module,
&[
Value::int(sup_id as i64),
Value::actor_ref(child),
Value::int(2),
],
);
assert_eq!(value, Some(Value::nil()));
assert_eq!(
rt.supervisors[&sup_id].children[0].0.restart_policy,