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    /// Close an open preview session without recording it: the app wrote a value of its own over
1591    /// what the gesture previewed (a text field's text replaced while being typed in), and that
1592    /// write recorded its own change. The next preview starts a fresh session whose prior is
1593    /// the app's value. Defaults to nothing: a plain signal keeps no session.
1594    fn end_preview(&self) {}
1595}
1596
1597impl<T: Clone + 'static> Binding<T> for Signal<T> {
1598    fn read(&self) -> T {
1599        self.get()
1600    }
1601    fn peek(&self) -> T {
1602        self.get_untracked()
1603    }
1604    fn write(&self, v: T) {
1605        self.set(v);
1606    }
1607    fn write_teardown(&self, _v: T) {}
1608}
1609
1610/// The object-safe half of [`Binding`], behind [`AnyBinding`]. Its methods carry an `erased_`
1611/// prefix so a call on a `Signal` inside this crate never sees two candidates named `read`.
1612trait ErasedBinding<T: 'static> {
1613    fn erased_read(&self) -> T;
1614    fn erased_peek(&self) -> T;
1615    fn erased_write(&self, v: T);
1616    fn erased_write_preview(&self, v: T);
1617    fn erased_write_commit(&self, v: T);
1618    fn erased_write_teardown(&self, v: T);
1619    fn erased_end_preview(&self);
1620}
1621
1622impl<T: 'static, B: Binding<T>> ErasedBinding<T> for B {
1623    fn erased_read(&self) -> T {
1624        Binding::read(self)
1625    }
1626    fn erased_peek(&self) -> T {
1627        Binding::peek(self)
1628    }
1629    fn erased_write(&self, v: T) {
1630        Binding::write(self, v)
1631    }
1632    fn erased_write_preview(&self, v: T) {
1633        Binding::write_preview(self, v)
1634    }
1635    fn erased_write_commit(&self, v: T) {
1636        Binding::write_commit(self, v)
1637    }
1638    fn erased_write_teardown(&self, v: T) {
1639        Binding::write_teardown(self, v)
1640    }
1641    fn erased_end_preview(&self) {
1642        Binding::end_preview(self)
1643    }
1644}
1645
1646/// A type-erased [`Binding`]: what a piece stores when its builder takes `impl Binding<T>`
1647/// (docs/api-style.md "Three input spellings"), so the piece itself needs no type parameter
1648/// per bound value.
1649///
1650/// `Copy`, like [`Signal`], so it captures into closures the same way: the erased binding lives
1651/// in a slot owned by the reactive scope that created it, which is the scope building the
1652/// piece. Reads and writes forward to the binding it wraps, preview and commit included.
1653pub struct AnyBinding<T: 'static> {
1654    slot: Signal<Rc<dyn ErasedBinding<T>>>,
1655}
1656
1657impl<T: 'static> Clone for AnyBinding<T> {
1658    fn clone(&self) -> Self {
1659        *self
1660    }
1661}
1662impl<T: 'static> Copy for AnyBinding<T> {}
1663
1664impl<T: 'static> AnyBinding<T> {
1665    /// Erase `binding`. Call it where the piece is built: the slot belongs to the current scope.
1666    pub fn new(binding: impl Binding<T>) -> Self {
1667        let erased: Rc<dyn ErasedBinding<T>> = Rc::new(binding);
1668        AnyBinding {
1669            slot: Signal::new(erased),
1670        }
1671    }
1672    fn inner(self) -> Rc<dyn ErasedBinding<T>> {
1673        self.slot.get_untracked()
1674    }
1675    /// Tracked read.
1676    pub fn get(self) -> T {
1677        self.inner().erased_read()
1678    }
1679    /// Tracked read, or `None` once the scope that created the binding is disposed.
1680    pub fn try_get(self) -> Option<T> {
1681        self.slot.try_get().map(|b| b.erased_read())
1682    }
1683    /// Untracked read.
1684    pub fn get_untracked(self) -> T {
1685        self.inner().erased_peek()
1686    }
1687    /// Tracked read through a projection.
1688    pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
1689        let v = self.inner().erased_read();
1690        f(&v)
1691    }
1692    /// Write, waking whatever tracks the binding.
1693    pub fn set(self, v: T) {
1694        self.inner().erased_write(v)
1695    }
1696    /// Write only when the value differs from the current one.
1697    pub fn set_if_changed(self, v: T)
1698    where
1699        T: PartialEq,
1700    {
1701        let b = self.inner();
1702        if b.erased_peek() != v {
1703            b.erased_write(v);
1704        }
1705    }
1706    /// Read the current value, let `f` change it, write it back.
1707    pub fn update(self, f: impl FnOnce(&mut T)) {
1708        let b = self.inner();
1709        let mut v = b.erased_peek();
1710        f(&mut v);
1711        b.erased_write(v);
1712    }
1713}
1714
1715impl<T: 'static> Binding<T> for AnyBinding<T> {
1716    fn read(&self) -> T {
1717        self.inner().erased_read()
1718    }
1719    fn peek(&self) -> T {
1720        self.inner().erased_peek()
1721    }
1722    fn write(&self, v: T) {
1723        self.inner().erased_write(v)
1724    }
1725    fn write_preview(&self, v: T) {
1726        self.inner().erased_write_preview(v)
1727    }
1728    fn write_commit(&self, v: T) {
1729        self.inner().erased_write_commit(v)
1730    }
1731    fn write_teardown(&self, v: T) {
1732        self.inner().erased_write_teardown(v)
1733    }
1734    fn end_preview(&self) {
1735        self.inner().erased_end_preview()
1736    }
1737}
1738
1739// ---------------------------------------------------------------------------
1740// Async data loading: Load + Resource (§4.5, docs/async.md)
1741// ---------------------------------------------------------------------------
1742
1743/// The lifecycle of an async-loaded value. `Failed` carries the fetcher's error as a shared
1744/// trait object so `Load` stays `Clone` for signal reads.
1745#[derive(Clone)]
1746pub enum Load<T> {
1747    Loading,
1748    Ready(T),
1749    Failed(Arc<dyn std::error::Error + Send + Sync>),
1750}
1751
1752impl<T> Load<T> {
1753    /// The loaded value, if ready.
1754    pub fn ready(&self) -> Option<&T> {
1755        match self {
1756            Load::Ready(v) => Some(v),
1757            _ => None,
1758        }
1759    }
1760    pub fn is_loading(&self) -> bool {
1761        matches!(self, Load::Loading)
1762    }
1763    pub fn is_ready(&self) -> bool {
1764        matches!(self, Load::Ready(_))
1765    }
1766    /// The failure, if the last fetch failed.
1767    pub fn error(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
1768        match self {
1769            Load::Failed(e) => Some(e.as_ref()),
1770            _ => None,
1771        }
1772    }
1773}
1774
1775impl<T: std::fmt::Debug> std::fmt::Debug for Load<T> {
1776    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1777        match self {
1778            Load::Loading => write!(f, "Loading"),
1779            Load::Ready(v) => f.debug_tuple("Ready").field(v).finish(),
1780            Load::Failed(e) => f.debug_tuple("Failed").field(&e.to_string()).finish(),
1781        }
1782    }
1783}
1784
1785/// Latest-wins bookkeeping shared by a Resource's reaction, its spawned futures, and disposal.
1786struct FetchState {
1787    generation: Cell<u64>,
1788    abort: RefCell<Option<Box<dyn FnOnce()>>>,
1789}
1790
1791impl FetchState {
1792    /// Invalidate the in-flight fetch: bump the generation first (so a completion that cannot
1793    /// be aborted still fails its check), then take-and-call the abort outside the borrow
1794    /// (dropping a future can re-enter reactive state).
1795    fn supersede(&self) -> u64 {
1796        let next = self.generation.get() + 1;
1797        self.generation.set(next);
1798        let old = self.abort.borrow_mut().take();
1799        if let Some(abort) = old {
1800            abort();
1801        }
1802        next
1803    }
1804}
1805
1806/// Declarative async data loading (§4.5): a tracked `source` whose value feeds an async
1807/// `fetcher`; the result lands in a `Signal<Load<T>>`. The source re-runs when its tracked
1808/// reads change; an unchanged source value refetches nothing, [`Resource::refetch`] always
1809/// does. Latest wins: a source change supersedes the in-flight fetch (aborting its task;
1810/// dropping any `FetchFuture` inside cancels the platform request) and a stale completion
1811/// writes nothing. Scope disposal aborts the in-flight fetch the same way.
1812///
1813/// ```ignore
1814/// let stations = Resource::new(
1815///     move || region.get(),                              // tracked: refetch on change
1816///     |region| async move { fetch_stations(region).await },
1817/// );
1818/// when(move || stations.ready(), move || station_list(stations));
1819/// ```
1820pub struct Resource<T: 'static> {
1821    state: Signal<Load<T>>,
1822    refetch_count: Signal<u64>,
1823    _not_send: PhantomData<*const T>,
1824}
1825
1826impl<T> Clone for Resource<T> {
1827    fn clone(&self) -> Self {
1828        *self
1829    }
1830}
1831impl<T> Copy for Resource<T> {}
1832
1833impl<T: 'static> Resource<T> {
1834    /// Start loading: `source` runs tracked (its signal reads become dependencies) and its
1835    /// value moves into `fetcher`'s future, which runs on the main-loop executor via the
1836    /// installed spawner, so no `Send` bound anywhere, and the future may read/write signals
1837    /// after its awaits. Infallible fetchers use `E = std::convert::Infallible`.
1838    #[track_caller]
1839    pub fn new<S, Fut, E>(
1840        source: impl Fn() -> S + 'static,
1841        fetcher: impl Fn(S) -> Fut + 'static,
1842    ) -> Resource<T>
1843    where
1844        S: Clone + PartialEq + 'static,
1845        Fut: Future<Output = Result<T, E>> + 'static,
1846        E: std::error::Error + Send + Sync + 'static,
1847    {
1848        let state: Signal<Load<T>> = Signal::new(Load::Loading);
1849        let refetch_count: Signal<u64> = Signal::new(0);
1850        let fs = Rc::new(FetchState {
1851            generation: Cell::new(0),
1852            abort: RefCell::new(None),
1853        });
1854        let reaction_fs = fs.clone();
1855        let prev: RefCell<Option<(S, u64)>> = RefCell::new(None);
1856        create_reaction(
1857            Rc::new(move || {
1858                // Tracked reads first: the refetch counter and the source. Everything else runs
1859                // untracked: the fetcher may read signals without making them dependencies.
1860                let count = refetch_count.get();
1861                let s = source();
1862                let fs = reaction_fs.clone();
1863                untrack(|| {
1864                    // Equality gate on (source value, refetch count): a rerun caused by an
1865                    // unrelated tracked read refetches nothing; refetch() always changes the
1866                    // pair, so it always fetches.
1867                    let same = prev
1868                        .borrow()
1869                        .as_ref()
1870                        .is_some_and(|(ps, pc)| ps == &s && *pc == count);
1871                    if same {
1872                        return;
1873                    }
1874                    *prev.borrow_mut() = Some((s.clone(), count));
1875                    let my_generation = fs.supersede();
1876                    state.set(Load::Loading);
1877                    let fut = fetcher(s);
1878                    let done = fs.clone();
1879                    let abort = spawn_local(Box::pin(async move {
1880                        let result = fut.await;
1881                        if done.generation.get() != my_generation {
1882                            return; // superseded while in flight; latest wins
1883                        }
1884                        done.abort.borrow_mut().take(); // completed: the stored abort is dead
1885                        match result {
1886                            Ok(v) => state.set(Load::Ready(v)),
1887                            Err(e) => state.set(Load::Failed(Arc::new(e))),
1888                        }
1889                    }));
1890                    // Eager-poll ordering: the spawner polls once before returning, so a
1891                    // synchronously-ready fetcher has already completed here; storing its
1892                    // abort is harmless only because the spawner contract makes aborting a
1893                    // finished task a no-op (this line is why that contract exists).
1894                    *fs.abort.borrow_mut() = Some(abort);
1895                });
1896            }),
1897            1,
1898        );
1899        // Disposal: supersede + abort the in-flight task. (A completion that slipped through
1900        // would write to disposed signals, the defined no-op, but aborting frees the platform
1901        // request immediately.)
1902        let cleanup_fs = fs;
1903        Scope::current().on_cleanup(move || {
1904            cleanup_fs.supersede();
1905        });
1906        Resource {
1907            state,
1908            refetch_count,
1909            _not_send: PhantomData,
1910        }
1911    }
1912
1913    /// The underlying state signal (tracked reads, `when(move || …)` guards, `each` sources).
1914    pub fn signal(self) -> Signal<Load<T>> {
1915        self.state
1916    }
1917
1918    /// The current load state (tracked).
1919    pub fn get(self) -> Load<T>
1920    where
1921        T: Clone,
1922    {
1923        self.state.get()
1924    }
1925
1926    /// Read the current load state by reference (tracked).
1927    pub fn with<R>(self, f: impl FnOnce(&Load<T>) -> R) -> R {
1928        self.state.with(f)
1929    }
1930
1931    /// Whether a fetch is in flight (tracked).
1932    pub fn loading(self) -> bool {
1933        self.with(Load::is_loading)
1934    }
1935
1936    /// Whether a value is ready (tracked): `when(move || r.ready(), …)`.
1937    pub fn ready(self) -> bool {
1938        self.with(Load::is_ready)
1939    }
1940
1941    /// Force a refetch with the current source value (even if unchanged).
1942    pub fn refetch(self) {
1943        self.refetch_count.update(|c| *c = c.wrapping_add(1));
1944    }
1945}
1946
1947// ---------------------------------------------------------------------------
1948// Tests
1949// ---------------------------------------------------------------------------
1950
1951#[cfg(test)]
1952mod tests {
1953    use super::*;
1954    use std::cell::Cell as StdCell;
1955    use std::rc::Rc;
1956
1957    fn counter() -> (Rc<StdCell<u32>>, impl Fn()) {
1958        let c = Rc::new(StdCell::new(0));
1959        let c2 = c.clone();
1960        (c, move || c2.set(c2.get() + 1))
1961    }
1962
1963    #[test]
1964    fn signal_get_set() {
1965        let s = Signal::new(1);
1966        assert_eq!(s.get(), 1);
1967        s.set(5);
1968        assert_eq!(s.get(), 5);
1969        s.update(|v| *v += 1);
1970        assert_eq!(s.get(), 6);
1971    }
1972
1973    #[test]
1974    fn signal_teardown_does_not_write_after_scope_disposal() {
1975        let scope = Scope::child();
1976        let warned = with_rt(|rt| rt.warned_writes.len());
1977        scope.enter(|| {
1978            let signal = Signal::new(String::new());
1979            signal.write_preview("Fixture final edit".into());
1980            assert_eq!(signal.peek(), "Fixture final edit");
1981            Scope::current().on_cleanup(move || {
1982                signal.write_teardown("Fixture final edit".into());
1983            });
1984        });
1985        scope.dispose();
1986        assert_eq!(with_rt(|rt| rt.warned_writes.len()), warned);
1987    }
1988
1989    #[test]
1990    fn persistent_binding_teardown_seals_preview() {
1991        #[derive(Clone)]
1992        struct FixtureBinding(Rc<RefCell<Vec<String>>>);
1993        impl Binding<String> for FixtureBinding {
1994            fn read(&self) -> String {
1995                String::new()
1996            }
1997            fn peek(&self) -> String {
1998                self.read()
1999            }
2000            fn write(&self, value: String) {
2001                self.0.borrow_mut().push(value);
2002            }
2003            fn write_preview(&self, _value: String) {}
2004        }
2005        let committed = Rc::new(RefCell::new(Vec::new()));
2006        let binding = FixtureBinding(committed.clone());
2007        let scope = Scope::child();
2008        scope.enter(|| {
2009            binding.write_preview("Fixture edit".into());
2010            Scope::current().on_cleanup(move || binding.write_teardown("Fixture edit".into()));
2011        });
2012        assert!(committed.borrow().is_empty());
2013        scope.dispose();
2014        assert_eq!(*committed.borrow(), ["Fixture edit"]);
2015    }
2016
2017    #[test]
2018    fn effect_reruns_on_change() {
2019        let s = Signal::new(1);
2020        let (count, bump) = counter();
2021        Effect::new(move || {
2022            s.track();
2023            bump();
2024        });
2025        assert_eq!(count.get(), 1); // initial run
2026        batch(|| s.set(2));
2027        assert_eq!(count.get(), 2);
2028        batch(|| s.set(3));
2029        assert_eq!(count.get(), 3);
2030    }
2031
2032    #[test]
2033    fn batch_coalesces() {
2034        let s = Signal::new(0);
2035        let (count, bump) = counter();
2036        Effect::new(move || {
2037            s.track();
2038            bump();
2039        });
2040        batch(|| {
2041            s.set(1);
2042            s.set(2);
2043            s.set(3);
2044        });
2045        assert_eq!(count.get(), 2); // initial + one drain
2046        assert_eq!(s.get(), 3);
2047    }
2048
2049    #[test]
2050    fn set_if_changed_no_op() {
2051        let s = Signal::new(7);
2052        let (count, bump) = counter();
2053        Effect::new(move || {
2054            s.track();
2055            bump();
2056        });
2057        batch(|| s.set_if_changed(7));
2058        assert_eq!(count.get(), 1); // no re-run
2059    }
2060
2061    #[test]
2062    fn memo_caches_and_diffs() {
2063        let s = Signal::new(1);
2064        let computes = Rc::new(StdCell::new(0));
2065        let c2 = computes.clone();
2066        let doubled = Memo::new(move || {
2067            c2.set(c2.get() + 1);
2068            s.get() * 2
2069        });
2070        assert_eq!(doubled.get(), 2);
2071        assert_eq!(doubled.get(), 2);
2072        assert_eq!(computes.get(), 1); // cached
2073        let (effect_runs, bump) = counter();
2074        Effect::new(move || {
2075            let _ = doubled.get();
2076            bump();
2077        });
2078        assert_eq!(effect_runs.get(), 1);
2079        batch(|| s.set(1)); // same value → memo recomputes? signal changed, memo recomputes, same output
2080        // memo output unchanged (1*2 == 2)? s was already 1 → set(1) marks dirty (set is not diffed)
2081        assert_eq!(effect_runs.get(), 1); // memo diffing gates the effect
2082        batch(|| s.set(5));
2083        assert_eq!(doubled.get(), 10);
2084        assert_eq!(effect_runs.get(), 2);
2085    }
2086
2087    #[test]
2088    fn bind_applies_on_change_only() {
2089        let s = Signal::new(1);
2090        let applied: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2091        let a2 = applied.clone();
2092        bind(
2093            move || s.get().to_string(),
2094            move |v| a2.borrow_mut().push(v.clone()),
2095        );
2096        assert_eq!(*applied.borrow(), vec!["1"]);
2097        batch(|| s.set(2));
2098        assert_eq!(*applied.borrow(), vec!["1", "2"]);
2099        batch(|| s.update(|v| *v = 2)); // update always marks; bind's eq gate stops the apply
2100        assert_eq!(*applied.borrow(), vec!["1", "2"]);
2101    }
2102
2103    #[test]
2104    fn watch_skips_initial_and_passes_old() {
2105        let s = Signal::new(10);
2106        type Log = Rc<RefCell<Vec<(i32, Option<i32>)>>>;
2107        let log: Log = Rc::new(RefCell::new(Vec::new()));
2108        let l2 = log.clone();
2109        watch(
2110            move || s.get(),
2111            move |new, old| l2.borrow_mut().push((*new, old.copied())),
2112        );
2113        assert!(log.borrow().is_empty());
2114        batch(|| s.set(11));
2115        assert_eq!(*log.borrow(), vec![(11, Some(10))]);
2116    }
2117
2118    #[test]
2119    fn scope_dispose_stops_effects_and_write_is_noop() {
2120        let s = Signal::new(0);
2121        let (count, bump) = counter();
2122        let scope = Scope::child();
2123        let inner = scope.enter(|| {
2124            let inner = Signal::new(1);
2125            Effect::new(move || {
2126                s.track();
2127                bump();
2128            });
2129            inner
2130        });
2131        assert_eq!(count.get(), 1);
2132        batch(|| s.set(1));
2133        assert_eq!(count.get(), 2);
2134        scope.dispose();
2135        batch(|| s.set(2));
2136        assert_eq!(count.get(), 2); // effect gone
2137        inner.set(9); // silent no-op
2138        assert_eq!(inner.try_get(), None);
2139    }
2140
2141    #[test]
2142    fn dispose_during_drain_skips_pending() {
2143        let s = Signal::new(0);
2144        let scope = Scope::child();
2145        let (count, bump) = counter();
2146        // Owner effect (created first in outer scope) disposes the child scope when s becomes 1.
2147        let scope_cell = Rc::new(StdCell::new(Some(scope)));
2148        let sc = scope_cell.clone();
2149        Effect::new(move || {
2150            if s.get() == 1
2151                && let Some(scope) = sc.take()
2152            {
2153                scope.dispose();
2154            }
2155        });
2156        scope.enter(|| {
2157            Effect::new(move || {
2158                s.track();
2159                bump();
2160            });
2161        });
2162        assert_eq!(count.get(), 1);
2163        batch(|| s.set(1));
2164        // Owner ran first (created earlier, same depth? owner depth 0 < child depth 1) and
2165        // disposed the child → child effect must not run again.
2166        assert_eq!(count.get(), 1);
2167    }
2168
2169    #[test]
2170    fn fixpoint_extends_drain() {
2171        let a = Signal::new(0);
2172        let b = Signal::new(0);
2173        let (count, bump) = counter();
2174        Effect::new(move || {
2175            if a.get() == 1 {
2176                b.set(1); // write during drain extends the drain
2177            }
2178        });
2179        Effect::new(move || {
2180            b.track();
2181            bump();
2182        });
2183        assert_eq!(count.get(), 1);
2184        batch(|| a.set(1));
2185        assert_eq!(count.get(), 2);
2186        assert_eq!(b.get(), 1);
2187    }
2188
2189    // Debug-only: release warns-and-defers instead of panicking (the release
2190    // side is pinned by `unwind_safety_tests::rerun_cap_defers_instead_of_killing_the_binding`).
2191    #[cfg(debug_assertions)]
2192    #[test]
2193    #[should_panic(expected = "re-ran more than")]
2194    fn rerun_cap_panics_in_debug() {
2195        let s = Signal::new(0);
2196        Effect::new(move || {
2197            let v = s.get();
2198            s.set(v + 1); // classic cycle
2199        });
2200        batch(|| s.set(1));
2201    }
2202
2203    #[test]
2204    fn context_provides_down() {
2205        #[derive(Clone, PartialEq, Debug)]
2206        struct Theme(u32);
2207        let scope = Scope::child();
2208        scope.provide(Theme(7));
2209        let child = scope.create_child();
2210        assert_eq!(child.use_context::<Theme>(), Some(Theme(7)));
2211        scope.dispose();
2212    }
2213
2214    #[test]
2215    fn trigger_notifies() {
2216        let t = Trigger::new();
2217        let (count, bump) = counter();
2218        Effect::new(move || {
2219            t.track();
2220            bump();
2221        });
2222        batch(|| t.notify());
2223        assert_eq!(count.get(), 2);
2224    }
2225
2226    #[test]
2227    fn turn_end_runs_after_fixpoint() {
2228        let s = Signal::new(0);
2229        let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2230        let o1 = order.clone();
2231        Effect::new(move || {
2232            s.track();
2233            o1.borrow_mut().push("effect");
2234        });
2235        let o2 = order.clone();
2236        on_turn_end(move || o2.borrow_mut().push("turn-end"));
2237        order.borrow_mut().clear();
2238        batch(|| s.set(1));
2239        assert_eq!(*order.borrow(), vec!["effect", "turn-end"]);
2240    }
2241
2242    #[test]
2243    fn at_turn_end_waits_for_the_turn_and_runs_once() {
2244        let s = Signal::new(0);
2245        let order: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
2246        // Outside a turn: now.
2247        let o = order.clone();
2248        at_turn_end(move || o.borrow_mut().push("now".into()));
2249        assert_eq!(*order.borrow(), vec!["now".to_string()]);
2250        order.borrow_mut().clear();
2251        // Inside a batch: after the drain, and before the standing hooks.
2252        let o1 = order.clone();
2253        Effect::new(move || {
2254            let v = s.get();
2255            o1.borrow_mut().push(format!("effect {v}"));
2256        });
2257        let o2 = order.clone();
2258        on_turn_end(move || o2.borrow_mut().push("standing".into()));
2259        order.borrow_mut().clear();
2260        let o3 = order.clone();
2261        batch(|| {
2262            at_turn_end(move || o3.borrow_mut().push("once".into()));
2263            s.set(1);
2264        });
2265        assert_eq!(*order.borrow(), vec!["effect 1", "once", "standing"]);
2266        // A batch with no reactive work still ends its turn for a deferred callback.
2267        order.borrow_mut().clear();
2268        let o4 = order.clone();
2269        batch(|| at_turn_end(move || o4.borrow_mut().push("quiet".into())));
2270        assert_eq!(*order.borrow(), vec!["quiet", "standing"]);
2271    }
2272
2273    #[test]
2274    fn bindings_run_before_effects() {
2275        let s = Signal::new(0);
2276        let order: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
2277        let o1 = order.clone();
2278        // Plain effect created first (lower seq); priority must still put the bind first.
2279        Effect::new(move || {
2280            s.track();
2281            o1.borrow_mut().push("effect");
2282        });
2283        let o2 = order.clone();
2284        bind(move || s.get(), move |_| o2.borrow_mut().push("bind"));
2285        order.borrow_mut().clear();
2286        batch(|| s.set(1));
2287        assert_eq!(*order.borrow(), vec!["bind", "effect"]);
2288    }
2289}
2290
2291#[cfg(test)]
2292mod resource_tests {
2293    use super::*;
2294    use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
2295
2296    // ---- test executor: mirrors day::task's shape (eager first poll; abort = remove+drop;
2297    // pump() re-polls whatever is still pending). `ABORTED` records aborts of still-pending
2298    // tasks, the probe the latest-wins/disposal tests read. All thread-local: each #[test]
2299    // thread gets a fresh Runtime and a fresh executor.
2300
2301    thread_local! {
2302        static TEST_TASKS: RefCell<Vec<(u64, Option<LocalBoxFuture>)>> =
2303            const { RefCell::new(Vec::new()) };
2304        static NEXT_ID: Cell<u64> = const { Cell::new(1) };
2305        static ABORTED: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
2306        static INSTALLED: Cell<bool> = const { Cell::new(false) };
2307    }
2308
2309    fn noop_waker() -> Waker {
2310        fn raw() -> RawWaker {
2311            RawWaker::new(std::ptr::null(), &VT)
2312        }
2313        static VT: RawWakerVTable = RawWakerVTable::new(|_| raw(), |_| {}, |_| {}, |_| {});
2314        // SAFETY: every vtable entry ignores the data pointer.
2315        unsafe { Waker::from_raw(raw()) }
2316    }
2317
2318    fn poll_one(fut: &mut LocalBoxFuture) -> bool {
2319        let waker = noop_waker();
2320        let mut cx = Context::from_waker(&waker);
2321        fut.as_mut().poll(&mut cx).is_ready()
2322    }
2323
2324    fn install_test_spawner() {
2325        if INSTALLED.with(|c| c.replace(true)) {
2326            return;
2327        }
2328        install_spawner(|mut fut| {
2329            let id = NEXT_ID.with(|c| {
2330                let v = c.get();
2331                c.set(v + 1);
2332                v
2333            });
2334            if !poll_one(&mut fut) {
2335                TEST_TASKS.with(|t| t.borrow_mut().push((id, Some(fut))));
2336            }
2337            Box::new(move || {
2338                let removed = TEST_TASKS.with(|t| {
2339                    let mut t = t.borrow_mut();
2340                    let before = t.len();
2341                    t.retain(|(i, _)| *i != id);
2342                    before != t.len()
2343                });
2344                if removed {
2345                    ABORTED.with(|a| a.borrow_mut().push(id));
2346                }
2347            })
2348        });
2349    }
2350
2351    fn aborted_count() -> usize {
2352        ABORTED.with(|a| a.borrow().len())
2353    }
2354
2355    /// Re-poll every pending task once (completions drop out).
2356    fn pump() {
2357        let ids: Vec<u64> = TEST_TASKS.with(|t| t.borrow().iter().map(|(i, _)| *i).collect());
2358        for id in ids {
2359            let fut = TEST_TASKS.with(|t| {
2360                t.borrow_mut()
2361                    .iter_mut()
2362                    .find(|(i, _)| *i == id)
2363                    .and_then(|(_, s)| s.take())
2364            });
2365            let Some(mut fut) = fut else { continue };
2366            if poll_one(&mut fut) {
2367                TEST_TASKS.with(|t| t.borrow_mut().retain(|(i, _)| *i != id));
2368            } else {
2369                TEST_TASKS.with(|t| {
2370                    if let Some((_, s)) = t.borrow_mut().iter_mut().find(|(i, _)| *i == id) {
2371                        *s = Some(fut);
2372                    }
2373                });
2374            }
2375        }
2376        // Completions wrote signals; with no scheduler installed a test must drain explicitly
2377        // (the production main loop drains via the installed scheduler).
2378        flush_sync();
2379    }
2380
2381    type Slot<T> = Rc<RefCell<Option<Result<T, TestErr>>>>;
2382
2383    /// A future the test resolves by hand (fill the slot, then `pump()`); no waker wiring, since
2384    /// pump re-polls everything.
2385    fn manual_future<T: 'static>(slot: Slot<T>) -> impl Future<Output = Result<T, TestErr>> {
2386        std::future::poll_fn(move |_| match slot.borrow_mut().take() {
2387            Some(r) => Poll::Ready(r),
2388            None => Poll::Pending,
2389        })
2390    }
2391
2392    #[derive(Debug)]
2393    struct TestErr(&'static str);
2394    impl std::fmt::Display for TestErr {
2395        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2396            write!(f, "{}", self.0)
2397        }
2398    }
2399    impl std::error::Error for TestErr {}
2400
2401    #[test]
2402    fn resource_sync_fetcher_is_ready_immediately() {
2403        install_test_spawner();
2404        let r = Resource::new(|| (), |_| async { Ok::<_, std::convert::Infallible>(42) });
2405        assert!(r.ready());
2406        assert_eq!(r.with(|l| l.ready().copied()), Some(42));
2407    }
2408
2409    #[test]
2410    fn resource_loading_then_ready() {
2411        install_test_spawner();
2412        let slot: Slot<i32> = Rc::new(RefCell::new(None));
2413        let s2 = slot.clone();
2414        let r = Resource::new(move || (), move |_| manual_future(s2.clone()));
2415        assert!(r.loading());
2416        *slot.borrow_mut() = Some(Ok(7));
2417        pump();
2418        assert_eq!(r.with(|l| l.ready().copied()), Some(7));
2419    }
2420
2421    #[test]
2422    fn resource_failed_preserves_error() {
2423        install_test_spawner();
2424        let r = Resource::new(|| (), |_| async { Err::<i32, _>(TestErr("boom")) });
2425        assert!(!r.ready());
2426        assert_eq!(
2427            r.with(|l| l.error().map(|e| e.to_string())),
2428            Some("boom".into())
2429        );
2430    }
2431
2432    #[test]
2433    fn resource_refetches_on_source_change() {
2434        install_test_spawner();
2435        let src = Signal::new(1i32);
2436        let fetches = Rc::new(Cell::new(0));
2437        let f = fetches.clone();
2438        let r = Resource::new(
2439            move || src.get(),
2440            move |v| {
2441                f.set(f.get() + 1);
2442                async move { Ok::<_, TestErr>(v * 10) }
2443            },
2444        );
2445        assert_eq!(fetches.get(), 1);
2446        assert_eq!(r.with(|l| l.ready().copied()), Some(10));
2447        batch(|| src.set(2));
2448        assert_eq!(fetches.get(), 2);
2449        assert_eq!(r.with(|l| l.ready().copied()), Some(20));
2450    }
2451
2452    #[test]
2453    fn resource_source_equality_gates() {
2454        install_test_spawner();
2455        let a = Signal::new(1i32);
2456        let b = Signal::new(10i32);
2457        let fetches = Rc::new(Cell::new(0));
2458        let f = fetches.clone();
2459        let r = Resource::new(
2460            move || {
2461                let _ = b.get(); // tracked but not part of the source value
2462                a.get()
2463            },
2464            move |v| {
2465                f.set(f.get() + 1);
2466                async move { Ok::<_, TestErr>(v) }
2467            },
2468        );
2469        assert_eq!(fetches.get(), 1);
2470        batch(|| b.set(20)); // reruns the reaction; the source value is unchanged → no refetch
2471        assert_eq!(fetches.get(), 1);
2472        assert_eq!(r.with(|l| l.ready().copied()), Some(1));
2473        batch(|| a.set(2)); // the value changed → refetch
2474        assert_eq!(fetches.get(), 2);
2475    }
2476
2477    #[test]
2478    fn resource_refetch_forces() {
2479        install_test_spawner();
2480        let fetches = Rc::new(Cell::new(0));
2481        let f = fetches.clone();
2482        let r = Resource::new(
2483            || (),
2484            move |_| {
2485                f.set(f.get() + 1);
2486                async { Ok::<_, TestErr>(0) }
2487            },
2488        );
2489        assert_eq!(fetches.get(), 1);
2490        batch(|| r.refetch()); // same source value; the refetch counter forces it past the gate
2491        assert_eq!(fetches.get(), 2);
2492    }
2493
2494    #[test]
2495    fn resource_latest_wins() {
2496        install_test_spawner();
2497        let src = Signal::new(1i32);
2498        let slots: Rc<RefCell<Vec<Slot<i32>>>> = Rc::new(RefCell::new(Vec::new()));
2499        let sl = slots.clone();
2500        let r = Resource::new(
2501            move || src.get(),
2502            move |_| {
2503                let slot: Slot<i32> = Rc::new(RefCell::new(None));
2504                sl.borrow_mut().push(slot.clone());
2505                manual_future(slot)
2506            },
2507        );
2508        assert!(r.loading());
2509        let before = aborted_count();
2510        batch(|| src.set(2)); // supersede generation 1 while it is in flight
2511        assert_eq!(aborted_count(), before + 1, "the stale task was aborted");
2512        // Resolving generation 1 anyway must change nothing (its future is gone).
2513        *slots.borrow()[0].borrow_mut() = Some(Ok(111));
2514        pump();
2515        assert!(r.loading(), "a stale result writes nothing");
2516        *slots.borrow()[1].borrow_mut() = Some(Ok(222));
2517        pump();
2518        assert_eq!(r.with(|l| l.ready().copied()), Some(222));
2519    }
2520
2521    #[test]
2522    fn resource_scope_disposal_aborts() {
2523        install_test_spawner();
2524        let scope = Scope::child();
2525        let slot: Slot<i32> = Rc::new(RefCell::new(None));
2526        let s2 = slot.clone();
2527        let r = scope.enter(|| Resource::new(move || (), move |_| manual_future(s2.clone())));
2528        assert!(r.loading());
2529        let before = aborted_count();
2530        scope.dispose();
2531        assert_eq!(aborted_count(), before + 1, "disposal aborted the fetch");
2532        // Resolving afterwards is inert: the future is gone; nothing pends; no panic.
2533        *slot.borrow_mut() = Some(Ok(1));
2534        pump();
2535    }
2536
2537    #[test]
2538    fn resource_ready_is_tracked() {
2539        install_test_spawner();
2540        let slot: Slot<i32> = Rc::new(RefCell::new(None));
2541        let s2 = slot.clone();
2542        let r = Resource::new(move || (), move |_| manual_future(s2.clone()));
2543        let runs = Rc::new(Cell::new(0));
2544        let rn = runs.clone();
2545        Effect::new(move || {
2546            let _ = r.ready();
2547            rn.set(rn.get() + 1);
2548        });
2549        assert_eq!(runs.get(), 1);
2550        *slot.borrow_mut() = Some(Ok(1));
2551        pump();
2552        assert!(runs.get() >= 2, "ready() re-ran the effect on completion");
2553    }
2554
2555    #[test]
2556    #[should_panic(expected = "no spawner installed")]
2557    fn spawner_missing_panics() {
2558        // No test spawner installed: this test thread's Runtime has none.
2559        let _r = Resource::new(|| (), |_| async { Ok::<_, std::convert::Infallible>(1) });
2560    }
2561}
2562
2563#[cfg(test)]
2564mod unwind_safety_tests {
2565    use super::*;
2566
2567    /// Run `f`, swallowing a panic, with the panic hook silenced so the test output stays clean.
2568    fn contained(f: impl FnOnce() + std::panic::UnwindSafe) {
2569        let prev = std::panic::take_hook();
2570        std::panic::set_hook(Box::new(|_| {}));
2571        let r = std::panic::catch_unwind(f);
2572        std::panic::set_hook(prev);
2573        assert!(r.is_err(), "expected the closure to panic");
2574    }
2575
2576    /// A panic inside `Scope::enter` must not leave the runtime parented to the transient scope.
2577    /// Before the guard, every later `Signal::new` landed in a disposed scope and its first read
2578    /// panicked with a misleading "read of disposed Signal".
2579    #[test]
2580    fn panic_in_scope_enter_restores_current_scope() {
2581        let before = with_rt(|rt| rt.current_scope);
2582        let scope = Scope::detached();
2583        contained(|| scope.enter(|| panic!("boom in enter")));
2584        assert_eq!(with_rt(|rt| rt.current_scope), before, "scope not restored");
2585        // The real symptom: a signal created afterwards must still be alive and readable.
2586        let s = Signal::new(7u32);
2587        assert_eq!(s.get(), 7);
2588    }
2589
2590    /// A panic inside `untrack` must pop its `None` observer, or dependency tracking stays off
2591    /// for the rest of the process and nothing ever updates again.
2592    /// A panic inside an effect's own closure (contained by a backend trampoline) must pop
2593    /// the effect's observer frame during unwind; a stranded frame would attribute every
2594    /// later read to the dead run, even through a user's own `catch_unwind`, without any
2595    /// call to `recover_from_panic`.
2596    #[test]
2597    fn panic_in_effect_body_pops_its_observer_frame() {
2598        let depth = with_rt(|rt| rt.observers.len());
2599        let boom = Signal::new(false);
2600        Effect::new(move || {
2601            if boom.get() {
2602                panic!("effect boom");
2603            }
2604        });
2605        assert_eq!(with_rt(|rt| rt.observers.len()), depth);
2606        contained(|| batch(|| boom.set(true)));
2607        assert_eq!(
2608            with_rt(|rt| rt.observers.len()),
2609            depth,
2610            "observer frame stranded by the panicking effect run"
2611        );
2612        recover_from_panic(); // clear draining/pending for the tests that follow
2613    }
2614
2615    #[test]
2616    fn panic_in_untrack_restores_tracking() {
2617        let depth = with_rt(|rt| rt.observers.len());
2618        contained(|| untrack(|| panic!("boom in untrack")));
2619        assert_eq!(with_rt(|rt| rt.observers.len()), depth, "observer stranded");
2620
2621        // Tracking still works: an effect re-runs when its source changes.
2622        let src = Signal::new(0i32);
2623        let runs = Rc::new(RefCell::new(0));
2624        let r2 = runs.clone();
2625        Effect::new(move || {
2626            src.get();
2627            *r2.borrow_mut() += 1;
2628        });
2629        flush_sync();
2630        let before = *runs.borrow();
2631        src.set(1);
2632        flush_sync();
2633        assert!(
2634            *runs.borrow() > before,
2635            "effect did not re-run — tracking is off"
2636        );
2637    }
2638
2639    /// A panic inside `batch` must not strand `batch_depth`, which would stop every later write
2640    /// from scheduling a drain.
2641    #[test]
2642    fn panic_in_batch_restores_depth() {
2643        let depth = with_rt(|rt| rt.batch_depth);
2644        contained(|| batch(|| panic!("boom in batch")));
2645        assert_eq!(with_rt(|rt| rt.batch_depth), depth, "batch depth stranded");
2646    }
2647
2648    /// A panic inside a `with` closure must not consume the signal's value. Before the value was
2649    /// shared it was taken out for the closure's duration, so an unwind lost it permanently and
2650    /// the signal was dead for the rest of the process.
2651    #[test]
2652    fn panic_in_with_leaves_the_value_intact() {
2653        let s = Signal::new(String::from("intact"));
2654        contained(|| s.with(|_| panic!("boom in with")));
2655        assert_eq!(s.with(|v| v.clone()), "intact");
2656    }
2657
2658    /// Reading a signal from inside its own `with` closure now works. It used to find the hole
2659    /// left by the take and panic with "read of disposed Signal".
2660    #[test]
2661    fn reentrant_read_inside_with_succeeds() {
2662        let s = Signal::new(5u32);
2663        let doubled = s.with(|outer| *outer + s.with(|inner| *inner));
2664        assert_eq!(doubled, 10);
2665        assert_eq!(
2666            s.with(|v| *v),
2667            5,
2668            "value still in place after the nested read"
2669        );
2670    }
2671
2672    /// Two different signals read inside one another's closures: the ordinary case, and the
2673    /// reason the closure must run with the runtime borrow released.
2674    #[test]
2675    fn nested_reads_of_distinct_signals_succeed() {
2676        let a = Signal::new(2u32);
2677        let b = Signal::new(3u32);
2678        assert_eq!(a.with(|x| *x * b.with(|y| *y)), 6);
2679    }
2680
2681    /// Writing a signal while a read of it is in flight is reported instead of silently lost.
2682    #[test]
2683    fn write_during_read_panics_with_a_clear_message() {
2684        let s = Signal::new(1u32);
2685        let prev = std::panic::take_hook();
2686        std::panic::set_hook(Box::new(|_| {}));
2687        let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2688            s.with(|_| s.set(2));
2689        }));
2690        std::panic::set_hook(prev);
2691        let payload = r.unwrap_err();
2692        // A `panic!` with no format arguments carries a `&'static str`, not a `String`.
2693        let msg = payload
2694            .downcast_ref::<&str>()
2695            .map(|s| s.to_string())
2696            .or_else(|| payload.downcast_ref::<String>().cloned())
2697            .expect("panic payload should be a string");
2698        assert!(
2699            msg.contains("in flight") && msg.contains("Signal"),
2700            "message should name the cause, got: {msg}"
2701        );
2702    }
2703
2704    /// Release builds must survive a reactive cycle: the capped effect is skipped for the
2705    /// rest of the drain but re-arms on the next source write; it must not be permanently
2706    /// disabled. Release-only because the same cycle panics under
2707    /// `debug_assertions`; run via `cargo test --release -p day-reactive`.
2708    #[cfg(not(debug_assertions))]
2709    #[test]
2710    fn rerun_cap_defers_instead_of_killing_the_binding() {
2711        let s = Signal::new(0u32);
2712        let runs = std::rc::Rc::new(std::cell::Cell::new(0u32));
2713        let r2 = runs.clone();
2714        Effect::new(move || {
2715            let v = s.get();
2716            r2.set(r2.get() + 1);
2717            if v < 1_000_000 {
2718                s.set(v + 1); // self-sustaining cycle: trips the cap every drain
2719            }
2720        });
2721        flush_sync();
2722        let after_cycle = runs.get();
2723        assert!(
2724            after_cycle <= RERUN_CAP + 1,
2725            "cap did not bound the drain: {after_cycle} runs"
2726        );
2727
2728        // A fresh external write must re-arm the effect with a new per-drain budget.
2729        batch(|| s.set(2_000_000)); // past the cycle threshold: the effect runs once, quietly
2730        assert_eq!(
2731            runs.get(),
2732            after_cycle + 1,
2733            "binding stayed dead after hitting the re-run cap"
2734        );
2735    }
2736}
2737
2738#[cfg(test)]
2739mod owner_scope_tests {
2740    use super::*;
2741
2742    #[test]
2743    fn reactions_and_lazy_memos_keep_their_owner_and_restore_the_caller() {
2744        let outer = Scope::child();
2745        outer.provide("outer fixture");
2746        let first = outer.create_child();
2747        let second = outer.create_child();
2748        first.provide("first fixture");
2749        second.provide("second fixture");
2750        let source = Signal::new(0);
2751        let seen = Rc::new(RefCell::new(Vec::new()));
2752        let lazy = first.enter(|| {
2753            Memo::new(move || {
2754                (
2755                    source.get(),
2756                    Scope::current().use_context::<&str>().unwrap(),
2757                )
2758            })
2759        });
2760        let nested = second.enter(|| {
2761            Memo::new(move || (lazy.get(), Scope::current().use_context::<&str>().unwrap()))
2762        });
2763        second.enter(|| assert_eq!(lazy.get(), (0, "first fixture")));
2764        assert_eq!(nested.get(), ((0, "first fixture"), "second fixture"));
2765        for (scope, name) in [(first, "first fixture"), (second, "second fixture")] {
2766            let seen = seen.clone();
2767            scope.enter(|| {
2768                Effect::new(move || {
2769                    seen.borrow_mut()
2770                        .push((source.get(), Scope::current().use_context::<&str>()));
2771                    assert_eq!(Scope::current().use_context::<&str>(), Some(name));
2772                })
2773            });
2774        }
2775        second.enter(|| {
2776            batch(|| source.set(1));
2777            assert_eq!(
2778                Scope::current().use_context::<&str>(),
2779                Some("second fixture")
2780            );
2781        });
2782        assert_eq!(nested.get(), ((1, "first fixture"), "second fixture"));
2783        assert_eq!(seen.borrow().len(), 4);
2784        outer.dispose();
2785        batch(|| source.set(2));
2786        assert_eq!(seen.borrow().len(), 4, "disposed reactions must not run");
2787    }
2788
2789    #[test]
2790    fn watches_allocate_state_and_cleanup_in_their_owner() {
2791        let owner = Scope::child();
2792        let trigger = Signal::new(0);
2793        let allocated = Rc::new(Cell::new(None::<Signal<i32>>));
2794        let cleaned = Rc::new(Cell::new(0));
2795        owner.enter(|| {
2796            let allocated = allocated.clone();
2797            let cleaned = cleaned.clone();
2798            watch(
2799                move || trigger.get(),
2800                move |value, _| {
2801                    allocated.set(Some(Signal::new(*value)));
2802                    let cleaned = cleaned.clone();
2803                    Scope::current().on_cleanup(move || cleaned.set(cleaned.get() + 1));
2804                },
2805            );
2806        });
2807        batch(|| trigger.set(1));
2808        let state = allocated.get().unwrap();
2809        assert_eq!(state.get(), 1);
2810        owner.dispose();
2811        assert_eq!(cleaned.get(), 1);
2812        assert!(state.try_get().is_none());
2813    }
2814
2815    #[test]
2816    fn panic_in_owned_computations_restores_scope_and_tracking() {
2817        let owner = Scope::child();
2818        owner.provide("owner fixture");
2819        let caller = Scope::child();
2820        caller.provide("caller fixture");
2821        let trigger = Signal::new(false);
2822        let memo = owner.enter(|| {
2823            Memo::new(move || {
2824                assert_eq!(
2825                    Scope::current().use_context::<&str>(),
2826                    Some("owner fixture")
2827                );
2828                assert!(!trigger.get(), "synthetic memo failure");
2829                7
2830            })
2831        });
2832        assert_eq!(memo.get(), 7);
2833        batch(|| trigger.set(true));
2834        caller.enter(|| {
2835            let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| memo.get()));
2836            assert!(result.is_err());
2837            assert_eq!(
2838                Scope::current().use_context::<&str>(),
2839                Some("caller fixture")
2840            );
2841            assert!(with_rt(|rt| rt.observers.is_empty()));
2842        });
2843        owner.dispose();
2844        caller.dispose();
2845    }
2846}