euv-core 0.41.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
use super::*;

/// Default initialization for `ReactiveRuntime`.
impl Default for ReactiveRuntime {
    /// Creates an empty reactive runtime with preallocated arena buffers.
    ///
    /// # Returns
    ///
    /// - `Self` - The initialized runtime instance.
    fn default() -> Self {
        Self {
            signals: Vec::with_capacity(INITIAL_ARENA_CAPACITY),
            free_signals: Vec::new(),
            memos: Vec::with_capacity(INITIAL_ARENA_CAPACITY),
            free_memos: Vec::new(),
            effects: Vec::with_capacity(INITIAL_ARENA_CAPACITY),
            free_effects: Vec::new(),
            scopes: Vec::with_capacity(INITIAL_ARENA_CAPACITY),
            free_scopes: Vec::new(),
            observer_stack: Vec::new(),
            scope_stack: Vec::new(),
            pending_effects: Vec::new(),
            dirty_queue: Vec::with_capacity(INITIAL_SUBSCRIBER_CAPACITY),
            batch_depth: 0,
            flushing: false,
            clock: 0,
            global_states: HashMap::new(),
            named_global_states: HashMap::new(),
            event_channels: HashMap::new(),
        }
    }
}

/// Core arena operations for `ReactiveRuntime`.
impl ReactiveRuntime {
    /// Allocates a new signal slot storing `initial_value`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `T` - Initial signal value.
    ///
    /// # Returns
    ///
    /// - `SignalId` - Handle for the newly created signal.
    pub(crate) fn create_signal<T>(&mut self, initial_value: T) -> SignalId
    where
        T: 'static,
    {
        let boxed: Box<dyn Any> = Box::new(initial_value);
        let id: SignalId = if let Some(index) = self.get_mut_free_signals().pop() {
            let entry: &mut SignalEntry = &mut self.get_mut_signals()[index as usize];
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            entry.set_version(0);
            entry.set_value(Some(boxed));
            entry.get_mut_subscribers().clear();
            SignalId::from_slot(SlotId::new(index, next_gen))
        } else {
            let index: u32 = self.get_signals().len() as u32;
            self.get_mut_signals().push(SignalEntry {
                generation: 1,
                version: 0,
                value: Some(boxed),
                subscribers: Vec::with_capacity(INITIAL_SUBSCRIBER_CAPACITY),
            });
            SignalId::from_slot(SlotId::new(index, 1))
        };
        if let Some(scope_id) = self.get_scope_stack().last().copied() {
            self.attach_signal_to_scope(scope_id, id);
        }
        id
    }

    /// Allocates a new root-lifetime signal in the arena without binding it to the active transient `Scope`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reactive runtime.
    /// - `T` - Initial signal value.
    ///
    /// # Returns
    ///
    /// - `SignalId` - Newly allocated detached signal identifier.
    pub(crate) fn create_detached_signal<T>(&mut self, initial_value: T) -> SignalId
    where
        T: 'static,
    {
        let boxed: Box<dyn Any> = Box::new(initial_value);
        if let Some(index) = self.get_mut_free_signals().pop() {
            let entry: &mut SignalEntry = &mut self.get_mut_signals()[index as usize];
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            entry.set_version(0);
            entry.set_value(Some(boxed));
            entry.get_mut_subscribers().clear();
            SignalId::from_slot(SlotId::new(index, next_gen))
        } else {
            let index: u32 = self.get_signals().len() as u32;
            self.get_mut_signals().push(SignalEntry {
                generation: 1,
                version: 0,
                value: Some(boxed),
                subscribers: Vec::with_capacity(INITIAL_SUBSCRIBER_CAPACITY),
            });
            SignalId::from_slot(SlotId::new(index, 1))
        }
    }

    /// Registers or replaces a root-lifetime global state signal keyed by `TypeId::of::<T>()`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reactive runtime.
    /// - `T` - Initial or replacement global state value.
    ///
    /// # Returns
    ///
    /// - `(SignalId, bool)` - Tuple of `(signal_id, should_flush)` when updating an existing slot.
    pub(crate) fn provide_global_state<T>(&mut self, initial: T) -> (SignalId, bool)
    where
        T: 'static,
    {
        let key: TypeId = TypeId::of::<T>();
        if let Some(existing_id) = self.get_global_states().get(&key).copied() {
            let slot: SlotId = existing_id.slot();
            let alive: bool = self
                .get_signals()
                .get(slot.as_usize())
                .map(|e: &SignalEntry| {
                    e.get_generation() == slot.get_generation() && e.value.is_some()
                })
                .unwrap_or(false);
            if alive {
                let (_, flush): (bool, bool) = self.write_signal(existing_id, initial);
                return (existing_id, flush);
            }
        }
        let id: SignalId = self.create_detached_signal(initial);
        let _: Option<SignalId> = self.get_mut_global_states().insert(key, id);
        (id, false)
    }

    /// Looks up a registered root-lifetime global state signal keyed by `TypeId::of::<T>()`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Reactive runtime reference.
    ///
    /// # Returns
    ///
    /// - `Option<SignalId>` - Registered signal handle if present.
    pub(crate) fn lookup_global_state<T>(&self) -> Option<SignalId>
    where
        T: 'static,
    {
        self.get_global_states().get(&TypeId::of::<T>()).copied()
    }

    /// Looks up a registered global state signal or initializes it lazily with `init`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reactive runtime.
    /// - `F` - Lazy initializer invoked only when absent.
    ///
    /// # Returns
    ///
    /// - `SignalId` - Existing or newly created global state signal handle.
    pub(crate) fn get_or_init_global_state<T, F>(&mut self, init: F) -> SignalId
    where
        T: 'static,
        F: FnOnce() -> T,
    {
        let key: TypeId = TypeId::of::<T>();
        if let Some(existing_id) = self.get_global_states().get(&key).copied() {
            return existing_id;
        }
        let id: SignalId = self.create_detached_signal(init());
        let _: Option<SignalId> = self.get_mut_global_states().insert(key, id);
        id
    }

    /// Registers or replaces a string-keyed root-lifetime named global state signal.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reactive runtime.
    /// - `&str` - Global state channel name.
    /// - `T` - Initial or replacement value.
    ///
    /// # Returns
    ///
    /// - `(SignalId, bool)` - Tuple of `(signal_id, should_flush)`.
    pub(crate) fn provide_named_global_state<T>(
        &mut self,
        name: &str,
        initial: T,
    ) -> (SignalId, bool)
    where
        T: 'static,
    {
        if let Some(existing_id) = self.get_named_global_states().get(name).copied() {
            let slot: SlotId = existing_id.slot();
            let alive: bool = self
                .get_signals()
                .get(slot.as_usize())
                .map(|e: &SignalEntry| {
                    e.get_generation() == slot.get_generation() && e.value.is_some()
                })
                .unwrap_or(false);
            if alive {
                let (_, flush): (bool, bool) = self.write_signal(existing_id, initial);
                return (existing_id, flush);
            }
        }
        let id: SignalId = self.create_detached_signal(initial);
        let _: Option<SignalId> = self
            .get_mut_named_global_states()
            .insert(name.to_string(), id);
        (id, false)
    }

    /// Looks up a string-keyed named global state signal.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Reactive runtime reference.
    /// - `&str` - Global state channel name.
    ///
    /// # Returns
    ///
    /// - `Option<SignalId>` - Registered signal handle if present.
    pub(crate) fn lookup_named_global_state(&self, name: &str) -> Option<SignalId> {
        self.get_named_global_states().get(name).copied()
    }

    /// Looks up or allocates the detached event channel signal for custom event type `E`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reactive runtime.
    ///
    /// # Returns
    ///
    /// - `SignalId` - Detached `Signal<(u64, Option<E>)>` channel identifier.
    pub(crate) fn ensure_event_channel<E>(&mut self) -> SignalId
    where
        E: CustomEvent,
    {
        let key: TypeId = TypeId::of::<E>();
        if let Some(existing_id) = self.get_event_channels().get(&key).copied() {
            return existing_id;
        }
        let initial: (u64, Option<E>) = (0, None);
        let id: SignalId = self.create_detached_signal(initial);
        let _: Option<SignalId> = self.get_mut_event_channels().insert(key, id);
        id
    }

    /// Reads a signal value via cloning inside the arena and records dependency tracking.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SignalId` - Signal identifier to read.
    ///
    /// # Returns
    ///
    /// - `Option<T>` - Cloned signal value if the slot is alive and matches type `T`.
    pub(crate) fn read_signal_cloned<T>(&mut self, id: SignalId) -> Option<T>
    where
        T: Clone + 'static,
    {
        self.track_dependency(DependencyId::Signal(id));
        let slot: SlotId = id.slot();
        let entry: &SignalEntry = self.get_signals().get(slot.as_usize())?;
        if entry.get_generation() != slot.get_generation() {
            return None;
        }
        let boxed: &Box<dyn Any> = entry.value.as_ref()?;
        boxed.downcast_ref::<T>().cloned()
    }

    /// Reads a signal value without recording any reactive dependency.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Reference to the reactive runtime.
    /// - `SignalId` - Signal identifier to inspect.
    ///
    /// # Returns
    ///
    /// - `Option<T>` - Cloned signal value if alive and matching type `T`.
    pub(crate) fn read_signal_untracked<T>(&self, id: SignalId) -> Option<T>
    where
        T: Clone + 'static,
    {
        let slot: SlotId = id.slot();
        let entry: &SignalEntry = self.get_signals().get(slot.as_usize())?;
        if entry.get_generation() != slot.get_generation() {
            return None;
        }
        let boxed: &Box<dyn Any> = entry.value.as_ref()?;
        boxed.downcast_ref::<T>().cloned()
    }

    /// Writes a new signal value in place and propagates dirty notifications without heap allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SignalId` - Signal identifier to update.
    /// - `T` - Replacement value.
    ///
    /// # Returns
    ///
    /// - `(bool, bool)` - Tuple `(updated, should_flush)` indicating whether the signal was alive and whether effects are pending.
    pub(crate) fn write_signal<T>(&mut self, id: SignalId, value: T) -> (bool, bool)
    where
        T: 'static,
    {
        let slot: SlotId = id.slot();
        let idx: usize = slot.as_usize();
        let Some(entry) = self.get_mut_signals().get_mut(idx) else {
            return (false, false);
        };
        if entry.get_generation() != slot.get_generation() || entry.value.is_none() {
            return (false, false);
        }
        if let Some(existing) = entry
            .value
            .as_mut()
            .and_then(|boxed: &mut Box<dyn Any>| boxed.downcast_mut::<T>())
        {
            *existing = value;
        } else {
            entry.set_value(Some(Box::new(value)));
        }
        let next_ver: u64 = entry.get_version().wrapping_add(1);
        entry.set_version(next_ver);
        let has_subs: bool = !entry.get_subscribers().is_empty();
        let next_clock: u64 = self.get_clock().wrapping_add(1);
        self.set_clock(next_clock);
        if has_subs {
            self.mark_signal_subscribers_dirty(idx);
        }
        let should_flush: bool =
            self.get_batch_depth() == 0 && !self.get_pending_effects().is_empty();
        (true, should_flush)
    }

    /// Writes a new signal value in place only when it differs from the stored value.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SignalId` - Signal identifier to update.
    /// - `T` - Candidate value compared using `PartialEq`.
    ///
    /// # Returns
    ///
    /// - `(bool, bool)` - Tuple `(changed, should_flush)` indicating whether the value changed and whether effects are pending.
    pub(crate) fn write_signal_if_changed<T>(&mut self, id: SignalId, value: T) -> (bool, bool)
    where
        T: PartialEq + 'static,
    {
        let slot: SlotId = id.slot();
        let idx: usize = slot.as_usize();
        let Some(entry) = self.get_mut_signals().get_mut(idx) else {
            return (false, false);
        };
        if entry.get_generation() != slot.get_generation() {
            return (false, false);
        }
        let Some(current) = entry
            .value
            .as_mut()
            .and_then(|boxed: &mut Box<dyn Any>| boxed.downcast_mut::<T>())
        else {
            return (false, false);
        };
        if *current == value {
            return (false, false);
        }
        *current = value;
        let next_ver: u64 = entry.get_version().wrapping_add(1);
        entry.set_version(next_ver);
        let has_subs: bool = !entry.get_subscribers().is_empty();
        let next_clock: u64 = self.get_clock().wrapping_add(1);
        self.set_clock(next_clock);
        if has_subs {
            self.mark_signal_subscribers_dirty(idx);
        }
        let should_flush: bool =
            self.get_batch_depth() == 0 && !self.get_pending_effects().is_empty();
        (true, should_flush)
    }

    /// Allocates a new memo slot with an in-place type-erased computation closure.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `F` - Memo computation closure mutating the cached value in place and returning `changed`.
    ///
    /// # Returns
    ///
    /// - `MemoId` - Handle for the newly created memo.
    pub(crate) fn create_memo<F>(&mut self, compute: F) -> MemoId
    where
        F: FnMut(&mut Option<Box<dyn Any>>) -> bool + 'static,
    {
        let depth: u32 = (self.get_observer_stack().len() as u32).saturating_add(1);
        let compute_rc: MemoComputeFn = Rc::new(RefCell::new(compute));
        let id: MemoId = if let Some(index) = self.get_mut_free_memos().pop() {
            let entry: &mut MemoEntry = &mut self.get_mut_memos()[index as usize];
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            entry.set_version(0);
            entry.set_state(NodeState::Dirty);
            entry.set_value(None);
            entry.set_compute(Some(compute_rc));
            entry.get_mut_dependencies().clear();
            entry.get_mut_subscribers().clear();
            entry.set_depth(depth);
            MemoId::from_slot(SlotId::new(index, next_gen))
        } else {
            let index: u32 = self.get_memos().len() as u32;
            self.get_mut_memos().push(MemoEntry {
                generation: 1,
                version: 0,
                state: NodeState::Dirty,
                value: None,
                compute: Some(compute_rc),
                dependencies: Vec::new(),
                subscribers: Vec::with_capacity(INITIAL_SUBSCRIBER_CAPACITY),
                depth,
            });
            MemoId::from_slot(SlotId::new(index, 1))
        };
        if let Some(scope_id) = self.get_scope_stack().last().copied() {
            self.attach_memo_to_scope(scope_id, id);
        }
        id
    }

    /// Allocates a new effect slot and schedules it for immediate execution.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `F` - Effect callback closure.
    ///
    /// # Returns
    ///
    /// - `EffectId` - Handle for the newly created effect.
    pub(crate) fn create_effect<F>(&mut self, callback: F) -> EffectId
    where
        F: FnMut() + 'static,
    {
        let depth: u32 = (self.get_observer_stack().len() as u32).saturating_add(1);
        let callback_rc: Rc<RefCell<dyn FnMut()>> = Rc::new(RefCell::new(callback));
        let id: EffectId = if let Some(index) = self.get_mut_free_effects().pop() {
            let entry: &mut EffectEntry = &mut self.get_mut_effects()[index as usize];
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            entry.set_alive(true);
            entry.set_scheduled(false);
            entry.set_callback(Some(callback_rc));
            entry.get_mut_dependencies().clear();
            entry.set_depth(depth);
            entry.set_frozen_depth(0);
            entry.set_pending_while_frozen(false);
            EffectId::from_slot(SlotId::new(index, next_gen))
        } else {
            let index: u32 = self.get_effects().len() as u32;
            self.get_mut_effects().push(EffectEntry {
                generation: 1,
                alive: true,
                scheduled: false,
                callback: Some(callback_rc),
                dependencies: Vec::new(),
                depth,
                frozen_depth: 0,
                pending_while_frozen: false,
            });
            EffectId::from_slot(SlotId::new(index, 1))
        };
        if let Some(scope_id) = self.get_scope_stack().last().copied() {
            self.attach_effect_to_scope(scope_id, id);
        }
        id
    }

    /// Creates a new ownership scope and optionally links it to the active parent scope.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    ///
    /// # Returns
    ///
    /// - `ScopeId` - Identifier for the newly created scope.
    pub(crate) fn create_scope(&mut self) -> ScopeId {
        let id: ScopeId = if let Some(index) = self.get_mut_free_scopes().pop() {
            let entry: &mut ScopeEntry = &mut self.get_mut_scopes()[index as usize];
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            entry.set_alive(true);
            entry.set_frozen(false);
            entry.get_mut_signals().clear();
            entry.get_mut_memos().clear();
            entry.get_mut_effects().clear();
            entry.get_mut_children().clear();
            entry.get_mut_cleanups().clear();
            ScopeId::from_slot(SlotId::new(index, next_gen))
        } else {
            let index: u32 = self.get_scopes().len() as u32;
            self.get_mut_scopes().push(ScopeEntry {
                generation: 1,
                alive: true,
                frozen: false,
                signals: Vec::new(),
                memos: Vec::new(),
                effects: Vec::new(),
                children: Vec::new(),
                cleanups: Vec::new(),
            });
            ScopeId::from_slot(SlotId::new(index, 1))
        };
        if let Some(parent_id) = self.get_scope_stack().last().copied() {
            let parent_slot: SlotId = parent_id.slot();
            if let Some(parent) = self.get_mut_scopes().get_mut(parent_slot.as_usize())
                && parent.get_generation() == parent_slot.get_generation()
                && parent.get_alive()
            {
                parent.get_mut_children().push(id);
            }
        }
        id
    }

    /// Registers a cleanup callback on the currently active scope.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `F` - Cleanup closure invoked when the active scope disposes.
    pub(crate) fn register_cleanup<F>(&mut self, cleanup: F)
    where
        F: FnOnce() + 'static,
    {
        if let Some(scope_id) = self.get_scope_stack().last().copied() {
            let slot: SlotId = scope_id.slot();
            if let Some(entry) = self.get_mut_scopes().get_mut(slot.as_usize())
                && entry.get_generation() == slot.get_generation()
                && entry.get_alive()
            {
                entry.get_mut_cleanups().push(Box::new(cleanup));
            }
        }
    }

    /// Records `dependency` on the currently executing observer if one exists.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `DependencyId` - The dependency accessed during evaluation.
    pub(crate) fn track_dependency(&mut self, dependency: DependencyId) {
        let Some(Some(subscriber)) = self.get_observer_stack().last().copied() else {
            return;
        };
        match dependency {
            DependencyId::Signal(sig_id) => {
                let slot: SlotId = sig_id.slot();
                if let Some(entry) = self.get_mut_signals().get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                    && !entry.get_subscribers().contains(&subscriber)
                {
                    entry.get_mut_subscribers().push(subscriber);
                }
            }
            DependencyId::Memo(memo_id) => {
                let slot: SlotId = memo_id.slot();
                if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                    && !entry.get_subscribers().contains(&subscriber)
                {
                    entry.get_mut_subscribers().push(subscriber);
                }
            }
        }
        match subscriber {
            SubscriberId::Memo(memo_id) => {
                let slot: SlotId = memo_id.slot();
                if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                    && !entry.get_dependencies().contains(&dependency)
                {
                    entry.get_mut_dependencies().push(dependency);
                }
            }
            SubscriberId::Effect(effect_id) => {
                let slot: SlotId = effect_id.slot();
                if let Some(entry) = self.get_mut_effects().get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                    && !entry.get_dependencies().contains(&dependency)
                {
                    entry.get_mut_dependencies().push(dependency);
                }
            }
        }
    }

    /// Propagates dirty flags downstream from signal slot `signal_idx` using the reusable scratch queue.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `usize` - Signal arena slot index.
    pub(crate) fn mark_signal_subscribers_dirty(&mut self, signal_idx: usize) {
        let Self {
            signals,
            dirty_queue,
            ..
        } = self;
        dirty_queue.clear();
        if let Some(entry) = signals.get(signal_idx) {
            for subscriber in entry.get_subscribers().iter().copied() {
                dirty_queue.push((subscriber, true));
            }
        }
        self.drain_dirty_queue();
    }

    /// Propagates dirty flags downstream from memo slot `memo_idx` using the reusable scratch queue.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `usize` - Memo arena slot index.
    pub(crate) fn mark_memo_subscribers_dirty(&mut self, memo_idx: usize) {
        let Self {
            memos, dirty_queue, ..
        } = self;
        dirty_queue.clear();
        if let Some(entry) = memos.get(memo_idx) {
            for subscriber in entry.get_subscribers().iter().copied() {
                dirty_queue.push((subscriber, true));
            }
        }
        self.drain_dirty_queue();
    }

    /// Drains the reusable `dirty_queue`, marking downstream memos and scheduling effects with zero allocations.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    fn drain_dirty_queue(&mut self) {
        let Self {
            memos,
            effects,
            pending_effects,
            dirty_queue,
            ..
        } = self;
        while let Some((sub, is_direct)) = dirty_queue.pop() {
            match sub {
                SubscriberId::Memo(memo_id) => {
                    let slot: SlotId = memo_id.slot();
                    if let Some(entry) = memos.get_mut(slot.as_usize()) {
                        if entry.get_generation() != slot.get_generation()
                            || entry.compute.is_none()
                        {
                            continue;
                        }
                        let target_state: NodeState = if is_direct {
                            NodeState::Dirty
                        } else {
                            NodeState::Check
                        };
                        if entry.get_state() == NodeState::Dirty
                            || (entry.get_state() == NodeState::Check
                                && target_state == NodeState::Check)
                        {
                            continue;
                        }
                        entry.set_state(target_state);
                        for child_sub in entry.get_subscribers().iter().copied() {
                            dirty_queue.push((child_sub, false));
                        }
                    }
                }
                SubscriberId::Effect(effect_id) => {
                    let slot: SlotId = effect_id.slot();
                    if let Some(entry) = effects.get_mut(slot.as_usize())
                        && entry.get_generation() == slot.get_generation()
                        && entry.get_alive()
                    {
                        if entry.get_frozen_depth() > 0 {
                            entry.set_pending_while_frozen(true);
                        } else if !entry.get_scheduled() {
                            entry.set_scheduled(true);
                            pending_effects.push(effect_id);
                        }
                    }
                }
            }
        }
    }

    /// Detaches a subscriber from all of its previously tracked upstream dependencies while preserving Vec capacity.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SubscriberId` - Subscriber whose dependency links should be cleared.
    pub(crate) fn clear_dependencies(&mut self, subscriber: SubscriberId) {
        let mut deps: Vec<DependencyId> = match subscriber {
            SubscriberId::Memo(memo_id) => {
                let slot: SlotId = memo_id.slot();
                match self.get_mut_memos().get_mut(slot.as_usize()) {
                    Some(entry) if entry.get_generation() == slot.get_generation() => {
                        take(entry.get_mut_dependencies())
                    }
                    _ => Vec::new(),
                }
            }
            SubscriberId::Effect(effect_id) => {
                let slot: SlotId = effect_id.slot();
                match self.get_mut_effects().get_mut(slot.as_usize()) {
                    Some(entry) if entry.get_generation() == slot.get_generation() => {
                        take(entry.get_mut_dependencies())
                    }
                    _ => Vec::new(),
                }
            }
        };
        if deps.is_empty() {
            return;
        }
        for dep in deps.drain(..) {
            match dep {
                DependencyId::Signal(sig_id) => {
                    let slot: SlotId = sig_id.slot();
                    if let Some(entry) = self.get_mut_signals().get_mut(slot.as_usize())
                        && entry.get_generation() == slot.get_generation()
                    {
                        entry
                            .get_mut_subscribers()
                            .retain(|item: &SubscriberId| *item != subscriber);
                    }
                }
                DependencyId::Memo(memo_id) => {
                    let slot: SlotId = memo_id.slot();
                    if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
                        && entry.get_generation() == slot.get_generation()
                    {
                        entry
                            .get_mut_subscribers()
                            .retain(|item: &SubscriberId| *item != subscriber);
                    }
                }
            }
        }
        match subscriber {
            SubscriberId::Memo(memo_id) => {
                let slot: SlotId = memo_id.slot();
                if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                {
                    entry.set_dependencies(deps);
                }
            }
            SubscriberId::Effect(effect_id) => {
                let slot: SlotId = effect_id.slot();
                if let Some(entry) = self.get_mut_effects().get_mut(slot.as_usize())
                    && entry.get_generation() == slot.get_generation()
                {
                    entry.set_dependencies(deps);
                }
            }
        }
    }

    /// Disposes a signal slot and returns it to the free list.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `SignalId` - Signal identifier to dispose.
    pub(crate) fn dispose_signal(&mut self, id: SignalId) {
        let slot: SlotId = id.slot();
        if let Some(entry) = self.get_mut_signals().get_mut(slot.as_usize())
            && entry.get_generation() == slot.get_generation()
            && entry.value.is_some()
        {
            entry.set_value(None);
            entry.get_mut_subscribers().clear();
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            self.get_mut_free_signals().push(slot.get_index());
        }
    }

    /// Disposes a memo slot and detaches its dependencies.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `MemoId` - Memo identifier to dispose.
    pub(crate) fn dispose_memo(&mut self, id: MemoId) {
        self.clear_dependencies(SubscriberId::Memo(id));
        let slot: SlotId = id.slot();
        if let Some(entry) = self.get_mut_memos().get_mut(slot.as_usize())
            && entry.get_generation() == slot.get_generation()
            && entry.compute.is_some()
        {
            entry.set_value(None);
            entry.set_compute(None);
            entry.get_mut_subscribers().clear();
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            self.get_mut_free_memos().push(slot.get_index());
        }
    }

    /// Disposes an effect slot and detaches its dependencies.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `EffectId` - Effect identifier to dispose.
    pub(crate) fn dispose_effect(&mut self, id: EffectId) {
        self.clear_dependencies(SubscriberId::Effect(id));
        let slot: SlotId = id.slot();
        if let Some(entry) = self.get_mut_effects().get_mut(slot.as_usize())
            && entry.get_generation() == slot.get_generation()
            && entry.get_alive()
        {
            entry.set_alive(false);
            entry.set_scheduled(false);
            entry.set_frozen_depth(0);
            entry.set_pending_while_frozen(false);
            entry.set_callback(None);
            let next_gen: u32 = entry.get_generation().wrapping_add(1);
            entry.set_generation(next_gen);
            self.get_mut_free_effects().push(slot.get_index());
        }
    }

    /// Collects all resources belonging to a scope and marks them disposed, returning cleanup closures.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `ScopeId` - Scope identifier to dispose recursively.
    ///
    /// # Returns
    ///
    /// - `Vec<Box<dyn FnOnce()>>` - Cleanup callbacks to execute outside the runtime borrow.
    pub(crate) fn dispose_scope_collect(&mut self, id: ScopeId) -> Vec<Box<dyn FnOnce()>> {
        let mut all_cleanups: Vec<Box<dyn FnOnce()>> = Vec::new();
        let mut stack: Vec<ScopeId> = vec![id];
        while let Some(current_id) = stack.pop() {
            let slot: SlotId = current_id.slot();
            let (children, effects, memos, signals, cleanups): ScopeDrain =
                match self.get_mut_scopes().get_mut(slot.as_usize()) {
                    Some(entry)
                        if entry.get_generation() == slot.get_generation() && entry.get_alive() =>
                    {
                        entry.set_alive(false);
                        let next_gen: u32 = entry.get_generation().wrapping_add(1);
                        entry.set_generation(next_gen);
                        let out: ScopeDrain = (
                            take(entry.get_mut_children()),
                            take(entry.get_mut_effects()),
                            take(entry.get_mut_memos()),
                            take(entry.get_mut_signals()),
                            take(entry.get_mut_cleanups()),
                        );
                        self.get_mut_free_scopes().push(slot.get_index());
                        out
                    }
                    _ => continue,
                };
            for child in children.into_iter() {
                stack.push(child);
            }
            for eff in effects.into_iter() {
                self.dispose_effect(eff);
            }
            for memo in memos.into_iter() {
                self.dispose_memo(memo);
            }
            for sig in signals.into_iter() {
                self.dispose_signal(sig);
            }
            all_cleanups.extend(cleanups);
        }
        all_cleanups
    }

    /// Computes live diagnostic statistics for the runtime arena.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Reference to the reactive runtime.
    ///
    /// # Returns
    ///
    /// - `ReactiveStats` - Snapshot of live node counts and write clock.
    #[must_use]
    pub fn stats(&self) -> ReactiveStats {
        let live_signals: usize = self
            .get_signals()
            .iter()
            .filter(|entry: &&SignalEntry| entry.value.is_some())
            .count();
        let live_memos: usize = self
            .get_memos()
            .iter()
            .filter(|entry: &&MemoEntry| entry.compute.is_some())
            .count();
        let live_effects: usize = self
            .get_effects()
            .iter()
            .filter(|entry: &&EffectEntry| entry.get_alive())
            .count();
        let live_scopes: usize = self
            .get_scopes()
            .iter()
            .filter(|entry: &&ScopeEntry| entry.get_alive())
            .count();
        ReactiveStats::new(
            live_signals,
            live_memos,
            live_effects,
            live_scopes,
            self.get_clock(),
        )
    }

    /// Attaches a signal identifier to an active scope entry.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `ScopeId` - Target scope identifier.
    /// - `SignalId` - Signal identifier to attach.
    fn attach_signal_to_scope(&mut self, scope_id: ScopeId, signal_id: SignalId) {
        let slot: SlotId = scope_id.slot();
        if let Some(entry) = self.get_mut_scopes().get_mut(slot.as_usize())
            && entry.get_generation() == slot.get_generation()
            && entry.get_alive()
        {
            entry.get_mut_signals().push(signal_id);
        }
    }

    /// Attaches a memo identifier to an active scope entry.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `ScopeId` - Target scope identifier.
    /// - `MemoId` - Memo identifier to attach.
    fn attach_memo_to_scope(&mut self, scope_id: ScopeId, memo_id: MemoId) {
        let slot: SlotId = scope_id.slot();
        if let Some(entry) = self.get_mut_scopes().get_mut(slot.as_usize())
            && entry.get_generation() == slot.get_generation()
            && entry.get_alive()
        {
            entry.get_mut_memos().push(memo_id);
        }
    }

    /// Attaches an effect identifier to an active scope entry.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `ScopeId` - Target scope identifier.
    /// - `EffectId` - Effect identifier to attach.
    fn attach_effect_to_scope(&mut self, scope_id: ScopeId, effect_id: EffectId) {
        let slot: SlotId = scope_id.slot();
        let scope_is_frozen: bool = if let Some(entry) =
            self.get_mut_scopes().get_mut(slot.as_usize())
            && entry.get_generation() == slot.get_generation()
            && entry.get_alive()
        {
            entry.get_mut_effects().push(effect_id);
            entry.get_frozen()
        } else {
            false
        };
        if scope_is_frozen {
            let eff_slot: SlotId = effect_id.slot();
            if let Some(eff) = self.get_mut_effects().get_mut(eff_slot.as_usize())
                && eff.get_generation() == eff_slot.get_generation()
            {
                let next_d: u32 = eff.get_frozen_depth().saturating_add(1);
                eff.set_frozen_depth(next_d);
            }
        }
    }

    /// Recursively freezes or resumes `id` and all nested child scopes, coalescing any pending dirty effects on resume.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable reference to the reactive runtime.
    /// - `ScopeId` - Root scope identifier to freeze or resume.
    /// - `bool` - `true` to freeze; `false` to resume.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when resuming scheduled one or more deferred effects that require flushing.
    pub(crate) fn set_scope_frozen(&mut self, id: ScopeId, freeze: bool) -> bool {
        let root_slot: SlotId = id.slot();
        let should_change: bool = self
            .get_scopes()
            .get(root_slot.as_usize())
            .map(|entry: &ScopeEntry| {
                entry.get_generation() == root_slot.get_generation()
                    && entry.get_alive()
                    && entry.get_frozen() != freeze
            })
            .unwrap_or(false);
        if !should_change {
            return false;
        }
        let mut stack: Vec<ScopeId> = vec![id];
        let mut any_resumed_dirty: bool = false;
        while let Some(cur_id) = stack.pop() {
            let slot: SlotId = cur_id.slot();
            let (children, effects): (Vec<ScopeId>, Vec<EffectId>) =
                match self.get_mut_scopes().get_mut(slot.as_usize()) {
                    Some(entry)
                        if entry.get_generation() == slot.get_generation() && entry.get_alive() =>
                    {
                        if cur_id == id {
                            entry.set_frozen(freeze);
                        }
                        (entry.get_children().clone(), entry.get_effects().clone())
                    }
                    _ => continue,
                };
            for child in children.into_iter() {
                stack.push(child);
            }
            for eff_id in effects.into_iter() {
                let eslot: SlotId = eff_id.slot();
                let mut schedule_now: bool = false;
                if let Some(eff) = self.get_mut_effects().get_mut(eslot.as_usize())
                    && eff.get_generation() == eslot.get_generation()
                    && eff.get_alive()
                {
                    if freeze {
                        let next_d: u32 = eff.get_frozen_depth().saturating_add(1);
                        eff.set_frozen_depth(next_d);
                    } else {
                        let next_d: u32 = eff.get_frozen_depth().saturating_sub(1);
                        eff.set_frozen_depth(next_d);
                        if next_d == 0 && eff.get_pending_while_frozen() {
                            eff.set_pending_while_frozen(false);
                            if !eff.get_scheduled() {
                                eff.set_scheduled(true);
                                schedule_now = true;
                            }
                        }
                    }
                }
                if schedule_now {
                    self.get_mut_pending_effects().push(eff_id);
                    any_resumed_dirty = true;
                }
            }
        }
        any_resumed_dirty
    }

    /// Returns whether scope `id` is currently alive and frozen.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Reactive runtime reference.
    /// - `ScopeId` - Scope identifier to query.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the scope is frozen.
    pub(crate) fn is_scope_frozen(&self, id: ScopeId) -> bool {
        let slot: SlotId = id.slot();
        self.get_scopes()
            .get(slot.as_usize())
            .map(|entry: &ScopeEntry| {
                entry.get_generation() == slot.get_generation()
                    && entry.get_alive()
                    && entry.get_frozen()
            })
            .unwrap_or(false)
    }
}