Skip to main content

euv_core/reactive/runtime/
fn.rs

1use super::*;
2
3/// Encodes a signal arena index as a packed source edge tag (`bit 31 = 0`).
4///
5/// # Arguments
6///
7/// - `u32` - Zero-based signal slot index.
8///
9/// # Returns
10///
11/// - `u32` - Packed source tag identifying the signal.
12#[must_use]
13#[inline(always)]
14pub(crate) const fn encode_signal_source_tag(index: u32) -> u32 {
15    index & EDGE_INDEX_MASK
16}
17
18/// Encodes a memo arena index as a packed source edge tag (`bit 31 = 1`).
19///
20/// # Arguments
21///
22/// - `u32` - Zero-based memo slot index.
23///
24/// # Returns
25///
26/// - `u32` - Packed source tag identifying the memo.
27#[must_use]
28#[inline(always)]
29pub(crate) const fn encode_memo_source_tag(index: u32) -> u32 {
30    (index & EDGE_INDEX_MASK) | EDGE_KIND_BIT
31}
32
33/// Returns `true` when a packed source edge tag refers to a memo rather than a signal.
34///
35/// # Arguments
36///
37/// - `u32` - Packed source edge tag.
38///
39/// # Returns
40///
41/// - `bool` - `true` for memo sources, `false` for signal sources.
42#[must_use]
43#[inline(always)]
44pub(crate) const fn is_memo_source_tag(tag: u32) -> bool {
45    (tag & EDGE_KIND_BIT) != 0
46}
47
48/// Encodes a memo arena index as a packed subscriber edge tag (`bit 31 = 0`).
49///
50/// # Arguments
51///
52/// - `u32` - Zero-based memo slot index.
53///
54/// # Returns
55///
56/// - `u32` - Packed subscriber tag identifying the memo.
57#[must_use]
58#[inline(always)]
59pub(crate) const fn encode_memo_sub_tag(index: u32) -> u32 {
60    index & EDGE_INDEX_MASK
61}
62
63/// Encodes an effect arena index as a packed subscriber edge tag (`bit 31 = 1`).
64///
65/// # Arguments
66///
67/// - `u32` - Zero-based effect slot index.
68///
69/// # Returns
70///
71/// - `u32` - Packed subscriber tag identifying the effect.
72#[must_use]
73#[inline(always)]
74pub(crate) const fn encode_effect_sub_tag(index: u32) -> u32 {
75    (index & EDGE_INDEX_MASK) | EDGE_KIND_BIT
76}
77
78/// Returns `true` when a packed subscriber edge tag refers to an effect rather than a memo.
79///
80/// # Arguments
81///
82/// - `u32` - Packed subscriber edge tag.
83///
84/// # Returns
85///
86/// - `bool` - `true` for effect subscribers, `false` for memo subscribers.
87#[must_use]
88#[inline(always)]
89pub(crate) const fn is_effect_sub_tag(tag: u32) -> bool {
90    (tag & EDGE_KIND_BIT) != 0
91}
92
93/// Extracts the zero-based arena slot index from a packed source or subscriber tag.
94///
95/// # Arguments
96///
97/// - `u32` - Packed source or subscriber tag.
98///
99/// # Returns
100///
101/// - `usize` - Zero-based arena slot index.
102#[must_use]
103#[inline(always)]
104pub(crate) const fn decode_edge_tag_index(tag: u32) -> usize {
105    (tag & EDGE_INDEX_MASK) as usize
106}
107
108/// Combines `(source_tag, sub_tag)` into a compact 64-bit key for `ReactiveRuntime::edge_index`.
109///
110/// # Arguments
111///
112/// - `u32` - Packed source tag.
113/// - `u32` - Packed subscriber tag.
114///
115/// # Returns
116///
117/// - `u64` - Unique composite lookup key.
118#[must_use]
119#[inline(always)]
120pub(crate) const fn edge_index_key(source_tag: u32, sub_tag: u32) -> u64 {
121    ((source_tag as u64) << 32) | (sub_tag as u64)
122}
123
124/// Returns whether the thread-local reactive runtime currently has an active tracking observer frame.
125///
126/// # Returns
127///
128/// - `bool` - `true` when reactive reads should record dependencies.
129#[must_use]
130#[inline(always)]
131pub(crate) fn is_tracking_active() -> bool {
132    TRACKING_ACTIVE
133        .try_with(|flag: &Cell<bool>| flag.get())
134        .unwrap_or(false)
135}
136
137/// Updates the fast-path `TRACKING_ACTIVE` thread-local flag and returns its previous value.
138///
139/// # Arguments
140///
141/// - `bool` - New active tracking state.
142///
143/// # Returns
144///
145/// - `bool` - Previous active tracking state.
146#[inline(always)]
147pub(crate) fn set_tracking_active(active: bool) -> bool {
148    TRACKING_ACTIVE
149        .try_with(|flag: &Cell<bool>| flag.replace(active))
150        .unwrap_or(false)
151}
152
153/// Returns the current nesting depth of active shared `RefCell::try_borrow()` signal reads.
154///
155/// # Returns
156///
157/// - `u32` - Current shared borrow nesting depth (`0` when no `with_ref` borrow is active).
158#[must_use]
159#[inline(always)]
160pub(crate) fn ref_borrow_depth() -> u32 {
161    REF_BORROW_DEPTH
162        .try_with(|depth: &Cell<u32>| depth.get())
163        .unwrap_or(0)
164}
165
166/// Records `dependency` immediately when unborrowed, or queues it in `PENDING_REF_TRACKS` while inside a nested `with_ref` borrow.
167///
168/// # Arguments
169///
170/// - `DependencyId` - Reactive source read by the active observer.
171#[inline]
172pub(crate) fn track_or_defer_dependency(dependency: DependencyId) {
173    if !is_tracking_active() {
174        return;
175    }
176    if ref_borrow_depth() == 0 {
177        with_runtime(
178            |runtime_ref: &mut ReactiveRuntime| {
179                runtime_ref.track_dependency(dependency);
180            },
181            (),
182        );
183        return;
184    }
185    let _: Result<(), _> = PENDING_REF_TRACKS.try_with(|cell: &RefCell<Vec<DependencyId>>| {
186        if let Ok(mut pending) = cell.try_borrow_mut() {
187            pending.push(dependency);
188        }
189    });
190}
191
192/// Flushes any deferred dependency reads recorded during nested `with_ref` calls once the outermost shared borrow releases.
193#[inline]
194pub(crate) fn flush_pending_ref_tracks() {
195    let mut staged: Vec<DependencyId> = PENDING_REF_TRACKS
196        .try_with(|cell: &RefCell<Vec<DependencyId>>| {
197            let is_empty: bool = cell
198                .try_borrow()
199                .map(|guard: Ref<'_, Vec<DependencyId>>| guard.is_empty())
200                .unwrap_or(true);
201            if is_empty {
202                return Vec::new();
203            }
204            match cell.try_borrow_mut() {
205                Ok(mut guard) => take(&mut *guard),
206                Err(_) => Vec::new(),
207            }
208        })
209        .unwrap_or_default();
210    if staged.is_empty() {
211        return;
212    }
213    if is_tracking_active() {
214        with_runtime(
215            |runtime_ref: &mut ReactiveRuntime| {
216                for dep in staged.drain(..) {
217                    runtime_ref.track_dependency(dep);
218                }
219            },
220            (),
221        );
222    } else {
223        staged.clear();
224    }
225    let _: Result<(), _> = PENDING_REF_TRACKS.try_with(|cell: &RefCell<Vec<DependencyId>>| {
226        if let Ok(mut guard) = cell.try_borrow_mut()
227            && guard.is_empty()
228            && staged.capacity() > guard.capacity()
229        {
230            *guard = staged;
231        }
232    });
233}
234
235/// Executes a closure with mutable access to the thread-local reactive runtime.
236///
237/// # Arguments
238///
239/// - `CallbackFn` - Closure receiving `&mut ReactiveRuntime`.
240/// - `ReturnValue` - Fallback return value used if the runtime cannot be borrowed.
241///
242/// # Returns
243///
244/// - `ReturnValue` - Closure result or fallback value.
245#[inline(always)]
246pub(crate) fn with_runtime<CallbackFn, ReturnValue>(
247    operation: CallbackFn,
248    fallback: ReturnValue,
249) -> ReturnValue
250where
251    CallbackFn: FnOnce(&mut ReactiveRuntime) -> ReturnValue,
252{
253    REACTIVE_RUNTIME
254        .try_with(
255            |cell: &RefCell<ReactiveRuntime>| match cell.try_borrow_mut() {
256                Ok(mut guard) => Some(operation(&mut guard)),
257                Err(_) => None,
258            },
259        )
260        .ok()
261        .flatten()
262        .unwrap_or(fallback)
263}
264
265/// Executes a read-only closure with shared `RefCell::try_borrow()` access to the thread-local reactive runtime.
266///
267/// # Arguments
268///
269/// - `CallbackFn` - Read-only closure receiving `&ReactiveRuntime`.
270/// - `ReturnValue` - Fallback return value used if the runtime is mutably borrowed.
271///
272/// # Returns
273///
274/// - `ReturnValue` - Closure result or fallback value.
275#[inline(always)]
276pub(crate) fn with_runtime_ref<CallbackFn, ReturnValue>(
277    operation: CallbackFn,
278    fallback: ReturnValue,
279) -> ReturnValue
280where
281    CallbackFn: FnOnce(&ReactiveRuntime) -> ReturnValue,
282{
283    REACTIVE_RUNTIME
284        .try_with(|cell: &RefCell<ReactiveRuntime>| match cell.try_borrow() {
285            Ok(guard) => Some(operation(&guard)),
286            Err(_) => None,
287        })
288        .ok()
289        .flatten()
290        .unwrap_or(fallback)
291}
292
293/// Borrows a signal's stored `&T` directly via shared `RefCell::try_borrow()` without cloning, supporting nested read-only borrows.
294///
295/// # Arguments
296///
297/// - `SignalId` - Signal identifier to borrow.
298/// - `bool` - Whether to record dependency tracking on the active observer.
299/// - `CallbackFn` - Read-only closure invoked with `&T`.
300///
301/// # Returns
302///
303/// - `Option<ReturnValue>` - Closure result when the signal is alive, matches `T`, and the runtime is not mutably borrowed.
304#[inline]
305pub(crate) fn read_signal_with_ref<ValueType, CallbackFn, ReturnValue>(
306    id: SignalId,
307    tracked: bool,
308    reader: CallbackFn,
309) -> Option<ReturnValue>
310where
311    ValueType: 'static,
312    CallbackFn: FnOnce(&ValueType) -> ReturnValue,
313{
314    if tracked {
315        track_or_defer_dependency(DependencyId::Signal(id));
316    }
317    let _ref_guard: RefBorrowGuard = RefBorrowGuard::enter();
318    let slot: SlotId = id.slot();
319    REACTIVE_RUNTIME
320        .try_with(|cell: &RefCell<ReactiveRuntime>| {
321            let guard: Ref<'_, ReactiveRuntime> = cell.try_borrow().ok()?;
322            let entry: &SignalEntry = guard.get_signals().get(slot.as_usize())?;
323            if entry.get_generation() != slot.get_generation() {
324                return None;
325            }
326            let value: &ValueType = entry.get_value().downcast_ref::<ValueType>()?;
327            Some(reader(value))
328        })
329        .ok()
330        .flatten()
331}
332
333/// Borrows a memo's cached `&T` directly via shared `RefCell::try_borrow()` without cloning, evaluating lazily first when unborrowed.
334///
335/// # Arguments
336///
337/// - `MemoId` - Memo identifier to borrow.
338/// - `ReaderFn` - Read-only closure invoked with `&T`.
339///
340/// # Returns
341///
342/// - `Option<ReturnValue>` - Closure result when the memo is alive, clean, and matches `T`.
343#[inline]
344pub(crate) fn read_memo_with_ref<ValueType, ReaderFn, ReturnValue>(
345    id: MemoId,
346    reader: ReaderFn,
347) -> Option<ReturnValue>
348where
349    ValueType: 'static,
350    ReaderFn: FnOnce(&ValueType) -> ReturnValue,
351{
352    if ref_borrow_depth() == 0 {
353        let needs_eval: bool = with_runtime_ref(
354            |runtime_ref: &ReactiveRuntime| {
355                let slot: SlotId = id.slot();
356                runtime_ref
357                    .get_memos()
358                    .get(slot.as_usize())
359                    .is_some_and(|entry: &MemoEntry| {
360                        entry.get_generation() == slot.get_generation()
361                            && entry.compute.is_some()
362                            && entry.get_state() != NodeState::Clean
363                    })
364            },
365            false,
366        );
367        if needs_eval {
368            let _: bool = evaluate_memo(id);
369        }
370    }
371    track_or_defer_dependency(DependencyId::Memo(id));
372    let _ref_guard: RefBorrowGuard = RefBorrowGuard::enter();
373    let slot: SlotId = id.slot();
374    REACTIVE_RUNTIME
375        .try_with(|cell: &RefCell<ReactiveRuntime>| {
376            let guard: Ref<'_, ReactiveRuntime> = cell.try_borrow().ok()?;
377            let entry: &MemoEntry = guard.get_memos().get(slot.as_usize())?;
378            if entry.get_generation() != slot.get_generation()
379                || entry.get_state() != NodeState::Clean
380            {
381                return None;
382            }
383            let value: &ValueType = entry.get_value().downcast_ref::<ValueType>()?;
384            Some(reader(value))
385        })
386        .ok()
387        .flatten()
388}
389
390/// Pull-verifies upstream `MemoId` dependencies for a `NodeState::Check` memo, short-circuiting on the first change.
391///
392/// # Arguments
393///
394/// - `MemoCheckDeps` - Zero-allocation inline or cursor-sliced upstream memo dependency snapshot.
395///
396/// # Returns
397///
398/// - `bool` - `true` as soon as any upstream memo recomputes to a changed value.
399fn verify_check_memos(deps: MemoCheckDeps) -> bool {
400    match deps {
401        MemoCheckDeps::Inline(buf, count) => {
402            let len: usize = count as usize;
403            for parent_memo in buf.iter().copied().take(len) {
404                if evaluate_memo(parent_memo) {
405                    return true;
406                }
407            }
408            false
409        }
410        MemoCheckDeps::Spill(start, end) => {
411            let mut changed: bool = false;
412            let mut cursor: usize = start;
413            while cursor < end {
414                let parent_opt: Option<MemoId> = with_runtime_ref(
415                    |runtime_ref: &ReactiveRuntime| {
416                        runtime_ref.get_check_scratch().get(cursor).copied()
417                    },
418                    None,
419                );
420                if let Some(parent_memo) = parent_opt
421                    && evaluate_memo(parent_memo)
422                {
423                    changed = true;
424                    break;
425                }
426                cursor += 1;
427            }
428            with_runtime(
429                |render_target: &mut ReactiveRuntime| {
430                    render_target.get_mut_check_scratch().truncate(start);
431                },
432                (),
433            );
434            changed
435        }
436    }
437}
438
439/// Reads a typed `Memo<T>` using fused runtime borrows (1 borrow on `Clean`, 2 borrows on `Dirty` or unchanged `Check`).
440///
441/// # Arguments
442///
443/// - `MemoId` - Target memo identifier to read and track.
444///
445/// # Returns
446///
447/// - `Option<ValueType>` - Current computed value if alive and matching type `T`.
448#[must_use]
449pub(crate) fn read_memo_fused<ValueType>(id: MemoId) -> Option<ValueType>
450where
451    ValueType: Clone + 'static,
452{
453    if ref_borrow_depth() > 0 {
454        return read_memo_with_ref::<ValueType, _, ValueType>(id, |val: &ValueType| val.clone());
455    }
456    let slot: SlotId = id.slot();
457    let idx: usize = slot.as_usize();
458    let prep: MemoReadPrep<ValueType> = with_runtime(
459        |runtime_ref: &mut ReactiveRuntime| {
460            let state: NodeState = {
461                let Some(entry) = runtime_ref.get_memos().get(idx) else {
462                    return MemoReadPrep::Dead;
463                };
464                if entry.get_generation() != slot.get_generation() {
465                    return MemoReadPrep::Dead;
466                }
467                entry.get_state()
468            };
469            match state {
470                NodeState::Clean => {
471                    let val: Option<ValueType> = runtime_ref.get_memos()[idx]
472                        .get_value()
473                        .downcast_ref::<ValueType>()
474                        .cloned();
475                    runtime_ref.track_dependency(DependencyId::Memo(id));
476                    MemoReadPrep::Ready(val)
477                }
478                NodeState::Dirty => {
479                    let (compute, prev_value): (MemoComputeFn, SignalSlot) = {
480                        let entry: &mut MemoEntry = &mut runtime_ref.get_mut_memos()[idx];
481                        let Some(compute) = entry.compute.clone() else {
482                            return MemoReadPrep::Dead;
483                        };
484                        let prev_value: SignalSlot = entry.get_mut_value().take();
485                        (compute, prev_value)
486                    };
487                    if !runtime_ref.begin_tracking(SubscriberId::Memo(id)) {
488                        runtime_ref.get_mut_memos()[idx].set_value(prev_value);
489                        return MemoReadPrep::Dead;
490                    }
491                    MemoReadPrep::Compute(compute, prev_value)
492                }
493                NodeState::Check => {
494                    if runtime_ref.get_memos()[idx].compute.is_none() {
495                        return MemoReadPrep::Dead;
496                    }
497                    if let Some(check_deps) = runtime_ref.collect_check_memos(idx) {
498                        MemoReadPrep::Check(check_deps)
499                    } else {
500                        let entry: &mut MemoEntry = &mut runtime_ref.get_mut_memos()[idx];
501                        entry.set_state(NodeState::Clean);
502                        let val: Option<ValueType> =
503                            entry.get_value().downcast_ref::<ValueType>().cloned();
504                        runtime_ref.track_dependency(DependencyId::Memo(id));
505                        MemoReadPrep::Ready(val)
506                    }
507                }
508            }
509        },
510        MemoReadPrep::Dead,
511    );
512    let (compute, mut value_slot): (MemoComputeFn, SignalSlot) = match prep {
513        MemoReadPrep::Dead => return None,
514        MemoReadPrep::Ready(val) => return val,
515        MemoReadPrep::Compute(compute, prev_value) => (compute, prev_value),
516        MemoReadPrep::Check(deps) => {
517            if !verify_check_memos(deps) {
518                return with_runtime(
519                    |render_target: &mut ReactiveRuntime| {
520                        let entry: &mut MemoEntry = render_target.get_mut_memos().get_mut(idx)?;
521                        if entry.get_generation() != slot.get_generation() {
522                            return None;
523                        }
524                        entry.set_state(NodeState::Clean);
525                        let val: Option<ValueType> =
526                            entry.get_value().downcast_ref::<ValueType>().cloned();
527                        render_target.track_dependency(DependencyId::Memo(id));
528                        val
529                    },
530                    None,
531                );
532            }
533            with_runtime(
534                |raytrace_val: &mut ReactiveRuntime| {
535                    let (compute, prev_value): (MemoComputeFn, SignalSlot) = {
536                        let entry: &mut MemoEntry = raytrace_val.get_mut_memos().get_mut(idx)?;
537                        if entry.get_generation() != slot.get_generation() {
538                            return None;
539                        }
540                        let compute: MemoComputeFn = entry.compute.clone()?;
541                        let prev_value: SignalSlot = entry.get_mut_value().take();
542                        (compute, prev_value)
543                    };
544                    if !raytrace_val.begin_tracking(SubscriberId::Memo(id)) {
545                        if let Some(entry) = raytrace_val.get_mut_memos().get_mut(idx) {
546                            entry.set_value(prev_value);
547                        }
548                        return None;
549                    }
550                    Some((compute, prev_value))
551                },
552                None,
553            )?
554        }
555    };
556    let mut guard: TrackingGuard = TrackingGuard::new();
557    let eval_result: Option<bool> = match compute.try_borrow_mut() {
558        Ok(mut func) => Some(func(&mut value_slot)),
559        Err(_) => None,
560    };
561    guard.disarm();
562    match eval_result {
563        Some(changed) => with_runtime(
564            |runtime_ref_primary: &mut ReactiveRuntime| {
565                runtime_ref_primary.finish_tracking();
566                let out_val: Option<ValueType> = value_slot.downcast_ref::<ValueType>().cloned();
567                let (alive, target): (bool, DirtyTarget) =
568                    if let Some(entry) = runtime_ref_primary.get_mut_memos().get_mut(idx) {
569                        if entry.get_generation() != slot.get_generation() {
570                            (false, DirtyTarget::Empty)
571                        } else {
572                            entry.set_value(value_slot);
573                            entry.set_state(NodeState::Clean);
574                            if changed {
575                                let next_ver: u64 = entry.get_version().wrapping_add(1);
576                                entry.set_version(next_ver);
577                                let sub_head: u32 = entry.get_sub_head();
578                                (true, runtime_ref_primary.dirty_target_from_head(sub_head))
579                            } else {
580                                (true, DirtyTarget::Empty)
581                            }
582                        }
583                    } else {
584                        (false, DirtyTarget::Empty)
585                    };
586                if !alive {
587                    return None;
588                }
589                if !matches!(target, DirtyTarget::Empty) {
590                    runtime_ref_primary.propagate_memo_dirty(idx, target);
591                }
592                runtime_ref_primary.track_dependency(DependencyId::Memo(id));
593                out_val
594            },
595            None,
596        ),
597        None => with_runtime(
598            |runtime_ref_secondary: &mut ReactiveRuntime| {
599                runtime_ref_secondary.abort_tracking();
600                let out_val: Option<ValueType> = value_slot.downcast_ref::<ValueType>().cloned();
601                let alive: bool = if let Some(entry) =
602                    runtime_ref_secondary.get_mut_memos().get_mut(idx)
603                    && entry.get_generation() == slot.get_generation()
604                {
605                    entry.set_value(value_slot);
606                    true
607                } else {
608                    false
609                };
610                if !alive {
611                    return None;
612                }
613                runtime_ref_secondary.track_dependency(DependencyId::Memo(id));
614                out_val
615            },
616            None,
617        ),
618    }
619}
620
621/// Evaluates a memo if dirty or check-marked, updating its cached SBO slot outside any `RefCell` borrow.
622///
623/// # Arguments
624///
625/// - `MemoId` - Memo identifier to refresh.
626///
627/// # Returns
628///
629/// - `bool` - True when the memo value changed during recomputation.
630pub(crate) fn evaluate_memo(id: MemoId) -> bool {
631    let slot: SlotId = id.slot();
632    let idx: usize = slot.as_usize();
633    let prep: MemoEvalPrep = with_runtime(
634        |runtime_ref: &mut ReactiveRuntime| {
635            let state: NodeState = {
636                let Some(entry) = runtime_ref.get_memos().get(idx) else {
637                    return MemoEvalPrep::Clean;
638                };
639                if entry.get_generation() != slot.get_generation() || entry.compute.is_none() {
640                    return MemoEvalPrep::Clean;
641                }
642                entry.get_state()
643            };
644            match state {
645                NodeState::Clean => MemoEvalPrep::Clean,
646                NodeState::Dirty => {
647                    let (compute, prev_value): (MemoComputeFn, SignalSlot) = {
648                        let entry: &mut MemoEntry = &mut runtime_ref.get_mut_memos()[idx];
649                        let Some(compute) = entry.compute.clone() else {
650                            return MemoEvalPrep::Clean;
651                        };
652                        let prev_value: SignalSlot = entry.get_mut_value().take();
653                        (compute, prev_value)
654                    };
655                    if !runtime_ref.begin_tracking(SubscriberId::Memo(id)) {
656                        runtime_ref.get_mut_memos()[idx].set_value(prev_value);
657                        return MemoEvalPrep::Clean;
658                    }
659                    MemoEvalPrep::Compute(compute, prev_value)
660                }
661                NodeState::Check => {
662                    if let Some(check_deps) = runtime_ref.collect_check_memos(idx) {
663                        MemoEvalPrep::Check(check_deps)
664                    } else {
665                        runtime_ref.get_mut_memos()[idx].set_state(NodeState::Clean);
666                        MemoEvalPrep::Clean
667                    }
668                }
669            }
670        },
671        MemoEvalPrep::Clean,
672    );
673    let (compute, mut value_slot): (MemoComputeFn, SignalSlot) = match prep {
674        MemoEvalPrep::Clean => return false,
675        MemoEvalPrep::Compute(compute, prev_value) => (compute, prev_value),
676        MemoEvalPrep::Check(deps) => {
677            if !verify_check_memos(deps) {
678                with_runtime(
679                    |render_target: &mut ReactiveRuntime| {
680                        if let Some(entry) = render_target.get_mut_memos().get_mut(idx)
681                            && entry.get_generation() == slot.get_generation()
682                        {
683                            entry.set_state(NodeState::Clean);
684                        }
685                    },
686                    (),
687                );
688                return false;
689            }
690            let Some(staged_memo) = with_runtime(
691                |raytrace_val: &mut ReactiveRuntime| {
692                    let (compute, prev_value): (MemoComputeFn, SignalSlot) = {
693                        let entry: &mut MemoEntry = raytrace_val.get_mut_memos().get_mut(idx)?;
694                        if entry.get_generation() != slot.get_generation() {
695                            return None;
696                        }
697                        let compute: MemoComputeFn = entry.compute.clone()?;
698                        let prev_value: SignalSlot = entry.get_mut_value().take();
699                        (compute, prev_value)
700                    };
701                    if !raytrace_val.begin_tracking(SubscriberId::Memo(id)) {
702                        if let Some(entry) = raytrace_val.get_mut_memos().get_mut(idx) {
703                            entry.set_value(prev_value);
704                        }
705                        return None;
706                    }
707                    Some((compute, prev_value))
708                },
709                None,
710            ) else {
711                return false;
712            };
713            staged_memo
714        }
715    };
716    let mut guard: TrackingGuard = TrackingGuard::new();
717    let changed: bool = match compute.try_borrow_mut() {
718        Ok(mut func) => func(&mut value_slot),
719        Err(_) => {
720            guard.disarm();
721            with_runtime(
722                |runtime_ref_primary: &mut ReactiveRuntime| {
723                    runtime_ref_primary.abort_tracking();
724                    if let Some(entry) = runtime_ref_primary.get_mut_memos().get_mut(idx)
725                        && entry.get_generation() == slot.get_generation()
726                    {
727                        entry.set_value(value_slot);
728                    }
729                },
730                (),
731            );
732            return false;
733        }
734    };
735    guard.disarm();
736    with_runtime(
737        |runtime_ref_secondary: &mut ReactiveRuntime| {
738            runtime_ref_secondary.finish_tracking();
739            let target: DirtyTarget =
740                if let Some(entry) = runtime_ref_secondary.get_mut_memos().get_mut(idx) {
741                    if entry.get_generation() != slot.get_generation() {
742                        return;
743                    }
744                    entry.set_value(value_slot);
745                    entry.set_state(NodeState::Clean);
746                    if changed {
747                        let next_ver: u64 = entry.get_version().wrapping_add(1);
748                        entry.set_version(next_ver);
749                        let sub_head: u32 = entry.get_sub_head();
750                        runtime_ref_secondary.dirty_target_from_head(sub_head)
751                    } else {
752                        DirtyTarget::Empty
753                    }
754                } else {
755                    DirtyTarget::Empty
756                };
757            if !matches!(target, DirtyTarget::Empty) {
758                runtime_ref_secondary.propagate_memo_dirty(idx, target);
759            }
760        },
761        (),
762    );
763    changed
764}
765
766/// Runs a single effect outside any `RefCell` borrow while tracking its dependencies via epoch mark-and-sweep.
767///
768/// # Arguments
769///
770/// - `EffectId` - Effect identifier to execute.
771pub(crate) fn run_effect(id: EffectId) {
772    let slot: SlotId = id.slot();
773    let callback_opt: Option<Rc<RefCell<dyn FnMut()>>> = with_runtime(
774        |runtime_ref: &mut ReactiveRuntime| {
775            let callback_fn: Rc<RefCell<dyn FnMut()>> = {
776                let entry: &mut EffectEntry =
777                    runtime_ref.get_mut_effects().get_mut(slot.as_usize())?;
778                if entry.get_generation() != slot.get_generation() || !entry.get_alive() {
779                    return None;
780                }
781                entry.set_scheduled(false);
782                entry.callback.clone()?
783            };
784            if !runtime_ref.begin_tracking(SubscriberId::Effect(id)) {
785                return None;
786            }
787            Some(callback_fn)
788        },
789        None,
790    );
791    let Some(callback) = callback_opt else {
792        return;
793    };
794    let mut guard: TrackingGuard = TrackingGuard::new();
795    let ran: bool = if let Ok(mut func) = callback.try_borrow_mut() {
796        func();
797        true
798    } else {
799        false
800    };
801    guard.disarm();
802    with_runtime(
803        |render_target: &mut ReactiveRuntime| {
804            if ran {
805                render_target.finish_tracking();
806            } else {
807                render_target.abort_tracking();
808            }
809        },
810        (),
811    );
812}
813
814/// Flushes all pending reactive effects in topological depth order when not inside a batch.
815pub fn flush_effects() {
816    if is_scene_borrowed() {
817        defer_effect_flush_while_borrowed();
818        return;
819    }
820    let mut step: FlushStep = with_runtime(
821        |runtime_ref: &mut ReactiveRuntime| {
822            if runtime_ref.get_batch_depth() > 0
823                || runtime_ref.get_flushing()
824                || runtime_ref.get_pending_effects().is_empty()
825            {
826                return FlushStep::Done;
827            }
828            runtime_ref.set_flushing(true);
829            runtime_ref.drain_pending_flush_step(Vec::new())
830        },
831        FlushStep::Done,
832    );
833    if matches!(step, FlushStep::Done) {
834        return;
835    }
836    let mut reusable_batch: Vec<(u32, EffectId)> = Vec::new();
837    let mut iterations: usize = 0;
838    loop {
839        match step {
840            FlushStep::Done => break,
841            FlushStep::Single(eff_id) => {
842                run_effect(eff_id);
843            }
844            FlushStep::Batch(mut batch, is_sorted) => {
845                if !is_sorted {
846                    batch.sort_by_key(|pair: &(u32, EffectId)| pair.0);
847                }
848                for (_, eff_id) in batch.drain(..) {
849                    run_effect(eff_id);
850                }
851                reusable_batch = batch;
852            }
853        }
854        iterations += 1;
855        if iterations >= MAX_FLUSH_ITERATIONS {
856            with_runtime(
857                |render_target: &mut ReactiveRuntime| {
858                    if reusable_batch.capacity()
859                        > render_target.get_flush_batch_scratch().capacity()
860                    {
861                        render_target.set_flush_batch_scratch(reusable_batch);
862                    }
863                    render_target.set_flushing(false);
864                },
865                (),
866            );
867            break;
868        }
869        let passed_batch: Vec<(u32, EffectId)> = take(&mut reusable_batch);
870        step = with_runtime(
871            |raytrace_val: &mut ReactiveRuntime| {
872                raytrace_val.drain_pending_flush_step(passed_batch)
873            },
874            FlushStep::Done,
875        );
876    }
877}
878
879/// Coalesces multiple signal writes inside `operation` into a single reactive flush pass.
880///
881/// # Arguments
882///
883/// - `CallbackFn` - Closure executing reactive writes.
884///
885/// # Returns
886///
887/// - `ReturnValue` - Value returned by `operation`.
888pub fn batch<CallbackFn, ReturnValue>(operation: CallbackFn) -> ReturnValue
889where
890    CallbackFn: FnOnce() -> ReturnValue,
891{
892    with_runtime(
893        |runtime_ref: &mut ReactiveRuntime| {
894            let next_depth: u32 = runtime_ref.get_batch_depth().saturating_add(1);
895            runtime_ref.set_batch_depth(next_depth);
896        },
897        (),
898    );
899    let result: ReturnValue = operation();
900    let should_flush: bool = with_runtime(
901        |render_target: &mut ReactiveRuntime| {
902            let next_depth: u32 = render_target.get_batch_depth().saturating_sub(1);
903            render_target.set_batch_depth(next_depth);
904            next_depth == 0
905        },
906        false,
907    );
908    if should_flush {
909        flush_effects();
910    }
911    result
912}
913
914/// Executes `operation` without tracking any reactive signal or memo reads (panic-safe and nested-`with_ref` safe).
915///
916/// # Arguments
917///
918/// - `CallbackFn` - Closure whose reactive reads should remain untracked.
919///
920/// # Returns
921///
922/// - `ReturnValue` - Value returned by `operation`.
923pub fn untracked<CallbackFn, ReturnValue>(operation: CallbackFn) -> ReturnValue
924where
925    CallbackFn: FnOnce() -> ReturnValue,
926{
927    let _guard: UntrackedGuard = UntrackedGuard::enter();
928    operation()
929}
930
931/// Registers a cleanup callback on the currently active reactive scope.
932///
933/// # Arguments
934///
935/// - `CallbackFn` - Cleanup callback executed once when the active scope disposes.
936pub fn on_cleanup<CallbackFn>(cleanup: CallbackFn)
937where
938    CallbackFn: FnOnce() + 'static,
939{
940    with_runtime(
941        |runtime_ref: &mut ReactiveRuntime| {
942            runtime_ref.register_cleanup(cleanup);
943        },
944        (),
945    );
946}
947
948/// Returns diagnostic statistics for the current thread's reactive runtime.
949///
950/// # Returns
951///
952/// - `ReactiveStats` - Snapshot of live signals, memos, effects, scopes, and clock.
953#[must_use]
954pub fn reactive_stats() -> ReactiveStats {
955    with_runtime_ref(
956        |runtime_ref: &ReactiveRuntime| runtime_ref.stats(),
957        ReactiveStats::default(),
958    )
959}
960
961/// Returns edge slab and arena capacity metrics for the current thread's reactive runtime.
962///
963/// # Returns
964///
965/// - `ReactiveGraphMetrics` - Snapshot of live edge count, total edge allocations, and arena capacities.
966#[must_use]
967pub fn reactive_graph_metrics() -> ReactiveGraphMetrics {
968    with_runtime_ref(
969        |runtime_ref: &ReactiveRuntime| runtime_ref.graph_metrics(),
970        ReactiveGraphMetrics::default(),
971    )
972}
973
974/// Returns the active per-thread reactive runtime epoch incremented on every `reset_reactive_runtime`.
975///
976/// # Returns
977///
978/// - `u64` - Active monotonic runtime epoch (`0` if thread-local storage is tearing down).
979#[inline]
980#[must_use]
981pub(crate) fn current_runtime_epoch() -> u64 {
982    RUNTIME_EPOCH.try_with(Cell::get).unwrap_or(0)
983}
984
985/// Resets the current thread's reactive runtime to an empty slim cold-start state.
986pub fn reset_reactive_runtime() {
987    let _: Result<(), _> = RUNTIME_EPOCH.try_with(|epoch: &Cell<u64>| {
988        let next: u64 = epoch.get().wrapping_add(1).max(1);
989        epoch.set(next);
990    });
991    reset_system_event_hub();
992    reset_scene_borrow_state();
993    let _: bool = set_tracking_active(false);
994    let _: Result<(), _> = REF_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
995        depth.set(0);
996    });
997    let _: Result<(), _> = PENDING_REF_TRACKS.try_with(|cell: &RefCell<Vec<DependencyId>>| {
998        if let Ok(mut pending) = cell.try_borrow_mut() {
999            pending.clear();
1000        }
1001    });
1002    with_runtime(
1003        |runtime_ref: &mut ReactiveRuntime| {
1004            *runtime_ref = ReactiveRuntime::default();
1005        },
1006        (),
1007    );
1008}