Skip to main content

day_reactive/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-reactive: the reactive core (DESIGN.md §3.3, §4).
5//!
6//! Build-once / bind-forever: signals, memos, effects, `bind`, and `watch` over a thread-local
7//! generational arena. All handles are `Copy` and `!Send`; the only cross-thread door is
8//! [`Setter`]. Writes batch; the drain runs to fixpoint in (priority, scope-depth, creation-seq)
9//! order; layout/turn-end callbacks run once after the fixpoint (§3.3's turn state machine).
10//!
11//! `Signal` is `!Send`:
12//! ```compile_fail
13//! fn assert_send<T: Send>(_: T) {}
14//! let s = day_reactive::Signal::new(1);
15//! assert_send(s); // must not compile
16//! ```
17
18// ---------------------------------------------------------------------------------------------
19// `tls_group!`: one pthread key for a module's whole set of thread-locals.
20//
21// On Android, Rust's `thread_local!` has no native-TLS path (`rustc --print cfg
22// --target aarch64-linux-android` emits no `target_thread_local`), so every `thread_local!`
23// static takes one of bionic's 128 `pthread_key_create` slots, allocated on first touch and
24// never released. day plus its dependencies declares far more than that, so a long-running app
25// exhausts the table as more of its code runs first, and the next library to ask for a key
26// fails. Android's WebView is the usual casualty: its browser startup takes several keys, gets
27// none, and traps with no message at all.
28//
29// This macro takes `thread_local!`'s syntax and gives back the same names with the same `.with`,
30// but backs all of them with one key: the slots become fields of a single per-module struct and
31// each name becomes a zero-sized handle that borrows its field. Call sites do not change.
32// Cell/RefCell conveniences (`set`/`get`/`replace`) are absent: go through `.with`, which is
33// what the field itself offers.
34#[macro_export]
35macro_rules! tls_group {
36    ($( $(#[$attr:meta])* $vis:vis static $name:ident : $ty:ty = $init:expr ; )+) => {
37        #[allow(non_snake_case)]
38        struct TlsGroupSlots { $( $name: $ty, )+ }
39        ::std::thread_local! {
40            static TLS_GROUP: TlsGroupSlots = TlsGroupSlots { $( $name: $init, )+ };
41        }
42        $(
43            $(#[$attr])*
44            #[allow(non_camel_case_types, dead_code)]
45            #[derive(Clone, Copy)]
46            $vis struct $name;
47            impl $name {
48                #[inline]
49                #[allow(dead_code)]
50                $vis fn with<R>(self, f: impl ::core::ops::FnOnce(&$ty) -> R) -> R {
51                    TLS_GROUP.with(|g| f(&g.$name))
52                }
53                #[inline]
54                #[allow(dead_code)]
55                $vis fn try_with<R>(
56                    self,
57                    f: impl ::core::ops::FnOnce(&$ty) -> R,
58                ) -> ::core::result::Result<R, ::std::thread::AccessError> {
59                    TLS_GROUP.try_with(|g| f(&g.$name))
60                }
61            }
62        )+
63    };
64}
65
66// ---------------------------------------------------------------------------------------------
67// `tls_root!` / `tls_slots!`: one pthread key for a whole crate.
68//
69// `tls_group!` above already collapses a module's statics to one key. These two go the last step:
70// each module declares its slots as a plain struct (`tls_slots!`) and the crate root gathers them
71// into a single thread-local (`tls_root!`). A crate then costs one key no matter how many modules
72// keep state, and the root is also the natural place to hang teardown.
73//
74// Call sites are unchanged: the names still answer `.with`. The cost is one line per module
75// naming its field in the root, and `tls_root!` listing the modules. `crate::tls_root` resolves
76// in the expanding crate, so each crate keeps its own root.
77#[macro_export]
78macro_rules! tls_root {
79    ($( $(#[$attr:meta])* $field:ident : $ty:ty ),+ $(,)?) => {
80        #[allow(non_snake_case)]
81        pub(crate) struct TlsRoot { $( $(#[$attr])* pub(crate) $field: $ty, )+ }
82        ::std::thread_local! {
83            static TLS_ROOT: TlsRoot =
84                TlsRoot { $( $(#[$attr])* $field: ::core::default::Default::default(), )+ };
85        }
86        /// Borrow the crate's single thread-local root. Reentrant: the root itself holds no
87        /// lock, so a slot's closure may reach another slot.
88        #[inline]
89        pub(crate) fn tls_root<R>(f: impl ::core::ops::FnOnce(&TlsRoot) -> R) -> R {
90            TLS_ROOT.with(f)
91        }
92        /// Best-effort access for destructor paths after the crate's TLS has gone away.
93        #[inline]
94        #[allow(dead_code)]
95        pub(crate) fn try_tls_root<R>(
96            f: impl ::core::ops::FnOnce(&TlsRoot) -> R,
97        ) -> ::core::result::Result<R, ::std::thread::AccessError> {
98            TLS_ROOT.try_with(f)
99        }
100    };
101}
102
103/// One module's slots, stored as `$field` of the crate's [`tls_root!`].
104// `crate::tls_root` is correct here, and `$crate` would be wrong: the root belongs to the crate
105// expanding this macro, not to day-reactive. That resolution is what gives each crate a root of
106// its own, so the lint is describing the intent rather than a mistake.
107#[allow(clippy::crate_in_macro_def)]
108#[macro_export]
109macro_rules! tls_slots {
110    ($field:ident; $( $(#[$attr:meta])* $vis:vis static $name:ident : $ty:ty = $init:expr ; )+) => {
111        #[allow(non_snake_case)]
112        pub(crate) struct TlsGroupSlots { $( $name: $ty, )+ }
113        impl ::core::default::Default for TlsGroupSlots {
114            fn default() -> Self { Self { $( $name: $init, )+ } }
115        }
116        $(
117            $(#[$attr])*
118            #[allow(non_camel_case_types, dead_code)]
119            #[derive(Clone, Copy)]
120            $vis struct $name;
121            impl $name {
122                #[inline]
123                #[allow(dead_code)]
124                $vis fn with<R>(self, f: impl ::core::ops::FnOnce(&$ty) -> R) -> R {
125                    crate::tls_root(|r| f(&r.$field.$name))
126                }
127                #[inline]
128                #[allow(dead_code)]
129                $vis fn try_with<R>(
130                    self,
131                    f: impl ::core::ops::FnOnce(&$ty) -> R,
132                ) -> ::core::result::Result<R, ::std::thread::AccessError> {
133                    crate::try_tls_root(|r| f(&r.$field.$name))
134                }
135            }
136        )+
137    };
138}
139
140use std::any::{Any, TypeId};
141use std::cell::{Cell, RefCell};
142use std::collections::{HashMap, HashSet};
143use std::future::Future;
144use std::marker::PhantomData;
145use std::panic::Location;
146use std::pin::Pin;
147use std::rc::Rc;
148use std::sync::Arc;
149
150use slotmap::{Key, SlotMap, new_key_type};
151
152new_key_type! {
153    pub struct NodeKey;
154    pub struct ScopeKey;
155}
156
157// ---------------------------------------------------------------------------
158// Runtime
159// ---------------------------------------------------------------------------
160
161#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
162enum NodeState {
163    Clean,
164    Check,
165    Dirty,
166}
167
168#[derive(Clone, Copy, PartialEq, Eq)]
169enum NodeKind {
170    Signal,
171    Memo,
172    /// Effects, binds, watches: anything with a re-runnable reaction closure.
173    Reaction,
174}
175
176/// Type-erased memo comparator (a monomorphized `PartialEq::eq`).
177type MemoEq = fn(&dyn Any, &dyn Any) -> bool;
178
179/// A node's stored value, shared so a reader can hold it while the runtime borrow is released.
180///
181/// `with`/`try_with` must run the caller's closure without holding the thread-local runtime
182/// borrow (the closure routinely reads other signals, which re-enters `with_rt`). This used to be
183/// done by taking the value out of the node and putting it back afterwards, which had two costs: a
184/// re-entrant read of the same signal found the hole and reported "disposed", and a panic inside
185/// the closure lost the value permanently. Sharing the cell instead lets a reader clone it out
186/// cheaply, so concurrent reads work and the value is never in limbo.
187type NodeValue = Rc<RefCell<Box<dyn Any>>>;
188
189struct Node {
190    kind: NodeKind,
191    state: NodeState,
192    value: Option<NodeValue>,
193    /// Memo recompute (returns boxed new value), compared with `eq`.
194    memo_compute: Option<Rc<dyn Fn() -> Box<dyn Any>>>,
195    memo_eq: Option<MemoEq>,
196    /// Reaction closure (effect/bind/watch body).
197    reaction: Option<Rc<dyn Fn()>>,
198    sources: Vec<NodeKey>,
199    /// Callbacks an external dependency registry (day-model's trigger claims) hangs on this
200    /// computation's current run, drained when the run's sources clear (re-track or disposal),
201    /// mirroring the per-run lifetime of `sources` itself. Run outside the runtime borrow.
202    run_cleanups: Vec<Box<dyn FnOnce()>>,
203    observers: Vec<NodeKey>,
204    // Computations restore this owner when they run, including lazy memo reads.
205    scope: ScopeKey,
206    /// Ordering: (priority, scope depth, creation seq). Priority 0 = structural binding.
207    priority: u8,
208    depth: u32,
209    seq: u64,
210    last_changed: u64,
211    last_run: u64,
212    queued: bool,
213    created_at: &'static Location<'static>,
214}
215
216struct ScopeData {
217    parent: ScopeKey,
218    children: Vec<ScopeKey>,
219    nodes: Vec<NodeKey>,
220    cleanups: Vec<Box<dyn FnOnce()>>,
221    context: HashMap<TypeId, Box<dyn Any>>,
222    depth: u32,
223}
224
225struct Runtime {
226    nodes: SlotMap<NodeKey, Node>,
227    scopes: SlotMap<ScopeKey, ScopeData>,
228    root_scope: ScopeKey,
229    current_scope: ScopeKey,
230    /// Observer stack; `None` = untracked frame.
231    observers: Vec<Option<NodeKey>>,
232    pending: Vec<NodeKey>,
233    batch_depth: u32,
234    draining: bool,
235    tick: u64,
236    next_seq: u64,
237    scheduler: Option<Rc<dyn Fn()>>,
238    schedule_posted: bool,
239    /// The async-spawn door ([`install_spawner`]): runs a boxed future on the app's main-loop
240    /// executor, returning an abort closure.
241    spawner: Option<Spawner>,
242    turn_end: Vec<Rc<dyn Fn()>>,
243    /// One-shot callbacks for the end of the current turn ([`at_turn_end`]).
244    turn_end_once: Vec<Box<dyn FnOnce()>>,
245    warned_writes: HashSet<*const Location<'static>>,
246}
247
248impl Runtime {
249    fn new() -> Self {
250        let mut scopes = SlotMap::with_key();
251        let root_scope = scopes.insert(ScopeData {
252            parent: ScopeKey::null(),
253            children: Vec::new(),
254            nodes: Vec::new(),
255            cleanups: Vec::new(),
256            context: HashMap::new(),
257            depth: 0,
258        });
259        Runtime {
260            nodes: SlotMap::with_key(),
261            scopes,
262            root_scope,
263            current_scope: root_scope,
264            observers: Vec::new(),
265            pending: Vec::new(),
266            batch_depth: 0,
267            draining: false,
268            tick: 1,
269            next_seq: 0,
270            scheduler: None,
271            schedule_posted: false,
272            turn_end_once: Vec::new(),
273            spawner: None,
274            turn_end: Vec::new(),
275            warned_writes: HashSet::new(),
276        }
277    }
278}
279
280crate::tls_group! {
281    static RT: RefCell<Runtime> = RefCell::new(Runtime::new());
282
283}
284
285/// Per-drain re-run cap (§4.2): panic in debug, warn-and-defer in release.
286const RERUN_CAP: u32 = 100;
287
288/// Per-turn cap on drain→turn-end rounds ([`flush_sync`]): same panic/warn split as
289/// [`RERUN_CAP`]. Two rounds settle the normal case (a turn-end hook scheduling reactive
290/// work, such as day-persistence's deferred requeries); reaching the cap means hooks are feeding
291/// each other every round.
292const TURN_ROUND_CAP: u32 = 8;
293
294fn with_rt<R>(f: impl FnOnce(&mut Runtime) -> R) -> R {
295    RT.with(|rt| f(&mut rt.borrow_mut()))
296}
297
298// ---------------------------------------------------------------------------
299// Graph internals
300// ---------------------------------------------------------------------------
301
302#[track_caller]
303fn create_node(rt: &mut Runtime, kind: NodeKind, scope: ScopeKey) -> NodeKey {
304    let depth = rt.scopes.get(scope).map(|s| s.depth).unwrap_or(0);
305    let seq = rt.next_seq;
306    rt.next_seq += 1;
307    let key = rt.nodes.insert(Node {
308        kind,
309        state: NodeState::Clean,
310        value: None,
311        memo_compute: None,
312        memo_eq: None,
313        reaction: None,
314        sources: Vec::new(),
315        run_cleanups: Vec::new(),
316        observers: Vec::new(),
317        scope,
318        priority: 1,
319        depth,
320        seq,
321        last_changed: 0,
322        last_run: 0,
323        queued: false,
324        created_at: Location::caller(),
325    });
326    if let Some(s) = rt.scopes.get_mut(scope) {
327        s.nodes.push(key);
328    }
329    key
330}
331
332/// Register a tracked read: current observer gains `source` as a dependency.
333fn track_read(rt: &mut Runtime, source: NodeKey) {
334    if let Some(Some(obs)) = rt.observers.last().copied() {
335        if obs == source {
336            return;
337        }
338        let already = rt.nodes[obs].sources.contains(&source);
339        if !already {
340            rt.nodes[obs].sources.push(source);
341            rt.nodes[source].observers.push(obs);
342        }
343    }
344}
345
346/// Unsubscribe `key` from its sources and hand back its run cleanups. The caller must run the
347/// returned closures after releasing the runtime borrow: they call into consumers (day-model
348/// claim release disposes trigger scopes) that re-enter the runtime.
349#[must_use]
350fn clear_sources(rt: &mut Runtime, key: NodeKey) -> Vec<Box<dyn FnOnce()>> {
351    let sources = std::mem::take(&mut rt.nodes[key].sources);
352    for s in sources {
353        if let Some(n) = rt.nodes.get_mut(s)
354            && let Some(pos) = n.observers.iter().position(|&o| o == key)
355        {
356            n.observers.swap_remove(pos);
357        }
358    }
359    std::mem::take(&mut rt.nodes[key].run_cleanups)
360}
361
362/// Mark downstream after a source changed. Direct observers get `Dirty`; transitive
363/// (through memos) get `Check`. Reactions are enqueued.
364fn mark_observers(rt: &mut Runtime, source: NodeKey, level: NodeState) {
365    // Small explicit stack to avoid recursion borrow issues.
366    let mut stack: Vec<(NodeKey, NodeState)> = rt.nodes[source]
367        .observers
368        .iter()
369        .map(|&o| (o, level))
370        .collect();
371    while let Some((key, level)) = stack.pop() {
372        let Some(node) = rt.nodes.get_mut(key) else {
373            continue;
374        };
375        if node.state >= level {
376            continue; // already at least this dirty
377        }
378        node.state = level;
379        match node.kind {
380            NodeKind::Reaction => {
381                if !node.queued {
382                    node.queued = true;
383                    rt.pending.push(key);
384                }
385            }
386            NodeKind::Memo => {
387                for &o in rt.nodes[key].observers.iter() {
388                    stack.push((o, NodeState::Check));
389                }
390            }
391            NodeKind::Signal => {}
392        }
393    }
394}
395
396/// Enter a computation's owner and tracking frame together. A memo can be pulled by a
397/// different window's reaction, and a queued effect can run after its caller has left scope.
398/// Neither should inherit that caller's context or allocate state into its scope.
399fn compute_in_owner<T>(key: NodeKey, f: impl FnOnce() -> T) -> Option<T> {
400    let owner = with_rt(|rt| {
401        let owner = rt.nodes.get(key)?.scope;
402        rt.scopes.contains_key(owner).then_some(owner)
403    })?;
404    let scope = Scope {
405        key: owner,
406        _not_send: PhantomData,
407    };
408    Some(scope.enter(|| {
409        with_rt(|rt| rt.observers.push(Some(key)));
410        let _guard = RtGuard(|rt: &mut Runtime| {
411            rt.observers.pop();
412        });
413        f()
414    }))
415}
416
417/// Pull-refresh a memo: recompute if (transitively) dirty; bump `last_changed` only on real change.
418fn refresh_memo(key: NodeKey) {
419    let (state, kind) = match with_rt(|rt| rt.nodes.get(key).map(|n| (n.state, n.kind))) {
420        Some(v) => v,
421        None => return,
422    };
423    if kind != NodeKind::Memo || state == NodeState::Clean {
424        return;
425    }
426    if state == NodeState::Check {
427        // Refresh sources; only recompute if one actually changed since our last run.
428        let (sources, last_run) =
429            with_rt(|rt| (rt.nodes[key].sources.clone(), rt.nodes[key].last_run));
430        let mut any_changed = false;
431        for s in sources {
432            refresh_memo(s);
433            if with_rt(|rt| {
434                rt.nodes
435                    .get(s)
436                    .map(|n| n.last_changed > last_run)
437                    .unwrap_or(false)
438            }) {
439                any_changed = true;
440            }
441        }
442        if !any_changed {
443            with_rt(|rt| {
444                if let Some(n) = rt.nodes.get_mut(key) {
445                    n.state = NodeState::Clean;
446                }
447            });
448            return;
449        }
450    }
451    // Recompute.
452    let compute = with_rt(|rt| rt.nodes[key].memo_compute.clone());
453    let Some(compute) = compute else { return };
454    let cleanups = with_rt(|rt| clear_sources(rt, key));
455    for f in cleanups {
456        f();
457    }
458    let Some(new_value) = compute_in_owner(key, || compute()) else {
459        return;
460    };
461    with_rt(|rt| {
462        let tick = rt.tick;
463        let Some(node) = rt.nodes.get_mut(key) else {
464            return;
465        };
466        let changed = match (node.value.as_ref(), node.memo_eq) {
467            (Some(old), Some(eq)) => {
468                // A reader may be holding this cell; compare against it without disturbing them.
469                let old = old.borrow();
470                !eq(old.as_ref(), new_value.as_ref())
471            }
472            _ => true,
473        };
474        node.last_run = tick;
475        node.state = NodeState::Clean;
476        if changed {
477            // Install a new cell rather than writing through the old one: a read in flight keeps
478            // reading the value it borrowed, for the duration of its closure, instead of panicking.
479            node.value = Some(Rc::new(RefCell::new(new_value)));
480            node.last_changed = tick;
481            rt.tick += 1;
482        }
483        // Downstream was already marked Check when we were invalidated; observers that pull us
484        // will see last_changed. Nothing further to do here.
485    });
486}
487
488/// Run one reaction if it is actually stale.
489fn run_reaction(key: NodeKey) {
490    let info = with_rt(|rt| {
491        rt.nodes.get_mut(key).map(|n| {
492            n.queued = false;
493            (n.state, n.sources.clone(), n.last_run)
494        })
495    });
496    let Some((state, sources, last_run)) = info else {
497        return;
498    };
499    if state == NodeState::Clean {
500        return;
501    }
502    if state == NodeState::Check {
503        let mut any_changed = false;
504        for s in &sources {
505            refresh_memo(*s);
506            if with_rt(|rt| {
507                rt.nodes
508                    .get(*s)
509                    .map(|n| n.last_changed > last_run)
510                    .unwrap_or(false)
511            }) {
512                any_changed = true;
513                break;
514            }
515        }
516        if !any_changed {
517            with_rt(|rt| {
518                if let Some(n) = rt.nodes.get_mut(key) {
519                    n.state = NodeState::Clean;
520                }
521            });
522            return;
523        }
524    }
525    let reaction = with_rt(|rt| rt.nodes.get(key).and_then(|n| n.reaction.clone()));
526    let Some(reaction) = reaction else { return };
527    let cleanups = with_rt(|rt| {
528        let cleanups = clear_sources(rt, key);
529        if let Some(n) = rt.nodes.get_mut(key) {
530            n.state = NodeState::Clean;
531        }
532        cleanups
533    });
534    // Released claims must drop before the fresh run tracks, and outside the borrow.
535    for f in cleanups {
536        f();
537    }
538    compute_in_owner(key, || reaction());
539    with_rt(|rt| {
540        let tick = rt.tick;
541        rt.tick += 1;
542        if let Some(n) = rt.nodes.get_mut(key) {
543            n.last_run = tick;
544        }
545    });
546}
547
548/// Drain the pending queue to fixpoint, then run turn-end callbacks (§3.3 steps 2–3),
549/// repeating both until the turn is quiescent. A turn-end callback may schedule new
550/// reactive work (day-persistence's autosave flush re-derives live queries and diffs the
551/// answers into signals); that work belongs to this turn: §3.3 step 2's "writes made
552/// during the drain extend the current drain", extended across the turn-end boundary.
553/// Left pending instead, every cross-row readout (a query-fed list, a derived bound)
554/// would render one turn stale. Round two drains the deltas and re-runs the hooks, and
555/// autosave then finds nothing dirty, so a settled app exits after two rounds;
556/// The turn-round cap stops turn-end hooks that feed each other forever.
557pub fn flush_sync() {
558    let already = with_rt(|rt| {
559        if rt.draining {
560            return true;
561        }
562        rt.draining = true;
563        false
564    });
565    if already {
566        return; // re-entrant flush folds into the current drain
567    }
568    let mut round = 0u32;
569    'turn: loop {
570        round += 1;
571        // Fresh per round: the re-run cap is per drain (§4.2), and each round is one drain.
572        let mut run_counts: HashMap<NodeKey, u32> = HashMap::new();
573        loop {
574            let mut batch = with_rt(|rt| std::mem::take(&mut rt.pending));
575            if batch.is_empty() {
576                break;
577            }
578            // (priority, scope-depth, creation-seq): owners before descendants.
579            with_rt(|rt| {
580                batch.sort_by_key(|&k| {
581                    rt.nodes
582                        .get(k)
583                        .map(|n| (n.priority, n.depth, n.seq))
584                        .unwrap_or((u8::MAX, u32::MAX, u64::MAX))
585                })
586            });
587            for key in batch {
588                let count = run_counts.entry(key).or_insert(0);
589                *count += 1;
590                if *count > RERUN_CAP {
591                    if *count == RERUN_CAP + 1 {
592                        let loc = with_rt(|rt| rt.nodes.get(key).map(|n| n.created_at));
593                        if let Some(loc) = loc {
594                            if cfg!(debug_assertions) {
595                                panic!(
596                                    "day-reactive: effect created at {loc} re-ran more than {RERUN_CAP} times in one drain (reactive cycle?)"
597                                );
598                            } else {
599                                log::warn!(
600                                    "day-reactive: effect created at {loc} exceeded the re-run cap; skipping it for the rest of this drain (the next source write re-arms it)"
601                                );
602                            }
603                        }
604                    }
605                    // Break the cycle but leave the node runnable. This key was drained out of
606                    // `pending` above with `queued` still true; without the reset here,
607                    // `mark_observers` would never enqueue it again and the binding would be
608                    // silently dead for the rest of the process. Clean + unqueued means the next
609                    // source write re-marks and re-enqueues it with a fresh per-drain budget.
610                    with_rt(|rt| {
611                        if let Some(n) = rt.nodes.get_mut(key) {
612                            n.queued = false;
613                            n.state = NodeState::Clean;
614                        }
615                    });
616                    continue;
617                }
618                run_reaction(key);
619            }
620        }
621        let (once, turn_end) = with_rt(|rt| {
622            rt.draining = false;
623            rt.schedule_posted = false;
624            (std::mem::take(&mut rt.turn_end_once), rt.turn_end.clone())
625        });
626        // One-shot work first: it settles what this turn changed (a toolbar composed once from
627        // everything the turn contributed), which the standing hooks (layout) then see.
628        for cb in once {
629            cb();
630        }
631        for cb in turn_end {
632            cb();
633        }
634        // Quiescent, or a nested flush inside a callback already settled everything.
635        let more = with_rt(|rt| {
636            if rt.pending.is_empty() {
637                return false;
638            }
639            rt.draining = true;
640            true
641        });
642        if !more {
643            return;
644        }
645        if round >= TURN_ROUND_CAP {
646            // The callbacks' first write posted a scheduled drain (draining was false
647            // then), so the deferred work still runs next turn, the same recovery shape as
648            // the re-run cap.
649            with_rt(|rt| rt.draining = false);
650            if cfg!(debug_assertions) {
651                panic!(
652                    "day-reactive: turn-end callbacks scheduled new reactive work for {TURN_ROUND_CAP} straight rounds in one turn (hooks feeding each other?)"
653                );
654            } else {
655                log::warn!(
656                    "day-reactive: turn-end callbacks still scheduling work after {TURN_ROUND_CAP} rounds; deferring the rest to the next turn"
657                );
658            }
659            return;
660        }
661        continue 'turn;
662    }
663}
664
665/// Reset the runtime to a clean idle state after a panic unwound through a drain or batch,
666/// e.g. a reactive-cycle assertion (the rerun cap) that tripped inside a native event callback
667/// which the backend *contained* (rather than letting it abort the process across the C ABI; a
668/// GTK/Qt signal trampoline can't unwind). The in-flight `pending` work and the observer stack
669/// are dropped (the next interaction re-derives them); persistent registrations (effects, memos,
670/// turn-end hooks) are kept.
671pub fn recover_from_panic() {
672    with_rt(|rt| {
673        rt.draining = false;
674        rt.schedule_posted = false;
675        rt.batch_depth = 0;
676        rt.turn_end_once.clear();
677        rt.pending.clear();
678        rt.observers.clear();
679        // The scope stack is unwound by `Scope::enter`'s guard, but a panic raised between
680        // scopes (or from a callsite that set `current_scope` directly) can still leave it on a
681        // disposed scope, where every later `Signal::new` would be born dead. Re-root it.
682        rt.current_scope = rt.root_scope;
683    });
684}
685
686/// After a write: schedule work. Inside a batch or drain, the fixpoint picks it up; outside,
687/// post a coalesced drain through the installed scheduler (§3.3 step 3).
688fn schedule_after_write(rt: &mut Runtime) -> Option<Rc<dyn Fn()>> {
689    if rt.batch_depth > 0 || rt.draining {
690        return None;
691    }
692    if rt.schedule_posted {
693        return None;
694    }
695    rt.schedule_posted = true;
696    rt.scheduler.clone()
697}
698
699fn signal_write_boxed(key: NodeKey, apply: impl FnOnce(&mut Box<dyn Any>) -> bool) {
700    let poster = with_rt(|rt| {
701        let node = rt.nodes.get_mut(key)?;
702        let cell = node.value.as_ref()?.clone();
703        let mut value = match cell.try_borrow_mut() {
704            Ok(v) => v,
705            // A write to a signal from inside its own `with`/`try_with` closure. Before the value
706            // was shared this silently did nothing (the read's restore clobbered the write), so
707            // say it plainly instead of losing the update.
708            Err(_) => panic!(
709                "day-reactive: wrote to a Signal while a with()/try_with() read of it is still \
710                 in flight — the write would be lost. Finish the read closure first (copy the \
711                 value out with get()) and write after it returns."
712            ),
713        };
714        let changed = apply(&mut value);
715        drop(value);
716        let node = rt.nodes.get_mut(key)?;
717        if !changed {
718            return None;
719        }
720        node.last_changed = rt.tick;
721        rt.tick += 1;
722        mark_observers(rt, key, NodeState::Dirty);
723        schedule_after_write(rt)
724    });
725    if let Some(post) = poster {
726        post();
727    }
728}
729
730// ---------------------------------------------------------------------------
731// Public: batching / scheduling / turn end
732// ---------------------------------------------------------------------------
733
734/// Run `f` in a batch: writes coalesce; the synchronous fixpoint drain runs at batch close.
735/// Restores a piece of runtime state when it goes out of scope, on the normal path and on an
736/// unwind. day-core contains panics at its trampoline boundaries (`pump_events`, posted tasks,
737/// lifecycle) so a panicking app callback degrades the UI instead of aborting the process; that
738/// guarantee is only worth anything if the reactive runtime is still coherent afterwards.
739/// Restoring after `f()` returns is not enough, because that line is skipped on unwind.
740struct RtGuard<F: FnMut(&mut Runtime)>(F);
741
742impl<F: FnMut(&mut Runtime)> Drop for RtGuard<F> {
743    fn drop(&mut self) {
744        with_rt(|rt| (self.0)(rt));
745    }
746}
747
748pub fn batch<R>(f: impl FnOnce() -> R) -> R {
749    with_rt(|rt| rt.batch_depth += 1);
750    let r = {
751        // Runs on unwind too, so a contained panic can't strand `batch_depth` above zero, which
752        // would stop every later write from scheduling a drain (a silently frozen UI). Saturating:
753        // if `recover_from_panic` already zeroed the depth mid-unwind, a plain `-= 1` here would
754        // underflow: a panic inside this Drop, which is a process abort.
755        let _g = RtGuard(|rt: &mut Runtime| rt.batch_depth = rt.batch_depth.saturating_sub(1));
756        f()
757    };
758    let should_drain = with_rt(|rt| {
759        rt.batch_depth == 0
760            && !rt.draining
761            && (!rt.pending.is_empty() || !rt.turn_end_once.is_empty())
762    });
763    if should_drain {
764        flush_sync();
765    }
766    r
767}
768
769/// Force a synchronous fixpoint drain **now**, even inside an open [`batch`]. Event dispatch wraps
770/// handlers in a batch (day-core), so a handler that needs its writes to drain immediately
771/// (namely `with_animation`, whose ambient animation must be live *while* the resulting patches
772/// apply) cannot rely on the batch's close (that runs later, after the scope ends). This
773/// temporarily drops the batch depth so [`flush_sync`] runs, then restores it. No-op if a drain
774/// is already in progress (the writes fold into it); harmless if nothing is pending.
775pub fn flush_now() {
776    let saved = with_rt(|rt| std::mem::replace(&mut rt.batch_depth, 0));
777    // Restored on unwind too: the debug rerun-cap panic can cross here under an event-dispatch
778    // batch, and skipping the restore would hand the enclosing batch guard a zero depth.
779    let _g = RtGuard(move |rt: &mut Runtime| rt.batch_depth = saved);
780    flush_sync();
781}
782
783/// Run `f` without tracking reads.
784pub fn untrack<R>(f: impl FnOnce() -> R) -> R {
785    with_rt(|rt| rt.observers.push(None));
786    // Popped on unwind too: a stranded `None` observer would silently disable dependency
787    // tracking for every read that followed, so nothing would ever update again.
788    let _g = RtGuard(|rt: &mut Runtime| {
789        rt.observers.pop();
790    });
791    f()
792}
793
794/// The identity of one reactive computation (a reaction or a memo) across its lifetime.
795/// Opaque; `Copy + Eq + Hash`, so an external dependency registry can key per-computation
796/// bookkeeping on it. Slotmap-generational underneath: a recycled slot is a new `RunId`.
797#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
798pub struct RunId(NodeKey);
799
800/// The computation currently tracking reads: `None` at top level and under [`untrack`].
801pub fn active_run() -> Option<RunId> {
802    with_rt(|rt| rt.observers.last().copied().flatten()).map(RunId)
803}
804
805/// Hang `f` on the active computation's current run: it fires when that computation next
806/// re-tracks (a re-run clears its sources first) or is disposed. This is the hook that lets an
807/// external dependency registry (day-model's trigger claims) mirror this graph's per-run
808/// source bookkeeping. Returns `false`, registering nothing, when no computation is tracking.
809pub fn on_run_retrack(f: impl FnOnce() + 'static) -> bool {
810    with_rt(|rt| {
811        let Some(Some(key)) = rt.observers.last().copied() else {
812            return false;
813        };
814        match rt.nodes.get_mut(key) {
815            Some(n) => {
816                n.run_cleanups.push(Box::new(f));
817                true
818            }
819            None => false,
820        }
821    })
822}
823
824/// Install "post a drain on the main loop". Backends call this once at startup.
825pub fn install_scheduler(post: impl Fn() + 'static) {
826    with_rt(|rt| rt.scheduler = Some(Rc::new(post)));
827}
828
829/// A boxed, `!Send` future for the [`install_spawner`] executor door.
830pub type LocalBoxFuture = Pin<Box<dyn Future<Output = ()> + 'static>>;
831
832/// The installed spawner: runs a future on the main-loop executor, returns its abort closure.
833type Spawner = Rc<dyn Fn(LocalBoxFuture) -> Box<dyn FnOnce()>>;
834
835/// Install the async-spawn door: `spawn` runs a future on the app's main-loop executor and
836/// returns an abort closure (remove + drop the future). The abort must be a no-op once the
837/// task has completed: [`Resource`] stores it after an eager first poll, so a synchronously
838/// ready future has already finished by then. day-core's `launch_with` wires this to
839/// `day::task` / `TaskHandle::abort`; call it once at startup (docs/async.md).
840pub fn install_spawner(spawn: impl Fn(LocalBoxFuture) -> Box<dyn FnOnce()> + 'static) {
841    with_rt(|rt| rt.spawner = Some(Rc::new(spawn)));
842}
843
844/// Spawn through the installed door ([`install_spawner`]); the [`on_main`] panic model.
845fn spawn_local(fut: LocalBoxFuture) -> Box<dyn FnOnce()> {
846    let spawner = with_rt(|rt| rt.spawner.clone());
847    match spawner {
848        Some(s) => s(fut),
849        None => panic!("day-reactive: no spawner installed (backend not started)"),
850    }
851}
852
853/// Register a callback run once after every fixpoint drain (day-core's layout turn).
854pub fn on_turn_end(cb: impl Fn() + 'static) {
855    with_rt(|rt| rt.turn_end.push(Rc::new(cb)));
856}
857
858/// Run `cb` once, when the current turn settles: after the drain inside a drain or a batch
859/// (even a batch that leaves no reactive work behind), or right away when no turn is open.
860///
861/// This is how a consumer coalesces a burst of changes into one pass. Swapping a page
862/// withdraws the old page's toolbar items and contributes the new page's within one turn, and
863/// only the settled result is worth handing to the toolkit.
864pub fn at_turn_end(cb: impl FnOnce() + 'static) {
865    let now = with_rt(|rt| {
866        if rt.draining || rt.batch_depth > 0 {
867            rt.turn_end_once.push(Box::new(cb));
868            None
869        } else {
870            Some(cb)
871        }
872    });
873    if let Some(cb) = now {
874        cb();
875    }
876}
877
878// ---------------------------------------------------------------------------
879// Cross-thread: the main poster + Setter
880// ---------------------------------------------------------------------------
881
882type MainPoster = Box<dyn Fn(Box<dyn FnOnce() + Send>) + Send + Sync>;
883static MAIN_POSTER: std::sync::OnceLock<MainPoster> = std::sync::OnceLock::new();
884
885/// Install the cross-thread → main-thread door. Backends call this once at startup.
886pub fn install_main_poster(post: impl Fn(Box<dyn FnOnce() + Send>) + Send + Sync + 'static) {
887    let _ = MAIN_POSTER.set(Box::new(post));
888}
889
890/// Whether a backend has installed the main poster yet, i.e. whether [`on_main`] would work
891/// rather than panic. Platform glue that can be called before launch (a notification tap that
892/// cold-starts the process) probes this and buffers instead of posting. The poster is set once
893/// and never cleared, so a `false` can only become `true`: a caller that buffers on a false
894/// negative is still correct, provided something drains the buffer at launch.
895pub fn has_main_poster() -> bool {
896    MAIN_POSTER.get().is_some()
897}
898
899/// Schedule `f` on the UI thread (usable from any thread once a backend installed the poster).
900pub fn on_main(f: impl FnOnce() + Send + 'static) {
901    match MAIN_POSTER.get() {
902        Some(post) => post(Box::new(f)),
903        None => panic!("day-reactive: no main poster installed (backend not started)"),
904    }
905}
906
907type DelayedPoster = Box<dyn Fn(u32, Box<dyn FnOnce() + Send>) + Send + Sync>;
908static DELAYED_POSTER: std::sync::OnceLock<DelayedPoster> = std::sync::OnceLock::new();
909
910/// Install the timer door (`Platform::post_delayed`). Backends call this once at startup.
911pub fn install_delayed_poster(
912    post: impl Fn(u32, Box<dyn FnOnce() + Send>) + Send + Sync + 'static,
913) {
914    let _ = DELAYED_POSTER.set(Box::new(post));
915}
916
917/// Schedule `f` on the UI thread after (at least) `ms` milliseconds, the rail behind
918/// `day::sleep` (docs/async.md).
919pub fn on_main_delayed(ms: u32, f: impl FnOnce() + Send + 'static) {
920    match DELAYED_POSTER.get() {
921        Some(post) => post(ms, Box::new(f)),
922        None => panic!("day-reactive: no delayed poster installed (backend not started)"),
923    }
924}
925
926// ---------------------------------------------------------------------------
927// Scope
928// ---------------------------------------------------------------------------
929
930/// Ownership scope for signals/effects (§4.3). `Copy` handle; not `Send`.
931#[derive(Clone, Copy, PartialEq, Eq)]
932pub struct Scope {
933    key: ScopeKey,
934    _not_send: PhantomData<*const ()>,
935}
936
937impl Scope {
938    pub fn current() -> Scope {
939        Scope {
940            key: with_rt(|rt| rt.current_scope),
941            _not_send: PhantomData,
942        }
943    }
944
945    pub fn root() -> Scope {
946        Scope {
947            key: with_rt(|rt| rt.root_scope),
948            _not_send: PhantomData,
949        }
950    }
951
952    /// Create a child of the current scope.
953    pub fn child() -> Scope {
954        Scope::current().create_child()
955    }
956
957    pub fn create_child(self) -> Scope {
958        let key = with_rt(|rt| {
959            let depth = rt.scopes.get(self.key).map(|s| s.depth + 1).unwrap_or(1);
960            let child = rt.scopes.insert(ScopeData {
961                parent: self.key,
962                children: Vec::new(),
963                nodes: Vec::new(),
964                cleanups: Vec::new(),
965                context: HashMap::new(),
966                depth,
967            });
968            if let Some(p) = rt.scopes.get_mut(self.key) {
969                p.children.push(child);
970            }
971            child
972        });
973        Scope {
974            key,
975            _not_send: PhantomData,
976        }
977    }
978
979    /// A scope owned by nobody; dispose it manually.
980    pub fn detached() -> Scope {
981        let key = with_rt(|rt| {
982            rt.scopes.insert(ScopeData {
983                parent: ScopeKey::null(),
984                children: Vec::new(),
985                nodes: Vec::new(),
986                cleanups: Vec::new(),
987                context: HashMap::new(),
988                depth: 0,
989            })
990        });
991        Scope {
992            key,
993            _not_send: PhantomData,
994        }
995    }
996
997    /// Run `f` with `self` as the current scope.
998    pub fn enter<R>(self, f: impl FnOnce() -> R) -> R {
999        let prev = with_rt(|rt| std::mem::replace(&mut rt.current_scope, self.key));
1000        // Restored on unwind too. Otherwise a contained panic leaves the runtime parented to
1001        // this (usually transient, soon-disposed) scope, so every later `Signal::new` is created
1002        // dead and its first read panics with a misleading "read of disposed Signal".
1003        let _g = RtGuard(move |rt: &mut Runtime| rt.current_scope = prev);
1004        f()
1005    }
1006
1007    pub fn on_cleanup(self, f: impl FnOnce() + 'static) {
1008        with_rt(|rt| {
1009            if let Some(s) = rt.scopes.get_mut(self.key) {
1010                s.cleanups.push(Box::new(f));
1011            }
1012        });
1013    }
1014
1015    pub fn is_alive(self) -> bool {
1016        with_rt(|rt| rt.scopes.contains_key(self.key))
1017    }
1018
1019    /// Dispose this scope: children first, then own nodes (unsubscribed + dropped) and cleanups.
1020    pub fn dispose(self) {
1021        let children = match with_rt(|rt| rt.scopes.get(self.key).map(|s| s.children.clone())) {
1022            Some(c) => c,
1023            None => return,
1024        };
1025        for c in children {
1026            (Scope {
1027                key: c,
1028                _not_send: PhantomData,
1029            })
1030            .dispose();
1031        }
1032        let (nodes, cleanups, parent) = match with_rt(|rt| {
1033            rt.scopes
1034                .remove(self.key)
1035                .map(|s| (s.nodes, s.cleanups, s.parent))
1036        }) {
1037            Some(v) => v,
1038            None => return,
1039        };
1040        let mut run_cleanups: Vec<Box<dyn FnOnce()>> = Vec::new();
1041        with_rt(|rt| {
1042            if let Some(p) = rt.scopes.get_mut(parent)
1043                && let Some(pos) = p.children.iter().position(|&c| c == self.key)
1044            {
1045                p.children.swap_remove(pos);
1046            }
1047            for key in nodes {
1048                run_cleanups.extend(clear_sources(rt, key));
1049                // Detach us from downstream observers too.
1050                if let Some(node) = rt.nodes.get_mut(key) {
1051                    let observers = std::mem::take(&mut node.observers);
1052                    for o in observers {
1053                        if let Some(on) = rt.nodes.get_mut(o)
1054                            && let Some(pos) = on.sources.iter().position(|&s| s == key)
1055                        {
1056                            on.sources.swap_remove(pos);
1057                        }
1058                    }
1059                }
1060                rt.nodes.remove(key);
1061                // Pending entries for removed nodes are skipped at pop (generational key check).
1062            }
1063        });
1064        // A dying computation's per-run claims drop like a re-track would drop them: outside
1065        // the borrow, before the scope's own cleanups (which may release scope-level claims).
1066        for f in run_cleanups {
1067            f();
1068        }
1069        for c in cleanups {
1070            c();
1071        }
1072    }
1073
1074    /// Provide a context value visible to this scope and its descendants.
1075    pub fn provide<T: 'static>(self, value: T) {
1076        with_rt(|rt| {
1077            if let Some(s) = rt.scopes.get_mut(self.key) {
1078                s.context.insert(TypeId::of::<T>(), Box::new(value));
1079            }
1080        });
1081    }
1082
1083    /// Look up a context value here or in any ancestor (requires `T: Clone`).
1084    pub fn use_context<T: Clone + 'static>(self) -> Option<T> {
1085        with_rt(|rt| {
1086            let mut cur = self.key;
1087            while let Some(s) = rt.scopes.get(cur) {
1088                if let Some(v) = s.context.get(&TypeId::of::<T>()) {
1089                    return v.downcast_ref::<T>().cloned();
1090                }
1091                cur = s.parent;
1092            }
1093            None
1094        })
1095    }
1096}
1097
1098// ---------------------------------------------------------------------------
1099// Signal
1100// ---------------------------------------------------------------------------
1101
1102/// A `Copy`, `!Send` reactive value handle (§4.2).
1103pub struct Signal<T: 'static> {
1104    key: NodeKey,
1105    created_at: &'static Location<'static>,
1106    _m: PhantomData<*const T>,
1107}
1108
1109impl<T: 'static> Clone for Signal<T> {
1110    fn clone(&self) -> Self {
1111        *self
1112    }
1113}
1114impl<T: 'static> Copy for Signal<T> {}
1115
1116impl<T: 'static> std::fmt::Debug for Signal<T> {
1117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1118        write!(f, "Signal({:?})", self.key)
1119    }
1120}
1121
1122impl<T: 'static> Signal<T> {
1123    #[track_caller]
1124    pub fn new(value: T) -> Self {
1125        Self::new_in(Scope::current(), value)
1126    }
1127
1128    /// A process-global signal: allocated in the root scope regardless of where the call
1129    /// runs, so it never dies with a transient caller. **Every lazily-initialized global
1130    /// registry must use this, not [`Signal::new`]**, because a lazy global first touched inside a
1131    /// presented cover / pushed page / `when` arm otherwise inherits that scope and is
1132    /// disposed with it, and every later read panics (the day-localization locale signal was the
1133    /// observed case).
1134    #[track_caller]
1135    pub fn global(value: T) -> Self {
1136        Self::new_in(Scope::root(), value)
1137    }
1138
1139    #[track_caller]
1140    pub fn new_in(scope: Scope, value: T) -> Self {
1141        let created_at = Location::caller();
1142        let key = with_rt(|rt| {
1143            let k = create_node(rt, NodeKind::Signal, scope.key);
1144            rt.nodes[k].value = Some(Rc::new(RefCell::new(Box::new(value) as Box<dyn Any>)));
1145            rt.nodes[k].created_at = created_at;
1146            k
1147        });
1148        Signal {
1149            key,
1150            created_at,
1151            _m: PhantomData,
1152        }
1153    }
1154
1155    /// Tracked read by reference.
1156    #[track_caller]
1157    pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1158        match self.try_with(f) {
1159            Some(r) => r,
1160            None => panic!(
1161                "day-reactive: read of disposed Signal created at {} (use try_with in closures that can outlive their scope)",
1162                self.created_at
1163            ),
1164        }
1165    }
1166
1167    pub fn try_with<R>(self, f: impl FnOnce(&T) -> R) -> Option<R> {
1168        // Clone the shared cell out so `f` runs with the runtime borrow released (it routinely
1169        // reads other signals). The value stays in the node throughout, so a re-entrant read of
1170        // This signal inside `f` succeeds instead of reporting a disposed node, and a panic in
1171        // `f` cannot strand it.
1172        let cell = with_rt(|rt| {
1173            track_read(rt, self.key);
1174            rt.nodes.get(self.key).and_then(|n| n.value.clone())
1175        })?;
1176        let value = cell.borrow();
1177        value.downcast_ref::<T>().map(f)
1178    }
1179
1180    pub fn with_untracked<R>(self, f: impl FnOnce(&T) -> R) -> R {
1181        untrack(|| self.with(f))
1182    }
1183
1184    #[track_caller]
1185    pub fn get(self) -> T
1186    where
1187        T: Clone,
1188    {
1189        self.with(|v| v.clone())
1190    }
1191
1192    pub fn try_get(self) -> Option<T>
1193    where
1194        T: Clone,
1195    {
1196        self.try_with(|v| v.clone())
1197    }
1198
1199    pub fn get_untracked(self) -> T
1200    where
1201        T: Clone,
1202    {
1203        untrack(|| self.get())
1204    }
1205
1206    /// Mark-only tracked read (subscribe without reading).
1207    pub fn track(self) {
1208        with_rt(|rt| track_read(rt, self.key));
1209    }
1210
1211    #[track_caller]
1212    pub fn set(self, value: T) {
1213        self.write_check(move |slot| {
1214            *slot = value;
1215            true
1216        });
1217    }
1218
1219    #[track_caller]
1220    pub fn set_if_changed(self, value: T)
1221    where
1222        T: PartialEq,
1223    {
1224        self.write_check(move |slot| {
1225            if *slot == value {
1226                false
1227            } else {
1228                *slot = value;
1229                true
1230            }
1231        });
1232    }
1233
1234    #[track_caller]
1235    pub fn update(self, f: impl FnOnce(&mut T)) {
1236        self.write_check(move |slot| {
1237            f(slot);
1238            true
1239        });
1240    }
1241
1242    #[track_caller]
1243    fn write_check(self, apply: impl FnOnce(&mut T) -> bool) {
1244        let alive = with_rt(|rt| rt.nodes.contains_key(self.key));
1245        if !alive {
1246            // Writes to disposed handles are defined no-ops (§4.3), warned once per callsite.
1247            let loc = Location::caller();
1248            let first = with_rt(|rt| rt.warned_writes.insert(loc as *const _));
1249            if first && cfg!(debug_assertions) {
1250                log::warn!(
1251                    "day-reactive: write at {loc} to a disposed signal (created at {}) ignored",
1252                    self.created_at
1253                );
1254            }
1255            return;
1256        }
1257        signal_write_boxed(self.key, |boxed| match boxed.downcast_mut::<T>() {
1258            Some(slot) => apply(slot),
1259            None => false,
1260        });
1261    }
1262
1263    /// A `Send` write-only handle (§3.3).
1264    pub fn setter(self) -> Setter<T>
1265    where
1266        T: Send,
1267    {
1268        Setter {
1269            key: self.key,
1270            _m: PhantomData,
1271        }
1272    }
1273}
1274
1275/// `Send` write-only handle to a signal; delivery hops to the UI thread via the main poster.
1276/// Writes after disposal are silent no-ops (§4.3).
1277pub struct Setter<T: Send + 'static> {
1278    key: NodeKey,
1279    _m: PhantomData<fn(T)>,
1280}
1281
1282impl<T: Send + 'static> Clone for Setter<T> {
1283    fn clone(&self) -> Self {
1284        *self
1285    }
1286}
1287impl<T: Send + 'static> Copy for Setter<T> {}
1288
1289impl<T: Send + 'static> Setter<T> {
1290    pub fn set(self, value: T) {
1291        let key = self.key;
1292        on_main(move || {
1293            let poster = with_rt(|rt| {
1294                let cell = rt.nodes.get(key)?.value.clone()?;
1295                {
1296                    let mut boxed = cell.try_borrow_mut().ok()?;
1297                    let slot = boxed.downcast_mut::<T>()?;
1298                    *slot = value;
1299                }
1300                let node = rt.nodes.get_mut(key)?;
1301                node.last_changed = rt.tick;
1302                rt.tick += 1;
1303                mark_observers(rt, key, NodeState::Dirty);
1304                schedule_after_write(rt)
1305            });
1306            if let Some(post) = poster {
1307                post();
1308            }
1309        });
1310    }
1311}
1312
1313// ---------------------------------------------------------------------------
1314// Memo
1315// ---------------------------------------------------------------------------
1316
1317/// Cached, equality-diffed derived value (§4.2).
1318pub struct Memo<T: 'static> {
1319    key: NodeKey,
1320    created_at: &'static Location<'static>,
1321    _m: PhantomData<*const T>,
1322}
1323
1324impl<T: 'static> Clone for Memo<T> {
1325    fn clone(&self) -> Self {
1326        *self
1327    }
1328}
1329impl<T: 'static> Copy for Memo<T> {}
1330
1331impl<T: 'static> Memo<T> {
1332    #[track_caller]
1333    pub fn new(f: impl Fn() -> T + 'static) -> Self
1334    where
1335        T: PartialEq,
1336    {
1337        Self::new_with_eq(f, |a, b| a == b)
1338    }
1339
1340    #[track_caller]
1341    pub fn new_with_eq(f: impl Fn() -> T + 'static, eq: fn(&T, &T) -> bool) -> Self {
1342        let created_at = Location::caller();
1343        // The value is stored as EqBox<T> (value + comparator together), so diffing needs no
1344        // specialization and the arena-level eq is a plain fn pointer (eqbox_eq::<T>).
1345        let key = with_rt(|rt| {
1346            let scope = rt.current_scope;
1347            create_node(rt, NodeKind::Memo, scope)
1348        });
1349        let compute: Rc<dyn Fn() -> Box<dyn Any>> =
1350            Rc::new(move || Box::new(EqBox { value: f(), eq }) as Box<dyn Any>);
1351        with_rt(|rt| {
1352            let node = &mut rt.nodes[key];
1353            node.memo_compute = Some(compute);
1354            node.memo_eq = Some(eqbox_eq::<T>);
1355            node.state = NodeState::Dirty; // lazy: computed on first read
1356            node.created_at = created_at;
1357        });
1358        Memo {
1359            key,
1360            created_at,
1361            _m: PhantomData,
1362        }
1363    }
1364
1365    #[track_caller]
1366    pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1367        refresh_memo(self.key);
1368        let value = with_rt(|rt| {
1369            track_read(rt, self.key);
1370            rt.nodes.get(self.key).and_then(|n| n.value.clone())
1371        });
1372        match value {
1373            // Shared, like `Signal::try_with`: the memo stays readable while `f` runs.
1374            Some(cell) => {
1375                let boxed = cell.borrow();
1376                boxed
1377                    .downcast_ref::<EqBox<T>>()
1378                    .map(|e| f(&e.value))
1379                    .unwrap_or_else(|| panic!("day-reactive: memo type mismatch"))
1380            }
1381            None => panic!(
1382                "day-reactive: read of disposed Memo created at {}",
1383                self.created_at
1384            ),
1385        }
1386    }
1387
1388    #[track_caller]
1389    pub fn get(self) -> T
1390    where
1391        T: Clone,
1392    {
1393        self.with(|v| v.clone())
1394    }
1395}
1396
1397/// Value + comparator stored together so memo diffing needs no specialization.
1398struct EqBox<T> {
1399    value: T,
1400    eq: fn(&T, &T) -> bool,
1401}
1402
1403fn eqbox_eq<T: 'static>(a: &dyn Any, b: &dyn Any) -> bool {
1404    match (a.downcast_ref::<EqBox<T>>(), b.downcast_ref::<EqBox<T>>()) {
1405        (Some(a), Some(b)) => (a.eq)(&a.value, &b.value),
1406        _ => false,
1407    }
1408}
1409
1410// ---------------------------------------------------------------------------
1411// Effect / bind / watch / Trigger
1412// ---------------------------------------------------------------------------
1413
1414/// A reaction that re-runs when its tracked reads change. Runs once at creation.
1415/// Every run enters the scope that created it. Ambient context and any new state or
1416/// cleanup registrations belong to that owner, including when another scope triggers it.
1417pub struct Effect;
1418
1419impl Effect {
1420    // Constructor-style registration: the reaction is owned by the current Scope (disposed
1421    // with it), so there is no handle value to return.
1422    #[allow(clippy::new_ret_no_self)]
1423    #[track_caller]
1424    pub fn new(f: impl Fn() + 'static) {
1425        create_reaction(Rc::new(f), 1);
1426    }
1427}
1428
1429#[track_caller]
1430fn create_reaction(f: Rc<dyn Fn()>, priority: u8) -> NodeKey {
1431    let created_at = Location::caller();
1432    let key = with_rt(|rt| {
1433        let scope = rt.current_scope;
1434        let k = create_node(rt, NodeKind::Reaction, scope);
1435        rt.nodes[k].reaction = Some(f);
1436        rt.nodes[k].priority = priority;
1437        rt.nodes[k].created_at = created_at;
1438        k
1439    });
1440    let reaction = with_rt(|rt| rt.nodes[key].reaction.clone());
1441    if let Some(reaction) = reaction {
1442        compute_in_owner(key, || reaction());
1443    }
1444    with_rt(|rt| {
1445        let tick = rt.tick;
1446        rt.tick += 1;
1447        if let Some(n) = rt.nodes.get_mut(key) {
1448            n.last_run = tick;
1449        }
1450    });
1451    key
1452}
1453
1454/// The binding primitive (§4.2): compute (tracked) + apply (untracked), equality-gated.
1455/// Structural priority: bindings drain before plain effects. `apply` receives the new value
1456/// by reference so `V` needs only `PartialEq` (no `Clone`).
1457#[track_caller]
1458pub fn bind<V: PartialEq + 'static>(
1459    compute: impl Fn() -> V + 'static,
1460    apply: impl Fn(&V) + 'static,
1461) {
1462    let last: RefCell<Option<V>> = RefCell::new(None);
1463    create_reaction(
1464        Rc::new(move || {
1465            let v = compute();
1466            if last.borrow().as_ref() != Some(&v) {
1467                untrack(|| apply(&v));
1468                *last.borrow_mut() = Some(v);
1469            }
1470        }),
1471        0,
1472    );
1473}
1474
1475/// `bind` pre-seeded with the value already applied at build time: the initial run does not
1476/// re-apply (pieces pass initial values through realize props; §5.2's no-duplicate-op rule).
1477#[track_caller]
1478pub fn bind_seeded<V: PartialEq + 'static>(
1479    seed: V,
1480    compute: impl Fn() -> V + 'static,
1481    apply: impl Fn(&V) + 'static,
1482) {
1483    let last: RefCell<Option<V>> = RefCell::new(Some(seed));
1484    create_reaction(
1485        Rc::new(move || {
1486            let v = compute();
1487            if last.borrow().as_ref() != Some(&v) {
1488                untrack(|| apply(&v));
1489                *last.borrow_mut() = Some(v);
1490            }
1491        }),
1492        0,
1493    );
1494}
1495
1496/// `bind` for payloads without `PartialEq`, applying on every recompute.
1497#[track_caller]
1498pub fn bind_always<V: 'static>(compute: impl Fn() -> V + 'static, apply: impl Fn(V) + 'static) {
1499    create_reaction(
1500        Rc::new(move || {
1501            let v = compute();
1502            untrack(|| apply(v));
1503        }),
1504        0,
1505    );
1506}
1507
1508/// Derive-state without effect-write loops (§4.2): `source` is tracked; `cb` runs untracked
1509/// with (new, old). Does not fire for the initial value: a "load whatever is selected"
1510/// reaction has to run once by hand first, or use [`bind`], which applies the initial value
1511/// and then every change.
1512#[track_caller]
1513pub fn watch<S: Clone + 'static>(
1514    source: impl Fn() -> S + 'static,
1515    cb: impl Fn(&S, Option<&S>) + 'static,
1516) {
1517    let prev: RefCell<Option<S>> = RefCell::new(None);
1518    create_reaction(
1519        Rc::new(move || {
1520            let new = source();
1521            let old = prev.borrow_mut().replace(new.clone());
1522            if old.is_some() {
1523                untrack(|| cb(&new, old.as_ref()));
1524            }
1525        }),
1526        1,
1527    );
1528}
1529
1530/// Data-less invalidation source.
1531#[derive(Clone, Copy)]
1532pub struct Trigger {
1533    signal: Signal<u64>,
1534}
1535
1536impl Trigger {
1537    #[track_caller]
1538    pub fn new() -> Self {
1539        Trigger {
1540            signal: Signal::new(0),
1541        }
1542    }
1543    pub fn track(self) {
1544        self.signal.track();
1545    }
1546    pub fn notify(self) {
1547        self.signal.update(|v| *v = v.wrapping_add(1));
1548    }
1549}
1550
1551impl Default for Trigger {
1552    fn default() -> Self {
1553        Self::new()
1554    }
1555}
1556
1557// ---------------------------------------------------------------------------
1558// Two-way binding surface (§5.3)
1559// ---------------------------------------------------------------------------
1560
1561/// A readable-writable value a control can bind to two-way: a `Signal`, or any projection that
1562/// knows how to read and write its own slot (day-model's `Field` is the other implementor).
1563///
1564/// The trait lives here rather than in day-pieces so a store crate can implement it without
1565/// depending on the piece vocabulary; day-pieces re-exports it, so piece code sees no move.
1566pub trait Binding<T: 'static>: Clone + 'static {
1567    /// Tracked read: the current value, subscribing the running computation to changes.
1568    fn read(&self) -> T;
1569    /// Untracked read: the current value, subscribing nothing (the reactive world's "peek").
1570    fn peek(&self) -> T;
1571    /// Write the value, waking whatever tracks it.
1572    fn write(&self, v: T);
1573    /// A live write mid-gesture (`Event::ValueChanged`): readers must follow, but nothing
1574    /// durable should key off it. Defaults to [`Binding::write`]: a plain signal has no
1575    /// notion of "durable", and a degraded backend that never commits stays correct.
1576    fn write_preview(&self, v: T) {
1577        self.write(v);
1578    }
1579    /// The settled value that ends a gesture (`Event::ValueCommitted`). Defaults to
1580    /// [`Binding::write`]; a day-model field seals its preview session here: one change
1581    /// record, one undo unit, one UPDATE for the whole drag.
1582    fn write_commit(&self, v: T) {
1583        self.write(v);
1584    }
1585    /// Seal the last preview when its control is disposed. Persistent bindings default to
1586    /// committing; scope-owned signals have already received the preview and may be gone.
1587    fn write_teardown(&self, v: T) {
1588        self.write_commit(v);
1589    }
1590}
1591
1592impl<T: Clone + 'static> Binding<T> for Signal<T> {
1593    fn read(&self) -> T {
1594        self.get()
1595    }
1596    fn peek(&self) -> T {
1597        self.get_untracked()
1598    }
1599    fn write(&self, v: T) {
1600        self.set(v);
1601    }
1602    fn write_teardown(&self, _v: T) {}
1603}
1604
1605/// The object-safe half of [`Binding`], behind [`AnyBinding`]. Its methods carry an `erased_`
1606/// prefix so a call on a `Signal` inside this crate never sees two candidates named `read`.
1607trait ErasedBinding<T: 'static> {
1608    fn erased_read(&self) -> T;
1609    fn erased_peek(&self) -> T;
1610    fn erased_write(&self, v: T);
1611    fn erased_write_preview(&self, v: T);
1612    fn erased_write_commit(&self, v: T);
1613    fn erased_write_teardown(&self, v: T);
1614}
1615
1616impl<T: 'static, B: Binding<T>> ErasedBinding<T> for B {
1617    fn erased_read(&self) -> T {
1618        Binding::read(self)
1619    }
1620    fn erased_peek(&self) -> T {
1621        Binding::peek(self)
1622    }
1623    fn erased_write(&self, v: T) {
1624        Binding::write(self, v)
1625    }
1626    fn erased_write_preview(&self, v: T) {
1627        Binding::write_preview(self, v)
1628    }
1629    fn erased_write_commit(&self, v: T) {
1630        Binding::write_commit(self, v)
1631    }
1632    fn erased_write_teardown(&self, v: T) {
1633        Binding::write_teardown(self, v)
1634    }
1635}
1636
1637/// A type-erased [`Binding`]: what a piece stores when its builder takes `impl Binding<T>`
1638/// (docs/api-style.md "Three input spellings"), so the piece itself needs no type parameter
1639/// per bound value.
1640///
1641/// `Copy`, like [`Signal`], so it captures into closures the same way: the erased binding lives
1642/// in a slot owned by the reactive scope that created it, which is the scope building the
1643/// piece. Reads and writes forward to the binding it wraps, preview and commit included.
1644pub struct AnyBinding<T: 'static> {
1645    slot: Signal<Rc<dyn ErasedBinding<T>>>,
1646}
1647
1648impl<T: 'static> Clone for AnyBinding<T> {
1649    fn clone(&self) -> Self {
1650        *self
1651    }
1652}
1653impl<T: 'static> Copy for AnyBinding<T> {}
1654
1655impl<T: 'static> AnyBinding<T> {
1656    /// Erase `binding`. Call it where the piece is built: the slot belongs to the current scope.
1657    pub fn new(binding: impl Binding<T>) -> Self {
1658        let erased: Rc<dyn ErasedBinding<T>> = Rc::new(binding);
1659        AnyBinding {
1660            slot: Signal::new(erased),
1661        }
1662    }
1663    fn inner(self) -> Rc<dyn ErasedBinding<T>> {
1664        self.slot.get_untracked()
1665    }
1666    /// Tracked read.
1667    pub fn get(self) -> T {
1668        self.inner().erased_read()
1669    }
1670    /// Tracked read, or `None` once the scope that created the binding is disposed.
1671    pub fn try_get(self) -> Option<T> {
1672        self.slot.try_get().map(|b| b.erased_read())
1673    }
1674    /// Untracked read.
1675    pub fn get_untracked(self) -> T {
1676        self.inner().erased_peek()
1677    }
1678    /// Tracked read through a projection.
1679    pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1680        let v = self.inner().erased_read();
1681        f(&v)
1682    }
1683    /// Write, waking whatever tracks the binding.
1684    pub fn set(self, v: T) {
1685        self.inner().erased_write(v)
1686    }
1687    /// Write only when the value differs from the current one.
1688    pub fn set_if_changed(self, v: T)
1689    where
1690        T: PartialEq,
1691    {
1692        let b = self.inner();
1693        if b.erased_peek() != v {
1694            b.erased_write(v);
1695        }
1696    }
1697    /// Read the current value, let `f` change it, write it back.
1698    pub fn update(self, f: impl FnOnce(&mut T)) {
1699        let b = self.inner();
1700        let mut v = b.erased_peek();
1701        f(&mut v);
1702        b.erased_write(v);
1703    }
1704}
1705
1706impl<T: 'static> Binding<T> for AnyBinding<T> {
1707    fn read(&self) -> T {
1708        self.inner().erased_read()
1709    }
1710    fn peek(&self) -> T {
1711        self.inner().erased_peek()
1712    }
1713    fn write(&self, v: T) {
1714        self.inner().erased_write(v)
1715    }
1716    fn write_preview(&self, v: T) {
1717        self.inner().erased_write_preview(v)
1718    }
1719    fn write_commit(&self, v: T) {
1720        self.inner().erased_write_commit(v)
1721    }
1722    fn write_teardown(&self, v: T) {
1723        self.inner().erased_write_teardown(v)
1724    }
1725}
1726
1727// ---------------------------------------------------------------------------
1728// Async data loading: Load + Resource (§4.5, docs/async.md)
1729// ---------------------------------------------------------------------------
1730
1731/// The lifecycle of an async-loaded value. `Failed` carries the fetcher's error as a shared
1732/// trait object so `Load` stays `Clone` for signal reads.
1733#[derive(Clone)]
1734pub enum Load<T> {
1735    Loading,
1736    Ready(T),
1737    Failed(Arc<dyn std::error::Error + Send + Sync>),
1738}
1739
1740impl<T> Load<T> {
1741    /// The loaded value, if ready.
1742    pub fn ready(&self) -> Option<&T> {
1743        match self {
1744            Load::Ready(v) => Some(v),
1745            _ => None,
1746        }
1747    }
1748    pub fn is_loading(&self) -> bool {
1749        matches!(self, Load::Loading)
1750    }
1751    pub fn is_ready(&self) -> bool {
1752        matches!(self, Load::Ready(_))
1753    }
1754    /// The failure, if the last fetch failed.
1755    pub fn error(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
1756        match self {
1757            Load::Failed(e) => Some(e.as_ref()),
1758            _ => None,
1759        }
1760    }
1761}
1762
1763impl<T: std::fmt::Debug> std::fmt::Debug for Load<T> {
1764    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1765        match self {
1766            Load::Loading => write!(f, "Loading"),
1767            Load::Ready(v) => f.debug_tuple("Ready").field(v).finish(),
1768            Load::Failed(e) => f.debug_tuple("Failed").field(&e.to_string()).finish(),
1769        }
1770    }
1771}
1772
1773/// Latest-wins bookkeeping shared by a Resource's reaction, its spawned futures, and disposal.
1774struct FetchState {
1775    generation: Cell<u64>,
1776    abort: RefCell<Option<Box<dyn FnOnce()>>>,
1777}
1778
1779impl FetchState {
1780    /// Invalidate the in-flight fetch: bump the generation first (so a completion that cannot
1781    /// be aborted still fails its check), then take-and-call the abort outside the borrow
1782    /// (dropping a future can re-enter reactive state).
1783    fn supersede(&self) -> u64 {
1784        let next = self.generation.get() + 1;
1785        self.generation.set(next);
1786        let old = self.abort.borrow_mut().take();
1787        if let Some(abort) = old {
1788            abort();
1789        }
1790        next
1791    }
1792}
1793
1794/// Declarative async data loading (§4.5): a tracked `source` whose value feeds an async
1795/// `fetcher`; the result lands in a `Signal<Load<T>>`. The source re-runs when its tracked
1796/// reads change; an unchanged source value refetches nothing, [`Resource::refetch`] always
1797/// does. Latest wins: a source change supersedes the in-flight fetch (aborting its task;
1798/// dropping any `FetchFuture` inside cancels the platform request) and a stale completion
1799/// writes nothing. Scope disposal aborts the in-flight fetch the same way.
1800///
1801/// ```ignore
1802/// let stations = Resource::new(
1803///     move || region.get(),                              // tracked: refetch on change
1804///     |region| async move { fetch_stations(region).await },
1805/// );
1806/// when(move || stations.ready(), move || station_list(stations));
1807/// ```
1808pub struct Resource<T: 'static> {
1809    state: Signal<Load<T>>,
1810    refetch_count: Signal<u64>,
1811    _not_send: PhantomData<*const T>,
1812}
1813
1814impl<T> Clone for Resource<T> {
1815    fn clone(&self) -> Self {
1816        *self
1817    }
1818}
1819impl<T> Copy for Resource<T> {}
1820
1821impl<T: 'static> Resource<T> {
1822    /// Start loading: `source` runs tracked (its signal reads become dependencies) and its
1823    /// value moves into `fetcher`'s future, which runs on the main-loop executor via the
1824    /// installed spawner, so no `Send` bound anywhere, and the future may read/write signals
1825    /// after its awaits. Infallible fetchers use `E = std::convert::Infallible`.
1826    #[track_caller]
1827    pub fn new<S, Fut, E>(
1828        source: impl Fn() -> S + 'static,
1829        fetcher: impl Fn(S) -> Fut + 'static,
1830    ) -> Resource<T>
1831    where
1832        S: Clone + PartialEq + 'static,
1833        Fut: Future<Output = Result<T, E>> + 'static,
1834        E: std::error::Error + Send + Sync + 'static,
1835    {
1836        let state: Signal<Load<T>> = Signal::new(Load::Loading);
1837        let refetch_count: Signal<u64> = Signal::new(0);
1838        let fs = Rc::new(FetchState {
1839            generation: Cell::new(0),
1840            abort: RefCell::new(None),
1841        });
1842        let reaction_fs = fs.clone();
1843        let prev: RefCell<Option<(S, u64)>> = RefCell::new(None);
1844        create_reaction(
1845            Rc::new(move || {
1846                // Tracked reads first: the refetch counter and the source. Everything else runs
1847                // untracked: the fetcher may read signals without making them dependencies.
1848                let count = refetch_count.get();
1849                let s = source();
1850                let fs = reaction_fs.clone();
1851                untrack(|| {
1852                    // Equality gate on (source value, refetch count): a rerun caused by an
1853                    // unrelated tracked read refetches nothing; refetch() always changes the
1854                    // pair, so it always fetches.
1855                    let same = prev
1856                        .borrow()
1857                        .as_ref()
1858                        .is_some_and(|(ps, pc)| ps == &s && *pc == count);
1859                    if same {
1860                        return;
1861                    }
1862                    *prev.borrow_mut() = Some((s.clone(), count));
1863                    let my_generation = fs.supersede();
1864                    state.set(Load::Loading);
1865                    let fut = fetcher(s);
1866                    let done = fs.clone();
1867                    let abort = spawn_local(Box::pin(async move {
1868                        let result = fut.await;
1869                        if done.generation.get() != my_generation {
1870                            return; // superseded while in flight; latest wins
1871                        }
1872                        done.abort.borrow_mut().take(); // completed: the stored abort is dead
1873                        match result {
1874                            Ok(v) => state.set(Load::Ready(v)),
1875                            Err(e) => state.set(Load::Failed(Arc::new(e))),
1876                        }
1877                    }));
1878                    // Eager-poll ordering: the spawner polls once before returning, so a
1879                    // synchronously-ready fetcher has already completed here; storing its
1880                    // abort is harmless only because the spawner contract makes aborting a
1881                    // finished task a no-op (this line is why that contract exists).
1882                    *fs.abort.borrow_mut() = Some(abort);
1883                });
1884            }),
1885            1,
1886        );
1887        // Disposal: supersede + abort the in-flight task. (A completion that slipped through
1888        // would write to disposed signals, the defined no-op, but aborting frees the platform
1889        // request immediately.)
1890        let cleanup_fs = fs;
1891        Scope::current().on_cleanup(move || {
1892            cleanup_fs.supersede();
1893        });
1894        Resource {
1895            state,
1896            refetch_count,
1897            _not_send: PhantomData,
1898        }
1899    }
1900
1901    /// The underlying state signal (tracked reads, `when(move || …)` guards, `each` sources).
1902    pub fn signal(self) -> Signal<Load<T>> {
1903        self.state
1904    }
1905
1906    /// The current load state (tracked).
1907    pub fn get(self) -> Load<T>
1908    where
1909        T: Clone,
1910    {
1911        self.state.get()
1912    }
1913
1914    /// Read the current load state by reference (tracked).
1915    pub fn with<R>(self, f: impl FnOnce(&Load<T>) -> R) -> R {
1916        self.state.with(f)
1917    }
1918
1919    /// Whether a fetch is in flight (tracked).
1920    pub fn loading(self) -> bool {
1921        self.with(Load::is_loading)
1922    }
1923
1924    /// Whether a value is ready (tracked): `when(move || r.ready(), …)`.
1925    pub fn ready(self) -> bool {
1926        self.with(Load::is_ready)
1927    }
1928
1929    /// Force a refetch with the current source value (even if unchanged).
1930    pub fn refetch(self) {
1931        self.refetch_count.update(|c| *c = c.wrapping_add(1));
1932    }
1933}
1934
1935// ---------------------------------------------------------------------------
1936// Tests
1937// ---------------------------------------------------------------------------
1938
1939#[cfg(test)]
1940mod tests {
1941    use super::*;
1942    use std::cell::Cell as StdCell;
1943    use std::rc::Rc;
1944
1945    fn counter() -> (Rc<StdCell<u32>>, impl Fn()) {
1946        let c = Rc::new(StdCell::new(0));
1947        let c2 = c.clone();
1948        (c, move || c2.set(c2.get() + 1))
1949    }
1950
1951    #[test]
1952    fn signal_get_set() {
1953        let s = Signal::new(1);
1954        assert_eq!(s.get(), 1);
1955        s.set(5);
1956        assert_eq!(s.get(), 5);
1957        s.update(|v| *v += 1);
1958        assert_eq!(s.get(), 6);
1959    }
1960
1961    #[test]
1962    fn signal_teardown_does_not_write_after_scope_disposal() {
1963        let scope = Scope::child();
1964        let warned = with_rt(|rt| rt.warned_writes.len());
1965        scope.enter(|| {
1966            let signal = Signal::new(String::new());
1967            signal.write_preview("Fixture final edit".into());
1968            assert_eq!(signal.peek(), "Fixture final edit");
1969            Scope::current().on_cleanup(move || {
1970                signal.write_teardown("Fixture final edit".into());
1971            });
1972        });
1973        scope.dispose();
1974        assert_eq!(with_rt(|rt| rt.warned_writes.len()), warned);
1975    }
1976
1977    #[test]
1978    fn persistent_binding_teardown_seals_preview() {
1979        #[derive(Clone)]
1980        struct FixtureBinding(Rc<RefCell<Vec<String>>>);
1981        impl Binding<String> for FixtureBinding {
1982            fn read(&self) -> String {
1983                String::new()
1984            }
1985            fn peek(&self) -> String {
1986                self.read()
1987            }
1988            fn write(&self, value: String) {
1989                self.0.borrow_mut().push(value);
1990            }
1991            fn write_preview(&self, _value: String) {}
1992        }
1993        let committed = Rc::new(RefCell::new(Vec::new()));
1994        let binding = FixtureBinding(committed.clone());
1995        let scope = Scope::child();
1996        scope.enter(|| {
1997            binding.write_preview("Fixture edit".into());
1998            Scope::current().on_cleanup(move || binding.write_teardown("Fixture edit".into()));
1999        });
2000        assert!(committed.borrow().is_empty());
2001        scope.dispose();
2002        assert_eq!(*committed.borrow(), ["Fixture edit"]);
2003    }
2004
2005    #[test]
2006    fn effect_reruns_on_change() {
2007        let s = Signal::new(1);
2008        let (count, bump) = counter();
2009        Effect::new(move || {
2010            s.track();
2011            bump();
2012        });
2013        assert_eq!(count.get(), 1); // initial run
2014        batch(|| s.set(2));
2015        assert_eq!(count.get(), 2);
2016        batch(|| s.set(3));
2017        assert_eq!(count.get(), 3);
2018    }
2019
2020    #[test]
2021    fn batch_coalesces() {
2022        let s = Signal::new(0);
2023        let (count, bump) = counter();
2024        Effect::new(move || {
2025            s.track();
2026            bump();
2027        });
2028        batch(|| {
2029            s.set(1);
2030            s.set(2);
2031            s.set(3);
2032        });
2033        assert_eq!(count.get(), 2); // initial + one drain
2034        assert_eq!(s.get(), 3);
2035    }
2036
2037    #[test]
2038    fn set_if_changed_no_op() {
2039        let s = Signal::new(7);
2040        let (count, bump) = counter();
2041        Effect::new(move || {
2042            s.track();
2043            bump();
2044        });
2045        batch(|| s.set_if_changed(7));
2046        assert_eq!(count.get(), 1); // no re-run
2047    }
2048
2049    #[test]
2050    fn memo_caches_and_diffs() {
2051        let s = Signal::new(1);
2052        let computes = Rc::new(StdCell::new(0));
2053        let c2 = computes.clone();
2054        let doubled = Memo::new(move || {
2055            c2.set(c2.get() + 1);
2056            s.get() * 2
2057        });
2058        assert_eq!(doubled.get(), 2);
2059        assert_eq!(doubled.get(), 2);
2060        assert_eq!(computes.get(), 1); // cached
2061        let (effect_runs, bump) = counter();
2062        Effect::new(move || {
2063            let _ = doubled.get();
2064            bump();
2065        });
2066        assert_eq!(effect_runs.get(), 1);
2067        batch(|| s.set(1)); // same value → memo recomputes? signal changed, memo recomputes, same output
2068        // memo output unchanged (1*2 == 2)? s was already 1 → set(1) marks dirty (set is not diffed)
2069        assert_eq!(effect_runs.get(), 1); // memo diffing gates the effect
2070        batch(|| s.set(5));
2071        assert_eq!(doubled.get(), 10);
2072        assert_eq!(effect_runs.get(), 2);
2073    }
2074
2075    #[test]
2076    fn bind_applies_on_change_only() {
2077        let s = Signal::new(1);
2078        let applied: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2079        let a2 = applied.clone();
2080        bind(
2081            move || s.get().to_string(),
2082            move |v| a2.borrow_mut().push(v.clone()),
2083        );
2084        assert_eq!(*applied.borrow(), vec!["1"]);
2085        batch(|| s.set(2));
2086        assert_eq!(*applied.borrow(), vec!["1", "2"]);
2087        batch(|| s.update(|v| *v = 2)); // update always marks; bind's eq gate stops the apply
2088        assert_eq!(*applied.borrow(), vec!["1", "2"]);
2089    }
2090
2091    #[test]
2092    fn watch_skips_initial_and_passes_old() {
2093        let s = Signal::new(10);
2094        type Log = Rc<RefCell<Vec<(i32, Option<i32>)>>>;
2095        let log: Log = Rc::new(RefCell::new(Vec::new()));
2096        let l2 = log.clone();
2097        watch(
2098            move || s.get(),
2099            move |new, old| l2.borrow_mut().push((*new, old.copied())),
2100        );
2101        assert!(log.borrow().is_empty());
2102        batch(|| s.set(11));
2103        assert_eq!(*log.borrow(), vec![(11, Some(10))]);
2104    }
2105
2106    #[test]
2107    fn scope_dispose_stops_effects_and_write_is_noop() {
2108        let s = Signal::new(0);
2109        let (count, bump) = counter();
2110        let scope = Scope::child();
2111        let inner = scope.enter(|| {
2112            let inner = Signal::new(1);
2113            Effect::new(move || {
2114                s.track();
2115                bump();
2116            });
2117            inner
2118        });
2119        assert_eq!(count.get(), 1);
2120        batch(|| s.set(1));
2121        assert_eq!(count.get(), 2);
2122        scope.dispose();
2123        batch(|| s.set(2));
2124        assert_eq!(count.get(), 2); // effect gone
2125        inner.set(9); // silent no-op
2126        assert_eq!(inner.try_get(), None);
2127    }
2128
2129    #[test]
2130    fn dispose_during_drain_skips_pending() {
2131        let s = Signal::new(0);
2132        let scope = Scope::child();
2133        let (count, bump) = counter();
2134        // Owner effect (created first in outer scope) disposes the child scope when s becomes 1.
2135        let scope_cell = Rc::new(StdCell::new(Some(scope)));
2136        let sc = scope_cell.clone();
2137        Effect::new(move || {
2138            if s.get() == 1
2139                && let Some(scope) = sc.take()
2140            {
2141                scope.dispose();
2142            }
2143        });
2144        scope.enter(|| {
2145            Effect::new(move || {
2146                s.track();
2147                bump();
2148            });
2149        });
2150        assert_eq!(count.get(), 1);
2151        batch(|| s.set(1));
2152        // Owner ran first (created earlier, same depth? owner depth 0 < child depth 1) and
2153        // disposed the child → child effect must not run again.
2154        assert_eq!(count.get(), 1);
2155    }
2156
2157    #[test]
2158    fn fixpoint_extends_drain() {
2159        let a = Signal::new(0);
2160        let b = Signal::new(0);
2161        let (count, bump) = counter();
2162        Effect::new(move || {
2163            if a.get() == 1 {
2164                b.set(1); // write during drain extends the drain
2165            }
2166        });
2167        Effect::new(move || {
2168            b.track();
2169            bump();
2170        });
2171        assert_eq!(count.get(), 1);
2172        batch(|| a.set(1));
2173        assert_eq!(count.get(), 2);
2174        assert_eq!(b.get(), 1);
2175    }
2176
2177    // Debug-only: release warns-and-defers instead of panicking (the release
2178    // side is pinned by `unwind_safety_tests::rerun_cap_defers_instead_of_killing_the_binding`).
2179    #[cfg(debug_assertions)]
2180    #[test]
2181    #[should_panic(expected = "re-ran more than")]
2182    fn rerun_cap_panics_in_debug() {
2183        let s = Signal::new(0);
2184        Effect::new(move || {
2185            let v = s.get();
2186            s.set(v + 1); // classic cycle
2187        });
2188        batch(|| s.set(1));
2189    }
2190
2191    #[test]
2192    fn context_provides_down() {
2193        #[derive(Clone, PartialEq, Debug)]
2194        struct Theme(u32);
2195        let scope = Scope::child();
2196        scope.provide(Theme(7));
2197        let child = scope.create_child();
2198        assert_eq!(child.use_context::<Theme>(), Some(Theme(7)));
2199        scope.dispose();
2200    }
2201
2202    #[test]
2203    fn trigger_notifies() {
2204        let t = Trigger::new();
2205        let (count, bump) = counter();
2206        Effect::new(move || {
2207            t.track();
2208            bump();
2209        });
2210        batch(|| t.notify());
2211        assert_eq!(count.get(), 2);
2212    }
2213
2214    #[test]
2215    fn turn_end_runs_after_fixpoint() {
2216        let s = Signal::new(0);
2217        let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2218        let o1 = order.clone();
2219        Effect::new(move || {
2220            s.track();
2221            o1.borrow_mut().push("effect");
2222        });
2223        let o2 = order.clone();
2224        on_turn_end(move || o2.borrow_mut().push("turn-end"));
2225        order.borrow_mut().clear();
2226        batch(|| s.set(1));
2227        assert_eq!(*order.borrow(), vec!["effect", "turn-end"]);
2228    }
2229
2230    #[test]
2231    fn at_turn_end_waits_for_the_turn_and_runs_once() {
2232        let s = Signal::new(0);
2233        let order: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2234        // Outside a turn: now.
2235        let o = order.clone();
2236        at_turn_end(move || o.borrow_mut().push("now".into()));
2237        assert_eq!(*order.borrow(), vec!["now".to_string()]);
2238        order.borrow_mut().clear();
2239        // Inside a batch: after the drain, and before the standing hooks.
2240        let o1 = order.clone();
2241        Effect::new(move || {
2242            let v = s.get();
2243            o1.borrow_mut().push(format!("effect {v}"));
2244        });
2245        let o2 = order.clone();
2246        on_turn_end(move || o2.borrow_mut().push("standing".into()));
2247        order.borrow_mut().clear();
2248        let o3 = order.clone();
2249        batch(|| {
2250            at_turn_end(move || o3.borrow_mut().push("once".into()));
2251            s.set(1);
2252        });
2253        assert_eq!(*order.borrow(), vec!["effect 1", "once", "standing"]);
2254        // A batch with no reactive work still ends its turn for a deferred callback.
2255        order.borrow_mut().clear();
2256        let o4 = order.clone();
2257        batch(|| at_turn_end(move || o4.borrow_mut().push("quiet".into())));
2258        assert_eq!(*order.borrow(), vec!["quiet", "standing"]);
2259    }
2260
2261    #[test]
2262    fn bindings_run_before_effects() {
2263        let s = Signal::new(0);
2264        let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2265        let o1 = order.clone();
2266        // Plain effect created first (lower seq); priority must still put the bind first.
2267        Effect::new(move || {
2268            s.track();
2269            o1.borrow_mut().push("effect");
2270        });
2271        let o2 = order.clone();
2272        bind(move || s.get(), move |_| o2.borrow_mut().push("bind"));
2273        order.borrow_mut().clear();
2274        batch(|| s.set(1));
2275        assert_eq!(*order.borrow(), vec!["bind", "effect"]);
2276    }
2277}
2278
2279#[cfg(test)]
2280mod resource_tests {
2281    use super::*;
2282    use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
2283
2284    // ---- test executor: mirrors day::task's shape (eager first poll; abort = remove+drop;
2285    // pump() re-polls whatever is still pending). `ABORTED` records aborts of still-pending
2286    // tasks, the probe the latest-wins/disposal tests read. All thread-local: each #[test]
2287    // thread gets a fresh Runtime and a fresh executor.
2288
2289    thread_local! {
2290        static TEST_TASKS: RefCell<Vec<(u64, Option<LocalBoxFuture>)>> =
2291            const { RefCell::new(Vec::new()) };
2292        static NEXT_ID: Cell<u64> = const { Cell::new(1) };
2293        static ABORTED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
2294        static INSTALLED: Cell<bool> = const { Cell::new(false) };
2295    }
2296
2297    fn noop_waker() -> Waker {
2298        fn raw() -> RawWaker {
2299            RawWaker::new(std::ptr::null(), &VT)
2300        }
2301        static VT: RawWakerVTable = RawWakerVTable::new(|_| raw(), |_| {}, |_| {}, |_| {});
2302        // SAFETY: every vtable entry ignores the data pointer.
2303        unsafe { Waker::from_raw(raw()) }
2304    }
2305
2306    fn poll_one(fut: &mut LocalBoxFuture) -> bool {
2307        let waker = noop_waker();
2308        let mut cx = Context::from_waker(&waker);
2309        fut.as_mut().poll(&mut cx).is_ready()
2310    }
2311
2312    fn install_test_spawner() {
2313        if INSTALLED.with(|c| c.replace(true)) {
2314            return;
2315        }
2316        install_spawner(|mut fut| {
2317            let id = NEXT_ID.with(|c| {
2318                let v = c.get();
2319                c.set(v + 1);
2320                v
2321            });
2322            if !poll_one(&mut fut) {
2323                TEST_TASKS.with(|t| t.borrow_mut().push((id, Some(fut))));
2324            }
2325            Box::new(move || {
2326                let removed = TEST_TASKS.with(|t| {
2327                    let mut t = t.borrow_mut();
2328                    let before = t.len();
2329                    t.retain(|(i, _)| *i != id);
2330                    before != t.len()
2331                });
2332                if removed {
2333                    ABORTED.with(|a| a.borrow_mut().push(id));
2334                }
2335            })
2336        });
2337    }
2338
2339    fn aborted_count() -> usize {
2340        ABORTED.with(|a| a.borrow().len())
2341    }
2342
2343    /// Re-poll every pending task once (completions drop out).
2344    fn pump() {
2345        let ids: Vec<u64> = TEST_TASKS.with(|t| t.borrow().iter().map(|(i, _)| *i).collect());
2346        for id in ids {
2347            let fut = TEST_TASKS.with(|t| {
2348                t.borrow_mut()
2349                    .iter_mut()
2350                    .find(|(i, _)| *i == id)
2351                    .and_then(|(_, s)| s.take())
2352            });
2353            let Some(mut fut) = fut else { continue };
2354            if poll_one(&mut fut) {
2355                TEST_TASKS.with(|t| t.borrow_mut().retain(|(i, _)| *i != id));
2356            } else {
2357                TEST_TASKS.with(|t| {
2358                    if let Some((_, s)) = t.borrow_mut().iter_mut().find(|(i, _)| *i == id) {
2359                        *s = Some(fut);
2360                    }
2361                });
2362            }
2363        }
2364        // Completions wrote signals; with no scheduler installed a test must drain explicitly
2365        // (the production main loop drains via the installed scheduler).
2366        flush_sync();
2367    }
2368
2369    type Slot<T> = Rc<RefCell<Option<Result<T, TestErr>>>>;
2370
2371    /// A future the test resolves by hand (fill the slot, then `pump()`); no waker wiring, since
2372    /// pump re-polls everything.
2373    fn manual_future<T: 'static>(slot: Slot<T>) -> impl Future<Output = Result<T, TestErr>> {
2374        std::future::poll_fn(move |_| match slot.borrow_mut().take() {
2375            Some(r) => Poll::Ready(r),
2376            None => Poll::Pending,
2377        })
2378    }
2379
2380    #[derive(Debug)]
2381    struct TestErr(&'static str);
2382    impl std::fmt::Display for TestErr {
2383        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2384            write!(f, "{}", self.0)
2385        }
2386    }
2387    impl std::error::Error for TestErr {}
2388
2389    #[test]
2390    fn resource_sync_fetcher_is_ready_immediately() {
2391        install_test_spawner();
2392        let r = Resource::new(|| (), |_| async { Ok::<_, std::convert::Infallible>(42) });
2393        assert!(r.ready());
2394        assert_eq!(r.with(|l| l.ready().copied()), Some(42));
2395    }
2396
2397    #[test]
2398    fn resource_loading_then_ready() {
2399        install_test_spawner();
2400        let slot: Slot<i32> = Rc::new(RefCell::new(None));
2401        let s2 = slot.clone();
2402        let r = Resource::new(move || (), move |_| manual_future(s2.clone()));
2403        assert!(r.loading());
2404        *slot.borrow_mut() = Some(Ok(7));
2405        pump();
2406        assert_eq!(r.with(|l| l.ready().copied()), Some(7));
2407    }
2408
2409    #[test]
2410    fn resource_failed_preserves_error() {
2411        install_test_spawner();
2412        let r = Resource::new(|| (), |_| async { Err::<i32, _>(TestErr("boom")) });
2413        assert!(!r.ready());
2414        assert_eq!(
2415            r.with(|l| l.error().map(|e| e.to_string())),
2416            Some("boom".into())
2417        );
2418    }
2419
2420    #[test]
2421    fn resource_refetches_on_source_change() {
2422        install_test_spawner();
2423        let src = Signal::new(1i32);
2424        let fetches = Rc::new(Cell::new(0));
2425        let f = fetches.clone();
2426        let r = Resource::new(
2427            move || src.get(),
2428            move |v| {
2429                f.set(f.get() + 1);
2430                async move { Ok::<_, TestErr>(v * 10) }
2431            },
2432        );
2433        assert_eq!(fetches.get(), 1);
2434        assert_eq!(r.with(|l| l.ready().copied()), Some(10));
2435        batch(|| src.set(2));
2436        assert_eq!(fetches.get(), 2);
2437        assert_eq!(r.with(|l| l.ready().copied()), Some(20));
2438    }
2439
2440    #[test]
2441    fn resource_source_equality_gates() {
2442        install_test_spawner();
2443        let a = Signal::new(1i32);
2444        let b = Signal::new(10i32);
2445        let fetches = Rc::new(Cell::new(0));
2446        let f = fetches.clone();
2447        let r = Resource::new(
2448            move || {
2449                let _ = b.get(); // tracked but not part of the source value
2450                a.get()
2451            },
2452            move |v| {
2453                f.set(f.get() + 1);
2454                async move { Ok::<_, TestErr>(v) }
2455            },
2456        );
2457        assert_eq!(fetches.get(), 1);
2458        batch(|| b.set(20)); // reruns the reaction; the source value is unchanged → no refetch
2459        assert_eq!(fetches.get(), 1);
2460        assert_eq!(r.with(|l| l.ready().copied()), Some(1));
2461        batch(|| a.set(2)); // the value changed → refetch
2462        assert_eq!(fetches.get(), 2);
2463    }
2464
2465    #[test]
2466    fn resource_refetch_forces() {
2467        install_test_spawner();
2468        let fetches = Rc::new(Cell::new(0));
2469        let f = fetches.clone();
2470        let r = Resource::new(
2471            || (),
2472            move |_| {
2473                f.set(f.get() + 1);
2474                async { Ok::<_, TestErr>(0) }
2475            },
2476        );
2477        assert_eq!(fetches.get(), 1);
2478        batch(|| r.refetch()); // same source value; the refetch counter forces it past the gate
2479        assert_eq!(fetches.get(), 2);
2480    }
2481
2482    #[test]
2483    fn resource_latest_wins() {
2484        install_test_spawner();
2485        let src = Signal::new(1i32);
2486        let slots: Rc<RefCell<Vec<Slot<i32>>>> = Rc::new(RefCell::new(Vec::new()));
2487        let sl = slots.clone();
2488        let r = Resource::new(
2489            move || src.get(),
2490            move |_| {
2491                let slot: Slot<i32> = Rc::new(RefCell::new(None));
2492                sl.borrow_mut().push(slot.clone());
2493                manual_future(slot)
2494            },
2495        );
2496        assert!(r.loading());
2497        let before = aborted_count();
2498        batch(|| src.set(2)); // supersede generation 1 while it is in flight
2499        assert_eq!(aborted_count(), before + 1, "the stale task was aborted");
2500        // Resolving generation 1 anyway must change nothing (its future is gone).
2501        *slots.borrow()[0].borrow_mut() = Some(Ok(111));
2502        pump();
2503        assert!(r.loading(), "a stale result writes nothing");
2504        *slots.borrow()[1].borrow_mut() = Some(Ok(222));
2505        pump();
2506        assert_eq!(r.with(|l| l.ready().copied()), Some(222));
2507    }
2508
2509    #[test]
2510    fn resource_scope_disposal_aborts() {
2511        install_test_spawner();
2512        let scope = Scope::child();
2513        let slot: Slot<i32> = Rc::new(RefCell::new(None));
2514        let s2 = slot.clone();
2515        let r = scope.enter(|| Resource::new(move || (), move |_| manual_future(s2.clone())));
2516        assert!(r.loading());
2517        let before = aborted_count();
2518        scope.dispose();
2519        assert_eq!(aborted_count(), before + 1, "disposal aborted the fetch");
2520        // Resolving afterwards is inert: the future is gone; nothing pends; no panic.
2521        *slot.borrow_mut() = Some(Ok(1));
2522        pump();
2523    }
2524
2525    #[test]
2526    fn resource_ready_is_tracked() {
2527        install_test_spawner();
2528        let slot: Slot<i32> = Rc::new(RefCell::new(None));
2529        let s2 = slot.clone();
2530        let r = Resource::new(move || (), move |_| manual_future(s2.clone()));
2531        let runs = Rc::new(Cell::new(0));
2532        let rn = runs.clone();
2533        Effect::new(move || {
2534            let _ = r.ready();
2535            rn.set(rn.get() + 1);
2536        });
2537        assert_eq!(runs.get(), 1);
2538        *slot.borrow_mut() = Some(Ok(1));
2539        pump();
2540        assert!(runs.get() >= 2, "ready() re-ran the effect on completion");
2541    }
2542
2543    #[test]
2544    #[should_panic(expected = "no spawner installed")]
2545    fn spawner_missing_panics() {
2546        // No test spawner installed: this test thread's Runtime has none.
2547        let _r = Resource::new(|| (), |_| async { Ok::<_, std::convert::Infallible>(1) });
2548    }
2549}
2550
2551#[cfg(test)]
2552mod unwind_safety_tests {
2553    use super::*;
2554
2555    /// Run `f`, swallowing a panic, with the panic hook silenced so the test output stays clean.
2556    fn contained(f: impl FnOnce() + std::panic::UnwindSafe) {
2557        let prev = std::panic::take_hook();
2558        std::panic::set_hook(Box::new(|_| {}));
2559        let r = std::panic::catch_unwind(f);
2560        std::panic::set_hook(prev);
2561        assert!(r.is_err(), "expected the closure to panic");
2562    }
2563
2564    /// A panic inside `Scope::enter` must not leave the runtime parented to the transient scope.
2565    /// Before the guard, every later `Signal::new` landed in a disposed scope and its first read
2566    /// panicked with a misleading "read of disposed Signal".
2567    #[test]
2568    fn panic_in_scope_enter_restores_current_scope() {
2569        let before = with_rt(|rt| rt.current_scope);
2570        let scope = Scope::detached();
2571        contained(|| scope.enter(|| panic!("boom in enter")));
2572        assert_eq!(with_rt(|rt| rt.current_scope), before, "scope not restored");
2573        // The real symptom: a signal created afterwards must still be alive and readable.
2574        let s = Signal::new(7u32);
2575        assert_eq!(s.get(), 7);
2576    }
2577
2578    /// A panic inside `untrack` must pop its `None` observer, or dependency tracking stays off
2579    /// for the rest of the process and nothing ever updates again.
2580    /// A panic inside an effect's own closure (contained by a backend trampoline) must pop
2581    /// the effect's observer frame during unwind; a stranded frame would attribute every
2582    /// later read to the dead run, even through a user's own `catch_unwind`, without any
2583    /// call to `recover_from_panic`.
2584    #[test]
2585    fn panic_in_effect_body_pops_its_observer_frame() {
2586        let depth = with_rt(|rt| rt.observers.len());
2587        let boom = Signal::new(false);
2588        Effect::new(move || {
2589            if boom.get() {
2590                panic!("effect boom");
2591            }
2592        });
2593        assert_eq!(with_rt(|rt| rt.observers.len()), depth);
2594        contained(|| batch(|| boom.set(true)));
2595        assert_eq!(
2596            with_rt(|rt| rt.observers.len()),
2597            depth,
2598            "observer frame stranded by the panicking effect run"
2599        );
2600        recover_from_panic(); // clear draining/pending for the tests that follow
2601    }
2602
2603    #[test]
2604    fn panic_in_untrack_restores_tracking() {
2605        let depth = with_rt(|rt| rt.observers.len());
2606        contained(|| untrack(|| panic!("boom in untrack")));
2607        assert_eq!(with_rt(|rt| rt.observers.len()), depth, "observer stranded");
2608
2609        // Tracking still works: an effect re-runs when its source changes.
2610        let src = Signal::new(0i32);
2611        let runs = Rc::new(RefCell::new(0));
2612        let r2 = runs.clone();
2613        Effect::new(move || {
2614            src.get();
2615            *r2.borrow_mut() += 1;
2616        });
2617        flush_sync();
2618        let before = *runs.borrow();
2619        src.set(1);
2620        flush_sync();
2621        assert!(
2622            *runs.borrow() > before,
2623            "effect did not re-run — tracking is off"
2624        );
2625    }
2626
2627    /// A panic inside `batch` must not strand `batch_depth`, which would stop every later write
2628    /// from scheduling a drain.
2629    #[test]
2630    fn panic_in_batch_restores_depth() {
2631        let depth = with_rt(|rt| rt.batch_depth);
2632        contained(|| batch(|| panic!("boom in batch")));
2633        assert_eq!(with_rt(|rt| rt.batch_depth), depth, "batch depth stranded");
2634    }
2635
2636    /// A panic inside a `with` closure must not consume the signal's value. Before the value was
2637    /// shared it was taken out for the closure's duration, so an unwind lost it permanently and
2638    /// the signal was dead for the rest of the process.
2639    #[test]
2640    fn panic_in_with_leaves_the_value_intact() {
2641        let s = Signal::new(String::from("intact"));
2642        contained(|| s.with(|_| panic!("boom in with")));
2643        assert_eq!(s.with(|v| v.clone()), "intact");
2644    }
2645
2646    /// Reading a signal from inside its own `with` closure now works. It used to find the hole
2647    /// left by the take and panic with "read of disposed Signal".
2648    #[test]
2649    fn reentrant_read_inside_with_succeeds() {
2650        let s = Signal::new(5u32);
2651        let doubled = s.with(|outer| *outer + s.with(|inner| *inner));
2652        assert_eq!(doubled, 10);
2653        assert_eq!(
2654            s.with(|v| *v),
2655            5,
2656            "value still in place after the nested read"
2657        );
2658    }
2659
2660    /// Two different signals read inside one another's closures: the ordinary case, and the
2661    /// reason the closure must run with the runtime borrow released.
2662    #[test]
2663    fn nested_reads_of_distinct_signals_succeed() {
2664        let a = Signal::new(2u32);
2665        let b = Signal::new(3u32);
2666        assert_eq!(a.with(|x| *x * b.with(|y| *y)), 6);
2667    }
2668
2669    /// Writing a signal while a read of it is in flight is reported instead of silently lost.
2670    #[test]
2671    fn write_during_read_panics_with_a_clear_message() {
2672        let s = Signal::new(1u32);
2673        let prev = std::panic::take_hook();
2674        std::panic::set_hook(Box::new(|_| {}));
2675        let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2676            s.with(|_| s.set(2));
2677        }));
2678        std::panic::set_hook(prev);
2679        let payload = r.unwrap_err();
2680        // A `panic!` with no format arguments carries a `&'static str`, not a `String`.
2681        let msg = payload
2682            .downcast_ref::<&str>()
2683            .map(|s| s.to_string())
2684            .or_else(|| payload.downcast_ref::<String>().cloned())
2685            .expect("panic payload should be a string");
2686        assert!(
2687            msg.contains("in flight") && msg.contains("Signal"),
2688            "message should name the cause, got: {msg}"
2689        );
2690    }
2691
2692    /// Release builds must survive a reactive cycle: the capped effect is skipped for the
2693    /// rest of the drain but re-arms on the next source write; it must not be permanently
2694    /// disabled. Release-only because the same cycle panics under
2695    /// `debug_assertions`; run via `cargo test --release -p day-reactive`.
2696    #[cfg(not(debug_assertions))]
2697    #[test]
2698    fn rerun_cap_defers_instead_of_killing_the_binding() {
2699        let s = Signal::new(0u32);
2700        let runs = std::rc::Rc::new(std::cell::Cell::new(0u32));
2701        let r2 = runs.clone();
2702        Effect::new(move || {
2703            let v = s.get();
2704            r2.set(r2.get() + 1);
2705            if v < 1_000_000 {
2706                s.set(v + 1); // self-sustaining cycle: trips the cap every drain
2707            }
2708        });
2709        flush_sync();
2710        let after_cycle = runs.get();
2711        assert!(
2712            after_cycle <= RERUN_CAP + 1,
2713            "cap did not bound the drain: {after_cycle} runs"
2714        );
2715
2716        // A fresh external write must re-arm the effect with a new per-drain budget.
2717        batch(|| s.set(2_000_000)); // past the cycle threshold: the effect runs once, quietly
2718        assert_eq!(
2719            runs.get(),
2720            after_cycle + 1,
2721            "binding stayed dead after hitting the re-run cap"
2722        );
2723    }
2724}
2725
2726#[cfg(test)]
2727mod owner_scope_tests {
2728    use super::*;
2729
2730    #[test]
2731    fn reactions_and_lazy_memos_keep_their_owner_and_restore_the_caller() {
2732        let outer = Scope::child();
2733        outer.provide("outer fixture");
2734        let first = outer.create_child();
2735        let second = outer.create_child();
2736        first.provide("first fixture");
2737        second.provide("second fixture");
2738        let source = Signal::new(0);
2739        let seen = Rc::new(RefCell::new(Vec::new()));
2740        let lazy = first.enter(|| {
2741            Memo::new(move || {
2742                (
2743                    source.get(),
2744                    Scope::current().use_context::<&str>().unwrap(),
2745                )
2746            })
2747        });
2748        let nested = second.enter(|| {
2749            Memo::new(move || (lazy.get(), Scope::current().use_context::<&str>().unwrap()))
2750        });
2751        second.enter(|| assert_eq!(lazy.get(), (0, "first fixture")));
2752        assert_eq!(nested.get(), ((0, "first fixture"), "second fixture"));
2753        for (scope, name) in [(first, "first fixture"), (second, "second fixture")] {
2754            let seen = seen.clone();
2755            scope.enter(|| {
2756                Effect::new(move || {
2757                    seen.borrow_mut()
2758                        .push((source.get(), Scope::current().use_context::<&str>()));
2759                    assert_eq!(Scope::current().use_context::<&str>(), Some(name));
2760                })
2761            });
2762        }
2763        second.enter(|| {
2764            batch(|| source.set(1));
2765            assert_eq!(
2766                Scope::current().use_context::<&str>(),
2767                Some("second fixture")
2768            );
2769        });
2770        assert_eq!(nested.get(), ((1, "first fixture"), "second fixture"));
2771        assert_eq!(seen.borrow().len(), 4);
2772        outer.dispose();
2773        batch(|| source.set(2));
2774        assert_eq!(seen.borrow().len(), 4, "disposed reactions must not run");
2775    }
2776
2777    #[test]
2778    fn watches_allocate_state_and_cleanup_in_their_owner() {
2779        let owner = Scope::child();
2780        let trigger = Signal::new(0);
2781        let allocated = Rc::new(Cell::new(None::<Signal<i32>>));
2782        let cleaned = Rc::new(Cell::new(0));
2783        owner.enter(|| {
2784            let allocated = allocated.clone();
2785            let cleaned = cleaned.clone();
2786            watch(
2787                move || trigger.get(),
2788                move |value, _| {
2789                    allocated.set(Some(Signal::new(*value)));
2790                    let cleaned = cleaned.clone();
2791                    Scope::current().on_cleanup(move || cleaned.set(cleaned.get() + 1));
2792                },
2793            );
2794        });
2795        batch(|| trigger.set(1));
2796        let state = allocated.get().unwrap();
2797        assert_eq!(state.get(), 1);
2798        owner.dispose();
2799        assert_eq!(cleaned.get(), 1);
2800        assert!(state.try_get().is_none());
2801    }
2802
2803    #[test]
2804    fn panic_in_owned_computations_restores_scope_and_tracking() {
2805        let owner = Scope::child();
2806        owner.provide("owner fixture");
2807        let caller = Scope::child();
2808        caller.provide("caller fixture");
2809        let trigger = Signal::new(false);
2810        let memo = owner.enter(|| {
2811            Memo::new(move || {
2812                assert_eq!(
2813                    Scope::current().use_context::<&str>(),
2814                    Some("owner fixture")
2815                );
2816                assert!(!trigger.get(), "synthetic memo failure");
2817                7
2818            })
2819        });
2820        assert_eq!(memo.get(), 7);
2821        batch(|| trigger.set(true));
2822        caller.enter(|| {
2823            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| memo.get()));
2824            assert!(result.is_err());
2825            assert_eq!(
2826                Scope::current().use_context::<&str>(),
2827                Some("caller fixture")
2828            );
2829            assert!(with_rt(|rt| rt.observers.is_empty()));
2830        });
2831        owner.dispose();
2832        caller.dispose();
2833    }
2834}