euv-core 0.48.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
use super::*;

/// Encodes a signal arena index as a packed source edge tag (`bit 31 = 0`).
///
/// # Arguments
///
/// - `u32` - Zero-based signal slot index.
///
/// # Returns
///
/// - `u32` - Packed source tag identifying the signal.
#[must_use]
#[inline(always)]
pub(crate) const fn encode_signal_source_tag(index: u32) -> u32 {
    index & EDGE_INDEX_MASK
}

/// Encodes a memo arena index as a packed source edge tag (`bit 31 = 1`).
///
/// # Arguments
///
/// - `u32` - Zero-based memo slot index.
///
/// # Returns
///
/// - `u32` - Packed source tag identifying the memo.
#[must_use]
#[inline(always)]
pub(crate) const fn encode_memo_source_tag(index: u32) -> u32 {
    (index & EDGE_INDEX_MASK) | EDGE_KIND_BIT
}

/// Returns `true` when a packed source edge tag refers to a memo rather than a signal.
///
/// # Arguments
///
/// - `u32` - Packed source edge tag.
///
/// # Returns
///
/// - `bool` - `true` for memo sources, `false` for signal sources.
#[must_use]
#[inline(always)]
pub(crate) const fn is_memo_source_tag(tag: u32) -> bool {
    (tag & EDGE_KIND_BIT) != 0
}

/// Encodes a memo arena index as a packed subscriber edge tag (`bit 31 = 0`).
///
/// # Arguments
///
/// - `u32` - Zero-based memo slot index.
///
/// # Returns
///
/// - `u32` - Packed subscriber tag identifying the memo.
#[must_use]
#[inline(always)]
pub(crate) const fn encode_memo_sub_tag(index: u32) -> u32 {
    index & EDGE_INDEX_MASK
}

/// Encodes an effect arena index as a packed subscriber edge tag (`bit 31 = 1`).
///
/// # Arguments
///
/// - `u32` - Zero-based effect slot index.
///
/// # Returns
///
/// - `u32` - Packed subscriber tag identifying the effect.
#[must_use]
#[inline(always)]
pub(crate) const fn encode_effect_sub_tag(index: u32) -> u32 {
    (index & EDGE_INDEX_MASK) | EDGE_KIND_BIT
}

/// Returns `true` when a packed subscriber edge tag refers to an effect rather than a memo.
///
/// # Arguments
///
/// - `u32` - Packed subscriber edge tag.
///
/// # Returns
///
/// - `bool` - `true` for effect subscribers, `false` for memo subscribers.
#[must_use]
#[inline(always)]
pub(crate) const fn is_effect_sub_tag(tag: u32) -> bool {
    (tag & EDGE_KIND_BIT) != 0
}

/// Extracts the zero-based arena slot index from a packed source or subscriber tag.
///
/// # Arguments
///
/// - `u32` - Packed source or subscriber tag.
///
/// # Returns
///
/// - `usize` - Zero-based arena slot index.
#[must_use]
#[inline(always)]
pub(crate) const fn decode_edge_tag_index(tag: u32) -> usize {
    (tag & EDGE_INDEX_MASK) as usize
}

/// Combines `(source_tag, sub_tag)` into a compact 64-bit key for `ReactiveRuntime::edge_index`.
///
/// # Arguments
///
/// - `u32` - Packed source tag.
/// - `u32` - Packed subscriber tag.
///
/// # Returns
///
/// - `u64` - Unique composite lookup key.
#[must_use]
#[inline(always)]
pub(crate) const fn edge_index_key(source_tag: u32, sub_tag: u32) -> u64 {
    ((source_tag as u64) << 32) | (sub_tag as u64)
}

/// Returns whether the thread-local reactive runtime currently has an active tracking observer frame.
///
/// # Returns
///
/// - `bool` - `true` when reactive reads should record dependencies.
#[must_use]
#[inline(always)]
pub(crate) fn is_tracking_active() -> bool {
    TRACKING_ACTIVE
        .try_with(|flag: &Cell<bool>| flag.get())
        .unwrap_or(false)
}

/// Updates the fast-path `TRACKING_ACTIVE` thread-local flag and returns its previous value.
///
/// # Arguments
///
/// - `bool` - New active tracking state.
///
/// # Returns
///
/// - `bool` - Previous active tracking state.
#[inline(always)]
pub(crate) fn set_tracking_active(active: bool) -> bool {
    TRACKING_ACTIVE
        .try_with(|flag: &Cell<bool>| flag.replace(active))
        .unwrap_or(false)
}

/// Returns the current nesting depth of active shared `RefCell::try_borrow()` signal reads.
///
/// # Returns
///
/// - `u32` - Current shared borrow nesting depth (`0` when no `with_ref` borrow is active).
#[must_use]
#[inline(always)]
pub(crate) fn ref_borrow_depth() -> u32 {
    REF_BORROW_DEPTH
        .try_with(|depth: &Cell<u32>| depth.get())
        .unwrap_or(0)
}

/// Records `dependency` immediately when unborrowed, or queues it in `PENDING_REF_TRACKS` while inside a nested `with_ref` borrow.
///
/// # Arguments
///
/// - `DependencyId` - Reactive source read by the active observer.
#[inline]
pub(crate) fn track_or_defer_dependency(dependency: DependencyId) {
    if !is_tracking_active() {
        return;
    }
    if ref_borrow_depth() == 0 {
        with_runtime(
            |rt: &mut ReactiveRuntime| {
                rt.track_dependency(dependency);
            },
            (),
        );
        return;
    }
    let _: Result<(), _> = PENDING_REF_TRACKS.try_with(|cell: &RefCell<Vec<DependencyId>>| {
        if let Ok(mut pending) = cell.try_borrow_mut() {
            pending.push(dependency);
        }
    });
}

/// Flushes any deferred dependency reads recorded during nested `with_ref` calls once the outermost shared borrow releases.
#[inline]
pub(crate) fn flush_pending_ref_tracks() {
    let mut staged: Vec<DependencyId> = PENDING_REF_TRACKS
        .try_with(|cell: &RefCell<Vec<DependencyId>>| {
            let is_empty: bool = cell
                .try_borrow()
                .map(|guard: Ref<'_, Vec<DependencyId>>| guard.is_empty())
                .unwrap_or(true);
            if is_empty {
                return Vec::new();
            }
            match cell.try_borrow_mut() {
                Ok(mut guard) => take(&mut *guard),
                Err(_) => Vec::new(),
            }
        })
        .unwrap_or_default();
    if staged.is_empty() {
        return;
    }
    if is_tracking_active() {
        with_runtime(
            |rt: &mut ReactiveRuntime| {
                for dep in staged.drain(..) {
                    rt.track_dependency(dep);
                }
            },
            (),
        );
    } else {
        staged.clear();
    }
    let _: Result<(), _> = PENDING_REF_TRACKS.try_with(|cell: &RefCell<Vec<DependencyId>>| {
        if let Ok(mut guard) = cell.try_borrow_mut()
            && guard.is_empty()
            && staged.capacity() > guard.capacity()
        {
            *guard = staged;
        }
    });
}

/// Executes a closure with mutable access to the thread-local reactive runtime.
///
/// # Arguments
///
/// - `F` - Closure receiving `&mut ReactiveRuntime`.
/// - `R` - Fallback return value used if the runtime cannot be borrowed.
///
/// # Returns
///
/// - `R` - Closure result or fallback value.
#[inline(always)]
pub(crate) fn with_runtime<F, R>(operation: F, fallback: R) -> R
where
    F: FnOnce(&mut ReactiveRuntime) -> R,
{
    REACTIVE_RUNTIME
        .try_with(
            |cell: &RefCell<ReactiveRuntime>| match cell.try_borrow_mut() {
                Ok(mut guard) => Some(operation(&mut guard)),
                Err(_) => None,
            },
        )
        .ok()
        .flatten()
        .unwrap_or(fallback)
}

/// Executes a read-only closure with shared `RefCell::try_borrow()` access to the thread-local reactive runtime.
///
/// # Arguments
///
/// - `F` - Read-only closure receiving `&ReactiveRuntime`.
/// - `R` - Fallback return value used if the runtime is mutably borrowed.
///
/// # Returns
///
/// - `R` - Closure result or fallback value.
#[inline(always)]
pub(crate) fn with_runtime_ref<F, R>(operation: F, fallback: R) -> R
where
    F: FnOnce(&ReactiveRuntime) -> R,
{
    REACTIVE_RUNTIME
        .try_with(|cell: &RefCell<ReactiveRuntime>| match cell.try_borrow() {
            Ok(guard) => Some(operation(&guard)),
            Err(_) => None,
        })
        .ok()
        .flatten()
        .unwrap_or(fallback)
}

/// Borrows a signal's stored `&T` directly via shared `RefCell::try_borrow()` without cloning, supporting nested read-only borrows.
///
/// # Arguments
///
/// - `SignalId` - Signal identifier to borrow.
/// - `bool` - Whether to record dependency tracking on the active observer.
/// - `F` - Read-only closure invoked with `&T`.
///
/// # Returns
///
/// - `Option<R>` - Closure result when the signal is alive, matches `T`, and the runtime is not mutably borrowed.
#[inline]
pub(crate) fn read_signal_with_ref<T, F, R>(id: SignalId, tracked: bool, reader: F) -> Option<R>
where
    T: 'static,
    F: FnOnce(&T) -> R,
{
    if tracked {
        track_or_defer_dependency(DependencyId::Signal(id));
    }
    let _ref_guard: RefBorrowGuard = RefBorrowGuard::enter();
    let slot: SlotId = id.slot();
    REACTIVE_RUNTIME
        .try_with(|cell: &RefCell<ReactiveRuntime>| {
            let guard: Ref<'_, ReactiveRuntime> = cell.try_borrow().ok()?;
            let entry: &SignalEntry = guard.get_signals().get(slot.as_usize())?;
            if entry.get_generation() != slot.get_generation() {
                return None;
            }
            let value: &T = entry.get_value().downcast_ref::<T>()?;
            Some(reader(value))
        })
        .ok()
        .flatten()
}

/// Borrows a memo's cached `&T` directly via shared `RefCell::try_borrow()` without cloning, evaluating lazily first when unborrowed.
///
/// # Arguments
///
/// - `MemoId` - Memo identifier to borrow.
/// - `impl FnOnce(&T) -> R` - Read-only closure invoked with `&T`.
///
/// # Returns
///
/// - `Option<R>` - Closure result when the memo is alive, clean, and matches `T`.
#[inline]
pub(crate) fn read_memo_with_ref<T, R>(id: MemoId, reader: impl FnOnce(&T) -> R) -> Option<R>
where
    T: 'static,
{
    if ref_borrow_depth() == 0 {
        let needs_eval: bool = with_runtime_ref(
            |rt: &ReactiveRuntime| {
                let slot: SlotId = id.slot();
                rt.get_memos()
                    .get(slot.as_usize())
                    .is_some_and(|entry: &MemoEntry| {
                        entry.get_generation() == slot.get_generation()
                            && entry.compute.is_some()
                            && entry.get_state() != NodeState::Clean
                    })
            },
            false,
        );
        if needs_eval {
            let _: bool = evaluate_memo(id);
        }
    }
    track_or_defer_dependency(DependencyId::Memo(id));
    let _ref_guard: RefBorrowGuard = RefBorrowGuard::enter();
    let slot: SlotId = id.slot();
    REACTIVE_RUNTIME
        .try_with(|cell: &RefCell<ReactiveRuntime>| {
            let guard: Ref<'_, ReactiveRuntime> = cell.try_borrow().ok()?;
            let entry: &MemoEntry = guard.get_memos().get(slot.as_usize())?;
            if entry.get_generation() != slot.get_generation()
                || entry.get_state() != NodeState::Clean
            {
                return None;
            }
            let value: &T = entry.get_value().downcast_ref::<T>()?;
            Some(reader(value))
        })
        .ok()
        .flatten()
}

/// Pull-verifies upstream `MemoId` dependencies for a `NodeState::Check` memo, short-circuiting on the first change.
///
/// # Arguments
///
/// - `MemoCheckDeps` - Zero-allocation inline or cursor-sliced upstream memo dependency snapshot.
///
/// # Returns
///
/// - `bool` - `true` as soon as any upstream memo recomputes to a changed value.
fn verify_check_memos(deps: MemoCheckDeps) -> bool {
    match deps {
        MemoCheckDeps::Inline(buf, count) => {
            let len: usize = count as usize;
            for parent_memo in buf.iter().copied().take(len) {
                if evaluate_memo(parent_memo) {
                    return true;
                }
            }
            false
        }
        MemoCheckDeps::Spill(start, end) => {
            let mut changed: bool = false;
            let mut cursor: usize = start;
            while cursor < end {
                let parent_opt: Option<MemoId> = with_runtime_ref(
                    |rt: &ReactiveRuntime| rt.get_check_scratch().get(cursor).copied(),
                    None,
                );
                if let Some(parent_memo) = parent_opt
                    && evaluate_memo(parent_memo)
                {
                    changed = true;
                    break;
                }
                cursor += 1;
            }
            with_runtime(
                |rt: &mut ReactiveRuntime| {
                    rt.get_mut_check_scratch().truncate(start);
                },
                (),
            );
            changed
        }
    }
}

/// Reads a typed `Memo<T>` using fused runtime borrows (1 borrow on `Clean`, 2 borrows on `Dirty` or unchanged `Check`).
///
/// # Arguments
///
/// - `MemoId` - Target memo identifier to read and track.
///
/// # Returns
///
/// - `Option<T>` - Current computed value if alive and matching type `T`.
#[must_use]
pub(crate) fn read_memo_fused<T>(id: MemoId) -> Option<T>
where
    T: Clone + 'static,
{
    if ref_borrow_depth() > 0 {
        return read_memo_with_ref::<T, T>(id, |val: &T| val.clone());
    }
    let slot: SlotId = id.slot();
    let idx: usize = slot.as_usize();
    let prep: MemoReadPrep<T> = with_runtime(
        |rt: &mut ReactiveRuntime| {
            let state: NodeState = {
                let Some(entry) = rt.get_memos().get(idx) else {
                    return MemoReadPrep::Dead;
                };
                if entry.get_generation() != slot.get_generation() {
                    return MemoReadPrep::Dead;
                }
                entry.get_state()
            };
            match state {
                NodeState::Clean => {
                    let val: Option<T> =
                        rt.get_memos()[idx].get_value().downcast_ref::<T>().cloned();
                    rt.track_dependency(DependencyId::Memo(id));
                    MemoReadPrep::Ready(val)
                }
                NodeState::Dirty => {
                    let (compute, prev_value): (MemoComputeFn, SignalSlot) = {
                        let entry: &mut MemoEntry = &mut rt.get_mut_memos()[idx];
                        let Some(compute) = entry.compute.clone() else {
                            return MemoReadPrep::Dead;
                        };
                        let prev_value: SignalSlot = entry.get_mut_value().take();
                        (compute, prev_value)
                    };
                    if !rt.begin_tracking(SubscriberId::Memo(id)) {
                        rt.get_mut_memos()[idx].set_value(prev_value);
                        return MemoReadPrep::Dead;
                    }
                    MemoReadPrep::Compute(compute, prev_value)
                }
                NodeState::Check => {
                    if rt.get_memos()[idx].compute.is_none() {
                        return MemoReadPrep::Dead;
                    }
                    if let Some(check_deps) = rt.collect_check_memos(idx) {
                        MemoReadPrep::Check(check_deps)
                    } else {
                        let entry: &mut MemoEntry = &mut rt.get_mut_memos()[idx];
                        entry.set_state(NodeState::Clean);
                        let val: Option<T> = entry.get_value().downcast_ref::<T>().cloned();
                        rt.track_dependency(DependencyId::Memo(id));
                        MemoReadPrep::Ready(val)
                    }
                }
            }
        },
        MemoReadPrep::Dead,
    );
    let (compute, mut value_slot): (MemoComputeFn, SignalSlot) = match prep {
        MemoReadPrep::Dead => return None,
        MemoReadPrep::Ready(val) => return val,
        MemoReadPrep::Compute(compute, prev_value) => (compute, prev_value),
        MemoReadPrep::Check(deps) => {
            if !verify_check_memos(deps) {
                return with_runtime(
                    |rt: &mut ReactiveRuntime| {
                        let entry: &mut MemoEntry = rt.get_mut_memos().get_mut(idx)?;
                        if entry.get_generation() != slot.get_generation() {
                            return None;
                        }
                        entry.set_state(NodeState::Clean);
                        let val: Option<T> = entry.get_value().downcast_ref::<T>().cloned();
                        rt.track_dependency(DependencyId::Memo(id));
                        val
                    },
                    None,
                );
            }
            with_runtime(
                |rt: &mut ReactiveRuntime| {
                    let (compute, prev_value): (MemoComputeFn, SignalSlot) = {
                        let entry: &mut MemoEntry = rt.get_mut_memos().get_mut(idx)?;
                        if entry.get_generation() != slot.get_generation() {
                            return None;
                        }
                        let compute: MemoComputeFn = entry.compute.clone()?;
                        let prev_value: SignalSlot = entry.get_mut_value().take();
                        (compute, prev_value)
                    };
                    if !rt.begin_tracking(SubscriberId::Memo(id)) {
                        if let Some(entry) = rt.get_mut_memos().get_mut(idx) {
                            entry.set_value(prev_value);
                        }
                        return None;
                    }
                    Some((compute, prev_value))
                },
                None,
            )?
        }
    };
    let mut guard: TrackingGuard = TrackingGuard::new();
    let eval_result: Option<bool> = match compute.try_borrow_mut() {
        Ok(mut func) => Some(func(&mut value_slot)),
        Err(_) => None,
    };
    guard.disarm();
    match eval_result {
        Some(changed) => with_runtime(
            |rt: &mut ReactiveRuntime| {
                rt.finish_tracking();
                let out_val: Option<T> = value_slot.downcast_ref::<T>().cloned();
                let (alive, target): (bool, DirtyTarget) =
                    if let Some(entry) = rt.get_mut_memos().get_mut(idx) {
                        if entry.get_generation() != slot.get_generation() {
                            (false, DirtyTarget::Empty)
                        } else {
                            entry.set_value(value_slot);
                            entry.set_state(NodeState::Clean);
                            if changed {
                                let next_ver: u64 = entry.get_version().wrapping_add(1);
                                entry.set_version(next_ver);
                                let sub_head: u32 = entry.get_sub_head();
                                (true, rt.dirty_target_from_head(sub_head))
                            } else {
                                (true, DirtyTarget::Empty)
                            }
                        }
                    } else {
                        (false, DirtyTarget::Empty)
                    };
                if !alive {
                    return None;
                }
                if !matches!(target, DirtyTarget::Empty) {
                    rt.propagate_memo_dirty(idx, target);
                }
                rt.track_dependency(DependencyId::Memo(id));
                out_val
            },
            None,
        ),
        None => with_runtime(
            |rt: &mut ReactiveRuntime| {
                rt.abort_tracking();
                let out_val: Option<T> = value_slot.downcast_ref::<T>().cloned();
                let alive: bool = if let Some(entry) = rt.get_mut_memos().get_mut(idx)
                    && entry.get_generation() == slot.get_generation()
                {
                    entry.set_value(value_slot);
                    true
                } else {
                    false
                };
                if !alive {
                    return None;
                }
                rt.track_dependency(DependencyId::Memo(id));
                out_val
            },
            None,
        ),
    }
}

/// Evaluates a memo if dirty or check-marked, updating its cached SBO slot outside any `RefCell` borrow.
///
/// # Arguments
///
/// - `MemoId` - Memo identifier to refresh.
///
/// # Returns
///
/// - `bool` - True when the memo value changed during recomputation.
pub(crate) fn evaluate_memo(id: MemoId) -> bool {
    let slot: SlotId = id.slot();
    let idx: usize = slot.as_usize();
    let prep: MemoEvalPrep = with_runtime(
        |rt: &mut ReactiveRuntime| {
            let state: NodeState = {
                let Some(entry) = rt.get_memos().get(idx) else {
                    return MemoEvalPrep::Clean;
                };
                if entry.get_generation() != slot.get_generation() || entry.compute.is_none() {
                    return MemoEvalPrep::Clean;
                }
                entry.get_state()
            };
            match state {
                NodeState::Clean => MemoEvalPrep::Clean,
                NodeState::Dirty => {
                    let (compute, prev_value): (MemoComputeFn, SignalSlot) = {
                        let entry: &mut MemoEntry = &mut rt.get_mut_memos()[idx];
                        let Some(compute) = entry.compute.clone() else {
                            return MemoEvalPrep::Clean;
                        };
                        let prev_value: SignalSlot = entry.get_mut_value().take();
                        (compute, prev_value)
                    };
                    if !rt.begin_tracking(SubscriberId::Memo(id)) {
                        rt.get_mut_memos()[idx].set_value(prev_value);
                        return MemoEvalPrep::Clean;
                    }
                    MemoEvalPrep::Compute(compute, prev_value)
                }
                NodeState::Check => {
                    if let Some(check_deps) = rt.collect_check_memos(idx) {
                        MemoEvalPrep::Check(check_deps)
                    } else {
                        rt.get_mut_memos()[idx].set_state(NodeState::Clean);
                        MemoEvalPrep::Clean
                    }
                }
            }
        },
        MemoEvalPrep::Clean,
    );
    let (compute, mut value_slot): (MemoComputeFn, SignalSlot) = match prep {
        MemoEvalPrep::Clean => return false,
        MemoEvalPrep::Compute(compute, prev_value) => (compute, prev_value),
        MemoEvalPrep::Check(deps) => {
            if !verify_check_memos(deps) {
                with_runtime(
                    |rt: &mut ReactiveRuntime| {
                        if let Some(entry) = rt.get_mut_memos().get_mut(idx)
                            && entry.get_generation() == slot.get_generation()
                        {
                            entry.set_state(NodeState::Clean);
                        }
                    },
                    (),
                );
                return false;
            }
            let Some(staged_memo) = with_runtime(
                |rt: &mut ReactiveRuntime| {
                    let (compute, prev_value): (MemoComputeFn, SignalSlot) = {
                        let entry: &mut MemoEntry = rt.get_mut_memos().get_mut(idx)?;
                        if entry.get_generation() != slot.get_generation() {
                            return None;
                        }
                        let compute: MemoComputeFn = entry.compute.clone()?;
                        let prev_value: SignalSlot = entry.get_mut_value().take();
                        (compute, prev_value)
                    };
                    if !rt.begin_tracking(SubscriberId::Memo(id)) {
                        if let Some(entry) = rt.get_mut_memos().get_mut(idx) {
                            entry.set_value(prev_value);
                        }
                        return None;
                    }
                    Some((compute, prev_value))
                },
                None,
            ) else {
                return false;
            };
            staged_memo
        }
    };
    let mut guard: TrackingGuard = TrackingGuard::new();
    let changed: bool = match compute.try_borrow_mut() {
        Ok(mut func) => func(&mut value_slot),
        Err(_) => {
            guard.disarm();
            with_runtime(
                |rt: &mut ReactiveRuntime| {
                    rt.abort_tracking();
                    if let Some(entry) = rt.get_mut_memos().get_mut(idx)
                        && entry.get_generation() == slot.get_generation()
                    {
                        entry.set_value(value_slot);
                    }
                },
                (),
            );
            return false;
        }
    };
    guard.disarm();
    with_runtime(
        |rt: &mut ReactiveRuntime| {
            rt.finish_tracking();
            let target: DirtyTarget = if let Some(entry) = rt.get_mut_memos().get_mut(idx) {
                if entry.get_generation() != slot.get_generation() {
                    return;
                }
                entry.set_value(value_slot);
                entry.set_state(NodeState::Clean);
                if changed {
                    let next_ver: u64 = entry.get_version().wrapping_add(1);
                    entry.set_version(next_ver);
                    let sub_head: u32 = entry.get_sub_head();
                    rt.dirty_target_from_head(sub_head)
                } else {
                    DirtyTarget::Empty
                }
            } else {
                DirtyTarget::Empty
            };
            if !matches!(target, DirtyTarget::Empty) {
                rt.propagate_memo_dirty(idx, target);
            }
        },
        (),
    );
    changed
}

/// Runs a single effect outside any `RefCell` borrow while tracking its dependencies via epoch mark-and-sweep.
///
/// # Arguments
///
/// - `EffectId` - Effect identifier to execute.
pub(crate) fn run_effect(id: EffectId) {
    let slot: SlotId = id.slot();
    let callback_opt: Option<Rc<RefCell<dyn FnMut()>>> = with_runtime(
        |rt: &mut ReactiveRuntime| {
            let cb: Rc<RefCell<dyn FnMut()>> = {
                let entry: &mut EffectEntry = rt.get_mut_effects().get_mut(slot.as_usize())?;
                if entry.get_generation() != slot.get_generation() || !entry.get_alive() {
                    return None;
                }
                entry.set_scheduled(false);
                entry.callback.clone()?
            };
            if !rt.begin_tracking(SubscriberId::Effect(id)) {
                return None;
            }
            Some(cb)
        },
        None,
    );
    let Some(callback) = callback_opt else {
        return;
    };
    let mut guard: TrackingGuard = TrackingGuard::new();
    let ran: bool = if let Ok(mut func) = callback.try_borrow_mut() {
        func();
        true
    } else {
        false
    };
    guard.disarm();
    with_runtime(
        |rt: &mut ReactiveRuntime| {
            if ran {
                rt.finish_tracking();
            } else {
                rt.abort_tracking();
            }
        },
        (),
    );
}

/// Flushes all pending reactive effects in topological depth order when not inside a batch.
pub fn flush_effects() {
    if is_scene_borrowed() {
        defer_effect_flush_while_borrowed();
        return;
    }
    let mut step: FlushStep = with_runtime(
        |rt: &mut ReactiveRuntime| {
            if rt.get_batch_depth() > 0 || rt.get_flushing() || rt.get_pending_effects().is_empty()
            {
                return FlushStep::Done;
            }
            rt.set_flushing(true);
            rt.drain_pending_flush_step(Vec::new())
        },
        FlushStep::Done,
    );
    if matches!(step, FlushStep::Done) {
        return;
    }
    let mut reusable_batch: Vec<(u32, EffectId)> = Vec::new();
    let mut iterations: usize = 0;
    loop {
        match step {
            FlushStep::Done => break,
            FlushStep::Single(eff_id) => {
                run_effect(eff_id);
            }
            FlushStep::Batch(mut batch, is_sorted) => {
                if !is_sorted {
                    batch.sort_by_key(|pair: &(u32, EffectId)| pair.0);
                }
                for (_, eff_id) in batch.drain(..) {
                    run_effect(eff_id);
                }
                reusable_batch = batch;
            }
        }
        iterations += 1;
        if iterations >= MAX_FLUSH_ITERATIONS {
            with_runtime(
                |rt: &mut ReactiveRuntime| {
                    if reusable_batch.capacity() > rt.get_flush_batch_scratch().capacity() {
                        rt.set_flush_batch_scratch(reusable_batch);
                    }
                    rt.set_flushing(false);
                },
                (),
            );
            break;
        }
        let passed_batch: Vec<(u32, EffectId)> = take(&mut reusable_batch);
        step = with_runtime(
            |rt: &mut ReactiveRuntime| rt.drain_pending_flush_step(passed_batch),
            FlushStep::Done,
        );
    }
}

/// Coalesces multiple signal writes inside `operation` into a single reactive flush pass.
///
/// # Arguments
///
/// - `F` - Closure executing reactive writes.
///
/// # Returns
///
/// - `R` - Value returned by `operation`.
pub fn batch<F, R>(operation: F) -> R
where
    F: FnOnce() -> R,
{
    with_runtime(
        |rt: &mut ReactiveRuntime| {
            let next_depth: u32 = rt.get_batch_depth().saturating_add(1);
            rt.set_batch_depth(next_depth);
        },
        (),
    );
    let result: R = operation();
    let should_flush: bool = with_runtime(
        |rt: &mut ReactiveRuntime| {
            let next_depth: u32 = rt.get_batch_depth().saturating_sub(1);
            rt.set_batch_depth(next_depth);
            next_depth == 0
        },
        false,
    );
    if should_flush {
        flush_effects();
    }
    result
}

/// Executes `operation` without tracking any reactive signal or memo reads (panic-safe and nested-`with_ref` safe).
///
/// # Arguments
///
/// - `F` - Closure whose reactive reads should remain untracked.
///
/// # Returns
///
/// - `R` - Value returned by `operation`.
pub fn untracked<F, R>(operation: F) -> R
where
    F: FnOnce() -> R,
{
    let _guard: UntrackedGuard = UntrackedGuard::enter();
    operation()
}

/// Registers a cleanup callback on the currently active reactive scope.
///
/// # Arguments
///
/// - `F` - Cleanup callback executed once when the active scope disposes.
pub fn on_cleanup<F>(cleanup: F)
where
    F: FnOnce() + 'static,
{
    with_runtime(
        |rt: &mut ReactiveRuntime| {
            rt.register_cleanup(cleanup);
        },
        (),
    );
}

/// Returns diagnostic statistics for the current thread's reactive runtime.
///
/// # Returns
///
/// - `ReactiveStats` - Snapshot of live signals, memos, effects, scopes, and clock.
#[must_use]
pub fn reactive_stats() -> ReactiveStats {
    with_runtime_ref(|rt: &ReactiveRuntime| rt.stats(), ReactiveStats::default())
}

/// Returns edge slab and arena capacity metrics for the current thread's reactive runtime.
///
/// # Returns
///
/// - `ReactiveGraphMetrics` - Snapshot of live edge count, total edge allocations, and arena capacities.
#[must_use]
pub fn reactive_graph_metrics() -> ReactiveGraphMetrics {
    with_runtime_ref(
        |rt: &ReactiveRuntime| rt.graph_metrics(),
        ReactiveGraphMetrics::default(),
    )
}

/// Returns the active per-thread reactive runtime epoch incremented on every `reset_reactive_runtime`.
///
/// # Returns
///
/// - `u64` - Active monotonic runtime epoch (`0` if thread-local storage is tearing down).
#[inline]
#[must_use]
pub(crate) fn current_runtime_epoch() -> u64 {
    RUNTIME_EPOCH.try_with(Cell::get).unwrap_or(0)
}

/// Resets the current thread's reactive runtime to an empty slim cold-start state.
pub fn reset_reactive_runtime() {
    let _: Result<(), _> = RUNTIME_EPOCH.try_with(|epoch: &Cell<u64>| {
        let next: u64 = epoch.get().wrapping_add(1).max(1);
        epoch.set(next);
    });
    reset_system_event_hub();
    reset_scene_borrow_state();
    let _: bool = set_tracking_active(false);
    let _: Result<(), _> = REF_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
        depth.set(0);
    });
    let _: Result<(), _> = PENDING_REF_TRACKS.try_with(|cell: &RefCell<Vec<DependencyId>>| {
        if let Ok(mut pending) = cell.try_borrow_mut() {
            pending.clear();
        }
    });
    with_runtime(
        |rt: &mut ReactiveRuntime| {
            *rt = ReactiveRuntime::default();
        },
        (),
    );
}