forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstress_tests.rs
More file actions
1699 lines (1439 loc) · 51.8 KB
/
Copy pathstress_tests.rs
File metadata and controls
1699 lines (1439 loc) · 51.8 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
//! Stress Tests: Chaos Engineering for the Nulang Actor Runtime
//!
//! These tests deliberately stress the most complex and undertested areas of
//! the system: actor lifecycle, supervision trees, links, monitors, and
//! scheduler fairness under load.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use crate::bytecode::{CodeModule, Constant, Instruction, OpCode};
use crate::lexer::Lexer;
use crate::parser::Parser;
use crate::runtime::*;
use crate::typechecker::TypeChecker;
use crate::types::ExitReason;
use crate::vm::{Value, VM};
// ---------------------------------------------------------------------------
// Helper: TestContext
// ---------------------------------------------------------------------------
#[derive(Debug, Clone, Default)]
#[allow(dead_code)]
struct TestContext {
counters: HashMap<String, u64>,
log: Vec<String>,
}
#[allow(dead_code)]
impl TestContext {
fn increment(&mut self, key: &str) {
*self.counters.entry(key.to_string()).or_insert(0) += 1;
}
fn get(&self, key: &str) -> u64 {
self.counters.get(key).copied().unwrap_or(0)
}
fn record(&mut self, entry: String) {
self.log.push(entry);
}
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Helper: compile_and_run_nula — compile .nula source and run it
// ---------------------------------------------------------------------------
/// Compile a .nula source string through the full pipeline and run it,
/// returning the resulting Value.
fn compile_and_run_nula(source: &str) -> Result<Value, crate::types::NuError> {
let mut lexer = Lexer::new(source);
let tokens = lexer.lex()?;
let mut parser = Parser::new(tokens);
let ast = parser.parse_module()?;
let mut type_checker = TypeChecker::new();
type_checker.check_module(&ast)?;
let hir = crate::hir_lower::lower_module(&ast, &type_checker.inferred_decl_types);
let mut mir = crate::mir_lower::lower_module(&hir)?;
let module = crate::mir_codegen::compile_mir(&mut mir, "stress")?;
let mut vm = VM::new();
vm.load_module(module);
vm.run()
}
/// Compile and run .nula source, asserting that the result is the given integer.
fn assert_nula_int(source: &str, expected: i64) {
let value = compile_and_run_nula(source).unwrap_or_else(|e| {
panic!(
"nula source failed to compile/run: {:?}\nSource:\n{}",
e, source
);
});
assert_eq!(
value.as_int(),
Some(expected),
"Expected {}, got {:?}\nSource:\n{}",
expected,
value,
source
);
}
// ---------------------------------------------------------------------------
// Test 1 — Slow Worker + Mailbox Flood
// ---------------------------------------------------------------------------
#[test]
fn stress_slow_worker_with_mailbox_flood() {
let mut rt = Runtime::new();
let _ctx = Arc::new(Mutex::new(TestContext::default()));
let slow_actor = rt.spawn_actor(Box::new(|| {
vec![
("name".into(), Value::int(1)), // 1 = "slow_worker"
("mode".into(), Value::int(2)), // 2 = "slow_io"
("quota".into(), Value::int(1000)),
]
}));
let flood_sender = rt.spawn_actor(Box::new(|| {
vec![
("name".into(), Value::int(3)), // 3 = "flood_sender"
]
}));
// Pre-seed the slow actor's mailbox with 10_000 messages
for i in 0..10_000 {
rt.send_message(
slow_actor,
"work",
&[
Value::int(i),
Value::int(42), // payload marker
],
);
}
// Inject a system-priority exit signal mid-flood via a linked actor
let signaler = rt.spawn_actor(Box::new(|| vec![]));
rt.link_actors(slow_actor, signaler);
rt.exit_actor(signaler, ExitReason::Error("system_signal".into()));
// Seed flood sender's mailbox
for i in 10_000..15_000 {
rt.send_message(flood_sender, "forward", &[Value::int(i)]);
}
// Run scheduler to process all messages
rt.run_scheduler();
// --- Assertions ---
// 1a. slow_actor survived the flood (signaler exited abnormally but
// the link kills slow_actor; with trap_exits=false it dies too.
// We verify the runtime is consistent either way.)
let slow_exists = rt.actors.contains_key(&slow_actor);
// 1b. If slow_actor survived, its mailbox should be drained.
if slow_exists {
if let Some(actor) = rt.actors.get(&slow_actor) {
assert!(
actor.mailbox.is_empty(),
"slow_actor mailbox should be drained after scheduler run"
);
// The scheduler processed messages — reduction_count proves work happened.
assert!(
actor.reduction_count > 0,
"slow_actor should have processed some messages, reductions={}",
actor.reduction_count
);
}
}
// 1c. Memory sanity: no leaked runtime state. Terminated actors are
// reaped from the actor table by handle_actor_exit, so anything still
// registered must be in a live (non-Terminated) state.
assert!(
rt.actors
.values()
.all(|a| a.state != ActorState::Terminated),
"terminated actors should have been reaped from the runtime"
);
}
// ---------------------------------------------------------------------------
// Test 2 — Actor Crash During Scheduling
// ---------------------------------------------------------------------------
#[test]
fn stress_actor_crash_during_scheduling() {
let mut rt = Runtime::new();
let sup = rt.create_supervisor("test_sup", RestartStrategy::OneForOne);
let child = rt.spawn_actor(Box::new(|| {
vec![
("name".into(), Value::int(4)), // 4 = "effect_child"
]
}));
let child_spec = ChildSpec::new("child", RestartPolicy::Permanent);
rt.supervise_child(sup, child_spec, child);
let sibling = rt.spawn_actor(Box::new(|| {
vec![
("name".into(), Value::int(5)), // 5 = "sibling"
]
}));
rt.link_actors(child, sibling);
// Simulate crash
rt.exit_actor(child, ExitReason::Error("crash_during_sched".into()));
rt.run_scheduler();
// Sibling (no trap_exits) should be terminated by linked exit
assert!(
!rt.actors.contains_key(&sibling),
"sibling linked to crashed child should have been terminated"
);
// Supervisor should survive
assert!(
rt.actors.contains_key(&sup),
"supervisor should survive child crash"
);
// Supervisor should have recorded the restart
if let Some(supvisor) = rt.supervisors.get(&sup) {
assert!(
supvisor.child_count() >= 1,
"supervisor should still have children after restart"
);
}
}
// ---------------------------------------------------------------------------
// Test 3 — Cascading Exit Under Load
// ---------------------------------------------------------------------------
#[test]
fn stress_cascading_exit_under_load() {
let mut rt = Runtime::new();
let root = rt.create_supervisor("root", RestartStrategy::OneForOne);
let mut supervisors: Vec<Vec<u64>> = vec![vec![root]];
for level in 1..=4 {
let mut current_level = Vec::new();
let parent_level = &supervisors[level - 1];
for parent in parent_level.iter().copied() {
let children_count = if level < 4 { 3 } else { 0 };
for i in 0..children_count {
let strategy = match level {
1 | 2 => RestartStrategy::OneForOne,
3 => RestartStrategy::RestForOne,
_ => unreachable!(),
};
let sup_name = format!("L{}_{}", level, i);
let sup = rt.create_supervisor(&sup_name, strategy);
let spec = ChildSpec::new(&sup_name, RestartPolicy::Permanent);
rt.supervise_child(parent, spec, sup);
current_level.push(sup);
}
}
if !current_level.is_empty() {
supervisors.push(current_level);
}
}
// L4 — leaf actors supervised by L3 supervisors
let mut leaf_actors: Vec<u64> = Vec::new();
if supervisors.len() > 3 {
for sup_l3 in &supervisors[3] {
for leaf_idx in 0..2 {
let leaf = rt.spawn_actor(Box::new(move || {
vec![
("name".into(), Value::int(10 + leaf_idx as i64)),
("level".into(), Value::int(4)),
]
}));
let spec = ChildSpec::new(format!("leaf_{}", leaf_idx), RestartPolicy::Temporary);
rt.supervise_child(*sup_l3, spec, leaf);
leaf_actors.push(leaf);
}
}
}
assert!(!leaf_actors.is_empty(), "should have created leaf actors");
let pre_crash_count = rt.actors.len();
let victim = leaf_actors[0];
rt.exit_actor(victim, ExitReason::Error("leaf_crash".into()));
rt.run_scheduler();
// Victim leaf is gone (Temporary policy → not restarted)
assert!(
!rt.actors.contains_key(&victim),
"crashed leaf with Temporary policy should not be restarted"
);
// Only the crashed leaf should be removed
let post_crash_count = rt.actors.len();
assert_eq!(
post_crash_count,
pre_crash_count - 1,
"only the crashed leaf should be removed; pre={}, post={}",
pre_crash_count,
post_crash_count
);
// All supervisors still exist
for (level, sups) in supervisors.iter().enumerate() {
for sup in sups {
assert!(
rt.actors.contains_key(sup),
"supervisor at level {} should survive leaf crash",
level
);
}
}
// Sibling leaf still exists
if leaf_actors.len() > 1 {
assert!(
rt.actors.contains_key(&leaf_actors[1]),
"sibling leaf should survive with OneForOne at L1-L2"
);
}
}
// ---------------------------------------------------------------------------
// Test 4 — Monitor During Rapid Spawn/Exit
// ---------------------------------------------------------------------------
#[test]
fn stress_monitor_during_rapid_spawn_exit() {
let mut rt = Runtime::new();
let watcher = rt.spawn_actor(Box::new(|| {
vec![
("name".into(), Value::int(6)), // 6 = "watcher"
("role".into(), Value::int(7)), // 7 = "monitor_collector"
]
}));
let mut targets: Vec<u64> = Vec::with_capacity(100);
for i in 0..100 {
let target = rt.spawn_actor(Box::new(move || {
vec![
("name".into(), Value::int(100 + i as i64)),
("seq".into(), Value::int(i as i64)),
]
}));
rt.monitor(watcher, target);
targets.push(target);
}
// Exit all targets — DOWN messages are sent synchronously to watcher
for (i, target) in targets.iter().enumerate() {
rt.exit_actor(*target, ExitReason::Error(format!("rapid_exit_{}", i)));
}
// Check mailbox BEFORE running scheduler (scheduler consumes messages)
let down_count_before = rt
.actors
.get(&watcher)
.map(|a| a.mailbox.len())
.unwrap_or(0);
assert!(
down_count_before >= 100,
"watcher should have at least 100 DOWN messages, got {}",
down_count_before
);
rt.run_scheduler();
// All target actors are gone
for target in &targets {
assert!(
!rt.actors.contains_key(target),
"target actor {} should be removed after exit",
target
);
}
// Watcher itself survived
assert!(rt.actors.contains_key(&watcher), "watcher should survive");
}
// ---------------------------------------------------------------------------
// Test 5 — Scheduler with Mixed Workload
// ---------------------------------------------------------------------------
#[test]
fn stress_scheduler_with_mixed_workload() {
let mut rt = Runtime::new();
let sink = rt.spawn_actor(Box::new(|| {
vec![
("name".into(), Value::int(8)), // 8 = "sink"
("role".into(), Value::int(9)), // 9 = "message_collector"
]
}));
let cpu_actor = rt.spawn_actor(Box::new(|| {
vec![
("name".into(), Value::int(10)), // 10 = "cpu_heavy"
("mode".into(), Value::int(11)), // 11 = "cpu_bound"
("quota".into(), Value::int(500)),
]
}));
let io_actor = rt.spawn_actor(Box::new(|| {
vec![
("name".into(), Value::int(12)), // 12 = "io_waiter"
("mode".into(), Value::int(13)), // 13 = "io_bound"
("quota".into(), Value::int(1)),
]
}));
// Seed workloads: send messages to each actor type
for i in 0..50 {
rt.send_message(
cpu_actor,
"compute",
&[Value::int(i), Value::int(1_000_000)],
);
}
for i in 0..100 {
rt.send_message(
io_actor,
"io_op",
&[
Value::int(i),
Value::int(20), // 20 = "read"
],
);
}
// Send 200 messages to the sink directly
for i in 0..200 {
rt.send_message(sink, "collect", &[Value::int(i)]);
}
rt.run_scheduler();
// All actors still exist and made progress
if let Some(actor) = rt.actors.get(&cpu_actor) {
assert!(
actor.reduction_count > 0,
"CPU actor should have made progress, reductions={}",
actor.reduction_count
);
} else {
panic!("CPU actor should still exist");
}
if let Some(actor) = rt.actors.get(&io_actor) {
assert!(
actor.reduction_count > 0,
"I/O actor should have made progress"
);
} else {
panic!("I/O actor should still exist");
}
if let Some(actor) = rt.actors.get(&sink) {
assert!(
actor.reduction_count > 0,
"Sink should have received and processed messages"
);
} else {
panic!("sink actor should still exist");
}
}
// ---------------------------------------------------------------------------
// Test 6 — Mailbox Never Drops System Messages
// ---------------------------------------------------------------------------
#[test]
fn stress_mailbox_never_drops_system_messages() {
let mut rt = Runtime::new();
let actor = rt.spawn_actor(Box::new(|| {
vec![
("name".into(), Value::int(16)), // 16 = "mailbox_test"
]
}));
// Push 1_000 normal-priority messages
for i in 0..1_000 {
let msg = Message {
behavior_id: 1,
payload: Arc::new(vec![Value::int(i)]),
sender: 0,
priority: MessagePriority::Normal,
trace_id: None,
};
if let Some(a) = rt.actors.get_mut(&actor) {
let _ = a.mailbox.push(msg);
}
}
// Push 100 system-priority messages
for i in 0..100 {
let msg = Message {
behavior_id: 0,
payload: Arc::new(vec![Value::int(1000 + i)]),
sender: 0,
priority: MessagePriority::System,
trace_id: None,
};
if let Some(a) = rt.actors.get_mut(&actor) {
let _ = a.mailbox.push(msg);
}
}
// Push 50 bulk-priority messages
for i in 0..50 {
let msg = Message {
behavior_id: 2,
payload: Arc::new(vec![Value::int(2000 + i)]),
sender: 0,
priority: MessagePriority::Bulk,
trace_id: None,
};
if let Some(a) = rt.actors.get_mut(&actor) {
let _ = a.mailbox.push(msg);
}
}
// Pop all messages and verify counts
let mut system_seen = 0;
let mut normal_seen = 0;
let mut bulk_seen = 0;
if let Some(a) = rt.actors.get_mut(&actor) {
while let Some(msg) = a.mailbox.pop() {
match msg.priority {
MessagePriority::System => system_seen += 1,
MessagePriority::Normal => normal_seen += 1,
MessagePriority::Bulk => bulk_seen += 1,
}
}
}
assert_eq!(
system_seen, 100,
"all 100 system messages must be present, got {}",
system_seen
);
assert_eq!(
normal_seen, 1_000,
"all 1_000 normal messages must be present, got {}",
normal_seen
);
assert_eq!(
bulk_seen, 50,
"all 50 bulk messages must be present, got {}",
bulk_seen
);
}
// ---------------------------------------------------------------------------
// Test 7 — Orphaned Actor Cleanup
// ---------------------------------------------------------------------------
#[test]
fn stress_orphaned_actor_cleanup() {
let mut rt = Runtime::new();
const N: usize = 20;
const DEGREE: usize = 2;
let mut actors: Vec<u64> = Vec::with_capacity(N);
for i in 0..N {
let id = rt.spawn_actor(Box::new(move || {
vec![
("name".into(), Value::int(50 + i as i64)),
("idx".into(), Value::int(i as i64)),
]
}));
actors.push(id);
}
// Link each actor to DEGREE others (ring topology — no cascading)
for i in 0..N {
for d in 1..=DEGREE {
let j = (i + d) % N;
if i < j {
rt.link_actors(actors[i], actors[j]);
}
}
}
let pre_kill_count = rt.actors.len();
assert_eq!(pre_kill_count, N, "should have {} actors before kill", N);
let hub = actors[N / 2];
rt.exit_actor(hub, ExitReason::Error("hub_killed".into()));
rt.run_scheduler();
// Hub is gone
assert!(!rt.actors.contains_key(&hub), "hub actor should be removed");
// Count terminated linked neighbors (DEGREE forward + DEGREE backward)
let mut terminated_count = 0;
for d in 1..=DEGREE {
let linked_idx_forward = (N / 2 + d) % N;
let linked_idx_backward = (N / 2 + N - d) % N;
if !rt.actors.contains_key(&actors[linked_idx_forward]) {
terminated_count += 1;
}
if !rt.actors.contains_key(&actors[linked_idx_backward]) {
terminated_count += 1;
}
}
// With trap_exits=false, linked neighbors should have terminated
assert!(
terminated_count >= DEGREE,
"at least {} neighbors should be terminated, got {}",
DEGREE,
terminated_count
);
// Remaining count should be consistent
let actual_remaining = rt.actors.len();
assert!(
actual_remaining < N,
"some actors should remain after cleanup, got {}",
actual_remaining
);
}
// ---------------------------------------------------------------------------
// Test 8 — Reduction Quota Fairness
// ---------------------------------------------------------------------------
#[test]
fn stress_reduction_quota_fairness() {
let mut rt = Runtime::new();
let actor_a = rt.spawn_actor(Box::new(|| {
vec![
("name".into(), Value::int(30)), // 30 = "fair_a"
("quota".into(), Value::int(10)),
]
}));
let actor_b = rt.spawn_actor(Box::new(|| {
vec![
("name".into(), Value::int(31)), // 31 = "fair_b"
("quota".into(), Value::int(10)),
]
}));
const MSG_COUNT: usize = 100;
for i in 0..MSG_COUNT {
rt.send_message(actor_a, "work", &[Value::int(i as i64)]);
rt.send_message(actor_b, "work", &[Value::int(i as i64)]);
}
// Run scheduler
rt.run_scheduler();
// Both actors should have processed messages (reductions > 0)
if let Some(a) = rt.actors.get(&actor_a) {
assert!(a.reduction_count > 0, "actor_a should have made progress");
}
if let Some(b) = rt.actors.get(&actor_b) {
assert!(b.reduction_count > 0, "actor_b should have made progress");
}
// Both mailboxes should be empty
if let Some(a) = rt.actors.get(&actor_a) {
assert!(a.mailbox.is_empty(), "actor_a mailbox should be empty");
}
if let Some(b) = rt.actors.get(&actor_b) {
assert!(b.mailbox.is_empty(), "actor_b mailbox should be empty");
}
}
// ---------------------------------------------------------------------------
// Test 9 — Effect Resume After Mailbox Pressure
// ---------------------------------------------------------------------------
#[test]
fn stress_effect_resume_after_mailbox_pressure() {
let mut rt = Runtime::new();
let effect_actor = rt.spawn_actor(Box::new(|| {
vec![
("name".into(), Value::int(40)), // 40 = "effect_resumer"
("effect".into(), Value::int(41)), // 41 = "SimulatedRead"
]
}));
// Start an effect on the actor
rt.send_message(effect_actor, "start_effect", &[]);
// Flood the mailbox while actor is running
for i in 0..5_000 {
rt.send_message(effect_actor, "flood", &[Value::int(i)]);
}
// Run scheduler — all messages should be processed
rt.run_scheduler();
// Actor should still exist and have processed messages
if let Some(actor) = rt.actors.get(&effect_actor) {
assert!(
actor.reduction_count > 0,
"actor should have processed messages, reductions={}",
actor.reduction_count
);
assert!(
actor.mailbox.is_empty(),
"mailbox should be empty after scheduler run"
);
} else {
// Actor may have been terminated by linked exit or supervisor
// — that is also a valid outcome for the stress test.
}
}
// ---------------------------------------------------------------------------
// Test 10 — Supervisor Crash During Recovery
// ---------------------------------------------------------------------------
#[test]
fn stress_supervisor_crash_during_recovery() {
let mut rt = Runtime::new();
let root = rt.create_supervisor("root", RestartStrategy::OneForAll);
let mid = rt.create_supervisor("mid", RestartStrategy::OneForOne);
rt.supervise_child(root, ChildSpec::new("mid", RestartPolicy::Permanent), mid);
let leaf = rt.spawn_actor(Box::new(|| {
vec![
("name".into(), Value::int(50)), // 50 = "leaf"
]
}));
rt.supervise_child(mid, ChildSpec::new("leaf", RestartPolicy::Permanent), leaf);
let _pre_crash_count = rt.actors.len();
rt.exit_actor(
mid,
ExitReason::Error("supervisor_died_mid_recovery".into()),
);
rt.run_scheduler();
// Root supervisor should survive
assert!(
rt.actors.contains_key(&root),
"root supervisor should survive"
);
// Actor count should be stable (root + replacement mid + replacement leaf)
let post_count = rt.actors.len();
assert!(
post_count >= 1,
"at least root should remain, got {} actors",
post_count
);
}
// ---------------------------------------------------------------------------
// Test 11 — Registry High Churn
// ---------------------------------------------------------------------------
#[test]
fn stress_registry_high_churn() {
let mut rt = Runtime::new();
const N: usize = 500;
let mut ids = Vec::with_capacity(N);
for i in 0..N {
let id = rt.spawn_actor(Box::new(move || {
vec![("name".into(), Value::int(200 + i as i64))]
}));
ids.push(id);
let name = format!("worker_{}", i);
rt.registry.register(&name, id).unwrap();
}
assert_eq!(rt.registry.registered().len(), N);
for i in 0..N {
let name = format!("worker_{}", i);
assert_eq!(rt.registry.whereis(&name), Some(ids[i]));
}
for i in (0..N).step_by(2) {
let name = format!("worker_{}", i);
rt.registry.unregister(&name).unwrap();
}
assert_eq!(rt.registry.registered().len(), N / 2);
rt.run_scheduler();
for i in 0..N {
let name = format!("worker_{}", i);
if i % 2 == 0 {
assert_eq!(rt.registry.whereis(&name), None);
} else {
assert_eq!(rt.registry.whereis(&name), Some(ids[i]));
}
}
}
// ---------------------------------------------------------------------------
// Test 12 — Process Groups Membership Churn
// ---------------------------------------------------------------------------
#[test]
fn stress_process_groups_membership_churn() {
let mut rt = Runtime::new();
const N: usize = 200;
let mut ids = Vec::with_capacity(N);
for i in 0..N {
let id = rt.spawn_actor(Box::new(move || {
vec![("name".into(), Value::int(300 + i as i64))]
}));
ids.push(id);
}
for (i, id) in ids.iter().enumerate() {
let group = format!("group_{}", i % 10);
rt.process_groups.join(&group, *id).unwrap();
}
for g in 0..10 {
let group = format!("group_{}", g);
assert_eq!(rt.process_groups.member_count(&group), N / 10);
}
for (i, id) in ids.iter().enumerate() {
if i % 3 == 0 {
let group = format!("group_{}", i % 10);
assert!(rt.process_groups.leave(&group, *id));
}
}
for g in 0..10 {
let group = format!("group_{}", g);
let remaining = rt.process_groups.member_count(&group);
assert!(remaining > 0);
assert!(remaining <= N / 10);
}
let victim = ids[1];
rt.exit_actor(victim, ExitReason::Error("pg_exit".into()));
rt.run_scheduler();
for g in 0..10 {
let group = format!("group_{}", g);
assert!(!rt.process_groups.is_member(&group, victim));
}
}
// ---------------------------------------------------------------------------
// Test 13 — Timer Wheel Overload
// ---------------------------------------------------------------------------
#[test]
fn stress_timer_wheel_overload() {
let mut rt = Runtime::new();
let actor = rt.spawn_actor(Box::new(|| vec![("name".into(), Value::int(400))]));
let mut ids = Vec::new();
for i in 0..5_000 {
let delay = std::time::Duration::from_nanos((i % 100 + 1) as u64);
let id = rt
.timer_wheel
.send_after(delay, actor, 1, vec![Value::int(i as i64)]);
ids.push(id);
}
assert_eq!(rt.timer_wheel.len(), 5_000);
for i in (0..5_000).step_by(2) {
assert!(rt.timer_wheel.cancel(ids[i]));
}
assert_eq!(rt.timer_wheel.len(), 2_500);
std::thread::sleep(std::time::Duration::from_millis(5));
let fired = rt.timer_wheel.tick(std::time::Instant::now());
assert!(!fired.is_empty(), "some timers should have fired");
}
// ---------------------------------------------------------------------------
// Test 14 — Persistent Actor Checkpoint / Recovery
// ---------------------------------------------------------------------------
#[test]
fn stress_persistent_actor_checkpoint_recovery() {
let mut rt = Runtime::new();
let mut models = HashMap::new();
models.insert("counter".to_string(), StateModel::Durable);
models.insert("scratch".to_string(), StateModel::Local);
let actor_id = rt.spawn_persistent_actor(
Box::new(|| {
vec![
("counter".into(), Value::int(0)),
("scratch".into(), Value::int(0)),
]
}),
models,
);
if let Some(actor) = rt.actors.get_mut(&actor_id) {
actor.set_state_field("counter", Value::int(42));
actor.set_state_field("scratch", Value::int(99));
}
rt.checkpoint_actor(actor_id);
assert_eq!(rt.persistence.latest_sequence(actor_id), 1);
rt.actors.remove(&actor_id);
let recovered = rt.recover_actor(actor_id);
assert_eq!(recovered, Some(actor_id));
let counter = rt
.actors
.get(&actor_id)
.and_then(|a| a.get_state_field("counter"))
.and_then(|v| v.as_int());
assert_eq!(counter, Some(42));
let scratch = rt
.actors
.get(&actor_id)
.and_then(|a| a.get_state_field("scratch"));
assert_eq!(scratch, None, "Local fields should not survive recovery");
}
// ---------------------------------------------------------------------------
// Test 15 — CRDT Counter Merge Stress
// ---------------------------------------------------------------------------
#[test]
fn stress_crdt_counter_merge_stress() {
let mut counter_a = GCounter::new(1);
let mut counter_b = GCounter::new(2);
for _ in 0..1_000 {
counter_a.increment();
}
for _ in 0..750 {
counter_b.increment();
}
counter_a.merge(&counter_b);
assert_eq!(counter_a.value(), 1_750);
counter_b.merge(&counter_a);
assert_eq!(counter_b.value(), 1_750);
}
// ---------------------------------------------------------------------------
// Test 16 — CRDT Manager Sync Ops
// ---------------------------------------------------------------------------
#[test]
fn stress_crdt_manager_sync_ops() {
let mut manager = CrdtManager::new(1);
let (id, _) = manager.create_gcounter();
for _ in 0..100 {
if let Some(c) = manager.get_gcounter_mut(id) {
c.increment();
}
}
let ops = manager.generate_sync_ops();
assert!(!ops.is_empty(), "sync ops should be generated");
for op in ops {
assert_eq!(op.crdt_type, CrdtType::GCounter);
assert_eq!(op.crdt_id, id);
}
}
// ---------------------------------------------------------------------------
// Test 17 — Monitor Spawn Storm
// ---------------------------------------------------------------------------
#[test]
fn stress_monitor_spawn_storm() {
let mut rt = Runtime::new();
let watcher = rt.spawn_actor(Box::new(|| vec![("name".into(), Value::int(500))]));
let mut ids = Vec::with_capacity(100);
for i in 0..100 {
let id = rt.spawn_actor(Box::new(move || {
vec![("name".into(), Value::int(600 + i as i64))]
}));
rt.monitor(watcher, id);
ids.push(id);
}
for id in &ids {
rt.exit_actor(*id, ExitReason::Error("storm".into()));
}
rt.run_scheduler();