reifydb-runtime 0.9.0

Runtime infrastructure for ReifyDB
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
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 ReifyDB

use std::{
	any::Any,
	cell::{Cell, RefCell},
	cmp::Ordering as CmpOrdering,
	collections::{BinaryHeap, VecDeque},
	error, fmt, mem,
	panic::{AssertUnwindSafe, catch_unwind},
	rc::{Rc, Weak},
};

use reifydb_value::value::duration::Duration;

use crate::{
	actor::{
		context::{CancellationToken, Context},
		mailbox::{ActorRef, create_dst_mailbox},
		timers::dst::{DstTimerHeap, fire_due_timers, new_timer_heap},
		traits::{Actor, Directive},
	},
	context::clock::{Clock, MockClock},
	pool::Pools,
};

struct ReadyEntry {
	logical_ts: u64,
	actor_id: usize,
}

impl PartialEq for ReadyEntry {
	fn eq(&self, other: &Self) -> bool {
		self.logical_ts == other.logical_ts && self.actor_id == other.actor_id
	}
}

impl Eq for ReadyEntry {}

impl PartialOrd for ReadyEntry {
	fn partial_cmp(&self, other: &Self) -> Option<CmpOrdering> {
		Some(self.cmp(other))
	}
}

impl Ord for ReadyEntry {
	fn cmp(&self, other: &Self) -> CmpOrdering {
		other.logical_ts.cmp(&self.logical_ts).then_with(|| other.actor_id.cmp(&self.actor_id))
	}
}

trait DstProcessable {
	fn process_one(&self) -> Option<Directive>;
	fn has_pending(&self) -> bool;
	fn is_alive(&self) -> bool;
	fn mark_dead(&self);
	fn post_stop(&self);
}

struct DstActorCell<A: Actor> {
	actor: A,
	state: RefCell<Option<A::State>>,
	queue: Rc<RefCell<VecDeque<A::Message>>>,
	ctx: Context<A::Message>,
	actor_ref: ActorRef<A::Message>,
}

impl<A: Actor> DstProcessable for DstActorCell<A> {
	fn process_one(&self) -> Option<Directive> {
		let msg = self.queue.borrow_mut().pop_front()?;
		let mut state_ref = self.state.borrow_mut();
		if let Some(ref mut state) = *state_ref {
			Some(self.actor.handle(state, msg, &self.ctx))
		} else {
			None
		}
	}

	fn has_pending(&self) -> bool {
		!self.queue.borrow().is_empty()
	}

	fn is_alive(&self) -> bool {
		self.actor_ref.is_alive()
	}

	fn mark_dead(&self) {
		self.actor_ref.mark_stopped();
	}

	fn post_stop(&self) {
		self.actor.post_stop();
	}
}

pub enum StepResult {
	Processed {
		actor_id: usize,
	},

	Panicked {
		actor_id: usize,
		payload: Box<dyn Any + Send>,
	},

	Stopped {
		actor_id: usize,
	},

	Idle,
}

struct DstActorSystemInner {
	cancel: CancellationToken,
	clock: Clock,
	mock_clock: MockClock,

	ready_queue: RefCell<BinaryHeap<ReadyEntry>>,

	logical_clock: Cell<u64>,

	timer_heap: DstTimerHeap,

	actors: RefCell<Vec<Option<Rc<dyn DstProcessable>>>>,

	alive_count: Cell<usize>,

	init_panics: RefCell<Vec<(usize, Box<dyn Any + Send>)>>,

	post_stop_panics: RefCell<Vec<(usize, Box<dyn Any + Send>)>>,

	children: RefCell<Vec<ActorSystem>>,
}

pub struct ActorSystem {
	inner: Rc<DstActorSystemInner>,
}

impl Clone for ActorSystem {
	fn clone(&self) -> Self {
		Self {
			inner: self.inner.clone(),
		}
	}
}

// SAFETY: the dst executor is single-threaded - no thread pool is compiled in and actors run inline
// via step() - so the Rc/RefCell-backed inner is only ever accessed from the one thread driving the
// system. These impls satisfy Send + Sync bounds and never back a real cross-thread transfer.
unsafe impl Send for ActorSystem {}
unsafe impl Sync for ActorSystem {}

impl ActorSystem {
	pub fn new(_pools: Pools, clock: Clock) -> Self {
		let mock_clock = match &clock {
			Clock::Mock(mc) => mc.clone(),
			Clock::Real => panic!("DST actor system requires a MockClock, not Clock::Real"),
		};

		Self {
			inner: Rc::new(DstActorSystemInner {
				cancel: CancellationToken::new(),
				clock,
				mock_clock,
				ready_queue: RefCell::new(BinaryHeap::new()),
				logical_clock: Cell::new(0),
				timer_heap: new_timer_heap(),
				actors: RefCell::new(Vec::new()),
				alive_count: Cell::new(0),
				init_panics: RefCell::new(Vec::new()),
				post_stop_panics: RefCell::new(Vec::new()),
				children: RefCell::new(Vec::new()),
			}),
		}
	}

	/// A system for test fixtures: each keeps its own ready queue and logical clock so simulations
	/// stay independent. The retained clone only ensures the system outlives the spawners it hands out.
	pub fn testing(clock: Clock) -> Self {
		let system = Self::new(Pools::default(), clock);
		mem::forget(system.clone());
		system
	}

	pub fn scope(&self) -> Self {
		let child_mock_clock = MockClock::new(self.inner.mock_clock.now().to_nanos());
		let child = Self {
			inner: Rc::new(DstActorSystemInner {
				cancel: self.inner.cancel.child_token(),
				clock: Clock::Mock(child_mock_clock.clone()),
				mock_clock: child_mock_clock,
				ready_queue: RefCell::new(BinaryHeap::new()),
				logical_clock: Cell::new(0),
				timer_heap: self.inner.timer_heap.clone(),
				actors: RefCell::new(Vec::new()),
				alive_count: Cell::new(0),
				init_panics: RefCell::new(Vec::new()),
				post_stop_panics: RefCell::new(Vec::new()),
				children: RefCell::new(Vec::new()),
			}),
		};
		self.inner.children.borrow_mut().push(child.clone());
		child
	}

	pub fn pools(&self) -> Pools {
		Pools::default()
	}

	pub fn spawner(&self) -> ActorSpawner {
		ActorSpawner {
			inner: Rc::downgrade(&self.inner),
			clock: self.inner.clock.clone(),
		}
	}

	pub fn cancellation_token(&self) -> CancellationToken {
		self.inner.cancel.clone()
	}

	pub fn is_cancelled(&self) -> bool {
		self.inner.cancel.is_cancelled()
	}

	pub fn shutdown(&self) {
		self.inner.cancel.cancel();

		for child in self.inner.children.borrow().iter() {
			child.shutdown();
		}

		let actors = self.inner.actors.borrow();
		for slot in actors.iter() {
			if let Some(cell) = slot {
				if cell.is_alive() {
					let _ = catch_unwind(AssertUnwindSafe(|| cell.post_stop()));
					cell.mark_dead();
				}
			}
		}
		self.inner.alive_count.set(0);
	}

	pub fn clock(&self) -> &Clock {
		&self.inner.clock
	}

	pub(crate) fn mock_clock(&self) -> &MockClock {
		&self.inner.mock_clock
	}

	pub(crate) fn timer_heap(&self) -> &DstTimerHeap {
		&self.inner.timer_heap
	}

	pub fn join(&self) -> Result<(), JoinError> {
		Ok(())
	}

	pub fn join_timeout(&self, _timeout: Duration) -> Result<(), JoinError> {
		Ok(())
	}

	pub fn spawn_coordination<A: Actor>(&self, _name: &str, actor: A) -> ActorHandle<A::Message> {
		let (actor_ref, queue) = create_dst_mailbox::<A::Message>();

		if self.is_cancelled() {
			actor_ref.mark_stopped();
			return ActorHandle {
				actor_ref,
			};
		}

		let cancel = self.cancellation_token();
		let ctx = Context::new(actor_ref.clone(), self.clone(), cancel);

		let cell = Rc::new(DstActorCell {
			actor,
			state: RefCell::new(None),
			queue,
			ctx: ctx.clone(),
			actor_ref: actor_ref.clone(),
		});

		let actor_id = {
			let mut actors = self.inner.actors.borrow_mut();
			let id = actors.len();
			actors.push(Some(cell.clone() as Rc<dyn DstProcessable>));
			id
		};

		let inner = self.inner.clone();
		actor_ref.set_notify(Box::new(move || {
			let ts = inner.logical_clock.get();
			inner.logical_clock.set(ts + 1);
			inner.ready_queue.borrow_mut().push(ReadyEntry {
				logical_ts: ts,
				actor_id,
			});
		}));

		match catch_unwind(AssertUnwindSafe(|| cell.actor.init(&ctx))) {
			Ok(initial_state) => {
				*cell.state.borrow_mut() = Some(initial_state);
				self.inner.alive_count.set(self.inner.alive_count.get() + 1);
			}
			Err(payload) => {
				cell.mark_dead();
				self.inner.init_panics.borrow_mut().push((actor_id, payload));
			}
		}

		ActorHandle {
			actor_ref,
		}
	}

	pub fn spawn_flow<A: Actor>(&self, name: &str, actor: A) -> ActorHandle<A::Message> {
		self.spawn_coordination(name, actor)
	}

	pub fn spawn_maintenance<A: Actor>(&self, name: &str, actor: A) -> ActorHandle<A::Message> {
		self.spawn_coordination(name, actor)
	}

	pub fn spawn_ephemeral<A: Actor>(&self, name: &str, actor: A) -> ActorHandle<A::Message> {
		self.spawn_coordination(name, actor)
	}

	pub fn step(&self) -> StepResult {
		{
			let mut panics = self.inner.init_panics.borrow_mut();
			if let Some((actor_id, payload)) = panics.pop() {
				return StepResult::Panicked {
					actor_id,
					payload,
				};
			}
		}

		{
			let mut panics = self.inner.post_stop_panics.borrow_mut();
			if let Some((actor_id, payload)) = panics.pop() {
				return StepResult::Panicked {
					actor_id,
					payload,
				};
			}
		}

		loop {
			let entry = self.inner.ready_queue.borrow_mut().pop();
			let entry = match entry {
				Some(e) => e,
				None => return StepResult::Idle,
			};

			let actor_id = entry.actor_id;
			let cell = {
				let actors = self.inner.actors.borrow();
				match actors.get(actor_id) {
					Some(Some(cell)) => cell.clone(),
					_ => continue,
				}
			};

			if !cell.is_alive() || !cell.has_pending() {
				continue;
			}

			let result = catch_unwind(AssertUnwindSafe(|| cell.process_one()));

			match result {
				Ok(Some(Directive::Stop)) => {
					if let Err(payload) = catch_unwind(AssertUnwindSafe(|| cell.post_stop())) {
						self.inner.post_stop_panics.borrow_mut().push((actor_id, payload));
					}
					cell.mark_dead();
					self.inner.alive_count.set(self.inner.alive_count.get() - 1);
					return StepResult::Stopped {
						actor_id,
					};
				}
				Ok(Some(_)) => {
					return StepResult::Processed {
						actor_id,
					};
				}
				Ok(None) => {
					continue;
				}
				Err(payload) => {
					if let Err(ps_payload) = catch_unwind(AssertUnwindSafe(|| cell.post_stop())) {
						self.inner.post_stop_panics.borrow_mut().push((actor_id, ps_payload));
					}
					cell.mark_dead();
					self.inner.alive_count.set(self.inner.alive_count.get() - 1);
					return StepResult::Panicked {
						actor_id,
						payload,
					};
				}
			}
		}
	}

	pub fn advance_time(&self, delta: Duration) {
		let target_nanos = self.inner.mock_clock.now().to_nanos() + delta.to_std().as_nanos() as u64;

		loop {
			let next_deadline = self.inner.timer_heap.borrow().peek().map(|e| e.deadline_nanos);

			match next_deadline {
				Some(deadline) if deadline <= target_nanos => {
					self.inner.mock_clock.set_nanos(deadline);
					fire_due_timers(&self.inner.timer_heap, deadline);
				}
				_ => break,
			}
		}

		self.inner.mock_clock.set_nanos(target_nanos);

		for child in self.inner.children.borrow().iter() {
			child.advance_time(delta);
		}
	}

	pub fn run_until_idle(&self) {
		loop {
			match self.step() {
				StepResult::Idle => break,
				_ => {}
			}
		}
	}

	pub fn has_pending(&self) -> bool {
		!self.inner.ready_queue.borrow().is_empty()
	}

	pub fn alive_count(&self) -> usize {
		self.inner.alive_count.get()
	}
}

impl fmt::Debug for ActorSystem {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_struct("ActorSystem")
			.field("cancelled", &self.is_cancelled())
			.field("alive_count", &self.alive_count())
			.finish_non_exhaustive()
	}
}

#[derive(Clone)]
pub struct ActorSpawner {
	inner: Weak<DstActorSystemInner>,
	clock: Clock,
}

// SAFETY: the dst executor is single-threaded - no thread pool is compiled in and actors run inline
// via ActorSystem::step() - so the Weak<DstActorSystemInner> is only ever accessed from the one thread
// driving the system. These impls satisfy Send + Sync bounds and never back a real cross-thread transfer.
unsafe impl Send for ActorSpawner {}
unsafe impl Sync for ActorSpawner {}

impl ActorSpawner {
	pub fn system(&self) -> ActorSystem {
		ActorSystem {
			inner: self.inner.upgrade().expect("runtime already shut down: cannot spawn actor"),
		}
	}

	pub fn clock(&self) -> &Clock {
		&self.clock
	}

	pub fn pools(&self) -> Pools {
		self.system().pools()
	}

	pub fn is_alive(&self) -> bool {
		self.inner.strong_count() > 0
	}

	pub fn cancellation_token(&self) -> Option<CancellationToken> {
		self.inner.upgrade().map(|inner| inner.cancel.clone())
	}

	pub fn scope(&self) -> ActorSpawner {
		self.system().scope().spawner()
	}

	pub fn shutdown(&self) {
		if let Some(inner) = self.inner.upgrade() {
			ActorSystem {
				inner,
			}
			.shutdown();
		}
	}

	pub fn spawn_coordination<A: Actor>(&self, name: &str, actor: A) -> ActorHandle<A::Message> {
		self.system().spawn_coordination(name, actor)
	}

	pub fn spawn_flow<A: Actor>(&self, name: &str, actor: A) -> ActorHandle<A::Message> {
		self.system().spawn_flow(name, actor)
	}

	pub fn spawn_maintenance<A: Actor>(&self, name: &str, actor: A) -> ActorHandle<A::Message> {
		self.system().spawn_maintenance(name, actor)
	}

	pub fn spawn_ephemeral<A: Actor>(&self, name: &str, actor: A) -> ActorHandle<A::Message> {
		self.system().spawn_ephemeral(name, actor)
	}
}

impl fmt::Debug for ActorSpawner {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		f.debug_struct("ActorSpawner").field("alive", &self.is_alive()).finish_non_exhaustive()
	}
}

pub struct ActorHandle<M> {
	pub actor_ref: ActorRef<M>,
}

impl<M> ActorHandle<M> {
	pub fn actor_ref(&self) -> &ActorRef<M> {
		&self.actor_ref
	}

	pub fn join(self) -> Result<(), JoinError> {
		Ok(())
	}
}

#[derive(Debug)]
pub struct JoinError {
	message: String,
}

impl JoinError {
	pub fn new(message: impl Into<String>) -> Self {
		Self {
			message: message.into(),
		}
	}
}

impl fmt::Display for JoinError {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		write!(f, "actor join failed: {}", self.message)
	}
}

impl error::Error for JoinError {}

#[cfg(test)]
mod tests {
	use std::sync::Arc;

	use super::*;
	use crate::{
		pool::{PoolConfig, Pools},
		sync::mutex::Mutex,
	};

	struct CounterActor;

	#[derive(Debug)]
	enum CounterMessage {
		Inc,
		Dec,
		Stop,
	}

	impl Actor for CounterActor {
		type State = i64;
		type Message = CounterMessage;

		fn init(&self, _ctx: &Context<Self::Message>) -> Self::State {
			0
		}

		fn handle(
			&self,
			state: &mut Self::State,
			msg: Self::Message,
			_ctx: &Context<Self::Message>,
		) -> Directive {
			match msg {
				CounterMessage::Inc => *state += 1,
				CounterMessage::Dec => *state -= 1,
				CounterMessage::Stop => return Directive::Stop,
			}
			Directive::Continue
		}
	}

	struct OrderActor;

	#[derive(Debug, Clone)]
	struct OrderMessage(u64);

	impl Actor for OrderActor {
		type State = Vec<u64>;
		type Message = OrderMessage;

		fn init(&self, _ctx: &Context<Self::Message>) -> Self::State {
			Vec::new()
		}

		fn handle(
			&self,
			state: &mut Self::State,
			msg: Self::Message,
			_ctx: &Context<Self::Message>,
		) -> Directive {
			state.push(msg.0);
			Directive::Continue
		}
	}

	struct PanicActor;

	#[derive(Debug)]
	enum PanicMessage {
		Ok,
		Boom,
	}

	impl Actor for PanicActor {
		type State = u64;
		type Message = PanicMessage;

		fn init(&self, _ctx: &Context<Self::Message>) -> Self::State {
			0
		}

		fn handle(
			&self,
			state: &mut Self::State,
			msg: Self::Message,
			_ctx: &Context<Self::Message>,
		) -> Directive {
			match msg {
				PanicMessage::Ok => {
					*state += 1;
					Directive::Continue
				}
				PanicMessage::Boom => panic!("actor boom"),
			}
		}
	}

	/// `Arc<Mutex<..>>` only satisfies the `Send + Sync` bounds on `Actor`; DST is
	/// single-threaded, so the lock is never contended.
	struct LogActor {
		log: Arc<Mutex<Vec<String>>>,
	}

	impl Actor for LogActor {
		type State = ();
		type Message = String;

		fn init(&self, _ctx: &Context<Self::Message>) -> Self::State {}

		fn handle(
			&self,
			_state: &mut Self::State,
			msg: Self::Message,
			_ctx: &Context<Self::Message>,
		) -> Directive {
			self.log.lock().push(msg);
			Directive::Continue
		}
	}

	struct ForwardActor {
		target: ActorRef<String>,
	}

	impl Actor for ForwardActor {
		type State = ();
		type Message = String;

		fn init(&self, _ctx: &Context<Self::Message>) -> Self::State {}

		fn handle(
			&self,
			_state: &mut Self::State,
			msg: Self::Message,
			_ctx: &Context<Self::Message>,
		) -> Directive {
			let _ = self.target.send(format!("fwd:{msg}"));
			Directive::Continue
		}
	}

	fn test_system() -> ActorSystem {
		let pools = Pools::new(PoolConfig::default());
		ActorSystem::new(pools, Clock::Mock(MockClock::from_millis(0)))
	}

	#[test]
	fn test_basic_step() {
		let system = test_system();
		let handle = system.spawn_coordination("counter", CounterActor);

		handle.actor_ref.send(CounterMessage::Inc).unwrap();
		handle.actor_ref.send(CounterMessage::Inc).unwrap();
		handle.actor_ref.send(CounterMessage::Inc).unwrap();

		for _ in 0..3 {
			match system.step() {
				StepResult::Processed {
					actor_id: 0,
				} => {}
				other => panic!("unexpected: {other:?}"),
			}
		}

		assert!(matches!(system.step(), StepResult::Idle));
	}

	#[test]
	fn test_strict_global_fifo() {
		let system = test_system();

		let log = Arc::new(Mutex::new(Vec::<String>::new()));

		let a = system.spawn_coordination(
			"a",
			LogActor {
				log: log.clone(),
			},
		);
		let b = system.spawn_coordination(
			"b",
			LogActor {
				log: log.clone(),
			},
		);

		a.actor_ref.send("msg1".into()).unwrap();
		a.actor_ref.send("msg2".into()).unwrap();
		b.actor_ref.send("msg3".into()).unwrap();

		system.run_until_idle();

		// Delivery order is global by enqueue, not per actor.
		assert_eq!(*log.lock(), vec!["msg1", "msg2", "msg3"]);
	}

	#[test]
	fn test_timer_advance() {
		let system = test_system();
		let handle = system.spawn_coordination("order", OrderActor);

		let ctx = Context::new(handle.actor_ref.clone(), system.clone(), system.cancellation_token());
		ctx.schedule_once(Duration::from_milliseconds(100).unwrap(), || OrderMessage(42));

		// A timer must not fire before the clock reaches its deadline.
		assert!(matches!(system.step(), StepResult::Idle));

		system.advance_time(Duration::from_milliseconds(100).unwrap());

		match system.step() {
			StepResult::Processed {
				actor_id: 0,
			} => {}
			other => panic!("unexpected: {other:?}"),
		}
		assert!(matches!(system.step(), StepResult::Idle));
	}

	#[test]
	fn test_timer_deadline_ordering() {
		let system = test_system();
		let log = Arc::new(Mutex::new(Vec::<String>::new()));
		let handle = system.spawn_coordination(
			"log",
			LogActor {
				log: log.clone(),
			},
		);

		let ctx = Context::new(handle.actor_ref.clone(), system.clone(), system.cancellation_token());

		// Scheduled in reverse deadline order, so firing in schedule order would be visible here.
		ctx.schedule_once(Duration::from_milliseconds(300).unwrap(), || "t300".into());
		ctx.schedule_once(Duration::from_milliseconds(100).unwrap(), || "t100".into());
		ctx.schedule_once(Duration::from_milliseconds(200).unwrap(), || "t200".into());

		system.advance_time(Duration::from_milliseconds(300).unwrap());
		system.run_until_idle();

		assert_eq!(*log.lock(), vec!["t100", "t200", "t300"]);
	}

	#[test]
	fn test_timer_repeat() {
		let system = test_system();
		let log = Arc::new(Mutex::new(Vec::<String>::new()));
		let handle = system.spawn_coordination(
			"log",
			LogActor {
				log: log.clone(),
			},
		);

		let ctx = Context::new(handle.actor_ref.clone(), system.clone(), system.cancellation_token());
		ctx.schedule_repeat(Duration::from_milliseconds(100).unwrap(), "tick".to_string());

		// A 350ms jump must yield the three deadlines it crossed, not one catch-up tick.
		system.advance_time(Duration::from_milliseconds(350).unwrap());
		system.run_until_idle();

		assert_eq!(log.lock().len(), 3);
	}

	#[test]
	fn test_run_until_idle_with_forwarding() {
		let system = test_system();
		let log = Arc::new(Mutex::new(Vec::<String>::new()));
		let log_handle = system.spawn_coordination(
			"log",
			LogActor {
				log: log.clone(),
			},
		);
		let fwd_handle = system.spawn_coordination(
			"fwd",
			ForwardActor {
				target: log_handle.actor_ref.clone(),
			},
		);

		fwd_handle.actor_ref.send("hello".into()).unwrap();
		system.run_until_idle();

		assert_eq!(*log.lock(), vec!["fwd:hello"]);
	}

	#[test]
	fn test_panic_handling() {
		let system = test_system();
		let handle = system.spawn_coordination("panic", PanicActor);

		handle.actor_ref.send(PanicMessage::Ok).unwrap();
		handle.actor_ref.send(PanicMessage::Boom).unwrap();

		assert!(matches!(
			system.step(),
			StepResult::Processed {
				actor_id: 0
			}
		));

		match system.step() {
			StepResult::Panicked {
				actor_id: 0,
				..
			} => {}
			other => panic!("expected Panicked, got {other:?}"),
		}

		// A panic must kill the actor rather than leave it accepting messages nobody handles.
		assert!(handle.actor_ref.send(PanicMessage::Ok).is_err());
		assert_eq!(system.alive_count(), 0);
	}

	#[test]
	fn test_actor_lifecycle_stop() {
		let system = test_system();
		let handle = system.spawn_coordination("counter", CounterActor);

		handle.actor_ref.send(CounterMessage::Inc).unwrap();
		handle.actor_ref.send(CounterMessage::Stop).unwrap();
		handle.actor_ref.send(CounterMessage::Inc).unwrap(); // queued before stop processed

		assert!(matches!(
			system.step(),
			StepResult::Processed {
				actor_id: 0
			}
		));
		assert!(matches!(
			system.step(),
			StepResult::Stopped {
				actor_id: 0
			}
		));

		// A message queued before the stop must not be delivered after it.
		assert!(matches!(system.step(), StepResult::Idle));

		assert!(handle.actor_ref.send(CounterMessage::Inc).is_err());
		assert_eq!(system.alive_count(), 0);
	}

	#[test]
	fn test_multiple_actors_fifo() {
		let system = test_system();
		let log = Arc::new(Mutex::new(Vec::<String>::new()));

		let a = system.spawn_coordination(
			"a",
			LogActor {
				log: log.clone(),
			},
		);
		let b = system.spawn_coordination(
			"b",
			LogActor {
				log: log.clone(),
			},
		);
		let c = system.spawn_coordination(
			"c",
			LogActor {
				log: log.clone(),
			},
		);

		// Interleaved across three actors, so a per-actor queue would reorder the log.
		a.actor_ref.send("a1".into()).unwrap();
		b.actor_ref.send("b1".into()).unwrap();
		c.actor_ref.send("c1".into()).unwrap();
		a.actor_ref.send("a2".into()).unwrap();
		b.actor_ref.send("b2".into()).unwrap();

		system.run_until_idle();

		assert_eq!(*log.lock(), vec!["a1", "b1", "c1", "a2", "b2"]);
	}

	#[test]
	fn test_spawner_tracks_system_liveness() {
		// No actor is spawned, so no ctx cycle keeps the inner Rc alive: a spawner that held a
		// strong Rc instead of a Weak would still build but report alive forever.
		let system = test_system();
		let spawner = system.spawner();
		assert!(spawner.is_alive());
		assert!(spawner.cancellation_token().is_some());

		drop(system);

		assert!(!spawner.is_alive(), "spawner must observe the system drop");
		assert!(spawner.cancellation_token().is_none());
	}

	#[test]
	fn test_spawner_spawns_onto_the_same_system() {
		// The spawner must upgrade to the originating system, or the actor is never stepped.
		let system = test_system();
		let spawner = system.spawner();

		let handle = spawner.spawn_coordination("via-spawner", CounterActor);
		handle.actor_ref.send(CounterMessage::Inc).unwrap();
		handle.actor_ref.send(CounterMessage::Inc).unwrap();
		system.run_until_idle();

		assert_eq!(system.alive_count(), 1);
	}

	impl fmt::Debug for StepResult {
		fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
			match self {
				StepResult::Processed {
					actor_id,
				} => write!(f, "Processed {{ actor_id: {actor_id} }}"),
				StepResult::Panicked {
					actor_id,
					..
				} => write!(f, "Panicked {{ actor_id: {actor_id} }}"),
				StepResult::Stopped {
					actor_id,
				} => write!(f, "Stopped {{ actor_id: {actor_id} }}"),
				StepResult::Idle => write!(f, "Idle"),
			}
		}
	}
}